aiinfra-tools 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/README.md +27 -3
  3. package/bin/aiinfra.mjs +5 -2
  4. package/bin/report.mjs +177 -0
  5. package/fleetops/README.md +33 -1
  6. package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
  7. package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
  8. package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
  9. package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
  10. package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
  11. package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
  12. package/fleetops/deploy/shadow-live/README.md +41 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +123 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +53 -0
  16. package/fleetops/docs/ADMISSION.md +9 -9
  17. package/fleetops/docs/FABRIC-STORAGE.md +1 -1
  18. package/fleetops/docs/SERVING.md +11 -1
  19. package/fleetops/docs/SHADOW.md +250 -0
  20. package/fleetops/docs/SIGNALS.md +5 -2
  21. package/fleetops/docs/WORKLOADS.md +1 -1
  22. package/fleetops/package.json +7 -4
  23. package/fleetops/src/adapters/fabric.mjs +19 -7
  24. package/fleetops/src/adapters/live.mjs +38 -5
  25. package/fleetops/src/adapters/logs.mjs +10 -7
  26. package/fleetops/src/adapters/nvsentinel.mjs +95 -0
  27. package/fleetops/src/adapters/topology.mjs +53 -1
  28. package/fleetops/src/admission.mjs +26 -18
  29. package/fleetops/src/api.mjs +2 -1
  30. package/fleetops/src/bundle.mjs +3 -0
  31. package/fleetops/src/calibrate.mjs +1 -1
  32. package/fleetops/src/detect.mjs +1 -1
  33. package/fleetops/src/export.mjs +5 -1
  34. package/fleetops/src/goodput.mjs +0 -2
  35. package/fleetops/src/incidents.mjs +1 -2
  36. package/fleetops/src/ingest.mjs +10 -3
  37. package/fleetops/src/inject.mjs +2 -2
  38. package/fleetops/src/live.mjs +2 -1
  39. package/fleetops/src/llmd.mjs +7 -3
  40. package/fleetops/src/optimize.mjs +1 -1
  41. package/fleetops/src/power.mjs +7 -7
  42. package/fleetops/src/procure.mjs +67 -0
  43. package/fleetops/src/rca.mjs +1 -1
  44. package/fleetops/src/rollout.mjs +1 -1
  45. package/fleetops/src/schema.mjs +3 -2
  46. package/fleetops/src/security.mjs +1 -1
  47. package/fleetops/src/serving.mjs +32 -10
  48. package/fleetops/src/shadow-canary.mjs +74 -0
  49. package/fleetops/src/shadow-gate.mjs +49 -0
  50. package/fleetops/src/shadow-prom.mjs +205 -0
  51. package/fleetops/src/shadow-replay.mjs +147 -0
  52. package/fleetops/src/shadow.mjs +291 -0
  53. package/fleetops/src/stats.mjs +14 -0
  54. package/fleetops/src/traces.mjs +0 -5
  55. package/fleetops/tests/fixtures/real/README.md +5 -0
  56. package/fleetops/tools/admit-node.sh +51 -16
  57. package/fleetops/tools/amd-admit.py +111 -0
  58. package/fleetops/tools/cmd/calibrate.mjs +61 -0
  59. package/fleetops/tools/cmd/capacity.mjs +116 -0
  60. package/fleetops/tools/cmd/common.mjs +32 -0
  61. package/fleetops/tools/cmd/data.mjs +343 -0
  62. package/fleetops/tools/cmd/help.mjs +243 -0
  63. package/fleetops/tools/cmd/incidents.mjs +216 -0
  64. package/fleetops/tools/cmd/rollout.mjs +122 -0
  65. package/fleetops/tools/cmd/server.mjs +122 -0
  66. package/fleetops/tools/cmd/serving.mjs +95 -0
  67. package/fleetops/tools/cmd/shadow.mjs +204 -0
  68. package/fleetops/tools/cmd/training.mjs +79 -0
  69. package/fleetops/tools/collect.sh +6 -1
  70. package/fleetops/tools/fleetops.mjs +18 -1308
  71. package/fleetops/tools/loop-demo.mjs +1 -1
  72. package/fleetops/tools/workload-profile.mjs +0 -1
  73. package/fleetscope/README.md +5 -1
  74. package/fleetscope/build.mjs +4 -0
  75. package/fleetscope/dist/index.html +1013 -28
  76. package/fleetscope/docs/AGENTIC.md +89 -0
  77. package/fleetscope/docs/PLANNING.md +4 -2
  78. package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
  79. package/fleetscope/package.json +4 -3
  80. package/fleetscope/src/agentic.js +288 -0
  81. package/fleetscope/src/ask.js +0 -1
  82. package/fleetscope/src/cluster-ui.js +1 -0
  83. package/fleetscope/src/engine.js +29 -13
  84. package/fleetscope/src/index.src.html +15 -5
  85. package/fleetscope/src/inference-ui.js +1 -0
  86. package/fleetscope/src/ingest.js +89 -3
  87. package/fleetscope/src/optimize.js +11 -5
  88. package/fleetscope/src/plan.js +1 -1
  89. package/fleetscope/src/training-ui.js +1 -0
  90. package/fleetscope/tools/agentic.mjs +148 -0
  91. package/fleetscope/tools/tracelab-data.mjs +27 -0
  92. package/gpu-health/README.md +13 -2
  93. package/gpu-health/docs/CONFIG.md +29 -1
  94. package/gpu-health/package.json +7 -4
  95. package/gpu-health/src/actions.mjs +16 -3
  96. package/gpu-health/src/analyze.mjs +3 -0
  97. package/gpu-health/src/config.mjs +3 -0
  98. package/gpu-health/src/executors.mjs +9 -4
  99. package/gpu-health/src/health.mjs +1 -1
  100. package/gpu-health/src/ingest.mjs +27 -3
  101. package/gpu-health/src/platforms.mjs +109 -0
  102. package/gpu-health/src/vendors.mjs +12 -5
  103. package/gpu-health/tools/gpu-health.mjs +6 -4
  104. package/gpu-ledger/README.md +3 -1
  105. package/gpu-ledger/package.json +12 -4
  106. package/gpu-ledger/src/adapters.mjs +3 -2
  107. package/gpu-ledger/src/cloud.mjs +104 -0
  108. package/gpu-ledger/src/core.mjs +12 -10
  109. package/gpu-ledger/tools/ledger.mjs +8 -2
  110. package/harness-ledger/README.md +152 -0
  111. package/harness-ledger/docs/FORMATS.md +114 -0
  112. package/harness-ledger/docs/METHOD.md +133 -0
  113. package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
  114. package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
  115. package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
  116. package/harness-ledger/package.json +19 -0
  117. package/harness-ledger/src/demo.mjs +115 -0
  118. package/harness-ledger/src/economics.mjs +184 -0
  119. package/harness-ledger/src/gpu.mjs +80 -0
  120. package/harness-ledger/src/html.mjs +63 -0
  121. package/harness-ledger/src/importers.mjs +247 -0
  122. package/harness-ledger/src/ledger.mjs +128 -0
  123. package/harness-ledger/src/opencost.mjs +55 -0
  124. package/harness-ledger/src/outcomes.mjs +67 -0
  125. package/harness-ledger/src/prices.mjs +75 -0
  126. package/harness-ledger/src/record.mjs +52 -0
  127. package/harness-ledger/src/waste.mjs +136 -0
  128. package/harness-ledger/tools/harness-ledger.mjs +199 -0
  129. package/harness-ledger/tools/validate-economics.mjs +69 -0
  130. package/harness-ledger/tools/validate-swebench.mjs +57 -0
  131. package/harness-ledger/tools/validate-tracelab.mjs +74 -0
  132. package/hybrid-tracing/package.json +4 -3
  133. package/hybrid-tracing/tools/fix-skew.mjs +1 -1
  134. package/inference-sizer/README.md +5 -1
  135. package/inference-sizer/build.mjs +1 -0
  136. package/inference-sizer/dist/index.html +299 -31
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/CATALOG.md +71 -0
  139. package/inference-sizer/docs/METHOD.md +1 -1
  140. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  141. package/inference-sizer/package.json +4 -3
  142. package/inference-sizer/src/accelerators.js +194 -0
  143. package/inference-sizer/src/catalog.js +55 -22
  144. package/inference-sizer/src/fit-ui.js +1 -1
  145. package/inference-sizer/src/index.src.html +3 -0
  146. package/inference-sizer/src/model.js +45 -7
  147. package/inference-sizer/src/ui.js +1 -1
  148. package/inference-sizer/tools/validate-agentx.mjs +116 -0
  149. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  150. package/mcp/README.md +6 -1
  151. package/mcp/server.mjs +34 -0
  152. package/package.json +10 -6
  153. package/schemas/README.md +3 -0
  154. package/schemas/aiinfra.report.schema.json +474 -0
  155. package/schemas/commands.mjs +14 -0
  156. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  157. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  158. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  159. package/schemas/harness-ledger.economics.schema.json +567 -0
  160. package/schemas/sizer.list.schema.json +15 -2
@@ -1,479 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
  // fleetops: the shared data layer for AIInfraTools, with calibration, root-cause analysis and optimization on top.
3
+ // This file parses arguments and dispatches; each area's commands live in cmd/<area>.mjs (data, calibrate, incidents,
4
+ // capacity, shadow, rollout, training, serving, server), with shared helpers in cmd/common.mjs and the usage in cmd/help.mjs.
3
5
  import fs from 'node:fs';
4
6
  import path from 'node:path';
5
7
  import { fileURLToPath } from 'node:url';
6
- import { DataStore, whereFrom, openStore, SCHEMA } from '../src/store.mjs';
8
+ import { openStore, SCHEMA } from '../src/store.mjs';
7
9
  import * as Retention from '../src/retention.mjs';
8
- import { migrate } from '../src/migrate.mjs';
9
- import * as Ingest from '../src/ingest.mjs';
10
- import * as Traces from '../src/traces.mjs';
11
- import * as Inc from '../src/incidents.mjs';
12
- import * as Sec from '../src/security.mjs';
13
- import * as Pull from '../src/pull.mjs';
14
- import { postWebhook, run as runAction } from '../../gpu-health/src/executors.mjs';
15
- import { Store as GhStore } from '../../gpu-health/src/actions.mjs';
16
- import { readLines } from '../src/lines.mjs';
17
- import * as Philly from '../src/adapters/philly.mjs';
18
- import * as Pub from '../src/adapters/public.mjs';
19
- import * as Live from '../src/adapters/live.mjs';
20
- import { toEpoch } from '../src/adapters/time.mjs';
21
- import * as Logs from '../src/adapters/logs.mjs';
22
- import * as Topo from '../src/adapters/topology.mjs';
23
- import { writeGpuHealth, toFleetScopeTrace, toGpuLedger } from '../src/export.mjs';
24
- import * as Calib from '../src/calibrate.mjs';
25
- import * as RCA from '../src/rca.mjs';
26
- import * as Opt from '../src/optimize.mjs';
27
- import * as Detect from '../src/detect.mjs';
28
- import * as Bench from '../src/bench.mjs';
29
- import * as Agent from '../src/agent.mjs';
30
- import * as Goodput from '../src/goodput.mjs';
31
- import * as Sdc from '../src/sdc.mjs';
32
- import * as Bundle from '../src/bundle.mjs';
33
- import * as Tune from '../src/tune.mjs';
34
- import * as Serving from '../src/serving.mjs';
35
- import * as Fabric from '../src/adapters/fabric.mjs';
36
- import * as Storage from '../src/adapters/storage.mjs';
37
- import * as Power from '../src/power.mjs';
38
- import * as Adm from '../src/admission.mjs';
39
- import * as RO from '../src/rollout.mjs';
40
- import { goodputMarkdown, goodputHtml } from '../src/goodput-report.mjs';
41
- import * as LiveView from '../src/live.mjs';
42
- import * as Inject from '../src/inject.mjs';
43
- import { loadConfig as ghConfig } from '../../gpu-health/src/config.mjs';
44
- import { createRequire } from 'node:module';
45
- const FSIN = createRequire(import.meta.url)('../../fleetscope/src/ingest.js');
46
-
47
- const HELP = `fleetops — shared data layer for AIInfraTools
48
-
49
- fleetops data import SOURCE FILE... [--store DIR] [options] load records into the store
50
- fleetops data import bundle FILE.tar.gz|DIR a trace bundle (tools/collect.sh): every file, by its
51
- manifest entry or by content
52
- fleetops send FILE.tar.gz|DIR --to URL [--token T] upload a bundle to a fleetops server (POST /v1/bundle)
53
- fleetops data summary [--store DIR] records per kind, time range and sources
54
- fleetops data query KIND [--from T] [--to T] [--where k=v]... [--limit N]
55
- fleetops data node NODE [--from T] [--to T] versions, shared switch/rack/PDU, log faults, changes
56
- fleetops data requests [--from T] [--to T] per-request records (stages, replica) from stored spans
57
- fleetops data rollup [--steps 60,3600] minute and hour device rollups (rollup-60/, rollup-3600/)
58
- fleetops data compact [--raw-days 7] [--apply] drop old raw device/request/span days after rolling up,
59
- keeping incident windows at full resolution (keep/)
60
- fleetops data migrate [--apply] bring the store to the current schema version
61
- fleetops serve [--port 9400] [--host 127.0.0.1] [--tokens FILE] [--on-prem [HOSTS]] [--site S] [--max-queue 200000]
62
- ingest (remote_write, OTLP over HTTP: protobuf or JSON) and serve the read API (/api/…); tokens scope reads to a tenant; every API read
63
- is audited in <store>/audit/api.jsonl; request content is redacted at ingest; --on-prem refuses outbound calls
64
- to hosts not listed (also FLEETOPS_EGRESS_ALLOW)
65
- fleetops token create --tokens FILE --name N [--roles read,ingest,admin] [--namespaces a,b] [--pools p] [--clusters c] [--infra]
66
- fleetops token list --tokens FILE
67
- fleetops data export gpu-health --out DIR [--from T] [--to T] samples.jsonl, jobs.json, results.jsonl for gpu-health
68
- fleetops data export fleetscope-trace --out FILE [--pool P] CSV for FleetScope's Trace replay node
69
- fleetops data export gpu-ledger --out usage.jsonl [--capacity cap.json] [--cluster C] usage records for gpu-ledger (billing, waste)
70
- fleetops demo --training [--days 7] [--tuned-at D] training jobs with planted badput (for goodput and tune);
71
- --tuned-at applies two recommendations on day D
72
- fleetops demo [--scenario NAME] [--seed N] [--list] [--now] a store with one planted cause (a benchmark scenario) to
73
- try detect, diagnose and incidents without a fleet;
74
- --now moves it so the incident ends now (for the agent)
75
-
76
- Sources (SOURCE):
77
- exporter DCGM / AMD / SambaNova exporter text [--vendor V] [--t EPOCH] [--site S]
78
- vllm vLLM /metrics snapshot --pool P [--before FILE | --window S] [--model M] [--gpu G] [--t EPOCH]
79
- prom-range Prometheus query_range JSON --field ttftP99|tpotP99|rate|kvUsage|… [--pool P]
80
- k8s-nodes kubectl get nodes -o json inventory with versions; rack and zone edges
81
- k8s-pods kubectl get pods -A -o json
82
- slurm-nodes scontrol show node -o (kernel version from OS=)
83
- nvidia-smi-q nvidia-smi -q [--node N] (default: file name) versions, serials, PCI → GPU map
84
- nvidia-topo nvidia-smi topo -m [--node N] NVLink and NIC affinity
85
- ibnetdiscover ibnetdiscover host → leaf → spine (with switch port numbers)
86
- perfquery perfquery [-x] LID PORT output [--switch NAME] switch port counters (errors, xmit wait, data)
87
- ibqueryerrors ibqueryerrors switch ports with error counters, fabric-wide
88
- ethtool ethtool -S IFACE --node N --iface I RoCE NIC counters: pause frames, discards, link errors
89
- ib-sysfs grep -H . /sys/class/infiniband/*/ports/*/{counters,hw_counters}/* --node N host IB/RoCE port counters, CNPs, ECN marks
90
- fabric-prom Prometheus query_range of switch counters [--map metric=field,…] UFM telemetry, SONiC, SNMP (ifInErrors, …)
91
- ports JSON lines {t, switch, port, symbolErrors?, xmitWait?, pfcPause?, …}
92
- lustre-jobstats lctl get_param obdfilter.*.job_stats (on an OSS) [--before FILE] [--fs NAME] [--target OST0003] per-OST I/O per job
93
- mountstats /proc/self/mountstats --node N [--before FILE --window S] NFS latency per export
94
- storage JSON lines {t, target, op, node?, job?, ops?, bytes?, latMs?} anything else (S3 clients, loaders)
95
- racks CSV: node,rack,row,pdu,site
96
- kernel-log journalctl -k -o short-iso | dmesg -T | dmesg | syslog [--node N] [--boot T] [--year Y] [--utc-offset H]
97
- XID, NVLink, PCIe AER, AMD RAS, MCE, IB link, NFS/Lustre, OOM (GPU index from nvidia-smi-q imports)
98
- app-log NCCL / PyTorch job output [--node N] [--job J] [--t T]
99
- k8s-events kubectl get events -A -o json cordon/reboot/scale changes; NotReady/OOM/mount/evict logs
100
- helm-history helm history REL -n NS -o json [--release R] [--namespace NS]
101
- otlp-traces OTLP/JSON traces (resourceSpans) [--derive] (also write per-request records)
102
- kineto PyTorch profiler trace JSON (one rank) [--job J] [--node N] [--rank R] [--t0 T] per-rank steps
103
- nccl-inspector NCCL Inspector profiler-plugin JSON [--job J] (default: from the nccl-inspector-<jobid> directory)
104
- step-log JSON lines {t, rank, node, step, durS, commS?, dataS?, ckptS?, mfu?, loss?, gradNorm?, n?} [--job J]
105
- requests gateway or proxy request logs (LiteLLM, OpenAI-style usage, OTLP gen_ai spans, CSV with t, isl,
106
- osl, ttft?, e2e?): token counts and latencies, never prompts [--pool P] [--start T]
107
- auto recognize each file by its content (exporter scrapes, vLLM metrics, nvidia-smi, kubectl JSON,
108
- sacct, kernel and NCCL logs, step logs, Kineto, OTLP, NCCL Inspector, request logs, …)
109
- admission tools/admit-node.sh output: versions, topology, DCGM diag, NCCL bandwidth, burn-in and SDC canary of a node
110
- sdc-checks JSON lines of silent-data-corruption checks: tools/sdc-canary.py output, or your trainer's
111
- {t, check: param-checksum|replay|nan, node, gpu, job, step, rank, group, value, ok}
112
- sacct sacct -P -X --format=JobID,JobName,State,ExitCode,Start,End,NodeList,AllocTRES
113
- changes JSON lines of change events
114
- git-log git log --date=unix --pretty=format:'@@%H|%ad|%an|%s' --name-only [--repo NAME]
115
- gpu-health a gpu-health state directory (events.jsonl, results.jsonl)
116
- philly-machines Philly cluster_machine_list
117
- philly-gpu Philly cluster_gpu_util [--from T] [--to T] [--step MIN] [--machines N|m1,m2]
118
- philly-jobs Philly cluster_job_log [--from T] [--to T]
119
- azure-llm Azure LLM inference trace CSV [--pool P] [--limit N]
120
- mlperf MLPerf mlperf_log_summary.txt files [--isl N] (the path names the system, model and scenario)
121
- acme AcmeTrace job trace CSV [--cluster NAME]
122
-
123
- Calibration (fits are stored as calibration records; profiles are JSON files the tools read):
124
- fleetops calibrate benchmarks [--isl N] [--no-fleetscope] [--profile OUT]
125
- fit the Inference Sizer (and FleetScope) to benchmark records; runs named *interactive* are held out and checked
126
- fleetops calibrate serving --graph G [--from T] [--to T] [--holdout 0.25] [--profile OUT] [--graph-out G2] [--every SECONDS]
127
- fit each FleetScope pool of a graph to its serving records; --every re-fits on a schedule
128
- fleetops calibrate drift --graph G --profile P [--from T] [--to T] [--fail-on-drift]
129
- simulate the latest window with the stored multipliers; outside the 10%/20% bar → a drift record
130
- fleetops calibrate apply --graph G --profile P --out G2 write the multipliers into a FleetScope graph
131
-
132
- Root-cause analysis (diagnoses are stored as incident records):
133
- fleetops rca detect [--from T] [--to T] [--min-failures 20] [--targets targets.json] [--diagnose] [--format md]
134
- find job-failure and latency incidents (seasonal baseline + CUSUM, grouped); --diagnose ranks causes for each
135
- fleetops rca diagnose --symptom job-failures|latency|device --from T --to T [--pool P] [--nodes n1,n2] [--format md]
136
- fleetops rca eval --labels FILE top-1 / top-3 accuracy on labeled incidents (JSON lines: { incident, cause })
137
- fleetops rca bench [--per-cause 10] [--seed 1] [--only PREFIX] [--injections] [--labels FILE] [--weights W] [--fit OUT]
138
- [--min-top1 0.8] [--min-top3 0.95]
139
- accuracy per cause on synthetic scenarios (default), injected faults and/or postmortem labels; --fit writes rule
140
- weights fitted on the labels (held-out accuracy reported); exit 5 below the bar
141
- detect/diagnose/bench take --weights W. detect: --method cusum (default) | threshold, --bin S, --group-gap S, --where k=v
142
-
143
- Incidents (lifecycle as incident_event records; paging is a dry run unless --live):
144
- fleetops incidents open [--from T] [--to T] detect, diagnose, open the new ones (severity from the symptom's size)
145
- fleetops incidents list [--status open|acknowledged|mitigated|resolved]
146
- fleetops incidents ack|mitigate|resolve|reopen|assign|severity|note ID --by NAME [--note TEXT] [--owner O]
147
- [--severity sev1..sev4] [--cause RULE --component X] (resolve --cause stores the confirmed cause as a label)
148
- fleetops incidents show ID | timeline ID [--out FILE.html] | postmortem ID [--out FILE.md]
149
- fleetops incidents page ID --to pagerduty|opsgenie|webhook --action trigger|ack|resolve [--key K] [--url U] [--live]
150
- rca bench --from-incidents score root-cause analysis on resolved incidents' confirmed causes
151
-
152
- Real labels from a real fleet:
153
- fleetops pull --from T [--to T] --prom URL [--loki URL] [--loki-query Q]… [--step 60] [--header 'Authorization: Bearer X']
154
- a window of DCGM/AMD/vLLM/NCCL-Inspector series and kernel/NCCL logs from the fleet's own monitoring
155
- fleetops backtest --labels postmortems.jsonl --prom URL [--loki URL] [--lookback 26h] [--weights W]
156
- pull each confirmed incident's window and score root-cause analysis on it (misses name the incident)
157
- fleetops gameday PLAN.json --allow FILE [--live] [--cooldown 900] [--prom URL --loki URL]
158
- run injections one after another on a TEST cluster (dry run unless --live), then score detection and diagnosis
159
-
160
- Goodput (where training GPU-hours went; checkpoint interval advice):
161
- fleetops goodput [--from T] [--to T | --days 7] [--job J] [--targets targets.json] [--format md|html] [--out FILE]
162
- allocated GPU-hours per job, team and day split into productive, slow steps, data stalls, checkpoint saves,
163
- lost work, restarts, startup and idle; the fleet's interruption rate; the best checkpoint interval per job
164
-
165
- Tuning (what to change, the expected effect, and afterwards whether it worked):
166
- fleetops tune [--from T] [--to T | --days 7] [--targets targets.json] [--pools pools.json] [--format md|json] [--out F]
167
- ranked changes for training (checkpoint interval, input pipeline, slow nodes, restarts, communication),
168
- inference (KV cache, pool size and autoscaling with the Inference Sizer) and the fleet (flaky nodes, idle GPUs),
169
- each with its evidence, knobs, expected effect and its basis (measured, model, upper bound)
170
- pools.json: { "chat": { "model": "llama33-70b", "gpu": "H100", "gpus": 32 } } (fleetops tune models lists ids)
171
- fleetops tune apply ID --by NAME [--at T] [--note TEXT] record that a recommendation was applied
172
- fleetops tune verify [ID] [--before 7d] [--after 7d] the metric before and after, a 95% interval, a verdict
173
- fleetops tune list applied recommendations and their verdicts
174
- fleetops tune holdout --from T --split T --to T recommend on [from, split), check on [split, to) that
175
- the problem each names is still there (before changing anything)
176
-
177
- Power (budgets per rack, PDU and site; which jobs a cap slows; caps planned and applied through approval):
178
- fleetops power report --budgets b.json [--from T --to T] IT kW (p99, peak) per rack/PDU/row/site vs budget, headroom in nodes
179
- fleetops power jobs each job's draw, how compute-bound it is, time at the limit, steps per kWh
180
- fleetops power predict --cap 70% | --cap 500W [--job J] predicted slowdown and kW saved per job under a cap
181
- fleetops power fit measure how clocks follow the power limit on your GPUs (α)
182
- fleetops power plan --budgets b.json [--save-kw N] [--max-slowdown 0.05] [--protect training] --out plan.json
183
- the caps that bring each group under budget at the least slowdown, queued for approval; then
184
- fleetops optimize advance --plan plan.json (applies, bakes, rolls back on a guard breach)
185
- fleetops power verify --plan plan.json measured kW saved and step slowdown against the prediction
186
- fleetops power demo two racks, one over budget
187
-
188
- Node admission and safe rollouts (a bad node or version stopped before it reaches a production job):
189
- tools/admit-node.sh [--burn-in 6h] --out admit.jsonl on the node: versions, topology, DCGM diag, NCCL, SDC canary
190
- fleetops data import admission admit.jsonl
191
- fleetops admit pending new nodes, nodes back from quarantine or repair
192
- fleetops admit check NODE [--policy p.json] [--record] pass / fail / missing per check → admit, reject or incomplete
193
- fleetops admit apply NODE [--live] admit-node (needs approval) or reject-node (automatic), dry run unless --live
194
- fleetops rollout plan --field driver --version V [--canary 2] [--waves 25%,100%] [--bake 6h] [--nodes REGEX] [--sku S]
195
- [--apply "ansible-playbook driver.yml -l {node} -e v={version}"] [--rollback "…"] --out rollout.json
196
- canary across racks, then waves, each queued for approval
197
- fleetops rollout advance --plan rollout.json [--live] after each bake: new version vs old on failures, hard faults,
198
- NCCL bandwidth, step compute in the same jobs, TTFT; a regression rolls the wave back and halts
199
- fleetops rollout check --field driver --version V [--from T --to T] the same comparison, ad hoc
200
- fleetops rollout status --plan rollout.json · fleetops rollout demo [--good]
201
-
202
- Serving (Inference Sizer both ways, and a one-command vLLM deployment on Kubernetes):
203
- fleetops serving models | gpus the catalog (ids, sizes, Hugging Face repos; GPU types)
204
- fleetops serving fit --gpu H100 --nodes 2 [--rate R] [--isl 2000 --osl 400] [--ttft 2 --tpot 0.05] [--rank largest|throughput]
205
- which models fit on that hardware, and how much load each carries within the targets
206
- fleetops serving capacity --model M --gpu G --nodes N | --gpus N [workload, targets]
207
- the most a model carries on given hardware: req/s (production and edge), concurrency, longest prompt, layout
208
- fleetops serving deploy --model M --gpu G (--nodes N | --gpus N | --rate R) [--name N] [--namespace serving]
209
- [--hf-secret SECRET] [--cache-pvc PVC] [--image IMG] [--autoscale [--prometheus URL]] [--create-namespace]
210
- [--from-pool P] [--out FILE] [--apply [--endpoint URL] [--wait 2400]] [--mode agg|disagg|auto]
211
- --mode disagg (or auto, when the sizer finds it smaller): prefill and decode pools on llm-d (DisaggregatedSet,
212
- NIXL KV transfer, the llm-d router chart); needs LeaderWorkerSet ≥ 0.11.1 and the InferencePool CRDs
213
- plan → Deployment or LeaderWorkerSet + Service (+ KEDA) → preflight; with --apply: apply, wait, smoke test, and
214
- register the pool for tune and the agent (<store>/serving/pools.json, targets.json). Without --apply: a dry run.
215
- fleetops serving delete NAME [--namespace serving] [--apply]
216
-
217
- Silent data corruption (GPUs that compute wrong answers without an error):
218
- fleetops sdc [--from T] [--to T | --days 7] [--format md]
219
- replicas that disagree, failed canaries and replays, the first rank to go non-finite, gradient outliers →
220
- suspect GPUs, and for each job the checkpoint to resume from; run tools/sdc-canary.py on nodes to confirm
221
-
222
- Live agent and dashboard (actions are dry runs unless --live AND the gpu-health policy has dryRun: false):
223
- fleetops agent [--interval 30] [--window 3600] [--state DIR] [--config gpu-health.json] [--agent-config agent.json]
224
- [--targets targets.json] [--prom URL [--loki URL]] [--page-to pagerduty|opsgenie|webhook --page-key K --page-url U]
225
- [--live] [--once]
226
- watch training and inference, diagnose what goes wrong, mitigate within the policy, verify, page when it can't
227
- fleetops agent status | log [--limit 50] | pause --by NAME | resume --by NAME | approve ID --by NAME | reject ID --by NAME
228
- fleetops serve --agent [agent options] ingest, run the agent in-process, and serve the dashboard at /live
229
- (state defaults to <store>/agent; approving from the page needs a token with the approve role)
230
-
231
- Fault injection on a TEST cluster (dry-run unless --live; every target must be in the --allow file):
232
- fleetops inject list
233
- fleetops inject FAULT --allow FILE [--for S] [--live] [--expect RULE] --param value … writes an injection label
234
-
235
- Optimization with safe execution (rollback is automatic; applying a stage always needs approval):
236
- fleetops optimize candidates [--from T] [--to T] [--price 4] [--max-attempts 2] [--graph G [--trace-pool P [--trace-from T --trace-to T]] [--target 0.99]] [--out cands.json]
237
- candidate changes from gpu-health (right-size, scale-in, reclaim), rca (retry storms) and FleetScope (pool sizes)
238
- fleetops optimize plan --candidates cands.json --out plan.json [--save-pct 20] [--baseline-weekly $] [--max-risk medium]
239
- [--guards guards.json] [--deployments deploy.json] [--bake 1800] [--state DIR]
240
- pick a set that meets the goal, stage it, and queue every stage for approval in gpu-health's queue
241
- fleetops optimize advance --plan plan.json [--state DIR] [--config gpu-health.json] [--live]
242
- check the last stage's SLO guard (regression → roll back, no approval needed), then run the next approved stage
243
- fleetops optimize verify --plan plan.json [--days 7] before/after GPU-hours and guard breaches → an optimization record
244
- Approve a stage with: gpu-health actions approve ID --by NAME --state DIR (DIR defaults to <store>/rollouts/state)
245
-
246
- Times (T) are ISO dates or epoch seconds. Common: --store DIR (default ./fleet-data), --backend jsonl|parquet (new stores;
247
- parquet needs \`npm install --no-save @duckdb/node-api@2.0.1-r.1\` in fleetops/), --json.`;
248
-
249
- function args(argv) {
250
- const o = { _: [], where: [] };
251
- for (let i = 0; i < argv.length; i++) {
252
- const a = argv[i];
253
- if (a.startsWith('--')) { const k = a.slice(2), nx = argv[i + 1], v = nx === undefined || nx.startsWith('--') ? true : (i++, nx); if (k === 'where') o.where.push(v); else o[k] = v; }
254
- else o._.push(a);
255
- }
256
- return o;
257
- }
258
- let J = false; const OUT = {};
259
- const say = (...a) => { if (!J) console.log(...a); };
260
- const read = f => fs.readFileSync(f, 'utf8');
261
- const time = v => (v == null || v === true ? undefined : toEpoch(/^\d{4}-\d{2}-\d{2}$/.test(v) ? v + 'T00:00:00Z' : v));
262
- const fmt = t => (Number.isFinite(t) ? new Date(t * 1000).toISOString().replace('.000', '') : '–');
263
-
264
- // PCI address → GPU index per node, from the latest nvidia-smi -q inventory in the store (for kernel logs).
265
- function pciMap(store) {
266
- const m = {};
267
- for (const r of store.scan('inventory', { where: r => Array.isArray(r.gpus) })) { m[r.node] = m[r.node] || {}; for (const g of r.gpus) if (g.pci) m[r.node][g.pci] = g.gpu; }
268
- return m;
269
- }
270
- function importSource(store, src, files, o) {
271
- const from = time(o.from), to = time(o.to), res = [];
272
- const put = (kind, recs) => { const r = store.append(kind, recs, { dedupe: true }); res.push(r); return r; };
273
- const tOf = f => (o.t ? time(o.t) : Math.floor(fs.statSync(f).mtimeMs / 1000));
274
- const nodeOf = f => (o.node && o.node !== true ? o.node : path.basename(f).replace(/\.(txt|log|out)$/, ''));
275
- // inventory with versions: a version that differs from the node's previous snapshot becomes a change record
276
- let lastByNode = null;
277
- const putInventory = recs => {
278
- if (!lastByNode) { lastByNode = new Map(); for (const r of store.scan('inventory', { where: r => r.versions })) { const p = lastByNode.get(r.node); if (!p || p.t < r.t) lastByNode.set(r.node, r); } }
279
- const changes = [];
280
- for (const r of recs.slice().sort((a, b) => a.t - b.t)) { if (r.versions) { changes.push(...Topo.versionChanges(lastByNode.get(r.node), r)); const p = lastByNode.get(r.node); if (!p || p.t < r.t) lastByNode.set(r.node, r); } }
281
- put('inventory', recs);
282
- if (changes.length) put('change', changes);
283
- };
284
- const each = f => (fs.statSync(f).isDirectory() ? [f] : [f]);
285
- for (const f of files.flatMap(each)) {
286
- switch (src) {
287
- case 'exporter': put('device', Live.exporterScrape(read(f), { vendor: o.vendor !== true ? o.vendor : undefined, t: o.t ? time(o.t) : Math.floor(fs.statSync(f).mtimeMs / 1000), site: o.site })); break;
288
- case 'vllm': put('serving', [Live.vllmSnapshot(read(f), { before: o.before ? read(o.before) : undefined, windowS: o.window ? +o.window : undefined, t: o.t ? time(o.t) : Math.floor(fs.statSync(f).mtimeMs / 1000), pool: o.pool || 'default', model: o.model, gpu: o.gpu })]); break;
289
- case 'prom-range': if (!o.field) throw new Error('prom-range needs --field'); put('serving', Live.promRange(read(f), { field: o.field, pool: o.pool })); break;
290
- case 'k8s-nodes': putInventory(Live.k8sNodes(read(f), { t: tOf(f) })); put('topology', Live.k8sNodeTopology(read(f), { t: tOf(f) })); break;
291
- case 'k8s-pods': put('placement', Live.k8sPods(read(f))); break;
292
- case 'slurm-nodes': putInventory(Live.slurmNodes(read(f), { t: tOf(f) })); break;
293
- case 'nvidia-smi-q': putInventory([Topo.nvidiaSmiQ(read(f), { node: nodeOf(f), t: tOf(f) }).inventory]); break;
294
- case 'nvidia-topo': put('topology', Topo.nvidiaTopo(read(f), { node: nodeOf(f), t: tOf(f) })); break;
295
- case 'ibnetdiscover': put('topology', Topo.ibnetdiscover(read(f), { t: tOf(f) })); break;
296
- case 'perfquery': put('port', Fabric.perfquery(read(f), { switch: o.switch, t: tOf(f) })); break;
297
- case 'ibqueryerrors': put('port', Fabric.ibqueryerrors(read(f), { t: tOf(f) })); break;
298
- case 'ib-sysfs': put('port', Fabric.ibSysfs(read(f), { node: o.node || nodeOf(f), t: tOf(f) })); break;
299
- case 'ethtool': put('port', Fabric.ethtool(read(f), { node: o.node || nodeOf(f), iface: o.iface || 'eth0', t: tOf(f) })); break;
300
- case 'fabric-prom': put('port', Fabric.fabricProm(JSON.parse(read(f)), { map: o.map ? Object.fromEntries(String(o.map).split(',').map(x => x.split('='))) : {} })); break;
301
- case 'ports': put('port', read(f).split(/\r?\n/).filter(l => l.trim()).map(l => Object.assign({ source: 'ports' }, JSON.parse(l)))); break;
302
- case 'lustre-jobstats': put('storage', Storage.lustreJobstats(read(f), { before: o.before ? read(o.before) : undefined, fs: o.fs || 'lustre', target: o.target || Storage.lustreTargetOf(f), t: tOf(f) })); break;
303
- case 'mountstats': put('storage', Storage.nfsMountstats(read(f), { node: o.node || nodeOf(f), before: o.before ? read(o.before) : undefined, windowS: o.window ? +o.window : undefined, t: tOf(f) })); break;
304
- case 'storage': put('storage', Storage.storageLines(read(f))); break;
305
- case 'racks': put('topology', Topo.racks(read(f), { t: tOf(f) })); break;
306
- case 'kernel-log': put('log', Logs.kernelLog(read(f), { node: o.node && o.node !== true ? o.node : undefined, boot: time(o.boot), year: o.year ? +o.year : undefined, utcOffset: o['utc-offset'] ? +o['utc-offset'] : 0, pciMap: pciMap(store) })); break;
307
- case 'app-log': put('log', Logs.ncclLog(read(f), { node: o.node && o.node !== true ? o.node : undefined, job: o.job && o.job !== true ? o.job : undefined, t: o.t ? time(o.t) : tOf(f) })); break;
308
- case 'k8s-events': { const e = Live.k8sEvents(read(f)); put('change', e.changes); put('log', e.logs); break; }
309
- case 'kineto': put('step', Traces.kineto(read(f), { job: o.job && o.job !== true ? o.job : path.basename(f).split(/[._]/)[0], node: o.node && o.node !== true ? o.node : undefined, rank: o.rank != null && o.rank !== true ? +o.rank : undefined, t0: o.t0 ? time(o.t0) : undefined })); break;
310
- case 'nccl-inspector': put('collective', Traces.ncclInspector(read(f), { job: o.job && o.job !== true ? o.job : (path.basename(path.dirname(path.resolve(f))).match(/nccl-inspector-(\S+)/) || [])[1], node: o.node && o.node !== true ? o.node : undefined })); break;
311
- case 'step-log': put('step', Traces.stepLog(read(f), { job: o.job && o.job !== true ? o.job : undefined })); break;
312
- case 'admission': {
313
- // tools/admit-node.sh output: { record: inventory|check|topology|sdc_check, … }
314
- const by = {};
315
- for (const l of read(f).split(/\r?\n/).filter(x => x.trim())) { const { record, ...r } = JSON.parse(l); if (!['inventory', 'check', 'topology', 'sdc_check'].includes(record)) throw new Error(`admission file: unexpected record ${record}`); (by[record] = by[record] || []).push(Object.assign({ source: 'admit-node' }, r, r.gpu != null ? { gpu: String(r.gpu) } : {})); }
316
- for (const [k, rs] of Object.entries(by)) put(k, rs);
317
- break;
318
- }
319
- case 'sdc-checks': put('sdc_check', read(f).split(/\r?\n/).filter(l => l.trim()).map(l => JSON.parse(l)).map(c => Object.assign({ source: 'sdc-canary' }, c, { gpu: c.gpu != null ? String(c.gpu) : undefined }))); break;
320
- case 'otlp-traces': { const spans = Ingest.otlpTracesToSpans(JSON.parse(read(f))); put('span', spans); if (o.derive) put('request', Traces.requestsFromSpans(spans)); break; }
321
- case 'helm-history': put('change', Live.helmHistory(read(f), { release: o.release && o.release !== true ? o.release : path.basename(f, '.json'), namespace: o.namespace && o.namespace !== true ? o.namespace : 'default' })); break;
322
- case 'sacct': put('job', Live.slurmSacct(read(f))); break;
323
- case 'changes': put('change', Live.changesJsonl(read(f))); break;
324
- case 'git-log': put('change', Live.gitLog(read(f), { repo: o.repo || path.basename(f) })); break;
325
- case 'gpu-health': {
326
- const ev = path.join(f, 'events.jsonl'), rs = path.join(f, 'results.jsonl');
327
- if (fs.existsSync(ev)) put('health', Live.gpuHealthEvents(read(ev)));
328
- if (fs.existsSync(rs)) put('job', Live.gpuHealthResults(read(rs)));
329
- break;
330
- }
331
- case 'philly-machines': put('inventory', Philly.machines(read(f), { t: from ?? 0 })); break;
332
- case 'philly-gpu': {
333
- let keep = null;
334
- if (o.machines && o.machines !== true) keep = /^\d+$/.test(o.machines) ? null : new Set(String(o.machines).split(','));
335
- const limit = /^\d+$/.test(String(o.machines || '')) ? +o.machines : 0;
336
- const inv = store.query('inventory', { where: r => r.source === 'philly' }), skus = Object.fromEntries(inv.map(r => [r.node, r.sku]));
337
- // the first N machines (by number) with 8 GPUs: a fixed, repeatable subset of the cluster
338
- if (limit) keep = new Set(inv.filter(r => r.devices === 8).map(r => r.node).sort((a, b) => +a.slice(1) - +b.slice(1)).slice(0, limit));
339
- let batch = [], n = 0;
340
- for (const s of Philly.gpuUtil(readLines(f), { from, to, stepMin: +(o.step || 10), machines: keep, skus })) { batch.push(s); if (batch.length >= 50000) { n += put('device', batch).written; batch = []; } }
341
- if (batch.length) put('device', batch);
342
- break;
343
- }
344
- case 'philly-jobs': { const x = Philly.jobLog(JSON.parse(read(f)), { from, to }); put('placement', x.placements); put('job', x.outcomes); break; }
345
- case 'azure-llm': put('request', Pub.azureLlm(read(f), { pool: o.pool || path.basename(f, '.csv'), limit: o.limit ? +o.limit : Infinity })); break;
346
- case 'mlperf': put('benchmark', [Pub.mlperfSummary(read(f), { path: o.path || f, t: o.t ? time(o.t) : 0, meta: { islMean: o.isl ? +o.isl : undefined } })]); break;
347
- case 'acme': put('job', Pub.acme(read(f), { cluster: o.cluster || 'acme', limit: o.limit ? +o.limit : Infinity })); break;
348
- // gateway or proxy request logs (LiteLLM, OpenAI-style usage, OTLP gen_ai spans, CSV), through FleetScope's parser;
349
- // token counts and latencies only, never prompts or completions
350
- case 'requests': {
351
- const parsed = FSIN.parseTrace(read(f), { maxRows: 5000000, maxSeconds: Number.MAX_SAFE_INTEGER });
352
- const pool = o.pool && o.pool !== true ? o.pool : path.basename(f).replace(/\.(jsonl?|csv|txt)$/, '');
353
- const t0 = time(o.start) ?? tOf(f) - Math.max(0, ...parsed.trace.map(r => +r.t || 0));
354
- put('request', parsed.trace.filter(r => +r.isl > 0 && +r.osl > 0).map(r => ({ t: r.abs != null ? r.abs : t0 + +r.t, pool, isl: +r.isl, osl: +r.osl, cached: r.cached != null ? +r.cached : undefined, ttft: r.ttft != null ? +r.ttft : undefined, e2e: r.e2e != null ? +r.e2e : undefined, source: 'requests' })));
355
- break;
356
- }
357
- case 'auto': {
358
- const s = Bundle.sniffFile(f, f);
359
- if (!s) { res.push({ kind: 'unrecognized', written: 0, skipped: 0, invalid: 0, errors: [`${f}: not recognized; name its source (fleetops data import SOURCE FILE)`] }); break; }
360
- const by = importSource(store, s, [f], o);
361
- for (const [kind, b] of Object.entries(by)) res.push(Object.assign({ kind }, b));
362
- break;
363
- }
364
- default: throw new Error(`unknown source "${src}"\n\n${HELP}`);
365
- }
366
- }
367
- // merge per kind
368
- const by = {};
369
- for (const r of res) { const b = by[r.kind] || (by[r.kind] = { written: 0, skipped: 0, invalid: 0, errors: [] }); b.written += r.written; b.skipped += r.skipped; b.invalid += r.invalid; b.errors.push(...r.errors); }
370
- return by;
371
- }
372
-
373
- // A bundle (tar, tar.gz or a directory): manifest entries, then anything recognized by content. One bad file doesn't
374
- // stop the rest; each file's result is reported.
375
- async function importBundle(store, target, o = {}) {
376
- if (!target) throw new Error('fleetops data import bundle FILE.tar.gz|DIR');
377
- let dir = target, tmp = null;
378
- if (!fs.statSync(target).isDirectory()) { const u = Bundle.unpack(fs.readFileSync(target)); dir = tmp = u.dir; }
379
- try {
380
- const p = Bundle.plan(dir), files = [], totals = {};
381
- // files another entry reads (a vLLM scrape's earlier snapshot) are not imported on their own
382
- const used = new Set(p.entries.map(e => e.opts && e.opts.before).filter(Boolean).map(Bundle.safeName));
383
- for (const e of p.entries) {
384
- if (used.has(e.path)) continue;
385
- if (e.opts && e.opts.before) e.opts = Object.assign({}, e.opts, { before: path.join(dir, Bundle.safeName(e.opts.before)) });
386
- if (e.missing) { files.push({ path: e.path, source: e.source, error: 'listed in the manifest but not in the bundle' }); continue; }
387
- if (!e.source) { files.push({ path: e.path, source: null, skipped: 'not recognized' }); continue; }
388
- try {
389
- const opts = Object.assign({}, e.opts);
390
- if (['kernel-log', 'nvidia-smi-q', 'nvidia-topo', 'app-log'].includes(e.source) && !opts.node && p.manifest && p.manifest.host) opts.node = p.manifest.host;
391
- if (opts.t != null) opts.t = String(opts.t);
392
- const by = importSource(store, e.source, [e.abs], opts);
393
- for (const [k, b] of Object.entries(by)) totals[k] = (totals[k] || 0) + b.written;
394
- files.push({ path: e.path, source: e.source, from: e.from, imported: by });
395
- } catch (err) { files.push({ path: e.path, source: e.source, error: err.message.split('\n')[0] }); }
396
- }
397
- if (store.flush) store.flush();
398
- return { manifest: p.manifest, files, totals };
399
- } finally { if (tmp) fs.rmSync(tmp, { recursive: true, force: true }); }
400
- }
401
-
402
- // fleetops send: a bundle (or a directory, tarred here) to a fleetops server's POST /v1/bundle.
403
- async function sendCmd(o) {
404
- const target = o._[1], url = o.to && o.to !== true ? o.to : null, token = o.token && o.token !== true ? o.token : process.env.FLEETOPS_TOKEN;
405
- if (!target || !url) throw new Error('fleetops send BUNDLE|DIR --to http://fleetops:9400 [--token T | FLEETOPS_TOKEN]');
406
- let body;
407
- if (fs.statSync(target).isDirectory()) {
408
- const walk = (d, b = '') => fs.readdirSync(path.join(d, b), { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(d, b ? `${b}/${e.name}` : e.name) : e.isFile() ? [b ? `${b}/${e.name}` : e.name] : []);
409
- body = (await import('node:zlib')).gzipSync(Bundle.writeTar(walk(target).map(n => ({ name: n, data: fs.readFileSync(path.join(target, n)) }))));
410
- } else body = fs.readFileSync(target);
411
- const r = await fetch(url.replace(/\/$/, '') + '/v1/bundle', { method: 'POST', headers: Object.assign({ 'content-type': 'application/gzip' }, token ? { authorization: `Bearer ${token}` } : {}), body });
412
- const text = await r.text();
413
- if (!r.ok) throw new Error(`${r.status}: ${text.trim()}`);
414
- const j = JSON.parse(text);
415
- if (J) { OUT.sent = j; return; }
416
- say(`sent ${(body.length / 1e6).toFixed(1)} MB: ${Object.entries(j.totals).map(([k, n]) => `${k} ${n}`).join(', ') || 'nothing new'}${j.files.some(f => f.error) ? `\n errors: ${j.files.filter(f => f.error).map(f => `${f.path}: ${f.error}`).join('; ')}` : ''}`);
417
- }
418
-
419
- // A demo store: one benchmark scenario (a fleet with one planted cause and distractors) written to --store, so the
420
- // detect → diagnose → incident flow can be tried without a fleet. The answer is printed so the result can be checked.
421
- function demo(store, o) {
422
- if (o.training) {
423
- const days = o.days ? +o.days : 7, t0 = Math.floor(Date.now() / 1000 / 3600) * 3600 - days * 86400;
424
- const at = o['tuned-at'] && o['tuned-at'] !== true ? t0 + +o['tuned-at'] * 86400 : null;
425
- // the two changes `tune` recommends for the first period: a faster input pipeline, more frequent checkpoints
426
- const tuned = at ? { at, 'sft-8b': { data: 0.12 }, 'pretrain-70b': { ckptEvery: 40 * 60 } } : null;
427
- const recs = Goodput.synthTraining({ t0, days, seed: o.seed ? +o.seed : 7, tuned }), written = {};
428
- for (const [k, r] of Object.entries(recs)) if (r.length) written[k] = store.append(k, r, { dedupe: true }).written;
429
- if (store.flush) store.flush();
430
- if (at) {
431
- const t = Tune.tune(store, { from: t0, to: at, now: at });
432
- for (const id of ['data-pipeline:sft-8b', 'checkpoint:pretrain-70b']) { const r = t.recommendations.find(x => x.id === id); if (r) Tune.applyTune(store, r, { by: 'demo', at }); }
433
- }
434
- const res = { store: store.dir, written, from: t0, to: t0 + days * 86400, planted: { 'pretrain-70b': 'checkpoints every 3 h on a fleet that interrupts it every ~6 h: lost work', 'sft-8b': 'a slow input pipeline: data stalls', 'rl-policy': 'one slow node for two days: slow steps' } };
435
- if (J) { OUT.demo = res; return; }
436
- say(`demo store ${store.dir}: ${days} days of training (${Object.entries(written).map(([k, n]) => `${k} ${n}`).join(', ')})`);
437
- for (const [j, w] of Object.entries(res.planted)) say(` ${j}: ${w}`);
438
- say(at ? `applied on day ${o['tuned-at']}: data-pipeline:sft-8b, checkpoint:pretrain-70b\ntry:\n fleetops tune --from ${new Date(t0 * 1000).toISOString()} --to ${new Date(at * 1000).toISOString()} --store ${store.dir}\n fleetops tune verify --store ${store.dir}` : `try:\n fleetops goodput --days ${days} --store ${store.dir}\n fleetops tune --days ${days} --store ${store.dir}\n fleetops goodput --days ${days} --format html --out goodput.html --store ${store.dir}`);
439
- return;
440
- }
441
- const names = Bench.SCENARIO_NAMES;
442
- if (o.list) { if (J) { OUT.scenarios = names; return; } names.forEach(n => say(n)); return; }
443
- const want = o.scenario && o.scenario !== true ? String(o.scenario) : 'hardware: GPU fault seen in dmesg';
444
- const name = names.find(n => n === want) || names.find(n => n.startsWith(want));
445
- if (!name) throw new Error(`no demo scenario starts with "${want}"; see fleetops demo --list`);
446
- const [lab] = Bench.generate({ perCause: 1, seed: o.seed ? +o.seed : 1, only: [name] });
447
- // --now: shift every time so the incident ends a minute ago, for the live agent and dashboard
448
- const shift = o.now ? Math.floor(Date.now() / 1000) - 60 - lab.incident.to : 0;
449
- const mv = r => { if (!shift) return r; const x = Object.assign({}, r); for (const k of ['t', 'start', 'end', 'since', 'from', 'to', 'alarmAt']) if (typeof x[k] === 'number' && x[k] > 1e9) x[k] += shift; return x; };
450
- if (shift) { lab.incident = mv(lab.incident); }
451
- const written = {};
452
- for (const [kind, recs] of Object.entries(lab.store.data)) if (recs.length) written[kind] = store.append(kind, recs.map(mv), { dedupe: true }).written;
453
- if (store.flush) store.flush();
454
- const inc = lab.incident, iso = t => new Date(t * 1000).toISOString();
455
- const scope = [inc.pool && `--pool ${inc.pool}`, inc.job && `--job ${inc.job}`, inc.nodes && `--nodes ${[].concat(inc.nodes).join(',')}`].filter(Boolean).join(' ');
456
- // demo fleets are small (12-24 nodes), so job-failure detection needs a lower floor than the default 20
457
- const mf = inc.symptom === 'job-failures' ? ' --min-failures 5' : '';
458
- const next = [`fleetops rca detect --from ${iso(inc.from - 6 * 3600)} --to ${iso(inc.to + 3600)}${mf} --diagnose --store ${store.dir}`,
459
- `fleetops rca diagnose --symptom ${inc.symptom} --from ${iso(inc.from)} --to ${iso(inc.to)}${scope ? ' ' + scope : ''} --store ${store.dir}`,
460
- `fleetops incidents open --from ${iso(inc.from - 6 * 3600)} --to ${iso(inc.to + 3600)}${mf} --store ${store.dir}`];
461
- const res = { scenario: name, store: store.dir, written, incident: Object.assign({}, inc, { fromIso: iso(inc.from), toIso: iso(inc.to) }), planted: { cause: lab.cause, component: lab.component || null }, next };
462
- if (J) { OUT.demo = res; return; }
463
- say(`demo store ${store.dir}: ${name}`);
464
- say(` ${Object.entries(written).map(([k, n]) => `${k} ${n}`).join(', ')}`);
465
- say(` incident: ${inc.symptom}, ${iso(inc.from)} → ${iso(inc.to)}${scope ? ' (' + scope + ')' : ''}`);
466
- say(` planted cause: ${lab.cause}${lab.component ? ` (${lab.component})` : ''}`);
467
- say('try:'); next.forEach(c => say(' ' + c));
468
- }
10
+ import { args, J, OUT, setJson } from './cmd/common.mjs';
11
+ import { HELP } from './cmd/help.mjs';
12
+ import { sendCmd, demo, procureCmd, dataCmd } from './cmd/data.mjs';
13
+ import { calibrate } from './cmd/calibrate.mjs';
14
+ import { rca, pull, backtest, gameday, incidents, inject } from './cmd/incidents.mjs';
15
+ import { powerCmd, admitCmd } from './cmd/capacity.mjs';
16
+ import { shadowCmd } from './cmd/shadow.mjs';
17
+ import { rolloutCmd, optimize } from './cmd/rollout.mjs';
18
+ import { goodputCmd, tuneCmd, sdcCmd } from './cmd/training.mjs';
19
+ import { servingCmd } from './cmd/serving.mjs';
20
+ import { tokenCmd, agentCmd, serve } from './cmd/server.mjs';
469
21
 
470
22
  async function main() {
471
23
  const o = args(process.argv.slice(2));
472
- J = !!o.json;
24
+ setJson(!!o.json);
473
25
  const [area, cmd, ...rest] = o._;
474
26
  if (!area || o.help || area === 'help') return console.log(HELP);
475
27
  if (o['on-prem'] && process.env.FLEETOPS_EGRESS_ALLOW == null) process.env.FLEETOPS_EGRESS_ALLOW = typeof o['on-prem'] === 'string' ? o['on-prem'] : '';
476
28
  if (area === 'token') return tokenCmd(cmd, o);
29
+ if (area === 'procure') return procureCmd(cmd, o);
477
30
  if (area === 'send') return sendCmd(o);
478
31
  const store = await openStore(o.store && o.store !== true ? o.store : 'fleet-data', { backend: o.backend && o.backend !== true ? o.backend : undefined });
479
32
  // the hourly rollup answers long lookbacks (root-cause "day before") when it exists
@@ -485,6 +38,7 @@ async function main() {
485
38
  if (area === 'optimize') return optimize(store, cmd, o);
486
39
  if (area === 'admit') return admitCmd(store, cmd, o);
487
40
  if (area === 'rollout') return rolloutCmd(store, cmd, o);
41
+ if (area === 'shadow') return shadowCmd(store, cmd, rest, o);
488
42
  if (area === 'inject') return inject(store, cmd, o);
489
43
  if (area === 'incidents') return incidents(store, cmd, rest, o);
490
44
  if (area === 'backtest') return backtest(store, o);
@@ -498,851 +52,7 @@ async function main() {
498
52
  if (area === 'serving') return servingCmd(store, cmd, o);
499
53
  if (area === 'power') return powerCmd(store, cmd, o);
500
54
  if (area !== 'data') throw new Error(`unknown command "${area}"\n\n${HELP}`);
501
- if (cmd === 'import' && rest[0] === 'bundle') {
502
- const r = await importBundle(store, rest[1], o);
503
- if (J) { OUT.bundle = r; return; }
504
- say(`bundle ${rest[1]}${r.manifest ? ` (${r.manifest.host || '?'}, collected ${r.manifest.collectedAt || '?'})` : ''}`);
505
- for (const e of r.files) say(` ${e.path.padEnd(40)} ${(e.source || '–').padEnd(15)} ${e.error ? `error: ${e.error}` : e.skipped ? e.skipped : Object.entries(e.imported || {}).map(([k, b]) => `${k} ${b.written}${b.invalid ? ` (${b.invalid} invalid: ${b.errors[0] || ''})` : ''}`).join(', ') || 'nothing new'}`);
506
- say(` total: ${Object.entries(r.totals).map(([k, n]) => `${k} ${n}`).join(', ') || 'nothing imported'}`);
507
- return;
508
- }
509
- if (cmd === 'import') {
510
- const [src, ...files] = rest;
511
- if (!src || !files.length) throw new Error('give a SOURCE and at least one FILE');
512
- const by = importSource(store, src, files, o);
513
- if (J) { OUT.imported = by; return; }
514
- for (const [k, b] of Object.entries(by)) say(`${k}: ${b.written} written, ${b.skipped} already there, ${b.invalid} invalid${b.errors.length ? `\n ${b.errors.slice(0, 5).join('\n ')}` : ''}`);
515
- return;
516
- }
517
- if (cmd === 'summary') {
518
- const s = store.summary();
519
- if (J) { OUT.summary = s; OUT.store = store.dir; return; }
520
- say(`store ${store.dir}`);
521
- for (const [k, v] of Object.entries(s)) say(` ${k.padEnd(10)} ${String(v.records).padStart(9)} ${fmt(v.from)} → ${fmt(v.to)} ${Object.entries(v.sources).map(([a, b]) => `${a}:${b}`).join(' ')}`);
522
- if (!Object.keys(s).length) say(' (empty)');
523
- return;
524
- }
525
- if (cmd === 'query') {
526
- const kind = rest[0];
527
- const rows = store.query(kind, { from: time(o.from), to: time(o.to), where: whereFrom(o.where), limit: o.limit ? +o.limit : 1000 });
528
- if (J) { OUT.records = rows; return; }
529
- for (const r of rows) console.log(JSON.stringify(r));
530
- return;
531
- }
532
- if (cmd === 'rollup') {
533
- const r = await Retention.rollup(store, { steps: o.steps && o.steps !== true ? String(o.steps).split(',').map(Number) : undefined });
534
- if (J) { OUT.rollup = r; return; }
535
- for (const x of r) say(` ${x.day} ${x.step} s: ${x.raw != null ? `${x.raw} samples → ` : ''}${x.rolled} records`);
536
- if (!r.length) say(' nothing new to roll up');
537
- return;
538
- }
539
- if (cmd === 'compact') {
540
- const r = await Retention.compact(store, { rawDays: o['raw-days'] ? +o['raw-days'] : 7, apply: !!o.apply });
541
- if (J) { OUT.compact = r; return; }
542
- say(`raw high-volume days before ${r.cutoff}: ${r.plan.length}${r.applied ? '' : ' (dry run: --apply to roll up, keep incident windows and drop them)'}`);
543
- for (const p of r.plan) say(` ${p.kind.padEnd(7)} ${p.day}${p.keepWindows ? ` ${p.keepWindows} incident window(s)${p.kept != null ? `: ${p.kept} records kept` : ''}` : ''}${p.dropped ? ' dropped' : ''}`);
544
- return;
545
- }
546
- if (cmd === 'migrate') {
547
- const r = migrate(store, { apply: !!o.apply });
548
- if (J) { OUT.migrate = r; return; }
549
- if (r.from >= r.to) return say(`store is at schema ${r.to}: nothing to do`);
550
- const changed = r.steps.filter(x => x.changed);
551
- say(`schema ${r.from} → ${r.to}: ${changed.length} day file(s) with ${changed.reduce((t, x) => t + x.changed, 0)} records to change${r.applied ? ' — done' : ' (dry run: --apply to rewrite)'}`);
552
- for (const x of changed.slice(0, 20)) say(` v${x.to} ${x.kind} ${x.day}: ${x.changed} of ${x.records} (${x.what})`);
553
- return;
554
- }
555
- if (cmd === 'requests') {
556
- // per-request records (stages, replica, tokens) from the spans in the store
557
- const from = time(o.from), to = time(o.to), spans = store.query('span', { from, to });
558
- const reqs = Traces.requestsFromSpans(spans);
559
- const r = store.append('request', reqs, { dedupe: true });
560
- if (J) { OUT.requests = { spans: spans.length, requests: reqs.length, written: r.written }; return; }
561
- say(`${spans.length} spans → ${reqs.length} requests (${r.written} new)`);
562
- return;
563
- }
564
- if (cmd === 'node') {
565
- // one node, everything the store knows: versions, what it shares, recent log faults and changes
566
- const node = rest[0]; if (!node) throw new Error('data node NODE [--from T] [--to T]');
567
- const to = time(o.to), from = time(o.from) ?? (to ?? Math.floor(Date.now() / 1000)) - 7 * 86400;
568
- const inv = store.query('inventory', { to, where: r => r.node === node }).sort((a, b) => a.t - b.t);
569
- const g = Topo.groups(store.query('topology', { to })).byNode[node] || {};
570
- const nvl = store.query('topology', { to, where: e => e.kind === 'nvlink' && e.node === node });
571
- const logs = store.query('log', { from, to, where: l => l.node === node && l.severity !== 'info' });
572
- const changes = store.query('change', { from, to, where: c => c.target === node });
573
- const out = { node, inventory: inv.at(-1) || null, versions: Object.assign({}, ...inv.map(r => r.versions || {})), shares: g, nvlinkPairs: nvl.length, logs, changes };
574
- if (J) { OUT.node = out; return; }
575
- const last = inv.at(-1);
576
- say(`${node}${last ? ` ${last.devices}× ${last.sku || last.vendor}` : ' (not in the inventory)'}`);
577
- say(` versions ${Object.entries(out.versions).map(([k, v]) => `${k} ${v}`).join(', ') || '–'}${last && last.mixedVersions ? ` (mixed across GPUs: ${last.mixedVersions.join(', ')})` : ''}`);
578
- say(` shares ${[...(g.leaf || []), g.rack, g.pdu, g.row, g.site].filter(Boolean).join(', ') || '–'}${nvl.length ? `; ${nvl.length} NVLink pairs` : ''}`);
579
- say(` changes ${changes.length ? `(${changes.length})` : '–'}`); for (const c of changes) say(` ${fmt(c.t)} ${c.kind}: ${c.summary || c.id}${c.since != null ? ` (between ${fmt(c.since)} and then)` : ''}`);
580
- say(` log faults ${logs.length ? `(${logs.length})` : '–'}`);
581
- for (const l of logs.slice(-15)) say(` ${fmt(l.t)} ${l.gpu != null ? 'gpu' + l.gpu + ' ' : ''}${l.code} [${l.class}/${l.severity}] ${l.msg.slice(0, 90)}`);
582
- return;
583
- }
584
- if (cmd === 'export') {
585
- const what = rest[0];
586
- if (what === 'gpu-health') { if (!o.out) throw new Error('--out DIR'); const r = writeGpuHealth(store, o.out, { from: time(o.from), to: time(o.to) }); if (J) OUT.exported = r; else say(`wrote ${r.samples} samples, ${r.jobs} jobs, ${r.results} results to ${r.dir}`); return; }
587
- if (what === 'fleetscope-trace') { if (!o.out) throw new Error('--out FILE'); const csv = toFleetScopeTrace(store, { from: time(o.from), to: time(o.to), pool: o.pool }); fs.writeFileSync(o.out, csv); const n = csv.split('\n').length - 2; if (J) OUT.exported = { file: o.out, requests: n }; else say(`wrote ${n} requests to ${o.out}`); return; }
588
- if (what === 'gpu-ledger') { if (!o.out) throw new Error('--out usage.jsonl'); const r = toGpuLedger(store, { from: time(o.from), to: time(o.to), cluster: o.cluster && o.cluster !== true ? o.cluster : null }); fs.writeFileSync(o.out, r.usage.map(x => JSON.stringify(x)).join('\n') + (r.usage.length ? '\n' : '')); if (o.capacity && o.capacity !== true) fs.writeFileSync(o.capacity, JSON.stringify(r.capacity, null, 1)); if (J) OUT.exported = { file: o.out, usage: r.usage.length, capacity: r.capacity }; else say(`wrote ${r.usage.length} usage records to ${o.out}${o.capacity && o.capacity !== true ? ` and capacity to ${o.capacity}` : ''} (gpu-ledger report --usage ${o.out})`); return; }
589
- throw new Error('export gpu-health | fleetscope-trace | gpu-ledger');
590
- }
591
- throw new Error(`unknown: data ${cmd}\n\n${HELP}`);
592
- }
593
-
594
- const pc = v => (v == null || !Number.isFinite(v) ? '–' : (v > 0 ? '+' : '') + Math.round(v * 100) + '%');
595
- const errs = rows => (rows || []).map(r => `${r.metric} ${pc(r.err)}`).join(', ');
596
- async function calibrate(store, cmd, o) {
597
- const now = o.now ? +o.now : Math.floor(Date.now() / 1000);
598
- const writeProfile = p => { if (o.profile && o.profile !== true) { fs.writeFileSync(o.profile, JSON.stringify(p, null, 1)); say(`profile written to ${o.profile}`); } };
599
- if (cmd === 'benchmarks') {
600
- const r = Calib.calibrateBenchmarks(store, { islMean: o.isl ? +o.isl : 300, fleetscope: !o['no-fleetscope'], now });
601
- store.append('calibration', r.records);
602
- writeProfile(r.profile);
603
- if (J) { Object.assign(OUT, r); return; }
604
- say(`Inference Sizer: GPUs predicted for each benchmark's measured load, before and after calibration (mean input ${r.profile.assumptions.islMean} tokens assumed)`);
605
- for (const x of r.runs) say(x.sizer.error ? ` ${x.system}: ${x.sizer.error}` : ` ${x.system}: used ${x.sizer.measuredGpus}; spec-sheet model ${x.sizer.before} (${pc(x.sizer.errBefore)}) → calibrated ${x.sizer.after} (${pc(x.sizer.errAfter)})${x.sizer.capped.length ? `; at the ceiling: ${x.sizer.capped.join(', ')}` : ''}`);
606
- if (!o['no-fleetscope']) {
607
- say('FleetScope: one pool at the benchmark\'s load');
608
- for (const x of r.runs) if (x.fleetscope) say(x.fleetscope.error ? ` ${x.system}: ${x.fleetscope.error}` : ` ${x.system}: before ${errs(x.fleetscope.before)}\n fitted prefill ×${x.fleetscope.calib.prefill}, decode ×${x.fleetscope.calib.decode}: ${x.fleetscope.pass ? 'within the bar' : `not within the bar (${x.fleetscope.diagnosis})`}; after ${errs(x.fleetscope.after)}`);
609
- }
610
- if (r.heldOut.length) say('Held out (low-latency runs, checked against the profile fitted on the same system):');
611
- for (const h of r.heldOut) {
612
- if (h.sizerCalibrated) say(` ${h.system} ${h.model}: sizer spec-sheet ${h.sizerSpecSheet.predicted} GPUs (${pc(h.sizerSpecSheet.err)}), calibrated ${h.sizerCalibrated.predicted} (${pc(h.sizerCalibrated.err)}) vs ${h.sizerCalibrated.measuredGpus} used`);
613
- if (h.fleetscopeCalibrated) say(` FleetScope spec-sheet ${errs(h.fleetscopeSpecSheet.rows)}\n FleetScope calibrated ${errs(h.fleetscopeCalibrated.rows)}`);
614
- }
615
- return;
616
- }
617
- const graphFile = o.graph && o.graph !== true ? o.graph : null;
618
- if (!graphFile) throw new Error('--graph FILE (a FleetScope graph: "Copy graph JSON" in the editor)');
619
- const graph = JSON.parse(read(graphFile));
620
- if (cmd === 'serving') {
621
- const run = () => {
622
- const t = Math.floor(Date.now() / 1000), to = time(o.to) ?? (o.every ? t : undefined), from = time(o.from) ?? (o.every ? t - 86400 : undefined);
623
- const r = Calib.calibrateServing(store, graph, { from, to, holdout: o.holdout ? +o.holdout : 0, now: o.now ? +o.now : t });
624
- store.append('calibration', r.records);
625
- writeProfile(r.profile);
626
- if (o['graph-out'] && o['graph-out'] !== true) fs.writeFileSync(o['graph-out'], JSON.stringify(Calib.applyToGraph(graph, r.profile).graph, null, 1));
627
- if (J) { Object.assign(OUT, r); return; }
628
- for (const p of r.pools) say(p.skipped ? ` ${p.name}: ${p.skipped}` : ` ${p.name}: prefill ×${p.calib.prefill}, decode ×${p.calib.decode} — ${p.pass ? 'within the bar' : `not within the bar (${p.diagnosis})`}\n fit: ${errs(p.after)}${p.heldOut ? `\n held out: ${errs(p.heldOut.rows)} — ${p.heldOut.pass ? 'pass' : 'fail'}` : ''}`);
629
- };
630
- run();
631
- if (o.every) { const every = +o.every * 1000; say(`re-fitting every ${o.every} s`); setInterval(() => { try { run(); } catch (e) { console.error(e.message); } }, every); }
632
- return;
633
- }
634
- if (cmd === 'drift') {
635
- if (!o.profile || o.profile === true) throw new Error('--profile FILE');
636
- const d = Calib.driftCheck(store, graph, JSON.parse(read(o.profile)), { from: time(o.from), to: time(o.to), now });
637
- store.append('drift', d);
638
- if (J) OUT.drift = d; else for (const x of d) say(` ${x.pool}: ${x.drifted ? 'DRIFT' : 'ok'} — ${x.why}`);
639
- if (o['fail-on-drift'] && d.some(x => x.drifted)) process.exitCode = 3;
640
- return;
641
- }
642
- if (cmd === 'apply') {
643
- if (!o.profile || !o.out) throw new Error('--profile FILE --out FILE');
644
- const r = Calib.applyToGraph(graph, JSON.parse(read(o.profile)));
645
- fs.writeFileSync(o.out, JSON.stringify(r.graph, null, 1));
646
- if (J) OUT.applied = r.applied; else say(`multipliers written for ${r.applied.join(', ') || 'no pools (no profile entries match the graph)'} → ${o.out}`);
647
- return;
648
- }
649
- throw new Error(`unknown: calibrate ${cmd}\n\n${HELP}`);
650
- }
651
-
652
- async function rca(store, cmd, o) {
653
- const show = list => {
654
- if (J) { OUT.incidents = list; return; }
655
- if (o.format === 'md') { console.log(list.map(d => RCA.markdown(d)).join('\n')); return; }
656
- for (const d of list) {
657
- say(`${d.id} [${d.confidence}]`);
658
- d.hypotheses.slice(0, 3).forEach((h, i) => say(` ${i + 1}. ${h.title} (${h.rule}, ${h.score.toFixed(2)})`));
659
- say(` ${d.narrative}`);
660
- }
661
- };
662
- const weights = o.weights && o.weights !== true ? JSON.parse(read(o.weights)) : undefined;
663
- if (cmd === 'detect') {
664
- const from = time(o.from), to = time(o.to), targets = o.targets && o.targets !== true ? JSON.parse(read(o.targets)) : {};
665
- const where = whereFrom(o.where);
666
- let incs;
667
- if (o.method === 'threshold') incs = [...RCA.detectJobFailureSpikes(store, { from, to, minFailures: o['min-failures'] ? +o['min-failures'] : 50, ratio: o.ratio ? +o.ratio : 4 }), ...RCA.detectServingRegressions(store, { from, to, targets })];
668
- else incs = Detect.groupIncidents([...Detect.detectJobFailures(store, { from, to, binS: o.bin ? +o.bin : 600, minFailures: o['min-failures'] ? +o['min-failures'] : 20, where }), ...Detect.detectServing(store, { from, to, targets }), ...Detect.detectTraining(store, { from, to })], { gapS: o['group-gap'] ? +o['group-gap'] : 1800 });
669
- if (!o.diagnose) {
670
- if (J) { OUT.incidents = incs; return; }
671
- for (const i of incs) say(`${i.id} ${i.symptom.startsWith('training') ? `${i.job || i.nodes.join(',')}${i.peak != null ? ` step ${i.peak.toFixed(3)} s vs ${i.baseline.toFixed(3)} s` : ''}` : i.failures != null ? `${i.failures} failures` : `${i.metric} peak ${i.peak.toFixed(3)}${i.limit ? ` > ${i.limit.toFixed(3)}` : i.baseline != null ? ` vs ${i.baseline.toFixed(3)}` : ''}`}${i.alarmAt ? `, alarm ${Math.round((i.alarmAt - i.from) / 60)} min after onset` : ''}, ${((i.to - i.from) / 3600).toFixed(1)} h${i.merged ? `, ${i.merged.length + 1} merged` : ''}${i.related ? `; related: ${i.related.join(', ')}` : ''}`);
672
- return;
673
- }
674
- const ds = incs.map(i => RCA.diagnose(store, i, { weights }));
675
- store.append('incident', ds);
676
- return show(ds);
677
- }
678
- if (cmd === 'diagnose') {
679
- if (!o.symptom || !o.from || !o.to) throw new Error('--symptom job-failures|latency|device --from T --to T');
680
- const inc = { symptom: o.symptom, from: time(o.from), to: time(o.to), pool: o.pool !== true ? o.pool : undefined, nodes: o.nodes && o.nodes !== true ? String(o.nodes).split(',') : undefined, metric: o.metric };
681
- const d = RCA.diagnose(store, inc, { weights });
682
- store.append('incident', [d]);
683
- return show([d]);
684
- }
685
- if (cmd === 'eval') {
686
- if (!o.labels || o.labels === true) throw new Error('--labels FILE');
687
- const labeled = read(o.labels).split(/\r?\n/).filter(l => l.trim()).map(l => JSON.parse(l)).map(l => Object.assign(l, { incident: Object.assign({}, l.incident, { from: time(l.incident.from), to: time(l.incident.to) }) }));
688
- const r = RCA.evaluate(store, labeled);
689
- if (J) { OUT.evaluation = r; return; }
690
- say(`${r.incidents} labeled incidents: top-1 ${(r.top1 * 100).toFixed(0)}%, top-3 ${(r.top3 * 100).toFixed(0)}%`);
691
- for (const x of r.rows) say(` ${x.id}: labeled ${x.cause}, ranked ${x.rank ?? 'not found'} (${x.got.join(', ')})`);
692
- return;
693
- }
694
- if (cmd === 'bench') return bench(store, o, weights);
695
- throw new Error(`unknown: rca ${cmd}\n\n${HELP}`);
696
- }
697
-
698
- // The root-cause benchmark: synthetic scenarios (default), injected faults (--injections), postmortem labels (--labels).
699
- async function bench(store, o, weights) {
700
- const pct = v => (v == null ? '–' : `${(v * 100).toFixed(1)}%`);
701
- const rows = [], parts = [];
702
- const useSynth = !o.injections && !o.labels && !o['from-incidents'] || o.synthetic;
703
- if (useSynth) { const r = Bench.run(Bench.generate({ perCause: o['per-cause'] ? +o['per-cause'] : 10, seed: o.seed ? +o.seed : 1, only: o.only && o.only !== true ? String(o.only).split(',') : undefined }), { weights }); rows.push(...r.rows); parts.push('synthetic'); }
704
- let inj = null;
705
- if (o.injections) { inj = Bench.evalInjections(store, { weights, from: time(o.from), to: time(o.to) }); rows.push(...inj.rows.filter(r => r.cause)); parts.push('injected'); }
706
- if (o['from-incidents']) { rows.push(...Bench.evalLabels(store, Inc.labelsFromIncidents(store), { weights }).map(r => Object.assign(r, { source: 'incident', scenario: `confirmed: ${r.cause}` }))); parts.push('confirmed incidents'); }
707
- if (o.labels && o.labels !== true) {
708
- const labeled = read(o.labels).split(/\r?\n/).filter(l => l.trim()).map(l => JSON.parse(l)).map(l => Object.assign(l, { incident: Object.assign({}, l.incident, { from: time(l.incident.from), to: time(l.incident.to) }) }));
709
- rows.push(...Bench.evalLabels(store, labeled, { weights })); parts.push('postmortem');
710
- }
711
- let sum = Bench.summarize(rows), fitted = null;
712
- if (o.fit && o.fit !== true) {
713
- // fit on half, report the other half; then fit on all for the file
714
- const train = rows.filter((_, i) => i % 2 === 0), test = rows.filter((_, i) => i % 2 === 1);
715
- const wHalf = Bench.fitWeights(train), testBefore = Bench.summarize(test), testAfter = Bench.applyWeights(test, wHalf);
716
- const w = Bench.fitWeights(rows), perCause = {};
717
- for (const r of rows) perCause[r.cause] = (perCause[r.cause] || 0) + 1;
718
- const thin = Object.entries(perCause).filter(([, n]) => n < 5).map(([c]) => c);
719
- fitted = { rules: w, fittedOn: { sources: parts, incidents: rows.length, perCause }, heldOut: { top1Before: testBefore.top1, top1After: testAfter.top1 },
720
- warnings: [...(parts.every(p => p === 'synthetic') ? ['fitted on synthetic scenarios only: these weights learn the generator, not your fleet; fit on injected or postmortem labels before using them'] : []), ...(thin.length ? [`fewer than 5 labeled incidents for: ${thin.join(', ')}`] : [])] };
721
- fs.writeFileSync(o.fit, JSON.stringify(fitted, null, 1));
722
- }
723
- if (J) { Object.assign(OUT, { benchmark: { sources: parts, top1: sum.top1, top3: sum.top3, lenientTop1: sum.lenientTop1, componentTop1: sum.componentTop1, byScenario: sum.byScenario, misses: sum.misses.map(m => ({ id: m.id, cause: m.cause, top: m.top, rank: m.rank })) }, injections: inj && { injections: inj.injections, detected: inj.detected, delayP50: inj.delayP50, delayP90: inj.delayP90, rows: inj.rows.map(({ hyps, ...r }) => r) }, fitted }); }
724
- else {
725
- say(`${sum.incidents} labeled incidents (${parts.join(' + ')}): top-1 ${pct(sum.top1)}, top-3 ${pct(sum.top3)}${sum.lenientTop1 !== sum.top1 ? `, top-1 counting equivalent causes ${pct(sum.lenientTop1)}` : ''}${sum.componentTop1 != null ? `, component named ${pct(sum.componentTop1)}` : ''}`);
726
- for (const [k, b] of Object.entries(sum.byScenario)) say(` ${(b.top1 + '/' + b.n).padStart(7)} ${k}${b.top1 < b.n ? ` ranked first: ${Object.entries(b.tops).map(([r, n]) => `${r} ${n}`).join(', ')}` : ''}`);
727
- if (inj) say(`injected faults: ${inj.injections}, detected ${pct(inj.detected)}, alarm after ${inj.delayP50 != null ? Math.round(inj.delayP50 / 60) : '–'} min (p50) / ${inj.delayP90 != null ? Math.round(inj.delayP90 / 60) : '–'} min (p90)`);
728
- if (inj) for (const r of inj.rows) say(` ${r.id}: ${r.detected ? `detected after ${Math.round(r.delayS / 60)} min` : 'not detected'}; ${r.cause ? `expected ${r.cause}, ranked ${r.rank ?? 'not found'} (top: ${r.top || 'none'})` : `top: ${r.top || 'none'} (detection only)`}`);
729
- if (fitted) { say(`weights written to ${o.fit}: ${Object.entries(fitted.rules).filter(([, v]) => v !== 1).map(([k, v]) => `${k} ×${v}`).join(', ') || 'all 1'}; held-out top-1 ${pct(fitted.heldOut.top1Before)} → ${pct(fitted.heldOut.top1After)}`); for (const w of fitted.warnings) say(` warning: ${w}`); }
730
- }
731
- const minT1 = o['min-top1'] ? +o['min-top1'] : null, minT3 = o['min-top3'] ? +o['min-top3'] : null;
732
- if ((minT1 != null && sum.top1 < minT1) || (minT3 != null && sum.top3 < minT3)) { console.error(`below the bar: top-1 ${pct(sum.top1)} (min ${pct(minT1)}), top-3 ${pct(sum.top3)} (min ${pct(minT3)})`); process.exitCode = 5; }
733
- }
734
-
735
- const hdrs = o => Object.fromEntries([].concat(o.header || []).filter(h => h !== true).map(h => { const i = String(h).indexOf(':'); return [h.slice(0, i).trim(), h.slice(i + 1).trim()]; }));
736
- const lokiQueries = o => [].concat(o['loki-query'] || ['{job=~".*kernel.*|.*syslog.*"}', '{container=~".+"} |~ "NCCL WARN|Watchdog caught|CUDA error|OutOfMemoryError"']).filter(q => q !== true);
737
- const dur = v => { const m = String(v || '').match(/^(\d+(?:\.\d+)?)([smhd]?)$/); return m ? +m[1] * { '': 1, s: 1, m: 60, h: 3600, d: 86400 }[m[2]] : undefined; };
738
-
739
- // Pull a window from Prometheus and/or Loki into the store.
740
- async function pull(store, cmd, o) {
741
- const from = time(o.from), to = time(o.to) ?? Math.floor(Date.now() / 1000);
742
- if (from == null) throw new Error('pull needs --from (and --to, default now)');
743
- const out = {};
744
- if (o.prom && o.prom !== true) out.prometheus = await Pull.pullPrometheus(store, o.prom, { from, to, step: o.step ? +o.step : 60, headers: hdrs(o) });
745
- if (o.loki && o.loki !== true) out.loki = await Pull.pullLoki(store, o.loki, lokiQueries(o), { from, to, headers: hdrs(o) });
746
- if (!out.prometheus && !out.loki) throw new Error('pull --prom URL and/or --loki URL');
747
- if (J) { OUT.pulled = out; return; }
748
- if (out.prometheus) say(`Prometheus: ${out.prometheus.device} device samples, ${out.prometheus.serving} serving rows, ${out.prometheus.collective} NCCL collective rows (${out.prometheus.unmapped} unmapped series samples)`);
749
- if (out.loki) say(`Loki: ${out.loki.lines} lines → ${out.loki.logs} classified log records (${out.loki.unmatched} not matched)`);
750
- }
751
-
752
- // Backtest: pull each labeled incident's window from the fleet's own monitoring and score root-cause analysis on it.
753
- async function backtest(store, o) {
754
- if (!o.labels || o.labels === true) throw new Error('backtest --labels postmortems.jsonl --prom URL [--loki URL]');
755
- const labels = read(o.labels).split(/\r?\n/).filter(l => l.trim()).map(l => JSON.parse(l)).map(l => Object.assign(l, { incident: Object.assign({}, l.incident, { from: time(l.incident.from), to: time(l.incident.to) }) }));
756
- const lookback = dur(o.lookback) ?? 26 * 3600, pulled = [];
757
- for (const l of labels) {
758
- const w = { from: l.incident.from - lookback, to: l.incident.to + 3600 }, got = { id: l.incident.id || `${l.cause}@${l.incident.from}` };
759
- if (o.prom && o.prom !== true) got.prometheus = await Pull.pullPrometheus(store, o.prom, Object.assign({ step: o.step ? +o.step : 60, headers: hdrs(o) }, w));
760
- if (o.loki && o.loki !== true) got.loki = await Pull.pullLoki(store, o.loki, lokiQueries(o), Object.assign({ headers: hdrs(o) }, w));
761
- pulled.push(got);
762
- if (!J) say(` pulled ${got.id}: ${got.prometheus ? `${got.prometheus.device} device, ${got.prometheus.serving} serving` : ''}${got.loki ? `, ${got.loki.logs} log records` : ''}`);
763
- }
764
- const weights = o.weights && o.weights !== true ? JSON.parse(read(o.weights)) : undefined;
765
- const rows = Bench.evalLabels(store, labels, { weights }), sum = Bench.summarize(rows);
766
- if (J) { Object.assign(OUT, { backtest: { incidents: rows.length, top1: sum.top1, top3: sum.top3, componentTop1: sum.componentTop1, rows: rows.map(({ hyps, ...r }) => Object.assign(r, { ranked: hyps.slice(0, 3) })) }, pulled }); return; }
767
- const pc = v => (v == null ? '–' : `${(v * 100).toFixed(1)}%`);
768
- say(`backtest on ${rows.length} confirmed incidents: top-1 ${pc(sum.top1)}, top-3 ${pc(sum.top3)}${sum.componentTop1 != null ? `, component ${pc(sum.componentTop1)}` : ''}`);
769
- for (const r of rows) say(` ${r.rank === 1 ? 'ok ' : 'MISS'} ${r.id}: confirmed ${r.cause}${r.component ? ` (${r.component})` : ''}; ranked ${r.rank ?? 'not found'}${r.rank !== 1 ? `, top: ${r.top || 'none'} ${r.hyps[0] ? r.hyps[0].score.toFixed(2) : ''}` : ''}`);
770
- if (sum.misses.length) say('A miss usually means a signal the store didn\'t get (no logs for that window, no topology) or a rule gap: check `fleetops data node` for the component and the window.');
771
- }
772
-
773
- // Game day: run a plan of injections on a test cluster one after another, then score them.
774
- async function gameday(store, cmd, o) {
775
- const planFile = cmd && cmd !== true ? cmd : o.plan;
776
- if (!planFile) throw new Error('gameday PLAN.json --allow FILE [--live] [--cooldown 900] [--prom URL --loki URL]');
777
- const plan = JSON.parse(read(planFile)), allow = Inject.loadAllow(o.allow && o.allow !== true ? o.allow : process.env.FLEETOPS_INJECT_ALLOW);
778
- const steps = plan.steps || plan, cool = o.cooldown ? +o.cooldown : plan.cooldownS ?? 900, live = !!o.live;
779
- const preps = steps.map(st => { const { fault, forS, ...params } = st; return { st, prep: Inject.prepare(fault, params, { allow }) }; }); // check every step before running any
780
- const done = [];
781
- for (const [i, { st, prep }] of preps.entries()) {
782
- if (!J) say(`step ${i + 1}/${preps.length}: ${prep.fault} on ${prep.nodes.join(', ') || prep.params.release || prep.params.host} for ${st.forS || 300} s (expect ${prep.expect || 'detection only'})`);
783
- const r = await Inject.run(prep, { live, forS: st.forS || 300, store, log: J ? () => {} : l => say(' ' + l.trim()) });
784
- done.push(r);
785
- if (live && i < preps.length - 1) { if (!J) say(` cooling down ${cool} s`); await new Promise(res => setTimeout(res, cool * 1000)); }
786
- }
787
- if (!live) { if (!J) say('dry run: nothing was run. Add --live on a test cluster.'); else OUT.gameday = { dryRun: true, steps: preps.length }; return; }
788
- if (o.prom || o.loki) { const lo = Math.min(...done.map(d => d.from)) - 26 * 3600, hi = Math.max(...done.map(d => d.to || d.from)) + 3600; if (o.prom && o.prom !== true) await Pull.pullPrometheus(store, o.prom, { from: lo, to: hi, headers: hdrs(o) }); if (o.loki && o.loki !== true) await Pull.pullLoki(store, o.loki, lokiQueries(o), { from: lo, to: hi, headers: hdrs(o) }); }
789
- const r = Bench.evalInjections(store, { from: Math.min(...done.map(d => d.from)) - 1, to: Math.max(...done.map(d => d.to || d.from)) + 1 });
790
- if (J) { OUT.gameday = { injections: r.injections, detected: r.detected, delayP50: r.delayP50, delayP90: r.delayP90, top1: r.diagnosis.top1, rows: r.rows.map(({ hyps, ...x }) => x) }; return; }
791
- say(`game day: ${r.injections} injections, detected ${(r.detected * 100).toFixed(0)}%, alarm after ${r.delayP50 != null ? Math.round(r.delayP50 / 60) : '–'} min (p50); diagnosis top-1 ${r.diagnosis.incidents ? (r.diagnosis.top1 * 100).toFixed(0) + '%' : '–'}`);
792
- for (const x of r.rows) say(` ${x.id}: ${x.detected ? `detected after ${Math.round(x.delayS / 60)} min` : 'not detected'}; ${x.cause ? `expected ${x.cause}, ranked ${x.rank ?? 'not found'}` : `top ${x.top}`}`);
793
- }
794
-
795
- // The incident workflow: open from detection, lifecycle, paging, timeline, postmortem.
796
- async function incidents(store, cmd, rest, o) {
797
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), id = rest[0];
798
- if (!cmd || cmd === 'list') {
799
- const all = Inc.state(store).filter(s => !opt('status') || s.status === o.status);
800
- if (J) { OUT.incidents = all.map(({ events, diagnosis, ...s }) => Object.assign(s, { top: diagnosis && diagnosis.hypotheses[0] && diagnosis.hypotheses[0].title })); return; }
801
- for (const s of all) say(`${s.severity} ${s.status.padEnd(12)} ${s.id}${s.owner ? ` @${s.owner}` : ''}${s.cause ? ` cause: ${s.cause}` : s.diagnosis && s.diagnosis.hypotheses[0] ? ` likely: ${s.diagnosis.hypotheses[0].rule}` : ''}`);
802
- if (!all.length) say('no incidents');
803
- return;
804
- }
805
- if (cmd === 'open') {
806
- // detect in the window, diagnose each, open the new ones
807
- const from = time(o.from), to = time(o.to), weights = opt('weights') ? JSON.parse(read(o.weights)) : undefined;
808
- const incs = Detect.groupIncidents([...Detect.detectJobFailures(store, { from, to, binS: o.bin ? +o.bin : 600, minFailures: o['min-failures'] ? +o['min-failures'] : 20, where: whereFrom(o.where) }), ...Detect.detectServing(store, { from, to }), ...Detect.detectTraining(store, { from, to })]);
809
- const opened = [];
810
- for (const i of incs) { const d = RCA.diagnose(store, i, { weights }); if (!store.query('incident', { where: x => x.id === d.id }).length) store.append('incident', [d]); const e = Inc.open(store, d, { by: opt('by') || 'fleetops' }); if (e) opened.push(e); }
811
- if (J) { OUT.opened = opened; return; }
812
- say(`${incs.length} incident(s) detected, ${opened.length} new`); for (const e of opened) say(` ${e.severity} ${e.id} ${e.summary}`);
813
- return;
814
- }
815
- if (!id) throw new Error(`incidents ${cmd} ID`);
816
- if (['acknowledge', 'ack', 'mitigate', 'resolve', 'reopen', 'assign', 'severity', 'note'].includes(cmd)) {
817
- const e = Inc.transition(store, id, cmd === 'ack' ? 'acknowledge' : cmd, { by: opt('by'), note: opt('note'), owner: opt('owner'), severity: opt('severity'), cause: opt('cause'), component: opt('component') });
818
- if (J) { OUT.event = e; return; }
819
- say(`${id}: ${e.event}${e.cause ? ` (confirmed cause ${e.cause}${e.component ? `, ${e.component}` : ''}: stored as a label for rca bench --from-incidents)` : ''}`);
820
- return;
821
- }
822
- if (cmd === 'show') {
823
- const s = Inc.state(store, id); if (!s) throw new Error(`no incident ${id}`);
824
- if (J) { OUT.incident = s; return; }
825
- say(`${s.id} ${s.severity} · ${s.status}${s.owner ? ` · @${s.owner}` : ''}${s.cause ? ` · cause ${s.cause}` : ''}`);
826
- for (const e of s.events) say(` ${fmt(e.t)} ${e.event} by ${e.by}${e.note ? `: ${e.note}` : ''}`);
827
- if (s.diagnosis) { say(' ranked causes:'); s.diagnosis.hypotheses.slice(0, 3).forEach((h, i) => say(` ${i + 1}. ${h.title} (${h.rule}, ${h.score.toFixed(2)})`)); }
828
- return;
829
- }
830
- if (cmd === 'timeline' || cmd === 'postmortem') {
831
- const out = cmd === 'timeline' ? Inc.timelineHtml(store, id) : Inc.postmortem(store, id);
832
- if (opt('out')) { fs.writeFileSync(o.out, out); say(`written to ${o.out}`); } else console.log(out);
833
- return;
834
- }
835
- if (cmd === 'page') {
836
- const provider = opt('to') || 'pagerduty', key = opt('key') || process.env[provider === 'opsgenie' ? 'OPSGENIE_API_KEY' : 'PAGERDUTY_ROUTING_KEY'];
837
- const r = await Inc.page(store, id, provider, opt('action') || 'trigger', { live: !!o.live, key, url: opt('url'), by: opt('by') || 'fleetops' });
838
- if (J) { OUT.page = r; return; }
839
- if (r.dryRun) { say(`dry run (--live to send): POST ${r.request.url}`); say(JSON.stringify(Object.assign({}, r.request.body, r.request.body.routing_key ? { routing_key: '…' } : {}), null, 1)); }
840
- else say(`${provider} ${o.action || 'trigger'}: HTTP ${r.status}${r.ok ? '' : ' (failed)'}`);
841
- return;
842
- }
843
- throw new Error(`unknown: incidents ${cmd}`);
844
- }
845
-
846
- // Fault injection on a test cluster (dry-run unless --live; targets must be in the --allow file).
847
- async function inject(store, cmd, o) {
848
- if (!cmd || cmd === 'list') {
849
- if (J) { OUT.faults = Object.fromEntries(Object.entries(Inject.FAULTS).map(([k, f]) => [k, { what: f.what, params: Object.keys(f.params), expect: f.expect, undo: !!f.revert, note: f.note }])); return; }
850
- for (const [k, f] of Object.entries(Inject.FAULTS)) say(` ${k.padEnd(13)} ${f.what}\n --${Object.keys(f.params).join(' --')}${f.revert ? ' [--for S]' : ''} expect: ${f.expect || 'detection only'}${f.note ? `\n ${f.note}` : ''}`);
851
- return;
852
- }
853
- const allowFile = o.allow && o.allow !== true ? o.allow : process.env.FLEETOPS_INJECT_ALLOW;
854
- if (!allowFile) throw new Error('--allow FILE (or FLEETOPS_INJECT_ALLOW): the test-cluster targets injection may touch, one per line');
855
- const params = Object.fromEntries(Object.entries(o).filter(([k]) => !['_', 'where', 'store', 'allow', 'live', 'for', 'json'].includes(k)));
856
- const prep = Inject.prepare(cmd, params, { allow: Inject.loadAllow(allowFile) });
857
- const r = await Inject.run(prep, { live: !!o.live, forS: o.for ? +o.for : 300, store, log: J ? () => {} : console.log });
858
- if (J) OUT.injection = r; else if (!r.dryRun) say(`${r.id}: ${r.applied ? 'applied' : 'FAILED to apply'}${r.reverted != null ? `, reverted ${r.reverted ? 'ok' : 'with errors'}` : ''}; label written to the store (expect ${r.expect || 'detection only'})`);
859
- }
860
-
861
- const money = v => '$' + Math.round(v).toLocaleString('en-US');
862
- // What the fleet costs per week now: GPUs in the inventory (or, without one, distinct GPUs seen) × 168 h × price.
863
- function baselineWeekly(store, from, to, price) {
864
- const nodes = new Map(); for (const r of store.scan('inventory', { to })) if (r.kind !== 'cpu') nodes.set(r.node, r.devices || 0);
865
- let n = [...nodes.values()].reduce((a, b) => a + b, 0);
866
- if (!n) { const g = new Set(); for (const r of store.scan('device', { from, to })) g.add(`${r.node}:${r.gpu}`); n = g.size; }
867
- return n * 168 * price;
868
- }
869
- async function powerCmd(store, cmd, o) {
870
- const opt = k => (o[k] != null && o[k] !== true ? o[k] : undefined), json = k => (opt(k) ? JSON.parse(read(opt(k))) : undefined), now = o.now ? +o.now : Math.floor(Date.now() / 1000);
871
- const to = time(opt('to')) ?? now, from = time(opt('from')) ?? to - (opt('hours') ? +opt('hours') * 3600 : 24 * 3600);
872
- const opts = Object.assign({}, json('options'), opt('fit-alpha') ? { alphaCompute: +opt('fit-alpha') } : {}, opt('max-slowdown') ? { maxSlowdown: +opt('max-slowdown') } : {}, opt('gpu-share') ? { gpuShare: +opt('gpu-share') } : {});
873
- const kw = v => (v == null || !Number.isFinite(v) ? '–' : v >= 100 ? Math.round(v).toLocaleString('en-US') : v.toFixed(1));
874
- if (cmd === 'demo') {
875
- const d = Power.synth(); for (const [k, rs] of Object.entries(d.records)) store.append(k, rs);
876
- const bf = path.join(store.dir, 'power-budgets.json'); fs.writeFileSync(bf, JSON.stringify(d.budgets, null, 1));
877
- if (J) { OUT.demo = { from: d.from, to: d.to, budgets: bf }; return; }
878
- return say(`demo in ${store.dir}: two racks of four 8×H100 nodes, rack r1 over its 24 kW budget; budgets in ${bf}\ntry: fleetops power report --budgets ${bf} --from ${d.from} --to ${d.to} --store ${store.dir}\n fleetops power plan --budgets ${bf} --from ${d.from} --to ${d.to} --out plan.json --store ${store.dir}`);
879
- }
880
- if (cmd === 'report') {
881
- const r = Power.report(store, { from, to, budgets: json('budgets') || {}, opts });
882
- if (J) { OUT.power = r; return; }
883
- if (!r.groups.length) return say(r.note);
884
- say(`${r.nodes} node(s), ${r.bins} × ${r.binS / 60}-min bins; ${r.note}\n`);
885
- say(`${'group'.padEnd(18)} ${'nodes'.padStart(5)} ${'avg kW'.padStart(8)} ${'p99 kW'.padStart(8)} ${'budget'.padStart(8)} ${'headroom'.padStart(9)} more nodes`);
886
- for (const g of r.groups) say(`${g.group.padEnd(18)} ${String(g.nodes).padStart(5)} ${kw(g.avgKw).padStart(8)} ${kw(g.p99Kw).padStart(8)} ${kw(g.budgetKw).padStart(8)} ${(g.headroomKw == null ? '–' : (g.headroomKw < 0 ? 'OVER ' : '') + kw(g.headroomKw)).padStart(9)} ${g.moreNodes == null ? '' : `${g.moreNodes} × ${g.sku} at ${kw(g.nodeKwP95)} kW (p95)`}${g.overBudgetShare ? ` over ${Math.round(g.overBudgetShare * 100)}% of the time` : ''}`);
887
- return;
888
- }
889
- if (cmd === 'jobs' || cmd === 'predict') {
890
- let js = Power.jobs(store, { from, to, opts }); if (opt('job')) js = js.filter(j => j.job === opt('job'));
891
- const cap = opt('cap'), capW = j => (!cap ? null : /%$/.test(cap) ? parseFloat(cap) / 100 * j.limitW : parseFloat(cap));
892
- if (cmd === 'predict' && !cap) throw new Error('--cap 70% or --cap 500W');
893
- const rows = js.map(j => Object.assign({}, j, { draws: undefined, devices: undefined }, cap ? { prediction: Power.predict(j, capW(j), opts) } : {}));
894
- if (cmd === 'predict') rows.sort((a, b) => a.prediction.slowdown - b.prediction.slowdown);
895
- if (J) { OUT.jobs = rows; return; }
896
- for (const j of rows) say(`${j.job.padEnd(22)} ${String(j.gpus).padStart(4)} GPU draw ${kw(j.drawP50)}/${kw(j.drawP95)} W (p50/p95) of ${kw(j.limitW)} compute-bound ${Math.round(j.computeBound * 100)}% at limit ${Math.round(j.atLimitShare * 100)}%${j.stepsPerKWh ? ` ${kw(j.stepsPerKWh)} steps/kWh` : ''}${j.prediction ? `\n${''.padEnd(24)}cap ${Math.round(j.prediction.capW)} W → ${(j.prediction.slowdown * 100).toFixed(1)}% slower, −${kw(j.prediction.savedKw)} kW IT${j.prediction.note ? ` (${j.prediction.note})` : ''}` : ''}`);
897
- return;
898
- }
899
- if (cmd === 'fit') { const f = Power.fit(store, { from: time(opt('from')), to }); if (J) { OUT.fit = f; return; } return say(f.alphaCompute == null ? f.note : `${f.note}\nuse it: --fit-alpha ${f.alphaCompute.toFixed(2)} (or options.alphaCompute)`); }
900
- if (cmd === 'plan') {
901
- if (!opt('out')) throw new Error('--out plan.json');
902
- const cfg = ghConfig(json('config')), state = opt('state') || path.join(store.dir, 'rollouts', 'state');
903
- const p = Power.plan(store, { from, to, budgets: json('budgets') || {}, saveKw: opt('save-kw') ? +opt('save-kw') : null, opts, protect: (opt('protect') || '').split(',').filter(Boolean), cfg, id: opt('id') });
904
- const guards = json('guards') || {}; for (const s of p.stages) s.guard = guards[s.candidate] || guards.default || null;
905
- p.state = state; const ids = Opt.enqueue(p, state, now); Opt.savePlan(opt('out'), p);
906
- if (J) { OUT.plan = p; OUT.queued = ids; return; }
907
- if (!p.groups.length) return say('every group with a budget is under it: nothing to cap');
908
- for (const g of p.groups) say(`${g.group}: p99 ${kw(g.p99Kw)} kW against ${kw(g.budgetKw)} → ${g.met ? 'under budget' : 'STILL OVER'} with caps saving ${kw(g.savedKw)} of ${kw(g.needKw)} kW needed`);
909
- for (const c of p.caps) say(` ${c.job.padEnd(22)} ${c.class || ''} ${c.capW} W (${Math.round(c.capPct * 100)}% of ${Math.round(c.limitW)}) on ${c.gpus} GPU(s): ${(c.predictedSlowdown * 100).toFixed(1)}% slower, −${kw(c.savedKw)} kW (draws ${kw(c.drawP95)} W p95, ${Math.round(c.computeBound * 100)}% compute-bound)`);
910
- say(`${p.stages.length} stage(s) queued for approval in ${state}; then: fleetops optimize advance --plan ${opt('out')}`);
911
- say(`model: slowdown = (draw/cap)^α, α ${p.assumptions.alphaCompute} compute-bound … ${p.assumptions.alphaMemory} memory-bound${opt('fit-alpha') ? ' (fitted)' : ' (defaults: run fleetops power fit to measure)'}`);
912
- return;
913
- }
914
- if (cmd === 'verify') {
915
- const p = JSON.parse(read(opt('plan') || '')), v = Power.verify(store, p, { now, opts });
916
- if (J) { OUT.verification = v; return; }
917
- if (!v.groups) return say(v.note);
918
- for (const g of v.groups) say(`${g.group}: p99 ${kw(g.p99Before)} → ${kw(g.p99After)} kW (saved ${kw(g.measuredSavedKw)}, predicted ${kw(g.predictedSavedKw)})`);
919
- for (const j of v.jobs) say(` ${j.job}: ${j.measuredSlowdown == null ? 'no step records' : `${(j.measuredSlowdown * 100).toFixed(1)}% slower`} (predicted ${(j.predictedSlowdown * 100).toFixed(1)}%)`);
920
- return;
921
- }
922
- throw new Error('fleetops power report | jobs | predict | fit | plan | verify | demo');
923
- }
924
-
925
- async function admitCmd(store, cmd, o) {
926
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), now = o.now ? +o.now : Math.floor(Date.now() / 1000);
927
- const policy = opt('policy') ? JSON.parse(read(opt('policy'))) : {}, state = opt('state') || path.join(store.dir, 'rollouts', 'state'), cfg = ghConfig(opt('config') ? JSON.parse(read(opt('config'))) : undefined);
928
- if (cmd === 'pending') {
929
- const p = Adm.pending(store, { now, policy }); if (J) { OUT.pending = p; return; }
930
- if (!p.length) return say('no nodes waiting for admission');
931
- for (const x of p) say(`${x.node}${x.sku ? ` (${x.sku})` : ''}: ${x.reasons.join('; ')}${x.last ? ` — last verdict ${x.last.verdict}` : ''}`);
932
- return say(`\nfleetops admit check NODE (run tools/admit-node.sh on the node and import its output first)`);
933
- }
934
- const node = o._[2]; if (!node) throw new Error('fleetops admit check|apply NODE');
935
- const v = Adm.evaluate(store, node, { now, policy });
936
- if (cmd === 'check') {
937
- if (o.record) store.append('admission', [{ t: now, node, verdict: v.verdict, failed: v.failed, missing: v.missing, sku: v.sku, source: 'fleetops-admit' }]);
938
- if (v.verdict === 'reject') process.exitCode = 3; else if (v.verdict === 'incomplete') process.exitCode = 2;
939
- if (J) { OUT.admission = v; return; }
940
- say(`${node}${v.sku ? ` (${v.sku})` : ''}: ${v.verdict.toUpperCase()}`);
941
- for (const c of v.checks) say(` ${c.status === 'pass' ? 'pass' : c.status === 'fail' ? 'FAIL' : 'miss'} ${c.name.padEnd(11)} ${c.evidence}${c.fix ? `\n → ${c.fix}` : ''}`);
942
- return;
943
- }
944
- if (cmd === 'apply') {
945
- // admitting releases the node and needs a person's approval in gpu-health's queue; rejecting keeps it out
946
- const a = Adm.gateAction(v, now); if (!a) { if (J) { OUT.admission = v; return; } return say(`${node}: incomplete (${v.missing.join(', ')}); nothing to apply`); }
947
- a.mode = (cfg.policy.actions || {})[a.kind] || (a.kind === 'admit-node' ? 'approve' : 'auto');
948
- const st = new GhStore(state), prior = st.data.actions.find(x => x.kind === a.kind && x.node === node && ['proposed', 'approved'].includes(x.status));
949
- const act = prior || Object.assign(a, { status: a.mode === 'auto' ? 'approved' : 'proposed' });
950
- if (!prior) { st.data.actions.push(act); st.audit(act, 'created', { status: act.status, mode: act.mode, reason: act.reason }); }
951
- store.append('admission', [{ t: now, node, verdict: v.verdict, failed: v.failed, missing: v.missing, sku: v.sku, source: 'fleetops-admit' }]);
952
- let r = null;
953
- if (act.status === 'approved') {
954
- r = await runAction(act, cfg, { dryRun: !(o.live && cfg.policy.dryRun === false) });
955
- Object.assign(act, { status: r.dryRun ? 'approved' : r.ok ? 'executed' : 'failed', updatedAt: now }); st.audit(act, r.dryRun ? 'dry-run' : r.ok ? 'executed' : 'failed', { commands: r.commands, text: r.text });
956
- }
957
- st.save();
958
- if (J) { OUT.admission = v; OUT.action = act; OUT.result = r; return; }
959
- say(`${node}: ${v.verdict}`);
960
- if (!r) return say(` ${act.kind} waits for approval: gpu-health actions approve ${act.id} --by NAME --state ${state}, then run this again`);
961
- say(` ${act.kind} ${r.dryRun ? 'dry run' : r.ok ? 'done' : 'failed'}: ${(r.commands || []).map(c => c.join(' ')).join(' && ') || r.text}`);
962
- if (r.dryRun) say(' (add --live, with policy.dryRun false in the gpu-health config, to run it)');
963
- return;
964
- }
965
- throw new Error('fleetops admit pending | check NODE [--record] | apply NODE [--live]');
966
- }
967
-
968
- async function rolloutCmd(store, cmd, o) {
969
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), now = o.now ? +o.now : Math.floor(Date.now() / 1000), json = k => (opt(k) ? JSON.parse(read(opt(k))) : undefined);
970
- const state = opt('state') || path.join(store.dir, 'rollouts', 'state'), cfg = ghConfig(json('config'));
971
- const hours = s => (s == null ? undefined : /h$/.test(s) ? parseFloat(s) * 3600 : /m$/.test(s) ? parseFloat(s) * 60 : +s);
972
- if (cmd === 'demo') {
973
- const d = RO.synth({ bad: !o.good }); for (const [k, rs] of Object.entries(d.records)) store.append(k, rs);
974
- if (J) { OUT.demo = { canary: d.canary, canaryAt: d.canaryAt, end: d.end, old: d.old, new: d.neu, bad: !o.good }; return; }
975
- return say(`demo fleet in ${store.dir}: 24 H100 nodes on driver ${d.old}; ${d.canary.join(' and ')} moved to ${d.neu} on ${new Date(d.canaryAt * 1000).toISOString().slice(0, 16)}${o.good ? '' : ' (a bad driver)'}\ntry: fleetops rollout check --field driver --version ${d.neu} --from ${d.canaryAt} --to ${d.end} --store ${store.dir}`);
976
- }
977
- if (cmd === 'check') {
978
- if (!opt('field') || !opt('version')) throw new Error('--field driver --version V [--from T] [--to T]');
979
- const to = time(opt('to')) ?? now, g = RO.compare(store, { field: opt('field'), version: opt('version'), since: time(opt('from')) ?? to - 7 * 86400, now: to, policy: json('policy') });
980
- if (J) { OUT.comparison = g; if (g.ok === false) process.exitCode = 4; return; }
981
- say(`${opt('field')} ${opt('version')} on ${(g.treated || []).length} node(s) vs ${g.control ?? 0} on other versions: ${g.ok === false ? 'REGRESSION' : g.ok ? 'no regression' : 'not enough data yet'}`);
982
- for (const m of g.metrics) say(` ${m.regression ? 'WORSE' : 'ok '} ${m.name}: ×${m.ratio.toFixed(2)}${m.p != null ? ` (p ${m.p < 1e-4 ? '<1e-4' : m.p.toFixed(4)})` : ''} ${m.detail}`);
983
- if (g.ok == null) say(` ${g.note}`);
984
- if (g.ok === false) process.exitCode = 4;
985
- return;
986
- }
987
- if (cmd === 'plan') {
988
- if (!opt('out')) throw new Error('--out rollout.json');
989
- const tmpl = k => (opt(k) ? [opt(k).split(' ').filter(Boolean)] : undefined); // "ansible-playbook driver.yml -l {node} -e v={version}"
990
- const p = RO.plan(store, { field: opt('field'), version: opt('version'), nodes: opt('nodes'), sku: opt('sku'), canary: opt('canary') ?? 2, waves: opt('waves') ? opt('waves').split(',') : undefined, bakeS: hours(opt('bake')), apply: tmpl('apply'), rollback: tmpl('rollback'), id: opt('id'), now, policy: json('policy') });
991
- p.state = state; const ids = RO.enqueue(p, state, now); fs.writeFileSync(opt('out'), JSON.stringify(p, null, 1));
992
- if (J) { OUT.plan = p; OUT.queued = ids; return; }
993
- say(`${p.id}: ${p.field} ${p.from} → ${p.version} on ${p.stages.reduce((a, s) => a + s.nodes.length, 0)} node(s), ${p.stages.length} wave(s), each queued for approval in ${state}:`);
994
- for (const s of p.stages) say(` ${s.n}. ${s.title}: ${s.nodes.slice(0, 6).join(', ')}${s.nodes.length > 6 ? ` … +${s.nodes.length - 6}` : ''} (bake ${(s.bakeS / 3600).toFixed(1)} h)`);
995
- return say(`then: gpu-health actions approve ${ids[0]} --by NAME --state ${state}; fleetops rollout advance --plan ${opt('out')}`);
996
- }
997
- const planFile = opt('plan'); if (!planFile) throw new Error('fleetops rollout demo | check | plan | advance --plan FILE | status --plan FILE');
998
- const p = JSON.parse(read(planFile));
999
- if (cmd === 'advance') {
1000
- const poster = (url, text) => { Sec.checkEgress(url); return postWebhook(url, text); };
1001
- const r = await RO.advance(p, { store, stateDir: opt('state') || p.state || state, cfg, live: !!o.live, now, poster });
1002
- fs.writeFileSync(planFile, JSON.stringify(p, null, 1));
1003
- if (J) { OUT.plan = p; OUT.log = r.log; return; }
1004
- for (const l of r.log) say(l); say(`${p.id}: ${p.status}`);
1005
- if (p.status === 'halted') process.exitCode = 4;
1006
- return;
1007
- }
1008
- if (cmd === 'status') { if (J) { OUT.plan = p; return; } say(`${p.id}: ${p.status}${p.haltReason ? ` — ${p.haltReason}` : ''}`); for (const s of p.stages) say(` ${s.n}. ${s.status.padEnd(11)} ${s.title}${s.guardResult ? ` [${s.guardResult.note}]` : ''}`); return; }
1009
- throw new Error(`unknown: rollout ${cmd}`);
1010
- }
1011
-
1012
- async function optimize(store, cmd, o) {
1013
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), json = k => (opt(k) ? JSON.parse(read(opt(k))) : undefined);
1014
- const now = o.now ? +o.now : Math.floor(Date.now() / 1000), price = o.price ? +o.price : 4;
1015
- const state = opt('state') || path.join(store.dir, 'rollouts', 'state');
1016
- const cfg = ghConfig(json('config'));
1017
- if (cmd === 'candidates') {
1018
- const from = time(o.from), to = time(o.to);
1019
- const cands = [...Opt.fromGpuHealth(store, { from, to, cfg }), ...Opt.fromRetryStorms(store, { from, to, price, maxAttempts: o['max-attempts'] ? +o['max-attempts'] : 2 })];
1020
- if (opt('graph')) {
1021
- // the store's requests go through the same CSV and parser as FleetScope's own --trace option
1022
- const rows = opt('trace-pool') ? FSIN.parseTrace(toFleetScopeTrace(store, { pool: o['trace-pool'], from: time(o['trace-from']), to: time(o['trace-to']) })).trace : null;
1023
- if (rows && !rows.length) throw new Error(`no request records for pool ${o['trace-pool']}`);
1024
- if (rows) say(`replaying ${rows.length} requests of ${o['trace-pool']} through the graph`);
1025
- cands.push(...Opt.fromFleetScope(json('graph'), { target: o.target ? +o.target : 0.99, traceRows: rows }));
1026
- }
1027
- const out = { from, to, price, baselineWeekly: baselineWeekly(store, from, to, price), candidates: cands.map(c => Object.assign({}, c, { graph: undefined })) };
1028
- if (opt('out')) fs.writeFileSync(o.out, JSON.stringify(out, null, 1));
1029
- if (J) { Object.assign(OUT, out); return; }
1030
- say(`${cands.length} candidates (fleet ≈ ${money(out.baselineWeekly)}/week at $${price}/GPU-hour)`);
1031
- say(' savings/week risk SLO candidate');
1032
- for (const c of cands.slice().sort((a, b) => b.savingsWeekly - a.savingsWeekly)) say(` ${money(c.savingsWeekly).padStart(11)} ${c.risk.padEnd(6)} ${(c.protected ? 'PROTECTED' : c.slo.impact).padEnd(24)} ${c.title}${c.realized ? ` (${c.realized})` : ''}`);
1033
- if (opt('out')) say(`written to ${o.out}`);
1034
- return;
1035
- }
1036
- if (cmd === 'plan') {
1037
- const c = json('candidates'); if (!c || !opt('out')) throw new Error('--candidates FILE --out plan.json');
1038
- const sel = Opt.select(c.candidates, { savePct: o['save-pct'] ? +o['save-pct'] : undefined, baselineWeekly: o['baseline-weekly'] ? +o['baseline-weekly'] : c.baselineWeekly, maxRisk: opt('max-risk') || 'medium' });
1039
- const plan = Opt.planRollout(sel, { guards: json('guards') || {}, deployments: json('deployments') || {}, bakeS: o.bake ? +o.bake : 1800, cfg });
1040
- plan.goal = { savePct: o['save-pct'] ? +o['save-pct'] : null, baselineWeekly: sel.baselineWeekly, savedPct: sel.savedPct, meetsGoal: sel.meetsGoal }; plan.skipped = sel.skipped; plan.state = state;
1041
- const ids = Opt.enqueue(plan, state, now);
1042
- Opt.savePlan(o.out, plan);
1043
- if (J) { OUT.plan = plan; OUT.queued = ids; return; }
1044
- say(`plan ${plan.id}: ${money(plan.totalWeekly)}/week${plan.potentialWeekly > plan.totalWeekly ? ` firm, up to ${money(plan.potentialWeekly)} if notified owners act` : ''}${sel.savedPct != null ? ` (${(sel.savedPct * 100).toFixed(1)}% of ${money(sel.baselineWeekly)})` : ''}${plan.goal.savePct ? ` — goal ${plan.goal.savePct}% ${sel.meetsGoal ? 'met' : 'NOT met'}` : ''}`);
1045
- const many = plan.candidates.length > 8;
1046
- for (const x of many ? plan.candidates.slice(0, 6) : plan.candidates) say(` + ${x.title} ${money(x.savingsWeekly)}/week, risk ${x.risk}`);
1047
- if (many) say(` + … ${plan.candidates.length - 6} more`);
1048
- for (const x of sel.skipped.slice(0, 8)) say(` - ${x.id}: ${x.why}`);
1049
- if (sel.skipped.length > 8) say(` - … ${sel.skipped.length - 8} more skipped`);
1050
- say(`${plan.stages.length} stages queued for approval in ${state}:`);
1051
- plan.stages.forEach((st, i) => say(` ${st.n}. ${st.title}${st.guard ? ` [guard: pool ${st.guard.pool} ${st.guard.metric} ≤ ${st.guard.limit ?? `+${Math.round((st.guard.maxRegression ?? 0.1) * 100)}%`}, bake ${st.bakeS}s]` : ''}\n approve: gpu-health actions approve ${ids[i]} --by NAME --state ${state}`));
1052
- say(`then: fleetops optimize advance --plan ${o.out}`);
1053
- return;
1054
- }
1055
- const planFile = opt('plan'); if (!planFile) throw new Error('--plan plan.json');
1056
- const plan = JSON.parse(read(planFile));
1057
- if (cmd === 'advance') {
1058
- const poster = (url, text) => { Sec.checkEgress(url); return postWebhook(url, text); }; // gpu-health's webhook (Lark-aware), behind the egress allowlist
1059
- const r = await Opt.advance(plan, { store, stateDir: opt('state') || plan.state || state, cfg, live: !!o.live, now, poster });
1060
- Opt.savePlan(planFile, plan);
1061
- if (J) { OUT.plan = plan; OUT.log = r.log; return; }
1062
- for (const l of r.log) say(l);
1063
- say(`plan ${plan.id}: ${plan.status}`);
1064
- if (plan.status === 'rolled-back') process.exitCode = 4;
1065
- return;
1066
- }
1067
- if (cmd === 'verify') {
1068
- const v = Opt.verify(plan, store, { days: o.days ? +o.days : 7, now });
1069
- store.append('optimization', [Object.assign({ t: now, id: plan.id, status: plan.status, expectedWeekly: plan.totalWeekly }, v)]);
1070
- if (J) { OUT.verification = v; return; }
1071
- if (!v.window) return say(v.note);
1072
- say(`${plan.id}: allocated GPU-hours ${v.before.gpuHours.toFixed(0)} → ${v.after.gpuHours.toFixed(0)} (${pc(v.gpuHoursChange)}) over ${(v.window / 86400).toFixed(1)} days; guard breaches ${v.before.breaches} → ${v.after.breaches}: ${v.verified ? 'verified' : 'NOT verified'}`);
1073
- return;
1074
- }
1075
- throw new Error(`unknown: optimize ${cmd}\n\n${HELP}`);
1076
- }
1077
-
1078
- function tokenCmd(cmd, o) {
1079
- const file = o.tokens && o.tokens !== true ? o.tokens : null;
1080
- if (!file) throw new Error('--tokens FILE');
1081
- if (cmd === 'create') {
1082
- if (!o.name || o.name === true) throw new Error('--name NAME');
1083
- const roles = String(o.roles && o.roles !== true ? o.roles : 'read').split(',');
1084
- const list = k => (o[k] && o[k] !== true ? String(o[k]).split(',') : undefined);
1085
- const scoped = ['namespaces', 'owners', 'pools', 'clusters'].some(k => list(k)) || o.infra;
1086
- const tenant = scoped ? Object.fromEntries([...['namespaces', 'owners', 'pools', 'clusters'].map(k => [k, list(k)]).filter(([, v]) => v), ...(o.infra ? [['infra', true]] : [])]) : '*';
1087
- const { token, entry } = Sec.addToken(file, { name: o.name, roles, tenant });
1088
- console.log(`token for ${entry.name} (${roles.join(', ')}; ${tenant === '*' ? 'all tenants' : JSON.stringify(tenant)}):\n${token}\nOnly its SHA-256 is stored in ${file}; this is the only time it is shown.`);
1089
- return;
1090
- }
1091
- if (cmd === 'list') { for (const t of Sec.loadTokens(file)) console.log(`${t.name.padEnd(20)} ${t.roles.join(',').padEnd(18)} ${t.tenant === '*' ? '*' : JSON.stringify(t.tenant)}`); return; }
1092
- throw new Error('token create|list --tokens FILE');
1093
- }
1094
-
1095
- // Streaming ingestion: remote_write and OTLP/HTTP (JSON) into the store.
1096
- // ---------- goodput ----------
1097
- function goodputCmd(store, o) {
1098
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined);
1099
- const to = time(opt('to')) ?? Math.floor(Date.now() / 1000), from = time(opt('from')) ?? to - (opt('days') ? +opt('days') : 7) * 86400;
1100
- const g = Goodput.goodput(store, { from, to, now: Math.min(to, Math.floor(Date.now() / 1000)), job: opt('job'), targets: opt('targets') ? JSON.parse(read(opt('targets'))) : {} });
1101
- const fmt = opt('format');
1102
- if (fmt === 'html' || fmt === 'md') { const text = fmt === 'html' ? goodputHtml(g) : goodputMarkdown(g); if (opt('out')) { fs.writeFileSync(opt('out'), text); say(`wrote ${opt('out')}`); if (J) OUT.wrote = opt('out'); } else process.stdout.write(text); return; }
1103
- if (J) { OUT.goodput = Object.assign({}, g, { jobs: g.jobs.map(({ attemptsList, ...j }) => j) }); return; }
1104
- process.stdout.write(goodputMarkdown(g));
1105
- }
1106
-
1107
- function tuneCmd(store, cmd, o) {
1108
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), json = f => JSON.parse(read(f));
1109
- const to = time(opt('to')) ?? Math.floor(Date.now() / 1000), from = time(opt('from')) ?? to - (opt('days') ? +opt('days') : 7) * 86400;
1110
- // pools deployed with `fleetops serving deploy` are known without --pools / --targets
1111
- const reg = f => { const p = path.join(store.dir, 'serving', f); return fs.existsSync(p) ? JSON.parse(read(p)) : {}; };
1112
- const args = { from, to, now: Math.min(to, Math.floor(Date.now() / 1000)), targets: Object.assign(reg('targets.json'), opt('targets') ? json(opt('targets')) : {}), pools: Object.assign(reg('pools.json'), opt('pools') ? json(opt('pools')) : {}) };
1113
- const last = path.join(store.dir, 'tune', 'last.json');
1114
- if (cmd === 'models') { const C = createRequire(import.meta.url)('../../inference-sizer/src/catalog.js'); if (J) { OUT.models = C.MODELS.map(m => m.id); OUT.gpus = C.GPUS.map(g => g.id); return; } say(`models: ${C.MODELS.map(m => m.id).join(' ')}\ngpus: ${C.GPUS.map(g => g.id).join(' ')}`); return; }
1115
- if (cmd === 'apply') {
1116
- const id = o._[2]; if (!id) throw new Error('fleetops tune apply ID --by NAME');
1117
- let rec = fs.existsSync(last) ? JSON.parse(read(last)).recommendations.find(r => r.id === id) : null;
1118
- if (!rec) rec = Tune.tune(store, args).recommendations.find(r => r.id === id);
1119
- if (!rec) throw new Error(`no recommendation ${id} (run fleetops tune first; ids are shown in its output)`);
1120
- const c = Tune.applyTune(store, rec, { by: opt('by'), at: time(opt('at')), note: opt('note') });
1121
- if (J) { OUT.applied = c; return; }
1122
- say(`recorded ${id} applied at ${fmt(c.t)} by ${c.by}${rec.verify ? `\nmeasure it once there is data after the change: fleetops tune verify ${id}` : ''}`);
1123
- return;
1124
- }
1125
- if (cmd === 'verify' || cmd === 'list') {
1126
- const ids = cmd === 'verify' && o._[2] ? [o._[2]] : [...new Set(Tune.applied(store).map(c => c.tune.id))];
1127
- const vo = { beforeS: dur(opt('before')) ?? 7 * 86400, afterS: dur(opt('after')) ?? 7 * 86400, now: Math.floor(Date.now() / 1000) };
1128
- const res = ids.map(id => Object.assign({ title: (Tune.applied(store).filter(c => c.tune.id === id).pop() || { tune: {} }).tune.title }, Tune.verifyTune(store, id, vo)));
1129
- if (J) { OUT.verified = res; return; }
1130
- if (!res.length) { say('nothing applied yet: fleetops tune apply ID --by NAME after making a change'); return; }
1131
- const f = (m, x) => (x == null ? '–' : m === 'pool.ttftP99' ? `${x.toFixed(3)} s` : m === 'fleet.interruptions' ? x.toFixed(2) : `${(x * 100).toFixed(1)}%`);
1132
- for (const r of res) say(`${r.verdict.toUpperCase().padEnd(15)} ${r.id}${r.title ? ` ${r.title}` : ''}${r.before ? `\n ${r.metric}${r.scope ? ` (${r.scope})` : ''}: ${f(r.metric, r.before.mean)} before (${r.before.n}) → ${f(r.metric, r.after.mean)} after (${r.after.n})${r.ci ? `, difference 95% CI ${f(r.metric, r.ci[0])} to ${f(r.metric, r.ci[1])}` : ''}` : ''}${r.note ? `\n ${r.note}` : ''}`);
1133
- return;
1134
- }
1135
- if (cmd === 'holdout') {
1136
- const split = time(opt('split')) ?? Math.round((from + to) / 2);
1137
- const h = Tune.holdout(store, Object.assign({}, args, { from, split, to }));
1138
- if (J) { OUT.holdout = h; return; }
1139
- say(`recommendations from ${fmt(from)} → ${fmt(split)}, checked on ${fmt(split)} → ${fmt(to)}:`);
1140
- for (const r of h.rows) {
1141
- const o2 = r.outOfSample;
1142
- const txt = r.id === 'flaky-nodes' && o2 ? `the same nodes: ${o2.failed.toFixed(0)} failed attempts against ${o2.expected.toFixed(0)} expected (${o2.ratio ? o2.ratio.toFixed(1) : '–'}×), ${(o2.share * 100).toFixed(1)}% of failures`
1143
- : r.id.startsWith('reclaim:') && o2 ? `${o2.still} of ${o2.of} jobs still flagged`
1144
- : r.inSample != null && typeof r.inSample === 'number' && typeof o2 === 'number' ? `${(r.inSample * 100).toFixed(1)}% before, ${(o2 * 100).toFixed(1)}% after` : (r.note || '');
1145
- say(` ${r.held == null ? '–' : r.held ? 'HELD ' : 'FADED'} ${r.id}: ${txt}`);
1146
- }
1147
- return;
1148
- }
1149
- if (cmd && cmd !== 'run') throw new Error(`unknown: tune ${cmd}`);
1150
- const t = Tune.tune(store, args);
1151
- fs.mkdirSync(path.dirname(last), { recursive: true }); fs.writeFileSync(last, JSON.stringify(t));
1152
- if (opt('format') === 'json' || J) { if (opt('out')) fs.writeFileSync(opt('out'), JSON.stringify(t, null, 1)); OUT.tune = t; if (!J) say(JSON.stringify(t, null, 1)); return; }
1153
- const text = Tune.tuneMarkdown(t);
1154
- if (opt('out')) { fs.writeFileSync(opt('out'), text); say(`wrote ${opt('out')}`); } else process.stdout.write(text);
1155
- }
1156
-
1157
- async function servingCmd(store, cmd, o) {
1158
- const opt = k => (o[k] != null && o[k] !== true ? o[k] : undefined), num = k => (opt(k) != null ? +opt(k) : undefined);
1159
- const f1 = v => (v == null ? '–' : v >= 100 ? Math.round(v).toLocaleString('en-US') : v.toFixed(v >= 10 ? 1 : 2));
1160
- if (cmd === 'models') { const ms = Serving.models(); if (J) { OUT.models = ms; return; } for (const m of ms) say(`${m.id.padEnd(18)} ${String(m.params).padStart(7)}B${m.active !== m.params ? ` (${m.active}B active)` : ''} ctx ${m.maxCtx} ${m.hf || ''}`); return; }
1161
- if (cmd === 'gpus') { const gs = Serving.gpus(); if (J) { OUT.gpus = gs; return; } for (const g of gs) say(`${g.id.padEnd(12)} ${g.label} · ${g.hbmGB} GB · ${g.perNode} per node${g.price ? ` · $${g.price}/GPU-h` : ''}`); return; }
1162
- const FIT = createRequire(import.meta.url)('../../inference-sizer/src/fit.js');
1163
- // workload: measured from a pool in the store, or given
1164
- let wl = { isl: num('isl') || 2000, osl: num('osl') || 400, islP99: num('isl-p99'), oslP99: num('osl-p99'), rate: num('rate') };
1165
- if (opt('from-pool')) {
1166
- const to = Math.floor(Date.now() / 1000), m = Serving.workloadFromStore(store, opt('from-pool'), { from: time(opt('from')) ?? to - 7 * 86400, to: time(opt('to')) ?? to });
1167
- if (!m) throw new Error(`fewer than 50 requests for pool ${opt('from-pool')} in the store (import request logs first)`);
1168
- wl = Object.assign(m, { rate: num('rate') ?? m.rate });
1169
- say(`workload ${m.source}: ISL ${Math.round(m.isl)} (p99 ${Math.round(m.islP99)}), OSL ${Math.round(m.osl)} (p99 ${Math.round(m.oslP99)}), p99 load ${m.rate.toFixed(2)} req/s`);
1170
- }
1171
- const tg = { ttftS: num('ttft') || 2, tpotS: num('tpot') || 0.05 };
1172
- const hw = { gpu: opt('gpu'), nodes: num('nodes'), gpus: num('gpus'), gpusPerNode: num('gpus-per-node') };
1173
- if (cmd === 'fit') {
1174
- if (!hw.gpu || (hw.nodes == null && hw.gpus == null)) throw new Error('fleetops serving fit --gpu G --nodes N (or --gpus N)');
1175
- if (hw.nodes == null) delete hw.nodes;
1176
- const r = FIT.fitModels(hw, wl, tg, { rank: opt('rank'), prompt: !!o.prompt });
1177
- if (J) { OUT.fit = r; return; }
1178
- say(`${hw.nodes != null ? `${hw.nodes} node(s)` : `${hw.gpus} GPUs`} of ${hw.gpu}; ISL ${Math.round(wl.isl)} / OSL ${Math.round(wl.osl)} tokens; TTFT ≤ ${tg.ttftS}s, TPOT ≤ ${tg.tpotS * 1000}ms${wl.rate ? `; needs ${wl.rate} req/s` : ''}`);
1179
- say(`ranked by ${r.rank === 'largest' ? 'size among the models that carry the load (size is a proxy for capability, not a quality score)' : 'requests per second'}\n`);
1180
- say(`${'model'.padEnd(18)} ${'params'.padStart(8)} ${'req/s'.padStart(8)} ${'edge'.padStart(8)} ${'out tok/s'.padStart(10)} ${'$/1M out'.padStart(8)} layout`);
1181
- for (const x of r.rows) {
1182
- const p = x.production, L = p.layout;
1183
- say(`${(r.need && x.meetsRate ? '✓ ' : r.need ? ' ' : '') + x.model.padEnd(r.need ? 16 : 18)} ${(x.params + 'B').padStart(8)} ${f1(p.rate).padStart(8)} ${f1(x.edge.rate).padStart(8)} ${f1(p.outTokensPerS).padStart(10)} ${(p.dollarsPerMOut ? '$' + p.dollarsPerMOut.toFixed(2) : '–').padStart(8)} ${L ? `${L.mode === 'agg' ? `${L.instances} × ${L.label}` : `P ${L.prefill.instances}×${L.prefill.label} / D ${L.decode.instances}×${L.decode.label}`}` : (p.why || '')}`);
1184
- }
1185
- say(`\nreq/s: production (15% headroom, an N+1 spare, 10% under the targets); edge: none of those. Spec-sheet efficiencies unless calibrated (fleetops calibrate).`);
1186
- return;
1187
- }
1188
- if (cmd === 'capacity') {
1189
- if (!opt('model') || !hw.gpu || (hw.nodes == null && hw.gpus == null)) throw new Error('fleetops serving capacity --model M --gpu G --nodes N (or --gpus N)');
1190
- if (hw.nodes == null) delete hw.nodes;
1191
- const c = FIT.capacity(opt('model'), hw, wl, tg, {});
1192
- if (J) { OUT.capacity = Object.assign({}, c, { production: Object.assign({}, c.production, { usersAt: undefined }) }); return; }
1193
- const p = c.production, L = p.layout;
1194
- say(`${c.name} on ${c.gpus} ${c.gpu}; ISL ${Math.round(c.wl.isl)} / OSL ${Math.round(c.wl.osl)}; TTFT ≤ ${c.tg.ttftS}s, TPOT ≤ ${c.tg.tpotS * 1000}ms`);
1195
- if (!p.rate) { say(` doesn't fit: ${p.why}${c.edge.rate ? ` (without headroom and the spare it carries ${f1(c.edge.rate)} req/s)` : ''}`); return; }
1196
- say(` max load: ${f1(p.rate)} req/s in production (${f1(c.edge.rate)} at the edge), ${f1(p.outTokensPerS)} output tokens/s`);
1197
- say(` users: ~${f1(p.usersAt(20))} daily active users at 20 requests each, if the load were flat (peaks need more)`);
1198
- say(` concurrency: ${L.concurrency} sequences in flight (${L.instances} instance(s) × ${Math.round(L.concurrency / L.instances)})`);
1199
- say(` layout: ${L.mode === 'agg' ? `${L.instances} × ${L.label} (${L.gpusPerInstance} GPU(s) each)` : `prefill ${L.prefill.instances}×${L.prefill.label}, decode ${L.decode.instances}×${L.decode.label}`}, ${p.nodes} node(s) with the spare`);
1200
- say(` longest prompt: ${c.maxPrompt ? `${c.maxPrompt.toLocaleString('en-US')} tokens at light load (model maximum ${c.modelMaxCtx.toLocaleString('en-US')})` : 'none fits'}`);
1201
- if (p.dollarsPerMOut) say(` cost: $${p.dollarsPerMOut.toFixed(2)} per million output tokens at that load (catalog price)`);
1202
- say(` ${p.reason}`);
1203
- return;
1204
- }
1205
- if (cmd === 'delete') {
1206
- const name = o._[2], ns = opt('namespace') || 'serving', f = path.join(store.dir, 'serving', `${name}.yaml`);
1207
- if (!name) throw new Error('fleetops serving delete NAME [--namespace serving] [--apply]');
1208
- const argv = fs.existsSync(f) ? ['delete', '-f', f, '--ignore-not-found'] : ['-n', ns, 'delete', 'deployment,leaderworkerset,service,scaledobject', '-l', `app=${name}`, '--ignore-not-found'];
1209
- const routerValues = path.join(store.dir, 'serving', `${name}.router.values.yaml`), helmArgv = fs.existsSync(routerValues) ? ['uninstall', name, '-n', ns] : null;
1210
- if (!o.apply) { say(`would run: kubectl ${argv.join(' ')}${helmArgv ? `\n helm ${helmArgv.join(' ')} (the llm-d router)` : ''}\nadd --apply to delete`); return; }
1211
- const r = Serving.kubectl(argv); if (r.code !== 0) throw new Error(r.err.trim());
1212
- if (helmArgv) { const h = Serving.helmRun(helmArgv); if (h.code !== 0) say(`helm uninstall: ${h.err.trim()}`); else fs.rmSync(routerValues); }
1213
- for (const reg of ['pools.json', 'targets.json']) { const p = path.join(store.dir, 'serving', reg); if (fs.existsSync(p)) { const x = JSON.parse(read(p)); delete x[name]; fs.writeFileSync(p, JSON.stringify(x, null, 1)); } }
1214
- say(r.out.trim()); return;
1215
- }
1216
- if (cmd !== 'deploy') throw new Error(`unknown: serving ${cmd || ''} (models, gpus, fit, capacity, deploy, delete)`);
1217
- const d = Serving.planDeployment({ model: opt('model'), gpu: opt('gpu'), nodes: hw.nodes, gpus: hw.gpus, gpusPerNode: hw.gpusPerNode, rate: wl.rate, isl: wl.isl, osl: wl.osl, islP99: wl.islP99, oslP99: wl.oslP99, ttftS: tg.ttftS, tpotS: tg.tpotS,
1218
- name: opt('name'), namespace: opt('namespace'), image: opt('image'), hf: opt('hf'), hfSecret: opt('hf-secret'), cachePvc: opt('cache-pvc'), maxModelLen: num('max-model-len'), autoscale: !!o.autoscale, prometheus: opt('prometheus'),
1219
- minReplicas: num('min-replicas'), maxReplicas: num('max-replicas'), createNamespace: !!o['create-namespace'], weights: opt('weights'), kvDtype: opt('kv-dtype'), mode: opt('mode'), routerVersion: opt('router-version'), sidecarImage: opt('sidecar-image'), gaieVersion: opt('gaie-version') });
1220
- if (opt('out')) { fs.writeFileSync(opt('out'), d.yaml); if (d.router) fs.writeFileSync(opt('out').replace(/(\.ya?ml)?$/, '.router.values.yaml'), d.router.yaml); }
1221
- if (!J) {
1222
- say(`${d.name}: ${d.model} (${d.hf}) on ${d.gpu}, ${d.sized.basis}`);
1223
- if (d.mode === 'disagg') say(` disaggregated on llm-d: prefill ${d.layout.prefill.instances} × TP${d.layout.prefill.tp}, decode ${d.layout.decode.instances} × TP${d.layout.decode.tp} (max-num-seqs ${d.layout.decode.maxNumSeqs}) = ${d.layout.gpus} GPUs; max-model-len ${d.layout.maxModelLen}; TTFT ≤ ${d.targets.ttftS}s, TPOT ≤ ${d.targets.tpotS * 1000}ms\n router: helm upgrade --install ${d.router.release} ${d.router.chart} --version ${d.router.version} -n ${d.namespace} -f <router values>`);
1224
- else say(` ${d.layout.instances} × TP${d.multiNode ? `${d.layout.gpusPerInstance / d.nodesPerInstance} × PP${d.nodesPerInstance} (LeaderWorkerSet, ${d.nodesPerInstance} nodes each)` : d.layout.tp + (d.layout.pp > 1 ? ` × PP${d.layout.pp}` : '')} = ${d.layout.gpus} GPUs; max-num-seqs ${d.layout.maxNumSeqs}, max-model-len ${d.layout.maxModelLen}; TTFT ≤ ${d.targets.ttftS}s, TPOT ≤ ${d.targets.tpotS * 1000}ms`);
1225
- for (const n of d.notes) say(` note: ${n}`);
1226
- if (!o.apply && !opt('out')) say(`\n${d.yaml}${d.router ? `\n# llm-d router values (${d.router.chart})\n${d.router.yaml}` : ''}`);
1227
- else if (opt('out')) say(` wrote ${opt('out')}${d.router ? ` and ${opt('out').replace(/(\.ya?ml)?$/, '.router.values.yaml')}` : ''}`);
1228
- if (d.prereqs && !o.apply) say(` prerequisites (once per cluster; install-serving.sh --install-prereqs runs them):\n${d.prereqs.map(c => ` ${c.join(' ')}`).join('\n')}`);
1229
- }
1230
- const log = (s, x) => {
1231
- if (J) return;
1232
- if (s === 'preflight') for (const c of x.checks) say(` ${c.pass ? 'ok ' : 'FAIL'} ${c.name}: ${c.detail}`);
1233
- else if (s === 'apply') say(` applied${x.out ? `:\n ${x.out.replace(/\n/g, '\n ')}` : ''}`);
1234
- else if (s === 'router') say(` llm-d router ${x.code === 0 ? 'installed' : 'failed'}`);
1235
- else if (s === 'wait') say(` ${x.code === 0 ? 'ready' : 'not ready'}${x.out && x.out.includes('pods') ? `: ${x.out}` : ''}`);
1236
- else if (s === 'smoke') say(x.ok ? ` smoke test: ${x.models.join(', ')} answered "${x.text}" (first response ${x.firstByteMs} ms)` : ` smoke test failed: ${x.error}`);
1237
- else if (s === 'register') say(x.pools ? ` registered: ${x.pools} (tune and the agent see the pool)` : '');
1238
- };
1239
- const r = await Serving.deploy(d, { apply: !!o.apply, endpoint: opt('endpoint'), waitS: num('wait') || 2400, registerDir: path.join(store.dir, 'serving'), log });
1240
- if (J) { OUT.deploy = Object.assign({ plan: Object.assign({}, d, { docs: undefined }) }, r); return; }
1241
- if (r.dryRun) say(`\ndry run: nothing applied. Add --apply to deploy${r.steps[0].ready ? '' : ' (fix the failed checks first)'}.`);
1242
- if (r.error) throw new Error(r.error);
1243
- if (r.ok) say(`\n${d.name} is serving: kubectl -n ${d.namespace} port-forward svc/${d.service || d.name} 8000:${d.servicePort || 8000}, then the OpenAI API at http://127.0.0.1:8000/v1 (model "${d.model}")`);
1244
- }
1245
-
1246
- function sdcCmd(store, o) {
1247
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined);
1248
- const to = time(opt('to')) ?? Math.floor(Date.now() / 1000), from = time(opt('from')) ?? to - (opt('days') ? +opt('days') : 7) * 86400;
1249
- const r = Sdc.findSdc(store, { from, to });
1250
- if (J) { OUT.sdc = r; return; }
1251
- process.stdout.write(Sdc.sdcMarkdown(r));
1252
- }
1253
-
1254
- // ---------- live agent ----------
1255
- function agentOpts(store, o) {
1256
- const opt = k => (o[k] && o[k] !== true ? o[k] : undefined), json = f => JSON.parse(read(f));
1257
- const agent = Object.assign({}, opt('agent-config') ? json(opt('agent-config')) : {});
1258
- if (opt('interval')) agent.intervalS = +opt('interval');
1259
- if (opt('window')) agent.windowS = dur(opt('window')) ?? +opt('window');
1260
- if (opt('targets')) agent.targets = json(opt('targets'));
1261
- if (opt('min-failures')) agent.minFailures = +opt('min-failures');
1262
- if (opt('page-to')) agent.page = { to: opt('page-to'), key: opt('page-key') || process.env.PAGERDUTY_ROUTING_KEY || process.env.OPSGENIE_API_KEY, url: opt('page-url'), minSeverity: opt('page-min-severity') || 'sev2' };
1263
- const stateDir = opt('state') || path.join(store.dir, 'agent');
1264
- const ghConfig = opt('config') ? json(opt('config')) : undefined;
1265
- // pull from the fleet's own monitoring before each tick, from where the last pull stopped
1266
- let pulledTo = null;
1267
- const before = opt('prom') || opt('loki') ? async now => {
1268
- const from = pulledTo ?? now - (agent.deviceWindowS || Agent.AGENT_DEFAULTS.deviceWindowS);
1269
- if (opt('prom')) await Pull.pullPrometheus(store, opt('prom'), { from, to: now, step: opt('step') ? +opt('step') : 30, headers: hdrs(o) });
1270
- if (opt('loki')) await Pull.pullLoki(store, opt('loki'), lokiQueries(o), { from, to: now, headers: hdrs(o) });
1271
- pulledTo = now;
1272
- } : null;
1273
- return { stateDir, ghConfig, agent, live: !!o.live, before };
1274
- }
1275
- function agentLine(r) {
1276
- const acts = r.executed.map(e => `${e.kind}:${e.outcome}`).join(', ');
1277
- return `${new Date(r.t * 1000).toISOString()} agent${r.paused ? ' (paused)' : ''}${r.devices ? ` · ${Object.entries(r.devices.states).map(([k, v]) => `${k} ${v}`).join(', ')}` : ''} · ${r.incidents.length} incident(s)${r.incidents.map(i => `\n ${i.id}: ${i.rule || 'no cause'} (${i.confidence}) → ${i.decision}${i.actions.length ? ' [' + i.actions.map(a => `${a.kind} ${a.mode}`).join(', ') + ']' : ''}`).join('')}${acts ? `\n ran: ${acts}` : ''}${r.verified.map(v => `\n verified ${v.id}: ${v.outcome}`).join('')}`;
1278
- }
1279
- async function agentCmd(store, cmd, o) {
1280
- const ao = agentOpts(store, o), opt = k => (o[k] && o[k] !== true ? o[k] : undefined);
1281
- if (cmd === 'pause' || cmd === 'resume') { if (!opt('by')) throw new Error(`agent ${cmd} --by NAME`); Agent.setPaused(ao.stateDir, cmd === 'pause', opt('by')); if (J) OUT.paused = cmd === 'pause'; else say(`agent ${cmd === 'pause' ? 'paused' : 'resumed'} by ${opt('by')}`); return; }
1282
- if (cmd === 'status') {
1283
- const v = LiveView.liveView(store, ao.stateDir, { agent: ao.agent, ghConfig: ao.ghConfig });
1284
- if (J) { OUT.status = { agent: v.agent, fleet: v.fleet.states, incidents: v.incidents, waiting: v.actions.open.filter(a => a.status === 'proposed') }; return; }
1285
- say(`agent ${v.agent.paused ? 'PAUSED' : v.agent.lastTick ? `last ran ${new Date(v.agent.lastTick * 1000).toISOString()}` : 'has not run'}${v.agent.live ? ' (live)' : ' (dry run)'} · autonomous actions in the last hour ${v.agent.autoLastHour}/${v.agent.autoLimit}`);
1286
- say(`GPUs: ${Object.entries(v.fleet.states).map(([k, n]) => `${k} ${n}`).join(', ') || 'no telemetry'}`);
1287
- for (const i of v.incidents) say(` ${i.severity} ${i.status.padEnd(12)} ${i.id}: ${i.title || 'no cause'} → ${i.decision || '–'}${i.verified ? ` (${i.verified.outcome})` : ''}`);
1288
- for (const a of v.actions.open.filter(a => a.status === 'proposed')) say(` waiting: ${a.id} ${a.reason.slice(0, 140)}`);
1289
- return;
1290
- }
1291
- if (cmd === 'log') { const d = Agent.decisions(ao.stateDir, o.limit ? +o.limit : 50); if (J) { OUT.log = d; return; } for (const e of d.reverse()) say(`${new Date(e.t * 1000).toISOString()} ${e.decision}${e.incident ? ' ' + e.incident : ''}${e.action ? ' ' + e.action : ''}${e.outcome ? ' → ' + e.outcome : ''}${e.title ? ': ' + e.title : ''}${e.note ? ': ' + e.note : ''}`); return; }
1292
- if (cmd === 'approve' || cmd === 'reject') {
1293
- const { Store: Q } = await import('../../gpu-health/src/actions.mjs');
1294
- const id = o._[2]; if (!id || !opt('by')) throw new Error(`agent ${cmd} ID --by NAME`);
1295
- const q = new Q(ao.stateDir), a = cmd === 'approve' ? q.approve(id, opt('by')) : q.reject(id, opt('by'), opt('reason') || '');
1296
- fs.appendFileSync(path.join(ao.stateDir, 'agent.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), decision: cmd === 'approve' ? 'approved' : 'rejected', action: a.id, kind: a.kind, by: opt('by'), incident: a.incident }) + '\n');
1297
- if (J) OUT[cmd + 'd'] = a; else say(`${a.id} ${a.status} by ${opt('by')}; it runs on the agent's next tick`);
1298
- return;
1299
- }
1300
- if (cmd && cmd !== 'run') throw new Error(`unknown: agent ${cmd}`);
1301
- if (o.once) {
1302
- if (ao.before) await ao.before(Math.floor(Date.now() / 1000));
1303
- const r = await Agent.tick(store, Object.assign({}, ao, { now: o.now && o.now !== true ? time(o.now) : undefined }));
1304
- if (J) { OUT.tick = r; return; }
1305
- say(agentLine(r)); return;
1306
- }
1307
- if (o.live) console.log('note: --live runs actions only when the gpu-health policy has dryRun: false (--config)');
1308
- Agent.start(store, ao, { onTick: r => console.log(agentLine(r)), before: ao.before });
1309
- const stop = () => { if (store.close) store.close(); process.exit(0); };
1310
- process.on('SIGINT', stop); process.on('SIGTERM', stop);
1311
- await new Promise(() => {});
1312
- }
1313
-
1314
- async function serve(store, o) {
1315
- const port = o.port ? +o.port : 9400, host = o.host && o.host !== true ? o.host : '127.0.0.1';
1316
- const tokens = o.tokens && o.tokens !== true ? Sec.loadTokens(o.tokens) : null;
1317
- // listening beyond this machine without tokens would expose every tenant's data: refuse unless asked for explicitly
1318
- if (!tokens && !['127.0.0.1', 'localhost', '::1'].includes(host) && !o['no-auth']) throw new Error(`--host ${host} needs --tokens FILE (or --no-auth to run open on a trusted network)`);
1319
- const pipe = new Ingest.Pipeline(store, { maxQueue: o['max-queue'] ? +o['max-queue'] : 200000, flushMs: o['flush-ms'] ? +o['flush-ms'] : 1000 }).start();
1320
- let extra = null, page = null, agentRun = null;
1321
- // POST /v1/bundle (role ingest): a trace bundle, imported as `data import bundle` would
1322
- const bundleRoute = async (req, res, who, send) => {
1323
- if (req.method !== 'POST' || req.url.split('?')[0] !== '/v1/bundle') return false;
1324
- if (!Sec.can(who, 'ingest')) { send(res, 403, 'needs the ingest role\n'); return true; }
1325
- const chunks = []; let n = 0;
1326
- for await (const c of req) { n += c.length; if (n > Bundle.MAX_FILE) { send(res, 413, 'bundle too large: import it with fleetops data import bundle\n'); return true; } chunks.push(c); }
1327
- const f = path.join(fs.mkdtempSync(path.join((await import('node:os')).tmpdir(), 'fleetops-up-')), 'bundle.tgz');
1328
- try { fs.writeFileSync(f, Buffer.concat(chunks)); const r = await importBundle(store, f, {}); send(res, 200, JSON.stringify({ totals: r.totals, files: r.files.map(x => ({ path: x.path, source: x.source, error: x.error, skipped: x.skipped })) }), 'application/json'); }
1329
- catch (e) { send(res, 400, `${e.message}\n`); }
1330
- finally { fs.rmSync(path.dirname(f), { recursive: true, force: true }); }
1331
- return true;
1332
- };
1333
- extra = bundleRoute;
1334
- if (o.agent) {
1335
- const ao = agentOpts(store, o);
1336
- const live = LiveView.liveRoutes({ store, stateDir: ao.stateDir, agent: ao.agent, ghConfig: ao.ghConfig, audit: Sec.auditor(store.dir) }); page = LiveView.LIVE_HTML;
1337
- extra = async (req, res, who, send) => (await bundleRoute(req, res, who, send)) || live(req, res, who, send);
1338
- agentRun = Agent.start(store, ao, { onTick: r => console.log(agentLine(r)), before: ao.before });
1339
- }
1340
- const srv = Ingest.server(pipe, { site: o.site && o.site !== true ? o.site : undefined, tokens, audit: Sec.auditor(store.dir), extra, page });
1341
- await new Promise(r => srv.listen(port, host, r));
1342
- console.log(`fleetops on http://${host}:${port} store ${store.dir} ${tokens ? `${tokens.length} token(s)` : 'open (no tokens)'}${process.env.FLEETOPS_EGRESS_ALLOW != null ? ` egress: ${process.env.FLEETOPS_EGRESS_ALLOW || 'none'}` : ''}\n POST /api/v1/write /v1/metrics /v1/logs /v1/traces /v1/bundle GET /api/summary /api/query /api/series /api/incidents /api/diagnose /metrics /healthz${o.agent ? `\n agent every ${agentOpts(store, o).agent.intervalS ?? Agent.AGENT_DEFAULTS.intervalS} s${o.live ? ' (live: still needs policy.dryRun false)' : ' (dry run)'}; dashboard http://${host}:${port}/live` : ''}`);
1343
- const stop = () => { if (agentRun) agentRun.stop(); srv.close(); pipe.stop(); if (store.close) store.close(); process.exit(0); };
1344
- process.on('SIGINT', stop); process.on('SIGTERM', stop);
1345
- await new Promise(() => {});
55
+ return dataCmd(store, cmd, rest, o);
1346
56
  }
1347
57
 
1348
58
  const self = fileURLToPath(import.meta.url);