aiinfra-tools 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/README.md +27 -3
  3. package/bin/aiinfra.mjs +5 -2
  4. package/bin/report.mjs +177 -0
  5. package/fleetops/README.md +33 -1
  6. package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
  7. package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
  8. package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
  9. package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
  10. package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
  11. package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
  12. package/fleetops/deploy/shadow-live/README.md +41 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +123 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +53 -0
  16. package/fleetops/docs/ADMISSION.md +9 -9
  17. package/fleetops/docs/FABRIC-STORAGE.md +1 -1
  18. package/fleetops/docs/SERVING.md +11 -1
  19. package/fleetops/docs/SHADOW.md +250 -0
  20. package/fleetops/docs/SIGNALS.md +5 -2
  21. package/fleetops/docs/WORKLOADS.md +1 -1
  22. package/fleetops/package.json +7 -4
  23. package/fleetops/src/adapters/fabric.mjs +19 -7
  24. package/fleetops/src/adapters/live.mjs +38 -5
  25. package/fleetops/src/adapters/logs.mjs +10 -7
  26. package/fleetops/src/adapters/nvsentinel.mjs +95 -0
  27. package/fleetops/src/adapters/topology.mjs +53 -1
  28. package/fleetops/src/admission.mjs +26 -18
  29. package/fleetops/src/api.mjs +2 -1
  30. package/fleetops/src/bundle.mjs +3 -0
  31. package/fleetops/src/calibrate.mjs +1 -1
  32. package/fleetops/src/detect.mjs +1 -1
  33. package/fleetops/src/export.mjs +5 -1
  34. package/fleetops/src/goodput.mjs +0 -2
  35. package/fleetops/src/incidents.mjs +1 -2
  36. package/fleetops/src/ingest.mjs +10 -3
  37. package/fleetops/src/inject.mjs +2 -2
  38. package/fleetops/src/live.mjs +2 -1
  39. package/fleetops/src/llmd.mjs +7 -3
  40. package/fleetops/src/optimize.mjs +1 -1
  41. package/fleetops/src/power.mjs +7 -7
  42. package/fleetops/src/procure.mjs +67 -0
  43. package/fleetops/src/rca.mjs +1 -1
  44. package/fleetops/src/rollout.mjs +1 -1
  45. package/fleetops/src/schema.mjs +3 -2
  46. package/fleetops/src/security.mjs +1 -1
  47. package/fleetops/src/serving.mjs +32 -10
  48. package/fleetops/src/shadow-canary.mjs +74 -0
  49. package/fleetops/src/shadow-gate.mjs +49 -0
  50. package/fleetops/src/shadow-prom.mjs +205 -0
  51. package/fleetops/src/shadow-replay.mjs +147 -0
  52. package/fleetops/src/shadow.mjs +291 -0
  53. package/fleetops/src/stats.mjs +14 -0
  54. package/fleetops/src/traces.mjs +0 -5
  55. package/fleetops/tests/fixtures/real/README.md +5 -0
  56. package/fleetops/tools/admit-node.sh +51 -16
  57. package/fleetops/tools/amd-admit.py +111 -0
  58. package/fleetops/tools/cmd/calibrate.mjs +61 -0
  59. package/fleetops/tools/cmd/capacity.mjs +116 -0
  60. package/fleetops/tools/cmd/common.mjs +32 -0
  61. package/fleetops/tools/cmd/data.mjs +343 -0
  62. package/fleetops/tools/cmd/help.mjs +243 -0
  63. package/fleetops/tools/cmd/incidents.mjs +216 -0
  64. package/fleetops/tools/cmd/rollout.mjs +122 -0
  65. package/fleetops/tools/cmd/server.mjs +122 -0
  66. package/fleetops/tools/cmd/serving.mjs +95 -0
  67. package/fleetops/tools/cmd/shadow.mjs +204 -0
  68. package/fleetops/tools/cmd/training.mjs +79 -0
  69. package/fleetops/tools/collect.sh +6 -1
  70. package/fleetops/tools/fleetops.mjs +18 -1308
  71. package/fleetops/tools/loop-demo.mjs +1 -1
  72. package/fleetops/tools/workload-profile.mjs +0 -1
  73. package/fleetscope/README.md +5 -1
  74. package/fleetscope/build.mjs +4 -0
  75. package/fleetscope/dist/index.html +1013 -28
  76. package/fleetscope/docs/AGENTIC.md +89 -0
  77. package/fleetscope/docs/PLANNING.md +4 -2
  78. package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
  79. package/fleetscope/package.json +4 -3
  80. package/fleetscope/src/agentic.js +288 -0
  81. package/fleetscope/src/ask.js +0 -1
  82. package/fleetscope/src/cluster-ui.js +1 -0
  83. package/fleetscope/src/engine.js +29 -13
  84. package/fleetscope/src/index.src.html +15 -5
  85. package/fleetscope/src/inference-ui.js +1 -0
  86. package/fleetscope/src/ingest.js +89 -3
  87. package/fleetscope/src/optimize.js +11 -5
  88. package/fleetscope/src/plan.js +1 -1
  89. package/fleetscope/src/training-ui.js +1 -0
  90. package/fleetscope/tools/agentic.mjs +148 -0
  91. package/fleetscope/tools/tracelab-data.mjs +27 -0
  92. package/gpu-health/README.md +13 -2
  93. package/gpu-health/docs/CONFIG.md +29 -1
  94. package/gpu-health/package.json +7 -4
  95. package/gpu-health/src/actions.mjs +16 -3
  96. package/gpu-health/src/analyze.mjs +3 -0
  97. package/gpu-health/src/config.mjs +3 -0
  98. package/gpu-health/src/executors.mjs +9 -4
  99. package/gpu-health/src/health.mjs +1 -1
  100. package/gpu-health/src/ingest.mjs +27 -3
  101. package/gpu-health/src/platforms.mjs +109 -0
  102. package/gpu-health/src/vendors.mjs +12 -5
  103. package/gpu-health/tools/gpu-health.mjs +6 -4
  104. package/gpu-ledger/README.md +3 -1
  105. package/gpu-ledger/package.json +12 -4
  106. package/gpu-ledger/src/adapters.mjs +3 -2
  107. package/gpu-ledger/src/cloud.mjs +104 -0
  108. package/gpu-ledger/src/core.mjs +12 -10
  109. package/gpu-ledger/tools/ledger.mjs +8 -2
  110. package/harness-ledger/README.md +152 -0
  111. package/harness-ledger/docs/FORMATS.md +114 -0
  112. package/harness-ledger/docs/METHOD.md +133 -0
  113. package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
  114. package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
  115. package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
  116. package/harness-ledger/package.json +19 -0
  117. package/harness-ledger/src/demo.mjs +115 -0
  118. package/harness-ledger/src/economics.mjs +184 -0
  119. package/harness-ledger/src/gpu.mjs +80 -0
  120. package/harness-ledger/src/html.mjs +63 -0
  121. package/harness-ledger/src/importers.mjs +247 -0
  122. package/harness-ledger/src/ledger.mjs +128 -0
  123. package/harness-ledger/src/opencost.mjs +55 -0
  124. package/harness-ledger/src/outcomes.mjs +67 -0
  125. package/harness-ledger/src/prices.mjs +75 -0
  126. package/harness-ledger/src/record.mjs +52 -0
  127. package/harness-ledger/src/waste.mjs +136 -0
  128. package/harness-ledger/tools/harness-ledger.mjs +199 -0
  129. package/harness-ledger/tools/validate-economics.mjs +69 -0
  130. package/harness-ledger/tools/validate-swebench.mjs +57 -0
  131. package/harness-ledger/tools/validate-tracelab.mjs +74 -0
  132. package/hybrid-tracing/package.json +4 -3
  133. package/hybrid-tracing/tools/fix-skew.mjs +1 -1
  134. package/inference-sizer/README.md +5 -1
  135. package/inference-sizer/build.mjs +1 -0
  136. package/inference-sizer/dist/index.html +299 -31
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/CATALOG.md +71 -0
  139. package/inference-sizer/docs/METHOD.md +1 -1
  140. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  141. package/inference-sizer/package.json +4 -3
  142. package/inference-sizer/src/accelerators.js +194 -0
  143. package/inference-sizer/src/catalog.js +55 -22
  144. package/inference-sizer/src/fit-ui.js +1 -1
  145. package/inference-sizer/src/index.src.html +3 -0
  146. package/inference-sizer/src/model.js +45 -7
  147. package/inference-sizer/src/ui.js +1 -1
  148. package/inference-sizer/tools/validate-agentx.mjs +116 -0
  149. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  150. package/mcp/README.md +6 -1
  151. package/mcp/server.mjs +34 -0
  152. package/package.json +10 -6
  153. package/schemas/README.md +3 -0
  154. package/schemas/aiinfra.report.schema.json +474 -0
  155. package/schemas/commands.mjs +14 -0
  156. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  157. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  158. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  159. package/schemas/harness-ledger.economics.schema.json +567 -0
  160. package/schemas/sizer.list.schema.json +15 -2
@@ -0,0 +1,122 @@
1
+ // fleetops CLI: server (see ../fleetops.mjs for the entry point and dispatch)
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import * as Ingest from '../../src/ingest.mjs';
5
+ import * as Sec from '../../src/security.mjs';
6
+ import * as Pull from '../../src/pull.mjs';
7
+ import * as Agent from '../../src/agent.mjs';
8
+ import * as Bundle from '../../src/bundle.mjs';
9
+ import * as LiveView from '../../src/live.mjs';
10
+ import { J, OUT, say, read, time, hdrs, lokiQueries, dur } from './common.mjs';
11
+ import { importBundle } from './data.mjs';
12
+
13
+ export function tokenCmd(cmd, o) {
14
+ const file = o.tokens && o.tokens !== true ? o.tokens : null;
15
+ if (!file) throw new Error('--tokens FILE');
16
+ if (cmd === 'create') {
17
+ if (!o.name || o.name === true) throw new Error('--name NAME');
18
+ const roles = String(o.roles && o.roles !== true ? o.roles : 'read').split(',');
19
+ const list = k => (o[k] && o[k] !== true ? String(o[k]).split(',') : undefined);
20
+ const scoped = ['namespaces', 'owners', 'pools', 'clusters'].some(k => list(k)) || o.infra;
21
+ const tenant = scoped ? Object.fromEntries([...['namespaces', 'owners', 'pools', 'clusters'].map(k => [k, list(k)]).filter(([, v]) => v), ...(o.infra ? [['infra', true]] : [])]) : '*';
22
+ const { token, entry } = Sec.addToken(file, { name: o.name, roles, tenant });
23
+ console.log(`token for ${entry.name} (${roles.join(', ')}; ${tenant === '*' ? 'all tenants' : JSON.stringify(tenant)}):\n${token}\nOnly its SHA-256 is stored in ${file}; this is the only time it is shown.`);
24
+ return;
25
+ }
26
+ if (cmd === 'list') { for (const t of Sec.loadTokens(file)) console.log(`${t.name.padEnd(20)} ${t.roles.join(',').padEnd(18)} ${t.tenant === '*' ? '*' : JSON.stringify(t.tenant)}`); return; }
27
+ throw new Error('token create|list --tokens FILE');
28
+ }
29
+
30
+ // ---------- live agent ----------
31
+ export function agentOpts(store, o) {
32
+ const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), json = f => JSON.parse(read(f));
33
+ const agent = Object.assign({}, opt('agent-config') ? json(opt('agent-config')) : {});
34
+ if (opt('interval')) agent.intervalS = +opt('interval');
35
+ if (opt('window')) agent.windowS = dur(opt('window')) ?? +opt('window');
36
+ if (opt('targets')) agent.targets = json(opt('targets'));
37
+ if (opt('min-failures')) agent.minFailures = +opt('min-failures');
38
+ if (opt('page-to')) agent.page = { to: opt('page-to'), key: opt('page-key') || process.env.PAGERDUTY_ROUTING_KEY || process.env.OPSGENIE_API_KEY, url: opt('page-url'), minSeverity: opt('page-min-severity') || 'sev2' };
39
+ const stateDir = opt('state') || path.join(store.dir, 'agent');
40
+ const ghConfig = opt('config') ? json(opt('config')) : undefined;
41
+ // pull from the fleet's own monitoring before each tick, from where the last pull stopped
42
+ let pulledTo = null;
43
+ const before = opt('prom') || opt('loki') ? async now => {
44
+ const from = pulledTo ?? now - (agent.deviceWindowS || Agent.AGENT_DEFAULTS.deviceWindowS);
45
+ if (opt('prom')) await Pull.pullPrometheus(store, opt('prom'), { from, to: now, step: opt('step') ? +opt('step') : 30, headers: hdrs(o) });
46
+ if (opt('loki')) await Pull.pullLoki(store, opt('loki'), lokiQueries(o), { from, to: now, headers: hdrs(o) });
47
+ pulledTo = now;
48
+ } : null;
49
+ return { stateDir, ghConfig, agent, live: !!o.live, before };
50
+ }
51
+ export function agentLine(r) {
52
+ const acts = r.executed.map(e => `${e.kind}:${e.outcome}`).join(', ');
53
+ return `${new Date(r.t * 1000).toISOString()} agent${r.paused ? ' (paused)' : ''}${r.devices ? ` · ${Object.entries(r.devices.states).map(([k, v]) => `${k} ${v}`).join(', ')}` : ''} · ${r.incidents.length} incident(s)${r.incidents.map(i => `\n ${i.id}: ${i.rule || 'no cause'} (${i.confidence}) → ${i.decision}${i.actions.length ? ' [' + i.actions.map(a => `${a.kind} ${a.mode}`).join(', ') + ']' : ''}`).join('')}${acts ? `\n ran: ${acts}` : ''}${r.verified.map(v => `\n verified ${v.id}: ${v.outcome}`).join('')}`;
54
+ }
55
+ export async function agentCmd(store, cmd, o) {
56
+ const ao = agentOpts(store, o), opt = k => (o[k] && o[k] !== true ? o[k] : undefined);
57
+ if (cmd === 'pause' || cmd === 'resume') { if (!opt('by')) throw new Error(`agent ${cmd} --by NAME`); Agent.setPaused(ao.stateDir, cmd === 'pause', opt('by')); if (J) OUT.paused = cmd === 'pause'; else say(`agent ${cmd === 'pause' ? 'paused' : 'resumed'} by ${opt('by')}`); return; }
58
+ if (cmd === 'status') {
59
+ const v = LiveView.liveView(store, ao.stateDir, { agent: ao.agent, ghConfig: ao.ghConfig });
60
+ if (J) { OUT.status = { agent: v.agent, fleet: v.fleet.states, incidents: v.incidents, waiting: v.actions.open.filter(a => a.status === 'proposed') }; return; }
61
+ say(`agent ${v.agent.paused ? 'PAUSED' : v.agent.lastTick ? `last ran ${new Date(v.agent.lastTick * 1000).toISOString()}` : 'has not run'}${v.agent.live ? ' (live)' : ' (dry run)'} · autonomous actions in the last hour ${v.agent.autoLastHour}/${v.agent.autoLimit}`);
62
+ say(`GPUs: ${Object.entries(v.fleet.states).map(([k, n]) => `${k} ${n}`).join(', ') || 'no telemetry'}`);
63
+ for (const i of v.incidents) say(` ${i.severity} ${i.status.padEnd(12)} ${i.id}: ${i.title || 'no cause'} → ${i.decision || '–'}${i.verified ? ` (${i.verified.outcome})` : ''}`);
64
+ for (const a of v.actions.open.filter(a => a.status === 'proposed')) say(` waiting: ${a.id} ${a.reason.slice(0, 140)}`);
65
+ return;
66
+ }
67
+ if (cmd === 'log') { const d = Agent.decisions(ao.stateDir, o.limit ? +o.limit : 50); if (J) { OUT.log = d; return; } for (const e of d.reverse()) say(`${new Date(e.t * 1000).toISOString()} ${e.decision}${e.incident ? ' ' + e.incident : ''}${e.action ? ' ' + e.action : ''}${e.outcome ? ' → ' + e.outcome : ''}${e.title ? ': ' + e.title : ''}${e.note ? ': ' + e.note : ''}`); return; }
68
+ if (cmd === 'approve' || cmd === 'reject') {
69
+ const { Store: Q } = await import('../../../gpu-health/src/actions.mjs');
70
+ const id = o._[2]; if (!id || !opt('by')) throw new Error(`agent ${cmd} ID --by NAME`);
71
+ const q = new Q(ao.stateDir), a = cmd === 'approve' ? q.approve(id, opt('by')) : q.reject(id, opt('by'), opt('reason') || '');
72
+ fs.appendFileSync(path.join(ao.stateDir, 'agent.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), decision: cmd === 'approve' ? 'approved' : 'rejected', action: a.id, kind: a.kind, by: opt('by'), incident: a.incident }) + '\n');
73
+ if (J) OUT[cmd + 'd'] = a; else say(`${a.id} ${a.status} by ${opt('by')}; it runs on the agent's next tick`);
74
+ return;
75
+ }
76
+ if (cmd && cmd !== 'run') throw new Error(`unknown: agent ${cmd}`);
77
+ if (o.once) {
78
+ if (ao.before) await ao.before(Math.floor(Date.now() / 1000));
79
+ const r = await Agent.tick(store, Object.assign({}, ao, { now: o.now && o.now !== true ? time(o.now) : undefined }));
80
+ if (J) { OUT.tick = r; return; }
81
+ say(agentLine(r)); return;
82
+ }
83
+ if (o.live) console.log('note: --live runs actions only when the gpu-health policy has dryRun: false (--config)');
84
+ Agent.start(store, ao, { onTick: r => console.log(agentLine(r)), before: ao.before });
85
+ const stop = () => { if (store.close) store.close(); process.exit(0); };
86
+ process.on('SIGINT', stop); process.on('SIGTERM', stop);
87
+ await new Promise(() => {});
88
+ }
89
+
90
+ export async function serve(store, o) {
91
+ const port = o.port ? +o.port : 9400, host = o.host && o.host !== true ? o.host : '127.0.0.1';
92
+ const tokens = o.tokens && o.tokens !== true ? Sec.loadTokens(o.tokens) : null;
93
+ // listening beyond this machine without tokens would expose every tenant's data: refuse unless asked for explicitly
94
+ if (!tokens && !['127.0.0.1', 'localhost', '::1'].includes(host) && !o['no-auth']) throw new Error(`--host ${host} needs --tokens FILE (or --no-auth to run open on a trusted network)`);
95
+ const pipe = new Ingest.Pipeline(store, { maxQueue: o['max-queue'] ? +o['max-queue'] : 200000, flushMs: o['flush-ms'] ? +o['flush-ms'] : 1000 }).start();
96
+ let extra = null, page = null, agentRun = null;
97
+ // POST /v1/bundle (role ingest): a trace bundle, imported as `data import bundle` would
98
+ const bundleRoute = async (req, res, who, send) => {
99
+ if (req.method !== 'POST' || req.url.split('?')[0] !== '/v1/bundle') return false;
100
+ if (!Sec.can(who, 'ingest')) { send(res, 403, 'needs the ingest role\n'); return true; }
101
+ const chunks = []; let n = 0;
102
+ for await (const c of req) { n += c.length; if (n > Bundle.MAX_FILE) { send(res, 413, 'bundle too large: import it with fleetops data import bundle\n'); return true; } chunks.push(c); }
103
+ const f = path.join(fs.mkdtempSync(path.join((await import('node:os')).tmpdir(), 'fleetops-up-')), 'bundle.tgz');
104
+ try { fs.writeFileSync(f, Buffer.concat(chunks)); const r = await importBundle(store, f, {}); send(res, 200, JSON.stringify({ totals: r.totals, files: r.files.map(x => ({ path: x.path, source: x.source, error: x.error, skipped: x.skipped })) }), 'application/json'); }
105
+ catch (e) { send(res, 400, `${e.message}\n`); }
106
+ finally { fs.rmSync(path.dirname(f), { recursive: true, force: true }); }
107
+ return true;
108
+ };
109
+ extra = bundleRoute;
110
+ if (o.agent) {
111
+ const ao = agentOpts(store, o);
112
+ const live = LiveView.liveRoutes({ store, stateDir: ao.stateDir, agent: ao.agent, ghConfig: ao.ghConfig, audit: Sec.auditor(store.dir) }); page = LiveView.LIVE_HTML;
113
+ extra = async (req, res, who, send) => (await bundleRoute(req, res, who, send)) || live(req, res, who, send);
114
+ agentRun = Agent.start(store, ao, { onTick: r => console.log(agentLine(r)), before: ao.before });
115
+ }
116
+ const srv = Ingest.server(pipe, { site: o.site && o.site !== true ? o.site : undefined, tokens, audit: Sec.auditor(store.dir), extra, page });
117
+ await new Promise(r => srv.listen(port, host, r));
118
+ console.log(`fleetops on http://${host}:${port} store ${store.dir} ${tokens ? `${tokens.length} token(s)` : 'open (no tokens)'}${process.env.FLEETOPS_EGRESS_ALLOW != null ? ` egress: ${process.env.FLEETOPS_EGRESS_ALLOW || 'none'}` : ''}\n POST /api/v1/write /v1/metrics /v1/logs /v1/traces /v1/bundle GET /api/summary /api/query /api/series /api/incidents /api/diagnose /metrics /healthz${o.agent ? `\n agent every ${agentOpts(store, o).agent.intervalS ?? Agent.AGENT_DEFAULTS.intervalS} s${o.live ? ' (live: still needs policy.dryRun false)' : ' (dry run)'}; dashboard http://${host}:${port}/live` : ''}`);
119
+ const stop = () => { if (agentRun) agentRun.stop(); srv.close(); pipe.stop(); if (store.close) store.close(); process.exit(0); };
120
+ process.on('SIGINT', stop); process.on('SIGTERM', stop);
121
+ await new Promise(() => {});
122
+ }
@@ -0,0 +1,95 @@
1
+ // fleetops CLI: serving (see ../fleetops.mjs for the entry point and dispatch)
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import * as Serving from '../../src/serving.mjs';
5
+ import { createRequire } from 'node:module';
6
+ import { J, OUT, say, read, time } from './common.mjs';
7
+
8
+ export async function servingCmd(store, cmd, o) {
9
+ const opt = k => (o[k] != null && o[k] !== true ? o[k] : undefined), num = k => (opt(k) != null ? +opt(k) : undefined);
10
+ const f1 = v => (v == null ? '–' : v >= 100 ? Math.round(v).toLocaleString('en-US') : v.toFixed(v >= 10 ? 1 : 2));
11
+ if (cmd === 'models') { const ms = Serving.models(); if (J) { OUT.models = ms; return; } for (const m of ms) say(`${m.id.padEnd(18)} ${String(m.params).padStart(7)}B${m.active !== m.params ? ` (${m.active}B active)` : ''} ctx ${m.maxCtx} ${m.hf || ''}`); return; }
12
+ if (cmd === 'gpus') { const gs = Serving.gpus(); if (J) { OUT.gpus = gs; return; } for (const g of gs) say(`${g.id.padEnd(12)} ${g.label} · ${g.hbmGB} GB · ${g.perNode} per node${g.price ? ` · $${g.price}/GPU-h` : ''}`); return; }
13
+ const FIT = createRequire(import.meta.url)('../../../inference-sizer/src/fit.js');
14
+ // workload: measured from a pool in the store, or given
15
+ let wl = { isl: num('isl') || 2000, osl: num('osl') || 400, islP99: num('isl-p99'), oslP99: num('osl-p99'), rate: num('rate') };
16
+ if (opt('from-pool')) {
17
+ const to = Math.floor(Date.now() / 1000), m = Serving.workloadFromStore(store, opt('from-pool'), { from: time(opt('from')) ?? to - 7 * 86400, to: time(opt('to')) ?? to });
18
+ if (!m) throw new Error(`fewer than 50 requests for pool ${opt('from-pool')} in the store (import request logs first)`);
19
+ wl = Object.assign(m, { rate: num('rate') ?? m.rate });
20
+ say(`workload ${m.source}: ISL ${Math.round(m.isl)} (p99 ${Math.round(m.islP99)}), OSL ${Math.round(m.osl)} (p99 ${Math.round(m.oslP99)}), p99 load ${m.rate.toFixed(2)} req/s`);
21
+ }
22
+ const tg = { ttftS: num('ttft') || 2, tpotS: num('tpot') || 0.05 };
23
+ const hw = { gpu: opt('gpu'), nodes: num('nodes'), gpus: num('gpus'), gpusPerNode: num('gpus-per-node') };
24
+ if (cmd === 'fit') {
25
+ if (!hw.gpu || (hw.nodes == null && hw.gpus == null)) throw new Error('fleetops serving fit --gpu G --nodes N (or --gpus N)');
26
+ if (hw.nodes == null) delete hw.nodes;
27
+ const r = FIT.fitModels(hw, wl, tg, { rank: opt('rank'), prompt: !!o.prompt });
28
+ if (J) { OUT.fit = r; return; }
29
+ say(`${hw.nodes != null ? `${hw.nodes} node(s)` : `${hw.gpus} GPUs`} of ${hw.gpu}; ISL ${Math.round(wl.isl)} / OSL ${Math.round(wl.osl)} tokens; TTFT ≤ ${tg.ttftS}s, TPOT ≤ ${tg.tpotS * 1000}ms${wl.rate ? `; needs ${wl.rate} req/s` : ''}`);
30
+ say(`ranked by ${r.rank === 'largest' ? 'size among the models that carry the load (size is a proxy for capability, not a quality score)' : 'requests per second'}\n`);
31
+ say(`${'model'.padEnd(18)} ${'params'.padStart(8)} ${'req/s'.padStart(8)} ${'edge'.padStart(8)} ${'out tok/s'.padStart(10)} ${'$/1M out'.padStart(8)} layout`);
32
+ for (const x of r.rows) {
33
+ const p = x.production, L = p.layout;
34
+ say(`${(r.need && x.meetsRate ? '✓ ' : r.need ? ' ' : '') + x.model.padEnd(r.need ? 16 : 18)} ${(x.params + 'B').padStart(8)} ${f1(p.rate).padStart(8)} ${f1(x.edge.rate).padStart(8)} ${f1(p.outTokensPerS).padStart(10)} ${(p.dollarsPerMOut ? '$' + p.dollarsPerMOut.toFixed(2) : '–').padStart(8)} ${L ? `${L.mode === 'agg' ? `${L.instances} × ${L.label}` : `P ${L.prefill.instances}×${L.prefill.label} / D ${L.decode.instances}×${L.decode.label}`}` : (p.why || '')}`);
35
+ }
36
+ say(`\nreq/s: production (15% headroom, an N+1 spare, 10% under the targets); edge: none of those. Spec-sheet efficiencies unless calibrated (fleetops calibrate).`);
37
+ return;
38
+ }
39
+ if (cmd === 'capacity') {
40
+ if (!opt('model') || !hw.gpu || (hw.nodes == null && hw.gpus == null)) throw new Error('fleetops serving capacity --model M --gpu G --nodes N (or --gpus N)');
41
+ if (hw.nodes == null) delete hw.nodes;
42
+ const c = FIT.capacity(opt('model'), hw, wl, tg, {});
43
+ if (J) { OUT.capacity = Object.assign({}, c, { production: Object.assign({}, c.production, { usersAt: undefined }) }); return; }
44
+ const p = c.production, L = p.layout;
45
+ say(`${c.name} on ${c.gpus} ${c.gpu}; ISL ${Math.round(c.wl.isl)} / OSL ${Math.round(c.wl.osl)}; TTFT ≤ ${c.tg.ttftS}s, TPOT ≤ ${c.tg.tpotS * 1000}ms`);
46
+ if (!p.rate) { say(` doesn't fit: ${p.why}${c.edge.rate ? ` (without headroom and the spare it carries ${f1(c.edge.rate)} req/s)` : ''}`); return; }
47
+ say(` max load: ${f1(p.rate)} req/s in production (${f1(c.edge.rate)} at the edge), ${f1(p.outTokensPerS)} output tokens/s`);
48
+ say(` users: ~${f1(p.usersAt(20))} daily active users at 20 requests each, if the load were flat (peaks need more)`);
49
+ say(` concurrency: ${L.concurrency} sequences in flight (${L.instances} instance(s) × ${Math.round(L.concurrency / L.instances)})`);
50
+ say(` layout: ${L.mode === 'agg' ? `${L.instances} × ${L.label} (${L.gpusPerInstance} GPU(s) each)` : `prefill ${L.prefill.instances}×${L.prefill.label}, decode ${L.decode.instances}×${L.decode.label}`}, ${p.nodes} node(s) with the spare`);
51
+ say(` longest prompt: ${c.maxPrompt ? `${c.maxPrompt.toLocaleString('en-US')} tokens at light load (model maximum ${c.modelMaxCtx.toLocaleString('en-US')})` : 'none fits'}`);
52
+ if (p.dollarsPerMOut) say(` cost: $${p.dollarsPerMOut.toFixed(2)} per million output tokens at that load (catalog price)`);
53
+ say(` ${p.reason}`);
54
+ return;
55
+ }
56
+ if (cmd === 'delete') {
57
+ const name = o._[2], ns = opt('namespace') || 'serving', f = path.join(store.dir, 'serving', `${name}.yaml`);
58
+ if (!name) throw new Error('fleetops serving delete NAME [--namespace serving] [--apply]');
59
+ const argv = fs.existsSync(f) ? ['delete', '-f', f, '--ignore-not-found'] : ['-n', ns, 'delete', 'deployment,leaderworkerset,service,scaledobject', '-l', `app=${name}`, '--ignore-not-found'];
60
+ const routerValues = path.join(store.dir, 'serving', `${name}.router.values.yaml`), helmArgv = fs.existsSync(routerValues) ? ['uninstall', name, '-n', ns] : null;
61
+ if (!o.apply) { say(`would run: kubectl ${argv.join(' ')}${helmArgv ? `\n helm ${helmArgv.join(' ')} (the llm-d router)` : ''}\nadd --apply to delete`); return; }
62
+ const r = Serving.kubectl(argv); if (r.code !== 0) throw new Error(r.err.trim());
63
+ if (helmArgv) { const h = Serving.helmRun(helmArgv); if (h.code !== 0) say(`helm uninstall: ${h.err.trim()}`); else fs.rmSync(routerValues); }
64
+ for (const reg of ['pools.json', 'targets.json']) { const p = path.join(store.dir, 'serving', reg); if (fs.existsSync(p)) { const x = JSON.parse(read(p)); delete x[name]; fs.writeFileSync(p, JSON.stringify(x, null, 1)); } }
65
+ say(r.out.trim()); return;
66
+ }
67
+ if (cmd !== 'deploy') throw new Error(`unknown: serving ${cmd || ''} (models, gpus, fit, capacity, deploy, delete)`);
68
+ const d = Serving.planDeployment({ model: opt('model'), gpu: opt('gpu'), nodes: hw.nodes, gpus: hw.gpus, gpusPerNode: hw.gpusPerNode, rate: wl.rate, isl: wl.isl, osl: wl.osl, islP99: wl.islP99, oslP99: wl.oslP99, ttftS: tg.ttftS, tpotS: tg.tpotS,
69
+ name: opt('name'), namespace: opt('namespace'), image: opt('image'), hf: opt('hf'), hfSecret: opt('hf-secret'), cachePvc: opt('cache-pvc'), maxModelLen: num('max-model-len'), autoscale: !!o.autoscale, prometheus: opt('prometheus'),
70
+ minReplicas: num('min-replicas'), maxReplicas: num('max-replicas'), createNamespace: !!o['create-namespace'], weights: opt('weights'), kvDtype: opt('kv-dtype'), mode: opt('mode'), routerVersion: opt('router-version'), sidecarImage: opt('sidecar-image'), gaieVersion: opt('gaie-version') });
71
+ if (opt('out')) { fs.writeFileSync(opt('out'), d.yaml); if (d.router) fs.writeFileSync(opt('out').replace(/(\.ya?ml)?$/, '.router.values.yaml'), d.router.yaml); }
72
+ if (!J) {
73
+ say(`${d.name}: ${d.model} (${d.hf}) on ${d.gpu}, ${d.sized.basis}`);
74
+ if (d.mode === 'disagg') say(` disaggregated on llm-d: prefill ${d.layout.prefill.instances} × TP${d.layout.prefill.tp}, decode ${d.layout.decode.instances} × TP${d.layout.decode.tp} (max-num-seqs ${d.layout.decode.maxNumSeqs}) = ${d.layout.gpus} GPUs; max-model-len ${d.layout.maxModelLen}; TTFT ≤ ${d.targets.ttftS}s, TPOT ≤ ${d.targets.tpotS * 1000}ms\n router: helm upgrade --install ${d.router.release} ${d.router.chart} --version ${d.router.version} -n ${d.namespace} -f <router values>`);
75
+ else say(` ${d.layout.instances} × TP${d.multiNode ? `${d.layout.gpusPerInstance / d.nodesPerInstance} × PP${d.nodesPerInstance} (LeaderWorkerSet, ${d.nodesPerInstance} nodes each)` : d.layout.tp + (d.layout.pp > 1 ? ` × PP${d.layout.pp}` : '')} = ${d.layout.gpus} GPUs; max-num-seqs ${d.layout.maxNumSeqs}, max-model-len ${d.layout.maxModelLen}; TTFT ≤ ${d.targets.ttftS}s, TPOT ≤ ${d.targets.tpotS * 1000}ms`);
76
+ for (const n of d.notes) say(` note: ${n}`);
77
+ if (!o.apply && !opt('out')) say(`\n${d.yaml}${d.router ? `\n# llm-d router values (${d.router.chart})\n${d.router.yaml}` : ''}`);
78
+ else if (opt('out')) say(` wrote ${opt('out')}${d.router ? ` and ${opt('out').replace(/(\.ya?ml)?$/, '.router.values.yaml')}` : ''}`);
79
+ if (d.prereqs && !o.apply) say(` prerequisites (once per cluster; install-serving.sh --install-prereqs runs them):\n${d.prereqs.map(c => ` ${c.join(' ')}`).join('\n')}`);
80
+ }
81
+ const log = (s, x) => {
82
+ if (J) return;
83
+ if (s === 'preflight') for (const c of x.checks) say(` ${c.pass ? 'ok ' : 'FAIL'} ${c.name}: ${c.detail}`);
84
+ else if (s === 'apply') say(` applied${x.out ? `:\n ${x.out.replace(/\n/g, '\n ')}` : ''}`);
85
+ else if (s === 'router') say(` llm-d router ${x.code === 0 ? 'installed' : 'failed'}`);
86
+ else if (s === 'wait') say(` ${x.code === 0 ? 'ready' : 'not ready'}${x.out && x.out.includes('pods') ? `: ${x.out}` : ''}`);
87
+ else if (s === 'smoke') say(x.ok ? ` smoke test: ${x.models.join(', ')} answered "${x.text}" (first response ${x.firstByteMs} ms)` : ` smoke test failed: ${x.error}`);
88
+ else if (s === 'register') say(x.pools ? ` registered: ${x.pools} (tune and the agent see the pool)` : '');
89
+ };
90
+ const r = await Serving.deploy(d, { apply: !!o.apply, endpoint: opt('endpoint'), waitS: num('wait') || 2400, registerDir: path.join(store.dir, 'serving'), log });
91
+ if (J) { OUT.deploy = Object.assign({ plan: Object.assign({}, d, { docs: undefined }) }, r); return; }
92
+ if (r.dryRun) say(`\ndry run: nothing applied. Add --apply to deploy${r.steps[0].ready ? '' : ' (fix the failed checks first)'}.`);
93
+ if (r.error) throw new Error(r.error);
94
+ if (r.ok) say(`\n${d.name} is serving: kubectl -n ${d.namespace} port-forward svc/${d.service || d.name} 8000:${d.servicePort || 8000}, then the OpenAI API at http://127.0.0.1:8000/v1 (model "${d.model}")`);
95
+ }
@@ -0,0 +1,204 @@
1
+ // fleetops CLI: shadow (see ../fleetops.mjs for the entry point and dispatch)
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import * as Sec from '../../src/security.mjs';
5
+ import * as Shadow from '../../src/shadow.mjs';
6
+ import * as Replay from '../../src/shadow-replay.mjs';
7
+ import * as SProm from '../../src/shadow-prom.mjs';
8
+ import * as Gate from '../../src/shadow-gate.mjs';
9
+ import * as Canary from '../../src/shadow-canary.mjs';
10
+ import { J, OUT, say, read, time, fmt, pctS } from './common.mjs';
11
+
12
+ // ---------- shadow upgrades ----------
13
+ export function selector(sel) {
14
+ if (!sel) return () => true;
15
+ const parts = String(sel).split(',').map(x => x.trim()).filter(Boolean).map(x => { const m = x.match(/^([\w.]+)(=|~)(.*)$/); if (!m) throw new Error(`selector "${x}": use field=value or field~regex`); return m[2] === '=' ? r => String(r[m[1]]) === m[3] : (re => r => re.test(String(r[m[1]] ?? '')))(new RegExp(m[3])); });
16
+ return r => parts.every(f => f(r));
17
+ }
18
+ export function shadowText(r) {
19
+ const L = [`${r.decision.toUpperCase()}: ${r.why}`, `${r.requests.baseline} baseline and ${r.requests.candidate} candidate requests, ${r.paired ? 'paired (the same requests on both)' : 'compared at matched load'}`, ''];
20
+ L.push(' metric candidate vs baseline (95% CI) verdict naive (no load matching)');
21
+ for (const k of ['ttft', 'tpot', 'e2e']) { const m = r.metrics[k]; if (!m || m.verdict === 'no data') { L.push(` ${k.padEnd(8)} no data`); continue; }
22
+ L.push(` ${k.padEnd(8)} ${pctS(m.effect).padStart(7)} (${pctS(m.lo)} to ${pctS(m.hi)})`.padEnd(51) + ` ${m.verdict.padEnd(14)} ${pctS(m.naive)}${m.coverage != null && m.coverage < 0.8 ? ` only ${(100 * m.coverage).toFixed(0)}% of baseline requests had matching load` : ''}${m.more ? ` ~${m.more} more per arm to settle` : ''}`); }
23
+ if (r.metrics.errorRate) L.push(` errors ${(100 * r.metrics.errorRate.baseline).toFixed(2)}% → ${(100 * r.metrics.errorRate.candidate).toFixed(2)}%`.padEnd(52) + r.metrics.errorRate.verdict);
24
+ if (r.metrics.tokPerGpuS) L.push(` tok/s per GPU ${r.metrics.tokPerGpuS.baseline.toFixed(0)} → ${r.metrics.tokPerGpuS.candidate.toFixed(0)} (${pctS(r.metrics.tokPerGpuS.effect)}; ${r.metrics.tokPerGpuS.note})`);
25
+ if (r.metrics.costPerMTok) L.push(` $ per M output tokens ${r.metrics.costPerMTok.baseline.toFixed(2)} → ${r.metrics.costPerMTok.candidate.toFixed(2)} (${pctS(r.metrics.costPerMTok.effect)}) ${r.metrics.costPerMTok.verdict}`);
26
+ if (r.answers) L.push(` answers ${r.answers.identical}/${r.answers.prompts} identical under greedy decoding; log-prob drift ${r.answers.meanAbsLogprobDiff != null ? r.answers.meanAbsLogprobDiff.toFixed(3) : '–'} ${r.answers.verdict}`);
27
+ if (r.prediction) L.push('', ` prediction ${r.prediction.holds ? 'holds' : 'is off: recalibrate'}: ` + r.prediction.rows.map(x => `${x.metric} predicted ${pctS(x.predicted)}, measured ${pctS(x.measured)}`).join('; '));
28
+ if (r.infra) L.push('', ' infra: ' + Object.entries(r.infra).map(([k, v]) => v.effect != null ? `${k} ${pctS(v.effect)}` : `${k} ${v.baseline} → ${v.candidate}`).join(', '));
29
+ return L.join('\n');
30
+ }
31
+ export async function shadowCmd(store, cmd, rest, o) {
32
+ const opt = k => (o[k] != null && o[k] !== true ? o[k] : undefined), json = k => (opt(k) ? JSON.parse(read(opt(k))) : undefined), num = k => (opt(k) != null ? +opt(k) : undefined);
33
+ const from = time(opt('from')), to = time(opt('to'));
34
+ const requests = sel => store.query('request', { from, to, where: selector(sel) });
35
+ const dir = path.join(store.dir, 'shadow'); fs.mkdirSync(dir, { recursive: true });
36
+ // the sizer calibration shadow verdicts keep: read by plan, the Inference Sizer (--calibration) and harness-ledger economics
37
+ const calFile = () => opt('calibration') || path.join(store.dir, 'calibration', 'sizer.json');
38
+ const calProfile = () => (fs.existsSync(calFile()) ? JSON.parse(read(calFile())) : null);
39
+ const learn = (r, planObj, label) => {
40
+ const out = [];
41
+ if (planObj && !o['no-recalibrate']) {
42
+ const rc = Shadow.recalibrate(planObj, r.metrics);
43
+ if (rc && rc.changed) {
44
+ const f = calFile(); fs.mkdirSync(path.dirname(f), { recursive: true });
45
+ const t = Math.floor(Date.now() / 1000), prof = Shadow.mergeProfile(calProfile(), rc, { fitOn: `shadow ${label}`, t });
46
+ fs.writeFileSync(f, JSON.stringify(prof, null, 1) + '\n'); store.append('calibration', [{ t, target: `sizer:${rc.key}`, tool: 'inference-sizer', eff: rc.eff, before: rc.before, rows: rc.rows, source: 'fleetops-shadow', fitOn: label }]);
47
+ out.push(`recalibrated ${rc.key} → ${f}: ` + rc.rows.filter(x => x.changed).map(x => `${x.metric} predicted ${pctS(x.predicted)}, measured ${pctS(x.measured)}`).join('; ') + ` (${Shadow.EFF_KEYS.filter(k => rc.before[k] !== rc.eff[k]).map(k => `${k} ${rc.before[k]}→${rc.eff[k]}`).join(', ')})`);
48
+ r.recalibrated = rc;
49
+ } else if (rc) for (const x of rc.rows.filter(y => y.note)) out.push(`${x.metric}: ${x.note}`);
50
+ }
51
+ // a promoted change's measured numbers go where planning and economics read them
52
+ if (r.decision === 'promote') {
53
+ const rec = { t: Math.floor(Date.now() / 1000), label, candidate: planObj && planObj.configs ? planObj.configs.candidate : null, effects: Object.fromEntries(['ttft', 'tpot', 'e2e', 'tokPerGpuS', 'costPerMTok'].filter(k => r.metrics[k] && Number.isFinite(r.metrics[k].effect)).map(k => [k, r.metrics[k].effect])),
54
+ tokPerGpuS: r.metrics.tokPerGpuS ? r.metrics.tokPerGpuS.candidate : null, calibration: r.recalibrated ? r.recalibrated.key : null };
55
+ fs.appendFileSync(path.join(dir, 'promoted.jsonl'), JSON.stringify(rec) + '\n'); out.push(`promoted: recorded in ${path.join(dir, 'promoted.jsonl')}${rec.calibration ? `; harness-ledger economics --calibration ${calFile()} uses it` : ''}`);
56
+ }
57
+ return out;
58
+ };
59
+ const readJsonl = f => read(f).split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
60
+ const traceRows = async f => { if (/\.json$/.test(f)) { const j = JSON.parse(read(f)); if (j.kind === 'fleetscope.agentic-profile') { const A = (await import('module')).createRequire(import.meta.url)('../../../fleetscope/src/agentic.js'); return A.synthesize(j, { sessionsPerHour: num('sessions-per-hour') || 600, horizonS: num('duration') || 600, seed: num('seed') || 1 }); } }
61
+ const { loadRows } = await import('../../../fleetscope/tools/agentic.mjs'); return (await loadRows(f)).rows; };
62
+ const arm = (name, url) => ({ name, url, model: opt('model'), apiKey: opt('api-key-env') ? process.env[opt('api-key-env')] : undefined });
63
+ if (cmd === 'demo') {
64
+ const d = Shadow.synth(); store.append('request', [...d.baseline, ...d.candidate]);
65
+ if (J) { OUT.demo = { baseline: d.baseline.length, candidate: d.candidate.length }; return; }
66
+ return say(`demo in ${store.dir}: ${d.baseline.length} baseline and ${d.candidate.length} candidate requests (variant field). The candidate is 8% slower at any load but got less than half the traffic.\ntry: fleetops shadow compare --baseline variant=baseline --candidate variant=candidate --store ${store.dir}`);
67
+ }
68
+ if (cmd === 'plan') {
69
+ const prof = calProfile(), b0 = json('baseline-config'), c0 = json('candidate-config'); if (!b0 || !c0) throw new Error('--baseline-config b.json --candidate-config c.json: { model, gpu, tp, gpus?, rate? } (Inference Sizer ids)');
70
+ const b = Shadow.applyCalibration(b0, prof), c = Shadow.applyCalibration(c0, prof);
71
+ const reqs = opt('trace') ? await traceRows(opt('trace')) : requests(opt('baseline'));
72
+ if (!reqs.length) throw new Error('no workload: give --trace FILE, or --baseline SEL with request records in the store');
73
+ const w = Shadow.workloadOf(reqs.map(r => Object.assign({ e2e: r.e2e ?? r.api ?? 0 }, r))), p = Shadow.plan({ baseline: b, candidate: c, workload: w, delta: num('effect') ?? 0.03, rps: num('rps') });
74
+ if (opt('out')) fs.writeFileSync(opt('out'), JSON.stringify(p, null, 1) + '\n');
75
+ if (J) { OUT.plan = p; return; }
76
+ if (b.calibrated || c.calibrated) say(`calibrated from ${calFile()}: ${[b, c].filter(x => x.calibrated).map(x => `${x.gpu}|${x.model}`).join(', ')}`);
77
+ return say(`predicted (candidate vs baseline at median prompt ${Math.round(w.isl)}, output ${Math.round(w.osl)}, cache hit ${w.prefixHit.toFixed(0)}%, ${w.inflight} in flight):\n TTFT ${pctS(p.predicted.ttft)}, TPOT ${pctS(p.predicted.tpot)}, tokens/s per GPU ${pctS(p.predicted.tokPerGpuS)}${p.predicted.costPerMTok != null ? `, $ per M tokens ${pctS(p.predicted.costPerMTok)}` : ''}\ntest: ${p.test.requestsPerArm} requests per arm to see a ${(100 * p.test.delta).toFixed(0)}% effect${p.test.paired ? ' (paired replay)' : ''}${p.test.seconds ? `, about ${Math.ceil(p.test.seconds / 60)} min at ${opt('rps')} req/s` : ''}\n${p.note}${opt('out') ? `\n→ ${opt('out')}` : ''}`);
78
+ }
79
+ if (cmd === 'replay') {
80
+ if (!opt('trace') || !opt('baseline') || !opt('candidate')) throw new Error('--trace FILE|profile.json --baseline URL --candidate URL [--live]');
81
+ const reqs = Replay.requestsFrom(await traceRows(opt('trace')), { speed: num('speed') || 1, maxRequests: num('max-requests') ?? 1000, durationS: num('duration') ?? Infinity, maxIsl: num('max-isl') ?? Infinity, maxOsl: num('max-osl') ?? Infinity });
82
+ const arms = [arm('baseline', opt('baseline')), arm('candidate', opt('candidate'))];
83
+ const res = await Replay.run(reqs, arms, { live: !!o.live, maxInflight: num('max-inflight') || 64, model: opt('model'), exact: !o['no-exact-output'] });
84
+ if (res.dryRun) { if (J) { OUT.replay = res; return; } return say(`dry run: ${res.plan.requests} requests (${res.plan.sessions} sessions) over ${Math.round(res.plan.seconds)} s; ${res.plan.note}.\nAdd --live to send them.`); }
85
+ store.append('request', res.records, { source: 'shadow-replay' });
86
+ if (opt('out')) fs.writeFileSync(opt('out'), res.records.map(r => JSON.stringify(r)).join('\n') + '\n');
87
+ if (J) { OUT.replay = { requests: res.records.length, errors: res.records.filter(r => r.error).length }; return; }
88
+ return say(`${res.records.length} measurements (${res.records.filter(r => r.error).length} errors) in ${store.dir}${opt('out') ? ` and ${opt('out')}` : ''}\nnext: fleetops shadow compare --baseline variant=baseline,source=shadow-replay --candidate variant=candidate,source=shadow-replay --store ${store.dir}`);
89
+ }
90
+ if (cmd === 'answers') {
91
+ if (!opt('baseline') || !opt('candidate')) throw new Error('--baseline URL --candidate URL [--prompts FILE] [--live]');
92
+ const prompts = opt('prompts') ? read(opt('prompts')).split('\n').map(l => l.trim()).filter(Boolean).map(l => (l.startsWith('{') ? JSON.parse(l).prompt : l)) : Replay.PROMPTS;
93
+ const res = await Replay.answers([arm('baseline', opt('baseline')), arm('candidate', opt('candidate'))], { prompts, live: !!o.live, model: opt('model'), maxTokens: num('max-tokens') || 64 });
94
+ if (opt('out') && !res.dryRun) fs.writeFileSync(opt('out'), JSON.stringify(res, null, 1) + '\n');
95
+ if (J) { OUT.answers = res; return; }
96
+ return say(res.dryRun ? `dry run: ${res.note}. Add --live to send them.` : `${res.identical}/${res.prompts} identical; first divergence at token ${res.meanFirstDivergence ?? '–'} on average; log-prob drift ${res.meanAbsLogprobDiff != null ? res.meanAbsLogprobDiff.toFixed(4) : '–'}${opt('out') ? ` → ${opt('out')}` : ''}`);
97
+ }
98
+ if (cmd === 'compare') {
99
+ let base, cand;
100
+ if (opt('results')) { const rs = readJsonl(opt('results')); base = rs.filter(r => r.variant === 'baseline'); cand = rs.filter(r => r.variant === 'candidate'); }
101
+ else { if (!opt('baseline') || !opt('candidate')) throw new Error('--results FILE, or --baseline SEL --candidate SEL'); base = requests(opt('baseline')); cand = requests(opt('candidate')); }
102
+ if (!base.length || !cand.length) throw new Error(`no requests: ${base.length} baseline, ${cand.length} candidate`);
103
+ const plan = json('plan'), re = k => (opt(k) ? new RegExp(opt(k)) : null);
104
+ const r = Shadow.compare(base, cand, { gates: json('gates'), predicted: plan && plan.predicted, answers: json('answers'),
105
+ baseline: { gpus: num('baseline-gpus'), rate: num('baseline-rate') }, candidate: { gpus: num('candidate-gpus'), rate: num('candidate-rate') },
106
+ infra: opt('baseline-nodes') ? Shadow.infraSignals(store, { baselineNodes: re('baseline-nodes'), candidateNodes: re('candidate-nodes'), from, to }) : null });
107
+ fs.appendFileSync(path.join(dir, 'verdicts.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), baseline: opt('baseline') || opt('results'), candidate: opt('candidate') || opt('results'), decision: r.decision, why: r.why, metrics: r.metrics, ...(r.prediction ? { prediction: r.prediction } : {}) }) + '\n');
108
+ const learned = learn(r, plan, `${opt('baseline') || opt('results')} → ${opt('candidate') || ''}`);
109
+ if (J) { OUT.shadow = r; return; }
110
+ return say(shadowText(r) + (learned.length ? '\n\n' + learned.join('\n') : ''));
111
+ }
112
+ if (cmd === 'baseline') {
113
+ const bdir = path.join(dir, 'baselines'); fs.mkdirSync(bdir, { recursive: true });
114
+ if (rest[0] === 'list' || !rest[0]) { const xs = fs.readdirSync(bdir).filter(f => f.endsWith('.jsonl')).map(f => { const ls = readJsonl(path.join(bdir, f)); const b = ls[ls.length - 1]; return { name: b.name, saved: fmt(b.t), requests: b.requests, versions: ls.length }; }); if (J) { OUT.baselines = xs; return; } return say(xs.length ? xs.map(x => `${x.name} ${x.requests} requests, saved ${x.saved} (${x.versions} version${x.versions > 1 ? 's' : ''})`).join('\n') : 'no baselines yet: fleetops shadow baseline save --name NAME --select SEL'); }
115
+ if (rest[0] === 'save') { if (!opt('name') || !opt('select')) throw new Error('--name NAME --select SEL'); const rs = requests(opt('select')); if (!rs.length) throw new Error('no requests match'); const b = Shadow.makeBaseline(opt('name'), rs, { meta: { select: opt('select'), from, to } }); fs.appendFileSync(path.join(bdir, opt('name').replace(/[^\w.-]/g, '_') + '.jsonl'), JSON.stringify(b) + '\n'); if (J) { OUT.baseline = { name: b.name, requests: b.requests, sample: b.sample.length }; return; } return say(`saved baseline ${b.name}: ${b.sample.length} of ${b.requests} requests`); }
116
+ throw new Error('fleetops shadow baseline save --name NAME --select SEL | list');
117
+ }
118
+ if (cmd === 'watch') {
119
+ if (!opt('name') || !opt('select')) throw new Error('--name NAME --select SEL [--from T --to T]');
120
+ const f = path.join(dir, 'baselines', opt('name').replace(/[^\w.-]/g, '_') + '.jsonl'); if (!fs.existsSync(f)) throw new Error(`no baseline ${opt('name')}: fleetops shadow baseline save first`);
121
+ const ls = readJsonl(f), b = ls[ls.length - 1], cur = requests(opt('select')); if (!cur.length) throw new Error('no current requests match');
122
+ const r = Shadow.drift(b, cur), hist = path.join(dir, 'watch-' + opt('name').replace(/[^\w.-]/g, '_') + '.jsonl');
123
+ fs.appendFileSync(hist, JSON.stringify({ t: Math.floor(Date.now() / 1000), from, to, metrics: Object.fromEntries(Object.entries(r.metrics).map(([k, v]) => [k, v.effect])), drifted: r.drifted }) + '\n');
124
+ const past = readJsonl(hist).slice(-8);
125
+ if (J) { OUT.watch = Object.assign(r, { history: past }); return; }
126
+ return say(`${r.note} (${r.current} requests vs baseline ${b.name} of ${fmt(b.t)})\n` + ['ttft', 'tpot', 'e2e'].map(k => { const m = r.metrics[k]; return ` ${k.padEnd(5)} ${pctS(m.effect)} (${pctS(m.lo)} to ${pctS(m.hi)}) ${m.verdict}`; }).join('\n') + `\n last ${past.length} checks, TPOT: ${past.map(x => pctS(x.metrics.tpot)).join(' ')}`);
127
+ }
128
+ if (cmd === 'prom') {
129
+ let d, saved = null;
130
+ const promHeaders = () => (opt('prom-token-env') ? { authorization: `Bearer ${process.env[opt('prom-token-env')] || ''}` } : undefined);
131
+ if (o.demo) { const w = SProm.synthWindows(); d = { baseline: w.baseline, candidate: w.candidate, step: w.step }; }
132
+ else if (opt('file')) { saved = JSON.parse(read(opt('file'))); d = Object.assign({ step: saved.step }, SProm.fromSaved(saved)); }
133
+ else {
134
+ if (!opt('prom') || !opt('baseline') || !opt('candidate')) throw new Error("--prom URL --baseline 'matchers' --candidate 'matchers' (or --file saved.json, or --demo)");
135
+ const now = Math.floor(Date.now() / 1000), step = num('step') || 60, t1 = to ?? now, t0 = from ?? t1 - (num('lookback') || 3600);
136
+ saved = await SProm.fetchArms(opt('prom'), { select: opt('select'), baseline: opt('baseline'), candidate: opt('candidate'), from: t0, to: t1, baselineFrom: num('baseline-lookback') ? t1 - num('baseline-lookback') : t0, step, headers: promHeaders() });
137
+ d = saved;
138
+ if (opt('save')) { const { baseline: _b, candidate: _c, ...keep } = saved; fs.writeFileSync(opt('save'), JSON.stringify(keep) + '\n'); } // the series, not the windows derived from them
139
+ }
140
+ if (!d.baseline.length || !d.candidate.length) throw new Error(`no windows with requests: ${d.baseline.length} baseline, ${d.candidate.length} candidate (check the selectors and the time range)`);
141
+ const planObj = json('plan');
142
+ const r = SProm.compareWindows(d.baseline, d.candidate, { step: d.step, gates: json('gates'), predicted: planObj && planObj.predicted, baseline: { gpus: num('baseline-gpus'), rate: num('baseline-rate') }, candidate: { gpus: num('candidate-gpus'), rate: num('candidate-rate') } });
143
+ fs.appendFileSync(path.join(dir, 'verdicts.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), source: 'prometheus', baseline: (saved && saved.selectors && saved.selectors.baseline) || (o.demo ? 'demo' : opt('file')), candidate: (saved && saved.selectors && saved.selectors.candidate) || (o.demo ? 'demo' : opt('file')), decision: r.decision, why: r.why, metrics: r.metrics, ...(r.prediction ? { prediction: r.prediction } : {}) }) + '\n');
144
+ const learned = learn(r, planObj, `prometheus ${(saved && saved.selectors && saved.selectors.candidate) || (o.demo ? 'demo' : opt('file'))}`);
145
+ if (J) { OUT.shadow = r; return; }
146
+ const L = r.load, ld = x => `${x.windows} windows, ${x.requests} requests, ${x.concPerEngine.toFixed(1)} in flight per engine, prompt ${Math.round(x.isl || 0)}, cache hit ${x.hit != null && Number.isFinite(x.hit) ? (100 * x.hit).toFixed(0) + '%' : '–'}${Number.isFinite(x.ttftP95) ? `, TTFT p95 ${x.ttftP95.toFixed(2)} s (median window; shown, not judged)` : ''}`;
147
+ const text = shadowText(Object.assign({}, r, { paired: false })).split('\n');
148
+ text[1] = `baseline: ${ld(L.baseline)}\ncandidate: ${ld(L.candidate)}\neach canary window against the baseline at the same load (median of windows shown)`;
149
+ return say(text.join('\n').replace(/requests had matching load/g, 'canary traffic was within the baseline\'s load range').replace(/more per arm to settle/g, 'more minutes to settle') + (learned.length ? '\n\n' + learned.join('\n') : ''));
150
+ }
151
+ if (cmd === 'serve') {
152
+ if (!opt('prom')) throw new Error('--prom URL (the Prometheus that scrapes both versions)');
153
+ const port = num('port') || 9410, host = opt('host') || '127.0.0.1', tokens = opt('tokens') ? Sec.loadTokens(opt('tokens')) : null;
154
+ if (!tokens && !['127.0.0.1', 'localhost', '::1'].includes(host) && !o['no-auth']) throw new Error(`--host ${host} needs --tokens FILE (or --no-auth on a network only the rollout controller reaches: Flagger webhooks can't send a token)`);
155
+ const step = num('step') || 60, headers = opt('prom-token-env') ? { authorization: `Bearer ${process.env[opt('prom-token-env')] || ''}` } : undefined;
156
+ const defaults = { select: opt('select'), baseline: opt('baseline'), candidate: opt('candidate'), lookback: num('lookback') || 900, baselineLookback: num('baseline-lookback') || 21600 };
157
+ for (const k of Object.keys(defaults)) if (defaults[k] == null) delete defaults[k];
158
+ const evaluate = async p => {
159
+ const now = Math.floor(Date.now() / 1000), d = await SProm.fetchArms(opt('prom'), { select: p.select, baseline: p.baseline, candidate: p.candidate, from: now - p.lookback, to: now, baselineFrom: now - Math.max(p.lookback, p.baselineLookback), step, headers });
160
+ return SProm.compareWindows(d.baseline, d.candidate, { step, gates: json('gates') });
161
+ };
162
+ const logf = path.join(dir, 'gate.jsonl'), srv = Gate.gateServer(evaluate, { tokens, defaults, log: e => fs.appendFileSync(logf, JSON.stringify(e) + '\n') });
163
+ await new Promise(r => srv.listen(port, host, r));
164
+ console.log(`shadow judge on http://${host}:${port} prometheus ${opt('prom')} ${tokens ? `${tokens.length} token(s)` : 'open (no tokens)'}\n POST /verdict (Argo Rollouts web metric) POST /flagger/rollout POST /flagger/confirm-promotion GET /verdict?baseline=…&candidate=… GET /healthz\n canary window ${defaults.lookback} s, baseline history ${defaults.baselineLookback} s; decisions → ${logf}`);
165
+ const stop = () => { srv.close(); process.exit(0); }; process.on('SIGINT', stop); process.on('SIGTERM', stop);
166
+ return new Promise(() => {});
167
+ }
168
+ if (cmd === 'canary') {
169
+ const sub = rest[0], cdir = path.join(dir, 'canaries'); fs.mkdirSync(cdir, { recursive: true });
170
+ const nm = opt('name'); if (!nm) throw new Error('--name NAME');
171
+ const file = path.join(cdir, nm.replace(/[^\w.-]/g, '_') + '.json'), audit = e => fs.appendFileSync(file.replace(/\.json$/, '.audit.jsonl'), JSON.stringify(Object.assign({ t: Math.floor(Date.now() / 1000) }, e)) + '\n');
172
+ const load = () => { if (!fs.existsSync(file)) throw new Error(`no canary ${nm}: fleetops shadow canary start first`); return JSON.parse(read(file)); };
173
+ const save = st => { const tmp = file + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(st, null, 1)); fs.renameSync(tmp, file); };
174
+ const kubectl = opt('kubectl') || 'kubectl', show = r => (r.dryRun ? `dry run (add --live to write):\n${r.commands.map(c => ' ' + c.map(x => (/[\s{}"]/.test(x) ? `'${x}'` : x)).join(' ')).join('\n')}` : `written: ${r.commands.map(c => `${c[3]} → ${JSON.parse(c[9]).spec.router.route.weight}`).join(', ')}`);
175
+ if (sub === 'start') {
176
+ if (fs.existsSync(file) && !o.force) throw new Error(`canary ${nm} exists (status ${load().status}); --force to start over`);
177
+ const st = Canary.start({ name: nm, namespace: opt('namespace') || 'default', group: opt('group'), baseline: opt('baseline'), candidate: opt('candidate'), steps: opt('steps') ? opt('steps').split(',').map(Number) : undefined, bakeS: num('bake') ?? 600 });
178
+ const r = Canary.apply(st, Canary.share(st), { live: !!o.live, kubectl });
179
+ if (!r.dryRun) { save(st); audit({ event: 'start', share: Canary.share(st) }); } // a dry run starts nothing
180
+ if (J) { OUT.canary = { state: st, apply: r }; return; }
181
+ return say(`canary ${nm}: ${st.candidate} at ${Canary.share(st)}% of ${st.group}, ${st.baseline} the rest; steps ${st.steps.join(', ')}%\n${show(r)}`);
182
+ }
183
+ if (sub === 'status') { const st = load(); if (J) { OUT.canary = st; return; } return say(`${nm}: ${st.status}, ${st.candidate} at ${Canary.share(st)}% since ${fmt(st.since)}${st.pending ? `; step to ${st.steps[st.pending.toStep]}% ${st.pending.approvedBy ? `approved by ${st.pending.approvedBy}, written by the next advance --live` : 'waits for approval'}` : ''}\n` + st.history.slice(-8).map(h => ` ${fmt(h.t)} ${h.event}${h.to != null ? ` → ${h.to}%` : ''}${h.by || h.approvedBy ? ` (${h.by || h.approvedBy})` : ''}${h.why ? `: ${h.why}` : ''}`).join('\n')); }
184
+ if (sub === 'approve') { const st = Canary.approve(load(), opt('by')); save(st); audit({ event: 'approved', by: opt('by'), to: st.steps[st.pending.toStep] }); if (J) { OUT.canary = st; return; } return say(`approved by ${opt('by')}: the step to ${st.steps[st.pending.toStep]}% is written by the next fleetops shadow canary advance --name ${nm} --live`); }
185
+ if (sub === 'advance') {
186
+ const st = load(), now = Math.floor(Date.now() / 1000), sel = Canary.selectors(st), lookback = Math.max(300, now - st.since);
187
+ let v;
188
+ if (st.status !== 'running') v = { verdict: 'wait', why: `canary is ${st.status}` };
189
+ else if (opt('judge')) { const r = await fetch(opt('judge').replace(/\/$/, '') + '/verdict', { method: 'POST', headers: Object.assign({ 'content-type': 'application/json' }, opt('judge-token-env') ? { authorization: `Bearer ${process.env[opt('judge-token-env')] || ''}` } : {}), body: JSON.stringify(Object.assign({}, sel, { lookback, baselineLookback: num('baseline-lookback') || 21600 })) }); if (!r.ok) throw new Error(`judge: HTTP ${r.status} ${await r.text()}`); v = await r.json(); }
190
+ else if (opt('prom')) { const step = num('step') || 60, d = await SProm.fetchArms(opt('prom'), Object.assign({}, sel, { from: now - lookback, to: now, baselineFrom: now - Math.max(lookback, num('baseline-lookback') || 21600), step, headers: opt('prom-token-env') ? { authorization: `Bearer ${process.env[opt('prom-token-env')] || ''}` } : undefined })); v = SProm.compareWindows(d.baseline, d.candidate, { step, gates: json('gates') }); }
191
+ else throw new Error('--prom URL (Prometheus scraping both members) or --judge URL (fleetops shadow serve)');
192
+ const { state, action } = Canary.decide(st, v.verdict, { now, why: v.why });
193
+ const r = action.patch ? Canary.apply(state, action.share, { live: !!o.live, kubectl }) : null;
194
+ // a step written only in a dry run hasn't happened: keep the approval for the live run
195
+ if (r && r.dryRun && action.type === 'apply') { if (J) { OUT.canary = { verdict: v.verdict, why: v.why, action, apply: r }; return; } return say(`${v.verdict}: ${action.note}\n${show(r)}`); }
196
+ if (r && r.dryRun && action.type === 'rollback') { audit({ event: 'rollback-dry-run', why: v.why }); if (J) { OUT.canary = { verdict: v.verdict, why: v.why, action, apply: r }; return; } return say(`ROLL BACK (${v.why})\n${show(r)}`); }
197
+ save(state); audit({ event: action.type, verdict: v.verdict, why: v.why, live: !!o.live, share: Canary.share(state) });
198
+ if (J) { OUT.canary = { verdict: v.verdict, why: v.why, action, apply: r, state }; return; }
199
+ return say(`${v.verdict}${v.why ? ` (${v.why})` : ''}: ${action.note || action.type}${r ? `\n${show(r)}` : ''}`);
200
+ }
201
+ throw new Error('fleetops shadow canary start | advance | approve | status');
202
+ }
203
+ throw new Error('fleetops shadow demo | plan | replay | answers | compare | baseline save|list | watch | prom | serve | canary');
204
+ }
@@ -0,0 +1,79 @@
1
+ // fleetops CLI: training (see ../fleetops.mjs for the entry point and dispatch)
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import * as Goodput from '../../src/goodput.mjs';
5
+ import * as Sdc from '../../src/sdc.mjs';
6
+ import * as Tune from '../../src/tune.mjs';
7
+ import { goodputMarkdown, goodputHtml } from '../../src/goodput-report.mjs';
8
+ import { createRequire } from 'node:module';
9
+ import { J, OUT, say, read, time, fmt, dur } from './common.mjs';
10
+
11
+ // Streaming ingestion: remote_write and OTLP/HTTP (JSON) into the store.
12
+ // ---------- goodput ----------
13
+ export function goodputCmd(store, o) {
14
+ const opt = k => (o[k] && o[k] !== true ? o[k] : undefined);
15
+ const to = time(opt('to')) ?? Math.floor(Date.now() / 1000), from = time(opt('from')) ?? to - (opt('days') ? +opt('days') : 7) * 86400;
16
+ const g = Goodput.goodput(store, { from, to, now: Math.min(to, Math.floor(Date.now() / 1000)), job: opt('job'), targets: opt('targets') ? JSON.parse(read(opt('targets'))) : {} });
17
+ const fmt = opt('format');
18
+ if (fmt === 'html' || fmt === 'md') { const text = fmt === 'html' ? goodputHtml(g) : goodputMarkdown(g); if (opt('out')) { fs.writeFileSync(opt('out'), text); say(`wrote ${opt('out')}`); if (J) OUT.wrote = opt('out'); } else process.stdout.write(text); return; }
19
+ if (J) { OUT.goodput = Object.assign({}, g, { jobs: g.jobs.map(({ attemptsList, ...j }) => j) }); return; }
20
+ process.stdout.write(goodputMarkdown(g));
21
+ }
22
+
23
+ export function tuneCmd(store, cmd, o) {
24
+ const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), json = f => JSON.parse(read(f));
25
+ const to = time(opt('to')) ?? Math.floor(Date.now() / 1000), from = time(opt('from')) ?? to - (opt('days') ? +opt('days') : 7) * 86400;
26
+ // pools deployed with `fleetops serving deploy` are known without --pools / --targets
27
+ const reg = f => { const p = path.join(store.dir, 'serving', f); return fs.existsSync(p) ? JSON.parse(read(p)) : {}; };
28
+ const args = { from, to, now: Math.min(to, Math.floor(Date.now() / 1000)), targets: Object.assign(reg('targets.json'), opt('targets') ? json(opt('targets')) : {}), pools: Object.assign(reg('pools.json'), opt('pools') ? json(opt('pools')) : {}) };
29
+ const last = path.join(store.dir, 'tune', 'last.json');
30
+ if (cmd === 'models') { const C = createRequire(import.meta.url)('../../../inference-sizer/src/catalog.js'); if (J) { OUT.models = C.MODELS.map(m => m.id); OUT.gpus = C.GPUS.map(g => g.id); return; } say(`models: ${C.MODELS.map(m => m.id).join(' ')}\ngpus: ${C.GPUS.map(g => g.id).join(' ')}`); return; }
31
+ if (cmd === 'apply') {
32
+ const id = o._[2]; if (!id) throw new Error('fleetops tune apply ID --by NAME');
33
+ let rec = fs.existsSync(last) ? JSON.parse(read(last)).recommendations.find(r => r.id === id) : null;
34
+ if (!rec) rec = Tune.tune(store, args).recommendations.find(r => r.id === id);
35
+ if (!rec) throw new Error(`no recommendation ${id} (run fleetops tune first; ids are shown in its output)`);
36
+ const c = Tune.applyTune(store, rec, { by: opt('by'), at: time(opt('at')), note: opt('note') });
37
+ if (J) { OUT.applied = c; return; }
38
+ say(`recorded ${id} applied at ${fmt(c.t)} by ${c.by}${rec.verify ? `\nmeasure it once there is data after the change: fleetops tune verify ${id}` : ''}`);
39
+ return;
40
+ }
41
+ if (cmd === 'verify' || cmd === 'list') {
42
+ const ids = cmd === 'verify' && o._[2] ? [o._[2]] : [...new Set(Tune.applied(store).map(c => c.tune.id))];
43
+ const vo = { beforeS: dur(opt('before')) ?? 7 * 86400, afterS: dur(opt('after')) ?? 7 * 86400, now: Math.floor(Date.now() / 1000) };
44
+ const res = ids.map(id => Object.assign({ title: (Tune.applied(store).filter(c => c.tune.id === id).pop() || { tune: {} }).tune.title }, Tune.verifyTune(store, id, vo)));
45
+ if (J) { OUT.verified = res; return; }
46
+ if (!res.length) { say('nothing applied yet: fleetops tune apply ID --by NAME after making a change'); return; }
47
+ const f = (m, x) => (x == null ? '–' : m === 'pool.ttftP99' ? `${x.toFixed(3)} s` : m === 'fleet.interruptions' ? x.toFixed(2) : `${(x * 100).toFixed(1)}%`);
48
+ for (const r of res) say(`${r.verdict.toUpperCase().padEnd(15)} ${r.id}${r.title ? ` ${r.title}` : ''}${r.before ? `\n ${r.metric}${r.scope ? ` (${r.scope})` : ''}: ${f(r.metric, r.before.mean)} before (${r.before.n}) → ${f(r.metric, r.after.mean)} after (${r.after.n})${r.ci ? `, difference 95% CI ${f(r.metric, r.ci[0])} to ${f(r.metric, r.ci[1])}` : ''}` : ''}${r.note ? `\n ${r.note}` : ''}`);
49
+ return;
50
+ }
51
+ if (cmd === 'holdout') {
52
+ const split = time(opt('split')) ?? Math.round((from + to) / 2);
53
+ const h = Tune.holdout(store, Object.assign({}, args, { from, split, to }));
54
+ if (J) { OUT.holdout = h; return; }
55
+ say(`recommendations from ${fmt(from)} → ${fmt(split)}, checked on ${fmt(split)} → ${fmt(to)}:`);
56
+ for (const r of h.rows) {
57
+ const o2 = r.outOfSample;
58
+ const txt = r.id === 'flaky-nodes' && o2 ? `the same nodes: ${o2.failed.toFixed(0)} failed attempts against ${o2.expected.toFixed(0)} expected (${o2.ratio ? o2.ratio.toFixed(1) : '–'}×), ${(o2.share * 100).toFixed(1)}% of failures`
59
+ : r.id.startsWith('reclaim:') && o2 ? `${o2.still} of ${o2.of} jobs still flagged`
60
+ : r.inSample != null && typeof r.inSample === 'number' && typeof o2 === 'number' ? `${(r.inSample * 100).toFixed(1)}% before, ${(o2 * 100).toFixed(1)}% after` : (r.note || '');
61
+ say(` ${r.held == null ? '–' : r.held ? 'HELD ' : 'FADED'} ${r.id}: ${txt}`);
62
+ }
63
+ return;
64
+ }
65
+ if (cmd && cmd !== 'run') throw new Error(`unknown: tune ${cmd}`);
66
+ const t = Tune.tune(store, args);
67
+ fs.mkdirSync(path.dirname(last), { recursive: true }); fs.writeFileSync(last, JSON.stringify(t));
68
+ if (opt('format') === 'json' || J) { if (opt('out')) fs.writeFileSync(opt('out'), JSON.stringify(t, null, 1)); OUT.tune = t; if (!J) say(JSON.stringify(t, null, 1)); return; }
69
+ const text = Tune.tuneMarkdown(t);
70
+ if (opt('out')) { fs.writeFileSync(opt('out'), text); say(`wrote ${opt('out')}`); } else process.stdout.write(text);
71
+ }
72
+
73
+ export function sdcCmd(store, o) {
74
+ const opt = k => (o[k] && o[k] !== true ? o[k] : undefined);
75
+ const to = time(opt('to')) ?? Math.floor(Date.now() / 1000), from = time(opt('from')) ?? to - (opt('days') ? +opt('days') : 7) * 86400;
76
+ const r = Sdc.findSdc(store, { from, to });
77
+ if (J) { OUT.sdc = r; return; }
78
+ process.stdout.write(Sdc.sdcMarkdown(r));
79
+ }
@@ -8,7 +8,7 @@
8
8
  # [--step-log FILE]... [--requests FILE]... [--app-log FILE]... [--kineto FILE]...
9
9
  # [--nccl-inspector DIR] [--sdc-checks FILE]... [--fabric] [--no-kernel] [--no-gpu]
10
10
  #
11
- # Per node (by default): nvidia-smi -q and topo -m (or rocm-smi), the kernel log since --since, and the DCGM exporter
11
+ # Per node (by default): nvidia-smi -q and topo -m, or amd-smi static and topology on AMD; the kernel log since --since; the DCGM exporter
12
12
  # at http://localhost:9400/metrics if it answers. --k8s adds nodes, pods and events cluster-wide; --slurm adds sacct
13
13
  # and scontrol show node. vLLM /metrics are scraped twice, a minute apart, so rates can be computed. NFS mountstats
14
14
  # (per-export latency), ethtool -S of the RDMA NICs (pause frames, discards, link errors) and the InfiniBand/RoCE port
@@ -89,6 +89,11 @@ if [ "$GPU" = 1 ]; then
89
89
  nvidia-smi -q > "$OUT/node/nvidia-smi-q.txt" 2>/dev/null || true; add node/nvidia-smi-q.txt nvidia-smi-q "{\"node\":\"$NODE\",\"t\":\"$NOW\"}"
90
90
  nvidia-smi topo -m > "$OUT/node/nvidia-topo.txt" 2>/dev/null || true; add node/nvidia-topo.txt nvidia-topo "{\"node\":\"$NODE\",\"t\":\"$NOW\"}"
91
91
  fi
92
+ if have amd-smi; then
93
+ ROCMV="$(sed -n 1p /opt/rocm/.info/version 2>/dev/null || true)"
94
+ amd-smi static --json > "$OUT/node/amd-smi-static.json" 2>/dev/null && add node/amd-smi-static.json amd-smi-static "{\"node\":\"$NODE\",\"t\":\"$NOW\"${ROCMV:+,\"rocm\":\"$ROCMV\"}}" || true
95
+ amd-smi topology --json > "$OUT/node/amd-smi-topology.json" 2>/dev/null && add node/amd-smi-topology.json amd-smi-topology "{\"node\":\"$NODE\",\"t\":\"$NOW\"}" || true
96
+ fi
92
97
  if curl -fsS -m 5 "$DCGM" -o "$OUT/node/dcgm.prom" 2>/dev/null; then add node/dcgm.prom exporter "{\"t\":\"$NOW\"}"; fi
93
98
  if [ -n "$AMD" ] && curl -fsS -m 5 "$AMD" -o "$OUT/node/amd.prom" 2>/dev/null; then add node/amd.prom exporter "{\"vendor\":\"amd\",\"t\":\"$NOW\"}"; fi
94
99
  fi