Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 44 additions & 19 deletions gpuqueue/platform.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,8 @@ def recover_active_probe(self, resource):
A pending probe keeps its identity until its actual receipt arrives.
Historical notices and old running receipts cannot trigger retries.
"""
if not self.probe_timed_out(resource) or resource.get('probe'):
if not (self.probe_timed_out(resource) or
resource['status'] == 'unknown' and resource.get('probe_invalid')) or resource.get('probe'):
return
monitor = resource.get('monitor') or {}
if monitor.get('attempts', 0) >= 3 or time.time()-monitor.get('at', 0) < 30:
Expand All @@ -252,14 +253,20 @@ def recover_active_probe(self, resource):
or internal.get('stop_requested_at')
or task['public']['state'] not in ['starting', 'running']):
continue
runner = read_json(self.store.root/'tasks'/task['id']/'run/status.json', {})
try:
runner = read_json(self.store.root/'tasks'/task['id']/'run/status.json', {})
if not isinstance(runner, dict):
continue
except (OSError, ValueError):
# Unreadable runner evidence cannot authorize a diagnostic retry.
continue
at = runner.get('updated_at')
if (runner.get('gpu_verified') is not True or runner.get('state') != 'running'
or not isinstance(at, (int, float)) or not math.isfinite(at)
or not -5 <= time.time()-at < 90):
continue
old_job = (resource.get('probe_timeout') or {}).get('job')
if old_job:
if old_job and old_job != (resource.get('probe_invalid') or {}).get('job'):
folder = self.job_folder(resource['id'])
receipt = read_json(folder/old_job/'status.json', {})
if (folder/(old_job+'.json')).exists() or receipt.get('state') == 'running':
Expand All @@ -281,23 +288,36 @@ def refresh_probe(self, resource, *, active=True):
folder = self.job_folder(resource['id']) / probe['job']
status = read_json(folder/'status.json', {})
if status.get('state') == 'finished' and status.get('exit_code') == 0:
output = (folder/'output.log').read_text(errors='replace')
line = next((line for line in output.splitlines() if line.startswith('GPUQ_TELEMETRY=')), None)
if not line:
raise PlatformError('GPU 检查已结束但没有有效遥测')
payload = json.loads(line.split('=', 1)[1])
gpus = []
for row in csv.reader(payload['gpus'].splitlines(), skipinitialspace=True):
if len(row) not in [6, 7]:
raise PlatformError('GPU 遥测字段不完整')
temperature = row[6].strip() if len(row) == 7 else 'N/A'
gpus.append({'index': int(row[0]), 'uuid': row[1], 'name': row[2], 'total_mb': float(row[3]), 'used_mb': float(row[4]), 'utilization': float(row[5]), 'temperature_c': None if temperature in ['N/A', '[N/A]', 'Not Supported', '[Not Supported]'] else float(temperature)})
apps = [row for row in csv.reader(payload['apps'].splitlines(), skipinitialspace=True) if len(row) == 2]
stamp = float(payload.get('at', status.get('at', (folder/'output.log').stat().st_mtime)))
if not math.isfinite(stamp) or stamp <= 0 or stamp > time.time()+5:
raise PlatformError('GPU 遥测采样时间无效')
try:
output = (folder/'output.log').read_text(errors='replace')
line = next((line for line in output.splitlines() if line.startswith('GPUQ_TELEMETRY=')), None)
if not line:
raise PlatformError('GPU 检查已结束但没有有效遥测')
payload = json.loads(line.split('=', 1)[1])
gpus = []
for row in csv.reader(payload['gpus'].splitlines(), skipinitialspace=True):
if len(row) not in [6, 7]:
raise PlatformError('GPU 遥测字段不完整')
temperature = row[6].strip() if len(row) == 7 else 'N/A'
gpus.append({'index': int(row[0]), 'uuid': row[1], 'name': row[2], 'total_mb': float(row[3]), 'used_mb': float(row[4]), 'utilization': float(row[5]), 'temperature_c': None if temperature in ['N/A', '[N/A]', 'Not Supported', '[Not Supported]'] else float(temperature)})
apps = [row for row in csv.reader(payload['apps'].splitlines(), skipinitialspace=True) if len(row) == 2]
stamp = float(payload.get('at', status.get('at', (folder/'output.log').stat().st_mtime)))
if not math.isfinite(stamp) or stamp <= 0 or stamp > time.time()+5:
raise PlatformError('GPU 遥测采样时间无效')
except (PlatformError, OSError, ValueError, TypeError, KeyError, AttributeError, OverflowError, csv.Error) as error:
resource.update(status='unknown', probe=None,
probe_invalid={'at': now(), 'job': probe['job']},
error='GPU 检查已结束,但遥测输出缺失、损坏或采样时间无效;资源可用性待核查('+type(error).__name__+')')
if resource.get('monitor'):
resource['monitor']['state'] = 'retry'
# The receipt resolved this probe: malformed output is not
# timeout evidence authorizing a replacement allocation.
if resource.get('probe_timeout'):
resource['last_probe_timeout'] = resource.pop('probe_timeout')
return
resource.update(status='online', telemetry={'gpus': gpus, 'apps': apps, 'at': stamp, 'host': payload.get('host', '')}, probe=None, probe_checked=time.time())
resource.pop('error', None)
resource.pop('probe_invalid', None)
if stamp >= resource.get('sample_requested_at', 0):
resource.pop('sample_requested_at', None)
resource.pop('monitor', None)
Expand Down Expand Up @@ -479,7 +499,12 @@ def select(self, task, active):
continue
managed_pids = set()
for running in active:
status = read_json(self.store.root/'tasks'/running['id']/'run/status.json', {})
try:
status = read_json(self.store.root/'tasks'/running['id']/'run/status.json', {})
if not isinstance(status, dict):
raise ValueError('Invalid runner status')
except (OSError, ValueError):
return None, '原任务执行状态文件不可读,状态待核查,暂不增加并行'
managed_pids.update(str(s['pid']) for s in status.get('steps', []) if s.get('state') == 'running' and s.get('pid'))
occupied = {row[0] for row in telemetry.get('apps', []) if row[1] not in managed_pids}
required_mb = memory_mb(required)
Expand Down
34 changes: 31 additions & 3 deletions gpuqueue/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ def tail(path, limit=8000):
stream.seek(max(0, path.stat().st_size-limit))
return redact(stream.read(limit).decode(errors='replace'))

class RunnerStatusError(ValueError):
pass

def runner_status(path):
try:
status = read_json(path)
if status is None and not path.exists():
return None
if not isinstance(status, dict) or not isinstance(status.get('state'), str):
raise ValueError('执行状态必须是 JSON 对象')
return status
except (OSError, ValueError) as error:
# Keep the corrupt file intact and distinguish it from a missing file.
raise RunnerStatusError('任务执行状态文件不可读,状态待核查('+type(error).__name__+')') from error

class Service:
def __init__(self, config, store=None, platform=None):
self.config = config
Expand Down Expand Up @@ -140,7 +155,18 @@ def refresh_task(self, task):
if row and row['stopped_at']:
internal['stop_confirmed'] = True
if not internal.get('stop_confirmed'):
return self._refresh_task(task)
previous = deepcopy(task)
try:
return self._refresh_task(task)
except RunnerStatusError as error:
public = task['public']
message = str(error)+';不会自动重跑,原文件保留供排查'
if public.get('result_refresh_error') != message:
public['events'].append(message)
public.update(state='stopping' if internal.get('stop_requested_at') else 'execution_unknown',
failureReason=message, result_refresh_error=message)
self.save_if_changed(task, previous)
return
# Late results are optional enrichment after a confirmed stop. Work on
# a copy so malformed metadata or unreadable logs cannot partially
# overwrite the saved result or stop other tasks from being scheduled.
Expand Down Expand Up @@ -207,7 +233,7 @@ def _refresh_task(self, task):
if not job_id:
return
folder = self.store.root/'tasks'/task['id']
status = read_json(folder/'run/status.json')
status = runner_status(folder/'run/status.json')
try:
job_status = read_json(self.platform.job_folder(request_id)/job_id/'status.json', {})
if not isinstance(job_status, dict):
Expand All @@ -221,7 +247,7 @@ def _refresh_task(self, task):
if job_status.get('state') in ['finished', 'failed'] or resource.get('status') == 'closed':
# The runner may have finished after the first status snapshot.
# Read again after observing exit before freezing a terminal task.
status = read_json(folder/'run/status.json')
status = runner_status(folder/'run/status.json')
if status:
public.update(state=status['state'], stage=status.get('stage', 0), step_records=status.get('steps', []), progress=None)
if status['state'] == 'completed':
Expand Down Expand Up @@ -258,6 +284,8 @@ def _refresh_task(self, task):
public.pop('failureReason',None)
for step in public.get('step_records',[]):
if step.get('state') == 'running': step['state'] = 'stopped'
if public.get('result_refresh_error') and public.get('failureReason') == public['result_refresh_error']:
public.pop('failureReason', None)
public.pop('result_refresh_error', None)
if (public['state'] in ['completed', 'failed', 'interrupted', 'stopped'] and (
(status or {}).get('state') in ['completed', 'failed']
Expand Down
66 changes: 66 additions & 0 deletions tests/test_probe_recovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,72 @@ def test_sampling_error_does_not_undo_computation_dispatch(self):
self.assertEqual(self.task['internal']['job_uuid'], 'compute')
self.assertEqual(self.resource['monitor']['state'], 'retry')

def test_finished_probe_with_invalid_output_is_consumed_without_timeout_evidence(self):
self.adapter.lark = Mock(return_value=dict(messages=[]))
payload = dict(at=time.time(), gpus='0, GPU-test, H100, 81559, 1, 0, 30', apps='')
outputs = ['no telemetry', 'GPUQ_TELEMETRY={truncated',
'GPUQ_TELEMETRY=[]', 'GPUQ_TELEMETRY={}',
'GPUQ_TELEMETRY='+json.dumps(dict(payload, gpus='0, GPU-test')),
'GPUQ_TELEMETRY='+json.dumps(dict(payload, gpus='bad, GPU-test, H100, 81559, 1, 0')),
'GPUQ_TELEMETRY='+json.dumps(dict(payload, gpus=None)),
'GPUQ_TELEMETRY='+json.dumps(dict(payload, apps=None))]
outputs += ['GPUQ_TELEMETRY='+json.dumps(dict(payload, at=stamp))
for stamp in ['bad', None, 0, -1, float('nan'), float('inf'), time.time()+60]]
folder = self.adapter.job_folder(REQUEST)/JOB
atomic_json(folder/'status.json', dict(state='finished', exit_code=0))
for output in outputs:
with self.subTest(output=output):
resource = dict(id=REQUEST, status='online', probe=dict(job=JOB, at=time.time()),
monitor=dict(state='sampling', attempts=1, at=time.time()), samples=[],
probe_timeout=dict(job=JOB, at='old'))
self.adapter.resources = {REQUEST: resource}
(folder/'output.log').write_text(output)
self.adapter.refresh()
self.assertIsNone(resource['probe'])
self.assertEqual(resource['status'], 'unknown')
self.assertEqual(resource['monitor']['state'], 'retry')
self.assertIn('遥测输出', resource['error'])
self.assertFalse(self.adapter.probe_timed_out(resource))
self.assertEqual(resource['last_probe_timeout']['job'], JOB)
self.assertEqual(resource['samples'], [])
# The invalid finished job cannot be consumed again next tick.
self.adapter.refresh()
self.adapter.submit_job.assert_not_called()
self.assertEqual((folder/'output.log').read_text(), output)

def test_invalid_probe_retries_only_diagnostics_with_fresh_runner_and_budget(self):
# A historical timeout/specification must not reattach the same probe
# once its finished but invalid output has been consumed.
self.resource['probe_timeout']['job'] = JOB
atomic_json(self.adapter.job_folder(REQUEST)/(JOB+'.json'), dict(argv=['read-only-probe']))
self.resource.update(probe_invalid=dict(job=JOB, at='old'),
monitor=dict(state='retry', attempts=3, at=time.time()-60))
self.recover()
self.adapter.submit_job.assert_not_called()
self.resource['monitor'].update(attempts=1, at=time.time())
self.recover()
self.adapter.submit_job.assert_not_called()
self.resource['monitor']['at'] = time.time()-60
self.recover()
self.adapter.submit_job.assert_called_once()
self.assertEqual(self.resource['monitor']['attempts'], 2)
folder = self.adapter.job_folder(REQUEST)/JOB
atomic_json(folder/'status.json', dict(state='finished', exit_code=0))
(folder/'output.log').write_text('GPUQ_TELEMETRY='+json.dumps(dict(
at=time.time(), gpus='0, GPU-test, H100, 81559, 1, 0', apps='')))
self.adapter.refresh_probe(self.resource)
self.assertEqual(self.resource['status'], 'online')
self.assertNotIn('probe_invalid', self.resource)
self.assertNotIn('monitor', self.resource)

def test_corrupt_runner_cannot_authorize_probe_recovery(self):
for content in ['{truncated', 'null', '[]']:
with self.subTest(content=content):
self.runner.write_text(content)
self.recover()
self.adapter.submit_job.assert_not_called()
self.assertEqual(self.runner.read_text(), content)


if __name__ == '__main__':
unittest.main()
Loading
Loading