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

stress-test-concurrent-elixir.ts

210 lines7.0 KB

1#!/usr/bin/env bun
2/**
3 * stress-test-concurrent-elixir.ts — 10 concurrent sessions via Elixir harness.
4 *
5 * All sessions use the mock provider (200 × 10KB deltas).
6 * Measures event throughput, per-process memory/GC, and SnapshotServer queue.
7 *
8 * Prerequisites: Elixir harness running with mock provider on port 4321.
9 */
10​
11import {
12 HarnessClientManager,
13 type HarnessRawEvent,
14} from "../apps/server/src/provider/Layers/HarnessClientManager.ts";
15import { writeFileSync, mkdirSync } from "node:fs";
16​
17const PORT = Number(process.env.T3CODE_HARNESS_PORT ?? 4321);
18const SECRET = process.env.T3CODE_HARNESS_SECRET ?? "dev-harness-secret";
19const OUTPUT_DIR = `${process.cwd()}/output/stress-test`;
20const METRICS_URL = `http://127.0.0.1:${PORT}/api/metrics`;
21const CWD = process.cwd();
22const N = 10;
23​
24mkdirSync(OUTPUT_DIR, { recursive: true });
25​
26const t0 = Date.now();
27const ts = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
28const log = (msg: string) => console.log(` ${ts()} ${msg}`);
29​
30function sleep(ms: number): Promise<void> {
31 return new Promise((r) => setTimeout(r, ms));
33​
34function percentile(arr: number[], p: number): number {
35 if (arr.length === 0) return 0;
36 const sorted = [...arr].sort((a, b) => a - b);
37 const idx = Math.ceil((p / 100) * sorted.length) - 1;
38 return sorted[Math.max(0, idx)]!;
40​
41async function main() {
42 console.log("\n" + "═".repeat(60));
43 console.log(" CONCURRENT: 10 sessions × 200 deltas × 10KB");
44 console.log(" Elixir harness — per-GenServer processes");
45 console.log("═".repeat(60));
46​
47 const startedAt = Date.now();
48 const sessionIds: string[] = [];
49 const states = new Map<string, { deltas: number; turnsCompleted: number }>();
50 const eventTimestamps: number[] = [];
51​
52 const mgr = new HarnessClientManager({
53 harnessPort: PORT,
54 harnessSecret: SECRET,
55 onEvent: (raw: HarnessRawEvent) => {
56 const state = states.get(raw.threadId);
57 if (!state) return;
58 if (raw.method === "item/agentMessage/delta") {
59 state.deltas++;
60 eventTimestamps.push(Date.now());
61 }
62 if (raw.method === "turn/completed") state.turnsCompleted++;
63 },
64 onSessionChanged: () => {},
65 onDisconnect: () => {},
66 onReconnect: () => {},
67 });
68​
69 await mgr.connect();
70 log("Connected");
71​
72 // Baseline metrics
73 const baseline = (await fetch(METRICS_URL).then((r) => r.json())) as Record<string, unknown>;
74 const baseBeam = baseline.beam as Record<string, unknown>;
75 log(
76 `Baseline: ${baseBeam.process_count} processes, ${((baseBeam.total_memory as number) / 1024 / 1024).toFixed(1)}MB`,
77 );
78​
79 // Start 10 mock sessions
80 for (let i = 0; i < N; i++) {
81 const tid = `concurrent-elixir-${i}-${Date.now()}`;
82 sessionIds.push(tid);
83 states.set(tid, { deltas: 0, turnsCompleted: 0 });
84​
85 await mgr.startSession({
86 threadId: tid,
87 provider: "mock",
88 cwd: CWD,
89 providerOptions: { mock: { deltaCount: 200, deltaSizeKb: 10, delayMs: 5 } },
90 });
91 }
92 log(`${N} sessions ready`);
93​
94 const preMetrics = (await fetch(METRICS_URL).then((r) => r.json())) as Record<string, unknown>;
95 const preBeam = preMetrics.beam as Record<string, unknown>;
96 log(
97 `After start: ${preBeam.process_count} processes, ${((preBeam.total_memory as number) / 1024 / 1024).toFixed(1)}MB`,
98 );
99​
100 // Send turns to ALL simultaneously
101 log("Sending turns to all 10 sessions...");
102 const turnPromises = sessionIds.map((tid) =>
103 mgr.sendTurn(tid, { input: [{ type: "text", text: "concurrent" }] }).catch(() => {}),
104 );
105 await Promise.all(turnPromises);
106 log("All turns accepted");
107​
108 // Poll metrics while running
109 const metricSnapshots: Array<Record<string, unknown>> = [];
110 const end = Date.now() + 60_000;
111 while (Date.now() < end) {
112 const allDone = [...states.values()].every((s) => s.turnsCompleted >= 1);
113 if (allDone) break;
114 try {
115 const m = (await fetch(METRICS_URL).then((r) => r.json())) as Record<string, unknown>;
116 metricSnapshots.push(m);
117 } catch {}
118 await sleep(1000);
119 }
120​
121 const totalDeltas = [...states.values()].reduce((s, st) => s + st.deltas, 0);
122 const completed = [...states.values()].filter((s) => s.turnsCompleted >= 1).length;
123​
124 let eventsPerSecond = 0;
125 if (eventTimestamps.length > 1) {
126 const dur = (eventTimestamps[eventTimestamps.length - 1]! - eventTimestamps[0]!) / 1000;
127 eventsPerSecond = dur > 0 ? Math.round(eventTimestamps.length / dur) : 0;
128 }
129​
130 // Final metrics
131 const postMetrics = (await fetch(METRICS_URL).then((r) => r.json())) as Record<string, unknown>;
132 const postBeam = postMetrics.beam as Record<string, unknown>;
133 const postSessions = (postMetrics.sessions as Array<Record<string, unknown>>) ?? [];
134 const snapshotServer = postMetrics.snapshot_server as Record<string, unknown>;
135​
136 // Per-session stats
137 const sessionMemories = postSessions
138 .filter((s) => String(s.thread_id ?? "").includes("concurrent-elixir"))
139 .map((s) => ({
140 memory: s.memory as number,
141 gc_count: s.gc_count as number,
142 reductions: s.reductions as number,
143 }));
144​
145 const maxSnapshotQueue = Math.max(
146 0,
147 ...metricSnapshots.map(
148 (m) => ((m.snapshot_server as Record<string, unknown>)?.message_queue_len as number) ?? 0,
149 ),
150 );
151​
152 log(`Completed: ${completed}/${N}, total deltas: ${totalDeltas}`);
153 log(`Event throughput: ${eventsPerSecond} events/s`);
154 log(`SnapshotServer max queue: ${maxSnapshotQueue}`);
155 log(
156 `Post: ${postBeam.process_count} processes, ${((postBeam.total_memory as number) / 1024 / 1024).toFixed(1)}MB`,
157 );
158​
159 if (sessionMemories.length > 0) {
160 const avgMem = sessionMemories.reduce((s, m) => s + m.memory, 0) / sessionMemories.length;
161 const avgGc = sessionMemories.reduce((s, m) => s + m.gc_count, 0) / sessionMemories.length;
162 log(`Per-session avg: mem=${(avgMem / 1024).toFixed(1)}KB, gc=${avgGc.toFixed(0)}`);
163 }
164​
165 // Cleanup
166 try {
167 await mgr.stopAll();
168 } catch {}
169 await sleep(2000);
170 mgr.disconnect();
171​
172 const completedAt = Date.now();
173​
174 const result = {
175 test: "concurrent",
176 runtime: "elixir",
177 startedAt,
178 completedAt,
179 duration_ms: completedAt - startedAt,
180 metricSnapshots,
181 summary: {
182 sessionCount: N,
183 sessionsCompleted: completed,
184 totalDeltas,
185 eventsPerSecond,
186 snapshotServerMaxQueue: maxSnapshotQueue,
187 perSessionMemories: sessionMemories,
188 avgSessionMemory:
189 sessionMemories.length > 0
190 ? Math.round(sessionMemories.reduce((s, m) => s + m.memory, 0) / sessionMemories.length)
191 : 0,
192 avgSessionGcCount:
193 sessionMemories.length > 0
194 ? Math.round(sessionMemories.reduce((s, m) => s + m.gc_count, 0) / sessionMemories.length)
195 : 0,
196 beamTotalMemory: postBeam.total_memory,
197 beamProcessCount: postBeam.process_count,
198 beamGcRuns: postBeam.gc_runs,
199 },
200 };
201​
202 const filename = `elixir-concurrent-${Date.now()}.json`;
203 writeFileSync(`${OUTPUT_DIR}/${filename}`, JSON.stringify(result, null, 2));
204 log(`Results written to ${OUTPUT_DIR}/${filename}`);
206​
207main().catch((e) => {
208 console.error("Fatal:", e);
209 process.exit(1);
210});