Skip to content

Commit 556be6d

Browse files
author
Peter Steinberger
committed
fix(scripts): diagnose gateway concurrency probes
1 parent b7f9cd0 commit 556be6d

9 files changed

Lines changed: 169 additions & 59 deletions

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1836,7 +1836,7 @@
18361836
"test:force": "node --import tsx scripts/test-force.ts",
18371837
"test:gateway": "node scripts/run-with-env.mjs OPENCLAW_GATEWAY_PROJECT_SHARDS=1 -- node scripts/run-vitest.mjs run --config test/vitest/vitest.gateway.config.ts",
18381838
"test:gateway:cpu-scenarios": "node scripts/check-gateway-cpu-scenarios.mjs",
1839-
"test:gateway:concurrency": "node --import tsx scripts/bench-gateway-concurrency.ts",
1839+
"test:gateway:concurrency": "node scripts/bench-gateway-concurrency.ts",
18401840
"test:gateway:memory-fd-repro": "node scripts/check-memory-fd-repro.mjs",
18411841
"test:gateway:watch-regression": "node scripts/check-gateway-watch-regression.mjs",
18421842
"test:install:e2e": "bash scripts/test-install-sh-e2e-docker.sh",

‎scripts/bench-gateway-concurrency.ts‎

Lines changed: 79 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { tmpdir } from "node:os";
77
import path from "node:path";
88
import { performance } from "node:perf_hooks";
99
import { pathToFileURL } from "node:url";
10-
import { PROTOCOL_VERSION } from "../packages/gateway-protocol/src/index.js";
10+
import { PROTOCOL_VERSION } from "../packages/gateway-protocol/src/version.ts";
1111
import { applyMockOpenAiModelConfig } from "./e2e/lib/fixtures/mock-openai-config.mjs";
1212
import { delay, stopChild } from "./lib/gateway-bench-child.ts";
1313
import { getFreePort } from "./lib/gateway-bench-probes.ts";
@@ -39,6 +39,7 @@ type MetricSummary = {
3939

4040
type TimedProbe = {
4141
atMs: number;
42+
error: string | null;
4243
latencyMs: number;
4344
ok: boolean;
4445
};
@@ -52,10 +53,20 @@ type ReadyProbe = TimedProbe & {
5253
utilization: number | null;
5354
};
5455

56+
type ControlUiProbe = TimedProbe & {
57+
status: number;
58+
};
59+
60+
type GatewaySample = {
61+
controlUi: ControlUiProbe;
62+
readyz: ReadyProbe;
63+
sessionsList: TimedProbe;
64+
};
65+
5566
type GatewayRpc = <T>(method: string, params: unknown, timeoutMs?: number) => Promise<T>;
5667

5768
type BenchmarkRun = {
58-
controlUi: TimedProbe[];
69+
controlUi: ControlUiProbe[];
5970
durationMs: number;
6071
readyz: ReadyProbe[];
6172
sessionsList: TimedProbe[];
@@ -164,7 +175,7 @@ function printUsage(): void {
164175
165176
Usage:
166177
pnpm test:gateway:concurrency -- [options]
167-
node --import tsx scripts/bench-gateway-concurrency.ts [options]
178+
node scripts/bench-gateway-concurrency.ts [options]
168179
169180
Options:
170181
--concurrency <n> Concurrent synthetic streaming turns (default: ${DEFAULT_CONCURRENCY})
@@ -264,6 +275,29 @@ function numberOrNull(value: unknown): number | null {
264275
return typeof value === "number" && Number.isFinite(value) ? value : null;
265276
}
266277

278+
function describeProbeError(error: unknown): string {
279+
const message = error instanceof Error ? error.message : String(error);
280+
return message.slice(0, 500);
281+
}
282+
283+
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)})`;
286+
}
287+
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+
);
299+
}
300+
267301
function captureChildOutput(child: ChildProcessWithoutNullStreams): () => string {
268302
let output = "";
269303
const append = (chunk: Buffer) => {
@@ -425,7 +459,8 @@ async function sampleGateway(params: {
425459
port: number;
426460
rpc: GatewayRpc;
427461
runStartedAt: number;
428-
}): Promise<{ controlUi: TimedProbe; readyz: ReadyProbe; sessionsList: TimedProbe }> {
462+
serial?: boolean;
463+
}): Promise<GatewaySample> {
429464
const atMs = performance.now() - params.runStartedAt;
430465
const safeHttpProbe = async (pathValue: string, accept: string) => {
431466
const startedAt = performance.now();
@@ -437,30 +472,38 @@ async function sampleGateway(params: {
437472
path: pathValue,
438473
port: params.port,
439474
})),
475+
error: null,
440476
ok: true,
441477
};
442-
} catch {
478+
} catch (error) {
443479
return {
444480
body: "",
481+
error: describeProbeError(error),
445482
latencyMs: performance.now() - startedAt,
446483
ok: false,
447484
status: 0,
448485
};
449486
}
450487
};
451-
const [readyz, controlUi, sessions] = await Promise.all([
452-
safeHttpProbe("/readyz", "application/json"),
453-
safeHttpProbe("/", "text/html"),
454-
(async () => {
455-
const startedAt = performance.now();
456-
try {
457-
const payload = await params.rpc("sessions.list", {}, HTTP_TIMEOUT_MS);
458-
return { latencyMs: performance.now() - startedAt, ok: true, payload };
459-
} catch {
460-
return { latencyMs: performance.now() - startedAt, ok: false, payload: null };
461-
}
462-
})(),
463-
]);
488+
const probeReadyz = () => safeHttpProbe("/readyz", "application/json");
489+
const probeControlUi = () => safeHttpProbe("/", "text/html");
490+
const probeSessions = async () => {
491+
const startedAt = performance.now();
492+
try {
493+
const payload = await params.rpc("sessions.list", {}, HTTP_TIMEOUT_MS);
494+
return { error: null, latencyMs: performance.now() - startedAt, ok: true, payload };
495+
} catch (error) {
496+
return {
497+
error: describeProbeError(error),
498+
latencyMs: performance.now() - startedAt,
499+
ok: false,
500+
payload: null,
501+
};
502+
}
503+
};
504+
const [readyz, controlUi, sessions] = params.serial
505+
? [await probeReadyz(), await probeControlUi(), await probeSessions()]
506+
: await Promise.all([probeReadyz(), probeControlUi(), probeSessions()]);
464507
const readyBody = (() => {
465508
if (readyz.status !== 200) {
466509
return {};
@@ -475,11 +518,18 @@ async function sampleGateway(params: {
475518
return {
476519
controlUi: {
477520
atMs,
521+
error:
522+
controlUi.error ??
523+
(controlUi.status === 200 && !controlUi.body.includes("<html")
524+
? "response body did not contain <html"
525+
: null),
478526
latencyMs: controlUi.latencyMs,
479527
ok: controlUi.ok && controlUi.status === 200 && controlUi.body.includes("<html"),
528+
status: controlUi.status,
480529
},
481530
readyz: {
482531
atMs,
532+
error: readyz.error,
483533
latencyMs: readyz.latencyMs,
484534
ok: readyz.ok && readyz.status === 200,
485535
status: readyz.status,
@@ -489,7 +539,12 @@ async function sampleGateway(params: {
489539
utilization: numberOrNull(eventLoop?.utilization),
490540
cpuCoreRatio: numberOrNull(eventLoop?.cpuCoreRatio),
491541
},
492-
sessionsList: { atMs, latencyMs: sessions.latencyMs, ok: sessions.ok },
542+
sessionsList: {
543+
atMs,
544+
error: sessions.error,
545+
latencyMs: sessions.latencyMs,
546+
ok: sessions.ok,
547+
},
493548
};
494549
}
495550

@@ -553,12 +608,11 @@ async function runGatewaySample(options: {
553608
port,
554609
rpc,
555610
runStartedAt,
611+
serial: true,
556612
});
557-
if (!baseline.readyz.ok || !baseline.sessionsList.ok || !baseline.controlUi.ok) {
558-
throw new Error("gateway probes did not pass before concurrent load");
559-
}
613+
assertBaselineProbes(baseline);
560614

561-
const controlUi: TimedProbe[] = [];
615+
const controlUi: ControlUiProbe[] = [];
562616
const readyz: ReadyProbe[] = [];
563617
const sessionsList: TimedProbe[] = [];
564618
let turnsDone = false;
@@ -700,7 +754,9 @@ async function main(): Promise<void> {
700754

701755
export const testing = {
702756
parseOptions,
757+
assertBaselineProbes,
703758
runTurn,
759+
sampleGateway,
704760
summarizeNumbers,
705761
summarizeRuns,
706762
};

‎scripts/check-gateway-cpu-scenarios.mjs‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,8 +411,6 @@ async function runGatewayCpuScenarios(options, params = {}) {
411411
"concurrency bench",
412412
process.execPath,
413413
[
414-
"--import",
415-
"tsx",
416414
"scripts/bench-gateway-concurrency.ts",
417415
"--concurrency",
418416
String(DEFAULT_GATEWAY_CONCURRENCY),

‎scripts/lib/dev-tooling-safety.ts‎

Lines changed: 2 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import path from "node:path";
33
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
44
import { redactSensitiveText } from "../../src/logging/redact.js";
55

6+
export { parseStrictIntegerOption } from "./strict-integer-option.ts";
7+
68
const REDACT_OPTIONS = { mode: "tools" } as const;
79

810
export function redactForDevToolLog(value: string): string {
@@ -43,30 +45,6 @@ export function redactHomePath(value: string, home = process.env.HOME ?? ""): st
4345
return value;
4446
}
4547

46-
export function parseStrictIntegerOption(params: {
47-
fallback: number;
48-
label: string;
49-
min: number;
50-
raw: string | undefined;
51-
}): number {
52-
const raw = params.raw?.trim();
53-
if (!raw) {
54-
return params.fallback;
55-
}
56-
if (!/^\d+$/u.test(raw)) {
57-
throw new Error(
58-
`${params.label} must be an integer >= ${params.min}; got ${JSON.stringify(raw)}`,
59-
);
60-
}
61-
const value = Number(raw);
62-
if (!Number.isSafeInteger(value) || value < params.min) {
63-
throw new Error(
64-
`${params.label} must be an integer >= ${params.min}; got ${JSON.stringify(raw)}`,
65-
);
66-
}
67-
return value;
68-
}
69-
7048
export function parseBooleanEnv(params: {
7149
fallback: boolean;
7250
name: string;

‎scripts/lib/gateway-bench-probes.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import { spawnSync } from "node:child_process";
33
import { request } from "node:http";
44
import { createServer } from "node:net";
5-
import { expectDefined } from "../../packages/normalization-core/src/expect.js";
5+
import { expectDefined } from "../../packages/normalization-core/src/expect.ts";
66

77
export async function getFreePort(): Promise<number> {
88
return new Promise((resolve, reject) => {

‎scripts/lib/gateway-bench-runtime.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { mkdirSync, writeFileSync } from "node:fs";
22
import path from "node:path";
33
import { performance } from "node:perf_hooks";
4-
import { expectDefined } from "../../packages/normalization-core/src/expect.js";
5-
import { parseStrictIntegerOption } from "./dev-tooling-safety.ts";
4+
import { expectDefined } from "../../packages/normalization-core/src/expect.ts";
65
import { delay } from "./gateway-bench-child.ts";
76
import { requestProbeStatus } from "./gateway-bench-probes.ts";
7+
import { parseStrictIntegerOption } from "./strict-integer-option.ts";
88

99
type GatewayBenchCase = {
1010
config: Record<string, unknown>;
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Strict integer parsing is dependency-free so native Node TypeScript scripts can reuse it.
2+
export function parseStrictIntegerOption(params: {
3+
fallback: number;
4+
label: string;
5+
min: number;
6+
raw: string | undefined;
7+
}): number {
8+
const raw = params.raw?.trim();
9+
if (!raw) {
10+
return params.fallback;
11+
}
12+
if (!/^\d+$/u.test(raw)) {
13+
throw new Error(
14+
`${params.label} must be an integer >= ${params.min}; got ${JSON.stringify(raw)}`,
15+
);
16+
}
17+
const value = Number(raw);
18+
if (!Number.isSafeInteger(value) || value < params.min) {
19+
throw new Error(
20+
`${params.label} must be an integer >= ${params.min}; got ${JSON.stringify(raw)}`,
21+
);
22+
}
23+
return value;
24+
}

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

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Gateway concurrency benchmark tests cover CLI parsing and bounded percentile summaries.
22
import { spawnSync } from "node:child_process";
3+
import { createServer } from "node:http";
34
import { performance } from "node:perf_hooks";
45
import { describe, expect, it } from "vitest";
56
import { testing } from "../../scripts/bench-gateway-concurrency.ts";
@@ -74,12 +75,65 @@ describe("gateway concurrency benchmark script", () => {
7475
expect(wait?.timeoutMs).toBeLessThanOrEqual(2_000);
7576
});
7677

78+
it("preserves HTTP and RPC failures in baseline probe diagnostics", async () => {
79+
const probeOrder: string[] = [];
80+
const server = createServer((req, res) => {
81+
probeOrder.push(req.url ?? "missing-url");
82+
res.statusCode = req.url === "/readyz" ? 503 : 200;
83+
res.end(req.url === "/readyz" ? '{"status":"starting"}' : "not html");
84+
});
85+
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
86+
const address = server.address();
87+
if (!address || typeof address === "string") {
88+
server.close();
89+
throw new Error("expected HTTP test server address");
90+
}
91+
try {
92+
const sample = await testing.sampleGateway({
93+
deadlineAt: performance.now() + 5_000,
94+
port: address.port,
95+
rpc: async () => {
96+
probeOrder.push("sessions.list");
97+
throw new Error("sessions.list failed: unauthorized");
98+
},
99+
runStartedAt: performance.now(),
100+
serial: true,
101+
});
102+
103+
expect(probeOrder).toEqual(["/readyz", "/", "sessions.list"]);
104+
expect(sample.readyz).toMatchObject({ error: null, ok: false, status: 503 });
105+
expect(sample.controlUi).toMatchObject({
106+
error: "response body did not contain <html",
107+
ok: false,
108+
status: 200,
109+
});
110+
expect(sample.sessionsList).toMatchObject({
111+
error: "sessions.list failed: unauthorized",
112+
ok: false,
113+
});
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,
116+
);
117+
} finally {
118+
server.close();
119+
}
120+
});
121+
122+
it("loads through native Node TypeScript stripping", () => {
123+
const result = spawnSync(process.execPath, ["scripts/bench-gateway-concurrency.ts", "--help"], {
124+
cwd: process.cwd(),
125+
encoding: "utf8",
126+
});
127+
128+
expect(result.status).toBe(0);
129+
expect(result.stdout).toContain("OpenClaw Gateway concurrency benchmark");
130+
});
131+
77132
it("ends CLI failures with the required wrapper marker", () => {
78-
const result = spawnSync(
79-
process.execPath,
80-
["--import", "tsx", "scripts/bench-gateway-concurrency.ts", "--wat"],
81-
{ cwd: process.cwd(), encoding: "utf8" },
82-
);
133+
const result = spawnSync(process.execPath, ["scripts/bench-gateway-concurrency.ts", "--wat"], {
134+
cwd: process.cwd(),
135+
encoding: "utf8",
136+
});
83137

84138
expect(result.status).toBe(1);
85139
expect(result.stderr.trim().split("\n").at(-1)).toBe(

‎test/scripts/check-gateway-cpu-scenarios.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ describe("gateway CPU scenario guard", () => {
186186
expect(calls.map((call) => call.args[0])).toEqual([
187187
"scripts/ensure-cli-startup-build.mjs",
188188
"--import",
189-
"--import",
189+
"scripts/bench-gateway-concurrency.ts",
190190
]);
191191
expect(calls[1]?.args).toContain("scripts/bench-gateway-startup.ts");
192192
expect(calls[2]?.args).toContain("scripts/bench-gateway-concurrency.ts");

0 commit comments

Comments
 (0)