Skip to content

Commit ee6e025

Browse files
fix(scripts): clean up tsgo process trees on timeout or signal (#123975)
* fix(scripts): bound tsgo runs with the managed-command watchdog run-tsgo bypassed the repo's managed-command seam and called spawnSync directly, so a wedged tsgo blocked its caller indefinitely: no timeout, no process-group cleanup, and no SIGKILL escalation. Observed in the wild as a tsgo holding 2.85 GB for 90+ minutes on 41s of total CPU with RSS frozen to the byte, ignoring SIGTERM, with its wrapper reparented to init. Because shouldReclaimLock() treats a live PID as a valid lock owner, that orphan also held the heavy-check lock until every other invocation hit the 10-minute lock timeout and threw. Route the run through runManagedCommand, which already owns process-group termination and SIGKILL escalation on timeout, and bound it with OPENCLAW_TSGO_TIMEOUT_MS (default 45m) through the shared readPositiveEnvInt helper, mirroring OPENCLAW_CLI_STARTUP_BUILD_TIMEOUT_MS in ensure-cli-startup-build.mts. * fix(scripts): saturate the tsgo watchdog at Node's timer ceiling An OPENCLAW_TSGO_TIMEOUT_MS above 2147483647 reached setTimeout unchanged, where Node collapses it to a 1ms delay, so raising the override killed healthy typechecks immediately instead of loosening the bound. * fix(scripts): make the tsgo watchdog opt-in and stop the harness leaking ClawSweeper review on 6ba02c9 raised two findings. [P1] The 45-minute default applied an unproven deadline to every tsgo invocation. No supported duration contract covers every host and project, and CI already bounds its own tsgo jobs at 15-20 minutes, so the default could only ever fire outside CI where it was least validated. Drop it: an unset OPENCLAW_TSGO_TIMEOUT_MS keeps the pre-existing unbounded wait, so no existing run changes behavior, and operators opt in per host. Documented in docs/help/testing.md beside the sibling Vitest watchdog. [P2] The regression harness could leak its wedged child. The fake compiler ignores SIGTERM by design, so a pre-fix or otherwise failing run left the tree running after spawnSync gave up. Bound the fixture's loop as a backstop. * fix(scripts): set the tsgo watchdog default from measured lane duration ClawSweeper on c7a699e reversed its earlier guidance: the opt-in default adopted last iteration "deliberately preserves the indefinite tsgo hang that this PR is meant to fix". Its objection was never that a default existed, only that 45 minutes was unmeasured. Measured instead of guessed: hosted tsgo lanes (check-test-types, and its core stripes) complete in 1-2 minutes across recent successful main runs, against CI job caps of 15-20 minutes. 30 minutes is 15-30x the observed duration, leaves room for a far slower local host, and still bounds the 90-minute and multi-hour wedges that motivated this PR. OPENCLAW_TSGO_TIMEOUT_MS remains the documented override for hosts that need longer. * test(scripts): reap the wedged fake tsgo tree on the harness outer timeout ClawSweeper on 0d9f360 flagged that the harness can still leave a detached pre-fix process tree alive after its outer timeout. The bounded fixture loop added earlier only capped the leak; it did not terminate the tree. spawnSync's killSignal reaches the direct child only. runManagedCommand spawns the compiler detached into its own process group, so the fake tsgo is a grandchild that never receives that signal. The fixture now records its pid and the harness reaps that group in a finally, with the bounded loop kept as a last-resort backstop. Verified: pid file written with the live pid, and killing that group terminates the tree; focused suite 16/16 with no surviving fake-tsgo processes. * fix(scripts): harden the tsgo watchdog after two-phase code review Review fixes on top of the watchdog change, from one native pass and six cold passes: - A rejected OPENCLAW_TSGO_TIMEOUT_MS escaped main() as a raw module rejection. It now reports one actionable line and exits 1. Strict validation was kept rather than switching to coercion, so a typo cannot silently fall back to the 30-minute default. - The rejection message named a numeric range while the parser enforces plain decimal digits, so 1e5 and 007 were refused by a message saying they qualified. It now names the real format and states that the watchdog cannot be disabled. - The timer ceiling is declared locally rather than imported from packages/. A static import there resolves before the sparse-checkout guard runs, which turned a clean sparse skip into ERR_MODULE_NOT_FOUND and flipped check-changed's typecheck lane from exit 0 to exit 1. - The wedge test asserted the kill message but not the outcome; it now captures the wedged pid and asserts the process group is gone. - Three near-duplicate "not killed" cases are table-driven. - Doc bullet corrected: values ABOVE the ceiling saturate at it, and the rejected-value list now includes non-decimal input. Deferred follow-up, not fixed here: scripts/lib/tsx-cli-shim.mjs shares a 5000ms force-kill delay with managed-child-process, so Ctrl-C can still orphan a wedged compiler about one run in three. Measured base 4/4 orphaned versus 4/10 here, so this change improves it; the fix is out of diff and shared with four other wrappers. * fix(scripts): close tsgo signal cleanup race * fix(scripts): make tsgo watchdog opt-in --------- Co-authored-by: ClawSweeper <[email protected]>
1 parent 000db97 commit ee6e025

5 files changed

Lines changed: 246 additions & 23 deletions

File tree

‎docs/help/testing.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,17 @@ Native dependency policy:
700700
after 5 minutes with no stdout or stderr output. Set
701701
`OPENCLAW_VITEST_NO_OUTPUT_TIMEOUT_MS=0` to disable the watchdog for
702702
an intentionally silent investigation.
703+
- `scripts/run-tsgo.mjs` leaves tsgo unbounded by default, preserving the
704+
behavior of existing local workflows. Set `OPENCLAW_TSGO_TIMEOUT_MS` to
705+
a positive millisecond value to make a wedged compiler fail loudly
706+
instead of blocking its caller forever. On expiry the whole tsgo process
707+
tree is killed and the run fails. Values above Node's timer
708+
ceiling saturate at it instead of collapsing to a 1ms deadline; `0`, a
709+
negative, a fraction, or anything above `Number.MAX_SAFE_INTEGER` is
710+
rejected and fails the run. Surrounding whitespace is trimmed first;
711+
the remaining value must use plain decimal digits without leading zeros,
712+
so values such as `1e5` or `007` are rejected. Unset the variable to
713+
disable the watchdog.
703714
704715
</Accordion>
705716

‎scripts/lib/tsx-cli-shim.mjs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import path from "node:path";
66
import { fileURLToPath, pathToFileURL } from "node:url";
77

88
const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
9-
const FORCE_KILL_DELAY_MS = 5_000;
9+
const DEFAULT_FORCE_KILL_DELAY_MS = 5_000;
1010
const SHIM_CHECKOUT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
1111

1212
function resolvePrimaryRoot(checkoutRoot) {
@@ -78,6 +78,7 @@ function signalChild(child, signal, detached) {
7878

7979
async function runTsxCliShimInner(moduleUrl, options) {
8080
const detached = options.detached ?? (process.platform !== "win32" && !process.stdin.isTTY);
81+
const forceKillDelayMs = options.forceKillDelayMs ?? DEFAULT_FORCE_KILL_DELAY_MS;
8182
let child = null;
8283
let forceKillTimer = null;
8384
const signalHandlers = new Map();
@@ -98,7 +99,7 @@ async function runTsxCliShimInner(moduleUrl, options) {
9899
signalChild(child, signal, detached);
99100
forceKillTimer ??= setTimeout(
100101
() => signalChild(child, "SIGKILL", detached),
101-
FORCE_KILL_DELAY_MS,
102+
forceKillDelayMs,
102103
);
103104
forceKillTimer.unref();
104105
};

‎scripts/run-tsgo.mjs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,7 @@ import { runTsxCliShim } from "./lib/tsx-cli-shim.mjs";
33
await runTsxCliShim(import.meta.url, {
44
implementation: "./run-tsgo.mts",
55
failureTool: "tsgo",
6+
// The implementation owns a detached compiler group and escalates after 5s.
7+
// Its outer shim must stay alive long enough to finish that cleanup.
8+
forceKillDelayMs: 10_000,
69
});

‎scripts/run-tsgo.mts‎

Lines changed: 50 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
// Runs tsgo through local resource policy and sparse-checkout guards.
2-
import { spawnSync } from "node:child_process";
32
import fs from "node:fs";
43
import os from "node:os";
54
import path from "node:path";
@@ -10,13 +9,30 @@ import {
109
resolveLocalCheckEnv,
1110
resolveRepoToolBinPath,
1211
} from "./lib/local-check-runtime.mts";
13-
import { createManagedCommandInvocation } from "./lib/managed-child-process.mts";
12+
import { runManagedCommand } from "./lib/managed-child-process.mts";
13+
import { readPositiveEnvInt } from "./lib/numeric-options.mjs";
1414
import {
1515
getSparseTsgoGuardError,
1616
shouldSkipSparseTsgoGuardError,
1717
} from "./lib/tsgo-sparse-guard.mts";
1818

19-
function main(): void {
19+
// Declared locally, as sibling scripts do, rather than imported from packages/:
20+
// a static import there resolves before the sparse-checkout guard can report a
21+
// missing project, turning a clean skip into ERR_MODULE_NOT_FOUND. Mirrors
22+
// normalization-core's MAX_TIMER_TIMEOUT_MS.
23+
const MAX_TIMER_TIMEOUT_MS = 2_147_000_000;
24+
25+
export function resolveTsgoTimeoutMs(env: NodeJS.ProcessEnv): number | undefined {
26+
if (!env.OPENCLAW_TSGO_TIMEOUT_MS?.trim()) {
27+
return undefined;
28+
}
29+
return Math.min(
30+
readPositiveEnvInt("OPENCLAW_TSGO_TIMEOUT_MS", env, MAX_TIMER_TIMEOUT_MS),
31+
MAX_TIMER_TIMEOUT_MS,
32+
);
33+
}
34+
35+
async function main(): Promise<void> {
2036
const hostResources = {
2137
logicalCpuCount:
2238
typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length,
@@ -46,25 +62,39 @@ function main(): void {
4662
}
4763

4864
ensureRepoToolNodeModulesLink(tsgoPath);
49-
const tsgo = createManagedCommandInvocation({
50-
args: finalArgs,
51-
bin: tsgoPath,
52-
env,
53-
});
54-
const result = spawnSync(tsgo.command, tsgo.args, {
55-
stdio: "inherit",
56-
env,
57-
shell: tsgo.shell,
58-
windowsVerbatimArguments: tsgo.windowsVerbatimArguments,
59-
});
60-
61-
if (result.error) {
62-
throw result.error;
65+
let timeoutMs: number | undefined;
66+
try {
67+
timeoutMs = resolveTsgoTimeoutMs(env);
68+
} catch {
69+
// main() is top-level awaited, so an escaping parse error would surface as a raw
70+
// module rejection with no guidance about the variable that caused it.
71+
console.error(
72+
`[tsgo] OPENCLAW_TSGO_TIMEOUT_MS must be plain decimal digits with no leading zero, sign, exponent, or decimal point, between 1 and ${Number.MAX_SAFE_INTEGER}; got ${env.OPENCLAW_TSGO_TIMEOUT_MS}. Unset it to disable the watchdog.`,
73+
);
74+
process.exitCode = 1;
75+
return;
76+
}
77+
try {
78+
// Managed run owns the whole tsgo process tree: on timeout it SIGKILLs the
79+
// process group, because a wedged checker ignores SIGTERM and would otherwise
80+
// block the caller forever on a compiler that will never report.
81+
process.exitCode = await runManagedCommand({
82+
bin: tsgoPath,
83+
args: finalArgs,
84+
env,
85+
timeoutMs,
86+
});
87+
} catch (error) {
88+
if ((error as { code?: string } | undefined)?.code !== "ETIMEDOUT") {
89+
throw error;
90+
}
91+
console.error(
92+
`[tsgo] no completion after ${timeoutMs}ms; killed the tsgo process tree. Raise OPENCLAW_TSGO_TIMEOUT_MS for intentionally longer builds, or unset it to disable the watchdog.`,
93+
);
94+
process.exitCode = 1;
6395
}
64-
65-
process.exitCode = result.status ?? 1;
6696
}
6797

6898
if (import.meta.main) {
69-
main();
99+
await main();
70100
}

‎test/scripts/run-tsgo.test.ts‎

Lines changed: 179 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Run Tsgo tests cover run tsgo script behavior.
2-
import { spawnSync } from "node:child_process";
2+
import { spawn, spawnSync } from "node:child_process";
33
import fs from "node:fs";
44
import path from "node:path";
55
import { describe, expect, it } from "vitest";
@@ -8,6 +8,8 @@ import {
88
getSparseTsgoGuardError,
99
shouldSkipSparseTsgoGuardError,
1010
} from "../../scripts/lib/tsgo-sparse-guard.mts";
11+
import { resolveTsgoTimeoutMs } from "../../scripts/run-tsgo.mts";
12+
import { waitForChildClose, waitForDead, waitForPidFile } from "../helpers/process-wait.js";
1113
import { createScriptTestHarness } from "./test-helpers.js";
1214

1315
const { createTempDir } = createScriptTestHarness();
@@ -232,3 +234,179 @@ describe("run-tsgo sparse guard", () => {
232234
});
233235
});
234236
});
237+
238+
describe.skipIf(process.platform === "win32")("run-tsgo watchdog", () => {
239+
it("keeps the watchdog opt-in", () => {
240+
expect(resolveTsgoTimeoutMs({})).toBeUndefined();
241+
expect(resolveTsgoTimeoutMs({ OPENCLAW_TSGO_TIMEOUT_MS: " " })).toBeUndefined();
242+
expect(resolveTsgoTimeoutMs({ OPENCLAW_TSGO_TIMEOUT_MS: "30000" })).toBe(30_000);
243+
});
244+
245+
function writeFakeTsgo(cwd: string, body: string) {
246+
const binDir = path.join(cwd, "node_modules", ".bin");
247+
fs.mkdirSync(binDir, { recursive: true });
248+
const fakeTsgo = path.join(binDir, "tsgo");
249+
fs.writeFileSync(fakeTsgo, body, "utf8");
250+
fs.chmodSync(fakeTsgo, 0o755);
251+
}
252+
253+
// The fake compiler is a grandchild in its own process group, so spawnSync's
254+
// killSignal never reaches it. Its recorded pid is the only handle the harness
255+
// has to tear the tree down when the outer timeout fires on a pre-fix run.
256+
function readFakeTsgoPid(cwd: string) {
257+
const pidFile = path.join(cwd, "fake-tsgo.pid");
258+
if (!fs.existsSync(pidFile)) {
259+
return undefined;
260+
}
261+
const pid = Number.parseInt(fs.readFileSync(pidFile, "utf8").trim(), 10);
262+
return Number.isInteger(pid) && pid > 1 ? pid : undefined;
263+
}
264+
265+
function reapFakeTsgo(cwd: string) {
266+
const pid = readFakeTsgoPid(cwd);
267+
if (pid === undefined) {
268+
return;
269+
}
270+
for (const target of [-pid, pid]) {
271+
try {
272+
process.kill(target, "SIGKILL");
273+
} catch {
274+
// Already reaped by the watchdog under test.
275+
}
276+
}
277+
}
278+
279+
function runFakeTsgo(
280+
cwd: string,
281+
timeoutMs: string | undefined,
282+
onBeforeReap?: (pid: number | undefined) => void,
283+
) {
284+
const { OPENCLAW_TSGO_TIMEOUT_MS: _unset, ...baseEnv } = process.env;
285+
try {
286+
return spawnSync(
287+
process.execPath,
288+
[path.resolve("scripts/run-tsgo.mjs"), "-p", "tsconfig.extensions.json"],
289+
{
290+
cwd,
291+
encoding: "utf8",
292+
env:
293+
timeoutMs === undefined ? baseEnv : { ...baseEnv, OPENCLAW_TSGO_TIMEOUT_MS: timeoutMs },
294+
// spawnSync blocks this thread, so vitest's own per-test budget can never
295+
// fire; a regression here would hang the worker instead of failing.
296+
timeout: 25_000,
297+
killSignal: "SIGKILL",
298+
},
299+
);
300+
} finally {
301+
onBeforeReap?.(readFakeTsgoPid(cwd));
302+
reapFakeTsgo(cwd);
303+
}
304+
}
305+
306+
it.each([{ bound: "0" }, { bound: "abc" }])(
307+
"explains a rejected OPENCLAW_TSGO_TIMEOUT_MS of $bound instead of crashing",
308+
({ bound }) => {
309+
const cwd = createTempDir("openclaw-run-tsgo-watchdog-");
310+
writeFakeTsgo(cwd, "#!/bin/sh\nexit 0\n");
311+
312+
const result = runFakeTsgo(cwd, bound);
313+
314+
expect(result.status).toBe(1);
315+
expect(result.stderr).toContain("must be plain decimal digits");
316+
expect(result.stderr).toContain("Unset it to disable the watchdog");
317+
expect(result.stderr).not.toContain("at readPositiveEnvInt");
318+
expect(result.stderr.trim().split("\n").at(-1)).toBe("[tsgo] FAILED (exit 1)");
319+
},
320+
30_000,
321+
);
322+
323+
it("kills a wedged tsgo that ignores SIGTERM instead of blocking its caller forever", () => {
324+
const cwd = createTempDir("openclaw-run-tsgo-watchdog-");
325+
// Mirrors the observed wedge: the checker refuses SIGTERM and never reports,
326+
// so only a process-group SIGKILL frees the caller. It records its pid so the
327+
// harness can reap the tree, and self-exits as a last-resort backstop.
328+
writeFakeTsgo(
329+
cwd,
330+
'#!/bin/sh\necho $$ > "$(dirname "$0")/../../fake-tsgo.pid"\ntrap \'\' TERM\ni=0\nwhile [ $i -lt 60 ]; do sleep 1; i=$((i+1)); done\n',
331+
);
332+
333+
const observedBeforeReap = {
334+
error: undefined as unknown,
335+
pid: undefined as number | undefined,
336+
};
337+
const result = runFakeTsgo(cwd, "2000", (pid) => {
338+
observedBeforeReap.pid = pid;
339+
if (pid === undefined) {
340+
return;
341+
}
342+
try {
343+
process.kill(pid, 0);
344+
} catch (error) {
345+
observedBeforeReap.error = error;
346+
}
347+
});
348+
349+
expect(result.status).toBe(1);
350+
expect(result.stderr).toContain("killed the tsgo process tree");
351+
// Printing the message is not the contract; the tree actually being gone is.
352+
expect(observedBeforeReap.pid).toBeDefined();
353+
expect(observedBeforeReap.error).toMatchObject({ code: "ESRCH" });
354+
expect(result.stderr.trim().split("\n").at(-1)).toBe("[tsgo] FAILED (exit 1)");
355+
}, 30_000);
356+
357+
it("lets the inner supervisor reap a wedged compiler before the wrapper exits on SIGTERM", async () => {
358+
const cwd = createTempDir("openclaw-run-tsgo-signal-");
359+
const pidFile = path.join(cwd, "fake-tsgo.pid");
360+
fs.writeFileSync(path.join(cwd, "tsconfig.extensions.json"), "{}\n");
361+
writeFakeTsgo(
362+
cwd,
363+
'#!/bin/sh\necho $$ > "$(dirname "$0")/../../fake-tsgo.pid"\ntrap \'\' TERM HUP INT\nwhile true; do sleep 1; done\n',
364+
);
365+
const wrapper = spawn(
366+
process.execPath,
367+
[path.resolve("scripts/run-tsgo.mjs"), "-p", "tsconfig.extensions.json"],
368+
{ cwd, stdio: "ignore" },
369+
);
370+
371+
try {
372+
const compilerPid = await waitForPidFile(pidFile, 10_000);
373+
wrapper.kill("SIGTERM");
374+
375+
await expect(waitForChildClose(wrapper, 15_000)).resolves.toEqual({
376+
code: 143,
377+
signal: null,
378+
});
379+
await expect(waitForDead(compilerPid, 2_000)).resolves.toBeUndefined();
380+
} finally {
381+
if (wrapper.exitCode === null && wrapper.signalCode === null) {
382+
wrapper.kill("SIGKILL");
383+
}
384+
reapFakeTsgo(cwd);
385+
}
386+
}, 20_000);
387+
388+
// Every bound that must leave a completing compiler alone. The ceiling case is the
389+
// regression that matters: without saturation Node collapses the delay to 1ms and
390+
// would kill this sleeping child immediately.
391+
it.each([
392+
{ bound: undefined, name: "the disabled watchdog", body: "#!/bin/sh\nsleep 2\nexit 0\n" },
393+
{ bound: "30000", name: "an explicit bound", body: "#!/bin/sh\nexit 0\n" },
394+
{
395+
bound: "2147483648",
396+
name: "an override past Node's timer ceiling",
397+
body: "#!/bin/sh\nsleep 1\nexit 0\n",
398+
},
399+
])(
400+
"leaves a completing tsgo alone under $name",
401+
({ bound, body }) => {
402+
const cwd = createTempDir("openclaw-run-tsgo-watchdog-");
403+
writeFakeTsgo(cwd, body);
404+
405+
const result = runFakeTsgo(cwd, bound);
406+
407+
expect(result.status).toBe(0);
408+
expect(result.stderr).not.toContain("killed the tsgo process tree");
409+
},
410+
30_000,
411+
);
412+
});

0 commit comments

Comments
 (0)