aiinfra-tools 0.3.0 → 0.5.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 (65) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +43 -0
  3. package/bin/aiinfra.mjs +12 -0
  4. package/fleetops/deploy/grafana-dashboard.json +71 -0
  5. package/fleetops/deploy/shadow-live/README.md +8 -0
  6. package/fleetops/deploy/shadow-live/kit.yaml +2 -0
  7. package/fleetops/deploy/shadow-live/run.sh +6 -1
  8. package/fleetops/docs/SHADOW.md +25 -2
  9. package/fleetops/package.json +1 -1
  10. package/fleetops/src/api.mjs +8 -0
  11. package/fleetops/src/ingest.mjs +9 -2
  12. package/fleetops/src/schema.mjs +3 -0
  13. package/fleetops/src/serving.mjs +11 -1
  14. package/fleetops/src/shadow-quality.mjs +107 -0
  15. package/fleetops/src/shadow.mjs +12 -6
  16. package/fleetops/tools/cmd/help.mjs +4 -1
  17. package/fleetops/tools/cmd/shadow.mjs +14 -2
  18. package/fleetscope/build.mjs +4 -0
  19. package/fleetscope/dist/index.html +809 -4
  20. package/fleetscope/package.json +1 -1
  21. package/fleetscope/src/engine.js +19 -2
  22. package/fleetscope/src/index.src.html +23 -1
  23. package/gpu-health/package.json +1 -1
  24. package/gpu-ledger/package.json +1 -1
  25. package/harness-ledger/README.md +48 -0
  26. package/harness-ledger/integrations/README.md +11 -0
  27. package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
  28. package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
  29. package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
  30. package/harness-ledger/package.json +1 -1
  31. package/harness-ledger/src/advise.mjs +410 -0
  32. package/harness-ledger/src/assess.mjs +66 -0
  33. package/harness-ledger/src/doctor.mjs +202 -0
  34. package/harness-ledger/src/engine-metrics.mjs +35 -0
  35. package/harness-ledger/src/importers.mjs +14 -3
  36. package/harness-ledger/src/lint.mjs +115 -0
  37. package/harness-ledger/src/mooncake.mjs +83 -0
  38. package/harness-ledger/src/profile.mjs +164 -0
  39. package/harness-ledger/src/record.mjs +2 -2
  40. package/harness-ledger/src/suggest.mjs +177 -0
  41. package/harness-ledger/src/trajectory.mjs +81 -0
  42. package/harness-ledger/src/workload-demo.mjs +100 -0
  43. package/harness-ledger/tools/harness-ledger.mjs +224 -5
  44. package/hybrid-tracing/package.json +1 -1
  45. package/inference-sizer/build.mjs +1 -0
  46. package/inference-sizer/dist/index.html +192 -17
  47. package/inference-sizer/docs/CATALOG.md +71 -0
  48. package/inference-sizer/docs/METHOD.md +1 -1
  49. package/inference-sizer/package.json +1 -1
  50. package/inference-sizer/src/accelerators.js +23 -1
  51. package/inference-sizer/src/catalog.js +49 -3
  52. package/inference-sizer/src/index.src.html +7 -0
  53. package/inference-sizer/src/model.js +29 -9
  54. package/inference-sizer/src/suggest.js +70 -0
  55. package/inference-sizer/src/ui.js +14 -4
  56. package/inference-sizer/tools/validate-agentx.mjs +8 -2
  57. package/inference-sizer/tools/validate-inferencex.mjs +1 -1
  58. package/mcp/README.md +3 -0
  59. package/mcp/server.mjs +22 -0
  60. package/package.json +3 -1
  61. package/schemas/README.md +3 -0
  62. package/schemas/commands.mjs +7 -0
  63. package/schemas/harness-ledger.advise.schema.json +1102 -0
  64. package/schemas/harness-ledger.assess.schema.json +2823 -0
  65. package/schemas/harness-ledger.suggest.schema.json +326 -0
package/CHANGELOG.md CHANGED
@@ -3,6 +3,160 @@
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
+ ## 0.5.0 (2026-11-29)
7
+
8
+ Optimize across the stack, and raise what is worth changing where people already work. `aiinfra assess`, `advise`
9
+ (with a dry run and a CI gate), `quality`, `suggest` and `prompt-lint` are new commands. The repository is now a
10
+ GitHub Action, and there are new integrations for Claude Code and the LiteLLM gateway. The Inference Sizer and
11
+ FleetScope pages show suggestions beside the answer. New `--json` output: `harness-ledger.advise`,
12
+ `harness-ledger.assess` and `harness-ledger.suggest`. No existing output changed. One prediction did change: the Sizer's
13
+ operating point now counts prefix-cache hits, so predicted TTFT is shorter for workloads that reuse prompts.
14
+
15
+ ### New: suggestions where people already look
16
+
17
+ Suggestions are now raised once each, in the tools people already use, and what people decide about them is
18
+ remembered (#89). Two public data formats are new inputs. New `--json` output: `harness-ledger.suggest`. No existing output
19
+ changed.
20
+
21
+ - **`aiinfra suggest`** turns the optimizer's and the doctor's findings into suggestions.
22
+ - Each suggestion carries its effect, its risk, whether the effect is counted from the traces or modelled, the
23
+ sessions most affected, and the dry-run command.
24
+ - A suggestion is raised once, and again only when its effect grows by half.
25
+ - `accept`, `dismiss`, `snooze` and `reopen` record what people decided. `--watch` re-runs on a rolling window.
26
+ - Sinks: a fleetops store, Slack and Lark/Feishu webhooks, and Langfuse comments on the affected sessions. Slack,
27
+ Lark and Langfuse send only with `--live`.
28
+ - **Claude Code:** `aiinfra claude-code-hook` works as SessionEnd, SessionStart and Stop hooks. It shows the last
29
+ session's cache misses and tool-output waste, and warns once per problem as it happens. A status line shows the
30
+ live cache hit rate and avoidable spend. Both are local, keep counts only, and never block a session.
31
+ - **Prompt lint:** `aiinfra prompt-lint` (`harness-ledger lint`) catches prompt templates and request bodies that will
32
+ miss the prefix cache:
33
+ - a per-call variable before static text;
34
+ - a literal timestamp or id in the prefix;
35
+ - a missing Anthropic cache breakpoint.
36
+
37
+ The GitHub Action gets `comment: true`: one pull request comment per step, updated in place.
38
+ - **LiteLLM gateway:** a proxy callback that reports, live, each request that breaks its session's prompt prefix and
39
+ why. It uses the same causes as the doctor, and a test checks that both name the same breaks. It writes Prometheus
40
+ counters and one log line per template and cause. It never changes or blocks a request.
41
+ - **Grafana:** a `suggestion` record kind, `/api/suggestions` on `fleetops serve`, and an **Optimization suggestions**
42
+ panel on the fleetops dashboard.
43
+ - **Inference Sizer and FleetScope pages:**
44
+ - The Sizer shows "What would change this": the same request re-planned with one change at a time (FP8/FP4 weights,
45
+ FP8 KV, speculative decoding, prefix caching, a shorter context), with GPUs and $/month.
46
+ - FleetScope shows "What to try": one-click what-ifs from the first bottleneck that its Ask box runs.
47
+ - **Inputs:**
48
+ - Agent trajectories with full message lists (SWE-agent, OpenHands datasets). Their request bodies feed the doctor.
49
+ - Mooncake-format serving traces: hit rate by cache size, and random against prefix-aware routing.
50
+ - `harness-ledger mooncake --requests` writes your own traffic as a Mooncake trace with no text, for AIPerf.
51
+ - **MCP:** `list_suggestions` (read-only). The server now has 23 tools.
52
+ - **Workload profile:** "fresh tokens per output token" now counts cache writes as prefilled, so some classes'
53
+ prefill/decode bound changes on data with large cache writes.
54
+
55
+ ### New: optimize across the stack
56
+
57
+ 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
58
+ in CI, and check that answers didn't get worse. New `--json` output: `harness-ledger.advise` and `harness-ledger.assess`.
59
+ No existing output changed.
60
+
61
+ - **`aiinfra assess`** gives one report: workload classes (critical, realtime, agentic, reasoning, batch) with
62
+ input:output token ratios and what bounds each; the prefix-cache doctor; and the optimizer for each goal. Text,
63
+ Markdown (`--md`, for a job summary) or JSON.
64
+ - **`aiinfra advise --goal ttft|tpot|e2e|cost|gpus|throughput`** covers changes in every layer:
65
+ - prompt layout, cache lifetime, tool-output caps, on-demand tool definitions, cold compaction, step caps and
66
+ reasoning budgets;
67
+ - batch off-peak and priority scheduling;
68
+ - prefix-aware routing, FP8/FP4 weights, FP8 KV and speculative decoding;
69
+ - disaggregation, other GPUs and other models.
70
+
71
+ Each change is measured on the recorded calls changed as it would change them, or on the Inference Sizer's operating
72
+ point when self-hosted. The answer gives three combinations (best, at no extra cost, no quality risk). `--apply`
73
+ runs a dry run with how to make and verify each change, `--fail-if 'ttft>+5%'` exits 3 when a bound is crossed, and
74
+ `--out` writes the change set.
75
+ - **Prefix-cache doctor** (`harness-ledger doctor`):
76
+ - hit rate now against what is reachable;
77
+ - from request bodies, which part of the prompt breaks the cache (`system-dynamic`, `tools-reordered`,
78
+ `json-key-order`, `whitespace`, `history-edited`, …) and a template lint;
79
+ - priced tool-output caps, cold compaction and the warm-compaction break-even;
80
+ - the engine's own hit rate from vLLM or SGLang metrics (`--engine-metrics FILE|URL`).
81
+ - **Quality gate** (`aiinfra quality`, `fleetops shadow quality`) replays real tasks with pass checks on both endpoints.
82
+ The checks are contains, regex, exact, number and json. Results are paired by task, with a non-inferiority bound
83
+ (`--max-drop` points). `shadow compare --quality` rolls back on a drop and extends the test when the result is
84
+ unsettled.
85
+ - **GitHub Action**: the repository's `action.yml` runs any of these, writes the Markdown report to the job summary and
86
+ fails the job on a failed gate.
87
+ - **MCP**: `workload_assess` and `optimize_metric` (read-only; `simulate` runs the dry run). The server now has 22 tools.
88
+ - **Records**: `llm_call` keeps `ttftS` (time to first token) when the source has it.
89
+ - **Inference Sizer**: the operating point (used by `fleetops shadow plan` and the validations) now counts prefix-cache
90
+ hits. Only the uncached part of a prompt is prefilled, as the sizing already assumed. Predictions for workloads with a
91
+ cache hit rate give a shorter TTFT than before.
92
+
93
+ ### Fixed
94
+
95
+ - **Paths on Windows:** harness-ledger expands a leading `~` to the home folder itself. Command Prompt and PowerShell
96
+ pass `~` through unexpanded, so before this `aiinfra suggest ~/.claude/projects` failed there with ENOENT. (#90)
97
+ - **Models without an example price:** when most calls are on a model the example price table doesn't list, such as a
98
+ newer Claude model, costs are now in relative units, with a note saying so. Before, every change on those calls
99
+ saved $0, so `suggest` raised nothing. When nothing clears the bar, `suggest` now says why: the closest changes, the
100
+ `--min-gain` threshold, and missing timings. (#90)
101
+
102
+ ## 0.4.0 (2026-11-29)
103
+
104
+ The services now deploy anywhere with one command, and the catalog is current. `deploy/cloud/up.sh` puts fleetops,
105
+ Grafana and the FleetScope and Inference Sizer pages on Google Cloud, AWS, Azure, a neocloud's Kubernetes, on-prem or a
106
+ single GPU server, and hybrid fleets send every site's GPU metrics to one hub. The sizer and FleetScope know the 2026
107
+ open-weight models and the attention they use, and Vera Rubin, MI455X and RTX PRO 6000. No `--json` output changed.
108
+
109
+ - **Deploy anywhere:** one Helm chart, `up.sh gcp | aws | azure | k8s | vm` and `down.sh`, Terraform for each cloud and
110
+ for existing clusters, container images for x86 and Arm (#83). See [docs/DEPLOY.md](docs/DEPLOY.md).
111
+ - **Hybrid fleets:** a site joins a hub with `--site NAME --hub URL`; fleetops records which site each record came from.
112
+ - **Models and hardware:** Kimi K3, DeepSeek V4, GLM-5.x, Qwen3.5 and 3.8, MiniMax M3, Gemma 4 and more; linear,
113
+ compressed and sparse attention in the sizer; a weekly task proposes catalog updates (#80).
114
+ - **AgentX validation** reads InferenceX's real model prefixes and GPU names (#81).
115
+ - **Not yet run on a real cloud:** CI installs a hub and a second site on a local kind cluster; the first GKE, EKS and AKS
116
+ runs will be recorded in [docs/RESULTS.md](docs/RESULTS.md).
117
+
118
+ ### New: deploy anywhere — clouds, neoclouds, on-prem and hybrid
119
+
120
+ - **One Helm chart** (`deploy/helm/aiinfratools`) for the service stack: fleetops, Grafana with the dashboard
121
+ provisioned, the FleetScope and Inference Sizer pages, and a collector (Prometheus in agent mode) that finds the GPU
122
+ exporters on the cluster and sends their series to fleetops. Hub mode runs everything; site mode runs only the
123
+ collector.
124
+ - **One command per target:** `deploy/cloud/up.sh gcp | aws | azure | k8s | vm` makes a GKE Autopilot, EKS Auto Mode or
125
+ AKS cluster when missing, or uses the cluster kubectl points at (neocloud, on-prem), or Docker on one machine.
126
+ `down.sh` removes it, the store's disk first so no cloud disk keeps billing. Google Cloud Shell has a button and a
127
+ walkthrough.
128
+ - **Hybrid fleets:** sites join a hub with `up.sh k8s|vm --site NAME --hub URL`; fleetops ingest takes a per-request
129
+ site from the `X-Fleetops-Site` header, so records say where they came from.
130
+ - **Terraform** for Google, AWS, Azure and existing clusters, through one shared module.
131
+ - **Images** for linux/amd64 and arm64 on GitHub's container registry, pushed from main and releases.
132
+ - **GPU model on any cloud:** fleetops' preflight reads it from GPU Feature Discovery, GKE's label or the instance type,
133
+ and the instance table now has Azure's ND H100/H200/MI300X v5, ND GB200 v6 and ND A100 v4 sizes.
134
+ - CI lints and renders the chart for every platform, validates the Terraform, and installs a hub and a second site on
135
+ kind to check that records arrive tagged by site. See [docs/DEPLOY.md](docs/DEPLOY.md).
136
+
137
+ ### New: models and hardware, current as of November 2026
138
+
139
+ - **Models:** Kimi K3 / K3.1 Pro, Kimi K2.6, DeepSeek-V4-Pro and V4-Flash, GLM-5.1 and GLM-5.3, Mistral Large 4,
140
+ Qwen3.5-397B and Qwen3.8 27B, MiniMax M3 and M2.7, Muse Spark Open and Gemma 4 31B join the Inference Sizer's catalog.
141
+ FleetScope's model menus now list the whole catalog, not five models.
142
+ - **Attention the sizer models:** linear-attention layers with a fixed state per sequence (`linFrac`, `linStateMB`),
143
+ compressed KV (`kvKeep`) and sparse attention (`sparseTopK`). Hugging Face configs with Gated DeltaNet layers or an
144
+ index top-k import with them. A model without these fields sizes exactly as before.
145
+ - **Hardware:** NVIDIA Vera Rubin NVL72, AMD Instinct MI455X (Helios) and NVIDIA RTX PRO 6000 Blackwell Server join the
146
+ accelerator registry, so they reach the sizer, FleetScope, fleetops' power model and telemetry matching.
147
+ - **AgentX validation reads InferenceX's own model prefixes** (`dsv4`, `kimik3.1`, `glm5.3`, `minimaxm3`, `musespark`,
148
+ `qwen3.5`, `gptoss`…), plus A100, Vera Rubin, MI455X and cloud-suffixed GPU names (`b200-nscale`). Models the sizer
149
+ can't size yet are counted as skipped, not read as a shorter prefix.
150
+ - **Kept current weekly:** `inference-sizer/docs/CATALOG.md` says where figures come from and how to add a model or a
151
+ chip, and lists what isn't in yet and why (Trainium3, TPU 8, DeepSeek V4.1 Flash). A weekly scheduled task follows it
152
+ and opens a pull request.
153
+
154
+ ### Fixed
155
+
156
+ - **Live test kit (`fleetops/deploy/shadow-live`):** the engines get 40 minutes to start instead of Kubernetes'
157
+ 10-minute default, which a first start on fresh GPU nodes (pulling the vLLM image, fetching the model) can pass. A
158
+ failed run writes `out/diag.txt` (pods, events, GPUs per node, engine logs) before cleaning up (#82).
159
+
6
160
  ## 0.3.0 (2026-11-26)
7
161
 
8
162
  The loop now covers what a change costs, not only whether it works. There is a new tool for agent harnesses
package/README.md CHANGED
@@ -37,6 +37,19 @@ npx aiinfra-tools sizer --model llama33-70b --gpu H100 # or: npm i -g aiinfra
37
37
  Every command takes `--json`; the output of the ones agents rely on is described by [JSON Schemas](schemas/README.md). Or open the repository in a Codespace ([.devcontainer](.devcontainer/devcontainer.json)): `aiinfra` is ready on the path. The package also installs each tool's own command (`fleetops`, `gpu-health`, `gpu-ledger`, `harness-ledger`, `inference-sizer`,
38
38
  `fleetscope`, `fix-skew`). Or clone the repository and run any tool from its folder.
39
39
 
40
+ ## Deploy the services
41
+
42
+ fleetops, Grafana and the FleetScope and Inference Sizer pages, on Google Cloud, AWS, Azure, a neocloud's Kubernetes,
43
+ on-prem or a single GPU server, in one command; hybrid fleets send every site's GPU metrics to one hub. Terraform too.
44
+ See [docs/DEPLOY.md](docs/DEPLOY.md).
45
+
46
+ ```bash
47
+ deploy/cloud/up.sh gcp | aws | azure | k8s | vm # a hub
48
+ deploy/cloud/up.sh k8s --site onprem-sd --hub https://fleetops.example.com # a site joining it
49
+ ```
50
+
51
+ [![Open in Cloud Shell](https://gstatic.com/cloudssh/images/open-btn.svg)](https://shell.cloud.google.com/cloudshell/editor?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fhardikashah-eng%2FAIInfraTools&cloudshell_tutorial=deploy%2Fcloud%2FTUTORIAL-gcp.md&shellonly=true)
52
+
40
53
  ## The loop in one command
41
54
 
42
55
  `aiinfra demo` runs Observe → Diagnose → Simulate → Approve → Optimize → Verify on one real week of the Microsoft
@@ -89,6 +102,36 @@ All skills need Node.js 22+ and nothing else.
89
102
 
90
103
  **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.
91
104
 
105
+ ## Optimize across the stack
106
+
107
+ `aiinfra assess traces/` reads agent logs or traces once and gives four things:
108
+
109
+ - the workload's classes (critical, realtime, agentic, reasoning, batch), with input:output token ratios and what bounds
110
+ each;
111
+ - why the prefix cache misses: which part of the prompt breaks it, and the engine's own hit rate against what the traces
112
+ could reuse;
113
+ - for each goal, every change across prompt, cache, harness, context, agent, model, model options, serving, GPU and
114
+ scheduling that moves it;
115
+ - the best combinations of those changes.
116
+
117
+ `aiinfra advise --goal ttft --apply …` dry-runs a combination and gates it in CI with `--fail-if`; the repository is
118
+ also a GitHub Action. `aiinfra quality` replays real tasks on both endpoints and blocks a drop in success rate. See
119
+ [docs/OPTIMIZE.md](docs/OPTIMIZE.md).
120
+
121
+ `aiinfra suggest` raises those changes where people already look, once each, and remembers what was accepted,
122
+ dismissed or snoozed. The places are:
123
+
124
+ - Claude Code, through a hook and a status line;
125
+ - pull requests, with a prompt lint and one comment kept up to date;
126
+ - the LiteLLM gateway, live, per request;
127
+ - a Grafana panel;
128
+ - Slack and Lark/Feishu cards;
129
+ - comments on Langfuse sessions;
130
+ - beside the answer in the Inference Sizer and FleetScope pages.
131
+
132
+ It reads your own logs, public agent trajectories (SWE-agent, OpenHands) and Mooncake serving traces. See
133
+ [docs/SUGGEST.md](docs/SUGGEST.md).
134
+
92
135
  ## Workload Intelligence
93
136
 
94
137
  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
  }
@@ -29,5 +29,13 @@ deploy/shadow-live/run.sh --yes # send the traffic; the namespace is deleted
29
29
  Results land in `deploy/shadow-live/out/`: `paired-verdict.txt`, `canary-verdict.txt`, `judge.json`, and
30
30
  `canary-series.json` (the Prometheus series, to rerun with `fleetops shadow prom --file`).
31
31
 
32
+ If a step fails, `out/diag.txt` holds the pods, recent events, GPU counts per node and the engines' last log lines.
33
+ The first start is slow: each node pulls the vLLM image (several GB) and the model before the engine starts, so the
34
+ engine Deployments allow 40 minutes to become ready rather than Kubernetes' 10-minute default.
35
+
36
+ On GKE, the L4 nodes carry `cloud.google.com/gke-accelerator=nvidia-l4` but not the label above; add it with
37
+ `kubectl label nodes -l cloud.google.com/gke-accelerator=nvidia-l4 nvidia.com/gpu.product=NVIDIA-L4`. Create the GPU node
38
+ pool with `--accelerator type=nvidia-l4,count=1,gpu-driver-version=latest` so the driver is installed for you.
39
+
32
40
  For an engine upgrade instead of a known change, set `chat-v2`'s image to the new vLLM version and drop
33
41
  `--no-enable-prefix-caching`; there the verdict is what you want to learn.
@@ -14,6 +14,7 @@ kind: Deployment
14
14
  metadata: { name: chat-v1, namespace: shadow-live }
15
15
  spec:
16
16
  replicas: 2
17
+ progressDeadlineSeconds: 2400 # pulling the vLLM image, fetching the model and starting the engine can pass the 10-minute default
17
18
  selector: { matchLabels: { app.kubernetes.io/name: chat-v1 } }
18
19
  template:
19
20
  metadata: { labels: { app: chat, app.kubernetes.io/name: chat-v1 } }
@@ -34,6 +35,7 @@ kind: Deployment
34
35
  metadata: { name: chat-v2, namespace: shadow-live }
35
36
  spec:
36
37
  replicas: 1
38
+ progressDeadlineSeconds: 2400 # pulling the vLLM image, fetching the model and starting the engine can pass the 10-minute default
37
39
  selector: { matchLabels: { app.kubernetes.io/name: chat-v2 } }
38
40
  template:
39
41
  metadata: { labels: { app: chat, app.kubernetes.io/name: chat-v2 } }
@@ -9,7 +9,12 @@ here="$(cd "$(dirname "$0")" && pwd)"; repo="$(cd "$here/../../.." && pwd)"; out
9
9
  F=(node "$repo/fleetops/tools/fleetops.mjs"); A=(node "$repo/fleetscope/tools/agentic.mjs")
10
10
  live=""; keep=""; for a in "$@"; do case "$a" in --yes) live="--live";; --keep) keep=1;; *) echo "unknown argument $a" >&2; exit 2;; esac; done
11
11
  mkdir -p "$out"; NS=(-n shadow-live); PIDS=()
12
- cleanup() { for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null || true; done; if [ -z "$keep" ] && [ -n "$live" ]; then kubectl delete -f "$here/kit.yaml" --ignore-not-found --wait=false; fi; }
12
+ diag() { # what a failed step needs to be read: pods, recent events, nodes and the engines' last log lines
13
+ { kubectl "${NS[@]}" get pods -o wide; echo; kubectl "${NS[@]}" get events --sort-by=.lastTimestamp | tail -40; echo
14
+ kubectl get nodes -l nvidia.com/gpu.product=NVIDIA-L4 -o custom-columns=NODE:.metadata.name,GPUS:.status.allocatable.nvidia\.com/gpu; echo
15
+ for d in chat-v1 chat-v2; do echo "-- $d"; kubectl "${NS[@]}" describe deploy "$d" | tail -15; kubectl "${NS[@]}" logs "deploy/$d" --tail=40 2>&1 || true; done
16
+ } > "$out/diag.txt" 2>&1 || true; echo "diagnostics written to $out/diag.txt" >&2; }
17
+ cleanup() { rc=$?; [ "$rc" -eq 0 ] || diag; for p in "${PIDS[@]}"; do kill "$p" 2>/dev/null || true; done; if [ -z "$keep" ] && [ -n "$live" ]; then kubectl delete -f "$here/kit.yaml" --ignore-not-found --wait=false; fi; }
13
18
  trap cleanup EXIT
14
19
 
15
20
  n=$(kubectl get nodes -l nvidia.com/gpu.product=NVIDIA-L4 -o name | wc -l)
@@ -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.3.0",
3
+ "version": "0.5.0",
4
4
  "license": "Apache-2.0",
5
5
  "private": true,
6
6
  "description": "Shared data layer, continuous calibration, root-cause analysis and safe optimization across the AIInfraTools utilities.",
@@ -7,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' };
@@ -7,6 +7,9 @@
7
7
  // POST /v1/traces OTLP traces (JSON) → span
8
8
  // GET /metrics fleetops' own metrics (Prometheus text); GET /healthz
9
9
  //
10
+ // Hybrid fleets: a collector at another site sends `X-Fleetops-Site: <name>` (Prometheus remote_write `headers:`,
11
+ // the OpenTelemetry collector's `headers:`), and that request's records carry that site instead of --site.
12
+ //
10
13
  // OTLP/HTTP in protobuf (the collector default) or JSON, gzip or not. OTLP/gRPC (port 4317) is not served: use the
11
14
  // collector's otlphttp exporter.
12
15
  import http from 'node:http';
@@ -20,6 +23,7 @@ import { handleApi } from './api.mjs';
20
23
 
21
24
  const VENDOR_RE = Object.entries(VENDORS).filter(([, p]) => p.detect).map(([k, p]) => [k, new RegExp(p.detect)]);
22
25
  const vendorOf = name => (VENDOR_RE.find(([, re]) => re.test(name)) || [])[0];
26
+ export const SITE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
23
27
  const esc = v => String(v).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
24
28
 
25
29
  // Series (labels + samples) → device records: one exporter "scrape" per vendor and timestamp, through gpu-health's
@@ -205,6 +209,9 @@ export function server(pipe, { site, maxBody = 32 << 20, tokens = null, audit =
205
209
  }
206
210
  if (req.method !== 'POST') return send(res, 404, 'not found\n');
207
211
  if (!can(who, 'ingest')) return send(res, 403, 'needs the ingest role\n');
212
+ const hdrSite = req.headers['x-fleetops-site'];
213
+ if (hdrSite !== undefined && !SITE_RE.test(String(hdrSite))) return send(res, 400, 'x-fleetops-site: letters, digits, . _ - (up to 64)\n');
214
+ const reqSite = hdrSite !== undefined ? String(hdrSite) : site;
208
215
  let body = await read(req);
209
216
  const enc = String(req.headers['content-encoding'] || '').toLowerCase(); // collectors gzip by default
210
217
  if (enc === 'gzip') body = zlib.gunzipSync(body); else if (enc === 'deflate') body = zlib.inflateSync(body); else if (enc && enc !== 'identity' && enc !== 'snappy') return send(res, 415, `content-encoding ${enc} not supported\n`);
@@ -212,12 +219,12 @@ export function server(pipe, { site, maxBody = 32 << 20, tokens = null, audit =
212
219
  if (req.url === '/api/v1/write') {
213
220
  const series = decodeWriteRequest(snappyDecompress(body)), coll = seriesToCollectives(series);
214
221
  if (coll.length && !pipe.offer('collective', coll)) return send(res, 429, 'queue full, retry\n');
215
- const r = seriesToDevices(series.filter(x => !/^nccl_/.test(x.labels.__name__ || '')), { site }); pipe.m.unmapped += r.unmapped; kind = 'device'; recs = r.devices;
222
+ const r = seriesToDevices(series.filter(x => !/^nccl_/.test(x.labels.__name__ || '')), { site: reqSite }); pipe.m.unmapped += r.unmapped; kind = 'device'; recs = r.devices;
216
223
  } else if (/^\/v1\/(metrics|logs|traces)$/.test(req.url)) {
217
224
  const ct = req.headers['content-type'] || '', kindOf = req.url.slice(4);
218
225
  if (!/json|protobuf/.test(ct)) return send(res, 415, 'OTLP must be application/json or application/x-protobuf\n');
219
226
  const proto = /protobuf/.test(ct), j = proto ? decodeOtlp(kindOf, body) : JSON.parse(body.toString('utf8'));
220
- if (req.url === '/v1/metrics') { const r = seriesToDevices(otlpMetricsToSeries(j), { site }); pipe.m.unmapped += r.unmapped; kind = 'device'; recs = r.devices; }
227
+ if (req.url === '/v1/metrics') { const r = seriesToDevices(otlpMetricsToSeries(j), { site: reqSite }); pipe.m.unmapped += r.unmapped; kind = 'device'; recs = r.devices; }
221
228
  else if (req.url === '/v1/logs') { const r = otlpLogsToRecords(j); pipe.m.unmapped += r.unmatched; kind = 'log'; recs = r.logs; }
222
229
  else { kind = 'span'; recs = otlpTracesToSpans(j); }
223
230
  } else return send(res, 404, 'not found\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']);
@@ -219,6 +219,16 @@ export function toYaml(o, ind = 0) {
219
219
  // runner(argv, { input }) → { code, out, err }: kubectl, real or not (tests)
220
220
  export const kubectl = (argv, { input } = {}) => { const r = spawnSync('kubectl', argv, { input, encoding: 'utf8', maxBuffer: 64 << 20 }); return { code: r.error ? 127 : r.status, out: r.stdout || '', err: r.stderr || (r.error ? r.error.message : '') }; };
221
221
 
222
+ // The GPU model on a node, whichever cloud labelled it: GPU Feature Discovery's labels (any cluster with the NVIDIA or
223
+ // AMD operator), GKE's accelerator label, else the instance type (EKS, AKS, GKE, neocloud VMs named like a cloud's).
224
+ const PRODUCT_LABELS = [...new Set(Object.values(REG.VENDORS).flatMap(v => v.productLabels))];
225
+ export function gpuProductOf(labels) {
226
+ const l = PRODUCT_LABELS.map(k => labels[k]).find(Boolean);
227
+ if (l) return l;
228
+ const inst = REG.instanceOf(labels['node.kubernetes.io/instance-type'] || labels['beta.kubernetes.io/instance-type']);
229
+ return inst ? inst.chip : '';
230
+ }
231
+
222
232
  // What the cluster has: GPUs per node of the resource, CRDs, the secret.
223
233
  export function preflight(d, { runner = kubectl, helm = helmRun } = {}) {
224
234
  const checks = [], ok = (name, pass, detail) => checks.push({ name, pass, detail });
@@ -228,7 +238,7 @@ export function preflight(d, { runner = kubectl, helm = helmRun } = {}) {
228
238
  const nodes = runner(['get', 'nodes', '-o', 'json']);
229
239
  if (nodes.code === 0) {
230
240
  const items = JSON.parse(nodes.out).items || [];
231
- const per = items.map(n => ({ name: n.metadata.name, gpus: +((n.status.allocatable || {})[d.needs.gpuResource] || 0), product: (n.metadata.labels || {})['nvidia.com/gpu.product'] || (n.metadata.labels || {})['amd.com/gpu.product-name'] || '', ready: (n.status.conditions || []).some(c => c.type === 'Ready' && c.status === 'True'), cordoned: !!(n.spec || {}).unschedulable }));
241
+ const per = items.map(n => ({ name: n.metadata.name, gpus: +((n.status.allocatable || {})[d.needs.gpuResource] || 0), product: gpuProductOf(n.metadata.labels || {}), ready: (n.status.conditions || []).some(c => c.type === 'Ready' && c.status === 'True'), cordoned: !!(n.spec || {}).unschedulable }));
232
242
  const usable = per.filter(n => n.ready && !n.cordoned && n.gpus >= (d.needs.pods ? Math.min(...d.needs.pods) : d.needs.perPod));
233
243
  let fitPods, podsNeeded;
234
244
  if (d.needs.pods) {