aiinfra-tools 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/README.md +27 -3
  3. package/bin/aiinfra.mjs +5 -2
  4. package/bin/report.mjs +177 -0
  5. package/fleetops/README.md +33 -1
  6. package/fleetops/deploy/shadow-gate/argo-analysistemplate.yaml +34 -0
  7. package/fleetops/deploy/shadow-gate/argo-rollout-example.yaml +38 -0
  8. package/fleetops/deploy/shadow-gate/flagger-canary.yaml +34 -0
  9. package/fleetops/deploy/shadow-gate/judge.yaml +51 -0
  10. package/fleetops/deploy/shadow-gate/llmd-canary-example.yaml +35 -0
  11. package/fleetops/deploy/shadow-gate/podmonitor-vllm.yaml +20 -0
  12. package/fleetops/deploy/shadow-live/README.md +41 -0
  13. package/fleetops/deploy/shadow-live/kit.yaml +123 -0
  14. package/fleetops/deploy/shadow-live/load-canary.yaml +26 -0
  15. package/fleetops/deploy/shadow-live/run.sh +53 -0
  16. package/fleetops/docs/ADMISSION.md +9 -9
  17. package/fleetops/docs/FABRIC-STORAGE.md +1 -1
  18. package/fleetops/docs/SERVING.md +11 -1
  19. package/fleetops/docs/SHADOW.md +250 -0
  20. package/fleetops/docs/SIGNALS.md +5 -2
  21. package/fleetops/docs/WORKLOADS.md +1 -1
  22. package/fleetops/package.json +7 -4
  23. package/fleetops/src/adapters/fabric.mjs +19 -7
  24. package/fleetops/src/adapters/live.mjs +38 -5
  25. package/fleetops/src/adapters/logs.mjs +10 -7
  26. package/fleetops/src/adapters/nvsentinel.mjs +95 -0
  27. package/fleetops/src/adapters/topology.mjs +53 -1
  28. package/fleetops/src/admission.mjs +26 -18
  29. package/fleetops/src/api.mjs +2 -1
  30. package/fleetops/src/bundle.mjs +3 -0
  31. package/fleetops/src/calibrate.mjs +1 -1
  32. package/fleetops/src/detect.mjs +1 -1
  33. package/fleetops/src/export.mjs +5 -1
  34. package/fleetops/src/goodput.mjs +0 -2
  35. package/fleetops/src/incidents.mjs +1 -2
  36. package/fleetops/src/ingest.mjs +10 -3
  37. package/fleetops/src/inject.mjs +2 -2
  38. package/fleetops/src/live.mjs +2 -1
  39. package/fleetops/src/llmd.mjs +7 -3
  40. package/fleetops/src/optimize.mjs +1 -1
  41. package/fleetops/src/power.mjs +7 -7
  42. package/fleetops/src/procure.mjs +67 -0
  43. package/fleetops/src/rca.mjs +1 -1
  44. package/fleetops/src/rollout.mjs +1 -1
  45. package/fleetops/src/schema.mjs +3 -2
  46. package/fleetops/src/security.mjs +1 -1
  47. package/fleetops/src/serving.mjs +32 -10
  48. package/fleetops/src/shadow-canary.mjs +74 -0
  49. package/fleetops/src/shadow-gate.mjs +49 -0
  50. package/fleetops/src/shadow-prom.mjs +205 -0
  51. package/fleetops/src/shadow-replay.mjs +147 -0
  52. package/fleetops/src/shadow.mjs +291 -0
  53. package/fleetops/src/stats.mjs +14 -0
  54. package/fleetops/src/traces.mjs +0 -5
  55. package/fleetops/tests/fixtures/real/README.md +5 -0
  56. package/fleetops/tools/admit-node.sh +51 -16
  57. package/fleetops/tools/amd-admit.py +111 -0
  58. package/fleetops/tools/cmd/calibrate.mjs +61 -0
  59. package/fleetops/tools/cmd/capacity.mjs +116 -0
  60. package/fleetops/tools/cmd/common.mjs +32 -0
  61. package/fleetops/tools/cmd/data.mjs +343 -0
  62. package/fleetops/tools/cmd/help.mjs +243 -0
  63. package/fleetops/tools/cmd/incidents.mjs +216 -0
  64. package/fleetops/tools/cmd/rollout.mjs +122 -0
  65. package/fleetops/tools/cmd/server.mjs +122 -0
  66. package/fleetops/tools/cmd/serving.mjs +95 -0
  67. package/fleetops/tools/cmd/shadow.mjs +204 -0
  68. package/fleetops/tools/cmd/training.mjs +79 -0
  69. package/fleetops/tools/collect.sh +6 -1
  70. package/fleetops/tools/fleetops.mjs +18 -1308
  71. package/fleetops/tools/loop-demo.mjs +1 -1
  72. package/fleetops/tools/workload-profile.mjs +0 -1
  73. package/fleetscope/README.md +5 -1
  74. package/fleetscope/build.mjs +4 -0
  75. package/fleetscope/dist/index.html +1013 -28
  76. package/fleetscope/docs/AGENTIC.md +89 -0
  77. package/fleetscope/docs/PLANNING.md +4 -2
  78. package/fleetscope/docs/VALIDATION-AGENTIC.md +37 -0
  79. package/fleetscope/package.json +4 -3
  80. package/fleetscope/src/agentic.js +288 -0
  81. package/fleetscope/src/ask.js +0 -1
  82. package/fleetscope/src/cluster-ui.js +1 -0
  83. package/fleetscope/src/engine.js +29 -13
  84. package/fleetscope/src/index.src.html +15 -5
  85. package/fleetscope/src/inference-ui.js +1 -0
  86. package/fleetscope/src/ingest.js +89 -3
  87. package/fleetscope/src/optimize.js +11 -5
  88. package/fleetscope/src/plan.js +1 -1
  89. package/fleetscope/src/training-ui.js +1 -0
  90. package/fleetscope/tools/agentic.mjs +148 -0
  91. package/fleetscope/tools/tracelab-data.mjs +27 -0
  92. package/gpu-health/README.md +13 -2
  93. package/gpu-health/docs/CONFIG.md +29 -1
  94. package/gpu-health/package.json +7 -4
  95. package/gpu-health/src/actions.mjs +16 -3
  96. package/gpu-health/src/analyze.mjs +3 -0
  97. package/gpu-health/src/config.mjs +3 -0
  98. package/gpu-health/src/executors.mjs +9 -4
  99. package/gpu-health/src/health.mjs +1 -1
  100. package/gpu-health/src/ingest.mjs +27 -3
  101. package/gpu-health/src/platforms.mjs +109 -0
  102. package/gpu-health/src/vendors.mjs +12 -5
  103. package/gpu-health/tools/gpu-health.mjs +6 -4
  104. package/gpu-ledger/README.md +3 -1
  105. package/gpu-ledger/package.json +12 -4
  106. package/gpu-ledger/src/adapters.mjs +3 -2
  107. package/gpu-ledger/src/cloud.mjs +104 -0
  108. package/gpu-ledger/src/core.mjs +12 -10
  109. package/gpu-ledger/tools/ledger.mjs +8 -2
  110. package/harness-ledger/README.md +152 -0
  111. package/harness-ledger/docs/FORMATS.md +114 -0
  112. package/harness-ledger/docs/METHOD.md +133 -0
  113. package/harness-ledger/docs/VALIDATION-ECONOMICS.md +59 -0
  114. package/harness-ledger/docs/VALIDATION-SWEBENCH.md +26 -0
  115. package/harness-ledger/docs/VALIDATION-TRACELAB.md +56 -0
  116. package/harness-ledger/package.json +19 -0
  117. package/harness-ledger/src/demo.mjs +115 -0
  118. package/harness-ledger/src/economics.mjs +184 -0
  119. package/harness-ledger/src/gpu.mjs +80 -0
  120. package/harness-ledger/src/html.mjs +63 -0
  121. package/harness-ledger/src/importers.mjs +247 -0
  122. package/harness-ledger/src/ledger.mjs +128 -0
  123. package/harness-ledger/src/opencost.mjs +55 -0
  124. package/harness-ledger/src/outcomes.mjs +67 -0
  125. package/harness-ledger/src/prices.mjs +75 -0
  126. package/harness-ledger/src/record.mjs +52 -0
  127. package/harness-ledger/src/waste.mjs +136 -0
  128. package/harness-ledger/tools/harness-ledger.mjs +199 -0
  129. package/harness-ledger/tools/validate-economics.mjs +69 -0
  130. package/harness-ledger/tools/validate-swebench.mjs +57 -0
  131. package/harness-ledger/tools/validate-tracelab.mjs +74 -0
  132. package/hybrid-tracing/package.json +4 -3
  133. package/hybrid-tracing/tools/fix-skew.mjs +1 -1
  134. package/inference-sizer/README.md +5 -1
  135. package/inference-sizer/build.mjs +1 -0
  136. package/inference-sizer/dist/index.html +299 -31
  137. package/inference-sizer/docs/ACCELERATORS.md +62 -0
  138. package/inference-sizer/docs/CATALOG.md +71 -0
  139. package/inference-sizer/docs/METHOD.md +1 -1
  140. package/inference-sizer/docs/VALIDATION-INFERENCEX.md +37 -0
  141. package/inference-sizer/package.json +4 -3
  142. package/inference-sizer/src/accelerators.js +194 -0
  143. package/inference-sizer/src/catalog.js +55 -22
  144. package/inference-sizer/src/fit-ui.js +1 -1
  145. package/inference-sizer/src/index.src.html +3 -0
  146. package/inference-sizer/src/model.js +45 -7
  147. package/inference-sizer/src/ui.js +1 -1
  148. package/inference-sizer/tools/validate-agentx.mjs +116 -0
  149. package/inference-sizer/tools/validate-inferencex.mjs +132 -0
  150. package/mcp/README.md +6 -1
  151. package/mcp/server.mjs +34 -0
  152. package/package.json +10 -6
  153. package/schemas/README.md +3 -0
  154. package/schemas/aiinfra.report.schema.json +474 -0
  155. package/schemas/commands.mjs +14 -0
  156. package/schemas/fleetops.shadow.canary.schema.json +96 -0
  157. package/schemas/fleetops.shadow.compare.schema.json +266 -0
  158. package/schemas/fleetops.shadow.prom.schema.json +354 -0
  159. package/schemas/harness-ledger.economics.schema.json +567 -0
  160. package/schemas/sizer.list.schema.json +15 -2
@@ -15,6 +15,7 @@ import { createRequire } from 'node:module';
15
15
  import * as LLMD from './llmd.mjs';
16
16
 
17
17
  const require = createRequire(import.meta.url);
18
+ const REG = require('../../inference-sizer/src/accelerators.js');
18
19
  const SC = require('../../inference-sizer/src/catalog.js'), SM = require('../../inference-sizer/src/model.js'), FIT = require('../../inference-sizer/src/fit.js');
19
20
 
20
21
  // Models whose published weights are already quantized (no --quantization flag needed for the sizer's precision).
@@ -91,9 +92,9 @@ export function planDeployment(opts) {
91
92
  // the context the sizer planned memory for (its default 32K, or the workload's p99 prompt + output if longer)
92
93
  const maxLen = opts.maxModelLen || Math.min(m.maxCtx || 131072, Math.max(SM.SETTINGS.ctx, (wl.islP99 || wl.isl * 4) + (wl.oslP99 || wl.osl * 4)));
93
94
  const seqs = Math.max(8, Math.ceil(lay.concurrency / lay.instances * 1.25 / 8) * 8);
94
- const vendor = (g.vendor || '').toUpperCase() === 'AMD' ? 'amd' : 'nvidia';
95
- const image = opts.image || (vendor === 'amd' ? 'rocm/vllm:latest' : 'vllm/vllm-openai:latest');
96
- if (!opts.image) notes.push(`Image ${image} is a moving tag: pin a version (--image ${vendor === 'amd' ? 'rocm/vllm' : 'vllm/vllm-openai'}:vX.Y.Z) for production.`);
95
+ const V = REG.vendor(g), vendor = V.key;
96
+ const image = opts.image || `${V.images.vllm}:latest`;
97
+ if (!opts.image) notes.push(`Image ${image} is a moving tag: pin a version (--image ${V.images.vllm}:vX.Y.Z) for production.`);
97
98
  const args = [repo, '--served-model-name', m.id, '--port', '8000', '--tensor-parallel-size', String(multiNode ? per : lay.tp), '--max-model-len', String(maxLen),
98
99
  '--gpu-memory-utilization', String(opts.gpuMemoryUtilization || 0.9), '--max-num-seqs', String(seqs), '--kv-cache-dtype', opts.kvDtype || 'fp8', '--enable-prefix-caching'];
99
100
  if (multiNode || lay.pp > 1) args.push('--pipeline-parallel-size', String(multiNode ? nodesPer : lay.pp));
@@ -101,7 +102,17 @@ export function planDeployment(opts) {
101
102
  if (wprec === 'fp8' && !NATIVE_LOWP.has(m.id) && !/fp8/i.test(repo)) args.push('--quantization', 'fp8');
102
103
  if (wprec === 'fp4' && !NATIVE_LOWP.has(m.id) && !opts.hf) notes.push(`The plan assumes fp4 weights: pass --hf with an fp4 checkpoint of ${m.id}, or --weights fp8 to re-plan.`);
103
104
  if (m.experts > 0 && multiNode) args.push('--enable-expert-parallel');
104
- const gpuRes = vendor === 'amd' ? 'amd.com/gpu' : 'nvidia.com/gpu', perPod = multiNode ? per : tpp;
105
+ const gpuRes = V.k8sResource, perPod = multiNode ? per : tpp;
106
+ // Cloud TPU on GKE: the slice is picked by accelerator and topology labels; one host per instance for now
107
+ let nodeSelector = opts.nodeSelector || null;
108
+ if (V.kind === 'tpu') {
109
+ if (multiNode) throw new Error(`${m.id} on ${g.id} needs ${tpp} chips per instance, more than one ${per}-chip TPU host: multi-host TPU slices are not rendered yet`);
110
+ const topo = REG.tpuTopology(g.id, perPod);
111
+ if (!topo) throw new Error(`no single-host ${g.id} topology with ${perPod} chips`);
112
+ nodeSelector = Object.assign({ [V.productLabels[0]]: g.gkeAccelerator, [V.topologyLabel]: topo }, nodeSelector || {});
113
+ for (const flag of ['--kv-cache-dtype', '--quantization']) { const i = args.indexOf(flag); if (i >= 0) args.splice(i, 2); }
114
+ notes.push(`TPU: a ${g.gkeAccelerator} slice with topology ${topo} (${perPod} chip${perPod === 1 ? "" : "s"}) per instance. KV-cache and weight quantization flags are left to vLLM's TPU defaults: check the vllm-tpu release you pin for what it supports.`);
115
+ }
105
116
  const labels = { app: name, 'fleetops.aiinfra/pool': name, 'gpu-health.aiinfra/serving': 'true' };
106
117
  const env = [{ name: 'HF_HOME', value: '/cache/huggingface' }, { name: 'VLLM_NO_USAGE_STATS', value: '1' }];
107
118
  if (opts.hfSecret) env.push({ name: 'HF_TOKEN', valueFrom: { secretKeyRef: { name: opts.hfSecret, key: opts.hfSecretKey || 'token' } } });
@@ -117,7 +128,7 @@ export function planDeployment(opts) {
117
128
  startupProbe: probe(8000, { periodSeconds: 10, failureThreshold: 240 }), readinessProbe: probe(8000, { periodSeconds: 10 }), livenessProbe: probe(8000, { periodSeconds: 20, failureThreshold: 6 }) } : {}),
118
129
  });
119
130
  const annotations = { 'prometheus.io/scrape': 'true', 'prometheus.io/port': '8000', 'prometheus.io/path': '/metrics' };
120
- const spec = Object.assign({ volumes, terminationGracePeriodSeconds: 60 }, opts.nodeSelector ? { nodeSelector: opts.nodeSelector } : {});
131
+ const spec = Object.assign({ volumes, terminationGracePeriodSeconds: 60 }, nodeSelector ? { nodeSelector } : {});
121
132
  const docs = [];
122
133
  if (opts.createNamespace) docs.push({ apiVersion: 'v1', kind: 'Namespace', metadata: { name: ns } });
123
134
  let workload;
@@ -162,14 +173,15 @@ function planDisagg({ m, g, per, wl, tg, wprec, dis, agg, opts, name, ns }) {
162
173
  for (const [k, r] of [['prefill', P], ['decode', D]]) if (r.gpusPerInstance > per) throw new Error(`the ${k} instances need ${r.gpusPerInstance} GPUs, more than a node's ${per}: multi-node P/D roles are not rendered yet; use --mode agg`);
163
174
  if (P.pp > 1 || D.pp > 1) notes.push('The sizer used pipeline parallelism in a role; rendered as tensor parallelism over the same GPUs.');
164
175
  const repo = opts.hf || hfRepo(m); if (!repo) throw new Error(`no Hugging Face repo for ${m.id}; pass --hf ORG/NAME`);
165
- const vendor = (g.vendor || '').toUpperCase() === 'AMD' ? 'amd' : 'nvidia', gpuRes = vendor === 'amd' ? 'amd.com/gpu' : 'nvidia.com/gpu';
176
+ const V = REG.vendor(g), vendor = V.key, gpuRes = V.k8sResource;
177
+ if (!V.images.llmdVllm) throw new Error(`llm-d's P/D guide has no validated vLLM image for ${V.name}: use --mode agg`);
166
178
  const maxLen = opts.maxModelLen || Math.min(m.maxCtx || 131072, Math.max(SM.SETTINGS.ctx, (wl.islP99 || wl.isl * 4) + (wl.oslP99 || wl.osl * 4)));
167
179
  const seqs = Math.max(8, Math.ceil(L.concurrency / D.instances * 1.25 / 8) * 8);
168
180
  const quantization = wprec === 'fp8' && !NATIVE_LOWP.has(m.id) && !/fp8/i.test(repo) ? 'fp8' : null;
169
- const r = LLMD.render({ name, namespace: ns, model: m.id, repo, vendor, gpuResource: gpuRes, image: opts.image || LLMD.LLMD.vllm[vendor], hfSecret: opts.hfSecret, hfSecretKey: opts.hfSecretKey,
181
+ const r = LLMD.render({ name, namespace: ns, model: m.id, repo, vendor, gpuResource: gpuRes, kvBufferDevice: V.kvBufferDevice, image: opts.image || V.images.llmdVllm, hfSecret: opts.hfSecret, hfSecretKey: opts.hfSecretKey,
170
182
  maxLen, gpuMemoryUtilization: opts.gpuMemoryUtilization, kvDtype: opts.kvDtype || 'fp8', quantization, cachePvc: opts.cachePvc, sidecar: opts.sidecarImage,
171
183
  prefill: { tp: P.gpusPerInstance, replicas: P.instances }, decode: { tp: D.gpusPerInstance, replicas: D.instances, maxNumSeqs: seqs } });
172
- if (!opts.image) notes.push(`Image ${LLMD.LLMD.vllm[vendor]} is the vLLM release llm-d's P/D guide validates (${LLMD.LLMD.ref}).`);
184
+ if (!opts.image) notes.push(`Image ${V.images.llmdVllm} is the vLLM release llm-d's P/D guide validates (${LLMD.LLMD.ref}).`);
173
185
  notes.push('NIXL moves the KV cache over UCX: RDMA (InfiniBand, RoCE, EFA) between the prefill and decode nodes is strongly recommended; over TCP it works but slowly.');
174
186
  notes.push('The router\'s prefix-cache affinity gate is left out: calibrate peakPrefillThroughput for this model and GPU (llm-d guides/recipes/router/calibration) and add it.');
175
187
  if (agg) notes.push(`auto: disaggregated ${wl.rate ? `needs ${dis.nodes} node(s) against ${agg.nodes} aggregated` : `carries ${dis.rate.toFixed(1)} req/s against ${agg.rate.toFixed(1)} aggregated`}.`);
@@ -177,7 +189,7 @@ function planDisagg({ m, g, per, wl, tg, wprec, dis, agg, opts, name, ns }) {
177
189
  if (!opts.hfSecret) notes.push(`No --hf-secret: gated models (${repo}) need a Hugging Face token in a Secret.`);
178
190
  const gpus = P.instances * P.gpusPerInstance + D.instances * D.gpusPerInstance, routerYaml = toYaml(r.routerValues);
179
191
  return {
180
- name, namespace: ns, model: m.id, hf: repo, hfSecretName: opts.hfSecret || null, gpu: g.id, vendor, image: opts.image || LLMD.LLMD.vllm[vendor], kind: 'DisaggregatedSet', mode: 'disagg', multiNode: false, nodesPerInstance: 1,
192
+ name, namespace: ns, model: m.id, hf: repo, hfSecretName: opts.hfSecret || null, gpu: g.id, vendor, image: opts.image || V.images.llmdVllm, kind: 'DisaggregatedSet', mode: 'disagg', multiNode: false, nodesPerInstance: 1,
181
193
  layout: { mode: 'disagg', prefill: { tp: P.gpusPerInstance, instances: P.instances }, decode: { tp: D.gpusPerInstance, instances: D.instances, maxNumSeqs: seqs }, gpus, concurrency: L.concurrency, maxModelLen: maxLen, instances: P.instances + D.instances },
182
194
  sized: { basis: dis.rate && !wl.rate ? `all of the hardware: up to ${dis.rate.toFixed(1)} req/s within the targets` : `sized for ${wl.rate} req/s`, nodes: dis.nodes, gpus: dis.gpus, rate: dis.rate }, targets: tg, workload: wl, notes,
183
195
  docs: r.docs, yaml: r.docs.map(x => toYaml(x)).join('---\n'), router: { chart: LLMD.LLMD.routerChart, version: opts.routerVersion || LLMD.LLMD.routerVersion, release: name, values: r.routerValues, yaml: routerYaml }, service: r.service, servicePort: r.servicePort,
@@ -207,6 +219,16 @@ export function toYaml(o, ind = 0) {
207
219
  // runner(argv, { input }) → { code, out, err }: kubectl, real or not (tests)
208
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 : '') }; };
209
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
+
210
232
  // What the cluster has: GPUs per node of the resource, CRDs, the secret.
211
233
  export function preflight(d, { runner = kubectl, helm = helmRun } = {}) {
212
234
  const checks = [], ok = (name, pass, detail) => checks.push({ name, pass, detail });
@@ -216,7 +238,7 @@ export function preflight(d, { runner = kubectl, helm = helmRun } = {}) {
216
238
  const nodes = runner(['get', 'nodes', '-o', 'json']);
217
239
  if (nodes.code === 0) {
218
240
  const items = JSON.parse(nodes.out).items || [];
219
- 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 }));
220
242
  const usable = per.filter(n => n.ready && !n.cordoned && n.gpus >= (d.needs.pods ? Math.min(...d.needs.pods) : d.needs.perPod));
221
243
  let fitPods, podsNeeded;
222
244
  if (d.needs.pods) {
@@ -0,0 +1,74 @@
1
+ // An llm-d canary driven by the shadow-upgrade judge: two LLMInferenceServices (KServe v1alpha2) in one routing group,
2
+ // spec.router.route.weight setting each one's share (proportional, 0–1,000,000), the judge deciding each step.
3
+ //
4
+ // start the canary at its first step (by default 1% of traffic to the candidate)
5
+ // advance ask the judge about the traffic since the last weight change, then:
6
+ // rollback the candidate's weight goes to 0 at once (with --live): stopping is always allowed
7
+ // wait nothing changes
8
+ // promote the next step is queued for a person; it is applied by the next advance --live only after
9
+ // `approve --by NAME`. Raising a canary's share is never automatic.
10
+ // approve a person approves the queued step (their name is recorded)
11
+ //
12
+ // Nothing touches the cluster without --live; without it the kubectl commands are printed. Weights are written with
13
+ // kubectl patch (a merge patch on spec.router.route), so the rest of each resource is left alone.
14
+ import { execFileSync } from 'node:child_process';
15
+
16
+ export const TOTAL = 1000000; // KServe's maximum weight: shares are written as parts per million
17
+ export const DEFAULT_STEPS = [1, 5, 25, 50, 100];
18
+
19
+ export function start({ name, namespace = 'default', group, baseline, candidate, steps = DEFAULT_STEPS, bakeS = 600, now = Math.floor(Date.now() / 1000) }) {
20
+ if (!name || !group || !baseline || !candidate) throw new Error('name, group, baseline and candidate are required');
21
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(group) || group.length > 63) throw new Error(`group ${group}: lowercase letters, digits and -, at most 63 characters (KServe's rule)`);
22
+ const st = steps.map(Number);
23
+ if (!st.length || st.some((x, i) => !(x > 0 && x <= 100) || (i && x <= st[i - 1]))) throw new Error('steps: increasing percentages in (0, 100]');
24
+ return { kind: 'fleetops.llmd-canary', version: 1, name, namespace, group, baseline, candidate, steps: st, step: 0, bakeS, status: 'running', since: now, pending: null, history: [{ t: now, event: 'start', share: st[0] }] };
25
+ }
26
+ export const share = s => (s.status === 'rolled back' ? 0 : s.steps[s.step]);
27
+ export function weightsFor(pct) { const c = Math.round(pct * TOTAL / 100); return { baseline: TOTAL - c, candidate: c }; }
28
+ // the kubectl calls that set both members' weights
29
+ export function patches(s, pct, kubectl = 'kubectl') {
30
+ const w = weightsFor(pct);
31
+ return ['baseline', 'candidate'].map(k => [kubectl, 'patch', 'llminferenceservice', s[k], '-n', s.namespace, '--type', 'merge', '-p', JSON.stringify({ spec: { router: { route: { group: s.group, weight: w[k] } } } })]);
32
+ }
33
+ // the judge's selectors for the two members (llm-d labels each member's pods with llm_isvc_name through the PodMonitor)
34
+ export const selectors = s => ({ select: `namespace="${s.namespace}"`, baseline: `llm_isvc_name="${s.baseline}"`, candidate: `llm_isvc_name="${s.candidate}"` });
35
+
36
+ // What the verdict means for the canary. Returns { state, action }: action.type is rollback | apply | queued |
37
+ // awaiting-approval | wait | bake | done | stopped; action.patch is set when something should be written.
38
+ export function decide(s0, verdict, { now = Math.floor(Date.now() / 1000), why = '' } = {}) {
39
+ const s = JSON.parse(JSON.stringify(s0)), log = (event, extra = {}) => s.history.push(Object.assign({ t: now, event, share: share(s) }, extra));
40
+ if (s.status !== 'running') return { state: s, action: { type: 'stopped', note: `canary is ${s.status}` } };
41
+ if (verdict === 'rollback') {
42
+ s.status = 'rolled back'; s.pending = null; s.since = now; log('rollback', { why });
43
+ return { state: s, action: { type: 'rollback', share: 0, patch: true, note: `the judge says roll back: ${why}` } };
44
+ }
45
+ if (s.pending && s.pending.approvedBy) {
46
+ const to = s.pending.toStep, by = s.pending.approvedBy; s.step = to; s.since = now; log('step', { approvedBy: by, to: s.steps[to] }); s.pending = null;
47
+ if (to === s.steps.length - 1) { s.status = 'done'; log('done'); }
48
+ return { state: s, action: { type: 'apply', share: s.steps[to], patch: true, note: `step to ${s.steps[to]}% approved by ${by}` } };
49
+ }
50
+ if (verdict === 'wait') return { state: s, action: { type: 'wait', note: why || 'not settled yet' } };
51
+ if (verdict !== 'promote') return { state: s, action: { type: 'wait', note: `unknown verdict ${verdict}` } };
52
+ if (now - s.since < s.bakeS) return { state: s, action: { type: 'bake', note: `${s.bakeS - (now - s.since)} s more at ${share(s)}% before a step up is considered` } };
53
+ if (s.step === s.steps.length - 1) { s.status = 'done'; log('done'); return { state: s, action: { type: 'done', note: 'the candidate already carries its final share' } }; }
54
+ if (s.pending) return { state: s, action: { type: 'awaiting-approval', note: `step to ${s.steps[s.pending.toStep]}% waits for: fleetops shadow canary approve --name ${s.name} --by NAME` } };
55
+ s.pending = { id: `${s.name}-${s.step + 1}`, toStep: s.step + 1, createdAt: now, why }; log('queued', { to: s.steps[s.step + 1] });
56
+ return { state: s, action: { type: 'queued', note: `the judge says promote; the step to ${s.steps[s.step + 1]}% is queued for approval: fleetops shadow canary approve --name ${s.name} --by NAME` } };
57
+ }
58
+
59
+ export function approve(s0, by, { now = Math.floor(Date.now() / 1000) } = {}) {
60
+ if (!by || by === true) throw new Error('approver name required (--by NAME)');
61
+ if (!s0.pending) throw new Error(`nothing waits for approval on ${s0.name}`);
62
+ if (s0.pending.approvedBy) throw new Error(`${s0.pending.id} is already approved by ${s0.pending.approvedBy}`);
63
+ const s = JSON.parse(JSON.stringify(s0));
64
+ Object.assign(s.pending, { approvedBy: String(by), approvedAt: now }); s.history.push({ t: now, event: 'approved', by: String(by), to: s.steps[s.pending.toStep] });
65
+ return s;
66
+ }
67
+
68
+ // write the weights (live) or say what would be written
69
+ export function apply(s, pct, { live = false, kubectl = 'kubectl', run = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) } = {}) {
70
+ const cmds = patches(s, pct, kubectl);
71
+ if (!live) return { dryRun: true, commands: cmds };
72
+ const out = []; for (const [cmd, ...args] of cmds) out.push(run(cmd, args));
73
+ return { dryRun: false, commands: cmds, output: out };
74
+ }
@@ -0,0 +1,49 @@
1
+ // The shadow-upgrade judge as a service, for the rollout controllers people already run:
2
+ // Argo Rollouts an AnalysisTemplate `web` metric: POST /verdict → { verdict: promote | rollback | wait, … }
3
+ // successCondition result == "promote", failureCondition result == "rollback"; "wait" is inconclusive
4
+ // Flagger webhooks: POST /flagger/rollout (non-2xx only on rollback, so a failed check means "worse") and
5
+ // POST /flagger/confirm-promotion (200 only on promote: Flagger holds the promotion until then)
6
+ // anything else GET /verdict?baseline=…&candidate=…&lookback=900
7
+ // Each call queries Prometheus for both versions (shadow-prom.mjs) and judges at matched load. The request names the
8
+ // versions by label matchers ({ select, baseline, candidate }); they are checked as matchers before any query is built.
9
+ // Nothing here changes the rollout: the controller decides what a verdict does.
10
+ import http from 'node:http';
11
+ import { authenticate } from './security.mjs';
12
+ import { checkSelector } from './shadow-prom.mjs';
13
+
14
+ const num = v => (v == null || v === '' ? undefined : Number.isFinite(+v) ? +v : NaN);
15
+ export function params(src = {}, defaults = {}) {
16
+ const p = Object.assign({}, defaults);
17
+ for (const k of ['select', 'baseline', 'candidate']) if (src[k] != null && src[k] !== '') p[k] = String(src[k]);
18
+ for (const [k, a] of [['lookback', 'lookback'], ['baselineLookback', 'baseline-lookback'], ['baselineLookback', 'baselineLookback']]) { const v = num(src[a]); if (v !== undefined) p[k] = v; }
19
+ if (!p.baseline || !p.candidate) throw new Error('baseline and candidate selectors are required (label matchers, e.g. llm_isvc_name="chat-v2")');
20
+ for (const k of ['select', 'baseline', 'candidate']) if (p[k]) p[k] = checkSelector(p[k]);
21
+ for (const k of ['lookback', 'baselineLookback']) if (p[k] != null && !(p[k] >= 60 && p[k] <= 30 * 86400)) throw new Error(`${k}: seconds between 60 and 30 days`);
22
+ return p;
23
+ }
24
+
25
+ // evaluate(params) → the result of compareWindows (with `verdict`). log(entry) records each decision.
26
+ export function gateServer(evaluate, { tokens = null, defaults = {}, log = null, maxBody = 64 << 10 } = {}) {
27
+ const body = req => new Promise((res, rej) => { let n = 0; const parts = []; req.on('data', d => { n += d.length; if (n > maxBody) { rej(Object.assign(new Error('body too large'), { code: 413 })); req.destroy(); } else parts.push(d); }); req.on('end', () => res(Buffer.concat(parts).toString('utf8'))); req.on('error', rej); });
28
+ const send = (res, code, obj) => { const json = typeof obj !== 'string'; res.writeHead(code, { 'content-type': json ? 'application/json' : 'text/plain', 'cache-control': 'no-store' }); res.end(json ? JSON.stringify(obj) : obj + '\n'); };
29
+ return http.createServer(async (req, res) => {
30
+ const url = new URL(req.url, 'http://gate');
31
+ try {
32
+ if (req.method === 'GET' && url.pathname === '/healthz') return send(res, 200, 'ok');
33
+ if (!authenticate(tokens, req.headers.authorization)) return send(res, 401, 'a valid bearer token is required');
34
+ const route = url.pathname;
35
+ if (!['/verdict', '/flagger/rollout', '/flagger/confirm-promotion'].includes(route)) return send(res, 404, 'not found');
36
+ let src;
37
+ if (req.method === 'GET' && route === '/verdict') src = Object.fromEntries(url.searchParams);
38
+ else if (req.method === 'POST') { const t = await body(req); const j = t.trim() ? JSON.parse(t) : {}; src = route.startsWith('/flagger/') ? Object.assign({}, j.metadata || {}) : j; }
39
+ else return send(res, 405, 'method not allowed');
40
+ let p; try { p = params(src, defaults); } catch (e) { return send(res, 400, e.message); }
41
+ let r; try { r = await evaluate(p); } catch (e) { return send(res, 502, `prometheus: ${e.message}`); }
42
+ const out = { verdict: r.verdict, decision: r.decision, why: r.why, requests: r.requests, load: r.load, metrics: r.metrics, selectors: { select: p.select || null, baseline: p.baseline, candidate: p.candidate } };
43
+ if (log) log({ t: Math.floor(Date.now() / 1000), route, verdict: r.verdict, why: r.why, baseline: p.baseline, candidate: p.candidate, select: p.select || null });
44
+ if (route === '/verdict') return send(res, 200, out);
45
+ if (route === '/flagger/rollout') return r.verdict === 'rollback' ? send(res, 412, `roll back: ${r.why}`) : send(res, 200, out);
46
+ return r.verdict === 'promote' ? send(res, 200, out) : send(res, 412, `${r.decision}: ${r.why}`);
47
+ } catch (e) { return send(res, e.code === 413 ? 413 : 400, e.message); }
48
+ });
49
+ }
@@ -0,0 +1,205 @@
1
+ // Shadow upgrades from the metrics a canary already exports: per-version vLLM metrics in Prometheus (llm-d controlled
2
+ // deployments, Argo Rollouts, Flagger, or any two label selectors), compared at matched load. See docs/SHADOW.md.
3
+ //
4
+ // A canary's versions see different load: a canary at a small weight, or with fewer replicas, runs at lower load per
5
+ // engine, so it looks faster than it is. Prometheus has no per-request records, but it has short windows (one per
6
+ // step). Each window of each version carries its load (calls running and waiting per engine, mean prompt length,
7
+ // prefix-cache hit rate) and its mean latencies. The baseline's latency is fitted as a function of that load on its own
8
+ // windows; each canary window is compared with what the baseline shows at the canary's load, inside the load range the
9
+ // baseline covers. The interval comes from resampling windows of both versions and fitting again.
10
+ //
11
+ // Metric names are vLLM's (v1 engine): vllm:time_to_first_token_seconds, vllm:request_time_per_output_token_seconds
12
+ // (else vllm:inter_token_latency_seconds), vllm:e2e_request_latency_seconds, vllm:num_requests_running|waiting,
13
+ // vllm:prompt_tokens_total, vllm:generation_tokens_total, vllm:prefix_cache_hits_total|queries_total,
14
+ // vllm:request_success_total{finished_reason}. llm-d's controlled deployments label each version llm_isvc_name.
15
+ import { promRange } from './pull.mjs';
16
+ import { GATES, judge, decide, errorTest } from './shadow.mjs';
17
+ import { median, pctl, rng } from './stats.mjs';
18
+
19
+ // ---------- selectors ----------
20
+ // A selector is a list of Prometheus label matchers, as inside { }: llm_isvc_name="chat-v2",namespace="llm"
21
+ const MATCHER = /^\s*[a-zA-Z_][a-zA-Z0-9_]*\s*(=|!=|=~|!~)\s*"(?:[^"\\]|\\.)*"\s*$/;
22
+ export function checkSelector(s) {
23
+ const x = String(s ?? '').trim().replace(/^\{|\}$/g, '');
24
+ if (!x) throw new Error('empty selector');
25
+ // split on commas outside quotes
26
+ const parts = []; let cur = '', q = false;
27
+ for (let i = 0; i < x.length; i++) { const c = x[i]; if (c === '\\' && q) { cur += c + x[++i]; continue; } if (c === '"') q = !q; if (c === ',' && !q) { parts.push(cur); cur = ''; } else cur += c; }
28
+ if (q) throw new Error(`selector ${s}: unbalanced quotes`);
29
+ parts.push(cur);
30
+ const ok = parts.map(p => p.trim()).filter(Boolean);
31
+ for (const p of ok) if (!MATCHER.test(p)) throw new Error(`selector ${s}: "${p}" is not a label matcher (name="value", name=~"regex", != or !~)`);
32
+ return ok.join(',');
33
+ }
34
+ export const join = (...ss) => ss.filter(Boolean).map(checkSelector).join(',');
35
+
36
+ // ---------- the queries, per version ----------
37
+ export function queries(sel, step = 60) {
38
+ const S = checkSelector(sel), W = `[${Math.max(1, Math.round(step))}s]`, inc = (m, extra = '') => `sum(increase(${m}{${S}${extra}}${W}))`;
39
+ const mean = h => `(${inc(h + '_sum')} / ${inc(h + '_count')})`, p95 = h => `histogram_quantile(0.95, sum by (le) (rate(${h}_bucket{${S}}${W})))`;
40
+ return {
41
+ n: inc('vllm:e2e_request_latency_seconds_count'),
42
+ ttft: mean('vllm:time_to_first_token_seconds'),
43
+ tpot: `${mean('vllm:request_time_per_output_token_seconds')} or ${mean('vllm:inter_token_latency_seconds')}`,
44
+ e2e: mean('vllm:e2e_request_latency_seconds'),
45
+ ttftP95: p95('vllm:time_to_first_token_seconds'),
46
+ e2eP95: p95('vllm:e2e_request_latency_seconds'),
47
+ running: `avg(avg_over_time(vllm:num_requests_running{${S}}${W}))`,
48
+ waiting: `avg(avg_over_time(vllm:num_requests_waiting{${S}}${W}))`,
49
+ engines: `count(vllm:num_requests_running{${S}})`,
50
+ promptTok: inc('vllm:prompt_tokens_total'),
51
+ genTok: inc('vllm:generation_tokens_total'),
52
+ hits: inc('vllm:prefix_cache_hits_total'),
53
+ lookups: inc('vllm:prefix_cache_queries_total'),
54
+ finished: inc('vllm:request_success_total'),
55
+ errors: inc('vllm:request_success_total', ',finished_reason=~"abort|error"'),
56
+ };
57
+ }
58
+
59
+ // query_range answers (one series per query: every query aggregates to a single series) → windows
60
+ export function windowsFrom(series, step = 60) {
61
+ const at = new Map();
62
+ for (const [k, pts] of Object.entries(series)) for (const [t, v] of pts || []) { const x = +v; if (!Number.isFinite(x)) continue; if (!at.has(+t)) at.set(+t, { t: +t }); at.get(+t)[k] = x; }
63
+ const out = [];
64
+ for (const w of [...at.values()].sort((a, b) => a.t - b.t)) {
65
+ if (!(w.n > 0)) continue;
66
+ out.push({
67
+ t: w.t, n: w.n, stepS: step, ttft: w.ttft, tpot: w.tpot, e2e: w.e2e, ttftP95: w.ttftP95, e2eP95: w.e2eP95,
68
+ conc: (w.running || 0) + (w.waiting || 0), engines: w.engines || null,
69
+ isl: w.promptTok > 0 ? w.promptTok / w.n : null, osl: w.genTok > 0 ? w.genTok / w.n : null,
70
+ hit: w.lookups > 0 ? (w.hits || 0) / w.lookups : null, finished: w.finished ?? w.n, errors: w.errors || 0, genTok: w.genTok || 0,
71
+ });
72
+ }
73
+ return out;
74
+ }
75
+
76
+ // fetch both versions over [from, to] (the baseline from baselineFrom when given: its response to load is learned from
77
+ // a longer history than a short canary has); returns { baseline, candidate } windows and the raw series (to save, replay)
78
+ export async function fetchArms(prom, { baseline, candidate, select = null, from, to, baselineFrom = from, step = 60, fetcher, headers }) {
79
+ const sel = { baseline: join(select, baseline), candidate: join(select, candidate) }, raw = { baseline: {}, candidate: {} };
80
+ for (const arm of ['baseline', 'candidate']) {
81
+ for (const [k, q] of Object.entries(queries(sel[arm], step))) {
82
+ const r = await promRange(prom, q, { from: arm === 'baseline' ? baselineFrom : from, to, step, fetcher, headers });
83
+ raw[arm][k] = r.length ? r[0].samples.map(s => [s.t, s.v]) : [];
84
+ }
85
+ }
86
+ return { kind: 'fleetops.shadow-prom', from, baselineFrom, to, step, selectors: sel, series: raw, ...fromSaved({ step, series: raw }) };
87
+ }
88
+ export const fromSaved = j => ({ baseline: windowsFrom(j.series.baseline, j.step), candidate: windowsFrom(j.series.candidate, j.step) });
89
+
90
+ // ---------- matched load over windows ----------
91
+ // The baseline's latency as a function of load, fitted on its own windows: for each canary window, a local linear fit
92
+ // (LOESS) of the baseline's log latency around that window's load, tricube-weighted by distance in log calls per engine
93
+ // and by requests, with prompt length, prefix-cache hit (and output length for end-to-end time) as linear terms. Local
94
+ // fits follow the knee near saturation that a global curve misses. Canary windows outside the baseline's load range
95
+ // (2nd–98th percentile) are left out, never extrapolated.
96
+ const lc = w => Math.log(Math.max(0.5, w.conc || 0.5));
97
+ const covs = (w, m) => { const f = [w.isl > 0 ? Math.log(w.isl) : 0, w.hit ?? 0]; if (m === 'e2e') f.push(w.osl > 0 ? Math.log(w.osl) : 0); return f; };
98
+ function solve(A, b) {
99
+ const k = b.length;
100
+ for (let c = 0; c < k; c++) { let p = c; for (let r = c + 1; r < k; r++) if (Math.abs(A[r][c]) > Math.abs(A[p][c])) p = r; [A[c], A[p]] = [A[p], A[c]]; [b[c], b[p]] = [b[p], b[c]]; if (Math.abs(A[c][c]) < 1e-12) return null; for (let r = 0; r < k; r++) if (r !== c) { const f = A[r][c] / A[c][c]; for (let j = c; j < k; j++) A[r][j] -= f * A[c][j]; b[r] -= f * b[c]; } }
101
+ return b.map((v, i) => v / A[i][i]);
102
+ }
103
+ // baseline prepared once per (resampled) set: load, covariates, log latency, weight
104
+ const prep = (ws, m) => ws.map(w => ({ c: lc(w), x: covs(w, m), y: Math.log(w[m]), n: w.n })).sort((a, b) => a.c - b.c);
105
+ function predict(B, w, m, span) {
106
+ const c0 = lc(w), x0 = covs(w, m), k = Math.min(B.length, Math.max(12, Math.min(80, Math.ceil(span * B.length))));
107
+ // the k nearest in load: B is sorted by load, so they are a contiguous run around c0
108
+ let lo = 0, hi = B.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (B[mid].c < c0) lo = mid + 1; else hi = mid; }
109
+ let i0 = lo, i1 = lo; // [i0, i1)
110
+ while (i1 - i0 < k) { if (i0 > 0 && (i1 >= B.length || c0 - B[i0 - 1].c <= B[i1].c - c0)) i0--; else i1++; }
111
+ const h = Math.max(1e-6, Math.max(c0 - B[i0].c, B[i1 - 1].c - c0) * 1.0001), K = 2 + x0.length, A = Array.from({ length: K }, () => new Array(K).fill(0)), r = new Array(K).fill(0);
112
+ let tot = 0;
113
+ for (let i = i0; i < i1; i++) {
114
+ const u = Math.abs(B[i].c - c0) / h; if (u >= 1) continue; const wt = B[i].n * (1 - u ** 3) ** 3, f = [1, B[i].c - c0, ...B[i].x.map((v, j) => v - x0[j])]; tot += wt;
115
+ for (let a = 0; a < K; a++) { r[a] += wt * f[a] * B[i].y; for (let b = 0; b < K; b++) A[a][b] += wt * f[a] * f[b]; }
116
+ }
117
+ for (let a = 1; a < K; a++) A[a][a] += 1e-6 * tot; // keeps a constant covariate (no hit data) solvable
118
+ const beta = solve(A, r); return beta ? beta[0] : NaN;
119
+ }
120
+ const usable = (ws, m, minReq) => ws.filter(w => w[m] > 0 && w.n >= minReq);
121
+ function support(bw) {
122
+ const r = a => [pctl(a, 0.02), pctl(a, 0.98)], C = r(bw.map(lc)), I = r(bw.map(w => (w.isl > 0 ? Math.log(w.isl) : 0)));
123
+ return w => { const c = lc(w), i = w.isl > 0 ? Math.log(w.isl) : 0; return c >= C[0] && c <= C[1] && i >= I[0] && i <= I[1]; };
124
+ }
125
+ function adjEffect(bw, cw, m, span) {
126
+ const B = prep(bw, m); let s = 0, n = 0;
127
+ for (const w of cw) { const p = predict(B, w, m, span); if (!Number.isFinite(p)) continue; s += w.n * (Math.log(w[m]) - p); n += w.n; }
128
+ return n ? s / n : NaN;
129
+ }
130
+ const resample = (a, u) => a.map(() => a[Math.floor(u() * a.length)]);
131
+ // at least minWin canary windows and minRequests canary requests inside the baseline's load range, or no verdict
132
+ export function windowEffect(bw0, cw0, m, { minWin = 5, minReq = 5, minRequests = 200, boot = null, seed = 11, span = 0.3 } = {}) {
133
+ if (boot == null) boot = Math.max(100, Math.min(200, Math.round(60000 / Math.max(1, bw0.length + cw0.length))));
134
+ const bw = usable(bw0, m, minReq), call = usable(cw0, m, minReq);
135
+ if (bw.length < 20) return null;
136
+ const inside = support(bw), cw = call.filter(inside);
137
+ if (cw.length < minWin || cw.reduce((a, w) => a + w.n, 0) < minRequests) return null;
138
+ const est = adjEffect(bw, cw, m, span); if (!Number.isFinite(est)) return null;
139
+ const u = rng(seed + m.length * 7), bs = [];
140
+ for (let i = 0; i < boot; i++) { const e = adjEffect(resample(bw, u), resample(cw, u), m, span); if (Number.isFinite(e)) bs.push(e); }
141
+ const r = a => a.reduce((s, w) => s + w.n, 0);
142
+ return { est, lo: pctl(bs, 0.025), hi: pctl(bs, 0.975), windows: cw.length, baselineWindows: bw.length, coverage: r(call) ? r(cw) / r(call) : 0, mode: 'matched load (windows)' };
143
+ }
144
+ // the per-version comparison a dashboard makes: request-weighted means over the whole period, no load matching
145
+ export function windowNaive(bw, cw, m) {
146
+ const mean = ws => { let s = 0, n = 0; for (const w of ws) if (w[m] > 0) { s += w[m] * w.n; n += w.n; } return n ? s / n : NaN; };
147
+ return mean(cw) / mean(bw) - 1;
148
+ }
149
+
150
+ export function compareWindows(bw, cw, opt = {}) {
151
+ const G = Object.assign({}, GATES, opt.gates || {}), step = opt.step || (bw[0] && bw[0].stepS) || 60, metrics = {};
152
+ for (const m of ['ttft', 'tpot', 'e2e']) {
153
+ const e = windowEffect(bw, cw, m, opt);
154
+ // judge's "more" is in the unit it is given: windows here, turned into minutes at this step
155
+ const j = judge(e && { est: e.est, lo: e.lo, hi: e.hi }, G[m], e ? e.windows : 0);
156
+ if (j.more != null) j.more = Math.ceil(j.more * step / 60);
157
+ metrics[m] = Object.assign(j, e ? { windows: e.windows, mode: e.mode, coverage: e.coverage } : {}, { naive: windowNaive(bw, cw, m) });
158
+ }
159
+ const sum = (ws, k) => ws.reduce((a, w) => a + (w[k] || 0), 0), eb = { n: sum(bw, 'finished'), k: sum(bw, 'errors') }, ec = { n: sum(cw, 'finished'), k: sum(cw, 'errors') };
160
+ if (eb.n && ec.n) metrics.errorRate = errorTest(eb, ec, G.errorRate);
161
+ const B = opt.baseline || {}, C = opt.candidate || {}, secs = ws => ws.length * step;
162
+ if (B.gpus && C.gpus && bw.length && cw.length) {
163
+ const tb = sum(bw, 'genTok') / secs(bw) / B.gpus, tc = sum(cw, 'genTok') / secs(cw) / C.gpus;
164
+ metrics.tokPerGpuS = { baseline: tb, candidate: tc, effect: tc / tb - 1, note: 'each version at its own load: a canary at low weight shows less' };
165
+ if (B.rate && C.rate) { const cb = B.rate / 3600 / (tb / 1e6), cc = C.rate / 3600 / (tc / 1e6); metrics.costPerMTok = { baseline: cb, candidate: cc, effect: cc / cb - 1, note: 'at the load each version saw' }; }
166
+ }
167
+ const load = ws => ({ windows: ws.length, requests: Math.round(sum(ws, 'n')), concPerEngine: median(ws.map(w => w.conc)), isl: median(ws.map(w => w.isl).filter(Number.isFinite)), hit: median(ws.map(w => w.hit).filter(Number.isFinite)), ttftP95: median(ws.map(w => w.ttftP95).filter(Number.isFinite)), e2eP95: median(ws.map(w => w.e2eP95).filter(Number.isFinite)) });
168
+ let prediction = null;
169
+ if (opt.predicted) {
170
+ const rows = [];
171
+ 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) || !Number.isFinite(meas)) continue; rows.push({ metric: k, predicted: p, measured: meas, off: (1 + meas) / (1 + p) - 1 }); }
172
+ prediction = { rows, holds: rows.every(r => Math.abs(r.off) <= G.prediction) };
173
+ }
174
+ const d = decide(metrics, null, prediction, { unit: 'minutes of canary traffic' });
175
+ if (d.why === 'no latency data to judge yet') d.why = `too little canary traffic to judge yet (needs ${opt.minWin || 5} windows and ${opt.minRequests || 200} requests inside the baseline's load range)`;
176
+ return { decision: d.decision, why: d.why, verdict: verdictOf(d.decision), source: 'prometheus', step, ...(prediction ? { prediction } : {}), requests: { baseline: Math.round(sum(bw, 'n')), candidate: Math.round(sum(cw, 'n')) }, load: { baseline: load(bw), candidate: load(cw) }, metrics, gates: G };
177
+ }
178
+ // one word for rollout controllers
179
+ export const verdictOf = d => (d === 'promote' ? 'promote' : d === 'roll back' ? 'rollback' : 'wait');
180
+
181
+ // ---------- a canary that looks faster than it is ----------
182
+ // The baseline runs at 4–24 calls per engine over a day's swing; the canary, with too many replicas for its weight,
183
+ // at half that. The canary's TPOT is 8% worse at any load, its TTFT the same.
184
+ export function synthWindows({ seed = 5, n = 240, step = 60, t0 = Math.floor(Date.UTC(2026, 10, 25, 8) / 1000), slower = 0.08, loadShare = 0.5 } = {}) {
185
+ const u = rng(seed), noise = s => Math.exp(s * (u() + u() + u() - 1.5)), arm = (scale, k, rps) => {
186
+ const ws = [];
187
+ for (let i = 0; i < n; i++) {
188
+ const conc = scale * (14 + 10 * Math.sin(2 * Math.PI * i / n)) * noise(0.15), isl = 2000 * noise(0.3), osl = 300 * noise(0.2), hit = Math.min(0.98, 0.6 * noise(0.1));
189
+ const ttft = 0.06 * (1 + conc / 8) * (isl / 2000) ** 0.5 * (1 - 0.5 * hit) / 0.7 * noise(0.04), tpot = 0.02 * (1 + conc / 16) * k * noise(0.03);
190
+ const nReq = Math.max(1, Math.round(rps * step * conc / 14 * noise(0.1))), errors = u() < 0.02 ? 1 : 0;
191
+ ws.push({ t: t0 + i * step, n: nReq, stepS: step, ttft, tpot, e2e: ttft + tpot * osl, conc, engines: null, isl, osl, hit, finished: nReq, errors, genTok: nReq * osl });
192
+ }
193
+ return ws;
194
+ };
195
+ return { baseline: arm(1, 1, 9), candidate: arm(loadShare, 1 + slower, 1), step };
196
+ }
197
+ // the same windows as query_range series, for a mock Prometheus or a saved file
198
+ export function seriesOf(ws) {
199
+ const s = {}, put = (k, t, v) => { if (v == null || !Number.isFinite(v)) return; (s[k] = s[k] || []).push([t, String(v)]); };
200
+ for (const w of ws) {
201
+ put('n', w.t, w.n); put('ttft', w.t, w.ttft); put('tpot', w.t, w.tpot); put('e2e', w.t, w.e2e); put('running', w.t, w.conc); put('waiting', w.t, 0); put('engines', w.t, w.engines ?? 1);
202
+ put('promptTok', w.t, w.isl * w.n); put('genTok', w.t, w.genTok); put('hits', w.t, w.hit * 1000); put('lookups', w.t, 1000); put('finished', w.t, w.finished); put('errors', w.t, w.errors);
203
+ }
204
+ return s;
205
+ }
@@ -0,0 +1,147 @@
1
+ // Shadow replay: send the same recorded workload to a baseline and a candidate endpoint at the same moments, and
2
+ // measure each request on both. Every request goes to both arms with one pair id, so compare() can use per-request
3
+ // ratios, which need several times fewer requests than comparing two separate streams.
4
+ //
5
+ // Endpoints are OpenAI-compatible completion servers (vLLM, SGLang, TGI, llm-d gateways): POST /v1/completions with
6
+ // stream: true. Only model calls are sent; nothing else a recorded agent did (tools, writes) is repeated.
7
+ //
8
+ // Prompts are synthetic text of the recorded length. Requests of one session share a growing prefix, so the engine's
9
+ // prefix cache sees the same reuse the session had. Output length is the recorded one (max_tokens; with
10
+ // --exact-output, vLLM's ignore_eos too).
11
+ //
12
+ // Without live: true nothing is sent: run() returns the plan (requests, tokens, duration) so it can be checked first.
13
+
14
+ const WORDS = 'the of and to in is that for on with as at by from this be or are was it an which not have has can will one all their more would there what about out up into than them only other new some could time these two may first then do any like my now over such our man me even most made after also did many before must through back years where much your way well down should because each just those people how too little state good very make world still own see men work long get here between both life being under never day same another know while last might us great old year off come since against go came right used take three'.split(' ');
15
+ // n tokens of text: about one token per short word plus its space
16
+ export function text(seed, nTokens) {
17
+ let s = (seed >>> 0) || 1, out = '';
18
+ for (let i = 0; i < nTokens; i++) { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; out += WORDS[s % WORDS.length] + ' '; }
19
+ return out;
20
+ }
21
+ const hash = x => { let h = 2166136261; for (const ch of String(x)) h = Math.imul(h ^ ch.charCodeAt(0), 16777619); return h >>> 0; };
22
+
23
+ // rows: FleetScope trace rows { t, isl, osl, session?, cached? }. The first request of a session gets its whole prompt;
24
+ // each later one repeats the previous prompt and appends new text, as an agent loop does.
25
+ // maxIsl / maxOsl fit a long agent trace to a small model's context: a session's prompt grows up to maxIsl and then
26
+ // stays there (every later turn is a full prefix hit), output is capped at maxOsl.
27
+ export function requestsFrom(rows, { speed = 1, maxRequests = Infinity, durationS = Infinity, from = null, maxIsl = Infinity, maxOsl = Infinity } = {}) {
28
+ const sorted = [...rows].sort((a, b) => a.t - b.t), t0 = from ?? (sorted[0] ? sorted[0].t : 0), prefix = new Map(), out = [];
29
+ for (const r of sorted) {
30
+ const at = (r.t - t0) / speed; if (at > durationS || out.length >= maxRequests) break;
31
+ const sess = r.session != null ? String(r.session) : null, prev = sess ? prefix.get(sess) : null, isl = Math.min(Math.max(1, r.isl), maxIsl);
32
+ let prompt;
33
+ if (prev && isl > prev.tokens) prompt = prev.text + text(hash(sess + ':' + out.length), isl - prev.tokens);
34
+ else if (prev && r.isl > maxIsl && prev.tokens === isl) prompt = prev.text;
35
+ else prompt = text(hash((sess || 'r') + ':' + out.length + ':' + r.isl), isl);
36
+ if (sess) prefix.set(sess, { text: prompt, tokens: isl });
37
+ out.push({ pair: out.length, at, session: sess, isl, osl: Math.min(maxOsl, Math.max(1, r.osl || 1)), prompt });
38
+ }
39
+ return out;
40
+ }
41
+
42
+ export function summary(reqs, arms) {
43
+ const inTok = reqs.reduce((a, r) => a + r.isl, 0), outTok = reqs.reduce((a, r) => a + r.osl, 0), dur = reqs.length ? reqs[reqs.length - 1].at : 0;
44
+ return { requests: reqs.length, sessions: new Set(reqs.map(r => r.session).filter(Boolean)).size, seconds: dur, promptTokens: inTok, outputTokens: outTok,
45
+ arms: arms.map(a => ({ name: a.name, url: a.url })), note: `each request goes to ${arms.length} endpoints; ${(inTok / 1e6).toFixed(2)}M prompt and ${(outTok / 1e6).toFixed(2)}M output tokens per endpoint` };
46
+ }
47
+
48
+ // One streamed completion; times from the first byte of the response body that carries text.
49
+ export async function complete(arm, req, { model, exact = true, timeoutS = 600, fetchImpl = fetch, now = () => performance.now() / 1000 } = {}) {
50
+ const body = { model: arm.model || model, prompt: req.prompt, max_tokens: req.osl, temperature: 0, stream: true, stream_options: { include_usage: true } };
51
+ if (exact) Object.assign(body, { ignore_eos: true, min_tokens: req.osl });
52
+ const headers = { 'content-type': 'application/json' }; if (arm.apiKey) headers.authorization = `Bearer ${arm.apiKey}`;
53
+ const ctl = new AbortController(), timer = setTimeout(() => ctl.abort(), timeoutS * 1000);
54
+ const t0 = now(); let ttft = null, chunks = 0, usage = null;
55
+ try {
56
+ const res = await fetchImpl(arm.url.replace(/\/$/, '') + '/v1/completions', { method: 'POST', headers, body: JSON.stringify(body), signal: ctl.signal });
57
+ if (!res.ok) return { error: `HTTP ${res.status}`, e2e: now() - t0 };
58
+ const reader = res.body.getReader(), dec = new TextDecoder(); let buf = '';
59
+ for (;;) {
60
+ const { value, done } = await reader.read(); if (done) break;
61
+ buf += dec.decode(value, { stream: true });
62
+ let i; while ((i = buf.indexOf('\n')) >= 0) {
63
+ const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1);
64
+ if (!line.startsWith('data:')) continue; const d = line.slice(5).trim(); if (d === '[DONE]') continue;
65
+ let j; try { j = JSON.parse(d); } catch { continue; }
66
+ if (j.usage) usage = j.usage;
67
+ const txt = j.choices && j.choices[0] && (j.choices[0].text ?? (j.choices[0].delta && j.choices[0].delta.content));
68
+ if (txt) { chunks++; if (ttft == null) ttft = now() - t0; }
69
+ }
70
+ }
71
+ const e2e = now() - t0, osl = usage ? usage.completion_tokens : chunks;
72
+ const out = { ttft, e2e, osl, isl: usage ? usage.prompt_tokens : req.isl };
73
+ const cached = usage && usage.prompt_tokens_details && usage.prompt_tokens_details.cached_tokens; if (cached != null) out.cached = cached;
74
+ if (ttft != null && osl > 1) out.tpot = (e2e - ttft) / (osl - 1);
75
+ return out;
76
+ } catch (e) { return { error: e.name === 'AbortError' ? 'timeout' : String(e.message || e), e2e: now() - t0 }; }
77
+ finally { clearTimeout(timer); }
78
+ }
79
+
80
+ // Send every request to every arm at its scheduled time (open loop), at most maxInflight per arm at once.
81
+ export async function run(reqs, arms, { live = false, maxInflight = 64, model, exact = true, timeoutS = 600, fetchImpl = fetch, sleep = ms => new Promise(r => setTimeout(r, ms)), t0 = Math.floor(Date.now() / 1000), onRecord } = {}) {
82
+ if (!live) return { dryRun: true, plan: summary(reqs, arms) };
83
+ const records = [], start = performance.now() / 1000, inflight = new Map(arms.map(a => [a.name, 0])), pending = [];
84
+ const one = async (arm, req) => {
85
+ while (inflight.get(arm.name) >= maxInflight) await sleep(5);
86
+ inflight.set(arm.name, inflight.get(arm.name) + 1);
87
+ const sent = performance.now() / 1000 - start;
88
+ try {
89
+ const m = await complete(arm, req, { model, exact, timeoutS, fetchImpl });
90
+ const rec = Object.assign({ t: t0 + sent, variant: arm.name, pair: req.pair, session: req.session || undefined, isl: req.isl, osl: req.osl, source: 'shadow-replay' }, m);
91
+ if (m.error) rec.error = m.error;
92
+ records.push(rec); if (onRecord) onRecord(rec);
93
+ } finally { inflight.set(arm.name, inflight.get(arm.name) - 1); }
94
+ };
95
+ for (const req of reqs) {
96
+ const wait = req.at - (performance.now() / 1000 - start); if (wait > 0) await sleep(wait * 1000);
97
+ for (const arm of arms) pending.push(one(arm, req));
98
+ }
99
+ await Promise.all(pending);
100
+ return { dryRun: false, records: records.sort((a, b) => a.t - b.t || a.pair - b.pair), plan: summary(reqs, arms) };
101
+ }
102
+
103
+ // ---------- the same answers ----------
104
+ // Greedy decoding with log-probabilities on a fixed prompt set: identical tokens on both arms, the first position where
105
+ // they part, and how far the log-probabilities of the shared tokens moved. Numerics changes (kernels, FP8, a new tensor-
106
+ // parallel layout, an engine upgrade) show up here before they show up in any latency metric.
107
+ export const PROMPTS = [
108
+ 'Write a Python function that returns the n-th Fibonacci number iteratively.',
109
+ 'Explain in three sentences why the sky is blue.',
110
+ 'List five prime numbers greater than 100.',
111
+ 'Translate to French: The meeting has been moved to Thursday afternoon.',
112
+ 'Summarize the plot of a story about a lighthouse keeper who finds a message in a bottle.',
113
+ 'What is 17 multiplied by 23? Show the steps.',
114
+ 'Write a SQL query that returns the ten customers with the highest total order value.',
115
+ 'Give three tips for reducing memory use in a large Python program.',
116
+ 'Describe the difference between TCP and UDP for a beginner.',
117
+ 'Complete the sequence: 2, 6, 12, 20, 30, …',
118
+ 'Write a two-line slogan for a bicycle repair shop.',
119
+ 'Convert 72 degrees Fahrenheit to Celsius and explain the formula.',
120
+ 'What does the Unix command `grep -rn TODO .` do?',
121
+ 'Name the planets of the solar system in order from the sun.',
122
+ 'Write a regular expression that matches a US ZIP code with an optional four-digit extension.',
123
+ 'Explain what a hash map is and its average lookup cost.',
124
+ ];
125
+ export async function greedy(arm, prompt, { model, maxTokens = 64, fetchImpl = fetch } = {}) {
126
+ const headers = { 'content-type': 'application/json' }; if (arm.apiKey) headers.authorization = `Bearer ${arm.apiKey}`;
127
+ const res = await fetchImpl(arm.url.replace(/\/$/, '') + '/v1/completions', { method: 'POST', headers, body: JSON.stringify({ model: arm.model || model, prompt, max_tokens: maxTokens, temperature: 0, logprobs: 1, seed: 0 }) });
128
+ if (!res.ok) throw new Error(`${arm.name}: HTTP ${res.status}`);
129
+ const j = await res.json(), c = j.choices[0], lp = c.logprobs || {};
130
+ return { tokens: lp.tokens || (c.text ? [...c.text] : []), logprobs: lp.token_logprobs || [] };
131
+ }
132
+ export function compareAnswers(pairs) {
133
+ let same = 0, divergeSum = 0, diffs = [];
134
+ for (const { a, b } of pairs) {
135
+ let k = 0; while (k < a.tokens.length && k < b.tokens.length && a.tokens[k] === b.tokens[k]) k++;
136
+ if (k === a.tokens.length && k === b.tokens.length) same++; else divergeSum += k;
137
+ for (let i = 0; i < k; i++) if (Number.isFinite(a.logprobs[i]) && Number.isFinite(b.logprobs[i])) diffs.push(Math.abs(a.logprobs[i] - b.logprobs[i]));
138
+ }
139
+ const n = pairs.length, differ = n - same;
140
+ return { prompts: n, identical: same, matchRate: n ? same / n : 0, meanFirstDivergence: differ ? divergeSum / differ : null, meanAbsLogprobDiff: diffs.length ? diffs.reduce((x, y) => x + y, 0) / diffs.length : null };
141
+ }
142
+ export async function answers(arms, { prompts = PROMPTS, live = false, model, maxTokens = 64, fetchImpl = fetch } = {}) {
143
+ if (!live) return { dryRun: true, prompts: prompts.length, arms: arms.map(a => a.name), note: `${prompts.length} prompts × ${arms.length} endpoints, greedy, ${maxTokens} tokens each` };
144
+ const [A, B] = arms, pairs = [];
145
+ for (const p of prompts) pairs.push({ prompt: p, a: await greedy(A, p, { model, maxTokens, fetchImpl }), b: await greedy(B, p, { model, maxTokens, fetchImpl }) });
146
+ return Object.assign({ dryRun: false }, compareAnswers(pairs));
147
+ }