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

stress-test-subagent.ts

500 lines15.4 KB

1#!/usr/bin/env bun
2/**
3 * stress-test-subagent.ts — GAP 1: Subagent tree stress test.
4 *
5 * Tests how well each runtime handles N concurrent sessions, each spawning
6 * 3 subagents via plan mode. Measures event routing overhead, event
7 * throughput, and the complexity of tracking subagent lifecycles.
8 *
9 * Node side: spawns mock-codex-server in subagent mode as child processes.
10 * The manager must parse and route all events through a single process.
11 * Elixir side: uses harness with mock provider in subagent mode.
12 * Each session is a GenServer that independently handles its events.
13 *
14 * Usage:
15 * bun run scripts/stress-test-subagent.ts --runtime=node
16 * bun run scripts/stress-test-subagent.ts --runtime=elixir
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 (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 N = 5; // concurrent sessions, each with 3 subagents = 15 subagent lifecycles
41const DELTAS_PER_SESSION = 60; // split across 3 subagents (~20 each)
42const DELTA_SIZE_KB = 5;
43const DELAY_MS = 5;
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​
55function percentile(arr: number[], p: number): number {
56 if (arr.length === 0) return 0;
57 const sorted = [...arr].sort((a, b) => a - b);
58 return sorted[Math.max(0, Math.ceil((p / 100) * sorted.length) - 1)]!;
60​
61// ---------------------------------------------------------------------------
62// Session tracking
63// ---------------------------------------------------------------------------
64​
65interface SubagentStats {
66 sessionId: string;
67 totalEvents: number;
68 deltaEvents: number;
69 subagentSpawns: number;
70 subagentCompletions: number;
71 interactionBegins: number;
72 interactionEnds: number;
73 turnsCompleted: number;
74 totalPayloadBytes: number;
75 errors: string[];
76 firstEventAt: number | null;
77 lastEventAt: number | null;
79​
80function createStats(sessionId: string): SubagentStats {
81 return {
82 sessionId,
83 totalEvents: 0,
84 deltaEvents: 0,
85 subagentSpawns: 0,
86 subagentCompletions: 0,
87 interactionBegins: 0,
88 interactionEnds: 0,
89 turnsCompleted: 0,
90 totalPayloadBytes: 0,
91 errors: [],
92 firstEventAt: null,
93 lastEventAt: null,
94 };
96​
97function trackEvent(stats: SubagentStats, method: string, payload: unknown) {
98 stats.totalEvents++;
99 const now = Date.now();
100 if (!stats.firstEventAt) stats.firstEventAt = now;
101 stats.lastEventAt = now;
102​
103 try {
104 stats.totalPayloadBytes += JSON.stringify(payload).length;
105 } catch {}
106​
107 switch (method) {
108 case "item/agentMessage/delta":
109 stats.deltaEvents++;
110 break;
111 case "collab_agent_spawn_begin":
112 stats.subagentSpawns++;
113 break;
114 case "collab_agent_spawn_end":
115 stats.subagentCompletions++;
116 break;
117 case "collab_agent_interaction_begin":
118 stats.interactionBegins++;
119 break;
120 case "collab_agent_interaction_end":
121 stats.interactionEnds++;
122 break;
123 case "turn/completed":
124 stats.turnsCompleted++;
125 break;
126 }
128​
129// ---------------------------------------------------------------------------
130// Node runtime
131// ---------------------------------------------------------------------------
132​
133async function runNode() {
134 const allStats: SubagentStats[] = [];
135 const lags: number[] = [];
136 let lastLagCheck = performance.now();
137 const lagTimer = setInterval(() => {
138 const now = performance.now();
139 const lag = now - lastLagCheck - 100;
140 if (lag > 5) lags.push(lag);
141 lastLagCheck = now;
142 }, 100);
143​
144 const sessions = new Map<
145 string,
146 {
147 child: ChildProcessWithoutNullStreams;
148 rl: readline.Interface;
149 pending: Map<number, any>;
150 nextId: number;
151 codexThreadId: string | null;
152 }
153 >();
154​
155 // Start N sessions using mock-codex-server in subagent mode
156 for (let i = 0; i < N; i++) {
157 const sid = `subagent-node-${i}-${Date.now()}`;
158 const stats = createStats(sid);
159 allStats.push(stats);
160​
161 const child = spawn(
162 "bun",
163 [
164 "run",
165 "scripts/mock-codex-server.ts",
166 String(DELTAS_PER_SESSION),
167 String(DELTA_SIZE_KB),
168 String(DELAY_MS),
169 "subagent",
170 ],
171 { cwd: process.cwd(), env: process.env, stdio: ["pipe", "pipe", "pipe"] },
172 );
173​
174 const rl = readline.createInterface({ input: child.stdout });
175 const session = {
176 child,
177 rl,
178 pending: new Map<number, any>(),
179 nextId: 1,
180 codexThreadId: null as string | null,
181 };
182 sessions.set(sid, session);
183​
184 rl.on("line", (line: string) => {
185 try {
186 const msg = JSON.parse(line);
187 if (msg.id != null) {
188 const p = session.pending.get(msg.id);
189 if (p) {
190 session.pending.delete(msg.id);
191 p.resolve(msg.result ?? msg.error);
192 }
193 return;
194 }
195 if (msg.method) trackEvent(stats, msg.method, msg.params);
196 } catch {}
197 });
198 child.stderr?.resume();
199​
200 const rpc = (method: string, params: any) =>
201 new Promise<any>((resolve, reject) => {
202 const id = session.nextId++;
203 const timer = setTimeout(() => {
204 session.pending.delete(id);
205 reject(new Error("timeout"));
206 }, 30000);
207 session.pending.set(id, {
208 resolve: (v: any) => {
209 clearTimeout(timer);
210 resolve(v);
211 },
212 reject: (e: any) => {
213 clearTimeout(timer);
214 reject(e);
215 },
216 });
217 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
218 });
219​
220 try {
221 await rpc("initialize", {
222 clientInfo: { name: "stress", version: "1.0" },
223 capabilities: { experimentalApi: true },
224 });
225 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
226 const threadResult = await rpc("thread/start", { cwd: process.cwd() });
227 session.codexThreadId = threadResult?.thread?.id ?? null;
228 } catch (e) {
229 stats.errors.push(e instanceof Error ? e.message : String(e));
230 }
231 }
232​
233 log(`${sessions.size} sessions ready, sending subagent tasks...`);
234​
235 // Send turns with plan mode to all sessions
236 for (const stats of allStats) {
237 const session = sessions.get(stats.sessionId);
238 if (!session || stats.errors.length > 0) continue;
239​
240 const rpc = (method: string, params: any) =>
241 new Promise<any>((resolve, reject) => {
242 const id = session.nextId++;
243 const timer = setTimeout(() => {
244 session.pending.delete(id);
245 reject(new Error("timeout"));
246 }, 30000);
247 session.pending.set(id, {
248 resolve: (v: any) => {
249 clearTimeout(timer);
250 resolve(v);
251 },
252 reject: (e: any) => {
253 clearTimeout(timer);
254 reject(e);
255 },
256 });
257 session.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
258 });
259​
260 rpc("turn/start", {
261 threadId: session.codexThreadId,
262 input: [
263 {
264 type: "text",
265 text: "Build microservices: auth, posts, comments. Delegate each to a subagent.",
266 },
267 ],
268 collaborationMode: { mode: "plan" },
269 }).catch((e) => stats.errors.push(e instanceof Error ? e.message : String(e)));
270 }
271​
272 // Wait for all to complete (max 60s)
273 const end = Date.now() + 60_000;
274 while (Date.now() < end) {
275 if (allStats.every((s) => s.turnsCompleted > 0 || s.errors.length > 0)) break;
276 await sleep(500);
277 }
278​
279 clearInterval(lagTimer);
280​
281 for (const [, session] of sessions) {
282 try {
283 session.child.kill();
284 } catch {}
285 }
286​
287 return { allStats, lags };
289​
290// ---------------------------------------------------------------------------
291// Elixir runtime
292// ---------------------------------------------------------------------------
293​
294async function runElixir() {
295 if (!HarnessClientManager) throw new Error("HarnessClientManager not available — import failed");
296 const allStats: SubagentStats[] = [];
297​
298 const mgr = new HarnessClientManager({
299 harnessPort: HARNESS_PORT,
300 harnessSecret: HARNESS_SECRET,
301 onEvent: (raw: any) => {
302 const stats = allStats.find((s) => s.sessionId === raw.threadId);
303 if (stats) trackEvent(stats, raw.method, raw.payload);
304 },
305 onSessionChanged: () => {},
306 onDisconnect: () => {},
307 onReconnect: () => {},
308 });
309​
310 await mgr.connect();
311 log("Connected to harness");
312​
313 // Baseline metrics
314 const baseline = (await fetch(`http://127.0.0.1:${HARNESS_PORT}/api/metrics`).then((r) =>
315 r.json(),
316 )) as any;
317 log(
318 `Baseline: ${baseline.beam.process_count} processes, ${(baseline.beam.total_memory / 1024 / 1024).toFixed(1)}MB`,
319 );
320​
321 // Start N sessions with subagent mock mode
322 for (let i = 0; i < N; i++) {
323 const sid = `subagent-elixir-${i}-${Date.now()}`;
324 const stats = createStats(sid);
325 allStats.push(stats);
326​
327 try {
328 await mgr.startSession({
329 threadId: sid,
330 provider: "mock",
331 cwd: process.cwd(),
332 providerOptions: {
333 mock: {
334 deltaCount: DELTAS_PER_SESSION,
335 deltaSizeKb: DELTA_SIZE_KB,
336 delayMs: DELAY_MS,
337 mode: "subagent",
338 },
339 },
340 });
341 } catch (e) {
342 stats.errors.push(e instanceof Error ? e.message : String(e));
343 }
344 }
345​
346 log(
347 `${allStats.filter((s) => s.errors.length === 0).length} sessions ready, sending subagent tasks...`,
348 );
349​
350 // Send turns
351 for (const stats of allStats) {
352 if (stats.errors.length > 0) continue;
353 mgr
354 .sendTurn(stats.sessionId, {
355 input: [
356 {
357 type: "text",
358 text: "Build microservices: auth, posts, comments. Delegate each to a subagent.",
359 },
360 ],
361 collaborationMode: { mode: "plan" },
362 })
363 .catch((e: any) => stats.errors.push(e instanceof Error ? e.message : String(e)));
364 }
365​
366 // Wait for all to complete (max 60s)
367 const end = Date.now() + 60_000;
368 const metricSnapshots: any[] = [];
369 while (Date.now() < end) {
370 if (allStats.every((s) => s.turnsCompleted > 0 || s.errors.length > 0)) break;
371 try {
372 const m = await fetch(`http://127.0.0.1:${HARNESS_PORT}/api/metrics`).then((r) => r.json());
373 metricSnapshots.push(m);
374 } catch {}
375 await sleep(1000);
376 }
377​
378 // Final metrics
379 const postMetrics = (await fetch(`http://127.0.0.1:${HARNESS_PORT}/api/metrics`).then((r) =>
380 r.json(),
381 )) as any;
382 const sessionData = (postMetrics.sessions ?? [])
383 .filter((s: any) => String(s.thread_id ?? "").includes("subagent-elixir"))
384 .map((s: any) => ({ memory: s.memory, gc_count: s.gc_count, reductions: s.reductions }));
385​
386 try {
387 await mgr.stopAll();
388 } catch {}
389 mgr.disconnect();
390​
391 return { allStats, lags: [] as number[], metricSnapshots, sessionData, postMetrics };
393​
394// ---------------------------------------------------------------------------
395// Main
396// ---------------------------------------------------------------------------
397​
398async function main() {
399 console.log("\n" + "╔" + "═".repeat(58) + "╗");
400 console.log("║" + ` GAP 1: Subagent Tree Stress Test — ${RUNTIME}`.padEnd(58) + "║");
401 console.log(
402 "║" + ` ${N} sessions × 3 subagents = ${N * 3} subagent lifecycles`.padEnd(58) + "║",
403 );
404 console.log("║" + ` ${DELTAS_PER_SESSION} deltas/session × ${DELTA_SIZE_KB}KB`.padEnd(58) + "║");
405 console.log("╚" + "═".repeat(58) + "╝\n");
406​
407 const startedAt = Date.now();
408 const result = RUNTIME === "elixir" ? await runElixir() : await runNode();
409 const completedAt = Date.now();
410​
411 // Summary
412 console.log("\n" + "═".repeat(60));
413 console.log(" SUBAGENT STRESS TEST RESULTS");
414 console.log("═".repeat(60));
415​
416 const { allStats, lags } = result;
417​
418 for (const stats of allStats) {
419 console.log(
420 ` [${stats.sessionId.slice(0, 30)}] events=${stats.totalEvents} deltas=${stats.deltaEvents} spawns=${stats.subagentSpawns} completions=${stats.subagentCompletions} turns=${stats.turnsCompleted}${stats.errors.length > 0 ? " ERRORS=" + stats.errors.length : ""}`,
421 );
422 }
423​
424 const totalEvents = allStats.reduce((s, st) => s + st.totalEvents, 0);
425 const totalDeltas = allStats.reduce((s, st) => s + st.deltaEvents, 0);
426 const totalSpawns = allStats.reduce((s, st) => s + st.subagentSpawns, 0);
427 const totalPayload = allStats.reduce((s, st) => s + st.totalPayloadBytes, 0);
428 const duration = (completedAt - startedAt) / 1000;
429​
430 console.log(
431 `\n Total: ${totalEvents} events (${totalDeltas} deltas, ${totalSpawns} spawns), ${(totalPayload / 1024 / 1024).toFixed(1)}MB payload`,
432 );
433 console.log(
434 ` Duration: ${duration.toFixed(1)}s, Throughput: ${Math.round(totalEvents / duration)} events/s`,
435 );
436​
437 if (RUNTIME === "node" && lags.length > 0) {
438 console.log(
439 ` Event loop lag: p50=${percentile(lags, 50).toFixed(1)}ms p99=${percentile(lags, 99).toFixed(1)}ms max=${Math.max(...lags).toFixed(1)}ms`,
440 );
441 }
442​
443 // Verify subagent lifecycle integrity
444 const integrityOk = allStats.every(
445 (s) =>
446 s.errors.length === 0 &&
447 s.subagentSpawns === 3 &&
448 s.subagentCompletions === 3 &&
449 s.interactionBegins === 3 &&
450 s.interactionEnds === 3,
451 );
452 console.log(
453 `\n Subagent lifecycle integrity: ${integrityOk ? "PASS (3 spawns, 3 completions per session)" : "FAIL"}`,
454 );
455​
456 const output = {
457 test: "subagent",
458 runtime: RUNTIME,
459 startedAt,
460 completedAt,
461 duration_ms: completedAt - startedAt,
462 config: {
463 sessions: N,
464 deltasPerSession: DELTAS_PER_SESSION,
465 deltaSizeKb: DELTA_SIZE_KB,
466 delayMs: DELAY_MS,
467 },
468 sessions: allStats,
469 summary: {
470 sessionCount: N,
471 completed: allStats.filter((s) => s.turnsCompleted > 0).length,
472 totalEvents,
473 totalDeltas,
474 totalSubagentSpawns: totalSpawns,
475 totalPayloadMb: Math.round((totalPayload / 1024 / 1024) * 10) / 10,
476 eventsPerSecond: Math.round(totalEvents / duration),
477 lifecycleIntegrity: integrityOk,
478 ...(RUNTIME === "node" && lags.length > 0
479 ? {
480 lagP50_ms: Math.round(percentile(lags, 50) * 10) / 10,
481 lagP99_ms: Math.round(percentile(lags, 99) * 10) / 10,
482 lagMax_ms: Math.round(Math.max(...lags) * 10) / 10,
483 }
484 : {}),
485 ...("sessionData" in result ? { perSessionMetrics: (result as any).sessionData } : {}),
486 },
487 };
488​
489 const filename = `${RUNTIME}-subagent-${Date.now()}.json`;
490 writeFileSync(`${OUTPUT_DIR}/${filename}`, JSON.stringify(output, null, 2));
491 log(`Results written to ${OUTPUT_DIR}/${filename}`);
492 console.log("═".repeat(60));
493​
494 setTimeout(() => process.exit(0), 2000);
496​
497main().catch((err) => {
498 console.error("Fatal:", err);
499 process.exit(1);
500});