Open History to see the last commit
1#!/usr/bin/env bun
2/**
3 * benchmark-analyze.ts — Analysis pipeline for OTP crossover benchmarks.
4 *
5 * Reads benchmark JSON results, pairs Node/Elixir data at each step,
6 * detects crossover points, and outputs:
7 * 1. Markdown report with side-by-side tables
8 * 2. CSV files for charting (one per benchmark)
9 * 3. Crossover summary
10 *
11 * Usage:
12 * bun run scripts/benchmark-analyze.ts
13 * bun run scripts/benchmark-analyze.ts --dir=output/stress-test
14 */
15
16import { readdirSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
17
18const OUTPUT_DIR =
19 process.argv.find((a) => a.startsWith("--dir="))?.split("=")[1] ||
20 `${process.cwd()}/output/stress-test`;
21
22const BENCHMARKS = [
23 "session-ramp",
24 "payload-ramp",
25 "subagent-ramp",
26 "failure-storm",
27 "sustained-leak",
28];
29
30const BENCHMARK_LABELS: Record<string, string> = {
31 "session-ramp": "Session Count Ramp",
32 "payload-ramp": "Payload Size Ramp (Noisy Neighbor)",
33 "subagent-ramp": "Subagent Tree Width Ramp",
34 "failure-storm": "Failure Storm Under Load",
35 "sustained-leak": "Sustained Leak Over Time",
36};
37
38const BENCHMARK_UNITS: Record<string, string> = {
39 "session-ramp": "sessions",
40 "payload-ramp": "KB",
41 "subagent-ramp": "parent sessions",
42 "failure-storm": "simultaneous crashes",
43 "sustained-leak": "healthy sessions",
44};
45
46// ---------------------------------------------------------------------------
47// Types
48// ---------------------------------------------------------------------------
49
50interface BenchmarkStep {
51 benchmark: string;
52 runtime: "node" | "elixir";
53 step: number;
54 stepLabel: string;
55 metrics: Record<string, number | null>;
56 timeSeries?: Array<Record<string, number>>;
57}
58
59interface BenchmarkResult {
60 benchmark: string;
61 runtime: string;
62 steps: BenchmarkStep[];
63 [key: string]: unknown;
64}
65
66interface Crossover {
67 benchmark: string;
68 metric: string;
69 stepValue: number;
70 stepLabel: string;
71 nodeValue: number;
72 elixirValue: number;
73 ratio: number;
74}
75
76// ---------------------------------------------------------------------------
77// Load results
78// ---------------------------------------------------------------------------
79
80function parseResultFile(path: string): BenchmarkResult | null {
81 try {
82 const raw = JSON.parse(readFileSync(path, "utf-8"));
83 // Handle both formats: array of BenchmarkStep[] or {steps: BenchmarkStep[]}
84 if (Array.isArray(raw)) {
85 const steps = raw as BenchmarkStep[];
86 return {
87 benchmark: steps[0]?.benchmark ?? "unknown",
88 runtime: steps[0]?.runtime ?? "unknown",
89 steps,
90 };
91 }
92 // If it has a steps property, use directly
93 if (raw.steps && Array.isArray(raw.steps)) {
94 return raw as BenchmarkResult;
95 }
96 // If it's a single step object, wrap it
97 if (raw.benchmark && raw.metrics) {
98 return {
99 benchmark: raw.benchmark,
100 runtime: raw.runtime,
101 steps: [raw],
102 };
103 }
104 return null;
105 } catch {
106 return null;
107 }
108}
109
110function loadLatestResults(): Map<
111 string,
112 { node: BenchmarkResult | null; elixir: BenchmarkResult | null }
113> {
114 const files = readdirSync(OUTPUT_DIR).filter(
115 (f) => f.startsWith("benchmark-") && f.endsWith(".json"),
116 );
117
118 // Group by benchmark name, find latest per runtime
119 const grouped = new Map<string, { node: string | null; elixir: string | null }>();
120
121 for (const bench of BENCHMARKS) {
122 const nodeFiles = files
123 .filter((f) => f.startsWith(`benchmark-${bench}-node-`))
124 .sort()
125 .reverse();
126 const elixirFiles = files
127 .filter((f) => f.startsWith(`benchmark-${bench}-elixir-`))
128 .sort()
129 .reverse();
130
131 grouped.set(bench, {
132 node: nodeFiles[0] ?? null,
133 elixir: elixirFiles[0] ?? null,
134 });
135 }
136
137 const results = new Map<
138 string,
139 { node: BenchmarkResult | null; elixir: BenchmarkResult | null }
140 >();
141
142 for (const [bench, { node, elixir }] of grouped) {
143 results.set(bench, {
144 node: node ? parseResultFile(`${OUTPUT_DIR}/${node}`) : null,
145 elixir: elixir ? parseResultFile(`${OUTPUT_DIR}/${elixir}`) : null,
146 });
147 }
148
149 return results;
150}
151
152// ---------------------------------------------------------------------------
153// Crossover detection
154// ---------------------------------------------------------------------------
155
156function detectCrossover(
157 nodeSteps: BenchmarkStep[],
158 elixirSteps: BenchmarkStep[],
159 metric: string,
160 higherIsWorse: boolean = true,
161): Crossover | null {
162 // Find common steps
163 const nodeByStep = new Map(nodeSteps.map((s) => [s.step, s]));
164 const elixirByStep = new Map(elixirSteps.map((s) => [s.step, s]));
165
166 const commonSteps = [...nodeByStep.keys()]
167 .filter((k) => elixirByStep.has(k))
168 .sort((a, b) => a - b);
169
170 if (commonSteps.length < 2) return null;
171
172 // Find first step where Elixir is better than Node
173 for (const step of commonSteps) {
174 const nodeVal = nodeByStep.get(step)!.metrics[metric];
175 const elixirVal = elixirByStep.get(step)!.metrics[metric];
176
177 if (nodeVal == null || elixirVal == null) continue;
178
179 const elixirBetter = higherIsWorse
180 ? elixirVal < nodeVal * 0.8 // Elixir is 20%+ better
181 : elixirVal > nodeVal * 1.2; // Elixir is 20%+ better (higher is better)
182
183 if (elixirBetter) {
184 return {
185 benchmark: nodeByStep.get(step)!.benchmark,
186 metric,
187 stepValue: step,
188 stepLabel: nodeByStep.get(step)!.stepLabel,
189 nodeValue: nodeVal,
190 elixirValue: elixirVal,
191 ratio: nodeVal / (elixirVal || 1),
192 };
193 }
194 }
195
196 return null;
197}
198
199// ---------------------------------------------------------------------------
200// CSV generation
201// ---------------------------------------------------------------------------
202
203function generateCSV(
204 nodeSteps: BenchmarkStep[],
205 elixirSteps: BenchmarkStep[],
206 benchName: string,
207): string {
208 const nodeByStep = new Map(nodeSteps.map((s) => [s.step, s]));
209 const elixirByStep = new Map(elixirSteps.map((s) => [s.step, s]));
210
211 const allSteps = [...new Set([...nodeByStep.keys(), ...elixirByStep.keys()])].sort(
212 (a, b) => a - b,
213 );
214
215 // Collect all metric keys
216 const metricKeys = new Set<string>();
217 for (const s of [...nodeSteps, ...elixirSteps]) {
218 for (const k of Object.keys(s.metrics)) metricKeys.add(k);
219 }
220 const sortedKeys = [...metricKeys].sort();
221
222 // Header
223 const headers = ["step", "step_label"];
224 for (const k of sortedKeys) {
225 headers.push(`node_${k}`, `elixir_${k}`);
226 }
227
228 const rows = [headers.join(",")];
229
230 for (const step of allSteps) {
231 const n = nodeByStep.get(step);
232 const e = elixirByStep.get(step);
233 const label = n?.stepLabel ?? e?.stepLabel ?? String(step);
234
235 const row = [String(step), `"${label}"`];
236 for (const k of sortedKeys) {
237 row.push(
238 n?.metrics[k] != null ? String(n.metrics[k]) : "",
239 e?.metrics[k] != null ? String(e.metrics[k]) : "",
240 );
241 }
242 rows.push(row.join(","));
243 }
244
245 return rows.join("\n") + "\n";
246}
247
248// ---------------------------------------------------------------------------
249// Time series CSV (for sustained-leak)
250// ---------------------------------------------------------------------------
251
252function generateTimeSeriesCSV(nodeSteps: BenchmarkStep[], elixirSteps: BenchmarkStep[]): string {
253 const rows: string[] = [];
254
255 // For each step (healthy count variant), emit time series rows
256 for (const nStep of nodeSteps) {
257 const eStep = elixirSteps.find((s) => s.step === nStep.step);
258 if (!nStep.timeSeries?.length) continue;
259
260 const tsKeys = new Set<string>();
261 for (const ts of [...(nStep.timeSeries ?? []), ...(eStep?.timeSeries ?? [])]) {
262 for (const k of Object.keys(ts)) tsKeys.add(k);
263 }
264 const sortedKeys = [...tsKeys].filter((k) => k !== "elapsed_ms").sort();
265
266 if (rows.length === 0) {
267 // Header
268 const headers = ["healthy_count", "elapsed_ms"];
269 for (const k of sortedKeys) headers.push(`node_${k}`, `elixir_${k}`);
270 rows.push(headers.join(","));
271 }
272
273 const nodeByTime = new Map((nStep.timeSeries ?? []).map((t) => [t.elapsed_ms, t]));
274 const elixirByTime = new Map((eStep?.timeSeries ?? []).map((t) => [t.elapsed_ms, t]));
275 const allTimes = [...new Set([...nodeByTime.keys(), ...elixirByTime.keys()])].sort(
276 (a, b) => (a ?? 0) - (b ?? 0),
277 );
278
279 for (const t of allTimes) {
280 const nt = nodeByTime.get(t);
281 const et = elixirByTime.get(t);
282 const row = [String(nStep.step), String(t)];
283 for (const k of sortedKeys) {
284 row.push(nt?.[k] != null ? String(nt[k]) : "", et?.[k] != null ? String(et[k]) : "");
285 }
286 rows.push(row.join(","));
287 }
288 }
289
290 return rows.join("\n") + "\n";
291}
292
293// ---------------------------------------------------------------------------
294// Markdown generation
295// ---------------------------------------------------------------------------
296
297function fmt(val: number | null | undefined, decimals: number = 1): string {
298 if (val == null) return "—";
299 if (Math.abs(val) >= 1_000_000) return `${(val / 1_000_000).toFixed(1)}M`;
300 if (Math.abs(val) >= 10_000) return `${(val / 1000).toFixed(1)}K`;
301 return val.toFixed(decimals);
302}
303
304function fmtBytes(val: number | null | undefined): string {
305 if (val == null) return "—";
306 if (val >= 1_073_741_824) return `${(val / 1_073_741_824).toFixed(1)}GB`;
307 if (val >= 1_048_576) return `${(val / 1_048_576).toFixed(1)}MB`;
308 if (val >= 1024) return `${(val / 1024).toFixed(1)}KB`;
309 return `${val}B`;
310}
311
312function generateMarkdown(
313 results: Map<string, { node: BenchmarkResult | null; elixir: BenchmarkResult | null }>,
314 crossovers: Crossover[],
315): string {
316 const lines: string[] = [];
317
318 lines.push("# OTP Crossover Benchmark Results");
319 lines.push("");
320 lines.push(`_Generated: ${new Date().toISOString()}_`);
321 lines.push("");
322
323 // ---------------------------------------------------------------------------
324 // Crossover summary
325 // ---------------------------------------------------------------------------
326
327 lines.push("## Crossover Summary");
328 lines.push("");
329
330 if (crossovers.length === 0) {
331 lines.push(
332 "No crossover points detected (Elixir may not yet outperform Node at tested scales, or both runtimes performed similarly).",
333 );
334 } else {
335 lines.push("| Benchmark | Metric | Crossover At | Node | Elixir | Ratio |");
336 lines.push("|-----------|--------|-------------|------|--------|-------|");
337 for (const c of crossovers) {
338 lines.push(
339 `| ${c.benchmark} | ${c.metric} | ${c.stepLabel} | ${fmt(c.nodeValue)} | ${fmt(c.elixirValue)} | ${c.ratio.toFixed(1)}x |`,
340 );
341 }
342 }
343 lines.push("");
344
345 // ---------------------------------------------------------------------------
346 // Per-benchmark tables
347 // ---------------------------------------------------------------------------
348
349 for (const benchName of BENCHMARKS) {
350 const data = results.get(benchName);
351 if (!data) continue;
352
353 const label = BENCHMARK_LABELS[benchName] ?? benchName;
354 const unit = BENCHMARK_UNITS[benchName] ?? "step";
355
356 lines.push(`## ${label}`);
357 lines.push("");
358
359 const hasNode = data.node && data.node.steps?.length > 0;
360 const hasElixir = data.elixir && data.elixir.steps?.length > 0;
361
362 if (!hasNode && !hasElixir) {
363 lines.push("_No data available._");
364 lines.push("");
365 continue;
366 }
367
368 // Build comparison table
369 const nodeByStep = new Map((data.node?.steps ?? []).map((s) => [s.step, s]));
370 const elixirByStep = new Map((data.elixir?.steps ?? []).map((s) => [s.step, s]));
371 const allSteps = [...new Set([...nodeByStep.keys(), ...elixirByStep.keys()])].sort(
372 (a, b) => a - b,
373 );
374
375 // Primary metrics table
376 lines.push(
377 `| ${unit} | Node Latency P99 | Elixir Latency P99 | Node Memory | Elixir Memory | Node Throughput | Elixir Throughput | Correctness |`,
378 );
379 lines.push(
380 "|--------|-----------------|-------------------|-------------|--------------|----------------|------------------|-------------|",
381 );
382
383 for (const step of allSteps) {
384 const n = nodeByStep.get(step);
385 const e = elixirByStep.get(step);
386
387 lines.push(
388 `| ${step} | ${fmt(n?.metrics.latency_p99_ms)}ms | ${fmt(e?.metrics.latency_p99_ms)}ms | ${fmtBytes(n?.metrics.memory_bytes)} | ${fmtBytes(e?.metrics.memory_bytes)} | ${fmt(n?.metrics.throughput_events_per_sec, 0)}e/s | ${fmt(e?.metrics.throughput_events_per_sec, 0)}e/s | ${fmt(n?.metrics.correctness_pct, 0)}%/${fmt(e?.metrics.correctness_pct, 0)}% |`,
389 );
390 }
391 lines.push("");
392
393 // Runtime-specific metrics
394 if (hasNode) {
395 lines.push("**Node event loop lag:**");
396 lines.push("");
397 lines.push(`| ${unit} | Lag P50 | Lag P99 |`);
398 lines.push("|--------|---------|---------|");
399 for (const step of allSteps) {
400 const n = nodeByStep.get(step);
401 if (!n) continue;
402 lines.push(
403 `| ${step} | ${fmt(n.metrics.latency_p50_ms)}ms | ${fmt(n.metrics.event_loop_lag_p99_ms)}ms |`,
404 );
405 }
406 lines.push("");
407 }
408
409 if (hasElixir) {
410 lines.push("**Elixir per-process metrics:**");
411 lines.push("");
412 lines.push(`| ${unit} | Per-Session Memory | Scheduler Util |`);
413 lines.push("|--------|--------------------|----------------|");
414 for (const step of allSteps) {
415 const e = elixirByStep.get(step);
416 if (!e) continue;
417 lines.push(
418 `| ${step} | ${fmtBytes(e.metrics.per_session_memory_bytes)} | ${e.metrics.scheduler_util_avg != null ? (e.metrics.scheduler_util_avg * 100).toFixed(1) + "%" : "—"} |`,
419 );
420 }
421 lines.push("");
422 }
423
424 // Benchmark-specific extras
425 if (benchName === "subagent-ramp") {
426 lines.push("**Subagent integrity & fairness:**");
427 lines.push("");
428 lines.push(
429 `| ${unit} | Node Integrity | Elixir Integrity | Node Fairness σ | Elixir Fairness σ |`,
430 );
431 lines.push(
432 "|--------|----------------|-----------------|-----------------|-------------------|",
433 );
434 for (const step of allSteps) {
435 const n = nodeByStep.get(step);
436 const e = elixirByStep.get(step);
437 lines.push(
438 `| ${step} | ${fmt(n?.metrics.lifecycle_integrity_pct, 0)}% | ${fmt(e?.metrics.lifecycle_integrity_pct, 0)}% | ${fmt(n?.metrics.fairness_stddev)} | ${fmt(e?.metrics.fairness_stddev)} |`,
439 );
440 }
441 lines.push("");
442 }
443
444 if (benchName === "failure-storm") {
445 lines.push("**Crash impact on survivors:**");
446 lines.push("");
447 lines.push(
448 `| Crashes | Node Lag Spike | Elixir Lag Spike | Node Errors | Elixir Errors | Node Cleanup | Elixir Cleanup |`,
449 );
450 lines.push(
451 "|---------|---------------|-----------------|-------------|--------------|-------------|----------------|",
452 );
453 for (const step of allSteps) {
454 const n = nodeByStep.get(step);
455 const e = elixirByStep.get(step);
456 lines.push(
457 `| ${step} | ${fmt(n?.metrics.crash_lag_spike_ms)}ms | ${fmt(e?.metrics.crash_lag_spike_ms)}ms | ${fmt(n?.metrics.survivor_error_count, 0)} | ${fmt(e?.metrics.survivor_error_count, 0)} | ${fmtBytes(n?.metrics.memory_cleanup_bytes)} | ${fmtBytes(e?.metrics.memory_cleanup_bytes)} |`,
458 );
459 }
460 lines.push("");
461 }
462
463 if (benchName === "sustained-leak") {
464 lines.push("**Memory growth over time:**");
465 lines.push("");
466 lines.push(
467 `| Healthy Sessions | Node Growth | Elixir Growth | Node Growth % | Elixir Growth % | Leak Deltas (Node) | Leak Deltas (Elixir) |`,
468 );
469 lines.push(
470 "|-----------------|-------------|--------------|--------------|----------------|-------------------|---------------------|",
471 );
472 for (const step of allSteps) {
473 const n = nodeByStep.get(step);
474 const e = elixirByStep.get(step);
475 lines.push(
476 `| ${step} | ${fmtBytes(n?.metrics.memory_growth_bytes)} | ${fmtBytes(e?.metrics.memory_growth_bytes)} | ${fmt(n?.metrics.memory_growth_pct, 0)}% | ${fmt(e?.metrics.memory_growth_pct, 0)}% | ${fmt(n?.metrics.leak_deltas_received, 0)} | ${fmt(e?.metrics.leak_deltas_received, 0)} |`,
477 );
478 }
479 lines.push("");
480 }
481 }
482
483 // ---------------------------------------------------------------------------
484 // The Answer
485 // ---------------------------------------------------------------------------
486
487 lines.push("## The Answer");
488 lines.push("");
489
490 if (crossovers.length > 0) {
491 lines.push("Based on the benchmark data, the OTP crossover points are:");
492 lines.push("");
493 for (const c of crossovers) {
494 lines.push(
495 `- **${BENCHMARK_LABELS[c.benchmark] ?? c.benchmark}**: Elixir outperforms Node at **${c.stepLabel}** (${c.ratio.toFixed(1)}x better on ${c.metric})`,
496 );
497 }
498 lines.push("");
499 lines.push(
500 "> The structural advantage of OTP becomes measurable when T3Code operates beyond these thresholds — which is the scale reached when it becomes a true multi-agent orchestrator with concurrent subagent trees.",
501 );
502 } else {
503 lines.push(
504 "The benchmarks did not detect a clear crossover point at the tested scales. This could mean:",
505 );
506 lines.push("");
507 lines.push("- Both runtimes handle the tested scales equally well");
508 lines.push("- The crossover occurs beyond the tested range");
509 lines.push("- The workload characteristics need adjustment to surface the differences");
510 }
511 lines.push("");
512
513 return lines.join("\n");
514}
515
516// ---------------------------------------------------------------------------
517// Main
518// ---------------------------------------------------------------------------
519
520async function main() {
521 console.log("\n╔══════════════════════════════════════════════════════════════╗");
522 console.log("║ OTP Crossover Benchmark Analysis ║");
523 console.log("╚══════════════════════════════════════════════════════════════╝\n");
524
525 const results = loadLatestResults();
526 const csvDir = `${OUTPUT_DIR}/charts`;
527 mkdirSync(csvDir, { recursive: true });
528
529 let totalSteps = 0;
530 const crossovers: Crossover[] = [];
531
532 for (const [benchName, data] of results) {
533 const hasData = (data.node?.steps?.length ?? 0) > 0 || (data.elixir?.steps?.length ?? 0) > 0;
534 if (!hasData) {
535 console.log(` ○ ${benchName}: no data`);
536 continue;
537 }
538
539 const nodeSteps = data.node?.steps ?? [];
540 const elixirSteps = data.elixir?.steps ?? [];
541 totalSteps += nodeSteps.length + elixirSteps.length;
542
543 console.log(
544 ` ● ${benchName}: node=${nodeSteps.length} steps, elixir=${elixirSteps.length} steps`,
545 );
546
547 // Generate CSV
548 if (nodeSteps.length > 0 && elixirSteps.length > 0) {
549 const csv = generateCSV(nodeSteps, elixirSteps, benchName);
550 writeFileSync(`${csvDir}/benchmark-${benchName}.csv`, csv);
551 console.log(` → ${csvDir}/benchmark-${benchName}.csv`);
552
553 // Time series CSV for sustained-leak
554 if (benchName === "sustained-leak") {
555 const tsCsv = generateTimeSeriesCSV(nodeSteps, elixirSteps);
556 if (tsCsv.trim()) {
557 writeFileSync(`${csvDir}/benchmark-${benchName}-timeseries.csv`, tsCsv);
558 console.log(` → ${csvDir}/benchmark-${benchName}-timeseries.csv`);
559 }
560 }
561
562 // Detect crossovers
563 const latencyCrossover = detectCrossover(nodeSteps, elixirSteps, "latency_p99_ms", true);
564 if (latencyCrossover) crossovers.push(latencyCrossover);
565
566 const memoryCrossover = detectCrossover(nodeSteps, elixirSteps, "memory_bytes", true);
567 if (memoryCrossover) crossovers.push(memoryCrossover);
568
569 const throughputCrossover = detectCrossover(
570 nodeSteps,
571 elixirSteps,
572 "throughput_events_per_sec",
573 false,
574 );
575 if (throughputCrossover) crossovers.push(throughputCrossover);
576 }
577 }
578
579 if (totalSteps === 0) {
580 console.log("\n No benchmark data found. Run benchmarks first:");
581 console.log(" bun run scripts/benchmark-runner.ts --runtime=both\n");
582 process.exit(1);
583 }
584
585 // Generate markdown report
586 const markdown = generateMarkdown(results, crossovers);
587 const reportPath = `${OUTPUT_DIR}/benchmark-analysis.md`;
588 writeFileSync(reportPath, markdown);
589 console.log(`\n Report: ${reportPath}`);
590
591 // Print crossover summary
592 if (crossovers.length > 0) {
593 console.log("\n Crossover points detected:");
594 for (const c of crossovers) {
595 console.log(` ${c.benchmark} / ${c.metric}: at ${c.stepLabel} (${c.ratio.toFixed(1)}x)`);
596 }
597 } else {
598 console.log("\n No crossover points detected at tested scales.");
599 }
600
601 console.log(
602 `\n Total: ${totalSteps} data points across ${[...results.values()].filter((d) => d.node || d.elixir).length} benchmarks\n`,
603 );
604}
605
606main().catch((err) => {
607 console.error("Fatal:", err);
608 process.exit(1);
609});