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
@@ -0,0 +1,250 @@
1
+ # Shadow upgrades
2
+
3
+ Measure an infra change before it ships, and keep measuring the baseline so drift is caught. The change can be new
4
+ GPUs, an engine version or its configuration, networking, topology, or the serving layout.
5
+
6
+ ```
7
+ fleetops shadow plan --baseline-config h100.json --candidate-config b200.json --trace sessions.jsonl --rps 4 --out plan.json
8
+ fleetops shadow replay --trace sessions.jsonl --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live
9
+ fleetops shadow answers --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live --out answers.json
10
+ fleetops shadow compare --baseline variant=baseline,source=shadow-replay --candidate variant=candidate,source=shadow-replay \
11
+ --plan plan.json --answers answers.json --baseline-gpus 8 --baseline-rate 2.5 --candidate-gpus 8 --candidate-rate 5
12
+ fleetops shadow baseline save --name chat --select pool=chat --from 2026-11-01 --to 2026-11-08
13
+ fleetops shadow watch --name chat --select pool=chat --from 2026-11-24
14
+ fleetops shadow demo # a candidate that looks faster and isn't
15
+
16
+ # from a canary's own metrics (vLLM in Prometheus), and as the judge inside Argo Rollouts and Flagger
17
+ fleetops shadow prom --prom http://prometheus:9090 --select 'namespace="llm"' --baseline 'llm_isvc_name="chat-v1"' \
18
+ --candidate 'llm_isvc_name="chat-v2"' --lookback 3600 --baseline-lookback 21600
19
+ fleetops shadow serve --prom http://prometheus:9090 --host 0.0.0.0 --no-auth # deploy/shadow-gate/ has the manifests
20
+ fleetops shadow prom --demo # a canary that looks 20% faster per version and is 8% slower
21
+ ```
22
+
23
+ ## Architecture
24
+
25
+ ```mermaid
26
+ flowchart LR
27
+ change["Infra change<br/>GPUs · config · network · topology · serving"] --> plan
28
+ plan["plan<br/>predict the effect (Inference Sizer)<br/>size the test"] --> arms
29
+ subgraph arms["Compare three ways"]
30
+ live["Live<br/>a canary's per-version metrics (Prometheus)<br/>or engine traces of a mirrored pool"]
31
+ replay["Replay<br/>the same sessions sent to both endpoints"]
32
+ history["History<br/>this window against a saved baseline"]
33
+ end
34
+ arms --> match["Match the load<br/>calls in flight · prompt length · cache hit"]
35
+ match --> checks
36
+ subgraph checks["Check four things"]
37
+ speed["Speed: TTFT, TPOT, end-to-end"]
38
+ answers["Same answers: greedy tokens, log-probs"]
39
+ infra["Infra signals: NCCL, power, faults"]
40
+ cost["Cost: tokens/s per GPU, $ per M tokens"]
41
+ end
42
+ checks --> verdict["Verdict<br/>promote · roll back · extend · recalibrate"]
43
+ verdict --> store[("Baseline store<br/>verdicts, baselines, calibration")]
44
+ verdict --> ctl["Rollout controllers<br/>Argo Rollouts analysis · Flagger webhooks"]
45
+ store --> history
46
+ store -. calibrates .-> plan
47
+ ```
48
+
49
+ The same design is on the team whiteboard: *Shadow upgrades for AI infra*.
50
+
51
+ ### Components
52
+
53
+ | Piece | Code | Reads | Writes |
54
+ | --- | --- | --- | --- |
55
+ | Plan | `shadow.mjs` `plan`, `predict`, `testSize` | two Inference Sizer configs `{ model, gpu, tp, gpus?, rate? }`; a workload (trace, profile, or request records) | `plan.json`: predicted effects, requests per arm |
56
+ | Replay | `shadow-replay.mjs` `requestsFrom`, `run` | a trace or an agentic profile (FleetScope); two OpenAI-compatible endpoints | `request` records with `variant` and `pair`, in the store |
57
+ | Same answers | `shadow-replay.mjs` `answers` | a prompt set (built-in or a file); the two endpoints | `answers.json` |
58
+ | Compare | `shadow.mjs` `compare`, `effect`, `judge` | request records for each arm (store selectors or a results file); plan, answers, infra | a verdict; one line in `<store>/shadow/verdicts.jsonl` |
59
+ | Infra signals | `shadow.mjs` `infraSignals` | the store's `collective`, `device` and `log` records for each arm's nodes | part of the verdict |
60
+ | Baselines and watch | `shadow.mjs` `makeBaseline`, `drift` | request records of a service | `<store>/shadow/baselines/NAME.jsonl` (each save a version), `watch-NAME.jsonl` |
61
+ | Canary metrics | `shadow-prom.mjs` `queries`, `fetchArms`, `compareWindows` | Prometheus `query_range`: vLLM's per-version histograms and gauges, selected by label matchers | a verdict per canary; `verdicts.jsonl`; `--save` keeps the series |
62
+ | The judge | `shadow-gate.mjs` `gateServer` | HTTP calls from Argo Rollouts (`POST /verdict`) and Flagger (`/flagger/rollout`, `/flagger/confirm-promotion`) | `promote` / `rollback` / `wait`; `<store>/shadow/gate.jsonl` |
63
+
64
+ It is built on what fleetops already has:
65
+ - the data store and its `request` kind, filled from engine traces with `fleetops data import otlp-traces FILE --derive`;
66
+ - the collectors, for infra signals;
67
+ - FleetScope's trace readers and agentic profiles, for replay workloads;
68
+ - the Inference Sizer, for the prediction;
69
+ - `rollout`, which judges node-level versions (drivers, firmware) on failure rates. Shadow judges serving performance.
70
+
71
+ ### Where the arms come from
72
+
73
+ - **Replay** is the cleanest comparison. Each recorded request goes to both endpoints at the same moment with one
74
+ `pair` id, so the comparison uses per-request ratios. Those cancel request-to-request spread and need several times
75
+ fewer requests.
76
+ - Prompts are synthetic text of the recorded length.
77
+ - Requests of one session repeat the previous prompt and append, so the engine's prefix cache sees the session's real
78
+ reuse.
79
+ - Output length is held to the recorded one (`max_tokens`, plus vLLM's `ignore_eos` unless `--no-exact-output`).
80
+ - **Live** compares two versions serving production traffic: a canary split, or a mirrored shadow pool. The traffic
81
+ differs between the arms, so the comparison matches load. Two sources:
82
+ - **the canary's own metrics** (`shadow prom`, and the judge `shadow serve`): vLLM's per-version series in Prometheus,
83
+ in windows of one step each (below);
84
+ - **engine traces** of each pool (`fleetops data import otlp-traces --derive`), per request (`shadow compare`).
85
+ - **History** compares a window of a service with a saved baseline sample of the same service, at matched load.
86
+
87
+ ## The statistics
88
+
89
+ - **Matched load.**
90
+ - Every request is put in a stratum by the load it met:
91
+ - calls in flight in its own arm when it started, in half-powers of two: 1, 2, 3, 4, 6, 8, 11, 16…;
92
+ - prompt length, in powers of two;
93
+ - cache hit: under 50%, 50–90%, over 90%;
94
+ - for end-to-end time only, output length too.
95
+ - In each stratum both arms reach with at least 5 requests, the effect is log(median candidate) − log(median baseline).
96
+ - The strata are weighted by their traffic in both arms.
97
+ - The report gives the share of baseline requests that found a matching stratum. When the arms ran at very different
98
+ loads it is low, and the report says so.
99
+ - **Paired.** When at least half the requests carry a pair id on both arms, the effect is the median per-request log
100
+ ratio.
101
+ - **Confidence intervals.** By bootstrap: 400 resamples, of requests within strata or of pairs.
102
+ - **Verdict per metric, against a gate** (default ±5% for TTFT, TPOT, end-to-end):
103
+ - *worse*: the interval lies wholly above +gate;
104
+ - *better*: wholly below −gate;
105
+ - *same*: wholly inside ±gate;
106
+ - *inconclusive* otherwise, with an estimate of how many more requests per arm would settle it.
107
+ - **Errors.** A two-proportion test; worse when the rate rises by more than half a point and p < 0.05.
108
+ - **Decision.**
109
+ - *roll back*: answers differ, or anything is worse;
110
+ - *extend the test*: anything is inconclusive;
111
+ - *promote*: otherwise.
112
+ - The prediction is checked separately. When it's off by more than 15% on any metric, the verdict says to recalibrate
113
+ the sizer for this change, because then the model of the change is what's wrong, whichever way the change went.
114
+ - **Test size.** Requests per arm for a relative effect δ (two-sided α = 0.05, power 0.8):
115
+ - unpaired: n = 2(1.96 + 0.84)²σ²/ln(1+δ)², with σ the spread of log TTFT;
116
+ - paired: the same with σ shrunk to about 35%, the usual spread of a per-request ratio.
117
+
118
+ The comparison most dashboards make, all requests and no load matching, is shown beside every effect as *naive*. In the
119
+ demo, a candidate 8% slower at any load got less than half the traffic. Naively it looks 7.5% faster on TPOT; matched
120
+ on load it is 7.8% slower (+6.5% to +9.3%), and the decision is to roll back.
121
+
122
+ ### From a canary's own metrics
123
+
124
+ A canary's versions see different load. One at a small weight, or with more replicas than its weight needs, runs at
125
+ lower load per engine and looks faster than it is. Prometheus has no per-request records, but it has windows: each step
126
+ of each version carries its load and its mean latencies, from vLLM's own metrics.
127
+
128
+ | Per window | From |
129
+ | --- | --- |
130
+ | requests, TTFT, TPOT, end-to-end (means) | `increase()` of `vllm:e2e_request_latency_seconds`, `vllm:time_to_first_token_seconds`, `vllm:request_time_per_output_token_seconds` (else `vllm:inter_token_latency_seconds`) `_sum` / `_count` |
131
+ | calls in flight per engine | `vllm:num_requests_running` + `vllm:num_requests_waiting`, averaged over engines |
132
+ | prompt and output length | `vllm:prompt_tokens_total`, `vllm:generation_tokens_total` per request |
133
+ | prefix-cache hit | `vllm:prefix_cache_hits_total` / `vllm:prefix_cache_queries_total` |
134
+ | errors | `vllm:request_success_total{finished_reason=~"abort|error"}` (client aborts count: a timeout is a failure the user saw) |
135
+
136
+ The versions are named by label matchers: `llm_isvc_name` for llm-d's controlled deployments, the pod-template hash for
137
+ Argo Rollouts, the `app` label for Flagger (`deploy/shadow-gate/podmonitor-vllm.yaml` copies all three onto the
138
+ metrics). Matchers are checked as matchers before a query is built, so nothing else can be put into a query.
139
+
140
+ **Matching.** The baseline's latency is fitted as a function of load on its own windows: for each canary window, a
141
+ local linear fit (LOESS) of the baseline's log latency around that window's calls in flight per engine, weighted by
142
+ distance and by requests, with prompt length and cache hit (and output length for end-to-end time) as linear terms.
143
+ The canary window is compared with what the baseline shows at the canary's own load; the effect is the request-weighted
144
+ mean of those log ratios. Canary windows outside the baseline's load range (its 2nd–98th percentile) are left out, never
145
+ extrapolated, and the report gives the share of canary traffic that was inside. The interval comes from resampling
146
+ windows of both versions and fitting again. The baseline's response to load is learned from a longer history
147
+ (`--baseline-lookback`, six hours by default for the judge) than a short canary has.
148
+
149
+ Local fits matter: a single curve for the whole range missed the latency knee near saturation and put an identical
150
+ canary 4.6% slower. On synthetic canaries (identical, 3%, 8% and 12% slower; at half and a quarter of the baseline's
151
+ load; a smooth latency curve and one with a knee) the effect lands within 1 point of the truth, where per-version means
152
+ say the canary is 20–33% faster.
153
+
154
+ Too little canary traffic gives no verdict: at least 5 windows and 200 requests inside the baseline's range. Until then
155
+ the answer is *wait*.
156
+
157
+ ### Inside Argo Rollouts and Flagger
158
+
159
+ `fleetops shadow serve` runs the judge as a service (`deploy/shadow-gate/judge.yaml`). It never changes a rollout; the
160
+ controller does what the verdict says.
161
+
162
+ | Controller | How it calls the judge | promote | rollback | wait |
163
+ | --- | --- | --- | --- | --- |
164
+ | Argo Rollouts | `AnalysisTemplate` web metric, `POST /verdict` with `{ select, baseline, candidate, lookback }`, `jsonPath: {$.verdict}` (`argo-analysistemplate.yaml`, `argo-rollout-example.yaml`) | measurement succeeds | measurement fails; `failureLimit: 0` aborts the rollout | inconclusive; ten in a row leave the rollout paused for a person |
165
+ | Flagger | `rollout` webhook (`/flagger/rollout`) and `confirm-promotion` webhook (`/flagger/confirm-promotion`), versions in `metadata` (`flagger-canary.yaml`) | 200 on both | 412 on `rollout`: a failed check, `threshold` of them roll back | 200 on `rollout`, 412 on `confirm-promotion`: the promotion waits |
166
+ | llm-d controlled deployments, scripts | `GET /verdict?baseline=llm_isvc_name="v1"&candidate=llm_isvc_name="v2"` | | | |
167
+
168
+ Prometheus unreachable is an HTTP 502, which Argo counts as a measurement error (`consecutiveErrorLimit: 3`), not as a
169
+ verdict. Flagger webhooks can't send a token, so the judge runs without one behind a NetworkPolicy that admits only the
170
+ controllers' namespaces; with Argo alone, `--tokens` works too. The manifests are checked in CI against the real CRD
171
+ schemas of Argo Rollouts v1.10.2, Flagger v1.45.0 and Prometheus Operator v0.95.2.
172
+
173
+ ### An llm-d canary, stepped by the judge
174
+
175
+ `fleetops shadow canary` drives an llm-d canary: two LLMInferenceServices (KServe v1alpha2) in one routing group, each
176
+ member's share set by `spec.router.route.weight` (proportional, up to 1,000,000). Example manifests are in
177
+ `deploy/shadow-gate/llmd-canary-example.yaml`.
178
+
179
+ | Command | What it does |
180
+ | --- | --- |
181
+ | `canary start --name N --namespace NS --group G --baseline ISVC --candidate ISVC [--steps 1,5,25,50,100] --live` | Writes the first weights (1% to the candidate). Without `--live` it prints the `kubectl patch` commands and starts nothing |
182
+ | `canary advance --name N --prom URL \| --judge URL --live` | Asks the judge about the traffic since the last weight change |
183
+ | `canary approve --name N --by NAME` | A person approves the queued step |
184
+ | `canary status --name N` | Where the canary stands, and its history |
185
+
186
+ What `advance` does with the judge's answer:
187
+ - **rollback:** the candidate's weight goes to 0 at once, with `--live`. Stopping is always allowed.
188
+ - **wait:** nothing changes.
189
+ - **promote:** the next step is **queued for a person**. The next `advance --live` writes it only after `approve --by NAME`.
190
+ Raising a canary's share is never automatic, and each step bakes at least `--bake` seconds (600) first.
191
+
192
+ Weights are written with `kubectl patch --type merge` on `spec.router.route`, so nothing else on the resources changes.
193
+ Tests check the manifests and every patch against KServe's own CRD schema.
194
+
195
+ ### What a verdict teaches the other tools
196
+
197
+ `shadow plan` records the configs it predicted for. With `--plan`, `compare` and `prom` compare that prediction with the
198
+ measurement.
199
+ - **The prediction was off by more than 15%:** the candidate's sizer efficiencies are refitted until the sizer predicts
200
+ what was measured.
201
+ - TPOT is refitted through the decode efficiencies, then TTFT through prefill. Measurements are relative, so the
202
+ baseline is taken as calibrated, and only settled metrics are used.
203
+ - The result goes into `<store>/calibration/sizer.json` (and a `calibration` record), in the profile format that
204
+ `fleetops calibrate` writes. Three readers use it:
205
+ - `shadow plan` (its next prediction for that GPU and model);
206
+ - `inference-sizer --calibration`;
207
+ - `harness-ledger economics --calibration`, so the self-host vs API break-even uses measured efficiencies.
208
+ - What efficiencies can't explain is reported as a model gap, not fitted.
209
+ - **The decision is promote:** the change's measured effects (and tokens/s per GPU, when GPUs are given) are appended to
210
+ `<store>/shadow/promoted.jsonl`.
211
+
212
+ ### On real engines
213
+
214
+ `deploy/shadow-live/` runs everything on three 1-GPU L4 nodes: two vLLM versions differing by one known change
215
+ (prefix caching off), paired replay of agent sessions, an in-cluster canary judged from Prometheus, and the judge called
216
+ as Argo calls it. See its README. It has not been run yet.
217
+
218
+ ## Same answers
219
+
220
+ Speed gates miss numerics changes. A new kernel, FP8, a different tensor-parallel layout or an engine upgrade can
221
+ change outputs. `shadow answers` runs greedy decoding with log-probabilities on a fixed prompt set against both arms.
222
+ It reports:
223
+ - the share of prompts with identical tokens;
224
+ - where the first divergence falls;
225
+ - how far the log-probabilities of the shared tokens moved.
226
+
227
+ Fewer than 98% identical, or a mean log-prob drift over 0.05, is "different", and the decision is roll back however fast
228
+ the candidate is. Some changes are expected to alter outputs, such as a new quantization. For those, set
229
+ `--gates gates.json` with `{ "answers": { "match": 0.9 } }` and check quality separately.
230
+
231
+ ## Safety
232
+
233
+ - `replay` and `answers` send nothing without `--live`. Without it they print what they would send: requests, sessions,
234
+ tokens and duration.
235
+ - Only model calls are sent. Nothing else a recorded agent did (tool calls, writes) is repeated.
236
+ - API keys come from an environment variable named with `--api-key-env`, never from the command line.
237
+ - `--max-inflight` (64) bounds the load on each endpoint, and `--max-requests` (1,000) the length of a run.
238
+ - `shadow canary` writes weights only with `--live`. A rollback is written at once; a step up only after a person's
239
+ `approve --by NAME`. The tests never approve.
240
+ - `shadow prom` and `shadow serve` only read Prometheus. `FLEETOPS_EGRESS_ALLOW` limits which hosts they may call; the
241
+ judge's manifest allows the in-cluster Prometheus and nothing else.
242
+
243
+ ## Limits
244
+
245
+ - Mirrored live traffic doesn't share the baseline's KV cache, so cache-hit effects need replay.
246
+ - New hardware needs a candidate pool to replay against or to mirror to.
247
+ - Small effects (2–3%) need thousands of requests even paired. `plan` says how many before you start.
248
+ - Prometheus windows give means per step, not per-request distributions: tails (p95, p99) are shown but not judged.
249
+ - The demo and the tests use synthetic arms, mock endpoints and a mock Prometheus. Nothing here has been run against two
250
+ live engines yet; `deploy/shadow-live/` is the kit for that.
@@ -14,12 +14,15 @@ step it saw exporter counters, job outcomes and serving metrics. It now also see
14
14
  | `auto` | any of the files below | recognized by content (`fleetops data import auto FILE…`); a bundle from `tools/collect.sh` is imported with `data import bundle` ([TUNE.md](TUNE.md)) |
15
15
  | `requests` | gateway or proxy request logs: LiteLLM, OpenAI-style usage, OTLP gen_ai spans, CSV of t, isl, osl, ttft, e2e | `request` (token counts and latencies only) |
16
16
  | `kernel-log` | `journalctl -k -o short-iso`, `dmesg -T` (`--utc-offset`), `dmesg` (`--boot`), syslog (`--year`) | `log` |
17
- | `app-log` | NCCL / PyTorch job output, optionally `kubectl logs --timestamps` | `log` |
17
+ | `app-log` | NCCL, RCCL or PyTorch job output (CUDA or HIP errors), optionally `kubectl logs --timestamps` | `log` |
18
18
  | `nvidia-smi-q` | `nvidia-smi -q` | `inventory` with versions, GPU serials, UUIDs and the PCI → GPU map |
19
19
  | `nvidia-topo` | `nvidia-smi topo -m` | `topology`: NVLink pairs, GPU ↔ NIC PCIe path |
20
+ | `cloud-monitoring` | Google Cloud Monitoring `timeSeries.list` JSON: `kubernetes.io/node/accelerator/*` on GKE, or TPU VM accelerator metrics | `device`: duty cycle (SM), TensorCore utilization, memory bandwidth, memory used and total; GPU or TPU from the metric's `make` |
21
+ | `amd-smi-static` | `amd-smi static --json` (`--rocm V`) | `inventory` with driver, IFWI (VBIOS) per GPU, ROCm, power limit and the PCI → GPU map |
22
+ | `amd-smi-topology` | `amd-smi topology --json` (both layouts amd-smi has shipped) | `topology`: XGMI links and PCIe peer links with hops |
20
23
  | `ibnetdiscover` | `ibnetdiscover` | `topology`: host → leaf → spine |
21
24
  | `racks` | CSV `node,rack,row,pdu,site` | `topology` |
22
- | `k8s-nodes` | `kubectl get nodes -o json` | `inventory` with versions (GPU feature discovery labels, node info); rack/zone edges |
25
+ | `k8s-nodes` | `kubectl get nodes -o json` | `inventory` with versions (GPU feature discovery labels, node info), the cloud instance, zone and project from `spec.providerID`, and the GPU from the instance type when there are no GPU labels; rack/zone edges; `log` records for hardware conditions (the EKS node monitoring agent's `AcceleratedHardwareReady=False` with its XID, node-problem-detector conditions) and for GKE's scheduled host maintenance (`cloud.google.com/scheduled-maintenance-time`, a planned event) |
23
26
  | `slurm-nodes` | `scontrol show node -o` | `inventory` with the kernel version |
24
27
  | `k8s-events` | `kubectl get events -A -o json` | `change` (cordon, reboot, scaling) and `log` (NotReady, OOM, mount failures, evictions) |
25
28
  | `helm-history` | `helm history REL -n NS -o json` | `change` (one per revision) |
@@ -1,6 +1,6 @@
1
1
  # Workload Intelligence (first increment)
2
2
 
3
- Profile application-shaped inference demand and replay representative sessions through FleetScope. This module **does not** estimate GPU capacity itself; it generates requests and measurements that existing capacity tools can consume. Requires Node.js 20+.
3
+ Profile application-shaped inference demand and replay representative sessions through FleetScope. This module **does not** estimate GPU capacity itself; it generates requests and measurements that existing capacity tools can consume. Requires Node.js 22+.
4
4
 
5
5
  ## Try the six synthetic presets
6
6
 
@@ -1,15 +1,18 @@
1
1
  {
2
2
  "name": "fleetops",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Shared data layer, continuous calibration, root-cause analysis and safe optimization across the AIInfraTools utilities.",
7
7
  "type": "module",
8
- "bin": { "fleetops": "tools/fleetops.mjs" },
8
+ "bin": {
9
+ "fleetops": "tools/fleetops.mjs"
10
+ },
9
11
  "scripts": {
10
- "test": "node --test tests/*.test.mjs"
12
+ "test": "node --test tests/*.test.mjs",
13
+ "test:coverage": "node --test --experimental-test-coverage --test-coverage-exclude='tests/**' --test-coverage-exclude='../**' --test-coverage-lines=90 --test-coverage-branches=77 tests/*.test.mjs"
11
14
  },
12
15
  "engines": {
13
- "node": ">=20"
16
+ "node": ">=22"
14
17
  }
15
18
  }
@@ -46,7 +46,7 @@ export function ethtool(text, { node, iface = 'eth0', t = Math.floor(Date.now()
46
46
  if (!node) throw new Error('ethtool needs --node');
47
47
  const r = { t, switch: node, port: iface, nic: true, source: 'ethtool' };
48
48
  for (const line of String(text).split(/\r?\n/)) {
49
- const m = line.match(/^\s*([\w.\-]+):\s*(\d+)\s*$/); if (!m) continue;
49
+ const m = line.match(/^\s*([\w.-]+):\s*(\d+)\s*$/); if (!m) continue;
50
50
  const k = m[1], v = +m[2];
51
51
  if (/^(rx|tx)_prio\d+_pause$|^(rx|tx)_pause_ctrl_phy$|^(rx|tx)_global_pause$/.test(k)) add(r, 'pfcPause', v);
52
52
  else if (/^rx_discards_phy$|^tx_discards_phy$/.test(k)) add(r, 'xmitDiscards', v);
@@ -64,10 +64,17 @@ export function ethtool(text, { node, iface = 'eth0', t = Math.floor(Date.now()
64
64
 
65
65
  // The host side of an InfiniBand or RoCE port from sysfs: `grep -H . /sys/class/infiniband/*/ports/*/{counters,hw_counters}/*`,
66
66
  // one "PATH:VALUE" per line. counters/ are the standard IB port counters (data in 4-byte words, like perfquery);
67
- // hw_counters/ hold the RoCE congestion counters (CNPs, ECN marks) that ethtool -S does not show.
67
+ // hw_counters/ hold the RoCE congestion counters (CNPs, ECN marks) that ethtool -S does not show. On AWS, EFA devices
68
+ // (rdmap*, efa_*) sit in the same tree with their own hw_counters: SRD retransmits, retransmit timeouts (a network path
69
+ // change), impaired and unresponsive remote connections (Nitro v4 and later), and RDMA work-request errors
70
+ // (docs.aws.amazon.com/AWSEC2/latest/UserGuide/efa-working-monitor.html).
68
71
  const IBSYS = { symbol_error: 'symbolErrors', link_error_recovery: 'linkRecovery', link_downed: 'linkDowned', port_rcv_errors: 'rcvErrors', port_xmit_discards: 'xmitDiscards',
69
72
  port_xmit_wait: 'xmitWait', port_rcv_data: 'rxBytes', port_xmit_data: 'txBytes', np_cnp_sent: 'cnpSent', np_ecn_marked_roce_packets: 'ecnMarked', rp_cnp_handled: 'cnpHandled',
70
- out_of_buffer: 'outOfBuffer', local_ack_timeout_err: 'ackTimeouts', out_of_sequence: 'outOfSequence', packet_seq_err: 'packetSeqErrors' };
73
+ out_of_buffer: 'outOfBuffer', local_ack_timeout_err: 'ackTimeouts', out_of_sequence: 'outOfSequence', packet_seq_err: 'packetSeqErrors',
74
+ // EFA
75
+ tx_bytes: 'txBytes', rx_bytes: 'rxBytes', rx_drops: 'rxDrops', retrans_pkts: 'retransPkts', retrans_timeout_events: 'retransTimeouts',
76
+ impaired_remote_conn_events: 'impairedConns', unresponsive_remote_events: 'unresponsiveRemote', rdma_read_wr_err: 'rdmaErrors', rdma_write_wr_err: 'rdmaErrors' };
77
+ const EFA_ONLY = new Set(['retrans_pkts', 'retrans_timeout_events', 'impaired_remote_conn_events', 'unresponsive_remote_events', 'rdma_read_wr_err', 'rdma_write_wr_err', 'rx_drops']);
71
78
  export function ibSysfs(text, { node, t = Math.floor(Date.now() / 1000) } = {}) {
72
79
  if (!node) throw new Error('ib-sysfs needs --node');
73
80
  const by = new Map();
@@ -75,7 +82,9 @@ export function ibSysfs(text, { node, t = Math.floor(Date.now() / 1000) } = {})
75
82
  const m = line.match(/\/class\/infiniband\/([\w.-]+)\/ports\/(\d+)\/(?:hw_)?counters\/(\w+):\s*(\d+)\s*$/); if (!m) continue;
76
83
  const f = IBSYS[m[3]]; if (!f) continue;
77
84
  const k = `${m[1]}/${m[2]}`; if (!by.has(k)) by.set(k, { t, switch: node, port: k, nic: true, source: 'ib-sysfs' });
78
- by.get(k)[f] = /^port_(rcv|xmit)_data$/.test(m[3]) ? +m[4] * 4 : +m[4];
85
+ const r = by.get(k), v = /^port_(rcv|xmit)_data$/.test(m[3]) ? +m[4] * 4 : +m[4];
86
+ r[f] = f === 'rdmaErrors' ? (r[f] || 0) + v : v; // read and write errors add up
87
+ if (EFA_ONLY.has(m[3]) || /^(rdmap|efa_)/.test(m[1])) r.efa = true;
79
88
  }
80
89
  return [...by.values()];
81
90
  }
@@ -103,9 +112,12 @@ export function fabricProm(json, { map = {} } = {}) {
103
112
  }
104
113
 
105
114
  // How much each counter grew over [from, to] for one port, from its records (counters can reset: a drop restarts).
106
- export const COUNTERS = ['symbolErrors', 'linkRecovery', 'linkDowned', 'rcvErrors', 'xmitDiscards', 'fecUncorrected', 'xmitWait', 'pfcPause', 'ecnMarked', 'cnpSent', 'outOfBuffer', 'rxBytes', 'txBytes'];
107
- export const ERROR_COUNTERS = ['symbolErrors', 'linkRecovery', 'linkDowned', 'rcvErrors', 'xmitDiscards', 'fecUncorrected'];
108
- export const CONGESTION_COUNTERS = ['xmitWait', 'pfcPause', 'ecnMarked', 'cnpSent', 'outOfBuffer'];
115
+ export const COUNTERS = ['symbolErrors', 'linkRecovery', 'linkDowned', 'rcvErrors', 'xmitDiscards', 'fecUncorrected', 'xmitWait', 'pfcPause', 'ecnMarked', 'cnpSent', 'outOfBuffer', 'rxBytes', 'txBytes',
116
+ 'rxDrops', 'rdmaErrors', 'unresponsiveRemote', 'retransPkts', 'retransTimeouts', 'impairedConns'];
117
+ // EFA: dropped receives, failed RDMA work requests and unresponsive peers are errors; SRD retransmits, retransmit
118
+ // timeouts and impaired connections are the fabric pushing back (congestion or a bad path), as ECN and CNPs are on RoCE
119
+ export const ERROR_COUNTERS = ['symbolErrors', 'linkRecovery', 'linkDowned', 'rcvErrors', 'xmitDiscards', 'fecUncorrected', 'rxDrops', 'rdmaErrors', 'unresponsiveRemote'];
120
+ export const CONGESTION_COUNTERS = ['xmitWait', 'pfcPause', 'ecnMarked', 'cnpSent', 'outOfBuffer', 'retransPkts', 'retransTimeouts', 'impairedConns'];
109
121
  export function growth(records, from, to) {
110
122
  const rs = records.filter(r => r.t >= from && r.t <= to).sort((a, b) => a.t - b.t), out = { seconds: rs.length > 1 ? rs[rs.length - 1].t - rs[0].t : 0, samples: rs.length };
111
123
  for (const c of COUNTERS) {
@@ -1,14 +1,18 @@
1
1
  // Production sources: exporter scrapes, vLLM metrics, Kubernetes and Slurm inventory, job accounting, change feeds,
2
2
  // and gpu-health's own history. Each turns what a system already emits into data-layer records.
3
3
  import { createRequire } from 'node:module';
4
- import { samplesFromExporter } from '../../../gpu-health/src/ingest.mjs';
4
+ import { samplesFromExporter, samplesFromCloudMonitoring } from '../../../gpu-health/src/ingest.mjs';
5
+ import { cloudIdentity } from '../../../gpu-health/src/platforms.mjs';
5
6
  import { toEpoch } from './time.mjs';
6
7
 
7
8
  const require = createRequire(import.meta.url);
8
9
  const Cal = require('../../../fleetscope/src/calibrate.js');
10
+ const REG = require('../../../inference-sizer/src/accelerators.js');
9
11
 
10
12
  // DCGM, AMD or SambaNova exporter text → device samples (gpu-health's parser; the vendor is detected from metric names).
11
13
  export const exporterScrape = (text, opts = {}) => samplesFromExporter(text, opts).map(s => Object.assign(s, { source: opts.source || `exporter:${s.vendor}` }));
14
+ // Google Cloud Monitoring accelerator metrics (GKE nodes, TPU VMs) → device samples (gpu-health's parser)
15
+ export const cloudMonitoring = (json, opts = {}) => samplesFromCloudMonitoring(json, opts).map(s => Object.assign(s, { source: 'cloud-monitoring' }));
12
16
 
13
17
  // Two vLLM /metrics snapshots (or one with the window it covers) → one serving record for the pool.
14
18
  export function vllmSnapshot(text, { before, windowS, t, pool, model, gpu } = {}) {
@@ -30,8 +34,11 @@ export function promRange(json, { field, pool, label = 'model_name' } = {}) {
30
34
  return out;
31
35
  }
32
36
 
33
- const GPU_RESOURCES = { 'nvidia.com/gpu': ['nvidia', 'gpu'], 'amd.com/gpu': ['amd', 'gpu'], 'google.com/tpu': ['tpu', 'tpu'] };
34
- const SKU_LABELS = ['nvidia.com/gpu.product', 'amd.com/gpu.product-name', 'cloud.google.com/gke-tpu-accelerator', 'node.kubernetes.io/instance-type'];
37
+ // accelerator resources and product labels from the shared registry's vendor adapters
38
+ const GPU_RESOURCES = Object.assign({ 'google.com/tpu': ['tpu', 'tpu'] }, ...Object.entries(REG.VENDORS).map(([k, v]) => ({ [v.k8sResource]: [k, v.kind] })));
39
+ const SKU_LABELS = [...new Set(Object.values(REG.VENDORS).flatMap(v => v.productLabels).concat(['cloud.google.com/gke-tpu-accelerator', 'node.kubernetes.io/instance-type']))];
40
+ // spec.providerID → the cloud's own identity for the node (aws:///zone/i-…, gce://project/zone/name): see gpu-health/src/platforms.mjs
41
+ export { cloudIdentity };
35
42
  // `kubectl get nodes -o json` → inventory; `kubectl get pods -A -o json` → placements for pods that request accelerators.
36
43
  export function k8sNodes(json, { t = Math.floor(Date.now() / 1000) } = {}) {
37
44
  const j = typeof json === 'string' ? JSON.parse(json) : json;
@@ -46,11 +53,37 @@ export function k8sNodes(json, { t = Math.floor(Date.now() / 1000) } = {}) {
46
53
  const versions = { driver: ver('nvidia.com/cuda.driver-version.full', 'nvidia.com/cuda.driver'), cuda: ver('nvidia.com/cuda.runtime-version.full', 'nvidia.com/cuda.runtime'),
47
54
  firmware: lab('amd.com/gpu.firmware', 'nvidia.com/gpu.firmware'), kernel: info.kernelVersion, os: info.osImage, runtime: info.containerRuntimeVersion, kubelet: info.kubeletVersion };
48
55
  for (const k of Object.keys(versions)) if (!versions[k]) delete versions[k];
49
- return [{ t, node: n.metadata.name, vendor, kind, sku: SKU_LABELS.map(k => labels[k]).find(Boolean) || '', devices: +cap[res],
56
+ const itype = labels['node.kubernetes.io/instance-type'] || labels['beta.kubernetes.io/instance-type'], inst = REG.instanceOf(itype), cloud = cloudIdentity((n.spec || {}).providerID);
57
+ const sku = SKU_LABELS.filter(k => k !== 'node.kubernetes.io/instance-type').map(k => labels[k]).find(Boolean) || (inst && inst.chip) || itype || '';
58
+ return [{ t, node: n.metadata.name, vendor, kind, sku, devices: +cap[res],
50
59
  site: labels['topology.kubernetes.io/region'] || labels['topology.kubernetes.io/zone'] || '', rack: lab(...RACK_LABELS) || undefined,
60
+ ...(itype ? { instanceType: itype } : {}), ...(cloud ? { cloud } : {}),
51
61
  ...(Object.keys(versions).length ? { versions } : {}), source: 'kubernetes' }];
52
62
  });
53
63
  }
64
+ // Node conditions that report hardware trouble, as log records: the EKS node monitoring agent's AcceleratedHardwareReady,
65
+ // NetworkingReady, StorageReady and KernelReady (bad when False; the reason names the fault, e.g. NvidiaXID79Error),
66
+ // and node-problem-detector's conditions on any cloud (KernelDeadlock, ReadonlyFilesystem, … bad when True).
67
+ const STD_CONDITIONS = new Set(['Ready', 'MemoryPressure', 'DiskPressure', 'PIDPressure', 'NetworkUnavailable']);
68
+ const COND_CLASS = { AcceleratedHardwareReady: 'hardware', NetworkingReady: 'network', StorageReady: 'storage', KernelReady: 'node' };
69
+ export function k8sNodeConditions(json, { t: t0 = Math.floor(Date.now() / 1000) } = {}) {
70
+ const j = typeof json === 'string' ? JSON.parse(json) : json, out = [];
71
+ for (const n of j.items || []) for (const c of (n.status || {}).conditions || []) {
72
+ if (STD_CONDITIONS.has(c.type)) continue;
73
+ const bad = /Ready$/.test(c.type) ? c.status === 'False' : c.status === 'True';
74
+ if (!bad) continue;
75
+ const reason = String(c.reason || c.type), xid = reason.match(/NvidiaXID(\d+)Error/);
76
+ const cls = xid ? 'gpu' : /DoubleBit|ECC|PageRetire|RowRemap/i.test(reason) ? 'ecc' : /Neuron/.test(reason) ? 'hardware' : COND_CLASS[c.type] || 'node';
77
+ out.push({ t: toEpoch(c.lastTransitionTime || c.lastHeartbeatTime) ?? t0, node: n.metadata.name, code: xid ? `xid${xid[1]}` : `k8s_${c.type}`, class: cls, severity: 'hard',
78
+ reason, condition: c.type, msg: String(c.message || '').slice(0, 300), source: 'k8s-condition' });
79
+ }
80
+ // GKE: host maintenance scheduled for a GPU or TPU node (they don't live-migrate): planned, not a fault
81
+ for (const n of j.items || []) {
82
+ const at = +(((n.metadata || {}).labels || {})['cloud.google.com/scheduled-maintenance-time']);
83
+ if (at > 0) out.push({ t: t0, node: n.metadata.name, code: 'scheduled_maintenance', class: 'maintenance', severity: 'info', at, msg: `host maintenance scheduled for ${new Date(at * 1000).toISOString()}`, source: 'k8s-label' });
84
+ }
85
+ return out;
86
+ }
54
87
  // Rack labels people use; Kubernetes has no standard one.
55
88
  export const RACK_LABELS = ['topology.kubernetes.io/rack', 'node.kubernetes.io/rack', 'rack', 'topology.aiinfra/rack'];
56
89
  // Rack and zone of each accelerator node, as topology edges (from the same `kubectl get nodes -o json`).
@@ -123,7 +156,7 @@ export function slurmNodes(text, { t = Math.floor(Date.now() / 1000) } = {}) {
123
156
  // "gpu[01-03,07],cpu5" → ["gpu01","gpu02","gpu03","gpu07","cpu5"]
124
157
  export function expandNodes(list) {
125
158
  const out = [];
126
- for (const part of String(list || '').match(/[^,\[]+(\[[^\]]*\])?/g) || []) {
159
+ for (const part of String(list || '').match(/[^,[]+(\[[^\]]*\])?/g) || []) {
127
160
  const m = part.match(/^(.*)\[(.*)\]$/);
128
161
  if (!m) { if (part) out.push(part); continue; }
129
162
  for (const r of m[2].split(',')) {
@@ -96,23 +96,26 @@ export function kernelLog(text, { node, boot, year, utcOffset = 0, pciMap = {},
96
96
  return out;
97
97
  }
98
98
 
99
- // NCCL and PyTorch distributed logs (stdout of a training job) → log records. Lines usually look like
99
+ // NCCL, RCCL and PyTorch distributed logs (stdout of a training job) → log records. Lines usually look like
100
100
  // host:pid:tid [rank] NCCL WARN … or, with `kubectl logs --timestamps`, an ISO time first.
101
+ // RCCL (ROCm) keeps NCCL's prefixes; it reports its version as "RCCL version : X-hash" and HIP errors as "HIP error".
101
102
  // NCCL's own lines carry no time: pass `t` (the log's start or the job end) for those.
102
103
  const APP = [
103
104
  { re: /Watchdog caught collective operation timeout: WorkNCCL\(SeqNum=(\d+), OpType=(\w+).*?ran for (\d+) milliseconds/, f: m => ({ code: 'nccl_timeout', class: 'network', severity: 'hard', op: m[2], seq: +m[1], ms: +m[3] }) },
104
- { re: /NCCL WARN NET\/IB.*(?:Got completion|error)\D*(\d+)?/i, f: m => ({ code: 'nccl_ib_error', class: 'network', severity: 'hard', status: m[1] != null ? +m[1] : undefined }) },
105
+ // NCCL/RCCL: "NET/IB: Got completion from peer … with status=12 opcode=…" (older: "… with error 12, opcode …")
106
+ { re: /NCCL WARN NET\/IB.*?(?:Got completion|error)(?:.*?(?:status=|with error )(\d+))?/i, f: m => ({ code: 'nccl_ib_error', class: 'network', severity: 'hard', status: m[1] != null ? +m[1] : undefined }) },
105
107
  { re: /NCCL WARN .*(?:Connection (?:closed|reset|refused)|socket|remote process exited)/i, f: () => ({ code: 'nccl_peer_lost', class: 'network', severity: 'soft' }) },
106
108
  { re: /NCCL WARN Cuda failure '([^']+)'/, f: m => ({ code: 'nccl_cuda_failure', class: /ECC|uncorrectable/i.test(m[1]) ? 'ecc' : 'app', severity: 'hard', detail: m[1] }) },
107
109
  { re: /(?:NCCL error|ncclInternalError|ncclSystemError|unhandled system error)/i, f: () => ({ code: 'nccl_system_error', class: 'network', severity: 'soft' }) },
108
- { re: /CUDA error: uncorrectable ECC error/i, f: () => ({ code: 'cuda_ecc_uncorrectable', class: 'ecc', severity: 'hard' }) },
110
+ { re: /(?:CUDA|HIP) error: uncorrectable ECC error/i, f: () => ({ code: 'cuda_ecc_uncorrectable', class: 'ecc', severity: 'hard' }) },
109
111
  // mixed-precision loss scaling skips steps whose gradients overflowed: normal, not corruption
110
112
  { re: /(?:overflow|skipping (?:step|update|batch)|loss scale|grad(?:ient)? scaler)/i, f: () => ({ code: 'loss_scale_overflow', class: 'app', severity: 'ignore' }) },
111
113
  // non-finite loss or gradients (PyTorch anomaly detection, Megatron / DeepSpeed loss checks, trainer logs)
112
114
  { re: /(?:(?:loss|grad(?:ient)?s?(?: norm)?)\b[^\n]{0,24}?\b(?:is |= ?|: ?)(?:nan|inf)\b|Function '\w+' returned nan values|found (?:nan|inf) in|non-finite (?:loss|grad))/i, f: () => ({ code: 'non_finite', class: 'app', severity: 'soft' }) },
113
- { re: /CUDA error: an illegal memory access/i, f: () => ({ code: 'cuda_illegal_access', class: 'app', severity: 'soft' }) },
114
- { re: /(?:torch\.(?:cuda\.)?OutOfMemoryError|CUDA out of memory)/, f: () => ({ code: 'cuda_oom', class: 'app', severity: 'soft' }) },
115
- { re: /NCCL INFO NCCL version (\S+)/, f: m => ({ code: 'nccl_version', class: 'info', severity: 'info', version: m[1].replace(/\+.*/, '') }) },
115
+ { re: /(?:CUDA|HIP) error: an illegal memory access/i, f: () => ({ code: 'cuda_illegal_access', class: 'app', severity: 'soft' }) },
116
+ { re: /(?:torch\.(?:cuda\.)?OutOfMemoryError|(?:CUDA|HIP) out of memory)/, f: () => ({ code: 'cuda_oom', class: 'app', severity: 'soft' }) },
117
+ { re: /NCCL INFO NCCL version (\S+)/, f: m => ({ code: 'nccl_version', class: 'info', severity: 'info', lib: 'nccl', version: m[1].replace(/\+.*/, '') }) },
118
+ { re: /RCCL version\s*:\s*(\d+\.\d+\.\d+)/, f: m => ({ code: 'nccl_version', class: 'info', severity: 'info', lib: 'rccl', version: m[1] }) },
116
119
  ];
117
120
  export function ncclLog(text, { node, job, t: t0, keepInfo = true } = {}) {
118
121
  const out = [];
@@ -141,5 +144,5 @@ export function ncclLog(text, { node, job, t: t0, keepInfo = true } = {}) {
141
144
  // Device faults from logs, as gpu-health results: { t, kind: 'fault', node, gpu, code }.
142
145
  export function toGpuHealthFaults(logs) {
143
146
  return logs.filter(l => l.gpu != null && DEVICE_CLASSES.has(l.class) && l.severity !== 'ignore' && l.severity !== 'info')
144
- .map(l => ({ t: l.t, kind: 'fault', node: l.node, gpu: l.gpu, code: l.code, source: 'log' }));
147
+ .map(l => ({ t: l.t, kind: 'fault', node: l.node, gpu: l.gpu, code: l.code, source: l.source === 'nvsentinel' ? 'nvsentinel' : 'log' }));
145
148
  }
@@ -0,0 +1,95 @@
1
+ // NVSentinel (NVIDIA's GPU fault detection and remediation for Kubernetes) health events → `log` records.
2
+ //
3
+ // NVSentinel already detects GPU faults (DCGM health watches, XIDs from syslog, NVLink, NICs, CSP maintenance) and can
4
+ // cordon, drain and remediate nodes on its own. fleetops takes its events as evidence for root-cause analysis, and
5
+ // gpu-health defers to it: a node NVSentinel is remediating gets no second repair ladder from gpu-health.
6
+ //
7
+ // Reads, in any mix (JSON, JSON lines, or a Kubernetes List):
8
+ // - CloudEvents from the event exporter: { specversion, type: "com.nvidia.nvsentinel.health.v1", data: { healthEvent } }
9
+ // - datastore documents: { createdAt, healthEvent, healthEventStatus } (nodeQuarantined, faultRemediated, …)
10
+ // - HealthEventResource objects (healthevents.dgxc.nvidia.com): { spec: HealthEvent, status: HealthEventStatus }
11
+ // - bare HealthEvent objects (protobuf JSON: camelCase; enums as names or numbers; timestamps RFC 3339 or {seconds})
12
+ // Fields as in NVSentinel v1.33.0's data-models/protobufs/health_event.proto and event-exporter.
13
+ import { xidClass, DEVICE_CLASSES } from './logs.mjs';
14
+
15
+ const ACTIONS = { 0: 'NONE', 2: 'COMPONENT_RESET', 5: 'CONTACT_SUPPORT', 6: 'RUN_FIELDDIAG', 15: 'RESTART_VM', 24: 'RESTART_BM', 25: 'REPLACE_VM', 26: 'RUN_DCGMEUD', 27: 'CUSTOM', 99: 'UNKNOWN' };
16
+ const STRATEGIES = { 0: 'UNSPECIFIED', 1: 'EXECUTE_REMEDIATION', 2: 'STORE_ONLY', 3: 'STORE_AND_ANALYSE' };
17
+ const enumName = (v, table) => (v == null || v === '' ? null : typeof v === 'number' || /^\d+$/.test(String(v)) ? table[+v] || String(v) : String(v));
18
+ const ts = v => { if (v == null) return null; if (typeof v === 'object') { if (v.$date) return ts(v.$date); if (v.seconds != null) return +v.seconds + (+v.nanos || 0) / 1e9; } const t = Date.parse(v); return Number.isFinite(t) ? t / 1000 : typeof v === 'number' ? (v > 1e12 ? v / 1000 : v) : null; };
19
+
20
+ // a check → the log class it belongs to (XIDs by their number, through gpu-health's fault table)
21
+ function classify(e) {
22
+ const check = String(e.checkName || ''), comp = String(e.componentClass || ''), codes = (e.errorCode || []).map(String);
23
+ const xid = codes.map(c => (c.match(/^(?:XID[_ ]?)?(\d+)$/i) || [])[1]).find(Boolean);
24
+ if (xid && /xid|syslog/i.test(check + ' ' + e.agent)) { const [cls, sev] = xidClass(+xid); return { code: `xid${xid}`, class: cls, severity: sev }; }
25
+ if (/fallen ?off|gpufallenoff/i.test(check)) return { code: 'xid79', class: 'bus', severity: 'hard' };
26
+ const code = `nvsentinel:${check || comp || 'event'}`;
27
+ if (/sxid|nvswitch|nvlink|link/i.test(check)) return { code, class: 'link', severity: 'hard' };
28
+ if (/mem|ecc|row ?remap|sram|dbe|sbe/i.test(check)) return { code, class: 'ecc', severity: 'hard' };
29
+ if (/pci/i.test(check)) return { code, class: 'pcie', severity: 'hard' };
30
+ if (/ethernet|nic|infiniband|\bib\b|network/i.test(check + ' ' + comp)) return { code, class: 'network', severity: 'soft' };
31
+ if (/thermal|power|clock/i.test(check)) return { code, class: 'firmware', severity: 'soft' };
32
+ if (/dcgm|driver|firmware|inforom/i.test(check)) return { code, class: 'firmware', severity: 'soft' };
33
+ if (/^gpu$/i.test(comp)) return { code, class: 'firmware', severity: 'soft' };
34
+ return { code, class: 'node', severity: 'soft' };
35
+ }
36
+
37
+ export function toLog(e, status = null, { cluster = null } = {}) {
38
+ if (!e || !e.nodeName) return null;
39
+ const t = ts(e.generatedTimestamp); if (t == null) return null;
40
+ const c = classify(e), ents = e.entitiesImpacted || [], ent = k => (ents.find(x => x.entityType === k) || {}).entityValue;
41
+ const action = enumName(e.recommendedAction, ACTIONS), strategy = enumName(e.processingStrategy, STRATEGIES);
42
+ const r = { t, node: e.nodeName, code: c.code, class: c.class, severity: e.isHealthy ? 'info' : e.isFatal ? 'hard' : c.severity, msg: String(e.message || '').slice(0, 300), source: 'nvsentinel',
43
+ check: e.checkName || undefined, agent: e.agent || undefined, recommendedAction: action || undefined, healthy: !!e.isHealthy, strategy: strategy || undefined };
44
+ const gpu = ent('GPU'); if (gpu != null && /^\d+$/.test(gpu)) r.gpu = gpu; else if (gpu) r.gpuUuid = gpu;
45
+ if (ent('GPU_UUID')) r.gpuUuid = ent('GPU_UUID'); if (ent('PCI')) r.pci = ent('PCI');
46
+ if (cluster) r.cluster = cluster;
47
+ // NVSentinel acts on this event itself: it remediates unless told only to store, and only for unhealthy events that recommend something
48
+ r.remediating = !e.isHealthy && strategy !== 'STORE_ONLY' && strategy !== 'STORE_AND_ANALYSE' && !!action && !['NONE', 'UNKNOWN'].includes(action);
49
+ if (status) {
50
+ if (status.nodeQuarantined) r.quarantine = status.nodeQuarantined;
51
+ const fr = status.faultRemediated; if (fr != null) r.remediated = typeof fr === 'object' ? !!fr.value : !!fr;
52
+ if (status.remediationDecision && status.remediationDecision.action) r.remediationAction = status.remediationDecision.action;
53
+ }
54
+ if (!DEVICE_CLASSES.has(r.class)) delete r.gpu;
55
+ for (const k of Object.keys(r)) if (r[k] === undefined) delete r[k];
56
+ return r;
57
+ }
58
+
59
+ function* objects(text) {
60
+ const s = String(text).trim(); if (!s) return;
61
+ let docs;
62
+ try { const j = JSON.parse(s); docs = Array.isArray(j) ? j : j && Array.isArray(j.items) ? j.items : [j]; }
63
+ catch { docs = s.split(/\r?\n/).filter(l => l.trim()).map(l => { try { return JSON.parse(l); } catch { return null; } }); }
64
+ for (const d of docs) if (d && typeof d === 'object') yield d;
65
+ }
66
+
67
+ export function nvsentinelEvents(text) {
68
+ const logs = []; let unmatched = 0;
69
+ for (const d of objects(text)) {
70
+ let e = null, status = null, cluster = null;
71
+ if (d.specversion && d.data && d.data.healthEvent) { e = d.data.healthEvent; cluster = d.data.metadata && d.data.metadata.cluster; }
72
+ else if (d.healthEvent) { e = d.healthEvent; status = d.healthEventStatus || null; }
73
+ else if (d.kind === 'HealthEventResource' || (d.spec && d.spec.nodeName)) { e = d.spec; status = d.status || null; }
74
+ else if (d.nodeName && (d.checkName || d.componentClass)) e = d;
75
+ const r = e && toLog(e, status, { cluster });
76
+ if (r) logs.push(r); else unmatched++;
77
+ }
78
+ return { logs: logs.sort((a, b) => a.t - b.t), unmatched };
79
+ }
80
+
81
+ // Nodes NVSentinel is remediating now: the latest unhealthy, remediating event per node (and GPU) that no later healthy
82
+ // event for the same check has cleared and NVSentinel hasn't marked remediated.
83
+ export function remediating(logs, { now = Infinity, withinS = 24 * 3600 } = {}) {
84
+ const last = new Map();
85
+ for (const l of logs.filter(x => x.source === 'nvsentinel' && x.t <= now).sort((a, b) => a.t - b.t)) {
86
+ const k = `${l.node}|${l.check || l.code}`;
87
+ if (l.healthy) last.delete(k); else last.set(k, l);
88
+ }
89
+ const out = new Map();
90
+ for (const l of last.values()) if (l.remediating && !l.remediated && now - l.t <= withinS) {
91
+ const k = l.gpu != null ? `${l.node}/${l.gpu}` : l.node;
92
+ out.set(k, { by: 'nvsentinel', action: l.remediationAction || l.recommendedAction, check: l.check || l.code, t: l.t, quarantine: l.quarantine || null });
93
+ }
94
+ return out;
95
+ }