From a8fa16a6b22a38b8eebaef5e7c38db3d7291dadc 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 | 10 +++- tests/monitor.test.js | 26 ++++++++- web/app.js | 4 +- web/index.html | 2 +- web/monitor.js | 5 +- 12 files changed, 172 insertions(+), 46 deletions(-) diff --git a/SOURCE-SHA256.json b/SOURCE-SHA256.json index 11a95c3..986b245 100644 --- a/SOURCE-SHA256.json +++ b/SOURCE-SHA256.json @@ -54,7 +54,7 @@ "serverbox/lib/view/page/setting/entry.dart": "1fb436babe99bcd456e5a5d3c38dcb51640dd9cde9574325e94f7fce50e37e4f", "serverbox/test/unit/app/gpu_queue_test.dart": "e3514fe355b58f3a86d1cb83ccff58129532d5da132013f76cfdcc9bfeb7e854", "tests/browser_check.py": "f5885e5acf430749364699e81fdecf257906f898c971d39f837ae70811b14cd4", - "tests/browser_monitor_check.py": "fd9ff1273517bfeb988d75b96cfb00e288bbe692073e6e3101915526e6e527a1", + "tests/browser_monitor_check.py": "60f374d662cebb4c497596195c1fd7f2f2dd898471bd6755b74d1e0a07f93926", "tests/browser_stop_check.py": "39b4276e0c19af5ef3af8a0b9e993f2f585c9e2088c2e29b4c728001e1c7d2e0", "tests/browser_typography_check.py": "a4304aea410b98c0b4407ad24b87c3e914194f2657a9cc0e7842ebd768b74394", "tests/cloud.test.js": "da8dddec4638a65bb909d192f01fea7e9ff75a3b438ae08e0b76e67396defac1", @@ -62,7 +62,7 @@ "tests/local_python_server.py": "de99fc6b719c483975f196f25781e7f16122a710790eb74fd66ac8fff71d404c", "tests/local_server.mjs": "f7b943a06fc8881d9e083a05ff556948d8f8273b6fff59bb681e6ad5633520fa", "tests/modes.test.cjs": "f55a0afd571abe617a9c0cf1dc3f2591085d58dcad5435fd45382e6705548038", - "tests/monitor.test.js": "54fa84e136fe8d9303ec0bfa873d53a402a1cdd34adfd3eb475f32678efc5e0d", + "tests/monitor.test.js": "541a173049863f19885f83787a9387c86d703dcd2cf3f6436621965fd37397cc", "tests/test_gpuqueue.py": "c657e41630e8f25e4b4c65b84eb9621f9cfc60389d7ed1290218c7437a669972", "tests/test_host_monitor.py": "951bc42312a4cf24437a114cdf2881e6d6e119992d8a32d0fc4a4f73aa13c494", "tests/test_launcher.py": "c336ce79267510501294ee1f73600b5b57ab8143469d75a8cf5d827e650e941d", @@ -74,10 +74,10 @@ "tests/widget-update.test.cjs": "846ebaf0550e0899e5723f939fe9fb2965ac91030ab761f19be50a576bbe02a5", "tests/widget.test.cjs": "21dde14aa712b8f3c814354af8a1323e6c7f92af866169e78dd9b4095f501faf", "updates/gpu-queue-widget.json": "4ff3b46935ab67689c962cc22ceb3155960ff6de7572ff3435f15c481580a475", - "web/app.js": "c0b713c0fa0df7f6012dab436c27967e0d4b50dd5e913a054158bdb9f6c5144e", - "web/index.html": "65095a3bcebc12ed89db0a7c59f47da2ffa1e21b3c933471606e587f411c32b8", + "web/app.js": "8c601abf889844579eeaf6e54b6fb199530bdf216440c6d99a5f35fa17492381", + "web/index.html": "0bfb14d1118a4e5cb778eba6bc774a6c96486cb41744af2c56836980728cb72e", "web/model.js": "55d7b7162a64eb2b142e6be6b5b4174c463a94b49d8525947e0563ba62896d4c", - "web/monitor.js": "41d58e769c1fa728600ac73a645b1d4ce1ac4ca2d49127e4e6e1bfa073bf6066", + "web/monitor.js": "84d0fc2bf2d5f366a920e5fd3fe1b97adb04a0357af5bd326c041dc4d9fd7c24", "web/style.css": "c05706fbd5042983fd51632e531b277debdf8a22f378d109696ed980feb98162", "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 8ed952e..aa8dc02 100644 --- a/tests/browser_monitor_check.py +++ b/tests/browser_monitor_check.py @@ -57,10 +57,16 @@ 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('—') 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 6791623..bc6bf0d 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 0b82cf0..b40a485 100644 --- a/web/app.js +++ b/web/app.js @@ -78,7 +78,7 @@ function preserveContext(update){ } function render(){preserveContext(()=>{renderStats();renderResource();renderFeishuAuth();renderMonitor();renderList();renderDetail();renderMode();});} function renderStats(){const count=fn=>state.tasks.filter(fn).length;$('#stats').innerHTML=[['待你启动',count(t=>t.state==='ready'),'Agent 已准备好,等待你的决定','◷',''],['执行队列',count(queued),'已批准,可拖动调整顺序','☷',''],['正在运行',count(t=>group(t)==='running'),'顺序执行,空闲时增加并行','▷','running'],['需要处理',count(t=>group(t)==='failed'),'查看原因,已有产物保留','!','attention']].map(([name,value,desc,icon,cls])=>`
${name}${icon}
${String(value).padStart(2,'0')}
${desc}
`).join('');$('#nav-count').textContent=state.tasks.length;} -function renderResource(){const policy=heartbeat?.resource_policy,releaseNote=$('#resource-policy');releaseNote.hidden=!policy?.release_when_queue_idle;releaseNote.textContent=(heartbeat?.resources||[]).some(r=>r.release?.state==='pending_interface')?'任务已结束,GPU 待释放。平台尚无主动释放入口,当前未确认释放。':'已保存用完即释放的偏好。平台尚无主动释放入口,暂不能立即释放。';const online=serviceConnected&&heartbeat&&Date.now()-Date.parse(heartbeat.at)<120000;$('.prototype-tag').textContent=online?'服务器已连接':'等待服务器';const resources=heartbeat?.resources||[];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 个任务';$('#connection-note').innerHTML=`${online?'◈':'◷'}${heartbeat?.error&&heartbeat.feishu_auth?.state!=='blocked'?esc(heartbeat.error):online?'服务器已连接。提交只进入待启动列表;点击开始后才会复用或申请 GPU。':'等待服务器同步。启动指令会持久保存,服务连接后再处理。'}${heartbeat?' · 最近同步 '+date(heartbeat.at):''}`;} +function renderResource(){const policy=heartbeat?.resource_policy,releaseNote=$('#resource-policy');releaseNote.hidden=!policy?.release_when_queue_idle;releaseNote.textContent=(heartbeat?.resources||[]).some(r=>r.release?.state==='pending_interface')?'任务已结束,GPU 待释放。平台尚无主动释放入口,当前未确认释放。':'已保存用完即释放的偏好。平台尚无主动释放入口,暂不能立即释放。';const online=serviceConnected&&heartbeat&&Date.now()-Date.parse(heartbeat.at)<120000;$('.prototype-tag').textContent=online?'服务器已连接':'等待服务器';const resources=heartbeat?.resources||[];const now=Date.now()/1000;const fresh=resources.filter(r=>resourceView(r,now,serviceConnected).fresh);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 个任务';$('#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)}
${t.queue_stage&&t.phase?`
${esc(t.phase)}
`:''}
${t.steps.map((s,i)=>`${i?'→':''}${stepState(t,i)==='done'?'✓ ':''}${esc(s)}`).join('')}
${t.state==='running'?`
`:''}
${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 renderDetail(){const t=state.tasks.find(t=>t.id===state.selected);if(!t){$('#detail').innerHTML='
选择一个任务
查看准备情况和执行步骤
';return;}const index=selectedStep??Math.min(t.stage,t.steps.length-1),completed=t.step_records.filter(s=>s.state==='completed').length;$('#detail').innerHTML=`
任务详情 · ${t.id.slice(0,11)}${badge(t)}

${esc(t.name)}

${esc(t.description)}

${esc(t.agent)}${date(t.created_at)} 提交 · 北京时间
${t.state==='ready'?``:group(t)==='failed'?'':['completed','stopped','cancelled'].includes(t.state)?'':''}${canStop(t)?``:t.state==='stopping'?'':''}${t.phase&&t.state==='stopping'?`
${esc(t.phase)}
`:''}${queued(t)?`
${esc(queueDetails(t)).replaceAll('\n','
')}
`:''}
资源需求 · Agent 判断
${t.resources.gpus} 卡${t.memory?' · 每卡 '+t.memory+' GB':''}
运行时长
${esc(t.elapsed)}
固定版本
${esc(t.version)}
启动授权
${t.approved_at?date(t.approved_at):'等待你点击开始'}
执行步骤${completed} / ${t.steps.length} 已完成
${t.steps.map((name,i)=>{const st=stepState(t,i);return ``;}).join('')}
${[['overview','准备检查'],['logs','步骤日志'],['results','结果文件'],['events','事件']].map(([id,label])=>``).join('')}
${detailContent(t,index)}
`;$('#back-to-tasks')?.addEventListener('click',closeDetail);$('#detail [data-detail-start]')?.addEventListener('click',()=>start(t.id));$('#detail [data-detail-stop]')?.addEventListener('click',()=>requestStop(t.id));$('#diagnostic')?.addEventListener('click',()=>copy(`任务:${t.id}\n版本:${t.version}\n状态:${labels[t.state]}\n原因:${t.failureReason||'待核查'}\n申请:${t.request_uuid||'未申请'}\n任务回执:${t.job_uuid||'未提交'}\n${t.step_records.map(s=>s.name+'\n'+(s.log||'')).join('\n')}`));$('#view-results')?.addEventListener('click',()=>{detailTab='results';preserveContext(renderDetail);});$$('[data-step]').forEach(b=>b.addEventListener('click',()=>{selectedStep=Number(b.dataset.step);detailTab='logs';preserveContext(renderDetail);}));$$('[data-detail-tab]').forEach(b=>b.addEventListener('click',()=>{detailTab=b.dataset.detailTab;preserveContext(renderDetail);}));$$('[data-output]').forEach(b=>b.addEventListener('click',()=>copy(b.dataset.output)));renderMode();} @@ -135,7 +135,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?' · 采样更新等待中':'')}
${view.releasePending?'

待释放:平台尚未确认销毁。

':''}
${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 采样,等待已有资源探测。

'}
GPU 平均利用率 · 已累计 ${samples.length?Math.max(0,Math.round(samples.at(-1).at-samples[0].at)):0} 秒 / 最长 30 分钟${samples.length>1?`${samples.map(sample=>``).join('')}100%0%30 分钟前 ← 真实时间比例 → 现在`:'

等待两个不同时间的有效采样。

'}
diff --git a/web/index.html b/web/index.html index 19df7eb..9873d52 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 1f88e43..8a06e9d 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, releasePending:resource.release?.state==='pending_interface',