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

stress-test-scale50.ts

529 lines17.1 KB

1#!/usr/bin/env bun
2/**
3 * stress-test-scale50.ts — GAP 3: 50-session scale test.
4 *
5 * Scales up the concurrent session test from 10 → 50 sessions.
6 * All sessions use the mock provider (200 × 1KB deltas).
7 * Measures throughput per-session, event loop lag (Node), scheduler
8 * utilization (Elixir), and overall system behavior under load.
9 *
10 * Usage:
11 * bun run scripts/stress-test-scale50.ts --runtime=node
12 * bun run scripts/stress-test-scale50.ts --runtime=elixir
13 */
14​
15import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
16import readline from "node:readline";
17import { writeFileSync, mkdirSync } from "node:fs";
18import v8 from "node:v8";
19​
20let HarnessClientManager: any;
21try {
22 const mod = await import("../apps/server/src/provider/Layers/HarnessClientManager.ts");
23 HarnessClientManager = mod.HarnessClientManager;
24} catch (err) {
25 console.warn("Failed to import HarnessClientManager:", err);
27​
28// ---------------------------------------------------------------------------
29// Config
30// ---------------------------------------------------------------------------
31​
32const OUTPUT_DIR = `${process.cwd()}/output/stress-test`;
33const RUNTIME = process.argv.find((a) => a.startsWith("--runtime="))?.split("=")[1] || "node";
34const HARNESS_PORT = Number(process.env.T3CODE_HARNESS_PORT ?? 4321);
35const HARNESS_SECRET = process.env.T3CODE_HARNESS_SECRET ?? "dev-harness-secret";
36const N = 50;
37const DELTA_COUNT = 200;
38const DELTA_SIZE_KB = 1;
39const DELAY_MS = 5;
40​
41mkdirSync(OUTPUT_DIR, { recursive: true });
42​
43const t0 = Date.now();
44const ts = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
45const log = (msg: string) => console.log(` ${ts()} ${msg}`);
46​
47function sleep(ms: number): Promise<void> {
48 return new Promise((r) => setTimeout(r, ms));
50​
51function percentile(arr: number[], p: number): number {
52 if (arr.length === 0) return 0;
53 const sorted = [...arr].sort((a, b) => a - b);
54 return sorted[Math.max(0, Math.ceil((p / 100) * sorted.length) - 1)]!;
56​
57// ---------------------------------------------------------------------------
58// Session tracking
59// ---------------------------------------------------------------------------
60​
61interface SessionStats {
62 id: string;
63 deltaCount: number;
64 turnsCompleted: number;
65 firstDeltaAt: number | null;
66 lastDeltaAt: number | null;
67 errors: string[];
69​
70function createStats(id: string): SessionStats {
71 return {
72 id,
73 deltaCount: 0,
74 turnsCompleted: 0,
75 firstDeltaAt: null,
76 lastDeltaAt: null,
77 errors: [],
78 };
80​
81// ---------------------------------------------------------------------------
82// Node runtime — 50 child processes, single manager
83// ---------------------------------------------------------------------------
84​
85async function runNode() {
86 const allStats: SessionStats[] = [];
87 const eventTimestamps: number[] = [];
88​
89 // Event loop lag
90 const lags: number[] = [];
91 let lastLagCheck = performance.now();
92 const lagTimer = setInterval(() => {
93 const now = performance.now();
94 const lag = now - lastLagCheck - 100;
95 if (lag > 5) lags.push(lag);
96 lastLagCheck = now;
97 }, 100);
98​
99 const sessions = new Map<
100 string,
101 {
102 child: ChildProcessWithoutNullStreams;
103 rl: readline.Interface;
104 pending: Map<number, any>;
105 nextId: number;
106 codexThreadId: string | null;
107 }
108 >();
109​
110 // Spawn 50 mock sessions
111 log(`Starting ${N} mock child processes...`);
112 const startPhaseStart = Date.now();
113​
114 for (let i = 0; i < N; i++) {
115 const sid = `scale50-node-${i}-${Date.now()}`;
116 const stats = createStats(sid);
117 allStats.push(stats);
118​
119 const child = spawn(
120 "bun",
121 [
122 "run",
123 "scripts/mock-codex-server.ts",
124 String(DELTA_COUNT),
125 String(DELTA_SIZE_KB),
126 String(DELAY_MS),
127 "normal",
128 ],
129 { cwd: process.cwd(), env: process.env, stdio: ["pipe", "pipe", "pipe"] },
130 );
131​
132 const rl = readline.createInterface({ input: child.stdout });
133 const session = {
134 child,
135 rl,
136 pending: new Map<number, any>(),
137 nextId: 1,
138 codexThreadId: null as string | null,
139 };
140 sessions.set(sid, session);
141​
142 rl.on("line", (line: string) => {
143 try {
144 const msg = JSON.parse(line);
145 if (msg.id != null) {
146 const p = session.pending.get(msg.id);
147 if (p) {
148 session.pending.delete(msg.id);
149 if (msg.error) {
150 p.reject(
151 new Error(
152 typeof msg.error === "object" ? JSON.stringify(msg.error) : String(msg.error),
153 ),
154 );
155 } else {
156 p.resolve(msg.result);
157 }
158 }
159 return;
160 }
161 if (msg.method === "item/agentMessage/delta") {
162 stats.deltaCount++;
163 const now = Date.now();
164 eventTimestamps.push(now);
165 if (!stats.firstDeltaAt) stats.firstDeltaAt = now;
166 stats.lastDeltaAt = now;
167 }
168 if (msg.method === "turn/completed") stats.turnsCompleted++;
169 } catch {}
170 });
171 child.stderr?.resume();
172​
173 const rpc = (method: string, params: any) =>
174 new Promise<any>((resolve, reject) => {
175 const id = session.nextId++;
176 const timer = setTimeout(() => {
177 session.pending.delete(id);
178 reject(new Error("timeout"));
179 }, 30000);
180 session.pending.set(id, {
181 resolve: (v: any) => {
182 clearTimeout(timer);
183 resolve(v);
184 },
185 reject: (e: any) => {
186 clearTimeout(timer);
187 reject(e);
188 },
189 });
190 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
191 });
192​
193 try {
194 await rpc("initialize", { clientInfo: { name: "stress", version: "1.0" }, capabilities: {} });
195 child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "initialized" }) + "\n");
196 const threadResult = await rpc("thread/start", { cwd: process.cwd() });
197 session.codexThreadId = threadResult?.thread?.id ?? null;
198 } catch (e) {
199 stats.errors.push(e instanceof Error ? e.message : String(e));
200 }
201​
202 // Log progress every 10 sessions
203 if ((i + 1) % 10 === 0) log(` ${i + 1}/${N} sessions started`);
204 }
205​
206 const startupDuration = (Date.now() - startPhaseStart) / 1000;
207 log(`All ${N} sessions started in ${startupDuration.toFixed(1)}s`);
208​
209 // Heap snapshot before sending
210 const preHeap = process.memoryUsage();
211 log(`Pre-send heap: ${(preHeap.heapUsed / 1024 / 1024).toFixed(1)}MB`);
212​
213 // Send turns to ALL simultaneously
214 log("Sending turns to all 50 sessions...");
215 for (const stats of allStats) {
216 const session = sessions.get(stats.id);
217 if (!session || stats.errors.length > 0) continue;
218​
219 const rpc = (method: string, params: any) =>
220 new Promise<any>((resolve, reject) => {
221 const id = session.nextId++;
222 const timer = setTimeout(() => {
223 session.pending.delete(id);
224 reject(new Error("timeout"));
225 }, 60000);
226 session.pending.set(id, {
227 resolve: (v: any) => {
228 clearTimeout(timer);
229 resolve(v);
230 },
231 reject: (e: any) => {
232 clearTimeout(timer);
233 reject(e);
234 },
235 });
236 session.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
237 });
238​
239 rpc("turn/start", {
240 threadId: session.codexThreadId,
241 input: [{ type: "text", text: "scale50 test" }],
242 }).catch((e) => stats.errors.push(e instanceof Error ? e.message : String(e)));
243 }
244​
245 // Wait for completion (max 2 min)
246 const end = Date.now() + 120_000;
247 const metricSnapshots: Array<{
248 elapsed_ms: number;
249 heapUsed: number;
250 rss: number;
251 completed: number;
252 totalDeltas: number;
253 }> = [];
254 while (Date.now() < end) {
255 const completed = allStats.filter((s) => s.turnsCompleted > 0).length;
256 const totalDeltas = allStats.reduce((s, st) => s + st.deltaCount, 0);
257 const mem = process.memoryUsage();
258 metricSnapshots.push({
259 elapsed_ms: Date.now() - t0,
260 heapUsed: mem.heapUsed,
261 rss: mem.rss,
262 completed,
263 totalDeltas,
264 });
265​
266 if (
267 completed === allStats.length ||
268 allStats.every((s) => s.turnsCompleted > 0 || s.errors.length > 0)
269 )
270 break;
271 process.stdout.write(
272 `\r ${ts()} completed=${completed}/${N} deltas=${totalDeltas} heap=${(mem.heapUsed / 1024 / 1024).toFixed(1)}MB`,
273 );
274 await sleep(1000);
275 }
276​
277 clearInterval(lagTimer);
278 console.log("");
279​
280 // Kill all
281 for (const [, session] of sessions) {
282 try {
283 session.child.kill();
284 } catch {}
285 }
286​
287 return { allStats, eventTimestamps, lags, metricSnapshots, startupDuration };
289​
290// ---------------------------------------------------------------------------
291// Elixir runtime — 50 GenServer processes
292// ---------------------------------------------------------------------------
293​
294async function runElixir() {
295 if (!HarnessClientManager) throw new Error("HarnessClientManager not available — import failed");
296 const allStats: SessionStats[] = [];
297 const eventTimestamps: number[] = [];
298​
299 const mgr = new HarnessClientManager({
300 harnessPort: HARNESS_PORT,
301 harnessSecret: HARNESS_SECRET,
302 onEvent: (raw: any) => {
303 const stats = allStats.find((s) => s.id === raw.threadId);
304 if (!stats) return;
305 if (raw.method === "item/agentMessage/delta") {
306 stats.deltaCount++;
307 const now = Date.now();
308 eventTimestamps.push(now);
309 if (!stats.firstDeltaAt) stats.firstDeltaAt = now;
310 stats.lastDeltaAt = now;
311 }
312 if (raw.method === "turn/completed") stats.turnsCompleted++;
313 },
314 onSessionChanged: () => {},
315 onDisconnect: () => {},
316 onReconnect: () => {},
317 });
318​
319 await mgr.connect();
320 log("Connected to harness");
321​
322 const METRICS_URL = `http://127.0.0.1:${HARNESS_PORT}/api/metrics`;
323 const baseline = (await fetch(METRICS_URL).then((r) => r.json())) as any;
324 log(
325 `Baseline: ${baseline.beam.process_count} processes, ${(baseline.beam.total_memory / 1024 / 1024).toFixed(1)}MB`,
326 );
327​
328 // Start 50 mock sessions
329 log(`Starting ${N} sessions...`);
330 const startPhaseStart = Date.now();
331​
332 for (let i = 0; i < N; i++) {
333 const sid = `scale50-elixir-${i}-${Date.now()}`;
334 const stats = createStats(sid);
335 allStats.push(stats);
336​
337 try {
338 await mgr.startSession({
339 threadId: sid,
340 provider: "mock",
341 cwd: process.cwd(),
342 providerOptions: {
343 mock: { deltaCount: DELTA_COUNT, deltaSizeKb: DELTA_SIZE_KB, delayMs: DELAY_MS },
344 },
345 });
346 } catch (e) {
347 stats.errors.push(e instanceof Error ? e.message : String(e));
348 }
349​
350 if ((i + 1) % 10 === 0) log(` ${i + 1}/${N} sessions started`);
351 }
352​
353 const startupDuration = (Date.now() - startPhaseStart) / 1000;
354 log(`All ${N} sessions started in ${startupDuration.toFixed(1)}s`);
355​
356 const preMetrics = (await fetch(METRICS_URL).then((r) => r.json())) as any;
357 log(
358 `After start: ${preMetrics.beam.process_count} processes, ${(preMetrics.beam.total_memory / 1024 / 1024).toFixed(1)}MB`,
359 );
360​
361 // Send turns to ALL simultaneously
362 log("Sending turns to all 50 sessions...");
363 const turnPromises = allStats
364 .filter((s) => s.errors.length === 0)
365 .map((s) =>
366 mgr.sendTurn(s.id, { input: [{ type: "text", text: "scale50 test" }] }).catch(() => {}),
367 );
368 await Promise.all(turnPromises);
369 log("All turns accepted");
370​
371 // Wait for completion
372 const end = Date.now() + 120_000;
373 const metricSnapshots: any[] = [];
374 while (Date.now() < end) {
375 const completed = allStats.filter((s) => s.turnsCompleted > 0).length;
376 const totalDeltas = allStats.reduce((s, st) => s + st.deltaCount, 0);
377 if (completed >= N || allStats.every((s) => s.turnsCompleted > 0 || s.errors.length > 0)) break;
378​
379 try {
380 const m = (await fetch(METRICS_URL).then((r) => r.json())) as any;
381 metricSnapshots.push(m);
382 process.stdout.write(
383 `\r ${ts()} completed=${completed}/${N} deltas=${totalDeltas} mem=${(m.beam.total_memory / 1024 / 1024).toFixed(1)}MB procs=${m.beam.process_count}`,
384 );
385 } catch {}
386 await sleep(1000);
387 }
388​
389 console.log("");
390​
391 // Final metrics
392 const postMetrics = (await fetch(METRICS_URL).then((r) => r.json())) as any;
393 const sessionData = (postMetrics.sessions ?? [])
394 .filter((s: any) => String(s.thread_id ?? "").includes("scale50-elixir"))
395 .map((s: any) => ({ memory: s.memory, gc_count: s.gc_count, reductions: s.reductions }));
396​
397 try {
398 await mgr.stopAll();
399 } catch {}
400 mgr.disconnect();
401​
402 return {
403 allStats,
404 eventTimestamps,
405 lags: [] as number[],
406 metricSnapshots,
407 startupDuration,
408 sessionData,
409 postMetrics,
410 };
412​
413// ---------------------------------------------------------------------------
414// Main
415// ---------------------------------------------------------------------------
416​
417async function main() {
418 console.log("\n" + "╔" + "═".repeat(58) + "╗");
419 console.log("║" + ` GAP 3: 50-Session Scale Test — ${RUNTIME}`.padEnd(58) + "║");
420 console.log(
421 "║" + ` ${N} sessions × ${DELTA_COUNT} deltas × ${DELTA_SIZE_KB}KB`.padEnd(58) + "║",
422 );
423 console.log("╚" + "═".repeat(58) + "╝\n");
424​
425 const startedAt = Date.now();
426 const result = RUNTIME === "elixir" ? await runElixir() : await runNode();
427 const completedAt = Date.now();
428​
429 console.log("\n" + "═".repeat(60));
430 console.log(" 50-SESSION SCALE TEST RESULTS");
431 console.log("═".repeat(60));
432​
433 const { allStats, eventTimestamps, lags } = result;
434 const completed = allStats.filter((s) => s.turnsCompleted > 0).length;
435 const totalDeltas = allStats.reduce((s, st) => s + st.deltaCount, 0);
436 const errors = allStats.filter((s) => s.errors.length > 0).length;
437 const duration = (completedAt - startedAt) / 1000;
438​
439 console.log(` Sessions: ${completed}/${N} completed, ${errors} errors`);
440 console.log(` Total deltas: ${totalDeltas} (expected: ${N * DELTA_COUNT})`);
441 console.log(` Startup: ${result.startupDuration.toFixed(1)}s`);
442 console.log(` Total duration: ${duration.toFixed(1)}s`);
443​
444 // Throughput
445 if (eventTimestamps.length > 1) {
446 const streamDur = (eventTimestamps[eventTimestamps.length - 1]! - eventTimestamps[0]!) / 1000;
447 console.log(
448 ` Throughput: ${Math.round(eventTimestamps.length / streamDur)} events/s over ${streamDur.toFixed(1)}s`,
449 );
450 }
451​
452 // Per-session fairness (stddev of delta counts)
453 const counts = allStats.map((s) => s.deltaCount);
454 const avg = counts.reduce((s, c) => s + c, 0) / counts.length;
455 const stddev = Math.sqrt(counts.reduce((s, c) => s + (c - avg) ** 2, 0) / counts.length);
456 console.log(` Fairness: avg=${avg.toFixed(0)} deltas/session, stddev=${stddev.toFixed(1)}`);
457​
458 if (RUNTIME === "node" && lags.length > 0) {
459 console.log(
460 ` Event loop lag: p50=${percentile(lags, 50).toFixed(1)}ms p99=${percentile(lags, 99).toFixed(1)}ms max=${Math.max(...lags).toFixed(1)}ms`,
461 );
462 }
463​
464 if (RUNTIME === "elixir" && "sessionData" in result) {
465 const sd = (result as any).sessionData as Array<{ memory: number; gc_count: number }>;
466 if (sd.length > 0) {
467 const avgMem = sd.reduce((s, m) => s + m.memory, 0) / sd.length;
468 const avgGc = sd.reduce((s, m) => s + m.gc_count, 0) / sd.length;
469 console.log(` Per-session avg: mem=${(avgMem / 1024).toFixed(1)}KB, gc=${avgGc.toFixed(0)}`);
470 }
471 const pm = (result as any).postMetrics;
472 if (pm?.beam?.scheduler_utilization) {
473 const sched = pm.beam.scheduler_utilization;
474 if (Array.isArray(sched)) {
475 const avgUtil = sched.reduce((s: number, u: number) => s + u, 0) / sched.length;
476 console.log(
477 ` Scheduler utilization: avg=${(avgUtil * 100).toFixed(1)}%, max=${(Math.max(...sched) * 100).toFixed(1)}%`,
478 );
479 }
480 }
481 }
482​
483 const output = {
484 test: "scale50",
485 runtime: RUNTIME,
486 startedAt,
487 completedAt,
488 duration_ms: completedAt - startedAt,
489 config: { sessions: N, deltaCount: DELTA_COUNT, deltaSizeKb: DELTA_SIZE_KB, delayMs: DELAY_MS },
490 sessions: allStats,
491 metricSnapshots: result.metricSnapshots,
492 summary: {
493 sessionCount: N,
494 completed,
495 totalDeltas,
496 errors,
497 startupDuration_s: result.startupDuration,
498 totalDuration_s: duration,
499 eventsPerSecond:
500 eventTimestamps.length > 1
501 ? Math.round(
502 eventTimestamps.length /
503 ((eventTimestamps[eventTimestamps.length - 1]! - eventTimestamps[0]!) / 1000),
504 )
505 : 0,
506 fairnessStddev: Math.round(stddev * 10) / 10,
507 ...(RUNTIME === "node" && lags.length > 0
508 ? {
509 lagP50_ms: Math.round(percentile(lags, 50) * 10) / 10,
510 lagP99_ms: Math.round(percentile(lags, 99) * 10) / 10,
511 lagMax_ms: Math.round(Math.max(...lags) * 10) / 10,
512 }
513 : {}),
514 ...("sessionData" in result ? { perSessionMetrics: (result as any).sessionData } : {}),
515 },
516 };
517​
518 const filename = `${RUNTIME}-scale50-${Date.now()}.json`;
519 writeFileSync(`${OUTPUT_DIR}/${filename}`, JSON.stringify(output, null, 2));
520 log(`Results written to ${OUTPUT_DIR}/${filename}`);
521 console.log("═".repeat(60));
522​
523 setTimeout(() => process.exit(0), 2000);
525​
526main().catch((err) => {
527 console.error("Fatal:", err);
528 process.exit(1);
529});