Skip to content

Commit 448eb41

Browse files
authored
refactor(tooling): unify benchmark and process helpers (#125491)
* refactor(tooling): unify benchmark and process helpers * test(tooling): harden process fixture readiness * fix(tooling): keep benchmark harness types private
1 parent 7a507d8 commit 448eb41

19 files changed

Lines changed: 532 additions & 1343 deletions

‎scripts/bench-agent-concurrency.ts‎

Lines changed: 78 additions & 211 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,18 @@
1-
import { spawnSync } from "node:child_process";
2-
import fs from "node:fs";
3-
import path from "node:path";
41
import { pathToFileURL } from "node:url";
52
import { isRecord } from "@openclaw/normalization-core/record-coerce";
6-
import { classifyBoundedUnsignedDecimal } from "./lib/arg-utils.mts";
3+
import {
4+
emitBenchmarkReport,
5+
parseBenchmarkInteger,
6+
parseBenchmarkIntegerList,
7+
parseBenchmarkOptions,
8+
parseBenchmarkWorkerResult,
9+
runBenchmarkEntrypoint,
10+
runBenchmarkJobs,
11+
runBenchmarkWorker,
12+
summarizeBenchmarkTimings,
13+
type BenchmarkTimingSummary,
14+
type BenchmarkWorkerProcessResult,
15+
} from "./lib/benchmark-harness.mts";
716

817
const DEFAULT_FANOUT = [1, 8, 32, 64];
918
const DEFAULT_SWEEP_ROWS = [32, 128, 512];
@@ -39,15 +48,6 @@ type Options = {
3948
help: boolean;
4049
};
4150

42-
type TimingSummary = {
43-
count: number;
44-
min: number;
45-
p50: number;
46-
max: number;
47-
p95?: number;
48-
p99?: number;
49-
};
50-
5151
const SCENARIO_SPECS: ReadonlyArray<{
5252
scenario: WorkerScenario;
5353
sizes: "fanout" | "sweepRows";
@@ -114,13 +114,6 @@ const REQUIRED_INVARIANT_FIELDS: Record<WorkerScenario, readonly string[]> = {
114114
],
115115
};
116116

117-
type WorkerProcessResult = {
118-
status: number | null;
119-
stdout: string;
120-
stderr: string;
121-
error?: Error & { code?: string };
122-
};
123-
124117
type BenchmarkRuntime = {
125118
runWorker?: typeof runWorker;
126119
writeProgress?: (line: string) => void;
@@ -144,98 +137,35 @@ Options:
144137
`;
145138
}
146139

147-
function parseInteger(raw: string, flag: string, min: number, max: number): number {
148-
const result = classifyBoundedUnsignedDecimal(raw, min, max);
149-
if (result.kind === "syntax") {
150-
throw new Error(`${flag} must be an integer`);
151-
}
152-
if (result.kind === "below") {
153-
throw new Error(`${flag} must be at least ${min}`);
154-
}
155-
if (result.kind === "above") {
156-
throw new Error(`${flag} must be at most ${max}`);
157-
}
158-
return result.value;
159-
}
160-
161-
function parseList(raw: string, flag: string, max: number): number[] {
162-
if (!raw || raw.split(",").some((value) => value.length === 0)) {
163-
throw new Error(`${flag} requires a comma-separated integer list`);
164-
}
165-
const values = raw.split(",").map((value) => parseInteger(value, flag, 1, max));
166-
if (new Set(values).size !== values.length) {
167-
throw new Error(`${flag} contains duplicate values`);
168-
}
169-
return values;
170-
}
171-
172140
function parseOptions(argv: string[]): Options {
173-
const options: Options = {
174-
runs: 5,
175-
warmup: 1,
176-
fanout: DEFAULT_FANOUT,
177-
sweepRows: DEFAULT_SWEEP_ROWS,
178-
json: false,
179-
help: false,
180-
};
181-
const seen = new Set<string>();
182-
const valueFlags = new Set(["--runs", "--warmup", "--fanout", "--sweep-rows", "--output"]);
183-
for (let index = 0; index < argv.length; index += 1) {
184-
const flag = argv[index];
185-
if (!flag?.startsWith("--")) {
186-
throw new Error(`Unknown argument: ${flag}`);
187-
}
188-
if (seen.has(flag)) {
189-
throw new Error(`${flag} was provided more than once`);
190-
}
191-
seen.add(flag);
192-
if (flag === "--json" || flag === "--help") {
193-
options[flag === "--json" ? "json" : "help"] = true;
194-
continue;
195-
}
196-
if (!valueFlags.has(flag)) {
197-
throw new Error(`Unknown argument: ${flag}`);
198-
}
199-
const value = argv[index + 1];
200-
if (!value || value.startsWith("--")) {
201-
throw new Error(`${flag} requires a value`);
202-
}
203-
index += 1;
204-
if (flag === "--runs") {
205-
options.runs = parseInteger(value, flag, 1, 100);
206-
} else if (flag === "--warmup") {
207-
options.warmup = parseInteger(value, flag, 0, 20);
208-
} else if (flag === "--fanout") {
209-
options.fanout = parseList(value, flag, 256);
210-
} else if (flag === "--sweep-rows") {
211-
options.sweepRows = parseList(value, flag, 4096);
212-
} else {
213-
options.output = value;
214-
}
215-
}
216-
return options;
217-
}
218-
219-
function percentile(sorted: number[], ratio: number): number {
220-
return sorted[Math.max(0, Math.ceil(sorted.length * ratio) - 1)] ?? 0;
221-
}
222-
223-
function summarizeTimings(values: number[]): TimingSummary {
224-
if (values.length === 0) {
225-
throw new Error("cannot summarize an empty timing set");
226-
}
227-
const sorted = values.toSorted((left, right) => left - right);
228-
const summary: TimingSummary = {
229-
count: sorted.length,
230-
min: sorted[0] ?? 0,
231-
p50: percentile(sorted, 0.5),
232-
max: sorted.at(-1) ?? 0,
233-
};
234-
if (sorted.length >= 20) {
235-
summary.p95 = percentile(sorted, 0.95);
236-
summary.p99 = percentile(sorted, 0.99);
237-
}
238-
return summary;
141+
return parseBenchmarkOptions<Options>(
142+
argv,
143+
{
144+
runs: 5,
145+
warmup: 1,
146+
fanout: DEFAULT_FANOUT,
147+
sweepRows: DEFAULT_SWEEP_ROWS,
148+
json: false,
149+
help: false,
150+
},
151+
{
152+
"--runs": (options, value) => {
153+
options.runs = parseBenchmarkInteger(value, "--runs", 1, 100);
154+
},
155+
"--warmup": (options, value) => {
156+
options.warmup = parseBenchmarkInteger(value, "--warmup", 0, 20);
157+
},
158+
"--fanout": (options, value) => {
159+
options.fanout = parseBenchmarkIntegerList(value, "--fanout", 256);
160+
},
161+
"--sweep-rows": (options, value) => {
162+
options.sweepRows = parseBenchmarkIntegerList(value, "--sweep-rows", 4096);
163+
},
164+
"--output": (options, value) => {
165+
options.output = value;
166+
},
167+
},
168+
);
239169
}
240170

241171
function expectedWorkerKeys(options: Options): string[] {
@@ -275,7 +205,7 @@ function aggregateWorkerResults(
275205
}
276206
return {
277207
size,
278-
timingsMs: summarizeTimings(worker.timingsMs),
208+
timingsMs: summarizeBenchmarkTimings(worker.timingsMs),
279209
memory: worker.memory,
280210
invariant: worker.invariant,
281211
};
@@ -285,7 +215,7 @@ function aggregateWorkerResults(
285215
WorkerScenario,
286216
Array<{
287217
size: number;
288-
timingsMs: TimingSummary;
218+
timingsMs: BenchmarkTimingSummary;
289219
memory: WorkerResult["memory"];
290220
invariant: WorkerResult["invariant"];
291221
}>
@@ -377,42 +307,21 @@ function validateWorkerResult(
377307
}
378308

379309
function parseWorkerProcessResult(
380-
result: WorkerProcessResult,
310+
result: BenchmarkWorkerProcessResult,
381311
expected: { scenario: WorkerScenario; size: number; runs: number },
382312
): WorkerResult {
383-
if (result.error) {
384-
const detail =
385-
"code" in result.error && result.error.code === "ETIMEDOUT"
386-
? `timed out after ${WORKER_TIMEOUT_MS}ms`
387-
: result.error.message;
388-
throw new Error(`worker ${expected.scenario}:${expected.size} failed: ${detail}`);
389-
}
390-
if (result.status !== 0) {
391-
throw new Error(
392-
`worker ${expected.scenario}:${expected.size} failed (${result.status ?? "signal"}): ${result.stderr.trim() || result.stdout.trim()}`,
393-
);
394-
}
395-
const payloads = result.stdout
396-
.split(/\r?\n/u)
397-
.filter((line) => line.startsWith(WORKER_RESULT_SENTINEL));
398-
if (payloads.length !== 1) {
399-
throw new Error(
400-
`worker ${expected.scenario}:${expected.size} returned ${payloads.length} result payloads`,
401-
);
402-
}
403-
let parsed: unknown;
404-
try {
405-
parsed = JSON.parse(payloads[0]!.slice(WORKER_RESULT_SENTINEL.length));
406-
} catch {
407-
throw new Error(`worker ${expected.scenario}:${expected.size} returned invalid JSON`);
408-
}
409-
return validateWorkerResult(parsed, expected);
313+
return parseBenchmarkWorkerResult({
314+
result,
315+
label: `${expected.scenario}:${expected.size}`,
316+
sentinel: WORKER_RESULT_SENTINEL,
317+
timeoutMs: WORKER_TIMEOUT_MS,
318+
validate: (value) => validateWorkerResult(value, expected),
319+
});
410320
}
411321

412322
function runWorker(options: Options, scenario: WorkerScenario, size: number): WorkerResult {
413-
const result = spawnSync(
414-
process.execPath,
415-
[
323+
return runBenchmarkWorker({
324+
args: [
416325
"--import",
417326
"tsx",
418327
"scripts/bench-agent-concurrency-worker.ts",
@@ -425,16 +334,11 @@ function runWorker(options: Options, scenario: WorkerScenario, size: number): Wo
425334
"--warmup",
426335
String(options.warmup),
427336
],
428-
{
429-
cwd: process.cwd(),
430-
encoding: "utf8",
431-
env: { ...process.env, NODE_NO_WARNINGS: "1" },
432-
timeout: WORKER_TIMEOUT_MS,
433-
killSignal: "SIGTERM",
434-
maxBuffer: 16 * 1024 * 1024,
435-
},
436-
);
437-
return parseWorkerProcessResult(result, { scenario, size, runs: options.runs });
337+
label: `${scenario}:${size}`,
338+
sentinel: WORKER_RESULT_SENTINEL,
339+
timeoutMs: WORKER_TIMEOUT_MS,
340+
validate: (value) => validateWorkerResult(value, { scenario, size, runs: options.runs }),
341+
});
438342
}
439343

440344
function benchmark(options: Options, runtime: BenchmarkRuntime = {}) {
@@ -443,29 +347,12 @@ function benchmark(options: Options, runtime: BenchmarkRuntime = {}) {
443347
options[sizes].map((size) => ({ scenario, size })),
444348
);
445349
const run = runtime.runWorker ?? runWorker;
446-
const writeProgress =
447-
runtime.writeProgress ?? ((line: string) => process.stderr.write(`${line}\n`));
448-
const now = runtime.now ?? Date.now;
449-
const workers = jobs.map(({ scenario, size }, index) => {
450-
const ordinal = index + 1;
451-
writeProgress(
452-
`[bench-agent-concurrency] worker ${ordinal}/${jobs.length} start scenario=${scenario} size=${size}`,
453-
);
454-
const startedAt = now();
455-
try {
456-
const worker = run(options, scenario, size);
457-
const elapsedMs = Math.max(0, now() - startedAt);
458-
writeProgress(
459-
`[bench-agent-concurrency] worker ${ordinal}/${jobs.length} complete scenario=${scenario} size=${size} elapsed=${(elapsedMs / 1_000).toFixed(3)}s`,
460-
);
461-
return worker;
462-
} catch (error) {
463-
const elapsedMs = Math.max(0, now() - startedAt);
464-
writeProgress(
465-
`[bench-agent-concurrency] worker ${ordinal}/${jobs.length} failed scenario=${scenario} size=${size} elapsed=${(elapsedMs / 1_000).toFixed(3)}s`,
466-
);
467-
throw error;
468-
}
350+
const workers = runBenchmarkJobs(jobs, {
351+
prefix: "bench-agent-concurrency",
352+
describe: ({ scenario, size }) => `scenario=${scenario} size=${size}`,
353+
run: ({ scenario, size }) => run(options, scenario, size),
354+
now: runtime.now,
355+
writeProgress: runtime.writeProgress,
469356
});
470357
return aggregateWorkerResults(options, workers, {
471358
rssStartBytes,
@@ -480,48 +367,28 @@ async function main(argv = process.argv.slice(2)): Promise<void> {
480367
return;
481368
}
482369
const report = benchmark(options);
483-
const json = `${JSON.stringify(report, null, 2)}\n`;
484-
if (options.output) {
485-
fs.mkdirSync(path.dirname(path.resolve(options.output)), { recursive: true });
486-
fs.writeFileSync(options.output, json);
487-
}
488-
if (options.json) {
489-
process.stdout.write(json);
490-
return;
491-
}
492-
for (const [name, scenarios] of Object.entries(report.scenarios)) {
493-
for (const scenario of scenarios) {
494-
const tail =
495-
scenario.timingsMs.p95 === undefined
496-
? ""
497-
: ` p95=${scenario.timingsMs.p95.toFixed(3)}ms p99=${scenario.timingsMs.p99?.toFixed(3)}ms`;
498-
console.log(
499-
`${name} size=${scenario.size} p50=${scenario.timingsMs.p50.toFixed(3)}ms max=${scenario.timingsMs.max.toFixed(3)}ms${tail}`,
500-
);
501-
}
502-
}
503-
console.log(
504-
`max worker RSS ${(report.memory.workerProcessMaxRssBytes / 1024 / 1024).toFixed(1)} MiB`,
505-
);
370+
emitBenchmarkReport(report, options, (result) => [
371+
...Object.entries(result.scenarios).flatMap(([name, scenarios]) =>
372+
scenarios.map((scenario) => {
373+
const tail =
374+
scenario.timingsMs.p95 === undefined
375+
? ""
376+
: ` p95=${scenario.timingsMs.p95.toFixed(3)}ms p99=${scenario.timingsMs.p99?.toFixed(3)}ms`;
377+
return `${name} size=${scenario.size} p50=${scenario.timingsMs.p50.toFixed(3)}ms max=${scenario.timingsMs.max.toFixed(3)}ms${tail}`;
378+
}),
379+
),
380+
`max worker RSS ${(result.memory.workerProcessMaxRssBytes / 1024 / 1024).toFixed(1)} MiB`,
381+
]);
506382
}
507383

508384
export const testing = {
509385
aggregateWorkerResults,
510386
benchmark,
511387
parseOptions,
512388
parseWorkerProcessResult,
513-
summarizeTimings,
389+
summarizeTimings: summarizeBenchmarkTimings,
514390
};
515391

516392
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
517-
try {
518-
await main();
519-
} catch (error) {
520-
console.error(error instanceof Error ? error.message : String(error));
521-
process.exitCode = 1;
522-
} finally {
523-
if (process.exitCode && process.exitCode !== 0) {
524-
console.error(`[bench-agent-concurrency] FAILED (exit ${process.exitCode})`);
525-
}
526-
}
393+
await runBenchmarkEntrypoint("bench-agent-concurrency", main);
527394
}

0 commit comments

Comments
 (0)