From 774efeacf264adc00f0ebef4126a29397ce5fb95 Mon Sep 17 00:00:00 2001 From: theferry <217455109+Ferryyer@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:03:15 -0800 Subject: [PATCH] LS-99: sample GPU telemetry from active runners Co-authored-by: multica-agent --- SOURCE-SHA256.json | 8 +- gpuqueue/platform.py | 196 ++++++++++++-------- gpuqueue/runner.py | 132 +++++++++++++- gpuqueue/serverbox.py | 11 +- tests/test_gpuqueue.py | 4 +- tests/test_probe_recovery.py | 3 +- tests/test_request_diagnostics.py | 6 +- tests/test_resource_monitoring.py | 10 +- tests/test_runner_telemetry.py | 291 ++++++++++++++++++++++++++++++ 9 files changed, 563 insertions(+), 98 deletions(-) create mode 100644 tests/test_runner_telemetry.py diff --git a/SOURCE-SHA256.json b/SOURCE-SHA256.json index 68cbbac..11a95c3 100644 --- a/SOURCE-SHA256.json +++ b/SOURCE-SHA256.json @@ -20,9 +20,9 @@ "gpuqueue/control.py": "1412129e7f0f7c4f67db0c4c11f3e66f24cc1353f7bf67ad13b2ef86ae29de28", "gpuqueue/core.py": "a726498140ffc19076a461b9254ef3cb7ce7085119bd11997650f2068fef4c24", "gpuqueue/host_monitor.py": "ec685be9bf9e498eefe7f9b8719b06a581853df01dd006ade239d70ef6196e4b", - "gpuqueue/platform.py": "1c4aad5ea1c2f41937ebaeafec03a5cc99ffee7d2dda706446d9919e49277f9d", - "gpuqueue/runner.py": "300c18ee4360bdf320f1a02c9a1eae21cca33d39347f4157b43e705f5177c304", - "gpuqueue/serverbox.py": "204470fb517ccd27609f5b2d1d68fa30d1a53f541a18d8e4412761fa8023817c", + "gpuqueue/platform.py": "960be0be5133a4db752da705da0c5880bb7050f4772a5acc66a169a2b99d894b", + "gpuqueue/runner.py": "7f20c357c0df5e3c07ececa3d0a95648b5ae3c74bfd1c4ffba85e03396bf4756", + "gpuqueue/serverbox.py": "00de2db3e01a89525f69dd0c55d75d92d340c0aa552817cd255d58062f8c9c55", "gpuqueue/service.py": "df60d5d835a3baef689dba4a80362088c07eea1e711ecc7244fda4ed504d9972", "gpuqueue/stop_control.py": "10d2241a2882dbb97605f4fcb364c6f6fbe01451b8d90137d3aed1ff859433f7", "gpuqueue/web.py": "e399f5a728767bd1ffe7845f50a54f73a98c7771611a7f1b40addb5b21064ee1", @@ -63,7 +63,7 @@ "tests/local_server.mjs": "f7b943a06fc8881d9e083a05ff556948d8f8273b6fff59bb681e6ad5633520fa", "tests/modes.test.cjs": "f55a0afd571abe617a9c0cf1dc3f2591085d58dcad5435fd45382e6705548038", "tests/monitor.test.js": "54fa84e136fe8d9303ec0bfa873d53a402a1cdd34adfd3eb475f32678efc5e0d", - "tests/test_gpuqueue.py": "614df82d4652e8d529d5c030df852aabc766f9b03427bf2acf8d286a4e0cc316", + "tests/test_gpuqueue.py": "c657e41630e8f25e4b4c65b84eb9621f9cfc60389d7ed1290218c7437a669972", "tests/test_host_monitor.py": "951bc42312a4cf24437a114cdf2881e6d6e119992d8a32d0fc4a4f73aa13c494", "tests/test_launcher.py": "c336ce79267510501294ee1f73600b5b57ab8143469d75a8cf5d827e650e941d", "tests/test_local.py": "ebdb961978ede03745d8bb2eb7e8bc2624e4f88628574af590a0a2d8287d4bc4", diff --git a/gpuqueue/platform.py b/gpuqueue/platform.py index 3ba76b8..5532ef9 100644 --- a/gpuqueue/platform.py +++ b/gpuqueue/platform.py @@ -3,7 +3,6 @@ from concurrent.futures import ThreadPoolExecutor import datetime as dt import json -import math import os from pathlib import Path import re @@ -12,11 +11,61 @@ import uuid from .core import HOME, atomic_json, read_json, now from .feishu import FeishuAuthError, PlatformError, auth_error, command, verify_user -from .serverbox import publish as publish_serverbox +from .runner import parse_smi_telemetry, validate_telemetry +from .serverbox import FRESH_TTL_S, publish as publish_serverbox from .resources import record_terminal FORM = 'shrcn3qH6A3KPzzS07UzvgAUAkh' TRUSTED_SENDER = 'cli_aa59fbf9c878dd0b' +RUNNER_FRESH_TTL = 45 +RUNNER_HEARTBEAT_TTL = 90 +PROBE_CLAIM_TIMEOUT = 180 +PARALLEL_SAMPLE_WINDOW = 900 +PARALLEL_MAX_GAP = 190 +PARALLEL_IDLE_LOOKBACK = 330 + + +def telemetry_is_fresh(resource): + stamp = (resource.get('telemetry') or {}).get('at', 0) + return stamp > 0 and -5 <= time.time()-stamp <= FRESH_TTL_S + + +def sustained_low_utilization(samples, current): + # Only the latest continuous idle period counts toward parallel admission. + recent = sorted((s for s in samples if -5 <= current-s['at'] < PARALLEL_SAMPLE_WINDOW), + key=lambda sample: sample['at'], reverse=True) + if not recent: + return False + if any(current-s['at'] < PARALLEL_IDLE_LOOKBACK and s['utilization'] >= 30 for s in recent): + return False + latest = previous = recent[0]['at'] + for count, sample in enumerate(recent, 1): + stamp = sample['at'] + if sample['utilization'] >= 30 or previous-stamp > PARALLEL_MAX_GAP: + break + if count >= 5 and latest-stamp >= 270: + return True + previous = stamp + return False + + +def record_telemetry(resource, telemetry): + stamp = telemetry['at'] + previous = (resource.get('telemetry') or {}).get('at', 0) + if stamp > previous: + resource['telemetry'] = telemetry + samples = resource.setdefault('samples', []) + samples.append({'at': stamp, 'utilization': max(g['utilization'] for g in telemetry['gpus'])}) + resource['samples'] = [sample for sample in samples if stamp-sample['at'] < PARALLEL_SAMPLE_WINDOW] + resource['status'] = 'online' + 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) + if resource.get('probe_timeout'): + resource['last_probe_timeout'] = resource.pop('probe_timeout') + def memory_mb(resources): # Manifests use decimal GB; nvidia-smi reports binary MiB. @@ -234,36 +283,38 @@ def begin_task_sampling(self, task): self.persist() publish_serverbox(self.resources, self.home) - def recover_active_probe(self, resource): - """Retry only diagnostics, with fresh evidence from an existing runner. - - 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['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: - return + def active_runners(self, resource): for task in self.store.tasks(): internal = task['internal'] if (internal.get('request_uuid') != resource['id'] or not internal.get('approved_at') or internal.get('dispatch') != 'submitted' or not internal.get('job_uuid') - or internal.get('stop_requested_at') - or task['public']['state'] not in ['starting', 'running']): + or internal.get('stop_requested_at') or internal.get('stop_confirmed') + or task['public']['state'] not in ['dispatching', 'starting', 'running']): continue + path = 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 + with path.open() as stream: + if os.fstat(stream.fileno()).st_uid != os.getuid(): + continue + runner = json.load(stream) except (OSError, ValueError): - # Unreadable runner evidence cannot authorize a diagnostic retry. continue + if (isinstance(runner, dict) and runner.get('gpu_verified') is True + and runner.get('state') in ['starting', 'running']): + yield task, runner + + def recover_active_probe(self, resource, runners): + """Retry diagnostics when a legacy runner still has a fresh heartbeat.""" + 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: + return + for task, runner in runners: 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): + if (runner['state'] != 'running' or type(at) not in (int, float) + or not -5 <= time.time()-at < RUNNER_HEARTBEAT_TTL): continue old_job = (resource.get('probe_timeout') or {}).get('job') if old_job and old_job != (resource.get('probe_invalid') or {}).get('job'): @@ -279,9 +330,28 @@ def recover_active_probe(self, resource): return def refresh_probe(self, resource, *, active=True): - if resource['status'] not in ['ready', 'online'] and not ( - resource['status'] == 'unknown' and (resource.get('probe') or - (resource.get('monitor') or {}).get('state') == 'sampling')): + if resource['status'] not in ['ready', 'online', 'unknown']: + return + runners = list(self.active_runners(resource)) + current = time.time() + runner_telemetry = None + for _, runner in runners: + try: + telemetry = validate_telemetry(runner['telemetry'], current) + except (AttributeError, KeyError, TypeError, ValueError, OverflowError): + continue + stamp = telemetry['at'] + if current-stamp < RUNNER_FRESH_TTL and (runner_telemetry is None or stamp > runner_telemetry['at']): + runner_telemetry = telemetry + if runner_telemetry: + if runner_telemetry['at'] > (resource.get('telemetry') or {}).get('at', 0): + record_telemetry(resource, runner_telemetry) + if not resource.get('probe'): + return + else: + self.recover_active_probe(resource, runners) + if resource['status'] == 'unknown' and not (resource.get('probe') or + (resource.get('monitor') or {}).get('state') == 'sampling'): return probe = resource.get('probe') if probe: @@ -294,39 +364,25 @@ def refresh_probe(self, resource, *, active=True): 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 遥测采样时间无效') + telemetry = parse_smi_telemetry(payload, time.time()) 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') + resource['probe'] = None + if not runner_telemetry: + resource.update(status='unknown', probe_invalid={'at': now(), 'job': probe['job']}, + error='GPU 检查已结束,但遥测输出缺失、损坏或采样时间无效;资源可用性待核查('+type(error).__name__+')') + if resource.get('monitor'): + resource['monitor']['state'] = 'retry' + # A malformed receipt resolves the outstanding probe. + 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) - if resource.get('probe_timeout'): - resource['last_probe_timeout'] = resource.pop('probe_timeout') - resource.setdefault('samples', []).append({'at': stamp, 'utilization': max((g['utilization'] for g in gpus), default=100)}) - resource['samples'] = [sample for sample in resource['samples'] if stamp-sample['at'] < 420] + resource.update(probe=None, probe_checked=time.time()) + record_telemetry(resource, telemetry) return if status.get('state') in ['failed', 'finished']: + if runner_telemetry: + resource['probe'] = None + return output = folder/'output.log' timed_out = (status.get('exit_code') == 124 and output.is_file() and 'GPUQ_PROBE_TIMEOUT=1' in output.read_text(errors='replace').splitlines()) @@ -337,7 +393,7 @@ def refresh_probe(self, resource, *, active=True): if timed_out: resource['probe_timeout'] = {'at': now(), 'job': probe['job']} return - if time.time()-probe['at'] > 100: + if not runner_telemetry and time.time()-probe['at'] > PROBE_CLAIM_TIMEOUT: # A slow claim is not a failed query. Keep this exact probe so # a late receipt is reconciled instead of submitting duplicates. resource.update(status='unknown', @@ -346,10 +402,9 @@ def refresh_probe(self, resource, *, active=True): resource.setdefault('monitor', {})['state'] = 'waiting' return # Count from the GPU sample, not when a delayed receipt was consumed. - # With a slow platform poll, adding another 30 seconds here made a - # healthy allocation repeatedly cross the 90-second freshness limit. + # Keep the active delay short enough to catch the next platform poll. last_sample = (resource.get('telemetry') or {}).get('at', resource.get('probe_checked', 0)) - interval = 60 if not active and resource['status'] in ['ready', 'online'] else 10 + interval = 60 if not active and resource['status'] in ['ready', 'online'] else 2 if (not resource.get('probe_checked') or time.time()-last_sample >= interval or resource.get('sample_requested_at', 0) > last_sample): job = self.submit_job(resource['id'], ['/usr/bin/python3', '-c', PROBE_SCRIPT], self.home) @@ -376,7 +431,7 @@ def refresh(self, active=False): errors.append(error) due = [] # Slow historical notification searches must not serially delay - # current GPU samples beyond their 90-second freshness window. + # current GPU samples beyond their freshness window. with ThreadPoolExecutor(max_workers=4) as pool: notices = [(resource, pool.submit(self.refresh_notice, resource)) for resource in due] for resource, future in notices: @@ -392,12 +447,10 @@ def refresh(self, active=False): for resource in resources: # A failed notification query must not prevent reading a probe # already completed in shared HOME, or skip other allocations. - for refresh in (self.recover_active_probe, - lambda r: self.refresh_probe(r, active=active)): - try: - refresh(resource) - except (PlatformError, OSError, subprocess.SubprocessError) as error: - errors.append(error) + try: + self.refresh_probe(resource, active=active) + except (PlatformError, OSError, subprocess.SubprocessError) as error: + errors.append(error) if errors: # Keep the scheduler fail-closed while publishing any real # samples recovered above; never refresh their GPU timestamp. @@ -417,7 +470,7 @@ def request(self, task): required = task['doc']['resources'] # A known smaller allocation may be insufficient. Unknown or busy usable # allocations must be reconciled rather than treated as absent. - if any(r['status'] != 'online' or time.time()-r.get('telemetry', {}).get('at', 0)>90 or len([g for g in r.get('telemetry', {}).get('gpus', []) if g['total_mb'] >= memory_mb(required)+reserve_mb(g)]) >= required['gpus'] and r.get('type') == required['type'] for r in unresolved): + if any(r['status'] != 'online' or not telemetry_is_fresh(r) or len([g for g in r.get('telemetry', {}).get('gpus', []) if g['total_mb'] >= memory_mb(required)+reserve_mb(g)]) >= required['gpus'] and r.get('type') == required['type'] for r in unresolved): return None if read_json(self.store.root/'tasks'/task['id']/'run/stop.json',{}).get('digest') == task['digest']: return None @@ -487,13 +540,10 @@ def select(self, task, active): # Uncertain submissions above still require reconciliation before reuse. for resource in self.resources.values(): telemetry = resource.get('telemetry', {}) - if resource['status'] != 'online' or time.time()-telemetry.get('at', 0) > 90 or resource.get('type') != required['type']: + if resource['status'] != 'online' or not telemetry_is_fresh(resource) or resource.get('type') != required['type']: continue if active: - samples = [s for s in resource.get('samples', []) if time.time()-s['at'] < 330] - if len(samples) < 5 or samples[-1]['at']-samples[0]['at'] < 270 or any(s['utilization'] >= 30 for s in samples): - continue - if any(samples[i+1]['at']-samples[i]['at'] > 90 for i in range(len(samples)-1)): + if not sustained_low_utilization(resource.get('samples', []), time.time()): continue if time.time()-max(t['internal'].get('dispatched_at', time.time()) for t in active) < 300: continue @@ -512,7 +562,7 @@ def select(self, task, active): available.sort(key=lambda gpu: gpu['total_mb']-gpu['used_mb'], reverse=True) if len(available) >= required['gpus']: return (resource, [g['uuid'] for g in available[:required['gpus']]]), '' - if any(r['status'] == 'online' and r.get('type') == required['type'] and time.time()-r.get('telemetry', {}).get('at', 0)<=90 for r in self.resources.values()): + if any(r['status'] == 'online' and r.get('type') == required['type'] and telemetry_is_fresh(r) for r in self.resources.values()): return None, 'GPU 已就绪;当前空闲显存或并行条件尚不满足任务要求' replaceable = {r['id'] for r in self.replacement_candidates(task)} for resource in self.resources.values(): diff --git a/gpuqueue/runner.py b/gpuqueue/runner.py index 69d1c35..eb9bb87 100644 --- a/gpuqueue/runner.py +++ b/gpuqueue/runner.py @@ -1,14 +1,125 @@ """Foreground GPU pipeline. Reads immutable input; never applies for resources.""" -import datetime as dt +import csv import hashlib import json +import math import os from pathlib import Path +from queue import Empty, Queue +import selectors +import socket import subprocess import sys import tempfile +from threading import Thread import time -import selectors + +TELEMETRY_INTERVAL = 15 +GPU_FIELDS = 'index,uuid,name,memory.total,memory.used,utilization.gpu,temperature.gpu' +UNAVAILABLE_METRICS = {'N/A', '[N/A]', 'Not Supported', '[Not Supported]'} + + +def validate_telemetry(payload, current): + """Check and allowlist the fields shared by runner and probe samples.""" + stamp = payload['at'] + if type(stamp) not in (int, float) or not math.isfinite(stamp) or not 0 < stamp <= current+5: + raise ValueError('Invalid GPU sample time') + host = payload.get('host', '') + if not isinstance(host, str): + raise ValueError('Invalid GPU host') + if not isinstance(payload['gpus'], list) or not isinstance(payload['apps'], list): + raise ValueError('Invalid GPU telemetry') + + gpus, indexes, devices = [], set(), set() + for gpu in payload['gpus']: + index, device, name = (gpu[key] for key in ('index', 'uuid', 'name')) + total, used, utilization = (gpu[key] for key in ('total_mb', 'used_mb', 'utilization')) + temperature = gpu.get('temperature_c') + metrics = (total, used, utilization) if temperature is None else (total, used, utilization, temperature) + if (type(index) is not int or index < 0 or index in indexes + or not isinstance(device, str) or not device.strip() or device in devices + or not isinstance(name, str) or not name.strip() + or any(type(n) not in (int, float) or not math.isfinite(n) or n < 0 for n in metrics) + or total <= 0 or used > total or utilization > 100): + raise ValueError('Invalid GPU metrics') + indexes.add(index) + devices.add(device) + gpus.append(dict(index=index, uuid=device, name=name, total_mb=total, + used_mb=used, utilization=utilization, temperature_c=temperature)) + if not gpus: + raise ValueError('Missing GPU metrics') + + apps = payload['apps'] + for row in apps: + if (not isinstance(row, list) or len(row) != 2 + or not isinstance(row[0], str) or not row[0].strip() + or not isinstance(row[1], str) or not row[1].isdecimal()): + raise ValueError('Invalid GPU compute process') + return dict(gpus=gpus, apps=apps, at=stamp, host=host) + + +def parse_smi_telemetry(payload, current): + gpus = [] + for row in csv.reader(payload['gpus'].splitlines(), skipinitialspace=True): + if len(row) not in (6, 7): + raise ValueError('Invalid GPU metrics') + temperature = row[6].strip() if len(row) == 7 else 'N/A' + gpus.append(dict(index=int(row[0]), uuid=row[1].strip(), name=row[2].strip(), + total_mb=float(row[3]), used_mb=float(row[4]), utilization=float(row[5]), + temperature_c=None if temperature in UNAVAILABLE_METRICS else float(temperature))) + apps = [[field.strip() for field in row] + for row in csv.reader(payload['apps'].splitlines(), skipinitialspace=True)] + return validate_telemetry(dict(gpus=gpus, apps=apps, at=payload['at'], + host=payload.get('host', '')), current) + + +def query_smi(fields): + result = subprocess.run(['nvidia-smi', fields, '--format=csv,noheader,nounits'], + capture_output=True, text=True, timeout=5) + result.check_returncode() + return result.stdout.strip() + + +class TelemetrySampler: + """Run at most one sample off the heartbeat and log-draining thread.""" + def __init__(self): + self.next_at = time.monotonic() + self.results = Queue(maxsize=1) + self.pending = False + + def sample(self): + try: + gpus = query_smi('--query-gpu='+GPU_FIELDS) + stamp = time.time() + apps = query_smi('--query-compute-apps=gpu_uuid,pid') + sample = parse_smi_telemetry(dict(gpus=gpus, apps=apps, at=stamp, + host=socket.gethostname()), time.time()) + except Exception: + sample = None + self.results.put_nowait(sample) + + def collect(self, status): + if self.pending: + try: + sample = self.results.get_nowait() + except Empty: + return + self.pending = False + if sample is not None and sample['at'] > status.get('telemetry', {}).get('at', 0): + status['telemetry'] = sample + + def tick(self, status): + self.collect(status) + current = time.monotonic() + if current >= self.next_at: + self.next_at = current + TELEMETRY_INTERVAL + if not self.pending: + try: + Thread(target=self.sample, daemon=True).start() + self.pending = True + except Exception: + pass + def write(path, value): fd, temporary = tempfile.mkstemp(dir=path.parent, prefix='.state-') @@ -66,6 +177,8 @@ def execute(folder): if len(device_ids) != doc['resources']['gpus'] or not set(device_ids).issubset(set(gpu.stdout.split())): raise RuntimeError('Assigned GPU identity is unavailable') status['gpu_verified'] = True + sampler = TelemetrySampler() + sampler.tick(status) for index, step in enumerate(doc['steps']): # Verify the frozen code again at step boundaries. for relative, digest in doc['files'].items(): @@ -92,7 +205,7 @@ def execute(folder): selector.register(process.stdout, selectors.EVENT_READ) while selector.get_map(): # Output must not trigger a status fsync or delay the next heartbeat. - timeout = max(0, 10 - (time.monotonic() - heartbeat_at)) + timeout = max(0, min(heartbeat_at+10, sampler.next_at) - time.monotonic()) for key, _ in selector.select(timeout=timeout): chunk = os.read(key.fileobj.fileno(), 65536) if not chunk: @@ -102,6 +215,7 @@ def execute(folder): os.replace(log, log.with_suffix('.previous.log')) with log.open('ab') as stream: stream.write(chunk) + sampler.tick(status) heartbeat_now = time.monotonic() if heartbeat_now - heartbeat_at >= 10: status['updated_at'] = time.time() @@ -111,14 +225,18 @@ def execute(folder): process.stdout.close() # EOF only closes the log stream; the child may still be computing. while True: - timeout = max(0, 10 - (time.monotonic() - heartbeat_at)) + timeout = max(0, min(heartbeat_at+10, sampler.next_at) - time.monotonic()) try: code = process.wait(timeout=timeout) break except subprocess.TimeoutExpired: - status['updated_at'] = time.time() - write(state_file, status) - heartbeat_at = time.monotonic() + sampler.tick(status) + heartbeat_now = time.monotonic() + if heartbeat_now - heartbeat_at >= 10: + status['updated_at'] = time.time() + write(state_file, status) + heartbeat_at = heartbeat_now + sampler.collect(status) record.update(exit_code=code, finished_at=time.time()) if code != 0: record['state'] = 'failed' diff --git a/gpuqueue/serverbox.py b/gpuqueue/serverbox.py index 7fb78d7..57baf46 100644 --- a/gpuqueue/serverbox.py +++ b/gpuqueue/serverbox.py @@ -7,6 +7,9 @@ from .resources import published_resources +FRESH_TTL_S = 180 + + def metric(value): if value is None: return None @@ -29,9 +32,13 @@ def publish(resources, home): memory_used_mib=metric(gpu['used_mb']), memory_total_mib=metric(gpu['total_mb']), temperature_c=metric(gpu.get('temperature_c')))) + monitor_state = (resource.get('monitor') or {}).get('state') + if not monitor_state and resource.get('probe'): + monitor_state = 'sampling' records.append(dict(request=request, status=resource['status'], - collected_at=stamp, host=telemetry.get('host', ''), gpus=gpus, - monitor={key: resource['monitor'][key] for key in ['state'] if key in resource.get('monitor', {})}, + collected_at=stamp, fresh_ttl_s=FRESH_TTL_S, + host=telemetry.get('host', ''), gpus=gpus, + monitor={'state': monitor_state} if monitor_state else {}, release_pending=resource.get('release', {}).get('state') == 'pending_interface')) path = Path(home)/'.local/state/serverbox-gpu/registry.json' atomic_json(path, dict(schema=1, source='gpuq', updated_at=time.time(), resources=records)) diff --git a/tests/test_gpuqueue.py b/tests/test_gpuqueue.py index 325417a..b9a79db 100644 --- a/tests/test_gpuqueue.py +++ b/tests/test_gpuqueue.py @@ -185,13 +185,13 @@ def test_runner_real_child_burst_preserves_all_output_with_few_status_writes(sel def test_runner_silent_child_keeps_ten_second_heartbeats(self): result, _, writes, timeouts, _ = self.run_output_events([(30.5, b'')]) self.assertEqual(result, 0) - self.assertEqual(timeouts, [10, 10, 10, 10]) + self.assertEqual(timeouts, [10, 5, 5, 10, 10]) self.assertEqual([at for at, _ in writes[3:-2]], [10, 20, 30]) def test_runner_output_before_silence_does_not_postpone_heartbeat(self): result, _, writes, timeouts, _ = self.run_output_events([(9.75, b'progress'), (20.5, b'')]) self.assertEqual(result, 0) - self.assertEqual(timeouts, [10, 0.25, 10, 10]) + self.assertEqual(timeouts, [10, 0.25, 5, 5, 10]) self.assertEqual([at for at, _ in writes[3:-2]], [10, 20]) def test_runner_early_eof_keeps_heartbeat_until_child_exits(self): diff --git a/tests/test_probe_recovery.py b/tests/test_probe_recovery.py index ab99570..a056575 100644 --- a/tests/test_probe_recovery.py +++ b/tests/test_probe_recovery.py @@ -39,7 +39,6 @@ def write_runner(self, **changes): updated_at=time.time(), **changes)) def recover(self): - self.adapter.recover_active_probe(self.resource) self.adapter.refresh_probe(self.resource) def test_fresh_runner_recovers_only_readonly_probe_and_needs_real_sample(self): @@ -72,7 +71,7 @@ def test_historical_running_receipt_without_fresh_runner_cannot_retry(self): self.adapter.submit_job.assert_not_called() def test_pending_probe_is_kept_and_late_receipt_is_consumed_without_duplicates(self): - self.resource.update(status='online', probe=dict(job=JOB, at=time.time()-101)) + self.resource.update(status='online', probe=dict(job=JOB, at=time.time()-181)) specification = self.adapter.job_folder(REQUEST)/(JOB+'.json') atomic_json(specification, dict(argv=['read-only-probe'])) self.adapter.refresh_probe(self.resource) diff --git a/tests/test_request_diagnostics.py b/tests/test_request_diagnostics.py index 35ef6bb..2b93845 100644 --- a/tests/test_request_diagnostics.py +++ b/tests/test_request_diagnostics.py @@ -151,7 +151,7 @@ def test_pending_request_keeps_resource_and_execution_admission_checks(self): REQUEST: dict(id=REQUEST, status='pending', recorded_phase='submitted'), 'available': resource, } - for change in [dict(at=time.time()-100), + for change in [dict(at=time.time()-181), dict(gpus=[dict(uuid='GPU-1', total_mb=81920, used_mb=81920)]), dict(apps=[['GPU-1', '999']])]: with self.subTest(change=change): @@ -177,7 +177,7 @@ def test_pending_request_keeps_resource_and_execution_admission_checks(self): def test_late_probe_reuses_old_gpu_once_and_preserves_pending_replacement(self): task = self.task() old = self.enable_replacement() - old['probe'] = dict(job='late-probe', at=time.time()-101) + old['probe'] = dict(job='late-probe', at=time.time()-181) self.adapter.lark = Mock(side_effect=[{'questions': []}, {'record_id': 'new-receipt'}]) self.service.cycle() task = self.store.get(task['id']) @@ -451,7 +451,7 @@ def test_existing_healthy_gpu_is_reused_before_requesting_replacement(self): self.adapter.lark.assert_not_called() def test_actual_probe_timeout_records_evidence_without_claiming_release(self): - resource = dict(id=REQUEST, status='ready', probe=dict(job='unclaimed', at=time.time()-101)) + resource = dict(id=REQUEST, status='ready', probe=dict(job='unclaimed', at=time.time()-181)) self.adapter.refresh_probe(resource) self.assertTrue(self.adapter.probe_timed_out(resource)) self.assertEqual(resource['status'], 'unknown') diff --git a/tests/test_resource_monitoring.py b/tests/test_resource_monitoring.py index 9f21162..eeb4104 100644 --- a/tests/test_resource_monitoring.py +++ b/tests/test_resource_monitoring.py @@ -50,7 +50,7 @@ def online(self, age=0): class MonitoringTests(MonitoringFixture): def test_periods_use_actual_sample_time_in_both_ready_and_online(self): for status in ['ready', 'online']: - for active, age, count in [(False, 59, 0), (False, 60, 1), (True, 9, 0), (True, 10, 1)]: + for active, age, count in [(False, 59, 0), (False, 60, 1), (True, 1, 0), (True, 2, 1)]: with self.subTest(status=status, active=active, age=age): resource = dict(self.online(age), status=status) self.adapter.resources = {REQUEST: resource} @@ -58,7 +58,7 @@ def test_periods_use_actual_sample_time_in_both_ready_and_online(self): self.adapter.refresh(active=active) self.assertEqual(self.adapter.submit_job.call_count, count) - def test_idle_to_active_rechecks_ten_second_period_in_same_tick(self): + def test_idle_to_active_rechecks_two_second_period_in_same_tick(self): resource = self.online(20) self.adapter.resources = {REQUEST: resource} self.adapter.refresh(active=False) @@ -78,7 +78,7 @@ def test_initial_and_explicit_samples_bypass_idle_period(self): self.adapter.submit_job.assert_called_once() def test_inflight_and_late_receipt_keep_exact_job_and_sample_time(self): - resource = dict(self.online(60), probe=dict(job=JOB, at=NOW-101)) + resource = dict(self.online(60), probe=dict(job=JOB, at=NOW-181)) self.adapter.resources = {REQUEST: resource} spec = self.adapter.job_folder(REQUEST)/(JOB+'.json') atomic_json(spec, dict(argv=['read-only-probe'])) @@ -101,9 +101,9 @@ def test_inflight_and_late_receipt_keep_exact_job_and_sample_time(self): self.adapter.submit_job.assert_called_once() self.assertTrue(spec.exists()) - def test_selection_keeps_ninety_second_actual_telemetry_boundary(self): + def test_selection_uses_180_second_actual_telemetry_boundary(self): task = dict(internal={}, doc=dict(resources=dict(type='H卡离线', gpus=1, memory_gb=1))) - for age, ready in [(89, True), (90, True), (90.001, False)]: + for age, ready in [(179, True), (180, True), (180.001, False)]: with self.subTest(age=age): self.adapter.resources = {REQUEST: self.online(age)} selection, _ = self.adapter.select(task, []) diff --git a/tests/test_runner_telemetry.py b/tests/test_runner_telemetry.py new file mode 100644 index 0000000..b1d6e9c --- /dev/null +++ b/tests/test_runner_telemetry.py @@ -0,0 +1,291 @@ +"""Validate GPU monitoring with synthetic processes, task files and clocks.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import threading +import unittest +from unittest.mock import Mock, patch + +from gpuqueue import runner +from gpuqueue.core import Store, atomic_json, read_json +from gpuqueue.platform import Markflow, PROBE_SCRIPT + +REQUEST = '11111111-1111-4111-8111-111111111111' +JOB = '22222222-2222-4222-8222-222222222222' +NOW = 1_800_000_000 +GPU_CSV = '0, GPU-test, Test GPU, 81920, 1024, 10, 42' +APPS_CSV = 'GPU-test, 1234' +REQUIREMENTS = dict(type='H卡离线', gpus=1, memory_gb=1) + + +def sample(at): + return runner.parse_smi_telemetry(dict(gpus=GPU_CSV, apps=APPS_CSV, + at=at, host='synthetic-gpu'), at) + + +class RunnerTelemetryTests(unittest.TestCase): + def run_pipeline(self, query_failure=None): + with tempfile.TemporaryDirectory() as directory: + home = Path(directory).resolve() + (home/'step.py').write_text('pass') + store = Store(home/'queue') + with patch('gpuqueue.core.HOME', home): + task, _ = store.submit(dict(project=str(home), title='synthetic task', + code_files=['step.py'], steps=[dict(argv=['/usr/bin/python3', '{code}/step.py'])])) + folder = store.root/'tasks'/task['id'] + state = folder/'run/status.json' + atomic_json(folder/'run/approval.json', dict(digest=task['digest'], approved_at='browser', + gpu_uuids=['GPU-test'])) + clock, writes, queries = [0], [], [] + process = Mock(pid=1234) + key = Mock(fileobj=process.stdout) + selector = Mock() + selector.get_map.side_effect = lambda: clock[0] < 18 + + def select(timeout): + clock[0] = min(18, clock[0] + timeout) + return [(key, runner.selectors.EVENT_READ)] if clock[0] == 18 else [] + + def wait(timeout): + clock[0] = min(41, clock[0] + timeout) + if clock[0] < 41: + raise subprocess.TimeoutExpired('synthetic training', timeout) + return 0 + + selector.select.side_effect = select + process.wait.side_effect = wait + + def nvidia_smi(argv, **options): + if argv[1] == '--query-gpu=uuid': + return subprocess.CompletedProcess(argv, 0, 'GPU-test\n') + self.assertEqual(options['timeout'], 5) + queries.append((clock[0], argv[1])) + if clock[0] == 15 and query_failure == 'timeout': + raise subprocess.TimeoutExpired(argv, options['timeout']) + if clock[0] == 15 and query_failure == 'nonzero': + return subprocess.CompletedProcess(argv, 1, '') + output = GPU_CSV if argv[1].startswith('--query-gpu=') else APPS_CSV + if clock[0] == 30 and query_failure == 'parse': + output = 'invalid telemetry' + return subprocess.CompletedProcess(argv, 0, output) + + write = runner.write + + def capture(path, value): + write(path, value) + writes.append((clock[0], read_json(path))) + + # Finish samples synchronously only in this fake-clock timeline. + with patch.object(Path, 'home', return_value=home), \ + patch.object(runner.subprocess, 'run', side_effect=nvidia_smi), \ + patch.object(runner.subprocess, 'Popen', return_value=process), \ + patch.object(runner.selectors, 'DefaultSelector', return_value=selector), \ + patch.object(runner.os, 'read', return_value=b''), \ + patch.object(runner.time, 'monotonic', side_effect=lambda: clock[0]), \ + patch.object(runner.time, 'time', side_effect=lambda: NOW + clock[0]), \ + patch.object(runner.socket, 'gethostname', return_value='synthetic-gpu'), \ + patch.object(runner, 'Thread', side_effect=lambda *, target, daemon: Mock(start=target)), \ + patch.object(runner, 'write', side_effect=capture): + self.assertEqual(runner.execute(folder), 0) + self.assertEqual(read_json(state)['state'], 'completed') + self.assertEqual(read_json(state)['steps'][0]['exit_code'], 0) + return dict(writes), queries + + def test_samples_on_schedule_during_log_reads_and_after_eof(self): + writes, queries = self.run_pipeline() + self.assertEqual(queries, [(at, field) for at in (0, 15, 30) for field in + ('--query-gpu='+runner.GPU_FIELDS, '--query-compute-apps=gpu_uuid,pid')]) + self.assertEqual(writes[10]['telemetry'], sample(NOW)) + self.assertEqual(writes[20]['telemetry'], sample(NOW+15)) + self.assertEqual(writes[30]['updated_at'], NOW+30) + self.assertEqual(writes[40]['telemetry'], sample(NOW+30)) + + def test_failed_samples_preserve_last_snapshot_and_training_exit(self): + for failure in ('timeout', 'nonzero', 'parse'): + with self.subTest(failure=failure): + writes, _ = self.run_pipeline(failure) + failed_at = 40 if failure == 'parse' else 20 + last_sample_at = NOW+15 if failure == 'parse' else NOW + self.assertEqual(writes[failed_at]['telemetry'], sample(last_sample_at)) + self.assertEqual(writes[failed_at]['updated_at'], NOW+failed_at) + self.assertEqual(writes[41]['state'], 'completed') + + def test_pending_smi_does_not_block_caller_or_start_another_query(self): + started, release = threading.Event(), threading.Event() + status = {} + clock = Mock(return_value=0) + threads = [] + + def query(_): + started.set() + release.wait(timeout=5) + raise subprocess.TimeoutExpired('nvidia-smi', 5) + + def thread(**options): + threads.append(threading.Thread(**options)) + return threads[-1] + + with patch.object(runner.time, 'monotonic', clock), \ + patch.object(runner, 'Thread', side_effect=thread), \ + patch.object(runner, 'query_smi', side_effect=query): + sampler = runner.TelemetrySampler() + try: + sampler.tick(status) + self.assertTrue(started.wait(timeout=2)) + self.assertTrue(threads[0].is_alive()) + clock.return_value = 15 + sampler.tick(status) + self.assertEqual(len(threads), 1) + self.assertEqual(status, {}) + finally: + release.set() + for worker in threads: + worker.join(timeout=2) + + +class RunnerTelemetryPlatformTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.home = Path(directory.name) + self.task = dict(id='GQ-test', public=dict(state='running'), doc=dict(resources=REQUIREMENTS), + internal=dict(request_uuid=REQUEST, approved_at='browser', dispatch='submitted', + job_uuid='compute', dispatched_at=NOW-700)) + self.store = Mock(root=self.home/'queue') + self.store.metadata.side_effect = lambda key, *args: ( + {'replace_timed_out_gpu': True} if key == 'resource_policy' else None) + self.store.tasks.return_value = [self.task] + self.adapter = Markflow(self.store, dict(home=str(self.home))) + self.adapter.check_auth = Mock() + self.adapter.lark = Mock(return_value=dict(messages=[])) + self.adapter.submit_job = Mock(return_value=JOB) + self.resource = dict(id=REQUEST, status='online', type=REQUIREMENTS['type'], + telemetry=sample(NOW-10), probe_checked=NOW-10) + self.adapter.resources[REQUEST] = self.resource + self.state = self.store.root/'tasks'/self.task['id']/'run/status.json' + clock = patch('time.time', return_value=NOW) + self.clock = clock.start() + self.addCleanup(clock.stop) + + def write_runner(self, **changes): + atomic_json(self.state, dict(dict(state='starting', gpu_verified=True, updated_at=NOW, + telemetry=sample(NOW)), **changes)) + + def finish_probe(self, at, gpus=GPU_CSV, apps=APPS_CSV): + 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( + gpus=gpus, apps=apps, at=at, host='synthetic-gpu'))) + + def test_fresh_runner_recovers_resource_once_then_falls_back_when_stale(self): + self.resource.update(status='unknown', probe_timeout=dict(job='old-probe'), error='old') + self.write_runner() + for elapsed in (0, 20, 44): + self.clock.return_value = NOW+elapsed + self.adapter.refresh(active=True) + self.assertEqual(self.resource['telemetry'], sample(NOW)) + self.adapter.submit_job.assert_not_called() + self.assertEqual(self.resource['status'], 'online') + self.assertEqual(self.resource['samples'], [dict(at=NOW, utilization=10)]) + self.assertNotIn('error', self.resource) + self.assertNotIn('probe_timeout', self.resource) + self.assertEqual(self.resource['last_probe_timeout'], dict(job='old-probe')) + self.clock.return_value = NOW+45 + self.adapter.refresh(active=True) + self.adapter.submit_job.assert_called_once_with( + REQUEST, ['/usr/bin/python3', '-c', PROBE_SCRIPT], self.home) + + def test_finished_runner_restores_probe_path_even_with_a_recent_sample(self): + self.write_runner(state='running') + self.adapter.refresh(active=True) + self.adapter.submit_job.assert_not_called() + self.write_runner(state='completed') + self.clock.return_value = NOW+3 + self.adapter.refresh(active=True) + self.adapter.submit_job.assert_called_once() + + def test_inflight_probe_is_reconciled_without_regressing_runner_sample(self): + self.resource['probe'] = dict(job=JOB, at=NOW-181) + self.write_runner() + self.adapter.refresh(active=True) + self.assertEqual(self.resource['probe']['job'], JOB) + self.assertEqual(self.resource['status'], 'online') + self.assertNotIn('probe_timeout', self.resource) + record = read_json(self.home/'.local/state/serverbox-gpu/registry.json')['resources'][0] + self.assertEqual(record['monitor'], dict(state='sampling')) + self.assertEqual(record['fresh_ttl_s'], 180) + self.finish_probe(NOW-5) + self.adapter.refresh(active=True) + self.assertIsNone(self.resource['probe']) + self.assertEqual(self.resource['telemetry'], sample(NOW)) + self.assertEqual(self.resource['samples'], [dict(at=NOW, utilization=10)]) + self.adapter.submit_job.assert_not_called() + + def test_135_second_platform_poll_and_real_timeout(self): + self.resource.update(telemetry=dict(sample(NOW), apps=[]), probe=dict(job=JOB, at=NOW)) + pending = dict(internal=dict(approved_at='browser'), doc=dict(resources=REQUIREMENTS)) + for elapsed in (90, 100, 135): + self.clock.return_value = NOW+elapsed + self.adapter.refresh(active=True) + self.assertEqual(self.resource['status'], 'online') + self.assertIsNotNone(self.adapter.select(pending, [])[0]) + self.assertEqual(self.adapter.replacement_candidates(pending), []) + self.assertIsNone(self.adapter.request(pending)) + self.finish_probe(NOW+135) + self.adapter.refresh(active=True) + self.assertEqual(self.resource['telemetry']['at'], NOW+135) + self.assertIsNone(self.resource['probe']) + self.clock.return_value = NOW+137 + self.adapter.refresh(active=True) + self.adapter.submit_job.assert_called_once() + (self.adapter.job_folder(REQUEST)/JOB/'status.json').unlink() + for elapsed, status in ((180, 'online'), (181, 'unknown')): + self.clock.return_value = NOW+137+elapsed + self.adapter.refresh(active=True) + self.assertEqual(self.resource['status'], status) + self.assertEqual(self.resource['probe_timeout']['job'], JOB) + self.assertEqual(self.adapter.replacement_candidates(pending), [self.resource]) + self.assertEqual(self.resource['telemetry']['at'], NOW+135) + self.adapter.submit_job.assert_called_once() + + def test_rejects_unverified_unowned_unapproved_and_invalid_runner_samples(self): + changes = ( + dict(gpu_verified=False), + dict(telemetry=dict(sample(NOW), at=NOW+6)), + dict(telemetry=dict(sample(NOW), at=float('inf'))), + dict(telemetry=dict(sample(NOW), gpus=[])), + dict(telemetry=dict(sample(NOW), apps=[['invalid']])), + dict(telemetry=dict(sample(NOW), gpus=[dict(sample(NOW)['gpus'][0], utilization=float('nan'))])), + ) + for change in changes: + with self.subTest(change=change): + self.write_runner(**change) + self.adapter.refresh_probe(self.resource) + self.assertEqual(self.resource['telemetry'], sample(NOW-10)) + + self.write_runner() + with patch('gpuqueue.platform.os.getuid', return_value=os.getuid()+1): + self.adapter.refresh_probe(self.resource) + self.assertEqual(self.resource['telemetry'], sample(NOW-10)) + + internal = self.task['internal'] + for change in (dict(request_uuid=JOB), dict(approved_at=None), + dict(stop_confirmed=True), dict(stop_requested_at='browser')): + with self.subTest(change=change): + self.task['internal'] = dict(internal, **change) + self.adapter.refresh_probe(self.resource) + self.assertEqual(self.resource['telemetry'], sample(NOW-10)) + + def test_parallel_admission_has_room_for_five_platform_samples(self): + self.write_runner(steps=[dict(state='running', pid=1234)]) + self.resource['samples'] = [dict(at=NOW-offset, utilization=10) + for offset in (540, 405, 270, 135, 0)] + pending = dict(internal={}, doc=dict(resources=REQUIREMENTS)) + self.assertIsNotNone(self.adapter.select(pending, [self.task])[0]) + self.resource['samples'][2]['utilization'] = 50 + self.assertIsNone(self.adapter.select(pending, [self.task])[0]) + self.resource['samples'][2]['utilization'] = 10 + self.resource['samples'][0]['at'] = NOW-596 + self.assertIsNone(self.adapter.select(pending, [self.task])[0])