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

stress-test-node.ts

1,233 lines39.8 KB

1#!/usr/bin/env bun
2/**
3 * stress-test-node.ts — Node/V8 baseline stress test.
4 *
5 * Mimics CodexAppServerManager's architecture: spawns codex app-server
6 * child processes, manages them in a single Node process with a shared
7 * V8 heap, collects metrics that demonstrate Node's structural limitations.
8 *
9 * Usage:
10 * bun run scripts/stress-test-node.ts [--test a|b|c|all]
11 *
12 * Prerequisites:
13 * - `codex` binary available
14 */
15​
16import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
17import readline from "node:readline";
18import { randomUUID } from "node:crypto";
19import { writeFileSync, mkdirSync } from "node:fs";
20import v8 from "node:v8";
21​
22// ---------------------------------------------------------------------------
23// Config
24// ---------------------------------------------------------------------------
25​
26const OUTPUT_DIR = `${process.cwd()}/output/stress-test`;
27const CWD = process.cwd();
28const testArg = process.argv.find((a) => a.startsWith("--test="))?.split("=")[1] || "all";
29​
30mkdirSync(OUTPUT_DIR, { recursive: true });
31​
32// ---------------------------------------------------------------------------
33// Types
34// ---------------------------------------------------------------------------
35​
36interface NodeMetricsSample {
37 timestamp: number;
38 elapsed_ms: number;
39 memory: {
40 heapUsed: number;
41 heapTotal: number;
42 rss: number;
43 external: number;
44 arrayBuffers: number;
45 };
46 v8Heap: {
47 totalHeapSize: number;
48 usedHeapSize: number;
49 heapSizeLimit: number;
50 mallocedMemory: number;
51 };
52 sessionCount: number;
53 eventLoopLag_ms: number;
54 perSessionMemory: string; // "not available — shared V8 heap"
56​
57interface SessionState {
58 threadId: string;
59 provider: string;
60 turnsCompleted: number;
61 deltasReceived: number;
62 firstDeltaAt: number | null;
63 turnStartedAt: number | null;
64 turnCompletedAt: number | null;
65 latencies: number[];
66 errors: string[];
67 killed: boolean;
68 text: string;
70​
71interface CodexSession {
72 threadId: string;
73 child: ChildProcessWithoutNullStreams;
74 rl: readline.Interface;
75 codexThreadId: string | null;
76 nextRequestId: number;
77 pending: Map<
78 number,
79 { resolve: (v: unknown) => void; reject: (e: Error) => void; method: string }
80 >;
81 ready: boolean;
82 onNotification: (method: string, params: Record<string, unknown>) => void;
84​
85interface TestResult {
86 test: string;
87 runtime: "node";
88 startedAt: number;
89 completedAt: number;
90 duration_ms: number;
91 metrics: NodeMetricsSample[];
92 sessions: Record<string, SessionState>;
93 summary: Record<string, unknown>;
95​
96// ---------------------------------------------------------------------------
97// Helpers
98// ---------------------------------------------------------------------------
99​
100const t0 = Date.now();
101const ts = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
102const log = (msg: string) => console.log(` ${ts()} ${msg}`);
103​
104function sleep(ms: number): Promise<void> {
105 return new Promise((r) => setTimeout(r, ms));
107​
108function percentile(arr: number[], p: number): number {
109 if (arr.length === 0) return 0;
110 const sorted = [...arr].sort((a, b) => a - b);
111 const idx = Math.ceil((p / 100) * sorted.length) - 1;
112 return sorted[Math.max(0, idx)]!;
114​
115async function measureEventLoopLag(): Promise<number> {
116 return new Promise((resolve) => {
117 const start = process.hrtime.bigint();
118 setTimeout(() => {
119 resolve(Math.max(0, Number(process.hrtime.bigint() - start) / 1e6 - 1));
120 }, 1);
121 });
123​
124function collectNodeMetrics(sessionCount: number): NodeMetricsSample {
125 const mem = process.memoryUsage();
126 const heap = v8.getHeapStatistics();
127 return {
128 timestamp: Date.now(),
129 elapsed_ms: Date.now() - t0,
130 memory: {
131 heapUsed: mem.heapUsed,
132 heapTotal: mem.heapTotal,
133 rss: mem.rss,
134 external: mem.external,
135 arrayBuffers: mem.arrayBuffers,
136 },
137 v8Heap: {
138 totalHeapSize: heap.total_heap_size,
139 usedHeapSize: heap.used_heap_size,
140 heapSizeLimit: heap.heap_size_limit,
141 mallocedMemory: heap.malloced_memory,
142 },
143 sessionCount,
144 eventLoopLag_ms: 0, // filled in async
145 perSessionMemory: "not available — shared V8 heap",
146 };
148​
149function writeResult(test: string, result: TestResult) {
150 const filename = `node-${test}-${Date.now()}.json`;
151 const path = `${OUTPUT_DIR}/${filename}`;
152 writeFileSync(path, JSON.stringify(result, null, 2));
153 log(`Results written to ${path}`);
155​
156function createSessionState(threadId: string, provider: string): SessionState {
157 return {
158 threadId,
159 provider,
160 turnsCompleted: 0,
161 deltasReceived: 0,
162 firstDeltaAt: null,
163 turnStartedAt: null,
164 turnCompletedAt: null,
165 latencies: [],
166 errors: [],
167 killed: false,
168 text: "",
169 };
171​
172// ---------------------------------------------------------------------------
173// Codex Session Manager (mimics CodexAppServerManager)
174// ---------------------------------------------------------------------------
175​
176const activeSessions = new Map<string, CodexSession>();
177​
178function sendRpc(
179 session: CodexSession,
180 method: string,
181 params: Record<string, unknown>,
182): Promise<unknown> {
183 return new Promise((resolve, reject) => {
184 const id = session.nextRequestId++;
185 const msg = JSON.stringify({ jsonrpc: "2.0", id, method, params });
186​
187 const timer = setTimeout(() => {
188 if (session.pending.has(id)) {
189 session.pending.delete(id);
190 reject(new Error(`RPC timeout: ${method} (${id})`));
191 }
192 }, 60_000);
193​
194 session.pending.set(id, {
195 resolve: (v) => {
196 clearTimeout(timer);
197 resolve(v);
198 },
199 reject: (e) => {
200 clearTimeout(timer);
201 reject(e);
202 },
203 method,
204 });
205​
206 session.child.stdin.write(msg + "\n");
207 });
209​
210function sendNotification(
211 session: CodexSession,
212 method: string,
213 params?: Record<string, unknown>,
214): void {
215 const msg = JSON.stringify({ jsonrpc: "2.0", method, params: params ?? {} });
216 session.child.stdin.write(msg + "\n");
218​
219async function startCodexSession(
220 threadId: string,
221 state: SessionState,
222 onNotification: (method: string, params: Record<string, unknown>) => void,
223): Promise<CodexSession> {
224 const codexPath = "codex";
225 const child = spawn(codexPath, ["app-server"], {
226 cwd: CWD,
227 env: process.env,
228 stdio: ["pipe", "pipe", "pipe"],
229 });
230​
231 const rl = readline.createInterface({ input: child.stdout });
232​
233 const session: CodexSession = {
234 threadId,
235 child,
236 rl,
237 codexThreadId: null,
238 nextRequestId: 1,
239 pending: new Map(),
240 ready: false,
241 onNotification,
242 };
243​
244 // Process stdout lines (JSON-RPC messages)
245 rl.on("line", (line: string) => {
246 try {
247 const msg = JSON.parse(line);
248​
249 // Response to a request
250 if (msg.id !== undefined && msg.id !== null) {
251 const pending = session.pending.get(msg.id);
252 if (pending) {
253 session.pending.delete(msg.id);
254 if (msg.error) {
255 pending.reject(new Error(msg.error.message || "RPC error"));
256 } else {
257 pending.resolve(msg.result);
258 }
259 }
260 return;
261 }
262​
263 // Notification from codex
264 if (msg.method) {
265 onNotification(msg.method, msg.params ?? {});
266 }
267 } catch {
268 // non-JSON line, ignore
269 }
270 });
271​
272 // Ignore stderr
273 child.stderr?.resume();
274​
275 // Handle exit
276 child.on("exit", (code) => {
277 session.ready = false;
278 for (const [id, p] of session.pending) {
279 p.reject(new Error(`Process exited with code ${code}`));
280 session.pending.delete(id);
281 }
282 });
283​
284 activeSessions.set(threadId, session);
285​
286 // Initialize handshake (same as CodexAppServerManager)
287 await sendRpc(session, "initialize", {
288 clientInfo: { name: "t3-stress-test", version: "1.0.0" },
289 capabilities: {},
290 });
291 sendNotification(session, "initialized");
292​
293 // Start thread
294 const threadResult = (await sendRpc(session, "thread/start", {
295 cwd: CWD,
296 approvalPolicy: "never",
297 sandbox: "danger-full-access",
298 })) as Record<string, unknown>;
299​
300 const thread = threadResult.thread as Record<string, unknown> | undefined;
301 session.codexThreadId = (thread?.id as string) ?? null;
302 session.ready = true;
303​
304 return session;
306​
307async function sendTurn(session: CodexSession, prompt: string): Promise<unknown> {
308 const codexTid = session.codexThreadId ?? session.threadId;
309 return sendRpc(session, "turn/start", {
310 threadId: codexTid,
311 input: [{ type: "text", text: prompt }],
312 });
314​
315function killSession(threadId: string): void {
316 const session = activeSessions.get(threadId);
317 if (session) {
318 try {
319 session.child.kill();
320 } catch {}
321 activeSessions.delete(threadId);
322 }
324​
325function killAllSessions(): void {
326 for (const [tid] of activeSessions) {
327 killSession(tid);
328 }
330​
331// ---------------------------------------------------------------------------
332// Test A: Session Scaling (memory growth)
333// ---------------------------------------------------------------------------
334​
335async function testA(): Promise<TestResult> {
336 console.log("\n" + "═".repeat(60));
337 console.log(" TEST A: Session Scaling (Node baseline)");
338 console.log("═".repeat(60));
339​
340 const startedAt = Date.now();
341 const states = new Map<string, SessionState>();
342 const allMetrics: NodeMetricsSample[] = [];
343 const sessionsPerBatch = 5;
344 const prompt = "Count from 1 to 50, one number per line. Do not use any tools.";
345​
346 // Baseline
347 allMetrics.push(collectNodeMetrics(0));
348 log(`Baseline heap: ${(allMetrics[0]!.memory.heapUsed / 1024 / 1024).toFixed(1)}MB`);
349​
350 // Start 5 Codex sessions (Node only supports Codex via app-server)
351 const sessionIds: string[] = [];
352​
353 for (let i = 0; i < sessionsPerBatch; i++) {
354 const threadId = `node-scaling-${i}-${Date.now()}`;
355 sessionIds.push(threadId);
356 states.set(threadId, createSessionState(threadId, "codex"));
357​
358 const state = states.get(threadId)!;
359​
360 try {
361 await startCodexSession(threadId, state, (method, params) => {
362 if (method === "turn/started") state.turnStartedAt = Date.now();
363 if (method === "item/agentMessage/delta") {
364 const now = Date.now();
365 state.deltasReceived++;
366 if (state.firstDeltaAt === null) {
367 state.firstDeltaAt = now;
368 if (state.turnStartedAt) state.latencies.push(now - state.turnStartedAt);
369 }
370 state.text += String((params as any).delta ?? "");
371 }
372 if (method === "turn/completed") {
373 state.turnsCompleted++;
374 state.turnCompletedAt = Date.now();
375 state.firstDeltaAt = null;
376 state.turnStartedAt = null;
377 }
378 });
379 log(`codex[${i}] started`);
380 } catch (e) {
381 state.errors.push(e instanceof Error ? e.message : String(e));
382 log(`codex[${i}] FAILED: ${state.errors[0]}`);
383 }
384 }
385​
386 allMetrics.push(collectNodeMetrics(activeSessions.size));
387 log(
388 `After starting ${activeSessions.size} sessions: heap=${(allMetrics[allMetrics.length - 1]!.memory.heapUsed / 1024 / 1024).toFixed(1)}MB`,
389 );
390​
391 // Send 3 turns to each
392 for (let turn = 0; turn < 3; turn++) {
393 log(`\nTurn ${turn + 1}/3...`);
394​
395 for (const tid of sessionIds) {
396 const state = states.get(tid)!;
397 if (state.errors.length > 0) continue;
398 const session = activeSessions.get(tid);
399 if (!session) continue;
400​
401 try {
402 await sendTurn(session, `${prompt} (Turn ${turn + 1})`);
403 } catch (e) {
404 state.errors.push(e instanceof Error ? e.message : String(e));
405 }
406 }
407​
408 // Wait for turns (max 120s)
409 const turnEnd = Date.now() + 120_000;
410 while (Date.now() < turnEnd) {
411 const allDone = [...states.values()]
412 .filter((s) => s.errors.length === 0)
413 .every((s) => s.turnsCompleted >= turn + 1);
414 if (allDone) break;
415 allMetrics.push(collectNodeMetrics(activeSessions.size));
416 await sleep(2000);
417 }
418​
419 allMetrics.push(collectNodeMetrics(activeSessions.size));
420 const completed = [...states.values()].filter((s) => s.turnsCompleted >= turn + 1).length;
421 log(`Turn ${turn + 1} complete: ${completed}/${states.size} sessions`);
422 }
423​
424 const afterTurns = collectNodeMetrics(activeSessions.size);
425 allMetrics.push(afterTurns);
426​
427 // Kill all and measure cleanup
428 log("\nKilling all sessions...");
429 killAllSessions();
430 await sleep(5000);
431 // Force GC if available
432 try {
433 global.gc?.();
434 } catch {}
435 await sleep(2000);
436 const afterCleanup = collectNodeMetrics(0);
437 allMetrics.push(afterCleanup);
438​
439 const completedAt = Date.now();
440​
441 const result: TestResult = {
442 test: "scaling",
443 runtime: "node",
444 startedAt,
445 completedAt,
446 duration_ms: completedAt - startedAt,
447 metrics: allMetrics,
448 sessions: Object.fromEntries(states),
449 summary: {
450 totalSessions: states.size,
451 successfulSessions: [...states.values()].filter((s) => s.errors.length === 0).length,
452 baselineHeap: allMetrics[0]?.memory.heapUsed,
453 peakHeap: afterTurns.memory.heapUsed,
454 afterCleanupHeap: afterCleanup.memory.heapUsed,
455 heapReclaimed: afterTurns.memory.heapUsed - afterCleanup.memory.heapUsed,
456 peakRss: Math.max(...allMetrics.map((m) => m.memory.rss)),
457 perSessionMemory: "NOT AVAILABLE — shared V8 heap (this is the structural gap)",
458 avgLatency_ms:
459 [...states.values()].flatMap((s) => s.latencies).reduce((a, b) => a + b, 0) /
460 Math.max(1, [...states.values()].flatMap((s) => s.latencies).length),
461 },
462 };
463​
464 writeResult("scaling", result);
465 log(`Heap reclaimed: ${((result.summary.heapReclaimed as number) / 1024 / 1024).toFixed(1)}MB`);
466 return result;
468​
469// ---------------------------------------------------------------------------
470// Test B: GC Cross-Contamination
471// ---------------------------------------------------------------------------
472​
473async function testB(): Promise<TestResult> {
474 console.log("\n" + "═".repeat(60));
475 console.log(" TEST B: GC Cross-Contamination (Node baseline)");
476 console.log("═".repeat(60));
477​
478 const startedAt = Date.now();
479 const states = new Map<string, SessionState>();
480 const allMetrics: NodeMetricsSample[] = [];
481​
482 const tidA = `node-heavy-${Date.now()}`;
483 const tidB = `node-light-${Date.now()}`;
484 states.set(tidA, createSessionState(tidA, "codex"));
485 states.set(tidB, createSessionState(tidB, "codex"));
486 const stateA = states.get(tidA)!;
487 const stateB = states.get(tidB)!;
488​
489 // Latency measurement helper
490 const turnTimings = new Map<
491 string,
492 { sentAt: number; resolver: ((lat: number) => void) | null }
493 >();
494​
495 const makeHandler =
496 (state: SessionState, tid: string) => (method: string, params: Record<string, unknown>) => {
497 if (method === "turn/started") state.turnStartedAt = Date.now();
498 if (method === "item/agentMessage/delta") {
499 const now = Date.now();
500 state.deltasReceived++;
501 if (state.firstDeltaAt === null) {
502 state.firstDeltaAt = now;
503 if (state.turnStartedAt) state.latencies.push(now - state.turnStartedAt);
504 }
505 state.text += String((params as any).delta ?? "");
506​
507 const timing = turnTimings.get(tid);
508 if (timing?.resolver) {
509 timing.resolver(now - timing.sentAt);
510 timing.resolver = null;
511 }
512 }
513 if (method === "turn/completed") {
514 state.turnsCompleted++;
515 state.turnCompletedAt = Date.now();
516 state.firstDeltaAt = null;
517 state.turnStartedAt = null;
518 }
519 };
520​
521 function measureTurnLatency(session: CodexSession, tid: string, prompt: string): Promise<number> {
522 return new Promise<number>((resolve) => {
523 const timer = setTimeout(() => {
524 turnTimings.delete(tid);
525 resolve(-1);
526 }, 60_000);
527 turnTimings.set(tid, {
528 sentAt: Date.now(),
529 resolver: (lat) => {
530 clearTimeout(timer);
531 resolve(lat);
532 },
533 });
534 sendTurn(session, prompt).catch(() => {
535 clearTimeout(timer);
536 resolve(-1);
537 });
538 });
539 }
540​
541 // Phase 1: B alone (baseline)
542 log("Phase 1: Baseline — B alone (3 turns)");
543 const sessionB = await startCodexSession(tidB, stateB, makeHandler(stateB, tidB));
544 log("B ready");
545​
546 const baselineLatencies: number[] = [];
547 for (let i = 0; i < 3; i++) {
548 const lat = await measureTurnLatency(
549 sessionB,
550 tidB,
551 "Say hello in exactly one word. Do not use tools.",
552 );
553 if (lat > 0) baselineLatencies.push(lat);
554 log(` Baseline turn ${i + 1}: ${lat}ms`);
555 const end = Date.now() + 60_000;
556 while (Date.now() < end && stateB.turnsCompleted < i + 1) await sleep(500);
557 allMetrics.push(collectNodeMetrics(activeSessions.size));
558 }
559 log(`Baseline latencies: ${baselineLatencies.map((l) => `${l}ms`).join(", ")}`);
560​
561 // Phase 2: A churning + B concurrent
562 log("\nPhase 2: B with A churning");
563 const sessionA = await startCodexSession(tidA, stateA, makeHandler(stateA, tidA));
564 log("A ready");
565​
566 const heavyPrompt =
567 "Write a very long and detailed essay about the history of computing, from Charles Babbage " +
568 "through modern AI. Include every decade. Make it at least 1000 words. Do not use any tools.";
569​
570 log("Sending heavy turn to A (awaited)...");
571 await sendTurn(sessionA, heavyPrompt);
572 log("A turn accepted, waiting for streaming...");
573 const aStart = Date.now();
574 while (Date.now() - aStart < 90_000 && stateA.deltasReceived === 0) await sleep(1000);
575 log(`A has ${stateA.deltasReceived} deltas, proceeding`);
576​
577 const concurrentLatencies: number[] = [];
578 for (let i = 0; i < 3; i++) {
579 const turnsBefore = stateB.turnsCompleted;
580 const lat = await measureTurnLatency(
581 sessionB,
582 tidB,
583 "Say hello in exactly one word. Do not use tools.",
584 );
585 if (lat > 0) concurrentLatencies.push(lat);
586 log(` Concurrent turn ${i + 1}: ${lat}ms (A deltas: ${stateA.deltasReceived})`);
587 const end = Date.now() + 60_000;
588 while (Date.now() < end && stateB.turnsCompleted <= turnsBefore) await sleep(500);
589 allMetrics.push(collectNodeMetrics(activeSessions.size));
590 }
591 log(`Concurrent latencies: ${concurrentLatencies.map((l) => `${l}ms`).join(", ")}`);
592​
593 killAllSessions();
594 await sleep(3000);
595 allMetrics.push(collectNodeMetrics(0));
596​
597 const completedAt = Date.now();
598 const result: TestResult = {
599 test: "gc-contamination",
600 runtime: "node",
601 startedAt,
602 completedAt,
603 duration_ms: completedAt - startedAt,
604 metrics: allMetrics,
605 sessions: Object.fromEntries(states),
606 summary: {
607 baselineLatencies_ms: baselineLatencies,
608 concurrentLatencies_ms: concurrentLatencies,
609 baselineP50_ms: percentile(baselineLatencies, 50),
610 concurrentP50_ms: percentile(concurrentLatencies, 50),
611 latencyDelta_ms:
612 concurrentLatencies.length > 0 && baselineLatencies.length > 0
613 ? percentile(concurrentLatencies, 50) - percentile(baselineLatencies, 50)
614 : null,
615 sessionA_deltas: stateA.deltasReceived,
616 sessionB_totalDeltas: stateB.deltasReceived,
617 note:
618 "Node's V8 GC is stop-the-world — all sessions share the same heap. " +
619 "Cross-contamination may not show in this test because child processes " +
620 "run in separate OS processes, but GC in the MANAGER process affects all event handling.",
621 },
622 };
623​
624 writeResult("gc-contamination", result);
625 return result;
627​
628// ---------------------------------------------------------------------------
629// Test C: Crash Churn (recovery)
630// ---------------------------------------------------------------------------
631​
632async function testC(): Promise<TestResult> {
633 console.log("\n" + "═".repeat(60));
634 console.log(" TEST C: Crash Churn (Node baseline)");
635 console.log("═".repeat(60));
636​
637 const startedAt = Date.now();
638 const states = new Map<string, SessionState>();
639 const allMetrics: NodeMetricsSample[] = [];
640 const sessionIds: string[] = [];
641​
642 // Start 10 sessions
643 for (let i = 0; i < 10; i++) {
644 const tid = `node-crash-${i}-${Date.now()}`;
645 sessionIds.push(tid);
646 const state = createSessionState(tid, "codex");
647 states.set(tid, state);
648​
649 try {
650 await startCodexSession(tid, state, (method, params) => {
651 if (method === "turn/started") state.turnStartedAt = Date.now();
652 if (method === "item/agentMessage/delta") {
653 state.deltasReceived++;
654 if (state.firstDeltaAt === null) state.firstDeltaAt = Date.now();
655 state.text += String((params as any).delta ?? "");
656 }
657 if (method === "turn/completed") {
658 state.turnsCompleted++;
659 state.turnCompletedAt = Date.now();
660 state.firstDeltaAt = null;
661 state.turnStartedAt = null;
662 }
663 });
664 log(`session[${i}] started`);
665 } catch (e) {
666 state.errors.push(e instanceof Error ? e.message : String(e));
667 }
668 }
669​
670 allMetrics.push(collectNodeMetrics(activeSessions.size));
671 log(`${activeSessions.size} sessions started`);
672​
673 // Send tasks
674 const prompt =
675 "Write a detailed explanation of how compilers work, covering lexing, parsing, AST construction, and code generation. Do not use tools.";
676 for (const tid of sessionIds) {
677 const state = states.get(tid)!;
678 if (state.errors.length > 0) continue;
679 const session = activeSessions.get(tid);
680 if (session) {
681 try {
682 await sendTurn(session, prompt);
683 } catch (e) {
684 state.errors.push(e instanceof Error ? e.message : String(e));
685 }
686 }
687 }
688​
689 log("Tasks sent, waiting 5s before kills...");
690 await sleep(5000);
691​
692 const preKill = collectNodeMetrics(activeSessions.size);
693 allMetrics.push(preKill);
694​
695 // Kill first 3
696 const killTargets = sessionIds.slice(0, 3);
697 log(`Killing ${killTargets.length} sessions...`);
698 for (const tid of killTargets) {
699 killSession(tid);
700 states.get(tid)!.killed = true;
701 log(` Killed: ${tid.slice(0, 30)}`);
702 }
703​
704 // Monitor survivors for 15s
705 log("Monitoring survivors...");
706 for (let i = 0; i < 15; i++) {
707 allMetrics.push(collectNodeMetrics(activeSessions.size));
708 await sleep(1000);
709 }
710​
711 // Check survivor state
712 const survivorIds = sessionIds.slice(3);
713 const survivorErrors = survivorIds.map((tid) => states.get(tid)!).flatMap((s) => s.errors);
714​
715 const postKill = collectNodeMetrics(activeSessions.size);
716 allMetrics.push(postKill);
717​
718 killAllSessions();
719 await sleep(3000);
720 try {
721 global.gc?.();
722 } catch {}
723 await sleep(2000);
724 allMetrics.push(collectNodeMetrics(0));
725​
726 const completedAt = Date.now();
727​
728 const result: TestResult = {
729 test: "crash-churn",
730 runtime: "node",
731 startedAt,
732 completedAt,
733 duration_ms: completedAt - startedAt,
734 metrics: allMetrics,
735 sessions: Object.fromEntries(states),
736 summary: {
737 totalSessions: 10,
738 killed: killTargets.length,
739 survivorCount: survivorIds.length,
740 survivorErrors: survivorErrors.length,
741 survivorErrorMessages: survivorErrors,
742 preKillHeap: preKill.memory.heapUsed,
743 postKillHeap: postKill.memory.heapUsed,
744 heapReclaimed: preKill.memory.heapUsed - postKill.memory.heapUsed,
745 preKillRss: preKill.memory.rss,
746 postKillRss: postKill.memory.rss,
747 cascadingFailures: survivorErrors.length > 0,
748 note:
749 "Node kills child processes via child.kill(). The V8 heap shared by " +
750 "the manager process is NOT immediately affected — GC reclaims eventually.",
751 },
752 };
753​
754 writeResult("crash-churn", result);
755 return result;
757​
758// ---------------------------------------------------------------------------
759// Test GC-Lab: Controlled GC cross-contamination with mock server
760// ---------------------------------------------------------------------------
761​
762/** Spawn a mock Codex server with configurable payload sizes */
763function startMockSession(
764 threadId: string,
765 state: SessionState,
766 deltaCount: number,
767 deltaSizeKb: number,
768 delayMs: number,
769 onNotification: (method: string, params: Record<string, unknown>) => void,
770): Promise<CodexSession> {
771 return new Promise((resolve, reject) => {
772 const mockPath = `${process.cwd()}/scripts/mock-codex-server.ts`;
773 const child = spawn(
774 "bun",
775 ["run", mockPath, String(deltaCount), String(deltaSizeKb), String(delayMs)],
776 {
777 cwd: CWD,
778 env: process.env,
779 stdio: ["pipe", "pipe", "pipe"],
780 },
781 );
782​
783 const rl = readline.createInterface({ input: child.stdout });
784 const session: CodexSession = {
785 threadId,
786 child,
787 rl,
788 codexThreadId: null,
789 nextRequestId: 1,
790 pending: new Map(),
791 ready: false,
792 onNotification,
793 };
794​
795 rl.on("line", (line: string) => {
796 try {
797 const msg = JSON.parse(line);
798 if (msg.id !== undefined && msg.id !== null) {
799 const pending = session.pending.get(msg.id);
800 if (pending) {
801 session.pending.delete(msg.id);
802 if (msg.error) pending.reject(new Error(msg.error.message || "RPC error"));
803 else pending.resolve(msg.result);
804 }
805 return;
806 }
807 if (msg.method) onNotification(msg.method, msg.params ?? {});
808 } catch (err) {
809 console.error("Failed to parse JSONRPC line:", err);
810 }
811 });
812​
813 child.stderr?.resume();
814 child.on("exit", () => {
815 for (const [id, p] of session.pending) {
816 p.reject(new Error("Process exited"));
817 session.pending.delete(id);
818 }
819 });
820​
821 activeSessions.set(threadId, session);
822​
823 // Initialize handshake
824 sendRpc(session, "initialize", {
825 clientInfo: { name: "gc-lab", version: "1.0" },
826 capabilities: {},
827 })
828 .then(() => {
829 sendNotification(session, "initialized");
830 return sendRpc(session, "thread/start", {});
831 })
832 .then((result: any) => {
833 session.codexThreadId = result?.thread?.id ?? null;
834 session.ready = true;
835 resolve(session);
836 })
837 .catch(reject);
838 });
840​
841async function testGcLab(): Promise<TestResult> {
842 console.log("\n" + "═".repeat(60));
843 console.log(" TEST GC-LAB: Controlled GC Cross-Contamination");
844 console.log(" Session A: 500 deltas × 500KB (creates ~250MB garbage)");
845 console.log(" Session B: 500 deltas × 0.1KB (tiny payloads)");
846 console.log(" Both in same Node process (shared V8 heap)");
847 console.log("═".repeat(60));
848​
849 const startedAt = Date.now();
850 const states = new Map<string, SessionState>();
851 const allMetrics: NodeMetricsSample[] = [];
852 const gcPauses: Array<{ time: number; duration: number; kind: string }> = [];
853​
854 // Set up GC observer if available (Node, not guaranteed in Bun)
855 let gcObserver: any = null;
856 try {
857 const { PerformanceObserver } = await import("node:perf_hooks");
858 gcObserver = new PerformanceObserver((list: any) => {
859 for (const entry of list.getEntries()) {
860 gcPauses.push({
861 time: entry.startTime,
862 duration: entry.duration,
863 kind:
864 entry.detail?.kind === 1
865 ? "scavenge"
866 : entry.detail?.kind === 2
867 ? "mark-sweep"
868 : `kind-${entry.detail?.kind ?? "?"}`,
869 });
870 }
871 });
872 gcObserver.observe({ entryTypes: ["gc"] });
873 log("GC observer active");
874 } catch {
875 log("GC observer not available (Bun) — using event loop lag instead");
876 }
877​
878 const tidA = `gclab-heavy-${Date.now()}`;
879 const tidB = `gclab-light-${Date.now()}`;
880 states.set(tidA, createSessionState(tidA, "mock-codex"));
881 states.set(tidB, createSessionState(tidB, "mock-codex"));
882 const stateA = states.get(tidA)!;
883 const stateB = states.get(tidB)!;
884​
885 // Accumulate parsed objects to force old-gen promotion (prevents young-gen fast path)
886 // This simulates a real session manager that retains event state (like SnapshotServer)
887 const retainedObjects: unknown[] = [];
888​
889 // Event loop lag: measures how long the event loop is blocked (captures GC pauses)
890 const bEventLoopLags: number[] = [];
891 let lagTimer: ReturnType<typeof setTimeout> | null = null;
892 let lastLagCheck = performance.now();
893​
894 function startLagMonitor() {
895 function check() {
896 const now = performance.now();
897 const lag = now - lastLagCheck - 1; // Expected ~1ms
898 if (lag > 0.5) bEventLoopLags.push(lag);
899 lastLagCheck = now;
900 lagTimer = setTimeout(check, 1);
901 }
902 lastLagCheck = performance.now();
903 lagTimer = setTimeout(check, 1);
904 }
905 function stopLagMonitor() {
906 if (lagTimer) clearTimeout(lagTimer);
907 }
908​
909 const makeLabHandler =
910 (state: SessionState, retainDeltas: boolean) =>
911 (method: string, params: Record<string, unknown>) => {
912 if (method === "turn/started") state.turnStartedAt = Date.now();
913 if (method === "item/agentMessage/delta") {
914 state.deltasReceived++;
915 if (state.firstDeltaAt === null) state.firstDeltaAt = Date.now();
916 const delta = String((params as any).delta ?? "");
917 state.text += delta.slice(0, 100);
918​
919 if (retainDeltas) {
920 // KEEP the parsed object alive → forces old-gen promotion → triggers mark-sweep
921 retainedObjects.push({ delta, params, ts: Date.now() });
922 }
923 }
924 if (method === "turn/completed") {
925 state.turnsCompleted++;
926 state.turnCompletedAt = Date.now();
927 state.firstDeltaAt = null;
928 state.turnStartedAt = null;
929 }
930 };
931​
932 allMetrics.push(collectNodeMetrics(0));
933​
934 // Phase 1: B alone (baseline event loop lag)
935 log("Phase 1: B alone (baseline — 500 × 0.1KB deltas)");
936 const sessionB = await startMockSession(tidB, stateB, 500, 0.1, 1, makeLabHandler(stateB, false));
937 log("B ready");
938​
939 startLagMonitor();
940 await sendTurn(sessionB, "baseline");
941 const bEnd = Date.now() + 30_000;
942 while (Date.now() < bEnd && stateB.turnsCompleted < 1) await sleep(100);
943 stopLagMonitor();
944​
945 const baselineLags = [...bEventLoopLags];
946 bEventLoopLags.length = 0;
947 allMetrics.push(collectNodeMetrics(activeSessions.size));
948 log(
949 `Baseline: ${stateB.deltasReceived} deltas, ${baselineLags.length} lag samples, p50=${percentile(baselineLags, 50).toFixed(2)}ms, p99=${percentile(baselineLags, 99).toFixed(2)}ms, max=${baselineLags.length > 0 ? Math.max(...baselineLags).toFixed(2) : 0}ms`,
950 );
951​
952 const gcBefore = gcPauses.length;
953 const heapBefore = process.memoryUsage().heapUsed;
954​
955 // Phase 2: A (heavy, retained) + B (light) concurrent
956 log("\nPhase 2: A (500 × 500KB, RETAINED) + B (500 × 0.1KB) concurrent");
957 log("A's deltas are kept in memory → forces old-gen promotion → mark-sweep GC");
958 const sessionA = await startMockSession(tidA, stateA, 500, 500, 1, makeLabHandler(stateA, true));
959 log("A ready");
960​
961 startLagMonitor();
962 const turnAPromise = sendTurn(sessionA, "heavy");
963 const turnBPromise = sendTurn(sessionB, "concurrent");
964 await Promise.all([turnAPromise, turnBPromise]);
965​
966 // Wait for both to complete (A=1 turn total, B=2 turns total)
967 const bothEnd = Date.now() + 120_000;
968 while (Date.now() < bothEnd && (stateA.turnsCompleted < 1 || stateB.turnsCompleted < 2)) {
969 allMetrics.push(collectNodeMetrics(activeSessions.size));
970 await sleep(500);
971 }
972 stopLagMonitor();
973​
974 const concurrentLags = [...bEventLoopLags];
975 const gcDuringConcurrent = gcPauses.slice(gcBefore);
976 const heapAfter = process.memoryUsage().heapUsed;
977​
978 allMetrics.push(collectNodeMetrics(activeSessions.size));
979​
980 log(
981 `Concurrent: ${stateB.deltasReceived} total B deltas, ${concurrentLags.length} lag samples, p50=${percentile(concurrentLags, 50).toFixed(2)}ms, p99=${percentile(concurrentLags, 99).toFixed(2)}ms, max=${concurrentLags.length > 0 ? Math.max(...concurrentLags).toFixed(2) : 0}ms`,
982 );
983 log(
984 `Heap growth: ${((heapAfter - heapBefore) / 1024 / 1024).toFixed(1)}MB (retained objects: ${retainedObjects.length})`,
985 );
986 log(`GC pauses during concurrent phase: ${gcDuringConcurrent.length}`);
987 if (gcDuringConcurrent.length > 0) {
988 const markSweeps = gcDuringConcurrent.filter((p) => p.kind === "mark-sweep");
989 log(
990 ` Mark-sweep pauses: ${markSweeps.length}, max=${Math.max(...markSweeps.map((p) => p.duration)).toFixed(2)}ms`,
991 );
992 log(
993 ` Total GC pause time: ${gcDuringConcurrent.reduce((s, p) => s + p.duration, 0).toFixed(2)}ms`,
994 );
995 }
996​
997 // Capture count before cleanup
998 const retainedCount = retainedObjects.length;
999 retainedObjects.length = 0;
1000 if (gcObserver) gcObserver.disconnect();
1001 killAllSessions();
1002 await sleep(2000);
1003 allMetrics.push(collectNodeMetrics(0));
1004​
1005 const completedAt = Date.now();
1006​
1007 const result: TestResult = {
1008 test: "gc-lab",
1009 runtime: "node",
1010 startedAt,
1011 completedAt,
1012 duration_ms: completedAt - startedAt,
1013 metrics: allMetrics,
1014 sessions: Object.fromEntries(states),
1015 summary: {
1016 baselineLagSamples: baselineLags.length,
1017 concurrentLagSamples: concurrentLags.length,
1018 baselineP50_ms: Math.round(percentile(baselineLags, 50) * 100) / 100,
1019 baselineP99_ms: Math.round(percentile(baselineLags, 99) * 100) / 100,
1020 baselineMax_ms:
1021 baselineLags.length > 0 ? Math.round(Math.max(...baselineLags) * 100) / 100 : 0,
1022 concurrentP50_ms: Math.round(percentile(concurrentLags, 50) * 100) / 100,
1023 concurrentP99_ms: Math.round(percentile(concurrentLags, 99) * 100) / 100,
1024 concurrentMax_ms:
1025 concurrentLags.length > 0 ? Math.round(Math.max(...concurrentLags) * 100) / 100 : 0,
1026 heapGrowthMb: Math.round(((heapAfter - heapBefore) / 1024 / 1024) * 10) / 10,
1027 retainedObjects: retainedCount,
1028 gcPausesDuringConcurrent: gcDuringConcurrent.length,
1029 gcTotalPauseMs:
1030 Math.round(gcDuringConcurrent.reduce((s, p) => s + p.duration, 0) * 100) / 100,
1031 gcMarkSweepCount: gcDuringConcurrent.filter((p) => p.kind === "mark-sweep").length,
1032 gcMaxPauseMs:
1033 gcDuringConcurrent.length > 0
1034 ? Math.round(Math.max(...gcDuringConcurrent.map((p) => p.duration)) * 100) / 100
1035 : 0,
1036 sessionA_deltas: stateA.deltasReceived,
1037 sessionA_payloadSizeKb: 500,
1038 sessionB_deltas: stateB.deltasReceived,
1039 sessionB_payloadSizeKb: 0.1,
1040 },
1041 };
1042​
1043 writeResult("gc-lab", result);
1044 return result;
1046​
1047// ---------------------------------------------------------------------------
1048// Test Concurrent: 10 sessions streaming simultaneously
1049// ---------------------------------------------------------------------------
1050​
1051async function testConcurrent(): Promise<TestResult> {
1052 console.log("\n" + "═".repeat(60));
1053 console.log(" TEST CONCURRENT: 10 sessions × 200 deltas × 10KB");
1054 console.log(" All streaming simultaneously in one Node process");
1055 console.log("═".repeat(60));
1056​
1057 const startedAt = Date.now();
1058 const N = 10;
1059 const states = new Map<string, SessionState>();
1060 const allMetrics: NodeMetricsSample[] = [];
1061 const sessionIds: string[] = [];
1062 const eventTimestamps: number[] = []; // all event receipt times
1063​
1064 // Event loop lag monitor
1065 const lags: number[] = [];
1066 let lagTimer: ReturnType<typeof setTimeout> | null = null;
1067 let lastCheck = performance.now();
1068 function startLag() {
1069 function tick() {
1070 const now = performance.now();
1071 const lag = now - lastCheck - 1;
1072 if (lag > 0.5) lags.push(lag);
1073 lastCheck = now;
1074 lagTimer = setTimeout(tick, 1);
1076 lastCheck = performance.now();
1077 lagTimer = setTimeout(tick, 1);
1079 function stopLag() {
1080 if (lagTimer) clearTimeout(lagTimer);
1082​
1083 allMetrics.push(collectNodeMetrics(0));
1084​
1085 // Start 10 mock sessions (200 deltas × 10KB each, 5ms delay)
1086 for (let i = 0; i < N; i++) {
1087 const tid = `concurrent-${i}-${Date.now()}`;
1088 sessionIds.push(tid);
1089 const state = createSessionState(tid, "mock-codex");
1090 states.set(tid, state);
1091​
1092 try {
1093 await startMockSession(tid, state, 200, 10, 5, (method, params) => {
1094 if (method === "turn/started") state.turnStartedAt = Date.now();
1095 if (method === "item/agentMessage/delta") {
1096 state.deltasReceived++;
1097 eventTimestamps.push(Date.now());
1098 if (state.firstDeltaAt === null) state.firstDeltaAt = Date.now();
1100 if (method === "turn/completed") {
1101 state.turnsCompleted++;
1102 state.turnCompletedAt = Date.now();
1103 state.firstDeltaAt = null;
1104 state.turnStartedAt = null;
1106 });
1107 log(`session[${i}] started`);
1108 } catch (e) {
1109 state.errors.push(e instanceof Error ? e.message : String(e));
1112​
1113 allMetrics.push(collectNodeMetrics(activeSessions.size));
1114 log(`${activeSessions.size} sessions ready`);
1115​
1116 // Send turns to ALL simultaneously
1117 log("Sending turns to all 10 sessions...");
1118 startLag();
1119 const turnPromises = sessionIds.map((tid) => {
1120 const session = activeSessions.get(tid);
1121 if (!session) return Promise.resolve();
1122 return sendTurn(session, "concurrent test").catch(() => {});
1123 });
1124 await Promise.all(turnPromises);
1125 log("All turns accepted");
1126​
1127 // Wait for all to complete (max 60s)
1128 const end = Date.now() + 60_000;
1129 while (Date.now() < end) {
1130 const done = [...states.values()].every((s) => s.turnsCompleted >= 1 || s.errors.length > 0);
1131 if (done) break;
1132 allMetrics.push(collectNodeMetrics(activeSessions.size));
1133 await sleep(1000);
1135 stopLag();
1136​
1137 const completed = [...states.values()].filter((s) => s.turnsCompleted >= 1).length;
1138 const totalDeltas = [...states.values()].reduce((s, st) => s + st.deltasReceived, 0);
1139​
1140 // Calculate event throughput
1141 let eventsPerSecond = 0;
1142 if (eventTimestamps.length > 1) {
1143 const duration = (eventTimestamps[eventTimestamps.length - 1]! - eventTimestamps[0]!) / 1000;
1144 eventsPerSecond = duration > 0 ? Math.round(eventTimestamps.length / duration) : 0;
1146​
1147 allMetrics.push(collectNodeMetrics(activeSessions.size));
1148​
1149 log(`Completed: ${completed}/${N}, total deltas: ${totalDeltas}`);
1150 log(`Event throughput: ${eventsPerSecond} events/s`);
1151 log(
1152 `Event loop lag: p50=${percentile(lags, 50).toFixed(1)}ms, p99=${percentile(lags, 99).toFixed(1)}ms, max=${lags.length > 0 ? Math.max(...lags).toFixed(1) : 0}ms`,
1153 );
1154​
1155 killAllSessions();
1156 await sleep(2000);
1157 allMetrics.push(collectNodeMetrics(0));
1158​
1159 const completedAt = Date.now();
1160​
1161 const result: TestResult = {
1162 test: "concurrent",
1163 runtime: "node",
1164 startedAt,
1165 completedAt,
1166 duration_ms: completedAt - startedAt,
1167 metrics: allMetrics,
1168 sessions: Object.fromEntries(states),
1169 summary: {
1170 sessionCount: N,
1171 sessionsCompleted: completed,
1172 totalDeltas,
1173 eventsPerSecond,
1174 lagP50_ms: Math.round(percentile(lags, 50) * 100) / 100,
1175 lagP99_ms: Math.round(percentile(lags, 99) * 100) / 100,
1176 lagMax_ms: lags.length > 0 ? Math.round(Math.max(...lags) * 100) / 100 : 0,
1177 lagSamples: lags.length,
1178 peakHeap: Math.max(...allMetrics.map((m) => m.memory.heapUsed)),
1179 peakRss: Math.max(...allMetrics.map((m) => m.memory.rss)),
1180 },
1181 };
1182​
1183 writeResult("concurrent", result);
1184 return result;
1186​
1187// ---------------------------------------------------------------------------
1188// Main
1189// ---------------------------------------------------------------------------
1190​
1191async function main() {
1192 console.log("\n" + "╔" + "═".repeat(58) + "╗");
1193 console.log("║" + " T3Code Stress Test — Node/V8 Baseline".padEnd(58) + "║");
1194 console.log("║" + ` Tests: ${testArg}`.padEnd(58) + "║");
1195 console.log("║" + " Runtime: Node (shared V8 heap, child processes)".padEnd(58) + "║");
1196 console.log("╚" + "═".repeat(58) + "╝\n");
1197​
1198 // Verify codex is available
1199 try {
1200 const { execSync } = await import("node:child_process");
1201 execSync("codex --version", { stdio: "pipe" });
1202 log("codex binary available");
1203 } catch {
1204 console.error("ERROR: codex binary not found");
1205 process.exit(1);
1207​
1208 const results: TestResult[] = [];
1209​
1210 if (testArg === "all" || testArg === "a") results.push(await testA());
1211 if (testArg === "all" || testArg === "b") results.push(await testB());
1212 if (testArg === "all" || testArg === "c") results.push(await testC());
1213 if (testArg === "all" || testArg === "gc-lab") results.push(await testGcLab());
1214 if (testArg === "all" || testArg === "concurrent") results.push(await testConcurrent());
1215​
1216 console.log("\n" + "═".repeat(60));
1217 console.log(" ALL TESTS COMPLETE");
1218 console.log("═".repeat(60));
1219 for (const r of results) {
1220 console.log(` ${r.test}: ${(r.duration_ms / 1000).toFixed(1)}s`);
1222 console.log(`\n Results: ${OUTPUT_DIR}/`);
1223​
1224 // Ensure clean exit
1225 killAllSessions();
1226 setTimeout(() => process.exit(0), 1000);
1228​
1229main().catch((err) => {
1230 console.error("Fatal:", err);
1231 killAllSessions();
1232 process.exit(1);
1233});