aiinfra-tools 0.4.0 → 0.5.1

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 (62) hide show
  1. package/CHANGELOG.md +179 -0
  2. package/README.md +33 -1
  3. package/bin/aiinfra.mjs +12 -0
  4. package/fleetops/deploy/grafana-dashboard.json +71 -0
  5. package/fleetops/docs/SHADOW.md +25 -2
  6. package/fleetops/package.json +1 -1
  7. package/fleetops/src/adapters/nvsentinel.mjs +2 -1
  8. package/fleetops/src/api.mjs +8 -0
  9. package/fleetops/src/schema.mjs +3 -0
  10. package/fleetops/src/shadow-quality.mjs +107 -0
  11. package/fleetops/src/shadow.mjs +12 -6
  12. package/fleetops/tools/cmd/help.mjs +4 -1
  13. package/fleetops/tools/cmd/shadow.mjs +14 -2
  14. package/fleetscope/build.mjs +1 -0
  15. package/fleetscope/dist/index.html +134 -16
  16. package/fleetscope/package.json +1 -1
  17. package/fleetscope/src/engine.js +1 -1
  18. package/fleetscope/src/index.src.html +17 -1
  19. package/gpu-health/package.json +1 -1
  20. package/gpu-ledger/package.json +1 -1
  21. package/harness-ledger/README.md +48 -0
  22. package/harness-ledger/integrations/README.md +11 -0
  23. package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
  24. package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
  25. package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
  26. package/harness-ledger/package.json +1 -1
  27. package/harness-ledger/src/advise.mjs +410 -0
  28. package/harness-ledger/src/assess.mjs +66 -0
  29. package/harness-ledger/src/doctor.mjs +202 -0
  30. package/harness-ledger/src/engine-metrics.mjs +35 -0
  31. package/harness-ledger/src/importers.mjs +14 -3
  32. package/harness-ledger/src/lint.mjs +115 -0
  33. package/harness-ledger/src/mooncake.mjs +83 -0
  34. package/harness-ledger/src/prices.json +585 -0
  35. package/harness-ledger/src/prices.mjs +7 -17
  36. package/harness-ledger/src/profile.mjs +164 -0
  37. package/harness-ledger/src/record.mjs +2 -2
  38. package/harness-ledger/src/suggest.mjs +177 -0
  39. package/harness-ledger/src/trajectory.mjs +81 -0
  40. package/harness-ledger/src/workload-demo.mjs +100 -0
  41. package/harness-ledger/tools/harness-ledger.mjs +224 -5
  42. package/hybrid-tracing/package.json +1 -1
  43. package/inference-sizer/build.mjs +1 -0
  44. package/inference-sizer/dist/index.html +137 -18
  45. package/inference-sizer/docs/CATALOG.md +13 -4
  46. package/inference-sizer/package.json +1 -1
  47. package/inference-sizer/src/catalog.js +36 -10
  48. package/inference-sizer/src/fleetscope.js +1 -1
  49. package/inference-sizer/src/index.src.html +7 -0
  50. package/inference-sizer/src/model.js +10 -4
  51. package/inference-sizer/src/suggest.js +70 -0
  52. package/inference-sizer/src/ui.js +13 -3
  53. package/inference-sizer/tools/size.mjs +4 -0
  54. package/mcp/README.md +3 -0
  55. package/mcp/server.mjs +22 -0
  56. package/package.json +5 -2
  57. package/schemas/README.md +3 -0
  58. package/schemas/commands.mjs +7 -0
  59. package/schemas/harness-ledger.advise.schema.json +1106 -0
  60. package/schemas/harness-ledger.assess.schema.json +2839 -0
  61. package/schemas/harness-ledger.economics.schema.json +8 -2
  62. package/schemas/harness-ledger.suggest.schema.json +326 -0
package/CHANGELOG.md CHANGED
@@ -3,6 +3,185 @@
3
3
  All notable changes. Versions follow [Semantic Versioning](https://semver.org/); before 1.0, a minor version may
4
4
  change the `--json` output, and when it does the change is listed here (see [schemas/](schemas/README.md)).
5
5
 
6
+ ## Unreleased
7
+
8
+ ## 0.5.1 (2026-11-30)
9
+
10
+ Stays current on its own, and is easier to start with. Model prices and the Inference Sizer's model catalog are
11
+ checked every week. The AWS deploy paths are now tested against AWS Emulator in CI. A getting-started guide covers the
12
+ first suggestion and deploying anywhere. Fixes: Gemma 4's KV cache was undercounted, DeepSeek V4's sparse top-k was
13
+ wrong, and `up.sh vm` clashed with dcgm-exporter's port. One `--json` change: `harness-ledger.economics` per-resolved
14
+ figures can be `null`. One prediction changed: Gemma 4's time per output token is longer (12.5 → 15.6 ms on H100 at the
15
+ default load), because its sliding-window layers keep 4× the KV that was counted. GPU counts at the defaults are the
16
+ same.
17
+
18
+ ### New: kept current every week
19
+
20
+ - **Prices** (#92): harness-ledger's default prices come from LiteLLM's model price list, stored in
21
+ `harness-ledger/src/prices.json`. They cover 81 Anthropic, OpenAI and Gemini models, up from 7, including the newer
22
+ Claude and GPT models that were unpriced before. A weekly workflow (`.github/workflows/refresh.yml`) refreshes them:
23
+ when a price changes or a model appears, it runs the tests and opens one pull request (`scripts/refresh-prices.mjs`).
24
+ - **Model catalog check** (#92, #97): the same workflow compares the Inference Sizer's models with their Hugging Face
25
+ `config.json`. It compares layers, hidden size, heads, KV heads (and full-attention KV heads), attention kind,
26
+ experts, top-k and sparse top-k. It lists new open-weight models from the organizations the catalog follows, and
27
+ opens one "model catalog" issue when there is something to do (`scripts/check-catalog.mjs`). An entry's
28
+ `alsoRepos` names repos with the same layout (Kimi K3.1 Pro, MiniMax M3.1 Flash). A repo looked at and left out goes
29
+ in `REVIEWED`, with the reason, and the issue lists it as reviewed rather than new. A gated repo says it needs an
30
+ `HF_TOKEN` from an account that accepted the license.
31
+ - **AWS paths against AWS Emulator** (#99): `.github/workflows/aws-emulator.yml` installs AWS Emulator on the runner,
32
+ with no AWS account. `tests/aws-emulator/run.sh` then checks:
33
+ - the Capacity Blocks command `fleetops procure aws-blocks` prints (H100, H200, B200);
34
+ - `deploy/cloud/up.sh aws` and `down.sh aws` with an EKS cluster made in the emulator;
35
+ - `deploy/terraform/aws`: plan, and apply of its VPC and EKS modules.
36
+
37
+ It runs on pull requests that touch these paths, weekly, and on demand. An operation the emulator doesn't
38
+ implement is reported as an emulator gap.
39
+
40
+ ### New: getting started
41
+
42
+ - **Getting started guide** (#92, [docs/GETTING-STARTED.md](docs/GETTING-STARTED.md)): ten minutes from nothing to the
43
+ first suggestion on your own agent logs. It has commands for macOS, Linux, Windows Command Prompt and PowerShell, and
44
+ fixes for what can look off.
45
+ - **Deploying** (#93): the guide covers:
46
+ - Google Cloud, AWS and Azure, from their browser shells;
47
+ - a neocloud or on-prem Kubernetes cluster;
48
+ - one GPU server;
49
+ - your laptop (Docker, or kind/k3d);
50
+ - a hybrid hub with many sites;
51
+ - how to open it and take it down.
52
+ - **Video** (#94, #98): "What's new in 0.5.1", 56 seconds, landscape and LinkedIn 4:5. It opens with the payoff, says
53
+ AIInfraTools builds on the tools you already run, and covers:
54
+ - assess and suggest;
55
+ - where suggestions show up;
56
+ - dry runs and gates;
57
+ - the Sizer and FleetScope cards;
58
+ - the weekly checks;
59
+ - deploying anywhere.
60
+
61
+ Render it with `node scripts/render-scenes.mjs --video highlights` in `video/`.
62
+
63
+ ### Fixed
64
+
65
+ - **Gemma 4 KV cache** (#97): its sliding-window layers have 16 KV heads of 256, and its full-attention layers have 4
66
+ heads of 512 with keys and values in one tensor. The catalog used the full-attention shape for every layer, so
67
+ sliding-window KV was undercounted 4×. Three new model fields describe the full-attention layers: `globalKvHeads`,
68
+ `globalHeadDim` and `kvShared`. The Sizer's KV math and the FleetScope export use them, and `fromHFConfig` reads
69
+ them from a config.
70
+ - **DeepSeek V4** (#97): `fromHFConfig` reads its compressed attention. That is one shared KV head plus
71
+ `compress_ratios`, sized like MLA. Before, the importer read it as GQA. The catalog's sparse top-k is now 1024
72
+ (Pro) and 512 (Flash), not 2048.
73
+ - **MiniMax** block-sparse attention (`sparse_topk_blocks` × `sparse_block_size`) is read as `sparseTopK` (#97).
74
+ - **`up.sh vm` on a GPU server** (#93): fleetops listens on 9400, which is also dcgm-exporter's default port. When
75
+ 9400 is taken, fleetops now moves to the next free port (9410, …) and says so. Before, the install failed with a
76
+ port conflict. `--port P` picks the port yourself.
77
+ - **NVSentinel v1.34.0** (#97): the format check's baseline. The adapter reads the same fields, and doesn't read
78
+ `HealthEvent.id`, which v1.34.0 documents as not unique.
79
+ - **CLI** (#92): `aiinfra sizer --help` prints the usage instead of sizing the default model. Dry runs no longer print
80
+ rows that have no data (TTFT for calls without timings).
81
+
82
+ ### Changed
83
+
84
+ - **`--json` (`harness-ledger.economics`)** (#92): `fixes.rows[].perResolved` and `costPerResolvedAfter` can now be
85
+ `null`. That happens when calls are priced but have no outcomes to divide by. With more models priced, such rows
86
+ appear where none did before. `harness-ledger.advise` and `harness-ledger.assess` list their `costUnit`: `USD`, or
87
+ `units` with relative prices.
88
+
89
+ ## 0.5.0 (2026-11-29)
90
+
91
+ Optimize across the stack, and raise what is worth changing where people already work. `aiinfra assess`, `advise`
92
+ (with a dry run and a CI gate), `quality`, `suggest` and `prompt-lint` are new commands. The repository is now a
93
+ GitHub Action, and there are new integrations for Claude Code and the LiteLLM gateway. The Inference Sizer and
94
+ FleetScope pages show suggestions beside the answer. New `--json` output: `harness-ledger.advise`,
95
+ `harness-ledger.assess` and `harness-ledger.suggest`. No existing output changed. One prediction did change: the Sizer's
96
+ operating point now counts prefix-cache hits, so predicted TTFT is shorter for workloads that reuse prompts.
97
+
98
+ ### New: suggestions where people already look
99
+
100
+ Suggestions are now raised once each, in the tools people already use, and what people decide about them is
101
+ remembered (#89). Two public data formats are new inputs. New `--json` output: `harness-ledger.suggest`. No existing output
102
+ changed.
103
+
104
+ - **`aiinfra suggest`** turns the optimizer's and the doctor's findings into suggestions.
105
+ - Each suggestion carries its effect, its risk, whether the effect is counted from the traces or modelled, the
106
+ sessions most affected, and the dry-run command.
107
+ - A suggestion is raised once, and again only when its effect grows by half.
108
+ - `accept`, `dismiss`, `snooze` and `reopen` record what people decided. `--watch` re-runs on a rolling window.
109
+ - Sinks: a fleetops store, Slack and Lark/Feishu webhooks, and Langfuse comments on the affected sessions. Slack,
110
+ Lark and Langfuse send only with `--live`.
111
+ - **Claude Code:** `aiinfra claude-code-hook` works as SessionEnd, SessionStart and Stop hooks. It shows the last
112
+ session's cache misses and tool-output waste, and warns once per problem as it happens. A status line shows the
113
+ live cache hit rate and avoidable spend. Both are local, keep counts only, and never block a session.
114
+ - **Prompt lint:** `aiinfra prompt-lint` (`harness-ledger lint`) catches prompt templates and request bodies that will
115
+ miss the prefix cache:
116
+ - a per-call variable before static text;
117
+ - a literal timestamp or id in the prefix;
118
+ - a missing Anthropic cache breakpoint.
119
+
120
+ The GitHub Action gets `comment: true`: one pull request comment per step, updated in place.
121
+ - **LiteLLM gateway:** a proxy callback that reports, live, each request that breaks its session's prompt prefix and
122
+ why. It uses the same causes as the doctor, and a test checks that both name the same breaks. It writes Prometheus
123
+ counters and one log line per template and cause. It never changes or blocks a request.
124
+ - **Grafana:** a `suggestion` record kind, `/api/suggestions` on `fleetops serve`, and an **Optimization suggestions**
125
+ panel on the fleetops dashboard.
126
+ - **Inference Sizer and FleetScope pages:**
127
+ - The Sizer shows "What would change this": the same request re-planned with one change at a time (FP8/FP4 weights,
128
+ FP8 KV, speculative decoding, prefix caching, a shorter context), with GPUs and $/month.
129
+ - FleetScope shows "What to try": one-click what-ifs from the first bottleneck that its Ask box runs.
130
+ - **Inputs:**
131
+ - Agent trajectories with full message lists (SWE-agent, OpenHands datasets). Their request bodies feed the doctor.
132
+ - Mooncake-format serving traces: hit rate by cache size, and random against prefix-aware routing.
133
+ - `harness-ledger mooncake --requests` writes your own traffic as a Mooncake trace with no text, for AIPerf.
134
+ - **MCP:** `list_suggestions` (read-only). The server now has 23 tools.
135
+ - **Workload profile:** "fresh tokens per output token" now counts cache writes as prefilled, so some classes'
136
+ prefill/decode bound changes on data with large cache writes.
137
+
138
+ ### New: optimize across the stack
139
+
140
+ Ask for a metric and get every change across the stack that moves it (#88). You can dry-run any combination of them, gate it
141
+ in CI, and check that answers didn't get worse. New `--json` output: `harness-ledger.advise` and `harness-ledger.assess`.
142
+ No existing output changed.
143
+
144
+ - **`aiinfra assess`** gives one report: workload classes (critical, realtime, agentic, reasoning, batch) with
145
+ input:output token ratios and what bounds each; the prefix-cache doctor; and the optimizer for each goal. Text,
146
+ Markdown (`--md`, for a job summary) or JSON.
147
+ - **`aiinfra advise --goal ttft|tpot|e2e|cost|gpus|throughput`** covers changes in every layer:
148
+ - prompt layout, cache lifetime, tool-output caps, on-demand tool definitions, cold compaction, step caps and
149
+ reasoning budgets;
150
+ - batch off-peak and priority scheduling;
151
+ - prefix-aware routing, FP8/FP4 weights, FP8 KV and speculative decoding;
152
+ - disaggregation, other GPUs and other models.
153
+
154
+ Each change is measured on the recorded calls changed as it would change them, or on the Inference Sizer's operating
155
+ point when self-hosted. The answer gives three combinations (best, at no extra cost, no quality risk). `--apply`
156
+ runs a dry run with how to make and verify each change, `--fail-if 'ttft>+5%'` exits 3 when a bound is crossed, and
157
+ `--out` writes the change set.
158
+ - **Prefix-cache doctor** (`harness-ledger doctor`):
159
+ - hit rate now against what is reachable;
160
+ - from request bodies, which part of the prompt breaks the cache (`system-dynamic`, `tools-reordered`,
161
+ `json-key-order`, `whitespace`, `history-edited`, …) and a template lint;
162
+ - priced tool-output caps, cold compaction and the warm-compaction break-even;
163
+ - the engine's own hit rate from vLLM or SGLang metrics (`--engine-metrics FILE|URL`).
164
+ - **Quality gate** (`aiinfra quality`, `fleetops shadow quality`) replays real tasks with pass checks on both endpoints.
165
+ The checks are contains, regex, exact, number and json. Results are paired by task, with a non-inferiority bound
166
+ (`--max-drop` points). `shadow compare --quality` rolls back on a drop and extends the test when the result is
167
+ unsettled.
168
+ - **GitHub Action**: the repository's `action.yml` runs any of these, writes the Markdown report to the job summary and
169
+ fails the job on a failed gate.
170
+ - **MCP**: `workload_assess` and `optimize_metric` (read-only; `simulate` runs the dry run). The server now has 22 tools.
171
+ - **Records**: `llm_call` keeps `ttftS` (time to first token) when the source has it.
172
+ - **Inference Sizer**: the operating point (used by `fleetops shadow plan` and the validations) now counts prefix-cache
173
+ hits. Only the uncached part of a prompt is prefilled, as the sizing already assumed. Predictions for workloads with a
174
+ cache hit rate give a shorter TTFT than before.
175
+
176
+ ### Fixed
177
+
178
+ - **Paths on Windows:** harness-ledger expands a leading `~` to the home folder itself. Command Prompt and PowerShell
179
+ pass `~` through unexpanded, so before this `aiinfra suggest ~/.claude/projects` failed there with ENOENT. (#90)
180
+ - **Models without an example price:** when most calls are on a model the example price table doesn't list, such as a
181
+ newer Claude model, costs are now in relative units, with a note saying so. Before, every change on those calls
182
+ saved $0, so `suggest` raised nothing. When nothing clears the bar, `suggest` now says why: the closest changes, the
183
+ `--min-gain` threshold, and missing timings. (#90)
184
+
6
185
  ## 0.4.0 (2026-11-29)
7
186
 
8
187
  The services now deploy anywhere with one command, and the catalog is current. `deploy/cloud/up.sh` puts fleetops,
package/README.md CHANGED
@@ -7,7 +7,9 @@ and a person approves every change. Each tool is also an Agent Skill.
7
7
  **Try it in your browser:** [Inference Sizer](https://hardikashah-eng.github.io/AIInfraTools/sizer/) ·
8
8
  [What fits on my GPUs](https://hardikashah-eng.github.io/AIInfraTools/sizer/#fit) ·
9
9
  [FleetScope](https://hardikashah-eng.github.io/AIInfraTools/fleetscope/) ·
10
- **Install:** `npx aiinfra-tools --help`
10
+ **Install:** `npx aiinfra-tools --help` ·
11
+ **New here?** [Getting started](docs/GETTING-STARTED.md): ten minutes from nothing to the first change worth making on
12
+ your own agent logs.
11
13
 
12
14
  Each tool lives in its own folder with its own README. What has been checked against real data, and what it found:
13
15
  [docs/RESULTS.md](docs/RESULTS.md).
@@ -102,6 +104,36 @@ All skills need Node.js 22+ and nothing else.
102
104
 
103
105
  **Changing a tool.** The skill folders carry copies of the tools' code (`scripts/`), docs (`references/`) and examples (`assets/`), so each folder works on its own. After editing a tool, run `node scripts/build-skills.mjs`. CI fails while the copies are out of date. `node --test scripts/test-skills.mjs` runs each skill's documented commands from an isolated copy.
104
106
 
107
+ ## Optimize across the stack
108
+
109
+ `aiinfra assess traces/` reads agent logs or traces once and gives four things:
110
+
111
+ - the workload's classes (critical, realtime, agentic, reasoning, batch), with input:output token ratios and what bounds
112
+ each;
113
+ - why the prefix cache misses: which part of the prompt breaks it, and the engine's own hit rate against what the traces
114
+ could reuse;
115
+ - for each goal, every change across prompt, cache, harness, context, agent, model, model options, serving, GPU and
116
+ scheduling that moves it;
117
+ - the best combinations of those changes.
118
+
119
+ `aiinfra advise --goal ttft --apply …` dry-runs a combination and gates it in CI with `--fail-if`; the repository is
120
+ also a GitHub Action. `aiinfra quality` replays real tasks on both endpoints and blocks a drop in success rate. See
121
+ [docs/OPTIMIZE.md](docs/OPTIMIZE.md).
122
+
123
+ `aiinfra suggest` raises those changes where people already look, once each, and remembers what was accepted,
124
+ dismissed or snoozed. The places are:
125
+
126
+ - Claude Code, through a hook and a status line;
127
+ - pull requests, with a prompt lint and one comment kept up to date;
128
+ - the LiteLLM gateway, live, per request;
129
+ - a Grafana panel;
130
+ - Slack and Lark/Feishu cards;
131
+ - comments on Langfuse sessions;
132
+ - beside the answer in the Inference Sizer and FleetScope pages.
133
+
134
+ It reads your own logs, public agent trajectories (SWE-agent, OpenHands) and Mooncake serving traces. See
135
+ [docs/SUGGEST.md](docs/SUGGEST.md).
136
+
105
137
  ## Workload Intelligence
106
138
 
107
139
  FleetOps now includes a [workload profiler](fleetops/docs/WORKLOADS.md) with six synthetic application profiles (coding agents, chat, report generation, RAG search, deep research and autocomplete). It can inspect existing request logs or FleetOps request records, report workload fingerprints and export privacy-conscious session replay CSVs compatible with FleetScope.
package/bin/aiinfra.mjs CHANGED
@@ -21,10 +21,20 @@ export const TOOLS = {
21
21
  'workload-profile': { file: 'fleetops/tools/workload-profile.mjs', what: 'profile and synthesize application workloads (agents, chat, RAG…)' },
22
22
  'fix-skew': { file: 'hybrid-tracing/tools/fix-skew.mjs', what: 'estimate and remove clock skew from OTLP traces' },
23
23
  'skew-corrector': { file: 'hybrid-tracing/tools/skew-corrector.mjs', what: 'run the skew-corrector service' },
24
+ 'claude-code-hook': { file: 'harness-ledger/integrations/claude-code/aiinfra-hook.mjs', what: 'Claude Code hook: cache misses and tool-output waste shown in Claude Code (--print-settings)' },
25
+ 'claude-code-statusline': { file: 'harness-ledger/integrations/claude-code/aiinfra-statusline.mjs', what: 'Claude Code status line: the session\'s cache hit rate and avoidable spend' },
24
26
  mcp: { file: 'mcp/server.mjs', what: 'run every tool as an MCP server over stdio (for Claude, Cursor and other MCP clients)' },
25
27
  };
26
28
  TOOLS.report = { file: 'bin/report.mjs', what: 'plan → verify → account on one page: sizer prediction, last shadow verdict, calibration, agent economics' };
27
29
  TOOLS.demo = { file: 'fleetops/tools/loop-demo.mjs', what: 'the whole loop on a real week of a GPU cluster: observe → diagnose → simulate → approve → optimize → verify' };
30
+ // commands that are one tool's subcommand, promoted to the top level: `aiinfra assess …` is `aiinfra harness-ledger assess …`
31
+ export const SHORTCUTS = {
32
+ assess: { tool: 'harness-ledger', args: ['assess'], what: 'one report: workload classes and token ratios, prefix-cache doctor, the optimizer per goal' },
33
+ advise: { tool: 'harness-ledger', args: ['advise'], what: 'every change across the stack that moves TTFT, TPOT, cost or GPUs; best combinations; a dry run' },
34
+ suggest: { tool: 'harness-ledger', args: ['suggest'], what: 'the changes worth making, raised once and remembered; to Grafana, Slack, Lark or Langfuse' },
35
+ 'prompt-lint': { tool: 'harness-ledger', args: ['lint'], what: 'prompt templates and request bodies that will miss the prefix cache' },
36
+ quality: { tool: 'fleetops', args: ['shadow', 'quality'], what: 'replay real tasks on the baseline and candidate endpoints; block a drop in success rate' },
37
+ };
28
38
  const ALIASES = { 'inference-sizer': 'sizer', 'gpu-ledger': 'ledger', harness: 'harness-ledger', tracing: 'fix-skew', 'hybrid-tracing': 'fix-skew' };
29
39
  const version = () => JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
30
40
 
@@ -32,6 +42,7 @@ function help() {
32
42
  const w = Math.max(...Object.keys(TOOLS).map(k => k.length));
33
43
  return `aiinfra ${version()}: AIInfraTools from one command\n\nUsage: aiinfra <tool> [args…] (every tool takes --help; most take --json)\n\n` +
34
44
  Object.entries(TOOLS).map(([k, t]) => ` ${k.padEnd(w)} ${t.what}`).join('\n') +
45
+ '\n\nShortcuts:\n' + Object.entries(SHORTCUTS).map(([k, x]) => ` ${k.padEnd(w)} ${x.what} (${x.tool} ${x.args.join(' ')})`).join('\n') +
35
46
  `\n\nAlso: aiinfra version · aiinfra path <tool> (the script's path, for skills and scripts)\nDocs: https://github.com/hardikashah-eng/AIInfraTools\n`;
36
47
  }
37
48
 
@@ -40,6 +51,7 @@ export function main(argv) {
40
51
  if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(help()); return 0; }
41
52
  if (cmd === 'version' || cmd === '--version' || cmd === '-v') { process.stdout.write(version() + '\n'); return 0; }
42
53
  if (cmd === 'path') { const t = TOOLS[ALIASES[rest[0]] || rest[0]]; if (!t) { process.stderr.write(`unknown tool: ${rest[0]}\n`); return 2; } process.stdout.write(path.join(ROOT, t.file) + '\n'); return 0; }
54
+ if (SHORTCUTS[cmd]) return main([SHORTCUTS[cmd].tool, ...SHORTCUTS[cmd].args, ...rest]);
43
55
  const t = TOOLS[ALIASES[cmd] || cmd];
44
56
  if (!t) { process.stderr.write(`aiinfra: unknown tool "${cmd}"\n\n${help()}`); return 2; }
45
57
  const r = spawnSync(process.execPath, [path.join(ROOT, t.file), ...rest], { stdio: 'inherit' });
@@ -261,6 +261,77 @@
261
261
  ]
262
262
  }
263
263
  ]
264
+ },
265
+ {
266
+ "id": 6,
267
+ "type": "table",
268
+ "title": "Optimization suggestions",
269
+ "description": "Open suggestions from aiinfra suggest --store: the change, what it moves, its risk and the dry-run command. Accept, dismiss or snooze with aiinfra suggest accept|dismiss|snooze ID.",
270
+ "gridPos": {
271
+ "x": 0,
272
+ "y": 24,
273
+ "w": 24,
274
+ "h": 9
275
+ },
276
+ "targets": [
277
+ {
278
+ "datasource": {
279
+ "type": "yesoreyeram-infinity-datasource",
280
+ "uid": "${DS_FLEETOPS}"
281
+ },
282
+ "refId": "A",
283
+ "type": "json",
284
+ "source": "url",
285
+ "parser": "backend",
286
+ "format": "table",
287
+ "url": "/api/suggestions?status=open",
288
+ "url_options": {
289
+ "method": "GET"
290
+ },
291
+ "columns": [
292
+ {
293
+ "selector": "layer",
294
+ "text": "layer",
295
+ "type": "string"
296
+ },
297
+ {
298
+ "selector": "title",
299
+ "text": "change",
300
+ "type": "string"
301
+ },
302
+ {
303
+ "selector": "goal",
304
+ "text": "goal",
305
+ "type": "string"
306
+ },
307
+ {
308
+ "selector": "effectPct",
309
+ "text": "effect",
310
+ "type": "string"
311
+ },
312
+ {
313
+ "selector": "risk",
314
+ "text": "risk",
315
+ "type": "string"
316
+ },
317
+ {
318
+ "selector": "confidence",
319
+ "text": "from",
320
+ "type": "string"
321
+ },
322
+ {
323
+ "selector": "command",
324
+ "text": "dry run",
325
+ "type": "string"
326
+ },
327
+ {
328
+ "selector": "id",
329
+ "text": "id",
330
+ "type": "string"
331
+ }
332
+ ]
333
+ }
334
+ ]
264
335
  }
265
336
  ]
266
337
  }
@@ -7,8 +7,9 @@ GPUs, an engine version or its configuration, networking, topology, or the servi
7
7
  fleetops shadow plan --baseline-config h100.json --candidate-config b200.json --trace sessions.jsonl --rps 4 --out plan.json
8
8
  fleetops shadow replay --trace sessions.jsonl --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live
9
9
  fleetops shadow answers --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live --out answers.json
10
+ fleetops shadow quality --tasks tasks.jsonl --baseline http://vllm-old:8000 --candidate http://vllm-new:8000 --model M --live
10
11
  fleetops shadow compare --baseline variant=baseline,source=shadow-replay --candidate variant=candidate,source=shadow-replay \
11
- --plan plan.json --answers answers.json --baseline-gpus 8 --baseline-rate 2.5 --candidate-gpus 8 --candidate-rate 5
12
+ --plan plan.json --answers answers.json --quality .fleetops/shadow/quality.json --baseline-gpus 8 --baseline-rate 2.5 --candidate-gpus 8 --candidate-rate 5
12
13
  fleetops shadow baseline save --name chat --select pool=chat --from 2026-11-01 --to 2026-11-08
13
14
  fleetops shadow watch --name chat --select pool=chat --from 2026-11-24
14
15
  fleetops shadow demo # a candidate that looks faster and isn't
@@ -226,7 +227,29 @@ It reports:
226
227
 
227
228
  Fewer than 98% identical, or a mean log-prob drift over 0.05, is "different", and the decision is roll back however fast
228
229
  the candidate is. Some changes are expected to alter outputs, such as a new quantization. For those, set
229
- `--gates gates.json` with `{ "answers": { "match": 0.9 } }` and check quality separately.
230
+ `--gates gates.json` with `{ "answers": { "match": 0.9 } }` and check quality with the quality gate.
231
+
232
+ ## Quality gate
233
+
234
+ Identical tokens are the wrong bar for a change that is meant to alter outputs (FP8 or FP4 weights, an FP8 KV cache, a
235
+ new model, a capped tool output or a compacted context upstream). What matters is whether the candidate still solves the
236
+ tasks. `shadow quality` replays real evaluation tasks on both endpoints at temperature 0 and checks each answer:
237
+
238
+ ```jsonl
239
+ {"id": "refund-policy", "prompt": "Can I return an opened item after 40 days?", "check": {"type": "contains", "value": "30 days"}}
240
+ {"id": "sum", "messages": [{"role": "user", "content": "What is 17 * 23?"}], "check": {"type": "number", "value": 391}}
241
+ {"id": "json", "prompt": "Return the order as JSON with id and status.", "check": {"type": "json", "value": {"status": "shipped"}}}
242
+ ```
243
+
244
+ Checks: `contains`, `not-contains`, `regex`, `exact`, `number` (within `tol`), `json` (parses; with `value`, those keys
245
+ match). The comparison is paired by task: only the tasks one arm solved and the other didn't carry information. The gate
246
+ is a non-inferiority test on the difference in success rate: the candidate passes when the lower 95% bound of
247
+ (candidate − baseline) is above −`--max-drop` points (2 by default). A clear drop is **worse** and `compare --quality`
248
+ rolls back; an unsettled result with fewer than `--min-tasks` (20) or a wide interval is **inconclusive**, and the
249
+ decision is to extend the test, with an estimate of how many more tasks would settle it. Endpoint errors count as
250
+ failures. Nothing is sent without `--live`, and only task ids, pass/fail and counts are written (no prompts or answers).
251
+
252
+ `harness-ledger advise` marks the changes that carry quality risk; its dry run names this gate as the next step for them.
230
253
 
231
254
  ## Safety
232
255
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fleetops",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Shared data layer, continuous calibration, root-cause analysis and safe optimization across the AIInfraTools utilities.",
@@ -9,7 +9,8 @@
9
9
  // - datastore documents: { createdAt, healthEvent, healthEventStatus } (nodeQuarantined, faultRemediated, …)
10
10
  // - HealthEventResource objects (healthevents.dgxc.nvidia.com): { spec: HealthEvent, status: HealthEventStatus }
11
11
  // - bare HealthEvent objects (protobuf JSON: camelCase; enums as names or numbers; timestamps RFC 3339 or {seconds})
12
- // Fields as in NVSentinel v1.33.0's data-models/protobufs/health_event.proto and event-exporter.
12
+ // Fields as in NVSentinel v1.34.0's data-models/protobufs/health_event.proto and event-exporter (v1.33.0 had the same
13
+ // fields). HealthEvent.id is not read: it is set by producers and is not unique (v1.34.0's proto says so).
13
14
  import { xidClass, DEVICE_CLASSES } from './logs.mjs';
14
15
 
15
16
  const ACTIONS = { 0: 'NONE', 2: 'COMPONENT_RESET', 5: 'CONTACT_SUPPORT', 6: 'RUN_FIELDDIAG', 15: 'RESTART_VM', 24: 'RESTART_BM', 25: 'REPLACE_VM', 26: 'RUN_DCGMEUD', 27: 'CUSTOM', 99: 'UNKNOWN' };
@@ -7,6 +7,7 @@
7
7
  // GET /api/diagnose?symptom=S&from=T&to=T[&pool=P&job=J&nodes=a,b]
8
8
  // GET /api/goodput?from=T&to=T[&job=J&format=html|md] training goodput (unscoped or infra tokens)
9
9
  // GET /api/tune?from=T&to=T[&format=md] tuning recommendations (unscoped or infra tokens)
10
+ // GET /api/suggestions[?status=open&from=T] aiinfra suggest's suggestions, the latest record per id
10
11
  // Grafana: the Infinity data source (JSON, backend parser) reads /api/series and /api/incidents directly; see
11
12
  // deploy/grafana-dashboard.json.
12
13
  import { whereFrom } from './store.mjs';
@@ -48,6 +49,13 @@ export function handleApi(store, who, method, rawUrl) {
48
49
  const recs = scoped(q.kind, store.query(q.kind, { from, to, where: whereFrom(u.searchParams.getAll('where')) }), to).slice(0, limit);
49
50
  return json(recs, recs.length);
50
51
  }
52
+ if (p === '/api/suggestions') {
53
+ const latest = new Map();
54
+ for (const r of scoped('suggestion', store.query('suggestion', { from: time(q.from), to: time(q.to) }), time(q.to))) { const cur = latest.get(r.id); if (!cur || r.t >= cur.t) latest.set(r.id, r); }
55
+ const recs = [...latest.values()].filter(r => !q.status || r.status === q.status).sort((a, b) => Math.abs(b.effect || 0) - Math.abs(a.effect || 0))
56
+ .map(r => Object.assign({}, r, { effectPct: r.effect != null ? `${r.effect > 0 ? '+' : ''}${(100 * r.effect).toFixed(1)}%` : '', time: new Date(r.t * 1000).toISOString() }));
57
+ return json(recs, recs.length);
58
+ }
51
59
  if (p === '/api/series') {
52
60
  const kind = q.kind || 'device', field = q.field, step = Math.max(1, num(q.step, 60)), agg = AGG[q.agg || 'avg'];
53
61
  if (!field || !agg) return { status: 400, type: 'text/plain', body: 'field is required; agg is avg|max|min|sum|count|p50|p99\n' };
@@ -31,6 +31,8 @@
31
31
  // check a node check before admission (tools/admit-node.sh): { node, check: dcgm-diag|rvs-diag|nccl-allreduce|burn-in|pcie|gpu-count, ok?, value?, unit?, detail? }
32
32
  // admission a node's admission verdict: { node, verdict: admit|reject|incomplete, failed, missing, by? }
33
33
  // rollout a step of a version rollout: { id, event: applied|verified|rolled-back|halted, stage, field, version, nodes }
34
+ // suggestion a change worth making, from aiinfra suggest: { id, change, status: open|accepted|dismissed|snoozed, layer, title,
35
+ // goal, effect, saves, risk, confidence, command, sessions } (the latest per id is current: /api/suggestions)
34
36
  // Later PRs add calibration, drift, incident and optimization records.
35
37
 
36
38
  export const KINDS = {
@@ -60,6 +62,7 @@ export const KINDS = {
60
62
  check: ['node', 'check'],
61
63
  admission: ['node', 'verdict'],
62
64
  rollout: ['id', 'event'],
65
+ suggestion: ['id', 'change', 'status'],
63
66
  };
64
67
 
65
68
  export const JOB_STATUS = new Set(['ok', 'failed', 'killed', 'cancelled', 'timeout', 'retried']);
@@ -0,0 +1,107 @@
1
+ // The quality gate: replay real evaluation tasks on the baseline and the candidate endpoint and block the change when
2
+ // the candidate solves fewer of them. Latency checks say whether a change is faster; this says whether it still does
3
+ // the work (a quantized model, a capped tool output, a compacted context or a new model can all change answers).
4
+ //
5
+ // Tasks, one JSON object per line:
6
+ // { "id": "t1", "prompt": "…" | "messages": [ … ], "check": { "type": "contains", "value": "Paris" }, "maxTokens": 256 }
7
+ // Checks (on the answer text):
8
+ // contains / not-contains a substring (case-insensitive unless "case": true)
9
+ // regex a regular expression ("flags" optional)
10
+ // exact the whole answer, trimmed
11
+ // number the last number in the answer within "tol" (absolute, default 0) of "value"
12
+ // json the answer (or its first {…} block) parses as JSON; with "value", every key in value matches
13
+ // Both arms answer every task at temperature 0. The comparison is paired: each task is solved by both, neither, or one
14
+ // of the two, and only the tasks where they disagree carry information. The verdict is a non-inferiority test on the
15
+ // difference in success rate: the candidate passes when the lower 95% bound of (candidate − baseline) is above
16
+ // −maxDrop. Nothing is sent without --live; only task ids, pass/fail and counts are kept (no prompts or answers).
17
+ export const DEFAULTS = { maxDrop: 0.02, minTasks: 20, maxTokens: 512, concurrency: 8, timeoutS: 300 };
18
+
19
+ export function loadTasks(text) {
20
+ const tasks = [];
21
+ String(text).split(/\r?\n/).forEach((l, i) => {
22
+ const s = l.trim(); if (!s || s.startsWith('#')) return;
23
+ let t; try { t = JSON.parse(s); } catch { throw new Error(`tasks line ${i + 1}: not JSON`); }
24
+ if (!t.prompt && !Array.isArray(t.messages)) throw new Error(`tasks line ${i + 1}: needs "prompt" or "messages"`);
25
+ if (!t.check || !CHECKS[t.check.type]) throw new Error(`tasks line ${i + 1}: "check.type" one of ${Object.keys(CHECKS).join(', ')}`);
26
+ tasks.push({ id: String(t.id ?? `task-${i + 1}`), prompt: t.prompt, messages: t.messages, check: t.check, maxTokens: t.maxTokens });
27
+ });
28
+ const ids = new Set(); for (const t of tasks) { if (ids.has(t.id)) throw new Error(`tasks: duplicate id ${t.id}`); ids.add(t.id); }
29
+ return tasks;
30
+ }
31
+
32
+ const lastNumber = s => { const m = String(s).replace(/,(?=\d{3}\b)/g, '').match(/-?\d+(?:\.\d+)?(?:e[-+]?\d+)?/gi); return m ? Number(m[m.length - 1]) : null; };
33
+ const jsonOf = s => { try { return JSON.parse(s); } catch { const m = String(s).match(/\{[\s\S]*\}/); if (!m) return undefined; try { return JSON.parse(m[0]); } catch { return undefined; } } };
34
+ const subset = (want, got) => (want && typeof want === 'object' ? got != null && typeof got === 'object' && Object.keys(want).every(k => subset(want[k], got[k])) : want === got);
35
+ export const CHECKS = {
36
+ contains: (a, c) => (c.case ? a.includes(String(c.value)) : a.toLowerCase().includes(String(c.value).toLowerCase())),
37
+ 'not-contains': (a, c) => !CHECKS.contains(a, c),
38
+ regex: (a, c) => new RegExp(c.value, c.flags || '').test(a),
39
+ exact: (a, c) => a.trim() === String(c.value).trim(),
40
+ number: (a, c) => { const x = lastNumber(a); return x != null && Math.abs(x - Number(c.value)) <= Number(c.tol || 0); },
41
+ json: (a, c) => { const j = jsonOf(a); return j !== undefined && (c.value === undefined || subset(c.value, j)); },
42
+ };
43
+ export const check = (answer, chk) => CHECKS[chk.type](String(answer ?? ''), chk);
44
+
45
+ // one answer from an OpenAI-compatible endpoint (vLLM, SGLang, a gateway): chat completions, or plain completions
46
+ export async function ask(arm, task, { model, maxTokens = DEFAULTS.maxTokens, completions = false, fetchImpl = fetch, timeoutS = DEFAULTS.timeoutS } = {}) {
47
+ const headers = { 'content-type': 'application/json' }; if (arm.apiKey) headers.authorization = `Bearer ${arm.apiKey}`;
48
+ const base = { model: arm.model || model, max_tokens: task.maxTokens || maxTokens, temperature: 0, seed: 0 };
49
+ const prompt = task.prompt ?? task.messages.map(m => `${m.role}: ${typeof m.content === 'string' ? m.content : JSON.stringify(m.content)}`).join('\n');
50
+ const body = completions ? { ...base, prompt } : { ...base, messages: task.messages || [{ role: 'user', content: task.prompt }] };
51
+ const ac = new AbortController(), timer = setTimeout(() => ac.abort(), timeoutS * 1000);
52
+ try {
53
+ const res = await fetchImpl(arm.url.replace(/\/$/, '') + (completions ? '/v1/completions' : '/v1/chat/completions'), { method: 'POST', headers, body: JSON.stringify(body), signal: ac.signal });
54
+ if (!res.ok) return { error: `HTTP ${res.status}` };
55
+ const j = await res.json(), c = j.choices && j.choices[0];
56
+ return { text: c ? (completions ? c.text : c.message && c.message.content) ?? '' : '' };
57
+ } catch (e) { return { error: e.name === 'AbortError' ? 'timeout' : e.message }; } finally { clearTimeout(timer); }
58
+ }
59
+
60
+ // paired success rates. results: [{ id, baseline: bool, candidate: bool }]. The interval on the difference uses the
61
+ // discordant counts (lost: baseline solved it and the candidate didn't; gained: the reverse), with half a count added
62
+ // to each so that a run with no disagreements still has a width.
63
+ export function pairedQuality(results, { maxDrop = DEFAULTS.maxDrop, minTasks = DEFAULTS.minTasks } = {}) {
64
+ const n = results.length, bp = results.filter(r => r.baseline).length, cp = results.filter(r => r.candidate).length;
65
+ const lost = results.filter(r => r.baseline && !r.candidate).length, gained = results.filter(r => !r.baseline && r.candidate).length;
66
+ const diff = n ? (cp - bp) / n : 0;
67
+ const b = lost + 0.5, c = gained + 0.5, m = n + 1, d = (c - b) / m, se = Math.sqrt(Math.max(0, b + c - (c - b) ** 2 / m)) / m;
68
+ const lo = d - 1.96 * se, hi = d + 1.96 * se;
69
+ let verdict, why, more = 0;
70
+ if (n < minTasks) { verdict = 'inconclusive'; why = `${n} tasks: at least ${minTasks} are needed to judge`; more = minTasks - n; }
71
+ else if (lo > 0) { verdict = 'better'; why = `the candidate solves more tasks (+${(100 * diff).toFixed(1)} points)`; }
72
+ else if (lo >= -maxDrop) { verdict = 'same'; why = `no drop past ${(100 * maxDrop).toFixed(1)} points (95% bound ${(100 * lo).toFixed(1)})`; }
73
+ else if (hi < -maxDrop || (hi < 0 && diff <= -maxDrop)) { verdict = 'worse'; why = `the candidate solves fewer tasks (${(100 * diff).toFixed(1)} points; ${lost} lost, ${gained} gained)`; }
74
+ else {
75
+ verdict = 'inconclusive'; why = `the drop could be up to ${(100 * -lo).toFixed(1)} points: more tasks needed`;
76
+ const margin = Math.max(0.002, d + maxDrop); more = Math.max(1, Math.ceil(n * ((1.96 * se) / margin) ** 2 - n));
77
+ }
78
+ return { n, baseline: { passed: bp, rate: n ? bp / n : 0 }, candidate: { passed: cp, rate: n ? cp / n : 0 }, lost, gained, diff, lo, hi, maxDrop, verdict, why, more };
79
+ }
80
+
81
+ async function pool(items, k, f) { const out = new Array(items.length); let i = 0; await Promise.all(Array.from({ length: Math.min(k, items.length) }, async () => { while (i < items.length) { const j = i++; out[j] = await f(items[j], j); } })); return out; }
82
+
83
+ export async function runQuality(tasks, arms, { live = false, model, maxTokens, completions = false, concurrency = DEFAULTS.concurrency, maxDrop = DEFAULTS.maxDrop, minTasks = DEFAULTS.minTasks, fetchImpl = fetch, timeoutS } = {}) {
84
+ if (arms.length !== 2) throw new Error('two endpoints: baseline and candidate');
85
+ if (!live) return { dryRun: true, tasks: tasks.length, arms: arms.map(a => a.name), note: `${tasks.length} tasks × 2 endpoints at temperature 0 (${completions ? '/v1/completions' : '/v1/chat/completions'})` };
86
+ const [A, B] = arms;
87
+ const rows = await pool(tasks, concurrency, async t => {
88
+ const [a, b] = await Promise.all([ask(A, t, { model, maxTokens, completions, fetchImpl, timeoutS }), ask(B, t, { model, maxTokens, completions, fetchImpl, timeoutS })]);
89
+ return { id: t.id, baseline: !a.error && check(a.text, t.check), candidate: !b.error && check(b.text, t.check), errors: [a.error && 'baseline', b.error && 'candidate'].filter(Boolean) };
90
+ });
91
+ const q = pairedQuality(rows, { maxDrop, minTasks });
92
+ const errs = k => rows.filter(r => r.errors.includes(k)).length;
93
+ q.baseline.errors = errs('baseline'); q.candidate.errors = errs('candidate');
94
+ return Object.assign({ kind: 'fleetops.shadow-quality', dryRun: false, t: Math.floor(Date.now() / 1000) }, q, {
95
+ changed: rows.filter(r => r.baseline !== r.candidate).map(r => ({ id: r.id, baseline: r.baseline, candidate: r.candidate })) });
96
+ }
97
+
98
+ export function qualityText(q) {
99
+ if (q.dryRun) return `dry run: ${q.note}. Add --live to send them.`;
100
+ const L = [`quality: ${q.verdict.toUpperCase()}: ${q.why}`,
101
+ ` ${q.n} tasks; baseline solved ${q.baseline.passed} (${(100 * q.baseline.rate).toFixed(1)}%), candidate ${q.candidate.passed} (${(100 * q.candidate.rate).toFixed(1)}%)`,
102
+ ` difference ${(100 * q.diff).toFixed(1)} points (95% CI ${(100 * q.lo).toFixed(1)} to ${(100 * q.hi).toFixed(1)}); ${q.lost} lost, ${q.gained} gained; gate: no drop past ${(100 * q.maxDrop).toFixed(1)} points`];
103
+ if (q.baseline.errors || q.candidate.errors) L.push(` endpoint errors (counted as failures): baseline ${q.baseline.errors}, candidate ${q.candidate.errors}`);
104
+ if (q.verdict === 'inconclusive' && q.more) L.push(` about ${q.more} more tasks would settle it`);
105
+ if (q.changed && q.changed.length) L.push(` tasks that changed: ${q.changed.slice(0, 12).map(x => `${x.id} ${x.baseline ? 'lost' : 'gained'}`).join(', ')}${q.changed.length > 12 ? ` and ${q.changed.length - 12} more` : ''}`);
106
+ return L.join('\n');
107
+ }
@@ -133,9 +133,12 @@ export function compare(base0, cand0, opt = {}) {
133
133
  for (const [k, p] of Object.entries(opt.predicted)) { const m = metrics[k]; const meas = m ? (m.effect ?? null) : null; if (meas == null || !Number.isFinite(p)) continue; rows.push({ metric: k, predicted: p, measured: meas, off: (1 + meas) / (1 + p) - 1 }); }
134
134
  prediction = { rows, holds: rows.every(r => Math.abs(r.off) <= G.prediction) };
135
135
  }
136
- const d = decide(metrics, answers, prediction);
137
- // answers, prediction and infra appear only when given: absent rather than null, so their shape is part of the --json contract
138
- return Object.assign({ decision: d.decision, why: d.why, paired, requests: { baseline: base.length, candidate: cand.length }, metrics, gates: G }, answers ? { answers } : {}, prediction ? { prediction } : {}, opt.infra ? { infra: opt.infra } : {});
136
+ const quality = opt.quality && !opt.quality.dryRun ? opt.quality : null;
137
+ const d = decide(metrics, answers, prediction, { quality });
138
+ // answers, prediction, quality and infra appear only when given: absent rather than null, so their shape is part of the --json contract
139
+ return Object.assign({ decision: d.decision, why: d.why, paired, requests: { baseline: base.length, candidate: cand.length }, metrics, gates: G }, answers ? { answers } : {}, prediction ? { prediction } : {},
140
+ quality ? { quality: { n: quality.n, baseline: quality.baseline, candidate: quality.candidate, lost: quality.lost, gained: quality.gained, diff: quality.diff, lo: quality.lo, hi: quality.hi, maxDrop: quality.maxDrop, verdict: quality.verdict, why: quality.why } } : {},
141
+ opt.infra ? { infra: opt.infra } : {});
139
142
  }
140
143
 
141
144
  // errors: a difference in rate past the gate, by a one-sided two-proportion test. eb, ec: { n, k } (requests, errors)
@@ -145,15 +148,18 @@ export function errorTest(eb, ec, gate = GATES.errorRate) {
145
148
  }
146
149
 
147
150
  // promote / roll back / extend the test, from the metric verdicts (and answers and the prediction when there are any)
148
- export function decide(metrics, answers = null, prediction = null, { unit = 'requests per arm' } = {}) {
151
+ // quality: a quality-gate result (shadow-quality.mjs): fewer tasks solved rolls back, an unsettled result extends the test
152
+ export function decide(metrics, answers = null, prediction = null, { unit = 'requests per arm', quality = null } = {}) {
149
153
  const vs = Object.entries(metrics).filter(([, m]) => m && m.verdict);
150
154
  const worse = vs.filter(([, m]) => m.verdict === 'worse').map(([k]) => k), open = vs.filter(([, m]) => m.verdict === 'inconclusive').map(([k]) => k);
151
155
  let decision, why;
152
- if (answers && answers.verdict === 'different') { decision = 'roll back'; why = `answers differ (${(100 * answers.matchRate).toFixed(1)}% identical under greedy decoding)`; }
156
+ if (quality && quality.verdict === 'worse') { decision = 'roll back'; why = `quality: ${quality.why}`; }
157
+ else if (answers && answers.verdict === 'different') { decision = 'roll back'; why = `answers differ (${(100 * answers.matchRate).toFixed(1)}% identical under greedy decoding)`; }
153
158
  else if (worse.length) { decision = 'roll back'; why = `worse on ${worse.join(', ')}`; }
154
159
  else if (open.length) { decision = 'extend the test'; why = `not settled on ${open.join(', ')}: about ${Math.max(...open.map(k => metrics[k].more || 0))} more ${unit}`; }
155
160
  else if (['ttft', 'tpot', 'e2e'].every(k => !metrics[k] || metrics[k].verdict === 'no data')) { decision = 'extend the test'; why = 'no latency data to judge yet'; }
156
- else { decision = 'promote'; why = `no metric worse${vs.some(([, m]) => m.verdict === 'better') ? `; better on ${vs.filter(([, m]) => m.verdict === 'better').map(([k]) => k).join(', ')}` : ''}`; }
161
+ else if (quality && quality.verdict === 'inconclusive') { decision = 'extend the test'; why = `quality not settled: ${quality.why}`; }
162
+ else { decision = 'promote'; why = `no metric worse${vs.some(([, m]) => m.verdict === 'better') ? `; better on ${vs.filter(([, m]) => m.verdict === 'better').map(([k]) => k).join(', ')}` : ''}${quality ? `; quality ${quality.verdict} on ${quality.n} tasks` : ''}`; }
157
163
  if (prediction && !prediction.holds) why += '; the prediction was off: recalibrate the sizer for this change';
158
164
  return { decision, why };
159
165
  }
@@ -170,8 +170,11 @@ Shadow upgrades (an infra change measured against the baseline at matched load b
170
170
  the same requests to both endpoints at the same moments (dry run unless --live); results go to the store
171
171
  fleetops shadow answers --baseline URL --candidate URL [--prompts FILE] [--model M] [--live] --out answers.json
172
172
  greedy decoding on both: identical tokens, first divergence, log-probability drift
173
+ fleetops shadow quality --tasks tasks.jsonl --baseline URL --candidate URL [--model M] [--max-drop 2] [--min-tasks 20]
174
+ [--completions] [--concurrency 8] [--live] [--out quality.json]
175
+ real tasks with pass checks on both: success rates paired by task; blocks a drop past --max-drop points
173
176
  fleetops shadow compare --results FILE | --baseline SEL --candidate SEL [--from T --to T]
174
- [--plan plan.json] [--answers answers.json] [--baseline-gpus N --baseline-rate R --candidate-gpus N --candidate-rate R]
177
+ [--plan plan.json] [--answers answers.json] [--quality quality.json] [--baseline-gpus N --baseline-rate R --candidate-gpus N --candidate-rate R]
175
178
  [--baseline-nodes RE --candidate-nodes RE] [--gates gates.json] matched-load verdict: promote, roll back, extend
176
179
  with --plan: a prediction off by more than 15% refits the candidate's sizer efficiencies into
177
180
  <store>/calibration/sizer.json (--calibration F; --no-recalibrate to skip), which plan, inference-sizer --calibration