Skip to content

Commit 3d5aefb

Browse files
committed
fix(e2e): finish telegram timeout cleanup promptly
1 parent 628314f commit 3d5aefb

2 files changed

Lines changed: 98 additions & 11 deletions

File tree

‎scripts/e2e/telegram-user-credential-io.ts‎

Lines changed: 45 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ type RunCommandOptions = {
2222
const DEFAULT_OUTPUT_LIMIT = 128 * 1024;
2323
const DEFAULT_FETCH_BODY_LIMIT = 1024 * 1024;
2424
const KILL_GRACE_MS = readKillGraceMs();
25+
const PROCESS_TREE_EXIT_POLL_MS = 50;
2526
const SIGNAL_EXIT_CODES = {
2627
SIGHUP: 129,
2728
SIGINT: 130,
@@ -141,8 +142,8 @@ export function runCommand(
141142
let stderr = "";
142143
let settled = false;
143144
let killTimer: NodeJS.Timeout | undefined;
144-
let pendingTimeoutReject: (() => void) | undefined;
145145
let timedOutError: Error | undefined;
146+
let forceKillAt: number | undefined;
146147
const timeoutMs = Math.max(1, options.timeoutMs);
147148
const timeoutKillGraceMs = Math.max(0, options.timeoutKillGraceMs ?? KILL_GRACE_MS);
148149
const clearTimers = () => {
@@ -168,10 +169,11 @@ export function runCommand(
168169
`${command} ${args.join(" ")} timed out after ${timeoutMs}ms\n${stdout}${stderr}`,
169170
);
170171
activeChildTree.killChildTree("SIGTERM");
172+
forceKillAt = Date.now() + timeoutKillGraceMs;
171173
killTimer = setTimeout(() => {
172174
killTimer = undefined;
175+
forceKillAt = undefined;
173176
activeChildTree.killChildTree("SIGKILL");
174-
pendingTimeoutReject?.();
175177
}, timeoutKillGraceMs);
176178
}, timeoutMs);
177179
timeout.unref?.();
@@ -195,15 +197,11 @@ export function runCommand(
195197
}
196198
if (timedOutError && killTimer && childProcessTreeMayStillExist(child)) {
197199
const error = timedOutError;
198-
pendingTimeoutReject = () => {
199-
if (settled) {
200-
return;
201-
}
202-
settled = true;
203-
clearTimers();
204-
activeChildTree.unregister();
205-
reject(error);
206-
};
200+
void finishTimedOutChildProcessTree(child, activeChildTree, {
201+
forceKillAt,
202+
killTimer,
203+
timeoutKillGraceMs,
204+
}).then(() => fail(error), fail);
207205
return;
208206
}
209207
settled = true;
@@ -223,6 +221,29 @@ export function runCommand(
223221
});
224222
}
225223

224+
async function finishTimedOutChildProcessTree(
225+
child: ReturnType<typeof spawn>,
226+
activeChildTree: ReturnType<typeof registerActiveChildProcessTree>,
227+
options: {
228+
forceKillAt: number | undefined;
229+
killTimer: NodeJS.Timeout;
230+
timeoutKillGraceMs: number;
231+
},
232+
) {
233+
const graceRemainingMs =
234+
options.forceKillAt === undefined
235+
? options.timeoutKillGraceMs
236+
: Math.max(0, options.forceKillAt - Date.now());
237+
if (graceRemainingMs > 0) {
238+
await waitForChildProcessTreeExit(child, graceRemainingMs);
239+
}
240+
clearTimeout(options.killTimer);
241+
if (childProcessTreeMayStillExist(child)) {
242+
activeChildTree.killChildTree("SIGKILL");
243+
await waitForChildProcessTreeExit(child, options.timeoutKillGraceMs);
244+
}
245+
}
246+
226247
function signalChildProcessTree(child: ReturnType<typeof spawn>, signal: NodeJS.Signals) {
227248
if (process.platform !== "win32" && child.pid) {
228249
try {
@@ -247,6 +268,19 @@ function childProcessTreeMayStillExist(child: ReturnType<typeof spawn>) {
247268
}
248269
}
249270

271+
async function waitForChildProcessTreeExit(child: ReturnType<typeof spawn>, timeoutMs: number) {
272+
const deadlineAt = Date.now() + timeoutMs;
273+
while (Date.now() < deadlineAt) {
274+
if (!childProcessTreeMayStillExist(child)) {
275+
return true;
276+
}
277+
await new Promise((resolvePoll) => {
278+
setTimeout(resolvePoll, PROCESS_TREE_EXIT_POLL_MS);
279+
});
280+
}
281+
return !childProcessTreeMayStillExist(child);
282+
}
283+
250284
function registerActiveChildProcessTree(child: ReturnType<typeof spawn>) {
251285
const killChildTree = (signal: NodeJS.Signals) => signalChildProcessTree(child, signal);
252286
ACTIVE_CHILD_TREE_KILLERS.add(killChildTree);

‎test/scripts/telegram-user-credential.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,59 @@ setInterval(() => {}, 1000);
315315
},
316316
);
317317

318+
it.runIf(process.platform !== "win32")(
319+
"rejects timed-out commands when descendant processes exit cleanly",
320+
async () => {
321+
const dir = makeTempDir("openclaw-telegram-credential-tree-timeout-clean-");
322+
const childPidPath = path.join(dir, "child.pid");
323+
const readyPath = path.join(dir, "child.ready");
324+
const cleanupPath = path.join(dir, "child.cleanup");
325+
let childPid: number | undefined;
326+
327+
try {
328+
const childScript = [
329+
"const fs = require('node:fs');",
330+
"process.on('SIGTERM', () => {",
331+
` fs.writeFileSync(${JSON.stringify(cleanupPath)}, 'clean');`,
332+
" setTimeout(() => process.exit(0), 75);",
333+
"});",
334+
`fs.writeFileSync(${JSON.stringify(readyPath)}, 'ready');`,
335+
"setInterval(() => {}, 1000);",
336+
].join("");
337+
const parentScript = [
338+
"const { spawn } = require('node:child_process');",
339+
`const child = spawn(process.execPath, ['-e', ${JSON.stringify(childScript)}], {`,
340+
" stdio: 'ignore',",
341+
"});",
342+
`require('node:fs').writeFileSync(${JSON.stringify(childPidPath)}, String(child.pid));`,
343+
"process.on('SIGTERM', () => process.exit(0));",
344+
"setInterval(() => {}, 1000);",
345+
].join("");
346+
347+
const startedAt = Date.now();
348+
const runPromise = runCommand(process.execPath, ["-e", parentScript], dir, {
349+
timeoutKillGraceMs: 1_000,
350+
timeoutMs: 1_000,
351+
});
352+
const runError = runPromise.catch((error: unknown) => error);
353+
await waitForFile(readyPath, 2_000);
354+
childPid = Number.parseInt(readFileSync(childPidPath, "utf8"), 10);
355+
356+
await expect(runError).resolves.toMatchObject({
357+
code: "ETIMEDOUT",
358+
message: expect.stringContaining("timed out after 1000ms"),
359+
});
360+
361+
expect(readFileSync(cleanupPath, "utf8")).toBe("clean");
362+
expect(Date.now() - startedAt).toBeLessThan(1_700);
363+
} finally {
364+
if (childPid !== undefined && isProcessAlive(childPid)) {
365+
process.kill(childPid, "SIGKILL");
366+
}
367+
}
368+
},
369+
);
370+
318371
it.runIf(process.platform !== "win32")("kills timed-out child process groups", async () => {
319372
const dir = makeTempDir("openclaw-telegram-credential-tree-timeout-");
320373
const childPidPath = path.join(dir, "child.pid");

0 commit comments

Comments
 (0)