aiinfra-tools 0.2.0 → 0.3.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 (157) hide show
  1. package/CHANGELOG.md +210 -0
  2. package/README.md +14 -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 +33 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +121 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +48 -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 +1 -1
  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 +21 -9
  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 +1 -0
  75. package/fleetscope/dist/index.html +295 -26
  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 +10 -11
  84. package/fleetscope/src/index.src.html +9 -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 +205 -22
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  139. package/inference-sizer/package.json +4 -3
  140. package/inference-sizer/src/accelerators.js +172 -0
  141. package/inference-sizer/src/catalog.js +7 -20
  142. package/inference-sizer/src/fit-ui.js +1 -1
  143. package/inference-sizer/src/index.src.html +3 -0
  144. package/inference-sizer/src/model.js +22 -1
  145. package/inference-sizer/tools/validate-agentx.mjs +110 -0
  146. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  147. package/mcp/README.md +6 -1
  148. package/mcp/server.mjs +34 -0
  149. package/package.json +9 -4
  150. package/schemas/README.md +3 -0
  151. package/schemas/aiinfra.report.schema.json +474 -0
  152. package/schemas/commands.mjs +14 -0
  153. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  154. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  155. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  156. package/schemas/harness-ledger.economics.schema.json +567 -0
  157. package/schemas/sizer.list.schema.json +15 -2
@@ -5,6 +5,7 @@
5
5
  cached prompt tokens served from a prefix cache, when the log records it
6
6
  ttft/queue/e2e recorded latencies in seconds, used to compare with the simulation
7
7
  session user or session id, when the log records one
8
+ agent subagent id within a session (agentic traces), gap seconds since the session's previous request ended
8
9
  Only timing and token counts are read; prompt and response text are never touched. */
9
10
  (function (root) {
10
11
  'use strict';
@@ -56,12 +57,15 @@
56
57
  if (t < 0) continue;
57
58
  if (t > opt.maxSeconds) { notes.push('kept the first ' + Math.round(opt.maxSeconds / 60) + ' minutes'); break; }
58
59
  if (trace.length >= opt.maxRows) { notes.push('kept the first ' + opt.maxRows.toLocaleString('en-US') + ' requests'); break; }
59
- const row = { t, isl: Math.min(Math.round(r.isl), 200000), osl: Math.max(1, Math.min(Math.round(r.osl), 16000)) };
60
+ const row = { t, isl: Math.min(Math.round(r.isl), opt.maxIsl || 200000), osl: Math.max(1, Math.min(Math.round(r.osl), opt.maxOsl || 16000)) };
60
61
  if (isFinite(r.cached) && r.cached >= 0) row.cached = Math.min(Math.round(r.cached), row.isl - 1);
61
62
  if (isFinite(r.ttft) && r.ttft >= 0) row.ttft = r.ttft;
62
63
  if (isFinite(r.queue) && r.queue >= 0) row.queue = r.queue;
63
64
  if (isFinite(r.e2e) && r.e2e >= 0) row.e2e = r.e2e;
64
65
  if (r.session != null && r.session !== '') row.session = String(r.session);
66
+ if (r.agent != null && r.agent !== '') row.agent = String(r.agent);
67
+ if (isFinite(r.api) && r.api >= 0) row.api = r.api;
68
+ if (isFinite(r.tools)) row.tools = r.tools;
65
69
  trace.push(row);
66
70
  }
67
71
  if (bad) notes.push(bad + ' unreadable record' + (bad > 1 ? 's' : '') + ' skipped');
@@ -220,6 +224,84 @@
220
224
  return out;
221
225
  }
222
226
 
227
+ // ---------- agentic traces ----------
228
+ // Prefix reuse from block hashes: each request lists the hashes of its prompt's fixed-size blocks, chained so a block's
229
+ // hash depends on everything before it. The cached part of a request is the longest run of leading blocks some earlier
230
+ // request in the same scope already had: what an unbounded prefix cache would serve. scope 'session' (AgentX: hashes are
231
+ // session-scoped) or 'global' (Mooncake: one hash space for the whole trace).
232
+ function prefixReuse(rows, blockTokens, scope) {
233
+ const seen = new Map();
234
+ for (const r of rows) {
235
+ const key = scope === 'global' ? '' : (r.session || ''), set = seen.get(key) || new Set();
236
+ seen.set(key, set);
237
+ let n = 0; const h = r.hashes || [];
238
+ while (n < h.length && set.has(h[n])) n++;
239
+ for (const x of h) set.add(x);
240
+ r.cached = Math.min(r.isl, n * blockTokens);
241
+ delete r.hashes;
242
+ }
243
+ return rows;
244
+ }
245
+ // SemiAnalysis AgentX ("weka" traces, Apache-2.0): one JSON object per session { id, requests: [ { t, type, model, in,
246
+ // out, hash_ids, api_time, think_time? } | { type: 'subagent', agent_id, requests: [...] } ] }; t in seconds from the
247
+ // session start; in = 64-token hash blocks × 64. Sessions are laid end to end unless opt.sessionGapS spaces them.
248
+ function parseAgentX(docs, opt) {
249
+ opt = opt || {};
250
+ const rows = [];
251
+ let offset = 0;
252
+ const sessions = docs.map(d => (Array.isArray(d) ? { id: null, requests: d } : d)).filter(d => d && Array.isArray(d.requests));
253
+ sessions.forEach((d, i) => {
254
+ const id = String(d.id != null ? d.id : 'session-' + i), start = offset;
255
+ let end = start;
256
+ const add = (q, agent) => {
257
+ const t = start + (+q.t || 0), api = +q.api_time || 0;
258
+ rows.push({ t, isl: +q.in || 0, osl: +q.out || 1, session: id, agent, api, hashes: q.hash_ids || [], e2e: api || NaN });
259
+ end = Math.max(end, t + api);
260
+ };
261
+ for (const q of d.requests) {
262
+ if (q && q.type === 'subagent') for (const x of q.requests || []) add(x, String(q.agent_id || 'subagent'));
263
+ else if (q) add(q, null);
264
+ }
265
+ offset = opt.sessionGapS != null ? start + opt.sessionGapS : end;
266
+ });
267
+ rows.sort((a, b) => a.t - b.t);
268
+ prefixReuse(rows, opt.blockTokens || 64, 'session');
269
+ const out = finish(rows, 'AgentX agentic trace', [], Object.assign({ maxIsl: 2e6, maxOsl: 64000 }, opt));
270
+ out.stats.sessions = sessions.length;
271
+ out.notes.push('cached tokens: what an unbounded prefix cache would serve, from 64-token block hashes (within a session)');
272
+ return out;
273
+ }
274
+ // Mooncake (Kimi) traces: one request per line { timestamp (ms), input_length, output_length, hash_ids } with 512-token
275
+ // blocks in one hash space.
276
+ function parseMooncake(docs, opt) {
277
+ opt = opt || {};
278
+ const rows = docs.filter(d => d && d.input_length != null).map(d => ({ t: (+d.timestamp || 0) / 1000, isl: +d.input_length, osl: +d.output_length || 1, hashes: d.hash_ids || [] }));
279
+ rows.sort((a, b) => a.t - b.t);
280
+ prefixReuse(rows, opt.blockTokens || 512, 'global');
281
+ const out = finish(rows, 'Mooncake trace', [], Object.assign({ maxIsl: 2e6 }, opt));
282
+ out.notes.push('cached tokens: what an unbounded prefix cache would serve, from 512-token block hashes');
283
+ return out;
284
+ }
285
+ // TraceLab (UW SyFI coding-agent trace, CC BY 4.0): one model call per line, from Claude Code and Codex, with the
286
+ // provider's own cache accounting, timing events and tool calls.
287
+ function tracelabRow(o) {
288
+ const ev = o.timing_events || [], ts = ev.map(e => toSeconds(e.timestamp)).filter(isFinite);
289
+ if (!ts.length) return null;
290
+ const isClaude = o.claude_cache_read_input_tokens != null || o.provider === 'claude';
291
+ const cached = isClaude ? (+o.claude_cache_read_input_tokens || 0) : (+o.prefix_tokens || 0);
292
+ // the call starts at its input (user message or last tool result) and ends at its last model event
293
+ const inEv = ev.filter(e => /user_message|tool_result/.test(e.event_type)).map(e => toSeconds(e.timestamp)).filter(isFinite);
294
+ const outEv = ev.filter(e => /text|tool_call|reasoning|usage_report/.test(e.event_type)).map(e => toSeconds(e.timestamp)).filter(isFinite);
295
+ const t = inEv.length ? Math.max(...inEv) : Math.min(...ts), endT = outEv.length ? Math.max(...outEv) : t;
296
+ return { t, isl: +o.input_tokens_total || 0, osl: Math.max(1, (+o.output_tokens || 0)), cached, session: o.session_id, api: Math.max(0, endT - t), tools: (o.tools || []).length, model: o.model };
297
+ }
298
+ function parseTraceLab(docs, opt) {
299
+ const rows = docs.map(tracelabRow).filter(Boolean);
300
+ const out = finish(rows, 'TraceLab coding-agent trace', [], Object.assign({ maxIsl: 2e6, maxOsl: 64000 }, opt || {}));
301
+ out.notes.push('cached tokens as each provider reported them (Claude cache reads, Codex cached prefix)');
302
+ return out;
303
+ }
304
+
223
305
  // ---------- detection ----------
224
306
  function parseJsonLines(text) {
225
307
  const out = [];
@@ -232,14 +314,18 @@
232
314
  return { docs: out, bad };
233
315
  }
234
316
  function parseTrace(text, opt) {
235
- const s = text.replace(/^/, '').trimStart();
317
+ const s = text.replace(/^\uFEFF/, '').trimStart();
236
318
  if (s[0] === '{' || s[0] === '[') {
237
319
  let docs, bad = 0;
238
320
  try { const whole = JSON.parse(s); docs = Array.isArray(whole) ? whole : [whole]; }
239
321
  catch (e) { const jl = parseJsonLines(s); docs = jl.docs; bad = jl.bad; }
240
322
  if (!docs.length) throw new Error('The file looks like JSON but no record could be parsed.');
241
323
  let res;
324
+ const d0 = docs.find(d => d && typeof d === 'object');
242
325
  if (docs.some(d => d && (d.resourceSpans || d.batches))) res = parseOTLP(docs, opt);
326
+ else if (d0 && (Array.isArray(d0.requests) || (Array.isArray(d0) && d0[0] && d0[0].hash_ids))) res = parseAgentX(docs, opt);
327
+ else if (d0 && d0.input_length != null && d0.hash_ids) res = parseMooncake(docs, opt);
328
+ else if (d0 && d0.timing_events && d0.input_tokens_total != null) res = parseTraceLab(docs, opt);
243
329
  else if (docs.length === 1 && docs[0] && Array.isArray(docs[0].data) && docs[0].data.some(x => x && x.spans)) res = parseJaeger(docs[0], opt);
244
330
  else {
245
331
  const records = docs.length === 1 && docs[0] && Array.isArray(docs[0].data) ? docs[0].data : docs;
@@ -259,7 +345,7 @@
259
345
  return lines.join('\n') + '\n';
260
346
  }
261
347
 
262
- const api = { parseTrace, parseCSV, toCSV, toSeconds, LIMITS };
348
+ const api = { parseTrace, parseCSV, toCSV, toSeconds, LIMITS, parseAgentX, parseMooncake, parseTraceLab, tracelabRow, prefixReuse, finish };
263
349
  if (typeof module !== 'undefined' && module.exports) module.exports = api;
264
350
  else root.FleetIngest = api;
265
351
  })(typeof window !== 'undefined' ? window : this);
@@ -95,11 +95,14 @@
95
95
  // rent on demand, rent reserved (1-year commitments) with on-demand burst, and hybrid (buy on-prem for the
96
96
  // base load with a lead time, reserve nothing, burst the rest on demand). On-prem cost: capex (paid at
97
97
  // delivery), power at PUE, and operations; hardware keeps its residual value at the end.
98
- const CAP_DEFAULTS = { months: 24, gpusNow: 64, growthPct: 4, baseShare: 0.6, peakHoursShare: 0.35, gpuCapex: 32000, amortMonths: 48, kwPerGpu: 1.1, pue: 1.3, kwhPrice: 0.09, opsPerGpuMonth: 120, leadMonths: 3, reservedPerGpuH: 2.2, onDemandPerGpuH: 3.5, onPremStart: 0 };
98
+ // Two cloud ways to buy the peak on top of a reserved base: short-term blocks (AWS EC2 Capacity Blocks for ML,
99
+ // GCP calendar-mode reservations), bought in whole days, so the peak hours are assumed to come as one run of days;
100
+ // and spot, with a share of the spot hours redone after interruptions. Prices are placeholders: set your own.
101
+ const CAP_DEFAULTS = { months: 24, gpusNow: 64, growthPct: 4, baseShare: 0.6, peakHoursShare: 0.35, gpuCapex: 32000, amortMonths: 48, kwPerGpu: 1.1, pue: 1.3, kwhPrice: 0.09, opsPerGpuMonth: 120, leadMonths: 3, reservedPerGpuH: 2.2, onDemandPerGpuH: 3.5, onPremStart: 0, blockPerGpuH: 2.8, spotPerGpuH: 1.9, spotRework: 0.1 };
99
102
  function capacityPlan(o) {
100
103
  o = Object.assign({}, CAP_DEFAULTS, o || {});
101
104
  const H = 730, months = [];
102
- const strat = { demand: [], rent: [], reserved: [], hybrid: [], owned: [] };
105
+ const DAYS = H / 24;
103
106
  let owned = o.onPremStart;
104
107
  const deliveries = [];
105
108
  for (let m = 0; m < o.months; m++) {
@@ -108,6 +111,9 @@
108
111
  const avgUse = base + (peak - base) * o.peakHoursShare;
109
112
  const rent = avgUse * H * o.onDemandPerGpuH;
110
113
  const reserved = base * H * o.reservedPerGpuH + (peak - base) * o.peakHoursShare * H * o.onDemandPerGpuH;
114
+ const blockDays = Math.min(DAYS, Math.ceil(o.peakHoursShare * DAYS - 1e-9));
115
+ const blocks = base * H * o.reservedPerGpuH + (peak - base) * blockDays * 24 * o.blockPerGpuH;
116
+ const spot = base * H * o.reservedPerGpuH + (peak - base) * o.peakHoursShare * H * o.spotPerGpuH * (1 + o.spotRework);
111
117
  // hybrid: order on-prem GPUs so that, after the lead time, owned capacity covers the base load
112
118
  const futureBase = o.gpusNow * Math.pow(1 + o.growthPct / 100, m + o.leadMonths) * o.baseShare;
113
119
  const pipeline = deliveries.filter(d => d.at >= m).reduce((a, d) => a + d.n, 0);
@@ -118,12 +124,12 @@
118
124
  const onprem = owned * (o.kwPerGpu * o.pue * H * o.kwhPrice + o.opsPerGpuMonth);
119
125
  const uncovered = Math.max(0, base - owned) * H + (peak - Math.max(base, Math.min(owned, peak))) * o.peakHoursShare * H;
120
126
  const hybrid = capex + onprem + Math.max(0, uncovered) * o.onDemandPerGpuH;
121
- months.push({ m, peak, base, owned, order, capex, rent, reserved, hybrid });
127
+ months.push({ m, peak, base, owned, order, capex, rent, reserved, hybrid, blocks, spot, blockDays });
122
128
  }
123
129
  const residual = owned => owned * o.gpuCapex * Math.max(0, 1 - o.months / o.amortMonths);
124
130
  const sum = k => months.reduce((a, x) => a + x[k], 0);
125
- const totals = { rent: sum('rent'), reserved: sum('reserved'), hybrid: sum('hybrid') - residual(owned), hybridCash: sum('hybrid') };
126
- const ranked = Object.entries({ rent: totals.rent, reserved: totals.reserved, hybrid: totals.hybrid }).sort((a, b) => a[1] - b[1]);
131
+ const totals = { rent: sum('rent'), reserved: sum('reserved'), hybrid: sum('hybrid') - residual(owned), hybridCash: sum('hybrid'), blocks: sum('blocks'), spot: sum('spot') };
132
+ const ranked = Object.entries({ rent: totals.rent, reserved: totals.reserved, hybrid: totals.hybrid, blocks: totals.blocks, spot: totals.spot }).sort((a, b) => a[1] - b[1]);
127
133
  // break-even: first month where cumulative hybrid cash spend falls below cumulative renting
128
134
  let cr = 0, ch = 0, breakEven = null;
129
135
  for (const x of months) { cr += x.rent; ch += x.hybrid; if (breakEven == null && x.owned > 0 && ch <= cr) breakEven = x.m; }
@@ -26,7 +26,7 @@
26
26
  const arr = [];
27
27
  while (i < lines.length && indent(lines[i]) === ind && lines[i].trim().startsWith('- ')) {
28
28
  const rest = lines[i].trim().slice(2);
29
- if (/^[\w.\/-]+:(\s|$)/.test(rest)) { lines[i] = ' '.repeat(ind + 2) + rest; arr.push(block(ind + 2)); }
29
+ if (/^[\w./-]+:(\s|$)/.test(rest)) { lines[i] = ' '.repeat(ind + 2) + rest; arr.push(block(ind + 2)); }
30
30
  else { arr.push(scalar(rest)); i++; }
31
31
  }
32
32
  return arr;
@@ -1,3 +1,4 @@
1
+ /* global FleetScenario */ // set by scenario.js, loaded first on the page
1
2
  /* FleetScope Training view: one job seen four ways (GPUs, phases, scheduling, full). Browser only. */
2
3
  (function () {
3
4
  'use strict';
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // Agentic workloads for capacity planning: fit a profile of agent sessions from a real trace, generate synthetic sessions
3
+ // at any load, measure what a workload asks of a fleet, size GPUs for it, and check a profile against held-out sessions.
4
+ //
5
+ // node tools/agentic.mjs fit TRACE [-o profile.json] [--cache-ttl 300]
6
+ // node tools/agentic.mjs synth PROFILE --sessions-per-hour N [--hours 1] [--seed 1] [-o trace.csv|trace.jsonl]
7
+ // node tools/agentic.mjs stats TRACE|PROFILE [--sessions-per-hour N] [--hours 1] [--ideal]
8
+ // node tools/agentic.mjs size TRACE|PROFILE --sessions-per-hour N [--model qwen3-coder-480b] [--gpu B200] [--ttft 2000] [--tpot 30]
9
+ // [--kv-offload [--cpu-kv-gb 375] [--pcie-gbs 64]] KV beyond HBM held in host memory and reloaded over PCIe
10
+ // node tools/agentic.mjs validate TRACE [--sessions-per-hour 600] [--hours 1] [--seeds 5] [--holdout 0.3] [--model …] [--gpu …] [--markdown]
11
+ //
12
+ // TRACE: TraceLab (syfi_coding_trace.jsonl[.gz], or the word "tracelab" to fetch the public release), AgentX / "weka" session
13
+ // JSON lines, Mooncake JSON lines, or FleetScope trace CSV/JSONL with session ids. Every command takes --json.
14
+ import fs from 'node:fs';
15
+ import zlib from 'node:zlib';
16
+ import readline from 'node:readline';
17
+ import { createRequire } from 'node:module';
18
+ import { fileURLToPath } from 'node:url';
19
+ import { tracelabFile, TRACELAB } from './tracelab-data.mjs';
20
+
21
+ const require = createRequire(import.meta.url);
22
+ const IN = require('../src/ingest.js'), A = require('../src/agentic.js');
23
+ const C = require('../../inference-sizer/src/catalog.js'), M = require('../../inference-sizer/src/model.js');
24
+
25
+ export async function loadRows(file) {
26
+ const stream = fs.createReadStream(file), input = file.endsWith('.gz') ? stream.pipe(zlib.createGunzip()) : stream;
27
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
28
+ let kind = null; const rows = [], docs = [], text = [];
29
+ for await (const line of rl) {
30
+ const s = line.trim(); if (!s) continue;
31
+ if (!kind) kind = s[0] === '{' || s[0] === '[' ? 'json' : 'csv';
32
+ if (kind === 'csv') { text.push(line); continue; }
33
+ let o; try { o = JSON.parse(s); } catch { continue; }
34
+ if (o && o.timing_events && o.input_tokens_total != null) { const r = IN.tracelabRow(o); if (r) rows.push(r); }
35
+ else if (o && o.kind === 'llm_call') rows.push({ t: o.t, isl: o.input, osl: Math.max(1, o.output), cached: o.cacheRead ?? undefined, session: o.session, agent: o.agent !== 'main' ? o.agent : undefined, api: o.durS });
36
+ else if (o && o.t != null && o.isl != null) rows.push(o);
37
+ else docs.push(o);
38
+ }
39
+ const ALL = { maxRows: Infinity, maxSeconds: Infinity };
40
+ if (kind === 'csv') return { rows: IN.parseCSV(text.join('\n'), ALL).trace, format: 'FleetScope CSV' };
41
+ if (rows.length) return { rows, format: rows[0].model !== undefined ? 'TraceLab' : 'rows' };
42
+ const d0 = docs[0] || {};
43
+ if (Array.isArray(d0.requests) || Array.isArray(d0)) { const r = IN.parseAgentX(docs, ALL); return { rows: r.trace, format: r.format }; }
44
+ if (d0.input_length != null) { const r = IN.parseMooncake(docs, ALL); return { rows: r.trace, format: r.format }; }
45
+ throw new Error(`${file}: not a trace this tool reads (TraceLab, AgentX, Mooncake, FleetScope CSV/JSONL)`);
46
+ }
47
+ const isProfile = f => { if (!/\.json$/.test(f)) return null; try { const j = JSON.parse(fs.readFileSync(f, 'utf8')); return j && j.kind === 'fleetscope.agentic-profile' ? j : null; } catch { return null; } };
48
+
49
+ function settings(o) {
50
+ const m = C.MODELS.find(x => x.id === (o.model || 'qwen3-coder-480b')), g = C.GPUS.find(x => x.id === (o.gpu || 'B200'));
51
+ if (!m) throw new Error(`unknown model ${o.model}; one of ${C.MODELS.map(x => x.id).join(', ')}`);
52
+ if (!g) throw new Error(`unknown GPU ${o.gpu}; one of ${C.GPUS.map(x => x.id).join(', ')}`);
53
+ return Object.assign({}, M.SETTINGS, m, g, { ttft: +(o.ttft || 2000), tpot: +(o.tpot || 30), ctx: m.maxCtx || M.SETTINGS.ctx, modelId: m.id, gpuId: g.id });
54
+ }
55
+ // requests longer than the model's context can't be served by it: cap them (and say how many)
56
+ function capped(rows, ctx) { let n = 0; const out = rows.map(r => (r.isl + r.osl > ctx ? (n++, Object.assign({}, r, { isl: Math.max(1, ctx - r.osl), cached: r.cached != null ? Math.min(r.cached, ctx - r.osl - 1) : r.cached })) : r)); return { rows: out, over: n }; }
57
+
58
+ export function sizeReport(rows, s, o = {}) {
59
+ const c = capped(rows, s.ctx), st = A.workloadStats(c.rows, { cacheTtlS: o.cacheTtlS || 300 }), so = o.sizeOpts || {};
60
+ return { stats: st, overContext: c.over, agentic: A.sizeFor(st, s, M, so), flat: A.sizeFor(A.flatStats(st), s, M), model: s.modelId, gpu: s.gpuId };
61
+ }
62
+
63
+ const pct = x => (x == null || !Number.isFinite(x) ? '–' : `${x >= 0 ? '+' : ''}${(100 * x).toFixed(1)}%`);
64
+ const k = x => (x >= 1e6 ? (x / 1e6).toFixed(2) + 'M' : x >= 1e3 ? (x / 1e3).toFixed(1) + 'k' : (+x).toFixed(x < 10 ? 2 : 0));
65
+ export function validationMarkdown(V, sz, meta) {
66
+ const L = [`# Agentic workload profiles against held-out sessions`, '',
67
+ `Generated by \`node fleetscope/tools/agentic.mjs validate ${meta.file === TRACELAB.url.split('/').pop() ? 'tracelab' : meta.file} --hours ${V.settings.horizonS / 3600} --markdown\`. Data: ${meta.format === 'TraceLab' ? `[TraceLab](https://github.com/uw-syfi/TraceLab) ${TRACELAB.release} (${TRACELAB.license}; ${TRACELAB.citation})` : meta.format}, ${V.train.sessions + V.test.sessions} sessions (${k(V.train.rows + V.test.rows)} model calls). The profile is fitted on ${V.train.sessions} sessions and checked on the other ${V.test.sessions}: both are started on the same Poisson arrivals (${V.settings.sessionsPerHour} sessions/hour for ${V.settings.horizonS / 3600} h, ${V.settings.seeds.length} seeds); the held-out sessions keep their own recorded timing, the synthetic ones are drawn from the profile.`, '',
68
+ '## What the workload asks of a fleet: synthetic vs replay', '', '| Metric | Replay (held out) | Synthetic | Mean error over seeds |', '| --- | --- | --- | --- |'];
69
+ const r0 = V.runs[0];
70
+ const label = { cacheHit: 'Prefix-cache hit rate', 'isl.mean': 'Prompt tokens, mean', 'isl.p90': 'Prompt tokens, p90', 'osl.mean': 'Output tokens, mean', 'rps.mean': 'Calls/s, mean', 'rps.p95': 'Calls/s, p95 minute', 'prefillTps.mean': 'Prefill tokens/s (uncached), mean', 'prefillTps.p95': 'Prefill tokens/s (uncached), p95 minute', 'decodeTps.mean': 'Output tokens/s, mean', 'decodeTps.p95': 'Output tokens/s, p95 minute', 'kvTokens.p95': 'KV working set (tokens), p95' };
71
+ for (const key of A.KEYS) { const c = r0.cmp[key]; L.push(`| ${label[key]} | ${key === 'cacheHit' ? (100 * c.real).toFixed(1) + '%' : k(c.real)} | ${key === 'cacheHit' ? (100 * c.synth).toFixed(1) + '%' : k(c.synth)} | ${pct(V.agg[key].meanErr)} (abs ${(100 * V.agg[key].meanAbsErr).toFixed(1)}%) |`); }
72
+ if (sz) {
73
+ L.push('', `## GPUs: ${sz.real.model} on ${sz.real.gpu}, TTFT ${meta.ttft} ms, TPOT ${meta.tpot} ms`, '',
74
+ '| Sized from | Compute GPUs | GPUs to hold the KV working set | GPUs | Bound by |', '| --- | --- | --- | --- | --- |',
75
+ `| Held-out sessions, agentic (cache reuse and idle sessions counted) | ${sz.real.agentic.compute} | ${sz.real.agentic.kvGpus} | **${sz.real.agentic.gpus}** | ${sz.real.agentic.bound} |`,
76
+ `| Synthetic sessions from the profile | ${sz.synth.agentic.compute} | ${sz.synth.agentic.kvGpus} | **${sz.synth.agentic.gpus}** | ${sz.synth.agentic.bound} |`,
77
+ `| Held-out sessions, flat (same calls/s and mean ISL/OSL, no reuse, no idle sessions) | ${sz.real.flat.compute ?? 'no layout meets the targets'} | ${sz.real.flat.kvGpus} | **${sz.real.flat.gpus ?? '–'}** | ${sz.real.flat.compute == null ? 'prefilling the whole prompt every call misses the TTFT target' : sz.real.flat.bound} |`,
78
+ `| The same flat sizing with the TTFT target relaxed to 10 s | ${sz.flatRelaxed.compute ?? '–'} | ${sz.flatRelaxed.kvGpus} | **${sz.flatRelaxed.gpus ?? '–'}** | ${sz.flatRelaxed.bound} |`, '',
79
+ `${sz.real.overContext} of ${sz.real.stats.requests} replayed calls were longer than the model's ${k(meta.ctx)}-token context and were capped to it.`);
80
+ }
81
+ L.push('', '## Notes', '', '- Timing comes from the providers that served the trace (model time per call), not from the GPUs being sized; the profile carries the shape of the work — context growth, reuse, gaps, tool time — not latency.',
82
+ '- The KV working set assumes contexts stay resident from one call to the next for up to the cache lifetime (' + V.settings.cacheTtlS + ' s). Offloading to CPU memory or storage lowers the GPUs it needs and adds reload time.',
83
+ '- The flat row is how most sizing is done today: it overstates prefill (it re-prefills the whole prompt every call) and understates memory (it only counts in-flight requests).', '');
84
+ return L.join('\n');
85
+ }
86
+
87
+ function args(argv) { const o = { _: [] }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === '-o') o.out = argv[++i]; else if (a.startsWith('--')) { const n = argv[i + 1]; if (n !== undefined && !n.startsWith('--')) { o[a.slice(2)] = n; i++; } else o[a.slice(2)] = true; } else o._.push(a); } return o; }
88
+
89
+ export async function main(argv) {
90
+ const o = args(argv), [cmd] = o._, out = (obj, txt) => console.log(o.json ? JSON.stringify(obj, null, 1) : txt);
91
+ const ttl = +(o['cache-ttl'] || 300), horizonS = +(o.hours || 1) * 3600, sph = +(o['sessions-per-hour'] || 0);
92
+ if (!cmd || o.help) { console.log(fs.readFileSync(fileURLToPath(import.meta.url), 'utf8').split('\n').slice(1, 13).map(l => l.replace(/^\/\/ ?/, '')).join('\n')); return 0; }
93
+ // "tracelab" stands for the public TraceLab trace, fetched at a pinned release and checked
94
+ const file = o._[1] === 'tracelab' ? await tracelabFile(o.file) : o._[1];
95
+ if (!file) throw new Error(`${cmd}: give a trace or profile file (or "tracelab")`);
96
+ const prof = isProfile(file);
97
+ const workload = async () => {
98
+ if (prof) { if (!sph) throw new Error('a profile needs --sessions-per-hour'); return A.synthesize(prof, { sessionsPerHour: sph, horizonS, seed: +(o.seed || 1) }); }
99
+ const { rows } = await loadRows(file);
100
+ return sph ? A.replay(rows, { sessionsPerHour: sph, horizonS, seed: +(o.seed || 1) }) : rows;
101
+ };
102
+ if (cmd === 'fit') {
103
+ const { rows, format } = await loadRows(file), p = A.fitProfile(rows, { cacheTtlS: ttl, source: `${format}: ${file.replace(/^.*[\\/]/, '')}` });
104
+ if (o.out) fs.writeFileSync(o.out, JSON.stringify(p) + '\n');
105
+ const col = (name, f = 0.5) => { const i = p.main.paramsCols.indexOf(name), v = p.main.params.map(x => x[i]).sort((a, b) => a - b); return v[Math.floor(f * (v.length - 1))]; };
106
+ out(o.out ? { wrote: o.out, sessions: p.sessions, requests: p.requests } : p, `${format}: ${p.sessions} sessions, ${p.requests} calls; cache hit ${(100 * p.cacheHit).toFixed(1)}%\n per session (median): ${col('turns')} calls, first prompt ${k(col('firstIsl'))}, +${k(col('appendMean'))} tokens/call, ${col('shortGapMean').toFixed(1)} s between calls in the tool loop, ${(100 * col('longShare')).toFixed(0)}% of gaps over ${p.longGapS} s${o.out ? `\n → ${o.out}` : ''}`);
107
+ return 0;
108
+ }
109
+ if (cmd === 'synth') {
110
+ if (!prof) throw new Error('synth needs a profile (from "fit")');
111
+ const rows = A.synthesize(prof, { sessionsPerHour: sph || 600, horizonS, seed: +(o.seed || 1) });
112
+ const body = o.out && o.out.endsWith('.csv') ? IN.toCSV(rows) : rows.map(r => JSON.stringify(r)).join('\n') + '\n';
113
+ if (o.out) fs.writeFileSync(o.out, body); else process.stdout.write(body);
114
+ if (o.out) console.error(`${rows.length} calls in ${new Set(rows.map(r => r.session)).size} sessions → ${o.out}`);
115
+ return 0;
116
+ }
117
+ if (cmd === 'stats') {
118
+ const st = A.workloadStats(await workload(), { cacheTtlS: ttl, ideal: !!o.ideal });
119
+ out(st, `${st.requests} calls, ${st.sessions} sessions over ${(st.seconds / 3600).toFixed(2)} h; cache hit ${(100 * st.cacheHit).toFixed(1)}%\n prompt mean ${k(st.isl.mean)} p99 ${k(st.isl.p99)}; output mean ${k(st.osl.mean)}\n p95 minute: ${st.rps.p95.toFixed(2)} calls/s, ${k(st.prefillTps.p95)} prefill tok/s, ${k(st.decodeTps.p95)} output tok/s\n KV working set p95 ${k(st.kvTokens.p95)} tokens; in flight p95 ${st.inflight.p95}`);
120
+ return 0;
121
+ }
122
+ if (cmd === 'size') {
123
+ const sizeOpts = { kvOffload: !!o['kv-offload'], offload: Object.fromEntries([['cpuGBPerGpu', o['cpu-kv-gb']], ['pcieGBs', o['pcie-gbs']]].filter(([, v]) => v != null && v !== true).map(([k, v]) => [k, +v])) };
124
+ const s = settings(o), rep = sizeReport(await workload(), s, { cacheTtlS: ttl, sizeOpts }), a = rep.agentic, f = a.offload;
125
+ out(rep, `${rep.model} on ${rep.gpu}: agentic ${a.gpus} GPUs (compute ${a.compute}, KV working set ${a.kvGpus} → bound by ${a.bound}); flat ISL/OSL sizing would say ${rep.flat.gpus ?? 'no layout meets the targets'}${rep.overContext ? `; ${rep.overContext} calls capped at the model's context` : ''}`
126
+ + `\n KV offload ${a.kvOffloadUsed ? 'used' : !f.usable ? 'not usable here' : f.gpus < a.gpus ? 'would bring it to ' + f.gpus + ' GPUs (--kv-offload)' : 'not needed: compute sets the count'}: ${f.cpuGBPerGpu} GB host memory per GPU, ${(100 * f.offloadedShare).toFixed(0)}% of the working set off the GPUs, reload ${f.reloadMs.toFixed(0)} ms, PCIe ${(100 * (f.pcieUtil || 0)).toFixed(0)}% busy`
127
+ + (a.power && a.power.tokensPerSecPerMW != null ? `\n ${Math.round(a.power.tokensPerSecPerMW).toLocaleString('en-US')} output tokens/s per MW at the peak minute (${a.power.kw.toFixed(0)} kW, ${a.power.basis})` : ''));
128
+ return 0;
129
+ }
130
+ if (cmd === 'validate') {
131
+ const { rows, format } = await loadRows(file);
132
+ const V = A.validate(rows, { sessionsPerHour: sph || 600, horizonS, holdout: +(o.holdout || 0.3), cacheTtlS: ttl, source: format, seeds: Array.from({ length: +(o.seeds || 5) }, (_, i) => i + 1) });
133
+ const s = settings(o), r0 = V.runs[0], seed = r0.seed, starts = A.arrivals(0, V.settings.sessionsPerHour, horizonS, A.rng(seed * 7919));
134
+ const real = A.replay(V.testRows, { seed, starts, horizonS });
135
+ const sz = { real: sizeReport(real, s, { cacheTtlS: ttl }), synth: sizeReport(A.synthesize(V.profile, { seed, starts, horizonS }), s, { cacheTtlS: ttl }) };
136
+ // flat sizing usually can't meet the TTFT at all (it prefills the whole prompt each call): what it asks for with 10 s
137
+ sz.flatRelaxed = sizeReport(real, Object.assign({}, s, { ttft: 10000 }), { cacheTtlS: ttl }).flat;
138
+ const res = { format, train: V.train, test: V.test, agg: V.agg, runs: V.runs.map(r => ({ seed: r.seed, cmp: r.cmp })), sizing: { real: { agentic: sz.real.agentic, flat: sz.real.flat, flatRelaxedTtft: sz.flatRelaxed, overContext: sz.real.overContext }, synth: { agentic: sz.synth.agentic } } };
139
+ if (o.markdown) { console.log(validationMarkdown(V, sz, { file: file.replace(/^.*[\\/]/, ''), format, ttft: s.ttft, tpot: s.tpot, ctx: s.ctx })); return 0; }
140
+ out(res, `${format}: fit on ${V.train.sessions} sessions, checked on ${V.test.sessions}\n` + A.KEYS.map(key => ` ${key.padEnd(15)} mean error ${pct(V.agg[key].meanErr)}`).join('\n') + `\n GPUs (${s.modelId} on ${s.gpuId}): held-out ${sz.real.agentic.gpus}, synthetic ${sz.synth.agentic.gpus}, flat sizing ${sz.real.flat.gpus ?? 'no layout meets the targets'}`);
141
+ return 0;
142
+ }
143
+ throw new Error(`unknown command ${cmd}`);
144
+ }
145
+
146
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
147
+ main(process.argv.slice(2)).then(c => { process.exitCode = c; }, e => { console.error(`agentic: ${e.message}`); process.exitCode = 2; });
148
+ }
@@ -0,0 +1,27 @@
1
+ // The TraceLab coding-agent trace (UW SyFI, CC BY 4.0): 8,058 Claude Code and Codex sessions, 665,453 model calls, with
2
+ // the providers' cache accounting, timing and tool calls. Fetched at a pinned release, checked by SHA-256 and cached; it
3
+ // is not copied into this repository. https://github.com/uw-syfi/TraceLab
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import crypto from 'node:crypto';
8
+
9
+ export const TRACELAB = {
10
+ url: 'https://github.com/uw-syfi/TraceLab/releases/download/v0.0.2/syfi_coding_trace.jsonl.gz', release: 'v0.0.2',
11
+ sha256: '11ce51ec0a25e3d1d95b025bca2f7d1647e47571eb7cc968acd5fc64d4b4fb65', license: 'CC BY 4.0', citation: 'Zhu et al., TraceLab: Characterizing Coding Agent Workloads for LLM Serving, arXiv:2606.30560 (2026)',
12
+ };
13
+
14
+ // a local copy (--file, or TRACELAB_FILE) is used as is after the checksum; otherwise download once into the cache
15
+ export async function tracelabFile(local = process.env.TRACELAB_FILE, cache = path.join(os.homedir(), '.cache', 'aiinfra-tools', 'tracelab', TRACELAB.release)) {
16
+ const file = local || path.join(cache, 'syfi_coding_trace.jsonl.gz');
17
+ if (!fs.existsSync(file)) {
18
+ if (local) throw new Error(`${local}: not found`);
19
+ fs.mkdirSync(cache, { recursive: true });
20
+ const res = await fetch(TRACELAB.url);
21
+ if (!res.ok) throw new Error(`download ${TRACELAB.url}: HTTP ${res.status}`);
22
+ fs.writeFileSync(file + '.part', Buffer.from(await res.arrayBuffer())); fs.renameSync(file + '.part', file);
23
+ }
24
+ const h = crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
25
+ if (h !== TRACELAB.sha256) throw new Error(`${file}: SHA-256 ${h} is not TraceLab ${TRACELAB.release}'s ${TRACELAB.sha256}`);
26
+ return file;
27
+ }
@@ -13,7 +13,7 @@ Over time it also answers a fifth: **which GPUs keep coming back broken?** The [
13
13
 
14
14
  Every finding becomes an **action** in a queue. Your policy decides whether an action runs automatically, waits for a person to approve it, or is shown only as a suggestion. Approved actions run as fixed commands (no shell). They are dry-run by default, and every step is written to an audit log.
15
15
 
16
- No dependencies: Node 20+.
16
+ No dependencies: Node 22+.
17
17
 
18
18
  ## Try it
19
19
 
@@ -145,6 +145,17 @@ The page lists open actions with Approve, Reject and Dry-run/Execute buttons.
145
145
  - The page binds to localhost by default. Put it behind your SSO proxy before exposing it.
146
146
  - Real execution from the page also needs `--allow-live`.
147
147
 
148
+ ## Alongside NVSentinel
149
+
150
+ If NVSentinel already runs on the cluster, it detects GPU faults and cordons, drains and remediates nodes itself.
151
+ gpu-health doesn't queue a second repair ladder for a node NVSentinel is handling.
152
+ - **How events arrive:** fleetops imports NVSentinel's events (`fleetops data import nvsentinel`), and
153
+ `fleetops data export gpu-health` passes on the faults and the nodes being remediated.
154
+ - **What changes:** for those nodes, quarantine, drain, diagnostics and repairs become one `external-remediation` action
155
+ that names what NVSentinel is doing. Its mode is `never`: shown, never run.
156
+ - **Turning it off:** `"deferToExternal": false` in the config keeps gpu-health's own actions. A remediation older than a
157
+ day isn't deferred to.
158
+
148
159
  ## Running it on a real fleet
149
160
 
150
161
  ```bash
@@ -170,7 +181,7 @@ Every command takes `--json` and prints one JSON object, for scripts and LLM age
170
181
 
171
182
  | File | Contents | Needed for |
172
183
  |---|---|---|
173
- | `--samples` JSONL / `--prom` exporter text | per-GPU telemetry, see `src/ingest.mjs` for the fields | everything |
184
+ | `--samples` JSONL / `--prom` exporter text / `--cloud-monitoring` Google Cloud Monitoring `timeSeries` JSON (GKE node or TPU VM accelerator metrics) | per-device telemetry, see `src/ingest.mjs` for the fields | everything |
174
185
  | `--jobs` JSON | `[{ id, class, owner, namespace, start, end?, gpusPerReplica?, gpus: [{node, gpu}] }]`, from your scheduler | efficiency, savings, owner notices |
175
186
  | `--steps` JSONL | `{ job, rank, step, t, computeMs }`, from a training-loop hook | straggler detection (best) |
176
187
  | `--probes` JSONL | `{ t, node, gpu, sku, firmware, site, gemmTflops, hbmGBs, linkGBs? }`, from a short benchmark between jobs | speed index |
@@ -84,7 +84,7 @@ Action kinds:
84
84
 
85
85
  ## Executors
86
86
 
87
- Each action kind maps to a list of argv arrays, run in order without a shell, or to `"webhook"`, or to `{ "webhook": "what a person should do" }`. A vendor profile's `executors` win over these for its devices (`vendors.<v>.executors`). Placeholders: `{node} {gpu} {job} {namespace} {replicas} {level} {fraction} {reason} {vendor}`. Each value filled in must match `^[A-Za-z0-9][A-Za-z0-9._:/=-]{0,252}$`. Anything else, including values starting with `-`, stops the action.
87
+ Each action kind maps to a list of argv arrays, run in order without a shell, or to `"webhook"`, or to `{ "webhook": "what a person should do" }`. A vendor profile's `executors` win over these for its devices (`vendors.<v>.executors`), and a cloud platform's win over both for its nodes (see Platforms). Placeholders: `{node} {gpu} {job} {namespace} {replicas} {level} {fraction} {reason} {vendor}`, plus `{instance} {zone} {project}` on a cloud. Each value filled in must match `^[A-Za-z0-9][A-Za-z0-9._:/=-]{0,252}$`. Anything else, including values starting with `-`, stops the action.
88
88
 
89
89
  Slurm example. Draining in Slurm is per node, so quarantining one GPU drains the whole node:
90
90
 
@@ -96,6 +96,34 @@ Slurm example. Draining in Slurm is per node, so quarantining one GPU drains the
96
96
 
97
97
  `notify.webhook` takes a Lark/Feishu or Slack incoming-webhook URL; the message format is picked from the host. When it is empty, messages are printed only.
98
98
 
99
+ ## Platforms (clouds)
100
+
101
+ The vendor says how to read and reset a device; the platform says who owns the hardware. On a cloud instance:
102
+ - reseating, firmware alignment and facilities checks are never proposed;
103
+ - rebooting and replacing act on the cloud's instance, not the node name.
104
+
105
+ | Platform | `node-reboot` | `rma` (replace) |
106
+ | --- | --- | --- |
107
+ | `aws` | `aws ec2 reboot-instances --instance-ids {instance}` | `aws autoscaling set-instance-health --instance-id {instance} --health-status Unhealthy --no-should-respect-grace-period`: the instance's Auto Scaling group (EKS managed node groups use one) replaces it |
108
+ | `gke` | `gcloud compute instances reset {instance}` | `kubectl label node {node} cloud.google.com/fault-behavior={behavior}`: GKE drains the node, reports the host as faulty and brings the node back repaired. `{behavior}` is `XID`, `SDC` or `PERFORMANCE` from the fault class. TPU slices keep the TPU profile's steps |
109
+ | `gcp` (Compute Engine VMs, Slurm) | `gcloud compute instances reset {instance}` | `gcloud compute instances report-host-as-faulty {instance} --disruption-schedule=IMMEDIATE --fault-reasons=behavior={behavior}`, with `UNRECOVERABLE_GPU_ERROR`, `SILENT_DATA_CORRUPTION`, `PERFORMANCE`, or `CHIP_ERROR` for TPUs |
110
+
111
+ Tell gpu-health where each node runs:
112
+
113
+ ```json
114
+ { "platform": "aws",
115
+ "nodesFrom": "nodes.json",
116
+ "platforms": { "aws": { "autoRepair": true } } }
117
+ ```
118
+
119
+ - `nodesFrom`: a `kubectl get nodes -o json` file. Each node's `spec.providerID` (`aws:///us-east-1a/i-0abc…`, `gce://project/zone/name`) gives its platform, instance, zone and project. GKE nodes (with `cloud.google.com/gke-*` labels) get `gke`.
120
+ - `nodes.<name>`: `{ platform, instance, zone, project }` set by hand. These entries win over `nodesFrom`.
121
+ - `platformByNode`: `{ "regex": "aws" }`, for mixed fleets.
122
+ - `platform`: the default for every node.
123
+ - `autoRepair: true`: use this when the cloud repairs nodes itself (EKS node auto repair with the node monitoring agent, or GKE node auto-repair). Reboot and replace then become notes that say what the cloud will do, so gpu-health and the cloud don't both act on one node.
124
+
125
+ Executors can use `{instance}`, `{zone}` and `{project}`. A platform's executors win over the vendor's. Device actions (`gpu-reset`, power caps) stay the vendor's.
126
+
99
127
  ## Flakiness
100
128
 
101
129
  ```json
@@ -1,17 +1,20 @@
1
1
  {
2
2
  "name": "gpu-health",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "GPU health checks, efficiency and savings analysis, and an approval queue that runs fixes once approved.",
7
7
  "type": "module",
8
- "bin": { "gpu-health": "tools/gpu-health.mjs" },
8
+ "bin": {
9
+ "gpu-health": "tools/gpu-health.mjs"
10
+ },
9
11
  "scripts": {
10
12
  "test": "node --test tests/*.test.mjs",
11
13
  "demo": "node tools/gpu-health.mjs demo",
12
- "serve": "node tools/gpu-health.mjs serve"
14
+ "serve": "node tools/gpu-health.mjs serve",
15
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude='tests/**' --test-coverage-exclude='../**' --test-coverage-lines=93 --test-coverage-branches=80 tests/*.test.mjs"
13
16
  },
14
17
  "engines": {
15
- "node": ">=20"
18
+ "node": ">=22"
16
19
  }
17
20
  }
@@ -14,6 +14,9 @@ import { run } from './executors.mjs';
14
14
  import { ladderFor, supports, noun } from './vendors.mjs';
15
15
 
16
16
  const OPEN = new Set(['proposed', 'approved', 'suggested']);
17
+ // what an external remediator already does for a node: quarantine, drain, diagnose, repair, release
18
+ const DEFERRED = new Set(['quarantine', 'release', 'run-diag', 'deep-diag-next-boundary', 'gpu-reset', 'node-reboot', 'fabric-restart', 'rma', 'reseat', 'config-reset', 'firmware-align', 'drain-inference', 'swap-at-checkpoint', 'drain-replica', 'restart-without-node', 'avoid-large-jobs', 'cordon-node', 'uncordon-node']);
19
+ const ladderKinds = cfg => new Set([cfg.ladder || {}, ...Object.values(cfg.vendors || {}).map(v => (v && v.ladder) || {})].flatMap(l => Object.values(l).flat()).filter(x => typeof x === 'string'));
17
20
  const DISRUPTIVE = new Set(['gpu-reset', 'node-reboot', 'fabric-restart', 'reclaim-idle', 'scale-in', 'resize', 'swap-at-checkpoint', 'drain-inference', 'release', 'repartition', 'drain-replica', 'rollback-change', 'restart-without-node']);
18
21
 
19
22
  // Candidate actions from an analysis.
@@ -34,8 +37,8 @@ export function suggest(analysis, cfg) {
34
37
  if (h.breaker) add({ kind: 'exporter-check', target: 'fleet', reason: `${h.staleCount} of ${h.fleet} GPUs stopped reporting at once; checking monitoring before quarantining anything`, severity: 'high' });
35
38
  for (const node of h.nodesThin || []) add({ kind: 'exporter-check', node, target: `node:${node}`, reason: `every GPU on ${node} is reporting patchily: check the node's exporter and network before suspecting the GPUs`, severity: 'medium' });
36
39
  for (const g of Object.values(h.gpus)) {
37
- const k = g.key, cls = g.faultClass || 'default', ladder = ladderFor(cfg, g.vendor, cls);
38
- const base = { node: g.node, gpu: g.gpu, vendor: g.vendor || undefined, target: k, since: g.since, evidence: (g.signals || []).map(s => s.why) };
40
+ const k = g.key, cls = g.faultClass || 'default', ladder = ladderFor(cfg, g.vendor, cls, g.node);
41
+ const base = { node: g.node, gpu: g.gpu, vendor: g.vendor || undefined, faultClass: g.faultClass || undefined, target: k, since: g.since, evidence: (g.signals || []).map(s => s.why) };
39
42
  const jobs = jobsOn(k);
40
43
  if (g.state === 'quarantined') {
41
44
  add(Object.assign({}, base, { kind: 'quarantine', reason: g.why, severity: 'high' }));
@@ -82,9 +85,19 @@ export function suggest(analysis, cfg) {
82
85
  add(a);
83
86
  }
84
87
  for (const p of analysis.partitionPlan || []) if (p.gpusNeeded < p.gpusNow) add({ kind: 'repartition', target: `partition:${p.sku}`, reason: `pack fractional jobs on ${p.gpusNeeded} ${p.sku} GPU(s) instead of ${p.gpusNow}: ${p.layout.join(' | ')}`, severity: 'low' });
88
+ // a node another system (NVSentinel) is remediating gets no second repair ladder: its repair, drain and diag actions
89
+ // become one informational action, so the two never cordon, drain or reset the same node twice
90
+ const ext = cfg.deferToExternal === false ? {} : (analysis.external || {}), handled = a => a.node && (ext[`${a.node}/${a.gpu}`] || ext[a.node]);
91
+ const kept = [];
92
+ for (const a of out) {
93
+ const h = handled(a);
94
+ if (!h || !DEFERRED.has(a.kind) && !ladderKinds(cfg).has(a.kind)) { kept.push(a); continue; }
95
+ kept.push({ kind: 'external-remediation', node: a.node, gpu: ext[`${a.node}/${a.gpu}`] ? a.gpu : undefined, target: `external:${ext[`${a.node}/${a.gpu}`] ? `${a.node}/${a.gpu}` : a.node}`, severity: a.severity,
96
+ reason: `${h.by} is remediating ${a.node} (${h.check}${h.action ? `, ${h.action}` : ''}): gpu-health would have proposed ${a.kind} (${a.reason})`, evidence: a.evidence || [], deferred: a.kind });
97
+ }
85
98
  // drop what the device's platform can't do (no GPU reset on Cloud TPU, …), then de-duplicate by kind + target
86
99
  const seen = new Map();
87
- for (const a of out.filter(a => supports(cfg, a.vendor, a.kind))) {
100
+ for (const a of kept.filter(a => supports(cfg, a.vendor, a.kind, a.node))) {
88
101
  a.id = `${a.kind}:${a.target}`;
89
102
  const s = seen.get(a.id);
90
103
  if (!s) { seen.set(a.id, a); continue; }
@@ -42,6 +42,9 @@ export function analyze({ samples, jobs = [], steps = [], probes = [], results =
42
42
  jobUsage: jobStats.map(js => ({ job: js.job.id, class: js.job.class, owner: js.job.owner || '', gpus: js.gpus.length, sku: js.sku, usage: js.cls, usageText: CLASS_TEXT[js.cls],
43
43
  tensorP50: js.st.tensorP50, smP50: js.st.smP50, dramP50: js.st.dramP50, effP50: js.st.effP50, effP95: js.st.effP95, memPeakGB: js.st.memPeakGB, memTotalGB: js.st.memTotalGB, memSource: js.st.memSource, hours: js.st.hours })),
44
44
  };
45
+ // nodes (or GPUs) another system is remediating now: { 'node' | 'node/gpu': { by, action, check, t } }
46
+ analysis.external = Object.fromEntries(results.filter(r => r.kind === 'external-remediation' && r.t <= now && now - r.t <= 24 * 3600).sort((a, b) => a.t - b.t)
47
+ .map(r => [r.gpu != null ? `${r.node}/${r.gpu}` : r.node, { by: r.by, action: r.action, check: r.check, t: r.t }]));
45
48
  analysis.suggestions = suggest(analysis, cfg);
46
49
  return analysis;
47
50
  }
@@ -54,6 +54,8 @@ export const DEFAULTS = {
54
54
  },
55
55
  diagLevelByClass: { ecc: 3, bus: 3, link: 3, firmware: 2, pcie: 2, thermal: 3, slow: 3, stale: 1, power: 3, telemetry: 2, sdc: 4, platform: 3, default: 2 },
56
56
  // What may happen without a person. auto = executes at once; approve = queued for approval; never = suggestion only.
57
+ // Defer to an external remediator (NVSentinel) for nodes it is already handling: no second repair ladder
58
+ deferToExternal: true,
57
59
  policy: {
58
60
  dryRun: true, // commands run only with this false AND --live
59
61
  limits: { maxQuarantineShare: 0.1, minQuarantinePerRun: 2, maxNodeRebootsPerRun: 1, maxNodeCordonsPerRun: 2, maxScaleOutStep: 4, maxActionAgeSec: 3600 },
@@ -65,6 +67,7 @@ export const DEFAULTS = {
65
67
  'reclaim-idle': 'approve', 'scale-in': 'approve', 'resize': 'approve',
66
68
  'deep-diag-next-boundary': 'auto', 'avoid-large-jobs': 'approve', 'label-capability': 'approve', 'repartition': 'approve',
67
69
  'swap-at-checkpoint': 'approve', 'drain-inference': 'approve',
70
+ 'external-remediation': 'never', // another system (NVSentinel) is remediating this node: shown, never run
68
71
  // used by the fleetops live agent: stopping new work on a node and telling people is automatic; anything that
69
72
  // moves running work, adds cost or undoes a change waits for a person (see fleetops examples/agent-policy.realtime.json)
70
73
  'cordon-node': 'auto', 'uncordon-node': 'approve', 'link-check': 'auto', 'hold-rollout': 'auto',
@@ -5,8 +5,9 @@
5
5
  // commands without running them.
6
6
  import { spawnSync } from 'node:child_process';
7
7
  import { executorFor } from './vendors.mjs';
8
+ import { nodeVars } from './platforms.mjs';
8
9
 
9
- export const SAFE = /^[A-Za-z0-9][A-Za-z0-9._:\/=-]{0,252}$/;
10
+ export const SAFE = /^[A-Za-z0-9][A-Za-z0-9._:/=-]{0,252}$/;
10
11
 
11
12
  export function fill(template, vars) {
12
13
  return template.map(arg => arg.replace(/\{(\w+)\}/g, (_, k) => {
@@ -18,7 +19,7 @@ export function fill(template, vars) {
18
19
  }));
19
20
  }
20
21
 
21
- export const varsOf = a => Object.assign({ node: a.node, gpu: a.gpu, job: a.job, vendor: a.vendor, reason: a.reasonCode }, a.params || {});
22
+ export const varsOf = (a, cfg) => Object.assign({ node: a.node, gpu: a.gpu, job: a.job, vendor: a.vendor, reason: a.reasonCode }, nodeVars(cfg, a.node, a), a.params || {});
22
23
 
23
24
  export function message(a, howTo) {
24
25
  const target = [a.job && `job ${a.job}`, a.node && `${a.node}${a.gpu != null ? '/' + (a.vendor && a.vendor !== 'nvidia' && a.vendor !== 'amd' ? 'dev' : 'gpu') + a.gpu : ''}`].filter(Boolean).join(' on ');
@@ -26,11 +27,15 @@ export function message(a, howTo) {
26
27
  }
27
28
 
28
29
  export function plan(a, cfg) {
29
- const t = executorFor(cfg, a.vendor, a.kind);
30
+ const t = executorFor(cfg, a.vendor, a.kind, a.node);
30
31
  if (!t) throw new Error(`no executor configured for ${a.kind}${a.vendor ? ` (${a.vendor})` : ''}`);
31
32
  if (t === 'webhook') return { webhook: true, text: message(a) };
32
33
  if (t.webhook) return { webhook: true, text: message(a, t.webhook) }; // a step a person does: post what to do
33
- return { commands: t.map(argv => fill(argv, varsOf(a))) };
34
+ try { return { commands: t.map(argv => fill(argv, varsOf(a, cfg))) }; } catch (e) {
35
+ // a cloud executor needs the instance: say where it comes from
36
+ if (/\{(instance|zone|project)\}/.test(e.message)) throw new Error(`${e.message} for ${a.node}: set nodes.${a.node}.${e.message.match(/\{(\w+)\}/)[1]} in the config, or nodesFrom: a \`kubectl get nodes -o json\` file (its spec.providerID)`);
37
+ throw e;
38
+ }
34
39
  }
35
40
 
36
41
  const isLark = u => /(feishu\.cn|larksuite\.com|larkoffice\.com)/.test(u);
@@ -240,7 +240,7 @@ export function assessHealth({ samples, probes = [], results = [], jobs = [], pr
240
240
  const d = latestResult(results, k, p.since, ['diag']);
241
241
  if (d && d.pass) go('burnin', p.faultClass, `diag level ${d.level || '?'} passed; burn-in next`);
242
242
  else if (d && !d.pass) {
243
- const ladder = ladderFor(cfg, r.vendor, p.faultClass);
243
+ const ladder = ladderFor(cfg, r.vendor, p.faultClass, r.node);
244
244
  r.ladderStep = Math.min((p.ladderStep || 0) + 1, ladder.length - 1);
245
245
  r.state = ladder[r.ladderStep] === 'rma' ? 'rma' : 'remediate'; r.since = now; r.why = `diag failed${d.detail ? ': ' + d.detail : ''}; next step ${ladder[r.ladderStep]}`;
246
246
  r.history = [...(p.history || []), { t: now, state: r.state, why: r.why }].slice(-20);