Skip to content

Commit 174e771

Browse files
committed
fix(build): clean CLI startup metadata timeouts
1 parent b13af38 commit 174e771

2 files changed

Lines changed: 199 additions & 20 deletions

File tree

‎scripts/write-cli-startup-metadata.ts‎

Lines changed: 130 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ const extensionsDir = path.join(rootDir, "extensions");
2828
const ROOT_HELP_RENDER_TIMEOUT_MS = 120_000;
2929
const BROWSER_HELP_RENDER_TIMEOUT_MS = 120_000;
3030
const COMMAND_HELP_RENDER_TIMEOUT_MS = 120_000;
31+
const COMMAND_HELP_RENDER_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
32+
const COMMAND_HELP_RENDER_KILL_GRACE_MS = 5_000;
3133
const COMMAND_HELP_RENDER_CONCURRENCY = 2;
3234
const PRECOMPUTED_SUBCOMMAND_HELP_COMMANDS = ["doctor", "gateway", "models", "plugins"] as const;
3335
const CORE_CHANNEL_ORDER = [
@@ -291,37 +293,157 @@ async function spawnText(
291293
cwd: string;
292294
env: NodeJS.ProcessEnv;
293295
failureMessage: string;
296+
killGraceMs?: number;
297+
maxOutputBytes?: number;
294298
timeoutMs: number;
295299
},
296300
): Promise<string> {
301+
const maxOutputBytes = options.maxOutputBytes ?? COMMAND_HELP_RENDER_MAX_OUTPUT_BYTES;
302+
const killGraceMs = options.killGraceMs ?? COMMAND_HELP_RENDER_KILL_GRACE_MS;
303+
const useProcessGroup = process.platform !== "win32";
297304
return await new Promise((resolve, reject) => {
298305
const child = spawn(process.execPath, args, {
299306
cwd: options.cwd,
307+
detached: useProcessGroup,
300308
env: options.env,
301309
stdio: ["ignore", "pipe", "pipe"],
302310
});
303311
let stdout = "";
304312
let stderr = "";
313+
let outputBytes = 0;
314+
let outputExceeded = false;
305315
let settled = false;
306316
let timedOut = false;
317+
let waitingForKillGrace = false;
318+
let childClosedResult: { code: number | null; signal: NodeJS.Signals | null } | null = null;
319+
let killTimer: ReturnType<typeof setTimeout> | undefined;
320+
const parentSignalHandlers: { handler: () => void; signal: NodeJS.Signals }[] = [];
321+
const cleanupParentSignalHandlers = () => {
322+
for (const { signal, handler } of parentSignalHandlers) {
323+
process.off(signal, handler);
324+
}
325+
parentSignalHandlers.length = 0;
326+
};
327+
const signalChild = (signal: NodeJS.Signals) => {
328+
if (useProcessGroup && typeof child.pid === "number") {
329+
try {
330+
process.kill(-child.pid, signal);
331+
return;
332+
} catch (error) {
333+
if ((error as NodeJS.ErrnoException).code !== "ESRCH") {
334+
stderr += `failed to send ${signal} to process group: ${error instanceof Error ? error.message : String(error)}\n`;
335+
}
336+
}
337+
}
338+
child.kill(signal);
339+
};
340+
const relayParentSignal = (signal: NodeJS.Signals) => {
341+
const handler = () => {
342+
signalChild(signal);
343+
cleanupParentSignalHandlers();
344+
process.kill(process.pid, signal);
345+
};
346+
parentSignalHandlers.push({ handler, signal });
347+
process.once(signal, handler);
348+
};
349+
if (useProcessGroup) {
350+
relayParentSignal("SIGINT");
351+
relayParentSignal("SIGTERM");
352+
relayParentSignal("SIGHUP");
353+
}
354+
const processGroupIsAlive = () => {
355+
if (!useProcessGroup || typeof child.pid !== "number") {
356+
return false;
357+
}
358+
try {
359+
process.kill(-child.pid, 0);
360+
return true;
361+
} catch (error) {
362+
return (error as NodeJS.ErrnoException).code === "EPERM";
363+
}
364+
};
307365
const settle = (callback: () => void) => {
308366
if (settled) {
309367
return;
310368
}
311369
settled = true;
312370
clearTimeout(timeout);
371+
if (killTimer) {
372+
clearTimeout(killTimer);
373+
}
374+
cleanupParentSignalHandlers();
313375
callback();
314376
};
377+
const finishClose = (result: { code: number | null; signal: NodeJS.Signals | null }) => {
378+
settle(() => {
379+
if (result.code === 0 && !timedOut && !outputExceeded) {
380+
resolve(stdout);
381+
return;
382+
}
383+
const detail = stderr.trim();
384+
reject(
385+
new Error(
386+
options.failureMessage +
387+
(outputExceeded
388+
? `: output exceeded ${maxOutputBytes} bytes`
389+
: timedOut
390+
? `: timed out after ${options.timeoutMs}ms`
391+
: detail
392+
? `: ${detail}`
393+
: result.signal
394+
? `: terminated by ${result.signal}`
395+
: ""),
396+
),
397+
);
398+
});
399+
};
400+
const scheduleKill = () => {
401+
if (waitingForKillGrace) {
402+
return;
403+
}
404+
waitingForKillGrace = true;
405+
killTimer = setTimeout(() => {
406+
waitingForKillGrace = false;
407+
killTimer = undefined;
408+
signalChild("SIGKILL");
409+
if (childClosedResult) {
410+
finishClose(childClosedResult);
411+
}
412+
}, killGraceMs);
413+
};
414+
const requestStop = () => {
415+
signalChild("SIGTERM");
416+
scheduleKill();
417+
};
315418
const timeout = setTimeout(() => {
316419
timedOut = true;
317-
child.kill("SIGKILL");
420+
requestStop();
318421
}, options.timeoutMs);
422+
timeout.unref();
319423
child.stdout.setEncoding("utf8");
320424
child.stdout.on("data", (chunk: string) => {
425+
if (outputExceeded) {
426+
return;
427+
}
428+
outputBytes += Buffer.byteLength(chunk);
429+
if (outputBytes > maxOutputBytes) {
430+
outputExceeded = true;
431+
requestStop();
432+
return;
433+
}
321434
stdout += chunk;
322435
});
323436
child.stderr.setEncoding("utf8");
324437
child.stderr.on("data", (chunk: string) => {
438+
if (outputExceeded) {
439+
return;
440+
}
441+
outputBytes += Buffer.byteLength(chunk);
442+
if (outputBytes > maxOutputBytes) {
443+
outputExceeded = true;
444+
requestStop();
445+
return;
446+
}
325447
stderr += chunk;
326448
});
327449
child.once("error", (error) => {
@@ -330,25 +452,12 @@ async function spawnText(
330452
});
331453
});
332454
child.once("close", (code, signal) => {
333-
settle(() => {
334-
if (code === 0) {
335-
resolve(stdout);
336-
return;
337-
}
338-
const detail = stderr.trim();
339-
reject(
340-
new Error(
341-
options.failureMessage +
342-
(detail
343-
? `: ${detail}`
344-
: timedOut
345-
? ": timed out"
346-
: signal
347-
? `: terminated by ${signal}`
348-
: ""),
349-
),
350-
);
351-
});
455+
const result = { code, signal };
456+
if (waitingForKillGrace && processGroupIsAlive()) {
457+
childClosedResult = result;
458+
return;
459+
}
460+
finishClose(result);
352461
});
353462
});
354463
}
@@ -685,6 +794,7 @@ function hasAllPrecomputedSubcommandHelpText(value: unknown): boolean {
685794

686795
export const testing = {
687796
mapWithConcurrency,
797+
spawnText,
688798
};
689799

690800
export { testing as __testing };

‎test/scripts/write-cli-startup-metadata.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,28 @@ function writeStartupMetadataSourceSignatureFixture(rootDir: string): void {
4646
}
4747
}
4848

49+
function processIsAlive(pid: number): boolean {
50+
try {
51+
process.kill(pid, 0);
52+
return true;
53+
} catch (error) {
54+
return (error as NodeJS.ErrnoException).code === "EPERM";
55+
}
56+
}
57+
58+
async function waitForProcessExit(pid: number, timeoutMs = 1_000): Promise<void> {
59+
const deadline = Date.now() + timeoutMs;
60+
while (Date.now() < deadline) {
61+
if (!processIsAlive(pid)) {
62+
return;
63+
}
64+
await new Promise((resolve) => {
65+
setTimeout(resolve, 10);
66+
});
67+
}
68+
throw new Error(`process ${pid} was still alive after ${timeoutMs}ms`);
69+
}
70+
4971
describe("write-cli-startup-metadata", () => {
5072
const { createTempDir } = createScriptTestHarness();
5173

@@ -67,6 +89,53 @@ describe("write-cli-startup-metadata", () => {
6789
expect(peakActive).toBe(2);
6890
});
6991

92+
it("fails command help rendering when captured output exceeds the byte limit", async () => {
93+
await expect(
94+
__testing.spawnText(["--eval", "process.stdout.write('x'.repeat(2048))"], {
95+
cwd: process.cwd(),
96+
env: process.env,
97+
failureMessage: "render failed",
98+
killGraceMs: 25,
99+
maxOutputBytes: 1024,
100+
timeoutMs: 5_000,
101+
}),
102+
).rejects.toThrow("render failed: output exceeded 1024 bytes");
103+
});
104+
105+
it.runIf(process.platform !== "win32")(
106+
"kills descendant processes when command help rendering times out",
107+
async () => {
108+
const tempRoot = createTempDir("openclaw-startup-metadata-timeout-");
109+
const markerPath = path.join(tempRoot, "grandchild.pid");
110+
const grandchildScript = [
111+
"process.on('SIGTERM', () => {});",
112+
"setInterval(() => {}, 1000);",
113+
].join("\n");
114+
const parentScript = [
115+
"const { spawn } = await import('node:child_process');",
116+
"const { writeFileSync } = await import('node:fs');",
117+
`const grandchild = spawn(process.execPath, ["--eval", ${JSON.stringify(grandchildScript)}], { stdio: "ignore" });`,
118+
`writeFileSync(${JSON.stringify(markerPath)}, String(grandchild.pid));`,
119+
"process.on('SIGTERM', () => {});",
120+
"setInterval(() => {}, 1000);",
121+
].join("\n");
122+
123+
await expect(
124+
__testing.spawnText(["--input-type=module", "--eval", parentScript], {
125+
cwd: tempRoot,
126+
env: process.env,
127+
failureMessage: "render failed",
128+
killGraceMs: 25,
129+
maxOutputBytes: 1024,
130+
timeoutMs: 500,
131+
}),
132+
).rejects.toThrow("render failed: timed out after 500ms");
133+
134+
const grandchildPid = Number(readFileSync(markerPath, "utf8"));
135+
await waitForProcessExit(grandchildPid);
136+
},
137+
);
138+
70139
it("writes startup metadata with populated root help text when dist falls back to source rendering", async () => {
71140
const tempRoot = createTempDir("openclaw-startup-metadata-");
72141
const distDir = path.join(tempRoot, "dist");

0 commit comments

Comments
 (0)