aiinfra-tools 0.4.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.
- package/CHANGELOG.md +96 -0
- package/README.md +30 -0
- package/bin/aiinfra.mjs +12 -0
- package/fleetops/deploy/grafana-dashboard.json +71 -0
- package/fleetops/docs/SHADOW.md +25 -2
- package/fleetops/package.json +1 -1
- package/fleetops/src/api.mjs +8 -0
- package/fleetops/src/schema.mjs +3 -0
- package/fleetops/src/shadow-quality.mjs +107 -0
- package/fleetops/src/shadow.mjs +12 -6
- package/fleetops/tools/cmd/help.mjs +4 -1
- package/fleetops/tools/cmd/shadow.mjs +14 -2
- package/fleetscope/build.mjs +1 -0
- package/fleetscope/dist/index.html +92 -3
- package/fleetscope/package.json +1 -1
- package/fleetscope/src/index.src.html +17 -1
- package/gpu-health/package.json +1 -1
- package/gpu-ledger/package.json +1 -1
- package/harness-ledger/README.md +48 -0
- package/harness-ledger/integrations/README.md +11 -0
- package/harness-ledger/integrations/claude-code/aiinfra-hook.mjs +113 -0
- package/harness-ledger/integrations/claude-code/aiinfra-statusline.mjs +35 -0
- package/harness-ledger/integrations/litellm/aiinfra_prefix_lint.py +247 -0
- package/harness-ledger/package.json +1 -1
- package/harness-ledger/src/advise.mjs +410 -0
- package/harness-ledger/src/assess.mjs +66 -0
- package/harness-ledger/src/doctor.mjs +202 -0
- package/harness-ledger/src/engine-metrics.mjs +35 -0
- package/harness-ledger/src/importers.mjs +14 -3
- package/harness-ledger/src/lint.mjs +115 -0
- package/harness-ledger/src/mooncake.mjs +83 -0
- package/harness-ledger/src/profile.mjs +164 -0
- package/harness-ledger/src/record.mjs +2 -2
- package/harness-ledger/src/suggest.mjs +177 -0
- package/harness-ledger/src/trajectory.mjs +81 -0
- package/harness-ledger/src/workload-demo.mjs +100 -0
- package/harness-ledger/tools/harness-ledger.mjs +224 -5
- package/hybrid-tracing/package.json +1 -1
- package/inference-sizer/build.mjs +1 -0
- package/inference-sizer/dist/index.html +95 -5
- package/inference-sizer/package.json +1 -1
- package/inference-sizer/src/index.src.html +7 -0
- package/inference-sizer/src/model.js +5 -2
- package/inference-sizer/src/suggest.js +70 -0
- package/inference-sizer/src/ui.js +13 -3
- package/mcp/README.md +3 -0
- package/mcp/server.mjs +22 -0
- package/package.json +5 -2
- package/schemas/README.md +3 -0
- package/schemas/commands.mjs +7 -0
- package/schemas/harness-ledger.advise.schema.json +1102 -0
- package/schemas/harness-ledger.assess.schema.json +2823 -0
- package/schemas/harness-ledger.suggest.schema.json +326 -0
|
@@ -228,6 +228,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
228
228
|
.mtx th:first-child, .mtx td:first-child { text-align: left; }
|
|
229
229
|
.mtx input[type=number] { width: 52px; padding: 2px 4px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); }
|
|
230
230
|
.kpi.wide { grid-column: span 2; cursor: pointer; }
|
|
231
|
+
.kpi.try { cursor: default; } .kpi.try .tries { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
|
232
|
+
.kpi.try .tryb, .kpi.try .tryt { font: 12px var(--font-ui); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); background: var(--bg); color: inherit; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
|
233
|
+
.kpi.try .tryb { cursor: pointer; } .kpi.try .tryb:hover { border-color: currentColor; }
|
|
231
234
|
.kpi.wide .v { font-size: 13.5px; font-family: var(--font-ui); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
232
235
|
.legendHud { position: absolute; left: 10px; bottom: 8px; display: flex; gap: 10px; font-size: 11px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 8px; border-radius: 6px; }
|
|
233
236
|
.legendHud i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 4px; vertical-align: 0; }
|
|
@@ -1174,14 +1177,17 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
1174
1177
|
// returns TPOT, TTFT, and output tokens/s per GPU.
|
|
1175
1178
|
function operatingPoint(s, md, c, B) {
|
|
1176
1179
|
const st = decodeStep(s, md, c, B), ps = prefillStats(s, md, c), osl = s.avgOut, isl = Math.min(s.avgIn, s.ctx);
|
|
1180
|
+
// a prefix-cache hit skips that part of the prompt: only the new tokens are prefilled, attending to the cached ones
|
|
1181
|
+
// (as sizeAgg and prefillStats count them; ps.cap is in new tokens per second)
|
|
1182
|
+
const hit = Math.min(0.99, Math.max(0, (s.prefixHit || 0) / 100)), Lnew = Math.max(1, isl * (1 - hit)), Lc = isl - Lnew;
|
|
1177
1183
|
let tpot = st.t, ttft = ps.Sbatch, fp = 0;
|
|
1178
1184
|
for (let i = 0; i < 50; i++) {
|
|
1179
1185
|
const lam = B / (osl * tpot + ttft); // requests/s through this instance
|
|
1180
|
-
fp = Math.min(0.95, lam *
|
|
1186
|
+
fp = Math.min(0.95, lam * Lnew / ps.cap); // share of compute spent on prefill
|
|
1181
1187
|
const t = Math.max(st.tm, st.tc / (1 - fp)) * 1.1 + st.comm + st.ovh;
|
|
1182
1188
|
// a new prompt is prefilled in chunks between decode steps: its share of each step is what decode leaves
|
|
1183
1189
|
const free = Math.max(0.05, 1 - Math.max(st.tm, st.tc) / t);
|
|
1184
|
-
const tt = prefillTime(s, md, c,
|
|
1190
|
+
const tt = prefillTime(s, md, c, Lnew, Lc, 1) / free + mdWait(Math.min(0.85, fp), Lnew / ps.cap) + t;
|
|
1185
1191
|
if (Math.abs(t - tpot) < 1e-7 && Math.abs(tt - ttft) < 1e-6) { tpot = t; ttft = tt; break; }
|
|
1186
1192
|
tpot = t; ttft = tt;
|
|
1187
1193
|
}
|
|
@@ -1257,6 +1263,79 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
1257
1263
|
if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerModel = api;
|
|
1258
1264
|
})(this);
|
|
1259
1265
|
|
|
1266
|
+
</script>
|
|
1267
|
+
<script>
|
|
1268
|
+
/* Suggestions for the Inference Sizer and FleetScope pages: the changes that would change the answer, shown next to it.
|
|
1269
|
+
forSizer re-plans the same request with one change at a time (weight and KV precision, speculative decoding, prefix
|
|
1270
|
+
caching, a shorter context) and keeps the ones that need fewer GPUs. forFleet reads a FleetScope run's first
|
|
1271
|
+
bottleneck and cache numbers and proposes what-ifs the page's Ask box can run in one click.
|
|
1272
|
+
Both are models: `aiinfra assess` on real traces, then fleetops shadow, check them. */
|
|
1273
|
+
(function (root) {
|
|
1274
|
+
'use strict';
|
|
1275
|
+
// speculative decoding: k drafted tokens verified in one step, E accepted per step at acceptance a. A memory-bound
|
|
1276
|
+
// step barely grows with k+1 tokens; a compute-bound one grows with them (same model as harness-ledger advise).
|
|
1277
|
+
function specFactor(st, opt) {
|
|
1278
|
+
const a = (opt && opt.accept) || 0.7, k = (opt && opt.tokens) || 3;
|
|
1279
|
+
const E = (1 - Math.pow(a, k + 1)) / (1 - a), base = Math.max(st.tm, st.tc) + st.comm + st.ovh;
|
|
1280
|
+
const t = Math.max(st.tm * 1.05, st.tc * (k + 1)) + st.comm + st.ovh + 0.05 * Math.max(st.tm, st.tc);
|
|
1281
|
+
return { E: E, factor: t / E / base };
|
|
1282
|
+
}
|
|
1283
|
+
const HOURS = 730;
|
|
1284
|
+
const gpusOf = r => (r && r.chosen ? r.chosen.provGPUs : null);
|
|
1285
|
+
|
|
1286
|
+
function forSizer(s, r, M) {
|
|
1287
|
+
const base = gpusOf(r), out = [];
|
|
1288
|
+
const tryIt = (id, title, patch, extra) => {
|
|
1289
|
+
let r2; try { r2 = M.plan(Object.assign({}, s, patch), { noSens: true }); } catch (e) { return; }
|
|
1290
|
+
const g = gpusOf(r2);
|
|
1291
|
+
if (g == null || (base != null && g >= base)) return;
|
|
1292
|
+
out.push(Object.assign({ id: id, title: title, before: base, after: g, saved: base != null ? base - g : null,
|
|
1293
|
+
costBefore: base != null && s.price ? base * s.price * HOURS : null, costAfter: s.price ? g * s.price * HOURS : null }, extra));
|
|
1294
|
+
};
|
|
1295
|
+
const wprec = s.wprec || 'bf16';
|
|
1296
|
+
if (wprec === 'bf16' && s.tfFp8) tryIt('fp8-weights', 'FP8 weights', { wprec: 'fp8' }, { risk: 'quality', how: 'vLLM --quantization fp8, or an FP8 checkpoint' });
|
|
1297
|
+
if (wprec !== 'fp4' && s.tfFp4) tryIt('fp4-weights', 'FP4 weights (NVFP4/MXFP4)', { wprec: 'fp4' }, { risk: 'quality', how: 'an NVFP4 or MXFP4 checkpoint' });
|
|
1298
|
+
if (s.kvprec === 'bf16') tryIt('fp8-kv', 'FP8 KV cache', { kvprec: 'fp8' }, { risk: 'quality', how: 'vLLM --kv-cache-dtype fp8' });
|
|
1299
|
+
// speculative decoding on the layout the plan chose, at its operating batch
|
|
1300
|
+
const best = r && r.agg && r.agg.best;
|
|
1301
|
+
if (best && best.c && best.Bop) {
|
|
1302
|
+
try {
|
|
1303
|
+
const md = M.derive(s), st = M.decodeStep(s, md, best.c, Math.max(1, Math.round(best.Bop / (best.c.pp || 1)))), sf = specFactor(st);
|
|
1304
|
+
if (sf.factor < 0.95) tryIt('spec-decode', 'Speculative decoding (3 drafted tokens, 70% acceptance assumed)', { tpot: s.tpot / sf.factor },
|
|
1305
|
+
{ risk: 'none', how: 'vLLM --speculative-config (MTP heads where the model has them, else a draft model)', note: `about ${Math.round(100 * (1 - sf.factor))}% faster tokens at this batch` });
|
|
1306
|
+
} catch (e) { /* layout without a decode step: skip */ }
|
|
1307
|
+
}
|
|
1308
|
+
if ((s.prefixHit || 0) < 50 && s.avgIn >= 2000) tryIt('prefix-cache', 'Half of each prompt served from the prefix cache (shared system prompts, agent sessions)', { prefixHit: 50 },
|
|
1309
|
+
{ risk: 'none', how: 'stable prompt prefixes, prefix caching on, prefix-aware routing', note: 'measure your real hit rate: aiinfra assess traces/' });
|
|
1310
|
+
const need = (s.peakIn || 0) + (s.peakOut || 0);
|
|
1311
|
+
if (need > 0 && s.ctx > 2 * need) { let c = 4096; while (c < need * 1.25) c *= 2; if (c < s.ctx) tryIt('context', `Serve a ${c >= 1024 ? Math.round(c / 1024) + 'K' : c} context instead of ${Math.round(s.ctx / 1024)}K (your peak request is ${Math.round(need / 1024)}K)`, { ctx: c }, { risk: 'none', how: 'vLLM --max-model-len' }); }
|
|
1312
|
+
return out.sort((a, b) => (b.saved || 0) - (a.saved || 0));
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
// FleetScope: from a run's summary (first bottleneck, cache locality, speculative decoding) to what-ifs for its Ask box.
|
|
1316
|
+
// Titles are short (the tile sits next to the bottleneck, which names the pool); the Ask phrase names it.
|
|
1317
|
+
function forFleet(sum) {
|
|
1318
|
+
const out = [], bf = sum && sum.bottleneck && sum.bottleneck.first, add = (id, title, why, ask) => out.push({ id: id, title: title, why: why, ask: ask || null });
|
|
1319
|
+
if (bf) {
|
|
1320
|
+
const nm = bf.name;
|
|
1321
|
+
if (bf.kind === 'kv') { add('kv-routing', 'Route sessions to the replica that holds their prefix', `${nm}: KV cache full; reuse cuts what each session holds`, 'Turn on KV-aware routing'); add('kv-more', 'Add 2 instances', 'more KV memory in total', `Add 2 instances to ${nm}`); }
|
|
1322
|
+
if (bf.kind === 'compute') { add('compute-more', 'Add 2 instances', `${nm}: compute saturated`, `Add 2 instances to ${nm}`); add('compute-gpu', 'Move to B200', 'more FLOPS per instance', `What if ${nm} moves to B200?`); }
|
|
1323
|
+
if (bf.kind === 'tpot') { add('tpot-spec', 'Speculative decoding', `${nm}: decode batches too large for the TPOT target`, 'Turn on speculative decoding'); add('tpot-more', 'Add 2 instances', 'smaller decode batches each', `Add 2 instances to ${nm}`); }
|
|
1324
|
+
if (bf.kind === 'queue') add('queue-more', 'Add 2 instances', `${nm}: requests queue`, `Add 2 instances to ${nm}`);
|
|
1325
|
+
if (bf.kind === 'cold') add('cold-warm', 'Keep warm capacity', 'requests wait on cold starts: a higher minimum, or weights cached on local NVMe', null);
|
|
1326
|
+
if (bf.kind === 'link' || bf.kind === 'linkdown') add('link', 'Relieve the link', 'link saturated: send less traffic across it, or raise its bandwidth', null);
|
|
1327
|
+
if (bf.kind === 'down') add('down', 'Capacity for the outage', `${nm} lost instances: spare instances elsewhere carry it`, null);
|
|
1328
|
+
}
|
|
1329
|
+
const loc = sum && sum.locality;
|
|
1330
|
+
if (loc && (loc.misses || loc.hits) && loc.cachedShare < 0.5 && !out.some(x => x.id === 'kv-routing')) add('cache-routing', 'Route sessions to the replica that holds their prefix', `only ${Math.round(100 * loc.cachedShare)}% of prompt tokens came from cache`, 'Turn on KV-aware routing');
|
|
1331
|
+
if (!sum || !sum.spec) { if (bf && bf.kind !== 'tpot' && sum && sum.tpotP99 && !out.some(x => x.id === 'tpot-spec')) add('spec', 'Speculative decoding', 'faster tokens at the same GPUs', 'Turn on speculative decoding'); }
|
|
1332
|
+
return out.slice(0, 4);
|
|
1333
|
+
}
|
|
1334
|
+
|
|
1335
|
+
const api = { forSizer: forSizer, forFleet: forFleet, specFactor: specFactor };
|
|
1336
|
+
if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.SizerSuggest = api;
|
|
1337
|
+
})(this);
|
|
1338
|
+
|
|
1260
1339
|
</script>
|
|
1261
1340
|
<script>
|
|
1262
1341
|
/* FleetScope engine: time-stepped fleet simulation for LLM serving and training.
|
|
@@ -4921,9 +5000,19 @@ function renderKpis() {
|
|
|
4921
5000
|
t1('Days / 100B tokens', t.daysPer100B.toFixed(1), 'train', t.daysPer100B, bt.daysPer100B, true, v => v.toFixed(1));
|
|
4922
5001
|
t1('Training $ / hour', fUsd(t.costPerHr), 'train', t.costPerHr, bt.costPerHr, true, fUsd);
|
|
4923
5002
|
}
|
|
5003
|
+
// what to try next: one-click what-ifs for the Ask box, from the first bottleneck and the cache (SizerSuggest.forFleet)
|
|
5004
|
+
if (s.requests && window.SizerSuggest) {
|
|
5005
|
+
const tries = SizerSuggest.forFleet(s);
|
|
5006
|
+
if (tries.length) tiles.push('<div class="kpi wide try"><div class="k">What to try</div><div class="tries">' + tries.map(x => x.ask
|
|
5007
|
+
? '<button type="button" class="tryb" data-ask="' + esc(x.ask) + '" title="' + esc(x.title) + ': ' + esc(x.why) + ' \u2014 runs: ' + esc(x.ask) + '">' + esc(x.title) + '</button>'
|
|
5008
|
+
: '<span class="tryt" title="' + esc(x.why) + '">' + esc(x.title) + '</span>').join('') + '</div></div>');
|
|
5009
|
+
}
|
|
4924
5010
|
$('#kpis').innerHTML = tiles.join('');
|
|
4925
5011
|
}
|
|
4926
|
-
$('#kpis').addEventListener('click', e => {
|
|
5012
|
+
$('#kpis').addEventListener('click', e => {
|
|
5013
|
+
const a = e.target.closest('[data-ask]'); if (a) { $('#askBox').value = a.dataset.ask; $('#askForm').requestSubmit(); return; }
|
|
5014
|
+
const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek);
|
|
5015
|
+
});
|
|
4927
5016
|
|
|
4928
5017
|
// ---------- charts ----------
|
|
4929
5018
|
const CH = { w: 420, h: 150, l: 38, r: 8, t: 8, b: 18 };
|
package/fleetscope/package.json
CHANGED
|
@@ -228,6 +228,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
228
228
|
.mtx th:first-child, .mtx td:first-child { text-align: left; }
|
|
229
229
|
.mtx input[type=number] { width: 52px; padding: 2px 4px; border: 1px solid var(--line); border-radius: 5px; background: var(--panel); }
|
|
230
230
|
.kpi.wide { grid-column: span 2; cursor: pointer; }
|
|
231
|
+
.kpi.try { cursor: default; } .kpi.try .tries { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; }
|
|
232
|
+
.kpi.try .tryb, .kpi.try .tryt { font: 12px var(--font-ui); padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); background: var(--bg); color: inherit; white-space: nowrap; max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
|
233
|
+
.kpi.try .tryb { cursor: pointer; } .kpi.try .tryb:hover { border-color: currentColor; }
|
|
231
234
|
.kpi.wide .v { font-size: 13.5px; font-family: var(--font-ui); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
232
235
|
.legendHud { position: absolute; left: 10px; bottom: 8px; display: flex; gap: 10px; font-size: 11px; color: var(--muted); background: color-mix(in srgb, var(--panel) 80%, transparent); padding: 3px 8px; border-radius: 6px; }
|
|
233
236
|
.legendHud i { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 4px; vertical-align: 0; }
|
|
@@ -394,6 +397,9 @@ button, select, input { font: inherit; color: inherit; }
|
|
|
394
397
|
/*SIZERMODEL*/
|
|
395
398
|
</script>
|
|
396
399
|
<script>
|
|
400
|
+
/*SIZERSUGGEST*/
|
|
401
|
+
</script>
|
|
402
|
+
<script>
|
|
397
403
|
/*ENGINE*/
|
|
398
404
|
</script>
|
|
399
405
|
<script>
|
|
@@ -1684,9 +1690,19 @@ function renderKpis() {
|
|
|
1684
1690
|
t1('Days / 100B tokens', t.daysPer100B.toFixed(1), 'train', t.daysPer100B, bt.daysPer100B, true, v => v.toFixed(1));
|
|
1685
1691
|
t1('Training $ / hour', fUsd(t.costPerHr), 'train', t.costPerHr, bt.costPerHr, true, fUsd);
|
|
1686
1692
|
}
|
|
1693
|
+
// what to try next: one-click what-ifs for the Ask box, from the first bottleneck and the cache (SizerSuggest.forFleet)
|
|
1694
|
+
if (s.requests && window.SizerSuggest) {
|
|
1695
|
+
const tries = SizerSuggest.forFleet(s);
|
|
1696
|
+
if (tries.length) tiles.push('<div class="kpi wide try"><div class="k">What to try</div><div class="tries">' + tries.map(x => x.ask
|
|
1697
|
+
? '<button type="button" class="tryb" data-ask="' + esc(x.ask) + '" title="' + esc(x.title) + ': ' + esc(x.why) + ' \u2014 runs: ' + esc(x.ask) + '">' + esc(x.title) + '</button>'
|
|
1698
|
+
: '<span class="tryt" title="' + esc(x.why) + '">' + esc(x.title) + '</span>').join('') + '</div></div>');
|
|
1699
|
+
}
|
|
1687
1700
|
$('#kpis').innerHTML = tiles.join('');
|
|
1688
1701
|
}
|
|
1689
|
-
$('#kpis').addEventListener('click', e => {
|
|
1702
|
+
$('#kpis').addEventListener('click', e => {
|
|
1703
|
+
const a = e.target.closest('[data-ask]'); if (a) { $('#askBox').value = a.dataset.ask; $('#askForm').requestSubmit(); return; }
|
|
1704
|
+
const k = e.target.closest('[data-seek]'); if (k) seek(+k.dataset.seek);
|
|
1705
|
+
});
|
|
1690
1706
|
|
|
1691
1707
|
// ---------- charts ----------
|
|
1692
1708
|
const CH = { w: 420, h: 150, l: 38, r: 8, t: 8, b: 18 };
|
package/gpu-health/package.json
CHANGED
package/gpu-ledger/package.json
CHANGED
package/harness-ledger/README.md
CHANGED
|
@@ -120,6 +120,54 @@ On TraceLab's workload, with SWE-bench success rates ([VALIDATION-ECONOMICS.md](
|
|
|
120
120
|
- **Pooled teams:** at $3 a GPU-hour on B200 it wins from about 8–16× that volume.
|
|
121
121
|
- **Context:** half the calls exceed those models' 128k context.
|
|
122
122
|
|
|
123
|
+
## Assess, doctor, optimize
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
harness-ledger assess traces/ [--requests gateway.jsonl] [--engine-metrics http://vllm:8000] # all three below, one report
|
|
127
|
+
harness-ledger profile traces/ --critical 'harness:payments-*' # classes, token ratios, what bounds each
|
|
128
|
+
harness-ledger doctor traces/ --requests gateway.jsonl # why the prefix cache misses, and what to change
|
|
129
|
+
harness-ledger advise traces/ --goal ttft [--model deepseek-v3 --gpu H200 --gpus 64] [--apply IDS] [--fail-if 'ttft>+5%']
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- **The profile** puts each session in one of five classes: critical, realtime, agentic, reasoning or batch. For each
|
|
133
|
+
class it reports input:output tokens, the share read from cache, fresh tokens per output token, context and output
|
|
134
|
+
percentiles and pauses past the cache lifetime, and from those, whether prefill, decode or the KV cache bounds it.
|
|
135
|
+
- **The doctor** compares the hit rate now with what the same calls could reach. With request bodies, it names the
|
|
136
|
+
first point where each request stops matching the previous one and why (a timestamp in the system prompt, reordered
|
|
137
|
+
tools, JSON key order and so on), keeping only hashes and positions. With the engine's metrics, it gives the
|
|
138
|
+
server-side hit rate against what the traces could reuse.
|
|
139
|
+
- **The optimizer** prices every change across the stack that moves the goal. On an API, each change is measured on
|
|
140
|
+
the recorded calls changed as the change would change them. Self-hosted, it also uses the Inference Sizer's operating
|
|
141
|
+
point. It gives the best combination, the best at no extra cost and the best with no quality risk, then a dry run of
|
|
142
|
+
the ones you pick.
|
|
143
|
+
|
|
144
|
+
See [docs/OPTIMIZE.md](../docs/OPTIMIZE.md).
|
|
145
|
+
|
|
146
|
+
## Suggestions, prompt lint, and where they show up
|
|
147
|
+
|
|
148
|
+
```
|
|
149
|
+
harness-ledger suggest traces/ [--watch 3600 --since 24h] [--store DIR] [--slack URL|--lark URL] [--langfuse] [--live]
|
|
150
|
+
harness-ledger suggest list | accept ID | dismiss ID | snooze ID --for 2w | reopen ID
|
|
151
|
+
harness-ledger lint prompts/ [--md] [--fail] # a per-call value before static text, in a template
|
|
152
|
+
harness-ledger mooncake trace.jsonl --sim-replicas 8 # prefix reuse by cache size; random vs prefix routing
|
|
153
|
+
harness-ledger mooncake --requests gateway.jsonl --out trace.jsonl # your traffic as a Mooncake trace, no text
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`suggest` raises each change once, again only if it grows by half, and remembers what people decided. It also feeds:
|
|
157
|
+
|
|
158
|
+
- the Claude Code hook and status line (`integrations/claude-code/`);
|
|
159
|
+
- the LiteLLM prefix linter (`integrations/litellm/`);
|
|
160
|
+
- the Grafana panel, through a fleetops store;
|
|
161
|
+
- Slack and Lark/Feishu cards;
|
|
162
|
+
- comments on Langfuse sessions.
|
|
163
|
+
|
|
164
|
+
Two more input formats are detected:
|
|
165
|
+
|
|
166
|
+
- **`trajectory`:** agent runs with full message lists, such as SWE-agent or OpenHands datasets exported to JSON lines.
|
|
167
|
+
- **`mooncake`:** serving traces with chained block hashes.
|
|
168
|
+
|
|
169
|
+
See [docs/SUGGEST.md](../docs/SUGGEST.md).
|
|
170
|
+
|
|
123
171
|
## On real data
|
|
124
172
|
|
|
125
173
|
- **Real coding-agent use** ([VALIDATION-TRACELAB.md](docs/VALIDATION-TRACELAB.md)). On TraceLab (8,058 Claude Code
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Integrations
|
|
2
|
+
|
|
3
|
+
Where harness-ledger's findings show up without anyone running a report. See [docs/SUGGEST.md](../../docs/SUGGEST.md).
|
|
4
|
+
|
|
5
|
+
| Folder | What | Set up |
|
|
6
|
+
|---|---|---|
|
|
7
|
+
| [claude-code/](claude-code/) | Hooks that show cache misses and tool-output waste in Claude Code (last session at start, live warnings after a response), and a status line with the live cache hit rate | `aiinfra claude-code-hook --print-settings` → `~/.claude/settings.json` |
|
|
8
|
+
| [litellm/](litellm/) | A LiteLLM proxy callback that reports each request that breaks its session's prompt prefix, and why (Prometheus counters, one log line per template and cause) | `callbacks: aiinfra_prefix_lint.proxy_handler_instance` in the proxy's `litellm_settings` |
|
|
9
|
+
|
|
10
|
+
Both read only what passes through them, keep counts and hashes (no prompt text), and never block or change a session
|
|
11
|
+
or a request.
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A Claude Code hook: tells you, in Claude Code, when a session wasted tokens on the prompt cache or on oversized tool
|
|
3
|
+
// output, at the moment you can still do something about it. It reads only the session's own transcript, on your
|
|
4
|
+
// machine, and keeps counts (no prompt or tool text) in ~/.aiinfra/claude-code/ (or $AIINFRA_STATE/claude-code/).
|
|
5
|
+
//
|
|
6
|
+
// SessionEnd analyzes the finished session and keeps a one-line summary
|
|
7
|
+
// SessionStart shows the previous session's summary once, if it found something worth changing
|
|
8
|
+
// Stop (optional; run it async) after each response, warns once per session per problem as it happens:
|
|
9
|
+
// a cache miss that re-sent a large context, a pause that let the cache expire, a huge tool result
|
|
10
|
+
// The message is a hook systemMessage, shown to you, not added to Claude's context.
|
|
11
|
+
//
|
|
12
|
+
// Settings (~/.claude/settings.json or .claude/settings.json): node aiinfra-hook.mjs --print-settings
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
import { claudeCode } from '../../src/importers.mjs';
|
|
18
|
+
import { ledger } from '../../src/ledger.mjs';
|
|
19
|
+
|
|
20
|
+
const HERE = fileURLToPath(import.meta.url);
|
|
21
|
+
export const THRESHOLDS = { missTokens: 50000, bigResult: 20000, minWasteShare: 0.15, minTokens: 100000 };
|
|
22
|
+
export const stateDir = () => path.join(process.env.AIINFRA_STATE || path.join(os.homedir(), '.aiinfra'), 'claude-code');
|
|
23
|
+
const n = v => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
|
|
24
|
+
|
|
25
|
+
// one transcript (and its subagents' transcripts beside it) → what went to waste
|
|
26
|
+
export function analyze(transcriptPath, { cacheTtlS = 300 } = {}) {
|
|
27
|
+
const files = [transcriptPath], sub = path.join(path.dirname(transcriptPath), path.basename(transcriptPath, '.jsonl'), 'subagents');
|
|
28
|
+
if (fs.existsSync(sub)) for (const f of fs.readdirSync(sub)) if (f.endsWith('.jsonl')) files.push(path.join(sub, f));
|
|
29
|
+
const calls = files.flatMap(f => { try { return claudeCode(fs.readFileSync(f, 'utf8'), { file: f }); } catch { return []; } });
|
|
30
|
+
if (!calls.length) return null;
|
|
31
|
+
const r = ledger(calls, { cacheTtlS }), T = r.report.totals;
|
|
32
|
+
const by = c => r.findings.filter(f => f.cause === c);
|
|
33
|
+
const sum = (xs, k) => xs.reduce((a, x) => a + (x[k] || 0), 0);
|
|
34
|
+
const miss = by('cache-miss'), exp = by('cache-expired'), bloat = by('tool-output-bloat');
|
|
35
|
+
const tools = {}; for (const f of bloat) tools[f.tool] = (tools[f.tool] || 0) + f.tokens;
|
|
36
|
+
return { session: calls[0].session, calls: calls.length, input: T.input, cacheRead: T.cacheRead, hit: T.input ? T.cacheRead / T.input : null, cost: T.cost,
|
|
37
|
+
missed: { count: miss.length, tokens: sum(miss, 'tokens'), cost: sum(miss, 'cost') }, expired: { count: exp.length, tokens: sum(exp, 'tokens'), cost: sum(exp, 'cost') },
|
|
38
|
+
bloat: { count: bloat.length, tokens: sum(bloat, 'tokens'), cost: sum(bloat, 'cost'), tools }, avoidable: T.avoidableTokens || 0, avoidableCost: T.avoidableCost || 0,
|
|
39
|
+
lastCallT: calls.reduce((a, c) => Math.max(a, c.t || 0), 0), findings: r.findings.map(f => ({ cause: f.cause, at: f.at, tokens: f.tokens, tool: f.tool })) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// the summary worth showing, or null when the session was fine
|
|
43
|
+
export function message(A, { thresholds = THRESHOLDS, prefix = 'aiinfra', transcript = null } = {}) {
|
|
44
|
+
if (!A || A.input < thresholds.minTokens) return null;
|
|
45
|
+
const parts = [];
|
|
46
|
+
if (A.missed.tokens >= thresholds.missTokens) parts.push(`${n(A.missed.tokens)} tokens re-sent after ${A.missed.count} cache miss${A.missed.count === 1 ? '' : 'es'} (the prompt prefix changed)`);
|
|
47
|
+
if (A.expired.tokens >= thresholds.missTokens) parts.push(`${n(A.expired.tokens)} re-sent after ${A.expired.count} pause${A.expired.count === 1 ? '' : 's'} past the cache lifetime`);
|
|
48
|
+
const top = Object.entries(A.bloat.tools).sort((a, b) => b[1] - a[1])[0];
|
|
49
|
+
if (top && A.bloat.tokens >= thresholds.bigResult) parts.push(`${n(A.bloat.tokens)} from oversized tool output (mostly ${top[0]})`);
|
|
50
|
+
if (!parts.length || A.avoidable / A.input < thresholds.minWasteShare && A.missed.tokens < thresholds.missTokens * 4) return null;
|
|
51
|
+
return `${prefix}: ${Math.round(100 * (A.hit ?? 0))}% of input came from cache; ${parts.join('; ')}.` + (A.avoidableCost ? ` About $${A.avoidableCost.toFixed(2)} avoidable.` : '') + ` Details: aiinfra harness-ledger doctor ${transcript ? JSON.stringify(transcript) : '<transcript>'}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Stop: problems that appeared since the last check of this session, each kind raised once per session
|
|
55
|
+
export function live(A, seen, { thresholds = THRESHOLDS } = {}) {
|
|
56
|
+
const out = [];
|
|
57
|
+
const add = (key, text) => { if (!seen.includes(key)) { seen.push(key); out.push(text); } };
|
|
58
|
+
const big = A.findings.filter(f => (f.cause === 'cache-miss' || f.cause === 'cache-expired') && f.tokens >= thresholds.missTokens);
|
|
59
|
+
if (big.some(f => f.cause === 'cache-miss')) add('miss', `a cache miss re-sent ${n(Math.max(...big.filter(f => f.cause === 'cache-miss').map(f => f.tokens)))} tokens: something early in the prompt changed (a file re-read into the system prompt, tools changing, a /model switch)`);
|
|
60
|
+
if (big.some(f => f.cause === 'cache-expired')) add('expired', 'a pause past the cache lifetime made the next turn re-read the whole context: after a long pause, /compact first (the cache is gone anyway, so the summary is the cheapest thing to re-read)');
|
|
61
|
+
const huge = A.findings.filter(f => f.cause === 'tool-output-bloat' && f.tokens >= thresholds.bigResult);
|
|
62
|
+
if (huge.length) add(`bloat:${huge[0].tool}`, `${huge[0].tool} returned more than ${n(thresholds.bigResult)} tokens, which every later turn re-sends: narrow it (a line range, a head, a grep)`);
|
|
63
|
+
return out.length ? `aiinfra: ${out.join('; ')}.` : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const readJson = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } };
|
|
67
|
+
const writeJson = (f, v) => { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify(v, null, 1) + '\n'); };
|
|
68
|
+
|
|
69
|
+
export function handle(input, { dir = stateDir(), thresholds = THRESHOLDS } = {}) {
|
|
70
|
+
const ev = input.hook_event_name, tp = input.transcript_path && input.transcript_path.replace(/^~(?=\/)/, os.homedir());
|
|
71
|
+
if (ev === 'SessionEnd') {
|
|
72
|
+
if (!tp || !fs.existsSync(tp)) return null;
|
|
73
|
+
const A = analyze(tp); if (!A) return null;
|
|
74
|
+
const msg = message(A, { thresholds, transcript: tp });
|
|
75
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
76
|
+
fs.appendFileSync(path.join(dir, 'sessions.jsonl'), JSON.stringify({ t: Math.floor(Date.now() / 1000), session: input.session_id || A.session, cwd: input.cwd || null, calls: A.calls, input: A.input, hit: A.hit, missed: A.missed.tokens, expired: A.expired.tokens, bloat: A.bloat.tokens, avoidable: A.avoidable, avoidableCost: A.avoidableCost }) + '\n');
|
|
77
|
+
writeJson(path.join(dir, 'last.json'), { session: input.session_id || A.session, message: msg, shown: false, t: Math.floor(Date.now() / 1000) });
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
if (ev === 'SessionStart') {
|
|
81
|
+
const f = path.join(dir, 'last.json'), last = readJson(f);
|
|
82
|
+
if (!last || last.shown || !last.message || last.session === input.session_id) return null;
|
|
83
|
+
last.shown = true; writeJson(f, last);
|
|
84
|
+
return { systemMessage: `${last.message.replace(/^aiinfra:/, 'aiinfra (last session):')}` };
|
|
85
|
+
}
|
|
86
|
+
if (ev === 'Stop' || ev === 'SubagentStop') {
|
|
87
|
+
if (!tp || !fs.existsSync(tp)) return null;
|
|
88
|
+
const A = analyze(tp); if (!A) return null;
|
|
89
|
+
const f = path.join(dir, 'live', `${String(input.session_id || A.session).replace(/[^\w.-]/g, '_')}.json`), st = readJson(f) || { seen: [] };
|
|
90
|
+
const msg = live(A, st.seen, { thresholds }); writeJson(f, st);
|
|
91
|
+
return msg ? { systemMessage: msg } : null;
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function settingsSnippet(script = HERE) {
|
|
97
|
+
const cmd = `node "${script}"`;
|
|
98
|
+
return { hooks: {
|
|
99
|
+
SessionEnd: [{ hooks: [{ type: 'command', command: cmd, timeout: 10 }] }],
|
|
100
|
+
SessionStart: [{ hooks: [{ type: 'command', command: cmd, timeout: 10 }] }],
|
|
101
|
+
Stop: [{ hooks: [{ type: 'command', command: cmd, async: true, timeout: 30 }] }],
|
|
102
|
+
}, statusLine: { type: 'command', command: `node "${path.join(path.dirname(script), 'aiinfra-statusline.mjs')}"` } };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === HERE) {
|
|
106
|
+
if (process.argv.includes('--print-settings')) { process.stdout.write(JSON.stringify(settingsSnippet(), null, 2) + '\n'); process.exit(0); }
|
|
107
|
+
let raw = ''; process.stdin.setEncoding('utf8');
|
|
108
|
+
process.stdin.on('data', c => { raw += c; if (raw.length > 1 << 20) process.stdin.destroy(); });
|
|
109
|
+
process.stdin.on('end', () => {
|
|
110
|
+
// a hook must never get in the way of the session: any failure is silent (exit 0, nothing printed)
|
|
111
|
+
try { const out = handle(JSON.parse(raw || '{}')); if (out) process.stdout.write(JSON.stringify(out) + '\n'); } catch (e) { if (process.env.AIINFRA_DEBUG) process.stderr.write(`aiinfra-hook: ${e.message}\n`); }
|
|
112
|
+
});
|
|
113
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// A Claude Code status line: the session's prompt-cache hit rate and what went to waste so far, always in view.
|
|
3
|
+
// cache 84% · re-sent 1.2M · ~$0.80 avoidable
|
|
4
|
+
// Claude Code runs it with the session as JSON on stdin (transcript_path among it); the result is cached by the
|
|
5
|
+
// transcript's size so a refresh doesn't re-read an unchanged session. Settings: aiinfra-hook.mjs --print-settings
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { analyze, stateDir } from './aiinfra-hook.mjs';
|
|
11
|
+
|
|
12
|
+
const n = v => (v >= 1e6 ? `${(v / 1e6).toFixed(1)}M` : v >= 1e3 ? `${Math.round(v / 1e3)}k` : String(Math.round(v)));
|
|
13
|
+
export function line(A) {
|
|
14
|
+
if (!A) return 'cache –';
|
|
15
|
+
const resent = A.missed.tokens + A.expired.tokens, parts = [`cache ${A.hit == null ? '–' : Math.round(100 * A.hit) + '%'}`];
|
|
16
|
+
if (resent >= 1000) parts.push(`re-sent ${n(resent)}`);
|
|
17
|
+
if (A.bloat.tokens >= 1000) parts.push(`tool output +${n(A.bloat.tokens)}`);
|
|
18
|
+
if (A.avoidableCost >= 0.01) parts.push(`~$${A.avoidableCost.toFixed(2)} avoidable`);
|
|
19
|
+
return parts.join(' · ');
|
|
20
|
+
}
|
|
21
|
+
export function statusFor(input, { dir = stateDir() } = {}) {
|
|
22
|
+
const tp = input.transcript_path && input.transcript_path.replace(/^~(?=\/)/, os.homedir());
|
|
23
|
+
if (!tp || !fs.existsSync(tp)) return 'cache –';
|
|
24
|
+
const size = fs.statSync(tp).size, f = path.join(dir, 'statusline', `${path.basename(tp)}.json`);
|
|
25
|
+
try { const c = JSON.parse(fs.readFileSync(f, 'utf8')); if (c.size === size) return c.line; } catch { /* first look */ }
|
|
26
|
+
const out = line(analyze(tp));
|
|
27
|
+
try { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, JSON.stringify({ size, line: out })); } catch { /* read-only home: still print */ }
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
32
|
+
let raw = ''; process.stdin.setEncoding('utf8');
|
|
33
|
+
process.stdin.on('data', c => { raw += c; });
|
|
34
|
+
process.stdin.on('end', () => { try { process.stdout.write(statusFor(JSON.parse(raw || '{}')) + '\n'); } catch { process.stdout.write('cache –\n'); } });
|
|
35
|
+
}
|