parse-bench-readme.mjs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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, SUFFICIENCY } 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, cliCalls: s.cliCalls, cliContaminated: s.cliContaminated,
  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. // The other two feedback metrics, carried per run so the campaign can pool
  56. // them. Both are with-arm-only in practice — a without-arm makes no explore
  57. // calls, so it has nothing to be sufficient about and no bytes to allocate.
  58. suffAnswered: s.sufficiency.answered,
  59. suffCounts: s.sufficiency.counts,
  60. // Byte-weighted, so a run with no explore contributes NOTHING rather than a
  61. // zero; a zero would drag a repo toward "wasteful" for never spending a byte.
  62. allocUsed: s.allocation.envelope ? s.allocation.used : 0,
  63. allocEnvelope: s.allocation.envelope,
  64. allocCalls: s.allocation.calls.length,
  65. };
  66. }
  67. 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; };
  68. const fmtTime = (s) => s >= 60 ? `${Math.floor(s / 60)}m ${Math.round(s % 60)}s` : `${Math.round(s)}s`;
  69. const fmtTok = (t) => t >= 1e6 ? `${(t / 1e6).toFixed(1)}M` : `${Math.round(t / 1000)}k`;
  70. const pct = (w, wo) => wo > 0 ? Math.round((1 - w / wo) * 100) : 0;
  71. // Exclude MCP-cold-start-raced WITH runs by default — they measure a startup
  72. // race, not steady-state value. `CG_INCLUDE_RACED=1` keeps them (to see the raw
  73. // distribution). The WITHOUT arm has no MCP, so it's never raced.
  74. const includeRaced = process.env.CG_INCLUDE_RACED === '1';
  75. // A without-arm run that shelled out to the codegraph CLI measured
  76. // codegraph-over-CLI, not codegraph-absent. Drop it unless asked otherwise.
  77. const includeContaminated = process.env.CG_INCLUDE_CONTAMINATED === '1';
  78. const rows = [];
  79. let contaminated = 0;
  80. for (const repo of REPOS) {
  81. const dir = join(ROOT, repo);
  82. const runDirs = existsSync(dir) ? readdirSync(dir).filter(d => /^run\d+$/.test(d)).sort() : [];
  83. const W = [], WO = []; let racedExcluded = 0;
  84. for (const rd of runDirs) {
  85. const w = parse(join(dir, rd), 'headless-with');
  86. if (w) { if (w.raced && !includeRaced) racedExcluded++; else W.push(w); }
  87. const wo = parse(join(dir, rd), 'headless-without');
  88. if (wo) {
  89. if (wo.cliContaminated && !includeContaminated) { contaminated++; console.error(`[excluded] ${repo}/${rd} without-arm got codegraph CLI output ${wo.cliContaminated}x`); }
  90. else WO.push(wo);
  91. }
  92. }
  93. rows.push({ repo, W, WO, racedExcluded });
  94. }
  95. if (contaminated) console.error(`[excluded] ${contaminated} contaminated without-arm run(s); CG_INCLUDE_CONTAMINATED=1 keeps them\n`);
  96. // ---- Table 1: the existing throughput view. --------------------------------
  97. console.log('repo n(w/wo) time WITH→WITHOUT tools W→WO tokens W→WO (saved) cost W→WO (saved)');
  98. const savings = { cost: [], tokens: [], time: [], tools: [] };
  99. for (const { repo, W, WO, racedExcluded } of rows) {
  100. if (!W.length || !WO.length) { console.log(`${repo.padEnd(11)} (incomplete: w=${W.length} wo=${WO.length})`); continue; }
  101. const m = (arr, k) => median(arr.map(x => x[k]));
  102. const wT = m(W, 'dur'), woT = m(WO, 'dur'), wTok = m(W, 'tokens'), woTok = m(WO, 'tokens');
  103. const wC = m(W, 'cost'), woC = m(WO, 'cost'), wTl = m(W, 'tools'), woTl = m(WO, 'tools');
  104. savings.time.push(pct(wT, woT)); savings.tokens.push(pct(wTok, woTok)); savings.cost.push(pct(wC, woC)); savings.tools.push(pct(wTl, woTl));
  105. console.log(
  106. `${repo.padEnd(11)} ${W.length}/${WO.length} ` +
  107. `${(fmtTime(wT) + '→' + fmtTime(woT)).padEnd(22)}` +
  108. `${(Math.round(wTl) + '→' + Math.round(woTl)).padEnd(12)}` +
  109. `${(fmtTok(wTok) + '→' + fmtTok(woTok) + ' (' + pct(wTok, woTok) + '%)').padEnd(24)}` +
  110. `$${wC.toFixed(2)}→$${woC.toFixed(2)} (${pct(wC, woC)}%)` +
  111. (racedExcluded ? ` [${racedExcluded} raced run${racedExcluded === 1 ? '' : 's'} excluded]` : '')
  112. );
  113. }
  114. const avg = (a) => a.length ? Math.round(a.reduce((s, x) => s + x, 0) / a.length) : 0;
  115. console.log(`\nAVERAGE saved: cost ${avg(savings.cost)}% · tokens ${avg(savings.tokens)}% · time ${avg(savings.time)}% · tool calls ${avg(savings.tools)}%`);
  116. // ---- Table 2: residual context occupancy. ----------------------------------
  117. // WITH's retrieval residual is codegraph's tool output; WITHOUT's is Read +
  118. // Grep/Glob + Bash. Same question, same window — so the pair is comparable.
  119. const anyMulti = rows.some(({ W, WO }) => [...W, ...WO].some(r => r.segments > 1));
  120. console.log(`\n\nRESIDUAL CONTEXT OCCUPANCY — retrieval tokens still in the window at end of run`);
  121. console.log(`(WITH = codegraph responses · WITHOUT = Read + Grep/Glob + Bash responses)`);
  122. console.log(`${anyMulti ? 'multi-turn sessions' : 'SINGLE-TURN sessions — see the caveat below'}\n`);
  123. console.log('repo turns final ctx W→WO residual W→WO % of ctx W→WO % of window W→WO');
  124. const occ = { resid: [], shareCtx: [], fixed: [] };
  125. for (const { repo, W, WO } of rows) {
  126. if (!W.length || !WO.length) { console.log(`${repo.padEnd(11)} (incomplete)`); continue; }
  127. const m = (arr, k) => median(arr.map(x => x[k]));
  128. occ.fixed.push(m(W, 'ctxBase') - m(WO, 'ctxBase'));
  129. const wR = m(W, 'occSelf'), woR = m(WO, 'occSelf');
  130. const wCtx = m(W, 'ctx'), woCtx = m(WO, 'ctx');
  131. const wSc = m(W, 'occShareCtx'), woSc = m(WO, 'occShareCtx');
  132. const wSw = m(W, 'occShareWin'), woSw = m(WO, 'occShareWin');
  133. occ.resid.push(pct(wR, woR)); occ.shareCtx.push(pct(wSc, woSc));
  134. console.log(
  135. `${repo.padEnd(11)} ${String(median(W.map(x => x.turns)) + '/' + median(WO.map(x => x.turns))).padEnd(7)} ` +
  136. `${(fmtTok(wCtx) + '→' + fmtTok(woCtx)).padEnd(21)}` +
  137. `${(fmtTok(wR) + '→' + fmtTok(woR) + ' (' + pct(wR, woR) + '%)').padEnd(22)}` +
  138. `${(wSc.toFixed(1) + '%→' + woSc.toFixed(1) + '%').padEnd(18)}` +
  139. `${wSw.toFixed(1)}%→${woSw.toFixed(1)}%`
  140. );
  141. }
  142. // Direction must follow the SIGN, not the hope. `pct(w, wo)` is the reduction
  143. // going with→without, so a NEGATIVE value means the with-arm's residual is
  144. // LARGER. Hardcoding "lower" printed "-82% lower with codegraph" for the case
  145. // where codegraph in fact occupies 82% MORE — a double negative that reads as a
  146. // win and inverts the headline. Say which way it went, in words.
  147. const dir = (v) => (v < 0 ? 'HIGHER' : 'lower');
  148. const magn = (v) => Math.abs(v);
  149. console.log(
  150. `\nAVERAGE: retrieval residual ${magn(avg(occ.resid))}% ${dir(avg(occ.resid))} with codegraph` +
  151. ` · share-of-context ${magn(avg(occ.shareCtx))}% ${dir(avg(occ.shareCtx))}`
  152. );
  153. if (avg(occ.resid) < 0) {
  154. console.log(
  155. ` ^ codegraph front-loads one large verbatim payload that STAYS resident, where Read/Grep\n` +
  156. ` churn many small results that evict. Read alongside the cost/token table above: fewer\n` +
  157. ` total tokens processed can coexist with a larger persistent footprint. This is the axis\n` +
  158. ` issue #1500 reported.`
  159. );
  160. }
  161. console.log(
  162. `FIXED overhead: codegraph's tool schema + MCP instructions cost ${avg(occ.fixed) >= 0 ? '+' : ''}${avg(occ.fixed)} tok\n` +
  163. ` of context before any tool is called (median WITH ctxBase - median WITHOUT ctxBase, averaged\n` +
  164. ` over repos). It is paid whether or not the agent ever calls codegraph.`
  165. );
  166. // Per-run detail. Medians over 2-3 runs hide swings big enough to flip a repo's
  167. // sign — the agent's tool mix is the variable, and a with-arm run that reads
  168. // files ON TOP of calling explore pays for both. Show every run.
  169. console.log('\nper run (retrieval residual · tool mix — cg=explore rd=Read gr=Grep bs=Bash):');
  170. for (const { repo, W, WO } of rows) {
  171. if (!W.length && !WO.length) continue;
  172. 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}` : ''}`;
  173. console.log(` ${repo.padEnd(11)} W: ${W.map(one).join(' | ').padEnd(46)} WO: ${WO.map(one).join(' | ')}`);
  174. }
  175. if (!anyMulti) {
  176. console.log(
  177. `\nCAVEAT: every row is a SINGLE-turn session, so the residual is measured at the\n` +
  178. `moment the one question is answered. Occupancy is a cost that compounds over the turns\n` +
  179. `that FOLLOW; a single-turn number does not settle it. Re-run with "||"-separated\n` +
  180. `follow-ups (see run-all.sh) to measure the regime this metric is actually about.`
  181. );
  182. }
  183. // ---- Table 3: sufficiency + allocation, WITH arm only. ---------------------
  184. // Occupancy says what a response COST; these two say whether it was enough and
  185. // whether it spent its bytes on the right files. A campaign that reports only
  186. // occupancy cannot tell a tighter response from a worse one.
  187. //
  188. // Pooled per repo, not median-of-runs: both are per-CALL quantities (sufficiency
  189. // counts explores, allocation weights by bytes), and a repo contributes 2-15
  190. // calls across its runs. Median-of-run-percentages would weight a 1-call run the
  191. // same as a 5-call one.
  192. console.log(`\n\nEXPLORE SUFFICIENCY + ALLOCATION EFFICIENCY — with-arm only, pooled over runs`);
  193. console.log(`(sufficiency = what the agent did NEXT · allocation = share of returned bytes the answer cited)\n`);
  194. console.log('repo calls again read-ret read-miss grep MOVED ON alloc eff envelope');
  195. const totals = { answered: 0, counts: Object.fromEntries(SUFFICIENCY.map(([k]) => [k, 0])), used: 0, env: 0, calls: 0 };
  196. for (const { repo, W } of rows) {
  197. if (!W.length) { console.log(`${repo.padEnd(11)} (no with-arm runs)`); continue; }
  198. const answered = W.reduce((s, r) => s + r.suffAnswered, 0);
  199. const cnt = (k) => W.reduce((s, r) => s + r.suffCounts[k], 0);
  200. const env = W.reduce((s, r) => s + r.allocEnvelope, 0);
  201. const used = W.reduce((s, r) => s + r.allocUsed, 0);
  202. totals.answered += answered; totals.used += used; totals.env += env;
  203. totals.calls += W.reduce((s, r) => s + r.allocCalls, 0);
  204. for (const [k] of SUFFICIENCY) totals.counts[k] += cnt(k);
  205. const cell = (k) => (answered ? `${cnt(k)} ${Math.round((cnt(k) / answered) * 100)}%` : '—').padEnd(9);
  206. console.log(
  207. `${repo.padEnd(11)} ${String(answered).padEnd(7)} ` +
  208. `${cell('explore_again')}${cell('read_returned')}${cell('read_missed')}${cell('search')}` +
  209. `${(answered ? `${cnt('sufficient')} ${Math.round((cnt('sufficient') / answered) * 100)}%` : '—').padEnd(13)}` +
  210. `${(env ? `${((used / env) * 100).toFixed(1)}%` : '—').padEnd(12)}${fmtTok(env)}`
  211. );
  212. }
  213. const tp = (k) => totals.answered ? `${totals.counts[k]} (${Math.round((totals.counts[k] / totals.answered) * 100)}%)` : '—';
  214. console.log(
  215. `\nPOOLED (${totals.answered} answered explore calls): ` +
  216. SUFFICIENCY.map(([k, label]) => `${label} ${tp(k)}`).join(' · ')
  217. );
  218. console.log(
  219. `POOLED allocation efficiency: ${totals.env ? ((totals.used / totals.env) * 100).toFixed(1) + '%' : '—'} ` +
  220. `over ${totals.calls} calls / ${fmtTok(totals.env)} chars`
  221. );
  222. console.log(
  223. `\nHOW TO READ: "read-ret" (Read a file we RETURNED) is an allocation miss — right file,\n` +
  224. `wrong bytes; "read-miss" and "grep" are recall misses. "again" is ambiguous by construction.\n` +
  225. `Allocation efficiency is RELATIVE — attribution is by citation, so it compares BUILDS on the\n` +
  226. `same questions and is not a claim that codegraph wasted the remainder. Full guidance:\n` +
  227. `docs/benchmarks/agent-eval-feedback-metrics.md`
  228. );