Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

benchmark-failure-storm.ts

928 lines29.5 KB

1#!/usr/bin/env bun
2/**
3 * benchmark-failure-storm.ts — Benchmark 4: Failure Storm Under Load.
4 *
5 * Tests how many simultaneous session crashes each runtime can absorb
6 * without affecting survivor sessions.
7 *
8 * For each crash step K in CRASH_STEPS, launches (TOTAL_SESSIONS - K) normal
9 * sessions and K crash sessions. Crash sessions die after ~10 deltas.
10 * Measures survivor completeness, latency spikes around crash events,
11 * memory cleanup, and error cascading.
12 *
13 * Usage:
14 * bun run scripts/benchmark-failure-storm.ts --runtime=node
15 * bun run scripts/benchmark-failure-storm.ts --runtime=elixir
16 * bun run scripts/benchmark-failure-storm.ts --runtime=node --steps=0,1,3
17 */
18​
19import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
20import readline from "node:readline";
21import { writeFileSync, mkdirSync } from "node:fs";
22import v8 from "node:v8";
23​
24let HarnessClientManager: any;
25try {
26 const mod = await import("../apps/server/src/provider/Layers/HarnessClientManager.ts");
27 HarnessClientManager = mod.HarnessClientManager;
28} catch {}
29​
30// ---------------------------------------------------------------------------
31// Config
32// ---------------------------------------------------------------------------
33​
34const OUTPUT_DIR = `${process.cwd()}/output/stress-test`;
35const RUNTIME = process.argv.find((a) => a.startsWith("--runtime="))?.split("=")[1] || "node";
36const HARNESS_PORT = Number(process.env.T3CODE_HARNESS_PORT ?? 4321);
37const HARNESS_SECRET = process.env.T3CODE_HARNESS_SECRET ?? "dev-harness-secret";
38​
39const TOTAL_SESSIONS = 30;
40const DEFAULT_CRASH_STEPS = [0, 1, 3, 5, 10, 15, 20];
41const CRASH_STEPS: number[] = (() => {
42 const flag = process.argv.find((a) => a.startsWith("--steps="));
43 if (flag) return flag.split("=")[1]!.split(",").map(Number);
44 return DEFAULT_CRASH_STEPS;
45})();
46const RUNS_PER_STEP = 3;
47const DELTA_COUNT = 200;
48const DELTA_SIZE_KB = 5;
49const DELAY_MS = 10;
50const COOLDOWN_MS = 5000;
51​
52mkdirSync(OUTPUT_DIR, { recursive: true });
53​
54const t0 = Date.now();
55const ts = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
56const log = (msg: string) => console.log(` ${ts()} ${msg}`);
57​
58function sleep(ms: number): Promise<void> {
59 return new Promise((r) => setTimeout(r, ms));
61​
62function percentile(arr: number[], p: number): number {
63 if (arr.length === 0) return 0;
64 const sorted = [...arr].sort((a, b) => a - b);
65 return sorted[Math.max(0, Math.ceil((p / 100) * sorted.length) - 1)]!;
67​
68function median(arr: number[]): number {
69 return percentile(arr, 50);
71​
72// ---------------------------------------------------------------------------
73// Session tracking
74// ---------------------------------------------------------------------------
75​
76interface SessionStats {
77 id: string;
78 role: "survivor" | "victim";
79 deltaCount: number;
80 turnsCompleted: number;
81 firstDeltaAt: number | null;
82 lastDeltaAt: number | null;
83 errors: string[];
84 crashedAt: number | null;
86​
87function createStats(id: string, role: "survivor" | "victim"): SessionStats {
88 return {
89 id,
90 role,
91 deltaCount: 0,
92 turnsCompleted: 0,
93 firstDeltaAt: null,
94 lastDeltaAt: null,
95 errors: [],
96 crashedAt: null,
97 };
99​
100// ---------------------------------------------------------------------------
101// Output types
102// ---------------------------------------------------------------------------
103​
104interface BenchmarkStep {
105 benchmark: string;
106 runtime: "node" | "elixir";
107 step: number;
108 stepLabel: string;
109 metrics: {
110 memory_bytes: number;
111 per_session_memory_bytes: number | null;
112 latency_p50_ms: number;
113 latency_p99_ms: number;
114 throughput_events_per_sec: number;
115 event_loop_lag_p99_ms: number | null;
116 scheduler_util_avg: number | null;
117 correctness_pct: number;
118 startup_ms: number;
119 survivor_error_count: number;
120 crash_lag_spike_ms: number;
121 memory_cleanup_bytes: number;
122 };
123 timeSeries: Array<{ elapsed_ms: number; [key: string]: number }>;
125​
126// ---------------------------------------------------------------------------
127// Single run result
128// ---------------------------------------------------------------------------
129​
130interface RunResult {
131 survivorStats: SessionStats[];
132 victimStats: SessionStats[];
133 crashTimestamps: number[];
134 lagMeasurements: Array<{ ts: number; lag_ms: number }>;
135 memoryBefore: number;
136 memoryAfter: number;
137 survivorFirstDeltaLatencies: number[];
138 survivorThroughput: number;
139 startupMs: number;
140 timeSeries: Array<{ elapsed_ms: number; [key: string]: number }>;
142​
143// ---------------------------------------------------------------------------
144// Node runtime — child process per session
145// ---------------------------------------------------------------------------
146​
147async function runNodeSingle(K: number): Promise<RunResult> {
148 const survivors = TOTAL_SESSIONS - K;
149 const allStats: SessionStats[] = [];
150 const crashTimestamps: number[] = [];
151 const lagMeasurements: Array<{ ts: number; lag_ms: number }> = [];
152​
153 // Event loop lag tracking
154 let lastLagCheck = performance.now();
155 const lagTimer = setInterval(() => {
156 const now = performance.now();
157 const lag = now - lastLagCheck - 100;
158 lagMeasurements.push({ ts: Date.now(), lag_ms: Math.max(0, lag) });
159 lastLagCheck = now;
160 }, 100);
161​
162 const sessions = new Map<
163 string,
164 {
165 child: ChildProcessWithoutNullStreams;
166 rl: readline.Interface;
167 pending: Map<number, any>;
168 nextId: number;
169 codexThreadId: string | null;
170 }
171 >();
172​
173 const startPhaseStart = Date.now();
174​
175 // Spawn survivor sessions
176 for (let i = 0; i < survivors; i++) {
177 const sid = `survivor-node-${i}-${Date.now()}`;
178 const stats = createStats(sid, "survivor");
179 allStats.push(stats);
180​
181 const child = spawn(
182 "bun",
183 [
184 "run",
185 "scripts/mock-codex-server.ts",
186 String(DELTA_COUNT),
187 String(DELTA_SIZE_KB),
188 String(DELAY_MS),
189 "normal",
190 ],
191 { cwd: process.cwd(), env: process.env, stdio: ["pipe", "pipe", "pipe"] },
192 );
193​
194 const rl = readline.createInterface({ input: child.stdout });
195 const session = {
196 child,
197 rl,
198 pending: new Map<number, any>(),
199 nextId: 1,
200 codexThreadId: null as string | null,
201 };
202 sessions.set(sid, session);
203​
204 rl.on("line", (line: string) => {
205 try {
206 const msg = JSON.parse(line);
207 if (msg.id != null) {
208 const p = session.pending.get(msg.id);
209 if (p) {
210 session.pending.delete(msg.id);
211 p.resolve(msg.result ?? msg.error);
212 }
213 return;
214 }
215 if (msg.method === "item/agentMessage/delta") {
216 stats.deltaCount++;
217 const now = Date.now();
218 if (!stats.firstDeltaAt) stats.firstDeltaAt = now;
219 stats.lastDeltaAt = now;
220 }
221 if (msg.method === "turn/completed") stats.turnsCompleted++;
222 } catch {}
223 });
224 child.stderr?.resume();
225​
226 const rpc = (method: string, params: any) =>
227 new Promise<any>((resolve, reject) => {
228 const id = session.nextId++;
229 const timer = setTimeout(() => {
230 session.pending.delete(id);
231 reject(new Error("timeout"));
232 }, 30000);
233 session.pending.set(id, {
234 resolve: (v: any) => {
235 clearTimeout(timer);
236 resolve(v);
237 },
238 reject: (e: any) => {
239 clearTimeout(timer);
240 reject(e);
241 },
242 });
243 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
244 });
245​
246 try {
247 await rpc("initialize", { clientInfo: { name: "stress", version: "1.0" }, capabilities: {} });
248 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
249 const threadResult = await rpc("thread/start", { cwd: process.cwd() });
250 session.codexThreadId = threadResult?.thread?.id ?? null;
251 } catch (e) {
252 stats.errors.push(e instanceof Error ? e.message : String(e));
253 }
254 }
255​
256 // Spawn victim (crash) sessions
257 for (let i = 0; i < K; i++) {
258 const sid = `victim-node-${i}-${Date.now()}`;
259 const stats = createStats(sid, "victim");
260 allStats.push(stats);
261​
262 const child = spawn(
263 "bun",
264 [
265 "run",
266 "scripts/mock-codex-server.ts",
267 String(DELTA_COUNT),
268 String(DELTA_SIZE_KB),
269 String(DELAY_MS),
270 "crash",
271 ],
272 { cwd: process.cwd(), env: process.env, stdio: ["pipe", "pipe", "pipe"] },
273 );
274​
275 // Detect crash via exit event
276 child.on("exit", (code) => {
277 if (code !== 0) {
278 stats.crashedAt = Date.now();
279 crashTimestamps.push(Date.now());
280 }
281 });
282​
283 const rl = readline.createInterface({ input: child.stdout });
284 const session = {
285 child,
286 rl,
287 pending: new Map<number, any>(),
288 nextId: 1,
289 codexThreadId: null as string | null,
290 };
291 sessions.set(sid, session);
292​
293 rl.on("line", (line: string) => {
294 try {
295 const msg = JSON.parse(line);
296 if (msg.id != null) {
297 const p = session.pending.get(msg.id);
298 if (p) {
299 session.pending.delete(msg.id);
300 p.resolve(msg.result ?? msg.error);
301 }
302 return;
303 }
304 if (msg.method === "item/agentMessage/delta") {
305 stats.deltaCount++;
306 const now = Date.now();
307 if (!stats.firstDeltaAt) stats.firstDeltaAt = now;
308 stats.lastDeltaAt = now;
309 }
310 if (msg.method === "turn/completed") stats.turnsCompleted++;
311 } catch {}
312 });
313 child.stderr?.resume();
314​
315 const rpc = (method: string, params: any) =>
316 new Promise<any>((resolve, reject) => {
317 const id = session.nextId++;
318 const timer = setTimeout(() => {
319 session.pending.delete(id);
320 reject(new Error("timeout"));
321 }, 30000);
322 session.pending.set(id, {
323 resolve: (v: any) => {
324 clearTimeout(timer);
325 resolve(v);
326 },
327 reject: (e: any) => {
328 clearTimeout(timer);
329 reject(e);
330 },
331 });
332 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
333 });
334​
335 try {
336 await rpc("initialize", { clientInfo: { name: "stress", version: "1.0" }, capabilities: {} });
337 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
338 const threadResult = await rpc("thread/start", { cwd: process.cwd() });
339 session.codexThreadId = threadResult?.thread?.id ?? null;
340 } catch (e) {
341 stats.errors.push(e instanceof Error ? e.message : String(e));
342 }
343 }
344​
345 const startupMs = Date.now() - startPhaseStart;
346 log(
347 ` ${TOTAL_SESSIONS} sessions started in ${(startupMs / 1000).toFixed(1)}s (${survivors} survivors, ${K} victims)`,
348 );
349​
350 // Memory before sending turns
351 const memBefore = process.memoryUsage().heapUsed;
352​
353 // Fire ALL turns simultaneously
354 const turnSendTime = Date.now();
355 for (const stats of allStats) {
356 const session = sessions.get(stats.id);
357 if (!session || stats.errors.length > 0) continue;
358​
359 const rpc = (method: string, params: any) =>
360 new Promise<any>((resolve, reject) => {
361 const id = session.nextId++;
362 const timer = setTimeout(() => {
363 session.pending.delete(id);
364 reject(new Error("timeout"));
365 }, 60000);
366 session.pending.set(id, {
367 resolve: (v: any) => {
368 clearTimeout(timer);
369 resolve(v);
370 },
371 reject: (e: any) => {
372 clearTimeout(timer);
373 reject(e);
374 },
375 });
376 session.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
377 });
378​
379 rpc("turn/start", {
380 threadId: session.codexThreadId,
381 input: [{ type: "text", text: "failure storm test" }],
382 }).catch((e) => stats.errors.push(e instanceof Error ? e.message : String(e)));
383 }
384​
385 // Wait for survivors to complete (or crash events + 30s)
386 const timeSeries: Array<{ elapsed_ms: number; [key: string]: number }> = [];
387 const maxWait = Date.now() + 120_000;
388 let allCrashesDone = K === 0;
389 let crashSettledAt: number | null = K === 0 ? Date.now() : null;
390​
391 while (Date.now() < maxWait) {
392 const survivorsDone = allStats.filter(
393 (s) => s.role === "survivor" && s.turnsCompleted > 0,
394 ).length;
395 const victimsCrashed = allStats.filter(
396 (s) => s.role === "victim" && s.crashedAt !== null,
397 ).length;
398 const survivorDeltas = allStats
399 .filter((s) => s.role === "survivor")
400 .reduce((sum, s) => sum + s.deltaCount, 0);
401 const mem = process.memoryUsage();
402​
403 timeSeries.push({
404 elapsed_ms: Date.now() - turnSendTime,
405 survivor_completed: survivorsDone,
406 victim_crashed: victimsCrashed,
407 survivor_deltas: survivorDeltas,
408 heap_used: mem.heapUsed,
409 rss: mem.rss,
410 });
411​
412 if (!allCrashesDone && victimsCrashed >= K) {
413 allCrashesDone = true;
414 crashSettledAt = Date.now();
415 log(` All ${K} victims crashed. Continuing to monitor survivors...`);
416 }
417​
418 // Done when all survivors completed (or errored)
419 const allSurvivorsSettled = allStats
420 .filter((s) => s.role === "survivor")
421 .every((s) => s.turnsCompleted > 0 || s.errors.length > 0);
422 if (allSurvivorsSettled) break;
423​
424 // If crashes settled, wait up to 30 more seconds for survivors
425 if (crashSettledAt && Date.now() - crashSettledAt > 30_000) {
426 log(` 30s after crashes, some survivors still incomplete. Breaking.`);
427 break;
428 }
429​
430 process.stdout.write(
431 `\r ${ts()} survivors=${survivorsDone}/${survivors} victims_crashed=${victimsCrashed}/${K} deltas=${survivorDeltas}`,
432 );
433 await sleep(1000);
434 }
435​
436 console.log("");
437 clearInterval(lagTimer);
438​
439 // Memory after
440 const memAfter = process.memoryUsage().heapUsed;
441​
442 // Kill all remaining processes
443 for (const [, session] of sessions) {
444 try {
445 session.child.kill();
446 } catch {}
447 }
448​
449 // Compute survivor first-delta latencies
450 const survivorFirstDeltaLatencies = allStats
451 .filter((s) => s.role === "survivor" && s.firstDeltaAt)
452 .map((s) => s.firstDeltaAt! - turnSendTime);
453​
454 // Compute survivor throughput
455 const survivorEvents = allStats
456 .filter((s) => s.role === "survivor")
457 .reduce((sum, s) => sum + s.deltaCount, 0);
458 const survivorFirstDelta = Math.min(
459 ...allStats.filter((s) => s.role === "survivor" && s.firstDeltaAt).map((s) => s.firstDeltaAt!),
460 );
461 const survivorLastDelta = Math.max(
462 ...allStats.filter((s) => s.role === "survivor" && s.lastDeltaAt).map((s) => s.lastDeltaAt!),
463 );
464 const survivorStreamDuration = (survivorLastDelta - survivorFirstDelta) / 1000;
465 const survivorThroughput =
466 survivorStreamDuration > 0 ? survivorEvents / survivorStreamDuration : 0;
467​
468 return {
469 survivorStats: allStats.filter((s) => s.role === "survivor"),
470 victimStats: allStats.filter((s) => s.role === "victim"),
471 crashTimestamps,
472 lagMeasurements,
473 memoryBefore: memBefore,
474 memoryAfter: memAfter,
475 survivorFirstDeltaLatencies,
476 survivorThroughput,
477 startupMs,
478 timeSeries,
479 };
481​
482// ---------------------------------------------------------------------------
483// Elixir runtime — HarnessClientManager
484// ---------------------------------------------------------------------------
485​
486async function runElixirSingle(K: number): Promise<RunResult> {
487 const survivors = TOTAL_SESSIONS - K;
488 const allStats: SessionStats[] = [];
489 const crashTimestamps: number[] = [];
490 const lagMeasurements: Array<{ ts: number; lag_ms: number }> = [];
491​
492 const mgr = new HarnessClientManager({
493 harnessPort: HARNESS_PORT,
494 harnessSecret: HARNESS_SECRET,
495 onEvent: (raw: any) => {
496 const stats = allStats.find((s) => s.id === raw.threadId);
497 if (!stats) return;
498 if (raw.method === "item/agentMessage/delta") {
499 stats.deltaCount++;
500 const now = Date.now();
501 if (!stats.firstDeltaAt) stats.firstDeltaAt = now;
502 stats.lastDeltaAt = now;
503 }
504 if (raw.method === "turn/completed") stats.turnsCompleted++;
505 // Detect crash events for victims
506 if (raw.method === "session/error" || raw.method === "session/exited") {
507 if (stats.role === "victim") {
508 stats.crashedAt = Date.now();
509 crashTimestamps.push(Date.now());
510 } else {
511 // Error on a survivor means crash cascaded!
512 stats.errors.push(`unexpected ${raw.method}`);
513 }
514 }
515 },
516 onSessionChanged: () => {},
517 onDisconnect: () => {},
518 onReconnect: () => {},
519 });
520​
521 await mgr.connect();
522 log(" Connected to harness");
523​
524 const METRICS_URL = `http://127.0.0.1:${HARNESS_PORT}/api/metrics`;
525 let baselineMemory = 0;
526 try {
527 const baseline = (await fetch(METRICS_URL).then((r) => r.json())) as any;
528 baselineMemory = baseline.beam?.total_memory ?? 0;
529 } catch {}
530​
531 const startPhaseStart = Date.now();
532​
533 // Start survivor sessions
534 for (let i = 0; i < survivors; i++) {
535 const sid = `survivor-elixir-${i}-${Date.now()}`;
536 const stats = createStats(sid, "survivor");
537 allStats.push(stats);
538​
539 try {
540 await mgr.startSession({
541 threadId: sid,
542 provider: "mock",
543 cwd: process.cwd(),
544 providerOptions: {
545 mock: { deltaCount: DELTA_COUNT, deltaSizeKb: DELTA_SIZE_KB, delayMs: DELAY_MS },
546 },
547 });
548 } catch (e) {
549 stats.errors.push(e instanceof Error ? e.message : String(e));
550 }
551 }
552​
553 // Start victim (crash) sessions
554 for (let i = 0; i < K; i++) {
555 const sid = `victim-elixir-${i}-${Date.now()}`;
556 const stats = createStats(sid, "victim");
557 allStats.push(stats);
558​
559 try {
560 await mgr.startSession({
561 threadId: sid,
562 provider: "mock",
563 cwd: process.cwd(),
564 providerOptions: {
565 mock: {
566 deltaCount: DELTA_COUNT,
567 deltaSizeKb: DELTA_SIZE_KB,
568 delayMs: DELAY_MS,
569 mode: "crash",
570 },
571 },
572 });
573 } catch (e) {
574 stats.errors.push(e instanceof Error ? e.message : String(e));
575 }
576 }
577​
578 const startupMs = Date.now() - startPhaseStart;
579 log(
580 ` ${TOTAL_SESSIONS} sessions started in ${(startupMs / 1000).toFixed(1)}s (${survivors} survivors, ${K} victims)`,
581 );
582​
583 // Memory before sending turns
584 let memBefore = 0;
585 try {
586 const m = (await fetch(METRICS_URL).then((r) => r.json())) as any;
587 memBefore = m.beam?.total_memory ?? 0;
588 } catch {}
589​
590 // Fire ALL turns simultaneously
591 const turnSendTime = Date.now();
592 const turnPromises = allStats
593 .filter((s) => s.errors.length === 0)
594 .map((s) =>
595 mgr.sendTurn(s.id, { input: [{ type: "text", text: "failure storm test" }] }).catch(() => {}),
596 );
597 await Promise.all(turnPromises);
598 log(" All turns accepted");
599​
600 // Wait for survivors to complete
601 const timeSeries: Array<{ elapsed_ms: number; [key: string]: number }> = [];
602 const maxWait = Date.now() + 120_000;
603 let allCrashesDone = K === 0;
604 let crashSettledAt: number | null = K === 0 ? Date.now() : null;
605​
606 while (Date.now() < maxWait) {
607 const survivorsDone = allStats.filter(
608 (s) => s.role === "survivor" && s.turnsCompleted > 0,
609 ).length;
610 const victimsCrashed = allStats.filter(
611 (s) => s.role === "victim" && s.crashedAt !== null,
612 ).length;
613 const survivorDeltas = allStats
614 .filter((s) => s.role === "survivor")
615 .reduce((sum, s) => sum + s.deltaCount, 0);
616​
617 let beamMemory = 0;
618 let processCount = 0;
619 let schedulerUtil = 0;
620 try {
621 const m = (await fetch(METRICS_URL).then((r) => r.json())) as any;
622 beamMemory = m.beam?.total_memory ?? 0;
623 processCount = m.beam?.process_count ?? 0;
624 const sched = m.beam?.scheduler_utilization;
625 if (Array.isArray(sched) && sched.length > 0) {
626 schedulerUtil = sched.reduce((s: number, u: number) => s + u, 0) / sched.length;
627 }
628 } catch {}
629​
630 timeSeries.push({
631 elapsed_ms: Date.now() - turnSendTime,
632 survivor_completed: survivorsDone,
633 victim_crashed: victimsCrashed,
634 survivor_deltas: survivorDeltas,
635 beam_memory: beamMemory,
636 process_count: processCount,
637 scheduler_util: schedulerUtil,
638 });
639​
640 if (!allCrashesDone && victimsCrashed >= K) {
641 allCrashesDone = true;
642 crashSettledAt = Date.now();
643 log(` All ${K} victims crashed. Continuing to monitor survivors...`);
644 }
645​
646 const allSurvivorsSettled = allStats
647 .filter((s) => s.role === "survivor")
648 .every((s) => s.turnsCompleted > 0 || s.errors.length > 0);
649 if (allSurvivorsSettled) break;
650​
651 if (crashSettledAt && Date.now() - crashSettledAt > 30_000) {
652 log(` 30s after crashes, some survivors still incomplete. Breaking.`);
653 break;
654 }
655​
656 process.stdout.write(
657 `\r ${ts()} survivors=${survivorsDone}/${survivors} victims_crashed=${victimsCrashed}/${K} deltas=${survivorDeltas} procs=${processCount}`,
658 );
659 await sleep(1000);
660 }
661​
662 console.log("");
663​
664 // Memory after
665 let memAfter = 0;
666 try {
667 const m = (await fetch(METRICS_URL).then((r) => r.json())) as any;
668 memAfter = m.beam?.total_memory ?? 0;
669 } catch {}
670​
671 // Compute survivor first-delta latencies
672 const survivorFirstDeltaLatencies = allStats
673 .filter((s) => s.role === "survivor" && s.firstDeltaAt)
674 .map((s) => s.firstDeltaAt! - turnSendTime);
675​
676 // Compute survivor throughput
677 const survivorEvents = allStats
678 .filter((s) => s.role === "survivor")
679 .reduce((sum, s) => sum + s.deltaCount, 0);
680 const survivorWithDeltas = allStats.filter(
681 (s) => s.role === "survivor" && s.firstDeltaAt && s.lastDeltaAt,
682 );
683 const survivorFirstDelta =
684 survivorWithDeltas.length > 0 ? Math.min(...survivorWithDeltas.map((s) => s.firstDeltaAt!)) : 0;
685 const survivorLastDelta =
686 survivorWithDeltas.length > 0 ? Math.max(...survivorWithDeltas.map((s) => s.lastDeltaAt!)) : 0;
687 const survivorStreamDuration = (survivorLastDelta - survivorFirstDelta) / 1000;
688 const survivorThroughput =
689 survivorStreamDuration > 0 ? survivorEvents / survivorStreamDuration : 0;
690​
691 try {
692 await mgr.stopAll();
693 } catch {}
694 mgr.disconnect();
695​
696 return {
697 survivorStats: allStats.filter((s) => s.role === "survivor"),
698 victimStats: allStats.filter((s) => s.role === "victim"),
699 crashTimestamps,
700 lagMeasurements,
701 memoryBefore: memBefore,
702 memoryAfter: memAfter,
703 survivorFirstDeltaLatencies,
704 survivorThroughput,
705 startupMs,
706 timeSeries,
707 };
709​
710// ---------------------------------------------------------------------------
711// Compute crash lag spike: max lag within 2s of any crash event
712// ---------------------------------------------------------------------------
713​
714function computeCrashLagSpike(
715 crashTimestamps: number[],
716 lagMeasurements: Array<{ ts: number; lag_ms: number }>,
717): number {
718 if (crashTimestamps.length === 0 || lagMeasurements.length === 0) return 0;
719​
720 let maxLag = 0;
721 for (const crashTs of crashTimestamps) {
722 for (const m of lagMeasurements) {
723 if (Math.abs(m.ts - crashTs) <= 2000) {
724 maxLag = Math.max(maxLag, m.lag_ms);
725 }
726 }
727 }
728 return maxLag;
730​
731// ---------------------------------------------------------------------------
732// Run a single step (K crashes) with RUNS_PER_STEP repetitions, take median
733// ---------------------------------------------------------------------------
734​
735async function runStep(K: number): Promise<BenchmarkStep> {
736 const survivors = TOTAL_SESSIONS - K;
737 const stepLabel = `${K} crashes / ${survivors} survivors`;
738 log(`Step K=${K}: ${stepLabel}`);
739​
740 const runResults: RunResult[] = [];
741​
742 for (let run = 1; run <= RUNS_PER_STEP; run++) {
743 log(` Run ${run}/${RUNS_PER_STEP}`);
744 const result = RUNTIME === "elixir" ? await runElixirSingle(K) : await runNodeSingle(K);
745 runResults.push(result);
746​
747 // Progress summary
748 const survivorComplete = result.survivorStats.filter((s) => s.turnsCompleted > 0).length;
749 const survivorErrors = result.survivorStats.reduce((sum, s) => sum + s.errors.length, 0);
750 const victimCrashed = result.victimStats.filter((s) => s.crashedAt !== null).length;
751 const correctness =
752 survivors > 0
753 ? (result.survivorStats.reduce((sum, s) => sum + s.deltaCount, 0) /
754 (survivors * DELTA_COUNT)) *
755 100
756 : 100;
757 log(
758 ` survivors_ok=${survivorComplete}/${survivors} victim_crashed=${victimCrashed}/${K} correctness=${correctness.toFixed(1)}% errors=${survivorErrors}`,
759 );
760​
761 if (run < RUNS_PER_STEP) {
762 log(` Cooldown ${COOLDOWN_MS}ms...`);
763 await sleep(COOLDOWN_MS);
764 }
765 }
766​
767 // Take median of each metric across runs
768 const medianOf = (fn: (r: RunResult) => number) => median(runResults.map(fn));
769​
770 const survivorErrorCount = medianOf((r) =>
771 r.survivorStats.reduce((sum, s) => sum + s.errors.length, 0),
772 );
773​
774 const correctnessPct = medianOf((r) => {
775 if (survivors === 0) return 100;
776 const totalDeltas = r.survivorStats.reduce((sum, s) => sum + s.deltaCount, 0);
777 return (totalDeltas / (survivors * DELTA_COUNT)) * 100;
778 });
779​
780 const crashLagSpike = medianOf((r) => computeCrashLagSpike(r.crashTimestamps, r.lagMeasurements));
781​
782 const memoryCleanup = medianOf((r) => Math.max(0, r.memoryBefore - r.memoryAfter));
783​
784 const latencyP50 = medianOf((r) => percentile(r.survivorFirstDeltaLatencies, 50));
785 const latencyP99 = medianOf((r) => percentile(r.survivorFirstDeltaLatencies, 99));
786 const throughput = medianOf((r) => r.survivorThroughput);
787 const startupMs = medianOf((r) => r.startupMs);
788 const memoryBytes = medianOf((r) => r.memoryAfter);
789​
790 const lagP99 =
791 RUNTIME === "node"
792 ? medianOf((r) => {
793 const lags = r.lagMeasurements.map((m) => m.lag_ms);
794 return percentile(lags, 99);
795 })
796 : null;
797​
798 // Use the middle run's time series for output
799 const middleRun = runResults[Math.floor(runResults.length / 2)]!;
800​
801 return {
802 benchmark: "failure-storm",
803 runtime: RUNTIME as "node" | "elixir",
804 step: K,
805 stepLabel,
806 metrics: {
807 memory_bytes: memoryBytes,
808 per_session_memory_bytes: survivors > 0 ? memoryBytes / survivors : null,
809 latency_p50_ms: latencyP50,
810 latency_p99_ms: latencyP99,
811 throughput_events_per_sec: throughput,
812 event_loop_lag_p99_ms: lagP99,
813 scheduler_util_avg: null, // populated for elixir below
814 correctness_pct: correctnessPct,
815 startup_ms: startupMs,
816 survivor_error_count: survivorErrorCount,
817 crash_lag_spike_ms: crashLagSpike,
818 memory_cleanup_bytes: memoryCleanup,
819 },
820 timeSeries: middleRun.timeSeries,
821 };
823​
824// ---------------------------------------------------------------------------
825// Main
826// ---------------------------------------------------------------------------
827​
828async function main() {
829 console.log("\n" + "╔" + "═".repeat(62) + "╗");
830 console.log("║" + ` Benchmark 4: Failure Storm Under Load — ${RUNTIME}`.padEnd(62) + "║");
831 console.log(
832 "║" + ` ${TOTAL_SESSIONS} sessions, crash steps: [${CRASH_STEPS.join(",")}]`.padEnd(62) + "║",
833 );
834 console.log(
835 "║" +
836 ` ${DELTA_COUNT} deltas × ${DELTA_SIZE_KB}KB, ${RUNS_PER_STEP} runs/step`.padEnd(62) +
837 "║",
838 );
839 console.log("╚" + "═".repeat(62) + "╝\n");
840​
841 const steps: BenchmarkStep[] = [];
842​
843 for (const K of CRASH_STEPS) {
844 const step = await runStep(K);
845 steps.push(step);
846​
847 console.log("");
848 console.log(` ── K=${K} (${step.stepLabel}) ──`);
849 console.log(` correctness: ${step.metrics.correctness_pct.toFixed(1)}%`);
850 console.log(` survivor errors: ${step.metrics.survivor_error_count}`);
851 console.log(` crash lag spike: ${step.metrics.crash_lag_spike_ms.toFixed(1)}ms`);
852 console.log(
853 ` memory cleanup: ${(step.metrics.memory_cleanup_bytes / 1024 / 1024).toFixed(2)}MB`,
854 );
855 console.log(
856 ` latency p50/p99: ${step.metrics.latency_p50_ms.toFixed(1)}ms / ${step.metrics.latency_p99_ms.toFixed(1)}ms`,
857 );
858 console.log(
859 ` throughput: ${Math.round(step.metrics.throughput_events_per_sec)} events/s`,
860 );
861 if (step.metrics.event_loop_lag_p99_ms != null) {
862 console.log(` event loop p99: ${step.metrics.event_loop_lag_p99_ms.toFixed(1)}ms`);
863 }
864 console.log("");
865​
866 if (K < CRASH_STEPS[CRASH_STEPS.length - 1]!) {
867 log(`Cooldown between steps...`);
868 await sleep(COOLDOWN_MS);
869 }
870 }
871​
872 // Summary table
873 console.log("\n" + "═".repeat(90));
874 console.log(" FAILURE STORM RESULTS SUMMARY");
875 console.log("═".repeat(90));
876 console.log(
877 " " +
878 "K".padEnd(4) +
879 "Label".padEnd(26) +
880 "Correct%".padEnd(10) +
881 "Errors".padEnd(8) +
882 "LagSpike".padEnd(10) +
883 "Cleanup".padEnd(10) +
884 "Throughput".padEnd(12),
885 );
886 console.log(" " + "-".repeat(80));
887​
888 for (const s of steps) {
889 console.log(
890 " " +
891 String(s.step).padEnd(4) +
892 s.stepLabel.padEnd(26) +
893 `${s.metrics.correctness_pct.toFixed(1)}%`.padEnd(10) +
894 String(s.metrics.survivor_error_count).padEnd(8) +
895 `${s.metrics.crash_lag_spike_ms.toFixed(1)}ms`.padEnd(10) +
896 `${(s.metrics.memory_cleanup_bytes / 1024 / 1024).toFixed(1)}MB`.padEnd(10) +
897 `${Math.round(s.metrics.throughput_events_per_sec)} ev/s`.padEnd(12),
898 );
899 }
900​
901 console.log("═".repeat(90));
902​
903 // Write output
904 const filename = `benchmark-failure-storm-${RUNTIME}-${Date.now()}.json`;
905 const output = {
906 benchmark: "failure-storm",
907 runtime: RUNTIME,
908 config: {
909 totalSessions: TOTAL_SESSIONS,
910 crashSteps: CRASH_STEPS,
911 runsPerStep: RUNS_PER_STEP,
912 deltaCount: DELTA_COUNT,
913 deltaSizeKb: DELTA_SIZE_KB,
914 delayMs: DELAY_MS,
915 cooldownMs: COOLDOWN_MS,
916 },
917 steps,
918 };
919 writeFileSync(`${OUTPUT_DIR}/${filename}`, JSON.stringify(output, null, 2));
920 log(`Results written to ${OUTPUT_DIR}/${filename}`);
921​
922 setTimeout(() => process.exit(0), 2000);
924​
925main().catch((err) => {
926 console.error("Fatal:", err);
927 process.exit(1);
928});