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

stress-test-exception.ts

504 lines16.0 KB

1#!/usr/bin/env bun
2/**
3 * stress-test-exception.ts — GAP 4: Exception injection test.
4 *
5 * Start N sessions streaming simultaneously, then crash one mid-stream.
6 * Verify the other sessions continue unaffected.
7 *
8 * Node: crash one child process → manager must handle the error, but the
9 * event loop continues serving other sessions (expected: no cascading).
10 * Elixir: crash one GenServer → DynamicSupervisor handles it, other
11 * GenServers are completely independent (expected: zero impact).
12 *
13 * Uses mock provider in "crash" mode for the victim session.
14 *
15 * Usage:
16 * bun run scripts/stress-test-exception.ts --runtime=node
17 * bun run scripts/stress-test-exception.ts --runtime=elixir
18 */
19​
20import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
21import readline from "node:readline";
22import { writeFileSync, mkdirSync } from "node:fs";
23​
24let HarnessClientManager: any;
25try {
26 const mod = await import("../apps/server/src/provider/Layers/HarnessClientManager.ts");
27 HarnessClientManager = mod.HarnessClientManager;
28} catch (err) {
29 console.warn("Failed to import HarnessClientManager:", err);
31​
32// ---------------------------------------------------------------------------
33// Config
34// ---------------------------------------------------------------------------
35​
36const OUTPUT_DIR = `${process.cwd()}/output/stress-test`;
37const RUNTIME = process.argv.find((a) => a.startsWith("--runtime="))?.split("=")[1] || "node";
38const HARNESS_PORT = Number(process.env.T3CODE_HARNESS_PORT ?? 4321);
39const HARNESS_SECRET = process.env.T3CODE_HARNESS_SECRET ?? "dev-harness-secret";
40const SURVIVOR_COUNT = 5;
41const DELTA_COUNT = 200;
42const DELTA_SIZE_KB = 5;
43const DELAY_MS = 10;
44​
45mkdirSync(OUTPUT_DIR, { recursive: true });
46​
47const t0 = Date.now();
48const ts = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
49const log = (msg: string) => console.log(` ${ts()} ${msg}`);
50​
51function sleep(ms: number): Promise<void> {
52 return new Promise((r) => setTimeout(r, ms));
54​
55// ---------------------------------------------------------------------------
56// Session tracking
57// ---------------------------------------------------------------------------
58​
59interface SessionStats {
60 id: string;
61 role: "victim" | "survivor";
62 deltaCount: number;
63 turnsCompleted: number;
64 errors: string[];
65 crashDetected: boolean;
66 continuedAfterCrash: boolean;
68​
69function createStats(id: string, role: "victim" | "survivor"): SessionStats {
70 return {
71 id,
72 role,
73 deltaCount: 0,
74 turnsCompleted: 0,
75 errors: [],
76 crashDetected: false,
77 continuedAfterCrash: false,
78 };
80​
81// ---------------------------------------------------------------------------
82// Node runtime
83// ---------------------------------------------------------------------------
84​
85async function runNode() {
86 const allStats: SessionStats[] = [];
87 const sessions = new Map<
88 string,
89 {
90 child: ChildProcessWithoutNullStreams;
91 rl: readline.Interface;
92 pending: Map<number, any>;
93 nextId: number;
94 codexThreadId: string | null;
95 }
96 >();
97​
98 function spawnMock(id: string, mode: string, deltaCount: number) {
99 const child = spawn(
100 "bun",
101 [
102 "run",
103 "scripts/mock-codex-server.ts",
104 String(deltaCount),
105 String(DELTA_SIZE_KB),
106 String(DELAY_MS),
107 mode,
108 ],
109 { cwd: process.cwd(), env: process.env, stdio: ["pipe", "pipe", "pipe"] },
110 );
111​
112 const rl = readline.createInterface({ input: child.stdout });
113 const session = {
114 child,
115 rl,
116 pending: new Map<number, any>(),
117 nextId: 1,
118 codexThreadId: null as string | null,
119 };
120 sessions.set(id, session);
121 child.stderr?.resume();
122 return session;
123 }
124​
125 function rpc(session: ReturnType<typeof spawnMock>, method: string, params: any) {
126 return new Promise<any>((resolve, reject) => {
127 const id = session.nextId++;
128 const timer = setTimeout(() => {
129 session.pending.delete(id);
130 reject(new Error("timeout"));
131 }, 30000);
132 session.pending.set(id, {
133 resolve: (v: any) => {
134 clearTimeout(timer);
135 resolve(v);
136 },
137 reject: (e: any) => {
138 clearTimeout(timer);
139 reject(e);
140 },
141 });
142 session.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
143 });
144 }
145​
146 // Start victim session (will crash after ~10 deltas)
147 const victimId = `victim-node-${Date.now()}`;
148 const victimStats = createStats(victimId, "victim");
149 allStats.push(victimStats);
150​
151 const victimSession = spawnMock(victimId, "crash", DELTA_COUNT);
152 victimSession.rl.on("line", (line: string) => {
153 try {
154 const msg = JSON.parse(line);
155 if (msg.id != null) {
156 const p = victimSession.pending.get(msg.id);
157 if (p) {
158 victimSession.pending.delete(msg.id);
159 if (msg.error) {
160 p.reject(
161 new Error(
162 typeof msg.error === "object" ? JSON.stringify(msg.error) : String(msg.error),
163 ),
164 );
165 } else {
166 p.resolve(msg.result);
167 }
168 }
169 return;
170 }
171 if (msg.method === "item/agentMessage/delta") victimStats.deltaCount++;
172 if (msg.method === "turn/completed") victimStats.turnsCompleted++;
173 } catch {}
174 });
175​
176 victimSession.child.on("exit", (code) => {
177 victimStats.crashDetected = true;
178 victimStats.errors.push(`Process crashed with exit code ${code}`);
179 log(`VICTIM CRASHED (exit code ${code}) after ${victimStats.deltaCount} deltas`);
180 });
181​
182 await rpc(victimSession, "initialize", {
183 clientInfo: { name: "stress", version: "1.0" },
184 capabilities: {},
185 });
186 victimSession.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
187 const victimThread = await rpc(victimSession, "thread/start", { cwd: process.cwd() });
188 victimSession.codexThreadId = victimThread?.thread?.id ?? null;
189​
190 // Start survivor sessions (normal mode, will complete)
191 const survivorSessions: Array<{ session: ReturnType<typeof spawnMock>; stats: SessionStats }> =
192 [];
193 for (let i = 0; i < SURVIVOR_COUNT; i++) {
194 const sid = `survivor-node-${i}-${Date.now()}`;
195 const stats = createStats(sid, "survivor");
196 allStats.push(stats);
197​
198 const session = spawnMock(sid, "normal", DELTA_COUNT);
199 session.rl.on("line", (line: string) => {
200 try {
201 const msg = JSON.parse(line);
202 if (msg.id != null) {
203 const p = session.pending.get(msg.id);
204 if (p) {
205 session.pending.delete(msg.id);
206 if (msg.error) {
207 p.reject(
208 new Error(
209 typeof msg.error === "object" ? JSON.stringify(msg.error) : String(msg.error),
210 ),
211 );
212 } else {
213 p.resolve(msg.result);
214 }
215 }
216 return;
217 }
218 if (msg.method === "item/agentMessage/delta") {
219 stats.deltaCount++;
220 // Check if this happened after the victim crashed
221 if (victimStats.crashDetected) stats.continuedAfterCrash = true;
222 }
223 if (msg.method === "turn/completed") stats.turnsCompleted++;
224 } catch {}
225 });
226​
227 await rpc(session, "initialize", {
228 clientInfo: { name: "stress", version: "1.0" },
229 capabilities: {},
230 });
231 session.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
232 const sThread = await rpc(session, "thread/start", { cwd: process.cwd() });
233 session.codexThreadId = sThread?.thread?.id ?? null;
234 survivorSessions.push({ session, stats });
235 }
236​
237 log(`1 victim + ${SURVIVOR_COUNT} survivors ready`);
238​
239 // Send turns to ALL simultaneously (victim will crash mid-stream)
240 log("Sending turns to all sessions (victim will crash mid-stream)...");
241​
242 rpc(victimSession, "turn/start", {
243 threadId: victimSession.codexThreadId,
244 input: [{ type: "text", text: "crash test" }],
245 }).catch(() => {});
246​
247 for (const { session, stats } of survivorSessions) {
248 rpc(session, "turn/start", {
249 threadId: session.codexThreadId,
250 input: [{ type: "text", text: "survivor test" }],
251 }).catch((e) => stats.errors.push(e instanceof Error ? e.message : String(e)));
252 }
253​
254 // Wait for all survivors to complete (max 60s)
255 const end = Date.now() + 60_000;
256 while (Date.now() < end) {
257 const survivorsCompleted = survivorSessions.every(
258 ({ stats }) => stats.turnsCompleted > 0 || stats.errors.length > 0,
259 );
260 if (survivorsCompleted) break;
261 await sleep(500);
262 }
263​
264 // Kill remaining
265 for (const [, session] of sessions) {
266 try {
267 session.child.kill();
268 } catch {}
269 }
270​
271 return { allStats };
273​
274// ---------------------------------------------------------------------------
275// Elixir runtime
276// ---------------------------------------------------------------------------
277​
278async function runElixir() {
279 if (!HarnessClientManager) throw new Error("HarnessClientManager not available — import failed");
280 const allStats: SessionStats[] = [];
281 let victimCrashTime: number | null = null;
282​
283 const mgr = new HarnessClientManager({
284 harnessPort: HARNESS_PORT,
285 harnessSecret: HARNESS_SECRET,
286 onEvent: (raw: any) => {
287 const stats = allStats.find((s) => s.id === raw.threadId);
288 if (!stats) return;
289​
290 if (raw.method === "item/agentMessage/delta") {
291 stats.deltaCount++;
292 if (stats.role === "survivor" && victimCrashTime != null) {
293 stats.continuedAfterCrash = true;
294 }
295 }
296 if (raw.method === "turn/completed") stats.turnsCompleted++;
297 if (raw.method === "session/exited" || raw.method === "session/error") {
298 if (stats.role === "victim") {
299 stats.crashDetected = true;
300 victimCrashTime = Date.now();
301 log(`VICTIM CRASHED after ${stats.deltaCount} deltas`);
302 }
303 }
304 },
305 onSessionChanged: () => {},
306 onDisconnect: () => {},
307 onReconnect: () => {},
308 });
309​
310 await mgr.connect();
311 log("Connected to harness");
312​
313 const METRICS_URL = `http://127.0.0.1:${HARNESS_PORT}/api/metrics`;
314​
315 // Start victim session (crash mode)
316 const victimId = `victim-elixir-${Date.now()}`;
317 const victimStats = createStats(victimId, "victim");
318 allStats.push(victimStats);
319​
320 await mgr.startSession({
321 threadId: victimId,
322 provider: "mock",
323 cwd: process.cwd(),
324 providerOptions: {
325 mock: {
326 deltaCount: DELTA_COUNT,
327 deltaSizeKb: DELTA_SIZE_KB,
328 delayMs: DELAY_MS,
329 mode: "crash",
330 },
331 },
332 });
333​
334 // Start survivor sessions (normal mode)
335 for (let i = 0; i < SURVIVOR_COUNT; i++) {
336 const sid = `survivor-elixir-${i}-${Date.now()}`;
337 const stats = createStats(sid, "survivor");
338 allStats.push(stats);
339​
340 await mgr.startSession({
341 threadId: sid,
342 provider: "mock",
343 cwd: process.cwd(),
344 providerOptions: {
345 mock: {
346 deltaCount: DELTA_COUNT,
347 deltaSizeKb: DELTA_SIZE_KB,
348 delayMs: DELAY_MS,
349 mode: "normal",
350 },
351 },
352 });
353 }
354​
355 log(`1 victim + ${SURVIVOR_COUNT} survivors ready`);
356​
357 // Check metrics before
358 let preMetrics: any = { sessions: [], beam: { process_count: 0 } };
359 try {
360 const res = await fetch(METRICS_URL);
361 if (res.ok) preMetrics = await res.json();
362 } catch (e) {
363 log(`Warning: Could not fetch pre-crash metrics: ${e}`);
364 }
365 const preSessions = (preMetrics.sessions ?? []).length;
366 log(
367 `Pre-crash: ${preSessions} sessions active, ${preMetrics.beam?.process_count ?? 0} BEAM processes`,
368 );
369​
370 // Send turns to ALL
371 log("Sending turns to all sessions (victim will crash mid-stream)...");
372 for (const stats of allStats) {
373 mgr
374 .sendTurn(stats.id, {
375 input: [{ type: "text", text: stats.role === "victim" ? "crash test" : "survivor test" }],
376 })
377 .catch((e: any) => stats.errors.push(e instanceof Error ? e.message : String(e)));
378 }
379​
380 // Wait for survivors to complete (max 60s)
381 const end = Date.now() + 60_000;
382 while (Date.now() < end) {
383 const survivorsCompleted = allStats
384 .filter((s) => s.role === "survivor")
385 .every((s) => s.turnsCompleted > 0 || s.errors.length > 0);
386 if (survivorsCompleted) break;
387 await sleep(500);
388 }
389​
390 // Post-crash metrics
391 let postMetrics: any = { sessions: [], beam: { process_count: 0 } };
392 try {
393 const res = await fetch(METRICS_URL);
394 if (res.ok) postMetrics = await res.json();
395 } catch (e) {
396 log(`Warning: Could not fetch post-crash metrics: ${e}`);
397 }
398 const postSessions = (postMetrics.sessions ?? []).length;
399 log(`Post-crash: ${postSessions} sessions active (victim should be gone)`);
400​
401 try {
402 await mgr.stopAll();
403 } catch {}
404 mgr.disconnect();
405​
406 return { allStats, preSessionCount: preSessions, postSessionCount: postSessions };
408​
409// ---------------------------------------------------------------------------
410// Main
411// ---------------------------------------------------------------------------
412​
413async function main() {
414 console.log("\n" + "╔" + "═".repeat(58) + "╗");
415 console.log("║" + ` GAP 4: Exception Injection Test — ${RUNTIME}`.padEnd(58) + "║");
416 console.log("║" + ` 1 victim (crash) + ${SURVIVOR_COUNT} survivors (normal)`.padEnd(58) + "║");
417 console.log("║" + ` Verify crash isolation`.padEnd(58) + "║");
418 console.log("╚" + "═".repeat(58) + "╝\n");
419​
420 const startedAt = Date.now();
421 const result = RUNTIME === "elixir" ? await runElixir() : await runNode();
422 const completedAt = Date.now();
423​
424 console.log("\n" + "═".repeat(60));
425 console.log(" EXCEPTION INJECTION RESULTS");
426 console.log("═".repeat(60));
427​
428 const { allStats } = result;
429 const victim = allStats.find((s) => s.role === "victim")!;
430 const survivors = allStats.filter((s) => s.role === "survivor");
431​
432 console.log(`\n Victim:`);
433 console.log(` Crash detected: ${victim.crashDetected ? "YES" : "NO"}`);
434 console.log(` Deltas before crash: ${victim.deltaCount}`);
435​
436 console.log(`\n Survivors (${survivors.length}):`);
437 let allSurvived = true;
438 for (const s of survivors) {
439 const ok = s.turnsCompleted > 0 && s.errors.length === 0;
440 if (!ok) allSurvived = false;
441 console.log(
442 ` [${s.id.slice(0, 30)}] turns=${s.turnsCompleted} deltas=${s.deltaCount} continuedAfterCrash=${s.continuedAfterCrash} ${ok ? "OK" : "FAILED"}`,
443 );
444 }
445​
446 const someSurvivorContinuedAfterCrash = survivors.some((s) => s.continuedAfterCrash);
447 const isolationVerified = victim.crashDetected && allSurvived && someSurvivorContinuedAfterCrash;
448 console.log(
449 `\n CRASH ISOLATION: ${isolationVerified ? "VERIFIED — crash did NOT cascade" : "FAILED"}`,
450 );
451​
452 if (RUNTIME === "elixir" && "preSessionCount" in result) {
453 const r = result as any;
454 console.log(
455 ` Sessions: ${r.preSessionCount} → ${r.postSessionCount} (victim removed by DynamicSupervisor)`,
456 );
457 }
458​
459 const output = {
460 test: "exception-injection",
461 runtime: RUNTIME,
462 startedAt,
463 completedAt,
464 duration_ms: completedAt - startedAt,
465 config: {
466 survivorCount: SURVIVOR_COUNT,
467 deltaCount: DELTA_COUNT,
468 deltaSizeKb: DELTA_SIZE_KB,
469 delayMs: DELAY_MS,
470 },
471 victim: {
472 id: victim.id,
473 crashDetected: victim.crashDetected,
474 deltasBeforeCrash: victim.deltaCount,
475 errors: victim.errors,
476 },
477 survivors: survivors.map((s) => ({
478 id: s.id,
479 turnsCompleted: s.turnsCompleted,
480 deltaCount: s.deltaCount,
481 continuedAfterCrash: s.continuedAfterCrash,
482 errors: s.errors,
483 })),
484 summary: {
485 crashIsolationVerified: isolationVerified,
486 victimCrashed: victim.crashDetected,
487 survivorsCompleted: survivors.filter((s) => s.turnsCompleted > 0).length,
488 survivorsContinuedAfterCrash: survivors.filter((s) => s.continuedAfterCrash).length,
489 totalSurvivors: survivors.length,
490 },
491 };
492​
493 const filename = `${RUNTIME}-exception-${Date.now()}.json`;
494 writeFileSync(`${OUTPUT_DIR}/${filename}`, JSON.stringify(output, null, 2));
495 log(`Results written to ${OUTPUT_DIR}/${filename}`);
496 console.log("═".repeat(60));
497​
498 setTimeout(() => process.exit(0), 2000);
500​
501main().catch((err) => {
502 console.error("Fatal:", err);
503 process.exit(1);
504});