From f142ce934ba1d3339ba32a3b738fa540f4ecb6ef Mon Sep 17 00:00:00 2001 From: Ferryyer <217455109+Ferryyer@users.noreply.github.com> Date: Mon, 30 Nov 2026 03:03:12 -0800 Subject: [PATCH] LS-100 Align GPU telemetry freshness and guard the sensors probe Co-authored-by: multica-agent --- SOURCE-SHA256.json | 10 ++-- serverbox/crates/sbm_parser/src/commands.rs | 5 +- .../crates/sbm_parser/tests/script_compat.rs | 19 +------ .../scripts/gpu-task-monitor/patch_probe.py | 8 ++- .../scripts/gpu-task-monitor/telemetry.py | 27 +++++++-- .../scripts/gpu-task-monitor/test_probe.py | 45 +++++++++++++-- .../gpu-task-monitor/test_telemetry.py | 57 +++++++++++++++++-- tests/browser_monitor_check.py | 20 +++++-- tests/monitor.test.js | 26 ++++++++- web/app.js | 7 ++- web/index.html | 2 +- web/monitor.js | 5 +- 12 files changed, 183 insertions(+), 48 deletions(-) diff --git a/SOURCE-SHA256.json b/SOURCE-SHA256.json index b326ec7..6847859 100644 --- a/SOURCE-SHA256.json +++ b/SOURCE-SHA256.json @@ -67,7 +67,7 @@ "serverbox/test/unit/app/queue_protocol_test.dart": "f80ddb23f95e2f70b6068728cf4ee1151a8e0c86dc28ae60aa21708b0fb26ee5", "skills/inspire-queue/SKILL.md": "df9180e812f53d0ccddf655380d263f8ec4f2b298956ce94f9984a365338eecc", "tests/browser_check.py": "f5885e5acf430749364699e81fdecf257906f898c971d39f837ae70811b14cd4", - "tests/browser_monitor_check.py": "769f2324ffe7662e99a91bb5c475f0b1af494c920040a2cb76158e9559804bed", + "tests/browser_monitor_check.py": "47c5a064bcd92dcab4d3f7f824e65134afb44e48e8313ed5a268ea5573df6c04", "tests/browser_stop_check.py": "458df6c5f92504191c3331fed599f255ad21c994796f5d7035f2a6c98a3b558c", "tests/browser_task_status.py": "65c5ba6137681244012e15ef16f752c554ee34dacbe6e9ad56b23fcedacecc11", "tests/browser_task_versions_check.py": "63fcc728f2215a695555eb3e2d5c6b16e76f80fe7ea2b2c894f4e4707902ecc2", @@ -77,7 +77,7 @@ "tests/local_python_server.py": "90b43685a6a7a8af13904c40b19d1ee8d6273098d6d4578084fbc2cc6e4f29d5", "tests/local_server.mjs": "bc89ae93ccc0a1e325cbd408c9db5d76574ee76cfd659ef08eff80f33cdca901", "tests/modes.test.cjs": "bf206c7368254c5fa45682e0de482a59517cae7b02bfca9bf62d20aaf088f354", - "tests/monitor.test.js": "bacfb39a197d39f58385b51cbc36f1610f3994c11b207a6c520f147a6c4d6f43", + "tests/monitor.test.js": "941518b54be6b8f280dc66488f340bedcd836e3e03d223b6e9abaa23f69b6c63", "tests/test_chat_start.py": "da13d28efc3441b8bc7a0472e479efd6afca31151845aa0692b55812d6c76a09", "tests/test_gpu_handoff.py": "403575e39813323a971c892c37bcfa0a423772685e44840a2332d063c08d7d73", "tests/test_gpuqueue.py": "04ef9661e5477097c705eb10c795ec5b79bba97e1742c3dc72b57da8bc7779c0", @@ -98,10 +98,10 @@ "tests/widget-update.test.cjs": "17aba14bd32f6ffccd424e103af2fce2bedd63a46d43e955698757196e8359e0", "tests/widget.test.cjs": "21dde14aa712b8f3c814354af8a1323e6c7f92af866169e78dd9b4095f501faf", "updates/gpu-queue-widget.json": "4ff3b46935ab67689c962cc22ceb3155960ff6de7572ff3435f15c481580a475", - "web/app.js": "2831e342ebc04df73cbd2db15281c1d8d3fa920de56c526a9009f3dfc314fda6", - "web/index.html": "d975543a8ecdab73d13fa0c3b372e5c8c96839fb7065caac394270fd3904faca", + "web/app.js": "f9482c8458ba2ef1e2cd242d8f691ea05a958a97104dcbfa1e2837ac4cb57291", + "web/index.html": "cc91565ca89bd08204e941afda96a697e47987c4dd3de0e547fac8c8c89eb85a", "web/model.js": "0bf65ad5badd0d7ccdcb7e278bf55c1805ad702e902b6afc4b348d5300cfb083", - "web/monitor.js": "865a19aac2c810bc02b3fdafbbb919571ec6a35170f591761cc54e5f9a03333f", + "web/monitor.js": "471c658d43cbb092ce91975a2457674e12b37ab3a343c326efab37ef76704dad", "web/style.css": "77a0f4993c49cd263e57bdb8fe420b18ee51eb1047b4009944aab528242b53c1", "worker/api.js": "65ba1c1959a75f29eb03d4eaa0b4e1d8a776d3c6003985692d11417f8680dede" } diff --git a/serverbox/crates/sbm_parser/src/commands.rs b/serverbox/crates/sbm_parser/src/commands.rs index 98edd5a..1158cec 100644 --- a/serverbox/crates/sbm_parser/src/commands.rs +++ b/serverbox/crates/sbm_parser/src/commands.rs @@ -164,7 +164,10 @@ pub const LINUX: &[CommandSpec] = &[ // retain the same command ordering. cmd: ":", }, - CommandSpec { key: SENSORS, cmd: "sensors" }, + CommandSpec { + key: SENSORS, + cmd: "if command -v sensors >/dev/null 2>&1; then sensors; fi", + }, CommandSpec { key: DISK_SMART, // Most distros restrict raw ATA/NVMe ioctls to root, and this runs diff --git a/serverbox/crates/sbm_parser/tests/script_compat.rs b/serverbox/crates/sbm_parser/tests/script_compat.rs index e4e9a05..cc9e917 100644 --- a/serverbox/crates/sbm_parser/tests/script_compat.rs +++ b/serverbox/crates/sbm_parser/tests/script_compat.rs @@ -935,14 +935,8 @@ fn e2e_unix_status_script_runs() { ); } -/// A command that cannot run says so inside its own segment. -/// -/// With stderr discarded, a host without `lm-sensors` and a host with no -/// sensors are the same empty segment, and the page has nothing to tell them -/// apart with — which is why the status functions send it to stdout instead. -/// Emptying `PATH` makes every external command missing at once, which also -/// puts the attribution under test: each complaint has to land in the segment -/// of the command that made it, not in whichever one happened to be open. +/// Probe errors stay in their own segments, and a missing optional `sensors` +/// command leaves an empty segment. Emptying `PATH` exercises both behaviors. #[cfg(unix)] #[test] fn e2e_unix_a_failed_command_speaks_in_its_own_segment() { @@ -977,14 +971,7 @@ fn e2e_unix_a_failed_command_speaks_in_its_own_segment() { // `echo` is a shell builtin, so the branch is still identifiable. assert_eq!(map.get("echo").map(String::as_str), Some("__linux")); - // The wording is the shell's — dash says `not found`, bash with no PATH - // says `No such file or directory` — so what is asserted is that the - // segment is not empty and names the command that failed. - let sensors = map.get("sensors").map(String::as_str).unwrap_or_default(); - assert!(sensors.contains("sensors"), "sensors: {sensors:?}"); - // The complaint of the command before it stayed with the command before - // it: this segment names one command and no other. - assert!(!sensors.contains("diskstats"), "sensors: {sensors:?}"); + assert!(map.get("sensors").is_none_or(String::is_empty)); // `grep` is quiet about a missing file, and the `uname -n` it falls back // to is what complains. diff --git a/serverbox/scripts/gpu-task-monitor/patch_probe.py b/serverbox/scripts/gpu-task-monitor/patch_probe.py index 3e7488f..df061e0 100644 --- a/serverbox/scripts/gpu-task-monitor/patch_probe.py +++ b/serverbox/scripts/gpu-task-monitor/patch_probe.py @@ -12,13 +12,17 @@ OLD = 'if command -v nvidia-smi >/dev/null 2>&1; then nvidia-smi -q -x; elif [ -x /usr/lib/wsl/lib/nvidia-smi ]; then /usr/lib/wsl/lib/nvidia-smi -q -x; fi' NEW = OLD[:-2] + 'elif [ -x "$HOME/.local/bin/serverbox-gpu-status" ]; then "$HOME/.local/bin/serverbox-gpu-status" xml; fi' +SENSORS = 'if command -v sensors >/dev/null 2>&1; then sensors; fi' +SENSORS_SEGMENT = '\techo SrvBoxSep.b64.c2Vuc29ycw==\n\t\t' def patch_script(path): if path.is_symlink() or path.stat().st_uid != os.getuid(): return False raw = path.read_text() - if OLD not in raw: + patched = raw.replace(OLD, NEW).replace( + f'{SENSORS_SEGMENT}sensors\n', f'{SENSORS_SEGMENT}{SENSORS}\n') + if patched == raw: return False backup = path.with_suffix(path.suffix + '.before-gpu-monitor') try: @@ -28,7 +32,7 @@ def patch_script(path): except FileExistsError: pass with tempfile.NamedTemporaryFile(mode='w', dir=path.parent, delete=False) as stream: - stream.write(raw.replace(OLD, NEW)) + stream.write(patched) temp = Path(stream.name) temp.chmod(stat.S_IMODE(path.stat().st_mode)) os.replace(temp, path) diff --git a/serverbox/scripts/gpu-task-monitor/telemetry.py b/serverbox/scripts/gpu-task-monitor/telemetry.py index 31ff543..f0286b3 100644 --- a/serverbox/scripts/gpu-task-monitor/telemetry.py +++ b/serverbox/scripts/gpu-task-monitor/telemetry.py @@ -62,6 +62,10 @@ def atomic_json(path, data): os.replace(temp, path) +def _valid_fresh_ttl(value): + return type(value) in (int, float) and 0 < value < math.inf + + def latest(root=ROOT): registry = root / 'registry.json' if registry.exists(): @@ -71,6 +75,7 @@ def latest(root=ROOT): value = json.loads(registry.read_text()) if value.get('schema') != 1 or value.get('source') != 'gpuq': return None + registry_ttl = value.get('fresh_ttl_s') records = [] for item in value['resources']: stamp = float(item.get('collected_at', 0)) @@ -85,8 +90,10 @@ def latest(root=ROOT): not math.isfinite(number) or number < 0): raise ValueError('Invalid GPU measurement') state = 'ok' if item['status'] == 'online' else item['status'] - records.append(dict(item, schema=1, source='gpuq', state=state, - collected_at=stamp)) + record = dict(item, schema=1, source='gpuq', state=state, collected_at=stamp) + if _valid_fresh_ttl(registry_ttl) and not _valid_fresh_ttl(item.get('fresh_ttl_s')): + record['fresh_ttl_s'] = registry_ttl + records.append(record) return max(records, key=lambda x: (fresh(x), x['state'] not in ('closed', 'failed'), x['collected_at']), default=None) except (OSError, ValueError, TypeError, KeyError, AttributeError): @@ -106,7 +113,10 @@ def fresh(data, now=None, max_age=None): if not data or data.get('state') != 'ok' or not data.get('gpus'): return False if max_age is None: - max_age = 90 if data.get('source') == 'gpuq' else 20 + max_age = 20 + if data.get('source') == 'gpuq': + ttl = data.get('fresh_ttl_s') + max_age = min(300, max(20, ttl)) if _valid_fresh_ttl(ttl) else 180 age = (time.time() if now is None else now) - data['collected_at'] return math.isfinite(age) and -5 <= age <= max_age @@ -115,16 +125,21 @@ def status_text(data, now=None): if not data: return 'GPU:等待实例采集(暂无有效数据)' labels = dict(pending='申请中', ready='实例就绪,等待采样', unknown='连接待核查', - closed='已销毁或回收(平台已确认)', failed='申请或启动失败') + closed='已销毁或回收(平台已确认)', failed='申请或启动失败', + stopped='已停止或数据过期') retry_labels = dict(retry='查询断开,自动重连中', waiting='查询超时,自动核查中', reconciling='正在核对原查询回执', sampling='正在重新采样') + fallback = labels['stopped'] + if data.get('source') == 'gpuq': + labels['ok'] = '在线 · 采样更新等待中' + fallback = labels['unknown'] if fresh(data, now=now): state = '实时' - elif data['state'] in ('closed', 'failed'): + elif data['state'] in ('closed', 'failed', 'stopped'): state = labels[data['state']] else: state = retry_labels.get((data.get('monitor') or {}).get('state'), - labels.get(data['state'], '已停止或数据过期')) + labels.get(data['state'], fallback)) release = ' · 待释放,尚未确认销毁' if data.get('release_pending') else '' request = f' · GPU任务 {data["request"][:8]}' if not data.get('collected_at'): diff --git a/serverbox/scripts/gpu-task-monitor/test_probe.py b/serverbox/scripts/gpu-task-monitor/test_probe.py index 189214a..e1966a5 100644 --- a/serverbox/scripts/gpu-task-monitor/test_probe.py +++ b/serverbox/scripts/gpu-task-monitor/test_probe.py @@ -17,6 +17,8 @@ def test_source_command_matches_deployed_probe(self): lines = (root / 'crates/sbm_parser/src/commands.rs').read_text().splitlines() line = next(line for line in lines if 'cmd:' in line and 'serverbox-gpu-status' in line) self.assertEqual(json.loads(line.split('cmd: ', 1)[1].rstrip(',')), p.NEW) + sensors = next(lines[index + 1] for index, line in enumerate(lines) if 'key: SENSORS,' in line) + self.assertEqual(json.loads(sensors.split('cmd: ', 1)[1].rstrip(',')), p.SENSORS) def test_native_gpu_takes_priority_and_bridge_is_opt_in(self): with tempfile.TemporaryDirectory() as folder: @@ -39,16 +41,51 @@ def test_native_gpu_takes_priority_and_bridge_is_opt_in(self): def test_script_patch_is_atomic_idempotent_and_keeps_backup(self): with tempfile.TemporaryDirectory() as folder: path = Path(folder) / 'srvboxm_v87.sh' - original = '#!/bin/sh\n' + p.OLD + '\n' + prefix = '#!/bin/sh\n\texec 2>&1\n\techo SrvBoxSep.b64.bnZpZGlh\n\t\t' + sensor_segment = '\n\techo SrvBoxSep.b64.c2Vuc29ycw==\n\t\t' + other_segment = '\n\techo unrelated\n\t\tsensors\n' + original = prefix + p.OLD + sensor_segment + 'sensors' + other_segment path.write_text(original) path.chmod(0o700) + inode = path.stat().st_ino self.assertTrue(p.patch_script(path)) self.assertFalse(p.patch_script(path)) - self.assertEqual(path.read_text(), '#!/bin/sh\n' + p.NEW + '\n') - self.assertEqual(path.with_suffix('.sh.before-gpu-monitor').read_text(), original) - link = Path(folder) / 'link.sh' + patched = prefix + p.NEW + sensor_segment + p.SENSORS + other_segment + self.assertEqual(path.read_text(), patched) + self.assertNotEqual(path.stat().st_ino, inode) + self.assertEqual(path.stat().st_mode & 0o777, 0o700) + backup = path.with_suffix('.sh.before-gpu-monitor') + self.assertEqual(backup.read_text(), original) + self.assertEqual(backup.stat().st_mode & 0o777, 0o600) + + # Clients that already have the NVIDIA fix still need the sensor guard. + path.write_text(prefix + p.NEW + sensor_segment + 'sensors' + other_segment) + self.assertTrue(p.patch_script(path)) + self.assertFalse(p.patch_script(path)) + self.assertEqual(path.read_text(), patched) + self.assertEqual(backup.read_text(), original) + + path.write_text(original) + link = Path(folder) / 'srvboxm_v88.sh' link.symlink_to(path) self.assertFalse(p.patch_script(link)) + self.assertTrue(link.is_symlink()) + self.assertEqual(path.read_text(), original) + + def test_optional_sensors_output_is_empty_when_missing_and_preserved_when_present(self): + with tempfile.TemporaryDirectory() as folder: + script = Path(folder) / 'srvboxm_v88.sh' + script.write_text(f'#!/bin/sh\nexec 2>&1\n{p.SENSORS_SEGMENT}sensors\n') + self.assertTrue(p.patch_script(script)) + cmd = ['/bin/sh', str(script)] + env = dict(os.environ, PATH=folder) + marker = 'SrvBoxSep.b64.c2Vuc29ycw==\n' + self.assertEqual(subprocess.check_output(cmd, env=env, text=True), marker) + + sensors = Path(folder) / 'sensors' + sensors.write_text('#!/bin/sh\nprintf "fixture-sensor\\n"\n') + sensors.chmod(0o700) + self.assertEqual(subprocess.check_output(cmd, env=env, text=True), marker + 'fixture-sensor\n') if __name__ == '__main__': diff --git a/serverbox/scripts/gpu-task-monitor/test_telemetry.py b/serverbox/scripts/gpu-task-monitor/test_telemetry.py index b90e48d..2a2c853 100644 --- a/serverbox/scripts/gpu-task-monitor/test_telemetry.py +++ b/serverbox/scripts/gpu-task-monitor/test_telemetry.py @@ -1,8 +1,12 @@ +from contextlib import redirect_stdout import importlib.util +import io import json from pathlib import Path +import sys import tempfile import unittest +from unittest.mock import patch import xml.etree.ElementTree as ET spec = importlib.util.spec_from_file_location('telemetry', Path(__file__).with_name('telemetry.py')) @@ -34,7 +38,7 @@ def test_unavailable_is_not_zero(self): def test_stale_error_stopped_and_future_samples_are_not_live(self): data = self.sample() self.assertTrue(t.fresh(data, now=115)) - self.assertFalse(t.fresh(data, now=121)) + self.assertFalse(t.fresh(dict(data, fresh_ttl_s=300), now=121)) self.assertFalse(t.fresh(data, now=90)) for state in ['stopped', 'error']: self.assertFalse(t.fresh(dict(data, state=state), now=101)) @@ -50,8 +54,8 @@ def test_atomic_private_snapshot_and_partial_input(self): self.assertEqual(t.latest(root)['gpus'][0]['temperature_c'], 63) self.assertEqual(json.loads(path.read_text())['state'], 'ok') - def registry(self, root, resources): - t.atomic_json(root/'registry.json', dict(schema=1, source='gpuq', resources=resources)) + def registry(self, root, resources, **fields): + t.atomic_json(root/'registry.json', dict(schema=1, source='gpuq', resources=resources, **fields)) def record(self, request, status='online', stamp=100): return dict(request=request, status=status, collected_at=stamp, @@ -79,10 +83,53 @@ def test_registry_refresh_does_not_refresh_old_gpu_timestamp(self): root = Path(folder) self.registry(root, [self.record('new')]) data = t.latest(root) - self.assertTrue(t.fresh(data, now=185)) - self.assertFalse(t.fresh(data, now=191)) + self.assertEqual(data['collected_at'], 100) + self.assertTrue(t.fresh(data, now=235)) + self.assertTrue(t.fresh(data, now=280)) + self.assertFalse(t.fresh(data, now=281)) self.assertFalse(t.fresh(data, now=90)) + def test_registry_ttl_precedence_and_bounds(self): + with tempfile.TemporaryDirectory() as folder: + root = Path(folder) + record = self.record('new') + for override, max_age in [(None, 240), (60, 60), (1, 20), (600, 300), + ('60', 240), (True, 240), (-1, 240), (0, 240)]: + with self.subTest(override=override): + self.registry(root, [dict(record, fresh_ttl_s=override)], fresh_ttl_s=240) + data = t.latest(root) + self.assertTrue(t.fresh(data, now=100 + max_age)) + self.assertFalse(t.fresh(data, now=101 + max_age)) + for invalid_ttl in [float('inf'), float('nan')]: + data = dict(record, source='gpuq', state='ok', fresh_ttl_s=invalid_ttl) + self.assertTrue(t.fresh(data, now=280)) + self.assertFalse(t.fresh(data, now=281)) + + def test_xml_command_suppresses_samples_past_default_and_custom_windows(self): + sample = dict(self.sample(), source='gpuq') + for ttl, now, live in [(None, 235, True), (None, 281, False), + (60, 160, True), (60, 161, False)]: + with self.subTest(ttl=ttl, now=now), patch.object(t, 'latest', return_value=dict(sample, fresh_ttl_s=ttl)), \ + patch.object(t.time, 'time', return_value=now), patch.object(t.os, 'umask'), \ + patch.object(sys, 'argv', ['telemetry.py', 'xml']), redirect_stdout(io.StringIO()) as out: + t.main() + if live: + xml = ET.fromstring(out.getvalue()) + self.assertEqual(xml.findtext('timestamp'), '1970-01-01T08:01:40+08:00') + else: + self.assertEqual(out.getvalue(), '') + + def test_expired_online_sample_is_distinct_from_stopped_collector(self): + sample = dict(self.sample(), source='gpuq') + self.assertEqual(t.status_text(sample, now=281).split(' · 采集于')[0], + 'GPU:在线 · 采样更新等待中') + self.assertEqual(t.status_text(dict(sample, monitor={'state': 'retry'}), now=281).split(' · 采集于')[0], + 'GPU:查询断开,自动重连中') + stopped = dict(sample, state='stopped', monitor={'state': 'retry'}) + for data in [stopped, self.sample(), dict(self.sample(), state='error')]: + self.assertEqual(t.status_text(data, now=281).split(' · 采集于')[0], + 'GPU:已停止或数据过期') + def test_invalid_registry_metrics_fail_closed(self): with tempfile.TemporaryDirectory() as folder: root = Path(folder) diff --git a/tests/browser_monitor_check.py b/tests/browser_monitor_check.py index 3988e31..2053235 100644 --- a/tests/browser_monitor_check.py +++ b/tests/browser_monitor_check.py @@ -31,10 +31,12 @@ errors = [] page.on('pageerror', lambda error: errors.append(str(error))) sample_at = time.time() - 30 + release_reason = '释放意图已保存;等待平台回收回执' def state(route): data = route.fetch().json() + data['heartbeat']['resource_policy'] = {'release_when_queue_idle': True} data['heartbeat']['resources'] = [dict(id='fixture-instance', status='online', - ownership='queue', release=dict(state='pending_interface', reason='释放意图已保存;等待平台回收回执'), + ownership='queue', release=dict(state='pending_interface', reason=release_reason), telemetry=dict( at=sample_at, host='fixture-gpu-host', gpus=[dict(index=0, name='H100', used_mb=40960, total_mb=81920, utilization=65, temperature_c=61)]))] @@ -48,7 +50,7 @@ def state(route): expect(page.locator('#account-threads')).to_contain_text('fixture-user') expect(page.locator('#server-resources')).to_contain_text('61 °C') expect(page.locator('#server-resources')).to_contain_text('任务台申请') - expect(page.locator('#server-resources')).to_contain_text('释放意图已保存;等待平台回收回执') + expect(page.locator('#server-resources')).to_contain_text(release_reason) expect(page.locator('#server-resources')).to_contain_text('40.0 / 80.0 GiB') expect(page.locator('#memory-value')).to_contain_text('GiB') sample_at += 25 @@ -64,10 +66,20 @@ def state(route): download.value.save_as(OUT / 'fixture-monitor.json') exported = json.loads((OUT / 'fixture-monitor.json').read_text()) assert len(exported['resources'][0]['history']) == 2 - sample_at = time.time() - 100 + sample_at = time.time() - 135 page.locator('#refresh').click() - expect(page.locator('.monitor-status')).to_contain_text('采样过期') + expect(page.locator('.monitor-status.fresh')).to_have_text('在线') + expect(page.locator('#server-resources')).to_contain_text('61 °C') + expect(page.locator('#gpu-value')).to_have_text('65%') + sample_at = time.time() - 181 + page.locator('#refresh').click() + expect(page.locator('.monitor-status')).to_have_text('在线 · 采样更新等待中') expect(page.locator('#server-resources')).not_to_contain_text('61 °C') + expect(page.locator('#gpu-value')).to_have_text('—') + expect(page.locator('#resource-policy')).to_be_visible() + expect(page.locator('#resource-policy')).to_have_text(release_reason) + expect(page.locator('#server-resources')).to_contain_text('任务台申请') + expect(page.locator('#server-resources')).to_contain_text(release_reason) page.unroute('**/api/state') page.route('**/api/state', lambda route: route.abort()) page.locator('#refresh').click() diff --git a/tests/monitor.test.js b/tests/monitor.test.js index 41b2083..006ffb1 100644 --- a/tests/monitor.test.js +++ b/tests/monitor.test.js @@ -4,9 +4,33 @@ import {resourceView,MonitorHistory} from '../web/monitor.js'; const resource=(at=1000,status='online')=>({id:'instance',status,telemetry:{at,host:'gpu-host',gpus:[{name:'H100',index:0,utilization:80,used_mb:1024,total_mb:81920,temperature_c:60}]}}); test('only live samples expose metrics; future, stale, closed and unknown fail closed',()=>{ assert.equal(resourceView(resource(),1001).gpus[0].temperature,60); - for(const value of [resource(910),resource(1100),resource(1000,'closed'),resource(1000,'unknown')]){ + for(const value of [resource(819),resource(1100),resource(1000,'closed'),resource(1000,'unknown')]){ const view=resourceView(value,1000);assert.equal(view.fresh,false);assert.equal(view.gpus[0].utilization,null); } + assert.equal(resourceView(resource(),1001,false).gpus[0].temperature,null); +}); +test('default window keeps poll samples live through 180 seconds',()=>{ + const value=resource(); + assert.equal(resourceView(value,1135).gpus[0].temperature,60); + assert.equal(resourceView(value,1180).fresh,true); + const expired=resourceView(value,1181); + assert.equal(expired.at,1000); + assert.equal(expired.fresh,false); + assert.deepEqual(expired.gpus[0],{ + name:'H100',index:0,utilization:null,used:null,total:null,temperature:null, + }); +}); +test('finite positive TTLs override the default within the freshness bounds',()=>{ + for(const [ttl,maxAge] of [[60,60],[240,240],[1,20],[600,300]]){ + const value={...resource(),fresh_ttl_s:ttl}; + assert.equal(resourceView(value,1000+maxAge).fresh,true); + assert.equal(resourceView(value,1001+maxAge).gpus[0].used,null); + } + for(const ttl of [null,0,-1,'60',true,NaN,Infinity]){ + const value={...resource(),fresh_ttl_s:ttl}; + assert.equal(resourceView(value,1180).fresh,true); + assert.equal(resourceView(value,1181).fresh,false); + } }); test('missing and invalid metric values remain unavailable, never become zero',()=>{ const value=resource();Object.assign(value.telemetry.gpus[0],{temperature_c:null,utilization:NaN,used_mb:-1}); diff --git a/web/app.js b/web/app.js index 9708bf1..67067ad 100644 --- a/web/app.js +++ b/web/app.js @@ -133,7 +133,10 @@ function renderResource(){ const release=['pending_interface','armed','confirmed'].map(state=>releases.find(r=>r?.state===state)).find(Boolean); releaseNote.hidden=!heartbeat?.resource_policy?.release_when_queue_idle; releaseNote.textContent=release?.reason||'已保存空闲时释放的偏好。成员端无主动释放入口。'; - const online=serviceConnected&&heartbeat&&Date.now()-Date.parse(heartbeat.at)<120000;$('.prototype-tag').textContent=online?'服务器已连接':'等待服务器';const fresh=resources.filter(r=>serviceConnected&&r.status==='online'&&r.telemetry&&Date.now()/1000-r.telemetry.at>=-5&&Date.now()/1000-r.telemetry.at<90);const gpus=fresh.flatMap(r=>r.telemetry.gpus);const used=gpus.reduce((n,g)=>n+g.used_mb,0)/1024,total=gpus.reduce((n,g)=>n+g.total_mb,0)/1024;const utilization=gpus.length?Math.round(gpus.reduce((n,g)=>n+g.utilization,0)/gpus.length):null;$('#gpu-value').innerHTML=utilization===null?'—':`${utilization}%`;$('#gpu-bar').style.width=(utilization||0)+'%';$('#memory-value').innerHTML=gpus.length?`${used.toFixed(1)} / ${Math.round(total)} GiB`:'— GiB';$('#memory-bar').style.width=(total?used/total*100:0)+'%';const pending=resources.filter(r=>r.status==='pending').length;$('.resource-title div>span').innerHTML=`${serviceConnected?'':''} ${!serviceConnected?'连接异常 · 上次采样非实时':gpus.length?`${gpus.length} 张 GPU 已核验`:pending?`${pending} 份已有申请等待就绪`:'开始任务后核查并复用资源'}`;$('#schedule-label').textContent=state.tasks.filter(t=>group(t)==='running').length>1?'● 复用资源 · 并行中':'● 按顺序执行';$('#schedule-hint').textContent='设备互不重叠且满足显存与负载条件时,最多并行 2 个 GPU 任务';$('#connection-note').innerHTML=`${online?'◈':'◷'}${heartbeat?.error&&heartbeat.feishu_auth?.state!=='blocked'?esc(heartbeat.error):online?'服务器已连接。提交只进入待启动列表;点击开始后才会复用或申请 GPU。':'等待服务器同步。启动指令会持久保存,服务连接后再处理。'}${heartbeat?' · 最近同步 '+date(heartbeat.at):''}`;} + const now=Date.now()/1000; + const fresh=resources.filter(resource=>resourceView(resource,now,serviceConnected).fresh); + const gpus=fresh.flatMap(resource=>resource.telemetry.gpus||[]); + const online=serviceConnected&&heartbeat&&Date.now()-Date.parse(heartbeat.at)<120000;$('.prototype-tag').textContent=online?'服务器已连接':'等待服务器';const used=gpus.reduce((n,g)=>n+g.used_mb,0)/1024,total=gpus.reduce((n,g)=>n+g.total_mb,0)/1024;const utilization=gpus.length?Math.round(gpus.reduce((n,g)=>n+g.utilization,0)/gpus.length):null;$('#gpu-value').innerHTML=utilization===null?'—':`${utilization}%`;$('#gpu-bar').style.width=(utilization||0)+'%';$('#memory-value').innerHTML=gpus.length?`${used.toFixed(1)} / ${Math.round(total)} GiB`:'— GiB';$('#memory-bar').style.width=(total?used/total*100:0)+'%';const pending=resources.filter(r=>r.status==='pending').length;$('.resource-title div>span').innerHTML=`${serviceConnected?'':''} ${!serviceConnected?'连接异常 · 上次采样非实时':gpus.length?`${gpus.length} 张 GPU 已核验`:pending?`${pending} 份已有申请等待就绪`:'开始任务后核查并复用资源'}`;$('#schedule-label').textContent=state.tasks.filter(t=>group(t)==='running').length>1?'● 复用资源 · 并行中':'● 按顺序执行';$('#schedule-hint').textContent='设备互不重叠且满足显存与负载条件时,最多并行 2 个 GPU 任务';$('#connection-note').innerHTML=`${online?'◈':'◷'}${heartbeat?.error&&heartbeat.feishu_auth?.state!=='blocked'?esc(heartbeat.error):online?'服务器已连接。提交只进入待启动列表;点击开始后才会复用或申请 GPU。':'等待服务器同步。启动指令会持久保存,服务连接后再处理。'}${heartbeat?' · 最近同步 '+date(heartbeat.at):''}`;} function matches(t){return (!query||`${t.name} ${t.project} ${t.agent} ${t.id}`.toLowerCase().includes(query.toLowerCase()))&&(filter==='all'||filter==='queue'&&['queued','running'].includes(group(t))||filter==='ready'&&t.state==='ready'||filter==='history'&&['failed','completed','stopped'].includes(group(t)));} function renderList(){let html='';for(const [status,title,caption]of [['running','正在运行','流程成功后自动衔接'],['queued','执行队列','仅已批准的任务会运行'],['ready','待你启动','准备完成后,由你决定'],['failed','需要处理','已有产物保留,不自动重跑'],['stopped','已停止或撤回','已有快照和产物保留'],['completed','已完成','结果已保存']]){const tasks=state.tasks.filter(t=>group(t)===status&&matches(t));if(!tasks.length)continue;html+=`
${title}${tasks.length}${caption}
`;for(const t of tasks){const queue=state.tasks.filter(reorderable),pos=queue.findIndex(x=>x.id===t.id)+1;html+=`
${reorderable(t)?'':`${group(t)==='running'?'◉':group(t)==='failed'?'!':t.state==='completed'?'✓':'◇'}`}
${esc(t.name)}${esc(t.agent)}
${esc(t.project)} · ${t.id.slice(0,11)}
${taskEvidence(t)}
${t.steps.map((s,i)=>`${i?'→':''}${stepState(t,i)==='done'?'✓ ':''}${esc(s)}`).join('')}
${trainingBar(t)}
${badge(t)}${t.state==='ready'?``:reorderable(t)?`队列第 ${pos} 位
`:`${esc(t.elapsed)}`}
`;}}$('#task-list').innerHTML=html||`
${state.tasks.length?'没有符合条件的任务。':'任务队列为空。'}
${state.tasks.length?'试试其他筛选条件。':'让 Codex 或 Claude 准备任务并通过 gpuq submit 提交。'}
`;bindRows();renderMode();} function versionDetails(task){ @@ -279,7 +282,7 @@ function renderMonitor(){ const view=resourceView(resource,now,serviceConnected),samples=monitorHistory.samples.get(view.id)||[]; const points=samples.map(sample=>`${((sample.at-(now-1800))/1800*300).toFixed(1)},${(58-Math.min(100,sample.value)/100*54).toFixed(1)}`).join(' '); const age=Number.isFinite(view.at)&&view.at>0?Math.max(0,Math.floor(now-view.at)):null; - return `

${esc(view.host||'GPU 实例')}

${esc(view.id)}
${!serviceConnected?'连接异常 · 上次采样非实时':esc(statuses[view.status]||view.status||'未知')+(view.status==='online'&&!view.fresh?' · 采样过期':'')}
+ return `

${esc(view.host||'GPU 实例')}

${esc(view.id)}
${!serviceConnected?'连接异常 · 上次采样非实时':esc(statuses[view.status]||view.status||'未知')+(view.status==='online'&&!view.fresh?' · 采样更新等待中':'')}

${esc(view.ownership)}

${view.release?`

${esc(view.release)}

`:''}
${view.gpus.map(gpu=>`
GPU ${esc(gpu.index)} · ${esc(gpu.name)}
利用率
${metric(gpu.utilization,'%')}
显存
${gpu.used===null||gpu.total===null?'—':`${(gpu.used/1024).toFixed(1)} / ${(gpu.total/1024).toFixed(1)} GiB`}
温度
${metric(gpu.temperature,' °C')}
`).join('')||'

尚无 GPU 采样,等待已有资源探测。

'}
diff --git a/web/index.html b/web/index.html index ac7d6df..fafc90b 100644 --- a/web/index.html +++ b/web/index.html @@ -49,7 +49,7 @@
-
YOUR SERVERS, AT A GLANCE.

服务器与 GPU

复用已有 ServerBox 同步数据 · 采样超过 90 秒标记过期

+
YOUR SERVERS, AT A GLANCE.

服务器与 GPU

复用已有 ServerBox 同步数据 · 默认显示最近 180 秒内的采样

趋势仅记录此页面打开期间最近 30 分钟的采样,刷新后清空。实例详情为只读。

diff --git a/web/monitor.js b/web/monitor.js index 24cf8af..1369daa 100644 --- a/web/monitor.js +++ b/web/monitor.js @@ -1,7 +1,10 @@ // Read-only monitoring built on Inspire Queue telemetry; no ServerBox client required. export function resourceView(resource, now=Date.now()/1000, connected=true){ const telemetry=resource.telemetry||{}, at=Number(telemetry.at); - const fresh=connected&&resource.status==='online'&&Number.isFinite(at)&&at>0&&now-at>=-5&&now-at<90; + const ttl=resource.fresh_ttl_s; + const maxAge=Number.isFinite(ttl)&&ttl>0?Math.min(300,Math.max(20,ttl)):180; + const age=now-at; + const fresh=connected&&resource.status==='online'&&Number.isFinite(at)&&at>0&&age>=-5&&age<=maxAge; const number=value=>typeof value==='number'&&Number.isFinite(value)&&value>=0?value:null; return {id:resource.id, status:resource.status, host:telemetry.host||'', at, fresh, ownership:({queue:'任务台申请',member:'成员已有申请',unknown:'归属待核查'})[resource.ownership]||'归属待核查',