Skip to content

Commit 347f16d

Browse files
authored
fix(scripts): warm gateway concurrency probes (#118364)
1 parent 345343f commit 347f16d

2 files changed

Lines changed: 164 additions & 47 deletions

File tree

‎scripts/bench-gateway-concurrency.ts‎

Lines changed: 133 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,10 @@ type GatewayRpc = <T>(method: string, params: unknown, timeoutMs?: number) => Pr
6868
type BenchmarkRun = {
6969
controlUi: ControlUiProbe[];
7070
durationMs: number;
71+
probeWarmup: {
72+
durationMs: number;
73+
samples: GatewaySample[];
74+
};
7175
readyz: ReadyProbe[];
7276
sessionsList: TimedProbe[];
7377
turnCount: number;
@@ -98,6 +102,10 @@ const MAX_WARMUP = 10;
98102
const MAX_SAMPLES_PER_RUN = 2_048;
99103
const MAX_HTTP_BODY_BYTES = 1_048_576;
100104
const HTTP_TIMEOUT_MS = 20_000;
105+
const PROBE_WARMUP_TIMEOUT_MS = 60_000;
106+
const PROBE_WARMUP_TARGET_MS = 1_000;
107+
const PROBE_WARMUP_RETRY_DELAY_MS = 100;
108+
const GATEWAY_STDERR_TAIL_LINES = 20;
101109
const AGENT_WAIT_RPC_GRACE_MS = 5_000;
102110
const BOOLEAN_FLAGS = new Set(["--help", "-h", "--json"]);
103111
const VALUE_FLAGS = new Set([
@@ -182,7 +190,7 @@ Options:
182190
--runs <n> Measured gateway runs (default: ${DEFAULT_RUNS})
183191
--warmup <n> Warmup gateway runs (default: ${DEFAULT_WARMUP})
184192
--cadence-ms <ms> Probe cadence (default: ${DEFAULT_CADENCE_MS})
185-
--timeout-ms <ms> Whole benchmark wall-clock cap (default: ${DEFAULT_TIMEOUT_MS})
193+
--timeout-ms <ms> Whole benchmark cap, excluding probe warmup (default: ${DEFAULT_TIMEOUT_MS})
186194
--entry <path> Gateway CLI entry file (default: ${DEFAULT_ENTRY})
187195
--output <path> Write machine-readable JSON to a file
188196
--json Emit machine-readable JSON
@@ -281,31 +289,58 @@ function describeProbeError(error: unknown): string {
281289
}
282290

283291
function formatProbeResult(name: string, probe: TimedProbe & { status?: number }): string {
284-
const status = probe.status === undefined ? (probe.ok ? "ok" : "failed") : probe.status;
285-
return `${name}(ok=${probe.ok} status=${status} error=${probe.error ? JSON.stringify(probe.error) : "none"} latencyMs=${probe.latencyMs.toFixed(1)})`;
292+
const status = probe.status === undefined ? "n/a" : probe.status;
293+
return `${name}: ok=${probe.ok} status=${status} latencyMs=${probe.latencyMs.toFixed(1)} error=${probe.error ? JSON.stringify(probe.error) : "none"}`;
286294
}
287295

288-
function assertBaselineProbes(baseline: GatewaySample): void {
289-
if (baseline.readyz.ok && baseline.sessionsList.ok && baseline.controlUi.ok) {
290-
return;
291-
}
292-
throw new Error(
293-
`gateway probes did not pass before concurrent load: ${[
294-
formatProbeResult("readyz", baseline.readyz),
295-
formatProbeResult("sessionsList", baseline.sessionsList),
296-
formatProbeResult("controlUi", baseline.controlUi),
297-
].join("; ")}`,
298-
);
296+
function formatProbeFailure(sample: GatewaySample): string {
297+
return [
298+
"gateway probes did not become fast and healthy before concurrent load",
299+
formatProbeResult("readyz", sample.readyz),
300+
formatProbeResult("sessionsList", sample.sessionsList),
301+
formatProbeResult("controlUi", sample.controlUi),
302+
].join("\n ");
303+
}
304+
305+
function tailLines(output: string, lineCount: number): string {
306+
return output.trimEnd().split(/\r?\n/u).slice(-lineCount).join("\n");
299307
}
300308

301-
function captureChildOutput(child: ChildProcessWithoutNullStreams): () => string {
309+
function captureChildOutput(child: ChildProcessWithoutNullStreams): {
310+
readOutput: () => string;
311+
readStderrTail: () => string;
312+
} {
302313
let output = "";
303-
const append = (chunk: Buffer) => {
314+
let stderr = "";
315+
const appendOutput = (chunk: Buffer) => {
304316
output = `${output}${chunk.toString("utf8")}`.slice(-64 * 1_024);
305317
};
306-
child.stdout.on("data", append);
307-
child.stderr.on("data", append);
308-
return () => output;
318+
child.stdout.on("data", appendOutput);
319+
child.stderr.on("data", (chunk: Buffer) => {
320+
appendOutput(chunk);
321+
stderr = `${stderr}${chunk.toString("utf8")}`.slice(-64 * 1_024);
322+
});
323+
return {
324+
readOutput: () => output,
325+
readStderrTail: () => tailLines(stderr, GATEWAY_STDERR_TAIL_LINES),
326+
};
327+
}
328+
329+
function formatRunFailure(
330+
error: unknown,
331+
gatewayOutput: { readOutput: () => string; readStderrTail: () => string },
332+
mockOutput: { readOutput: () => string },
333+
): string {
334+
return [
335+
error instanceof Error ? error.message : String(error),
336+
gatewayOutput.readStderrTail()
337+
? `gateway stderr tail:\n${gatewayOutput.readStderrTail()}`
338+
: "gateway stderr tail: (empty)",
339+
gatewayOutput.readOutput() ? `gateway output tail:\n${gatewayOutput.readOutput()}` : "",
340+
mockOutput.readOutput() ? `mock provider output tail:\n${mockOutput.readOutput()}` : "",
341+
]
342+
.filter(Boolean)
343+
.join("\n");
309344
}
310345

311346
async function waitForMockServer(port: number, deadlineAt: number): Promise<void> {
@@ -371,6 +406,7 @@ function buildConfig(root: string, mockPort: number, concurrency: number): strin
371406
}
372407

373408
async function connectGateway(port: number, deadlineAt: number) {
409+
let requestDeadlineAt = deadlineAt;
374410
const client = createGatewayWsClient({
375411
handshakeTimeoutMs: Math.min(8_000, requireRemainingMs(deadlineAt, "connecting WebSocket")),
376412
openTimeoutMs: Math.min(8_000, requireRemainingMs(deadlineAt, "opening WebSocket")),
@@ -390,7 +426,7 @@ async function connectGateway(port: number, deadlineAt: number) {
390426
1,
391427
Math.min(
392428
requestedTimeoutMs ?? 65_000,
393-
requireRemainingMs(deadlineAt, `waiting for ${method}`),
429+
requireRemainingMs(requestDeadlineAt, `waiting for ${method}`),
394430
),
395431
),
396432
);
@@ -418,7 +454,13 @@ async function connectGateway(port: number, deadlineAt: number) {
418454
scopes: ["operator.read", "operator.write", "operator.admin"],
419455
caps: [],
420456
});
421-
return { close: client.close, request: requestRpc };
457+
return {
458+
close: client.close,
459+
request: requestRpc,
460+
setDeadlineAt: (value: number) => {
461+
requestDeadlineAt = value;
462+
},
463+
};
422464
}
423465

424466
async function runTurn(rpc: GatewayRpc, index: number, deadlineAt: number): Promise<void> {
@@ -490,7 +532,11 @@ async function sampleGateway(params: {
490532
const probeSessions = async () => {
491533
const startedAt = performance.now();
492534
try {
493-
const payload = await params.rpc("sessions.list", {}, HTTP_TIMEOUT_MS);
535+
const payload = await params.rpc(
536+
"sessions.list",
537+
{},
538+
Math.min(HTTP_TIMEOUT_MS, requireRemainingMs(params.deadlineAt, "probing sessions.list")),
539+
);
494540
return { error: null, latencyMs: performance.now() - startedAt, ok: true, payload };
495541
} catch (error) {
496542
return {
@@ -548,6 +594,40 @@ async function sampleGateway(params: {
548594
};
549595
}
550596

597+
async function warmGatewayProbes(params: {
598+
deadlineAt: number;
599+
sample: (deadlineAt: number) => Promise<GatewaySample>;
600+
retryDelayMs?: number;
601+
targetMs?: number;
602+
}): Promise<{ durationMs: number; samples: GatewaySample[] }> {
603+
const startedAt = performance.now();
604+
const samples: GatewaySample[] = [];
605+
const targetMs = params.targetMs ?? PROBE_WARMUP_TARGET_MS;
606+
while (remainingMs(params.deadlineAt) > 0) {
607+
const sample = await params.sample(params.deadlineAt);
608+
samples.push(sample);
609+
const healthy = sample.readyz.ok && sample.sessionsList.ok && sample.controlUi.ok;
610+
const fast =
611+
Math.max(
612+
sample.readyz.latencyMs,
613+
sample.sessionsList.latencyMs,
614+
sample.controlUi.latencyMs,
615+
) <= targetMs;
616+
if (healthy && fast) {
617+
return { durationMs: performance.now() - startedAt, samples };
618+
}
619+
await delay(
620+
Math.min(params.retryDelayMs ?? PROBE_WARMUP_RETRY_DELAY_MS, remainingMs(params.deadlineAt)),
621+
);
622+
}
623+
const lastSample = samples.at(-1);
624+
throw new Error(
625+
lastSample
626+
? formatProbeFailure(lastSample)
627+
: "gateway probes did not run before the warmup deadline",
628+
);
629+
}
630+
551631
async function runGatewaySample(options: {
552632
cadenceMs: number;
553633
concurrency: number;
@@ -560,8 +640,8 @@ async function runGatewaySample(options: {
560640
let gateway: ChildProcessWithoutNullStreams | undefined;
561641
let mockProvider: ChildProcessWithoutNullStreams | undefined;
562642
let client: Awaited<ReturnType<typeof connectGateway>> | undefined;
563-
let gatewayOutput = () => "";
564-
let mockOutput = () => "";
643+
let gatewayOutput = { readOutput: () => "", readStderrTail: () => "" };
644+
let mockOutput = { readOutput: () => "", readStderrTail: () => "" };
565645

566646
try {
567647
const configPath = buildConfig(root, mockPort, options.concurrency);
@@ -598,19 +678,28 @@ async function runGatewaySample(options: {
598678
startAt: runStartedAt,
599679
});
600680
if (ready.status !== 200) {
601-
throw new Error(`gateway did not become ready\n${gatewayOutput()}`);
681+
throw new Error(`gateway did not become ready\n${gatewayOutput.readOutput()}`);
602682
}
603-
await waitForGatewayDispatchReady(gatewayOutput, options.deadlineAt);
683+
await waitForGatewayDispatchReady(gatewayOutput.readOutput, options.deadlineAt);
604684
client = await connectGateway(port, options.deadlineAt);
605685
const rpc = client.request;
606-
const baseline = await sampleGateway({
607-
deadlineAt: options.deadlineAt,
608-
port,
609-
rpc,
610-
runStartedAt,
611-
serial: true,
686+
// The first authenticated RPC lazily imports the server-method graph. It measured 6.9s
687+
// on an idle M4 Pro (previously 18.4s) and crossed 20s on Linux; hot probes took 15-40ms.
688+
// Keep that cold work out of the load-phase deadline and latency distributions.
689+
const probeWarmupDeadlineAt = performance.now() + PROBE_WARMUP_TIMEOUT_MS;
690+
client.setDeadlineAt(probeWarmupDeadlineAt);
691+
const probeWarmup = await warmGatewayProbes({
692+
deadlineAt: probeWarmupDeadlineAt,
693+
sample: (deadlineAt) =>
694+
sampleGateway({
695+
deadlineAt,
696+
port,
697+
rpc,
698+
runStartedAt,
699+
}),
612700
});
613-
assertBaselineProbes(baseline);
701+
const loadDeadlineAt = options.deadlineAt + probeWarmup.durationMs;
702+
client.setDeadlineAt(loadDeadlineAt);
614703

615704
const controlUi: ControlUiProbe[] = [];
616705
const readyz: ReadyProbe[] = [];
@@ -619,7 +708,7 @@ async function runGatewaySample(options: {
619708
const turnsStartedAt = performance.now();
620709
const turns = Promise.all(
621710
Array.from({ length: options.concurrency }, (_, index) =>
622-
runTurn(rpc, index, options.deadlineAt),
711+
runTurn(rpc, index, loadDeadlineAt),
623712
),
624713
).finally(() => {
625714
turnsDone = true;
@@ -628,7 +717,7 @@ async function runGatewaySample(options: {
628717
for (;;) {
629718
const sampleStartedAt = performance.now();
630719
const sample = await sampleGateway({
631-
deadlineAt: options.deadlineAt,
720+
deadlineAt: loadDeadlineAt,
632721
port,
633722
rpc,
634723
runStartedAt,
@@ -642,7 +731,7 @@ async function runGatewaySample(options: {
642731
await delay(
643732
Math.min(
644733
Math.max(0, options.cadenceMs - (performance.now() - sampleStartedAt)),
645-
requireRemainingMs(options.deadlineAt, "sampling gateway load"),
734+
requireRemainingMs(loadDeadlineAt, "sampling gateway load"),
646735
),
647736
);
648737
}
@@ -653,19 +742,14 @@ async function runGatewaySample(options: {
653742
return {
654743
controlUi,
655744
durationMs: performance.now() - runStartedAt,
745+
probeWarmup,
656746
readyz,
657747
sessionsList,
658748
turnCount: options.concurrency,
659749
turnsDurationMs,
660750
};
661751
} catch (error) {
662-
const detail = [
663-
error instanceof Error ? error.message : String(error),
664-
gatewayOutput() ? `gateway output:\n${gatewayOutput()}` : "",
665-
mockOutput() ? `mock provider output:\n${mockOutput()}` : "",
666-
]
667-
.filter(Boolean)
668-
.join("\n");
752+
const detail = formatRunFailure(error, gatewayOutput, mockOutput);
669753
throw new Error(detail, { cause: error });
670754
} finally {
671755
client?.close();
@@ -717,12 +801,13 @@ async function main(): Promise<void> {
717801
return;
718802
}
719803
const options = parseOptions(argv);
720-
const deadlineAt = performance.now() + options.timeoutMs;
804+
let deadlineAt = performance.now() + options.timeoutMs;
721805
const runs: BenchmarkRun[] = [];
722806
const total = options.runs + options.warmup;
723807
for (let index = 0; index < total; index += 1) {
724808
requireRemainingMs(deadlineAt, "starting gateway run");
725809
const run = await runGatewaySample({ ...options, deadlineAt });
810+
deadlineAt += run.probeWarmup.durationMs;
726811
if (index >= options.warmup) {
727812
runs.push(run);
728813
console.error(
@@ -754,11 +839,14 @@ async function main(): Promise<void> {
754839

755840
export const testing = {
756841
parseOptions,
757-
assertBaselineProbes,
842+
formatProbeFailure,
843+
formatRunFailure,
758844
runTurn,
759845
sampleGateway,
760846
summarizeNumbers,
761847
summarizeRuns,
848+
tailLines,
849+
warmGatewayProbes,
762850
};
763851

764852
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {

‎test/scripts/bench-gateway-concurrency.test.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,9 +111,38 @@ describe("gateway concurrency benchmark script", () => {
111111
error: "sessions.list failed: unauthorized",
112112
ok: false,
113113
});
114-
expect(() => testing.assertBaselineProbes(sample)).toThrow(
115-
/readyz\(ok=false status=503 error=none .*sessionsList\(ok=false status=failed error="sessions\.list failed: unauthorized" .*controlUi\(ok=false status=200 error="response body did not contain <html"/u,
114+
const failure = testing.formatRunFailure(
115+
new Error(testing.formatProbeFailure(sample)),
116+
{
117+
readOutput: () => "gateway output",
118+
readStderrTail: () => testing.tailLines("old\nfirst retained\nlast retained\n", 2),
119+
},
120+
{ readOutput: () => "mock output" },
121+
);
122+
expect(failure).toMatch(
123+
/readyz: ok=false status=503 latencyMs=\d+\.\d error=none\n sessionsList: ok=false status=n\/a latencyMs=\d+\.\d error="sessions\.list failed: unauthorized"\n controlUi: ok=false status=200 latencyMs=\d+\.\d error="response body did not contain <html"/u,
116124
);
125+
expect(failure).toContain("gateway stderr tail:\nfirst retained\nlast retained");
126+
expect(failure).not.toContain("old");
127+
128+
const healthySlow = {
129+
controlUi: { ...sample.controlUi, error: null, latencyMs: 200, ok: true },
130+
readyz: { ...sample.readyz, latencyMs: 200, ok: true, status: 200 },
131+
sessionsList: { ...sample.sessionsList, error: null, latencyMs: 200, ok: true },
132+
};
133+
const healthyFast = {
134+
controlUi: { ...healthySlow.controlUi, latencyMs: 10 },
135+
readyz: { ...healthySlow.readyz, latencyMs: 10 },
136+
sessionsList: { ...healthySlow.sessionsList, latencyMs: 10 },
137+
};
138+
const samples = [sample, healthySlow, healthyFast];
139+
const warmed = await testing.warmGatewayProbes({
140+
deadlineAt: performance.now() + 5_000,
141+
retryDelayMs: 0,
142+
sample: async () => samples.shift() ?? healthyFast,
143+
targetMs: 100,
144+
});
145+
expect(warmed.samples).toHaveLength(3);
117146
} finally {
118147
server.close();
119148
}

0 commit comments

Comments
 (0)