1
0

parse-bench-readme.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env node
  2. // Aggregate the README A/B (bench-readme.sh output): per repo, median of N runs
  3. // per arm → time, tool calls, tokens, cost, % saved, and RESIDUAL CONTEXT
  4. // OCCUPANCY. Plus an average row.
  5. //
  6. // Tokens = SUM of per-turn assistant `usage` (input + output + cache read +
  7. // cache creation) — the cumulative "total tokens processed". NOTE: `result.usage`
  8. // is last-turn-only in some Claude Code versions, so reading it alone can
  9. // under-count badly; parseSession() sums per-segment and dedupes assistant
  10. // events by message.id (Claude Code emits one event per content block, each
  11. // carrying the same usage — summing per EVENT double-counts).
  12. //
  13. // The occupancy table answers the question "tokens processed" cannot: how much
  14. // of the window each arm's tool output STILL OCCUPIES when the run ends. Under
  15. // multi-turn rows that residual is charged against every following turn.
  16. //
  17. // Usage: node parse-bench-readme.mjs [/tmp/ab-readme]
  18. import { existsSync, readdirSync } from 'fs';
  19. import { join } from 'path';
  20. import { parseSession } from './parse-run.mjs';
  21. const ROOT = process.argv[2] || '/tmp/ab-readme';
  22. const REPOS = ['vscode', 'excalidraw', 'django', 'tokio', 'okhttp', 'gin', 'alamofire'];
  23. /** All segment files of one arm's session, in turn order (t1, t2, t3, …). */
  24. function segments(dir, label) {
  25. const first = join(dir, `run-${label}.jsonl`);
  26. if (!existsSync(first)) return null;
  27. const rest = readdirSync(dir)
  28. .map((f) => [f, new RegExp(`^run-${label}\\.t(\\d+)\\.jsonl$`).exec(f)])
  29. .filter(([, m]) => m)
  30. .sort((a, b) => Number(a[1][1]) - Number(b[1][1]))
  31. .map(([f]) => join(dir, f));
  32. return [first, ...rest];
  33. }
  34. function parse(dir, label) {
  35. const files = segments(dir, label);
  36. if (!files) return null;
  37. const s = parseSession(files);
  38. if (!s.ok) return null;
  39. const o = s.occupancy;
  40. return {
  41. dur: s.dur, tools: s.tools, reads: s.reads, grep: s.grep, cg: s.cg,
  42. bash: s.counts.Bash || 0,
  43. tokens: s.processed, cost: s.cost, raced: s.raced, turns: s.turns,
  44. segments: files.length,
  45. ctx: o.ctxFinal,
  46. ctxBase: o.ctxBase,
  47. occCg: o.residual.codegraph,
  48. occFile: o.residualFileAccess,
  49. // The arm's own retrieval residual: codegraph in the with-arm, Read/Grep/Bash
  50. // in the without-arm. Comparing these is the apples-to-apples pair.
  51. occSelf: o.residual.codegraph + o.residualFileAccess,
  52. occShareCtx: o.ctxFinal > 0 ? ((o.residual.codegraph + o.residualFileAccess) / o.ctxFinal) * 100 : 0,
  53. occShareWin: ((o.residual.codegraph + o.residualFileAccess) / o.windowTokens) * 100,
  54. window: o.windowTokens,
  55. };
  56. }
  57. const median = (arr) => { const v = [...arr].sort((a, b) => a - b); const n = v.length; return n === 0 ? 0 : n % 2 ? v[(n - 1) / 2] : (v[n / 2 - 1] + v[n / 2]) / 2; };
  58. const fmtTime = (s) => s >= 60 ? `${Math.floor(s / 60)}m ${Math.round(s % 60)}s` : `${Math.round(s)}s`;
  59. const fmtTok = (t) => t >= 1e6 ? `${(t / 1e6).toFixed(1)}M` : `${Math.round(t / 1000)}k`;
  60. const pct = (w, wo) => wo > 0 ? Math.round((1 - w / wo) * 100) : 0;
  61. // Exclude MCP-cold-start-raced WITH runs by default — they measure a startup
  62. // race, not steady-state value. `CG_INCLUDE_RACED=1` keeps them (to see the raw
  63. // distribution). The WITHOUT arm has no MCP, so it's never raced.
  64. const includeRaced = process.env.CG_INCLUDE_RACED === '1';
  65. const rows = [];
  66. for (const repo of REPOS) {
  67. const dir = join(ROOT, repo);
  68. const runDirs = existsSync(dir) ? readdirSync(dir).filter(d => /^run\d+$/.test(d)).sort() : [];
  69. const W = [], WO = []; let racedExcluded = 0;
  70. for (const rd of runDirs) {
  71. const w = parse(join(dir, rd), 'headless-with');
  72. if (w) { if (w.raced && !includeRaced) racedExcluded++; else W.push(w); }
  73. const wo = parse(join(dir, rd), 'headless-without'); if (wo) WO.push(wo);
  74. }
  75. rows.push({ repo, W, WO, racedExcluded });
  76. }
  77. // ---- Table 1: the existing throughput view. --------------------------------
  78. console.log('repo n(w/wo) time WITH→WITHOUT tools W→WO tokens W→WO (saved) cost W→WO (saved)');
  79. const savings = { cost: [], tokens: [], time: [], tools: [] };
  80. for (const { repo, W, WO, racedExcluded } of rows) {
  81. if (!W.length || !WO.length) { console.log(`${repo.padEnd(11)} (incomplete: w=${W.length} wo=${WO.length})`); continue; }
  82. const m = (arr, k) => median(arr.map(x => x[k]));
  83. const wT = m(W, 'dur'), woT = m(WO, 'dur'), wTok = m(W, 'tokens'), woTok = m(WO, 'tokens');
  84. const wC = m(W, 'cost'), woC = m(WO, 'cost'), wTl = m(W, 'tools'), woTl = m(WO, 'tools');
  85. savings.time.push(pct(wT, woT)); savings.tokens.push(pct(wTok, woTok)); savings.cost.push(pct(wC, woC)); savings.tools.push(pct(wTl, woTl));
  86. console.log(
  87. `${repo.padEnd(11)} ${W.length}/${WO.length} ` +
  88. `${(fmtTime(wT) + '→' + fmtTime(woT)).padEnd(22)}` +
  89. `${(Math.round(wTl) + '→' + Math.round(woTl)).padEnd(12)}` +
  90. `${(fmtTok(wTok) + '→' + fmtTok(woTok) + ' (' + pct(wTok, woTok) + '%)').padEnd(24)}` +
  91. `$${wC.toFixed(2)}→$${woC.toFixed(2)} (${pct(wC, woC)}%)` +
  92. (racedExcluded ? ` [${racedExcluded} raced run${racedExcluded === 1 ? '' : 's'} excluded]` : '')
  93. );
  94. }
  95. const avg = (a) => a.length ? Math.round(a.reduce((s, x) => s + x, 0) / a.length) : 0;
  96. console.log(`\nAVERAGE saved: cost ${avg(savings.cost)}% · tokens ${avg(savings.tokens)}% · time ${avg(savings.time)}% · tool calls ${avg(savings.tools)}%`);
  97. // ---- Table 2: residual context occupancy. ----------------------------------
  98. // WITH's retrieval residual is codegraph's tool output; WITHOUT's is Read +
  99. // Grep/Glob + Bash. Same question, same window — so the pair is comparable.
  100. const anyMulti = rows.some(({ W, WO }) => [...W, ...WO].some(r => r.segments > 1));
  101. console.log(`\n\nRESIDUAL CONTEXT OCCUPANCY — retrieval tokens still in the window at end of run`);
  102. console.log(`(WITH = codegraph responses · WITHOUT = Read + Grep/Glob + Bash responses)`);
  103. console.log(`${anyMulti ? 'multi-turn sessions' : 'SINGLE-TURN sessions — see the caveat below'}\n`);
  104. console.log('repo turns final ctx W→WO residual W→WO % of ctx W→WO % of window W→WO');
  105. const occ = { resid: [], shareCtx: [], fixed: [] };
  106. for (const { repo, W, WO } of rows) {
  107. if (!W.length || !WO.length) { console.log(`${repo.padEnd(11)} (incomplete)`); continue; }
  108. const m = (arr, k) => median(arr.map(x => x[k]));
  109. occ.fixed.push(m(W, 'ctxBase') - m(WO, 'ctxBase'));
  110. const wR = m(W, 'occSelf'), woR = m(WO, 'occSelf');
  111. const wCtx = m(W, 'ctx'), woCtx = m(WO, 'ctx');
  112. const wSc = m(W, 'occShareCtx'), woSc = m(WO, 'occShareCtx');
  113. const wSw = m(W, 'occShareWin'), woSw = m(WO, 'occShareWin');
  114. occ.resid.push(pct(wR, woR)); occ.shareCtx.push(pct(wSc, woSc));
  115. console.log(
  116. `${repo.padEnd(11)} ${String(median(W.map(x => x.turns)) + '/' + median(WO.map(x => x.turns))).padEnd(7)} ` +
  117. `${(fmtTok(wCtx) + '→' + fmtTok(woCtx)).padEnd(21)}` +
  118. `${(fmtTok(wR) + '→' + fmtTok(woR) + ' (' + pct(wR, woR) + '%)').padEnd(22)}` +
  119. `${(wSc.toFixed(1) + '%→' + woSc.toFixed(1) + '%').padEnd(18)}` +
  120. `${wSw.toFixed(1)}%→${woSw.toFixed(1)}%`
  121. );
  122. }
  123. console.log(`\nAVERAGE: retrieval residual ${avg(occ.resid)}% lower with codegraph · share-of-context ${avg(occ.shareCtx)}% lower`);
  124. console.log(
  125. `FIXED overhead: codegraph's tool schema + MCP instructions cost ${avg(occ.fixed) >= 0 ? '+' : ''}${avg(occ.fixed)} tok\n` +
  126. ` of context before any tool is called (median WITH ctxBase - median WITHOUT ctxBase, averaged\n` +
  127. ` over repos). It is paid whether or not the agent ever calls codegraph.`
  128. );
  129. // Per-run detail. Medians over 2-3 runs hide swings big enough to flip a repo's
  130. // sign — the agent's tool mix is the variable, and a with-arm run that reads
  131. // files ON TOP of calling explore pays for both. Show every run.
  132. console.log('\nper run (retrieval residual · tool mix — cg=explore rd=Read gr=Grep bs=Bash):');
  133. for (const { repo, W, WO } of rows) {
  134. if (!W.length && !WO.length) continue;
  135. const one = (r) => `${fmtTok(r.occSelf)}${r.cg ? ` cg${r.cg}` : ''}${r.reads ? ` rd${r.reads}` : ''}${r.grep ? ` gr${r.grep}` : ''}${r.bash ? ` bs${r.bash}` : ''}`;
  136. console.log(` ${repo.padEnd(11)} W: ${W.map(one).join(' | ').padEnd(46)} WO: ${WO.map(one).join(' | ')}`);
  137. }
  138. if (!anyMulti) {
  139. console.log(
  140. `\nCAVEAT: every row is a SINGLE-turn session, so the residual is measured at the\n` +
  141. `moment the one question is answered. Occupancy is a cost that compounds over the turns\n` +
  142. `that FOLLOW; a single-turn number does not settle it. Re-run with "||"-separated\n` +
  143. `follow-ups (see run-all.sh) to measure the regime this metric is actually about.`
  144. );
  145. }