Skip to content

Commit 74c1900

Browse files
authored
refactor(tooling): unify managed child process cleanup (#127480)
1 parent ee468b8 commit 74c1900

16 files changed

Lines changed: 514 additions & 841 deletions

‎scripts/bench-cli-startup.ts‎

Lines changed: 26 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ import os from "node:os";
55
import path from "node:path";
66
import { pathToFileURL } from "node:url";
77
import { expectDefined } from "../packages/normalization-core/src/expect.js";
8+
import {
9+
inspectManagedProcessGroup,
10+
terminateManagedChild,
11+
waitForManagedProcessGroupExit,
12+
} from "./lib/managed-child-process.mts";
813

914
type CommandCase = {
1015
id: string;
@@ -116,7 +121,6 @@ const DEFAULT_WARMUP = 1;
116121
const DEFAULT_TIMEOUT_MS = 30_000;
117122
const DEFAULT_TIMEOUT_KILL_GRACE_MS = 1_000;
118123
const TIMEOUT_KILL_GRACE_MS = resolveTimeoutKillGraceMs(process.env);
119-
const PROCESS_GROUP_EXIT_POLL_MS = 25;
120124
const DEFAULT_ENTRY = "openclaw.mjs";
121125
const MAX_RSS_MARKER = "__OPENCLAW_MAX_RSS_KB__=";
122126

@@ -799,10 +803,9 @@ async function runSample(params: {
799803

800804
try {
801805
return await new Promise<Sample>((resolve) => {
802-
const useProcessGroup = process.platform !== "win32";
803806
const proc = spawn(process.execPath, nodeArgs, {
804807
cwd: process.cwd(),
805-
detached: useProcessGroup,
808+
detached: process.platform !== "win32",
806809
env: {
807810
...process.env,
808811
HOME: runRoot,
@@ -846,10 +849,10 @@ async function runSample(params: {
846849

847850
const timeout = setTimeout(() => {
848851
timedOut = true;
849-
signalSampleProcess(proc, "SIGTERM", useProcessGroup);
852+
signalSampleProcess(proc, "SIGTERM");
850853
forceKillAt = Date.now() + TIMEOUT_KILL_GRACE_MS;
851854
forceKillTimer = setTimeout(() => {
852-
signalSampleProcess(proc, "SIGKILL", useProcessGroup);
855+
signalSampleProcess(proc, "SIGKILL");
853856
}, TIMEOUT_KILL_GRACE_MS).unref?.();
854857
}, params.timeoutMs);
855858
timeout.unref?.();
@@ -889,12 +892,11 @@ async function runSample(params: {
889892
stderrTail: tailLines(stderr, 20),
890893
}),
891894
});
892-
if (timedOut && isSampleProcessGroupAlive(proc, useProcessGroup)) {
895+
if (timedOut && isSampleProcessGroupAlive(proc)) {
893896
void finishAfterTimeoutCleanup({
894897
complete,
895898
forceKillAt,
896899
proc,
897-
useProcessGroup,
898900
});
899901
return;
900902
}
@@ -912,74 +914,48 @@ async function finishAfterTimeoutCleanup(params: {
912914
complete: () => void;
913915
forceKillAt: number | null;
914916
proc: ReturnType<typeof spawn>;
915-
useProcessGroup: boolean;
916917
}): Promise<void> {
917918
const graceRemainingMs =
918919
params.forceKillAt === null
919920
? TIMEOUT_KILL_GRACE_MS
920921
: Math.max(0, params.forceKillAt - Date.now());
921922
if (graceRemainingMs > 0) {
922-
await waitForSampleProcessGroupExit(params.proc, params.useProcessGroup, graceRemainingMs);
923+
await waitForSampleProcessGroupExit(params.proc, graceRemainingMs);
923924
}
924-
if (isSampleProcessGroupAlive(params.proc, params.useProcessGroup)) {
925-
signalSampleProcess(params.proc, "SIGKILL", params.useProcessGroup);
925+
if (isSampleProcessGroupAlive(params.proc)) {
926+
signalSampleProcess(params.proc, "SIGKILL");
926927
}
927-
await waitForSampleProcessGroupExit(params.proc, params.useProcessGroup, TIMEOUT_KILL_GRACE_MS);
928+
await waitForSampleProcessGroupExit(params.proc, TIMEOUT_KILL_GRACE_MS);
928929
params.complete();
929930
}
930931

931-
function signalSampleProcess(
932-
proc: ReturnType<typeof spawn>,
933-
signal: NodeJS.Signals,
934-
useProcessGroup: boolean,
935-
): void {
932+
function signalSampleProcess(proc: ReturnType<typeof spawn>, signal: NodeJS.Signals): void {
936933
if (!proc.pid) {
937934
return;
938935
}
939-
try {
940-
if (useProcessGroup) {
941-
process.kill(-proc.pid, signal);
942-
} else {
943-
proc.kill(signal);
944-
}
945-
} catch (error) {
936+
const handleSignalError = (error: unknown) => {
946937
const code = (error as NodeJS.ErrnoException | undefined)?.code;
947938
if (code !== "ESRCH" && code !== "EPERM") {
948939
throw error;
949940
}
950-
}
941+
};
942+
terminateManagedChild(proc, signal, {
943+
onChildSignalError: handleSignalError,
944+
onProcessGroupSignalError: handleSignalError,
945+
processGroupFallback: "never",
946+
useWindowsTaskkill: false,
947+
});
951948
}
952949

953-
function isSampleProcessGroupAlive(
954-
proc: ReturnType<typeof spawn>,
955-
useProcessGroup: boolean,
956-
): boolean {
957-
if (!useProcessGroup || !proc.pid) {
958-
return false;
959-
}
960-
try {
961-
process.kill(-proc.pid, 0);
962-
return true;
963-
} catch (error) {
964-
return (error as NodeJS.ErrnoException | undefined)?.code === "EPERM";
965-
}
950+
function isSampleProcessGroupAlive(proc: ReturnType<typeof spawn>): boolean {
951+
return inspectManagedProcessGroup(proc, { errorPolicy: "alive-on-eperm" }) === "live";
966952
}
967953

968-
async function waitForSampleProcessGroupExit(
954+
function waitForSampleProcessGroupExit(
969955
proc: ReturnType<typeof spawn>,
970-
useProcessGroup: boolean,
971956
timeoutMs: number,
972957
): Promise<boolean> {
973-
const deadlineAt = Date.now() + timeoutMs;
974-
while (Date.now() < deadlineAt) {
975-
if (!isSampleProcessGroupAlive(proc, useProcessGroup)) {
976-
return true;
977-
}
978-
await new Promise((resolvePoll) => {
979-
setTimeout(resolvePoll, PROCESS_GROUP_EXIT_POLL_MS);
980-
});
981-
}
982-
return !isSampleProcessGroupAlive(proc, useProcessGroup);
958+
return waitForManagedProcessGroupExit(proc, timeoutMs, { errorPolicy: "alive-on-eperm" });
983959
}
984960

985961
async function runCase(params: {

‎scripts/dev/tui-pty-test-watch.ts‎

Lines changed: 11 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
// Tui Pty Test Watch script supports OpenClaw repository automation.
2-
import { spawn, spawnSync } from "node:child_process";
2+
import { spawn } from "node:child_process";
33
import { mkdir, open, writeFile } from "node:fs/promises";
44
import { createRequire } from "node:module";
55
import path from "node:path";
66
import { pathToFileURL } from "node:url";
7+
import { terminateManagedChild } from "../lib/managed-child-process.mts";
78
import { sleep as delay } from "../lib/sleep.mjs";
8-
import { resolveWindowsTaskkillPath } from "../lib/windows-taskkill.mjs";
99

1010
type Options = {
1111
altScreen: boolean;
@@ -48,12 +48,6 @@ type ChildStopper = {
4848

4949
type SignalChild = (child: KillableChild, signal: NodeJS.Signals) => void;
5050

51-
type RunTaskkill = (
52-
command: string,
53-
args: string[],
54-
options: { stdio: "ignore" },
55-
) => { error?: unknown; status?: number | null } | undefined;
56-
5751
function unrefTimer(timer: ReturnType<typeof setTimeout>): void {
5852
(timer as { unref?: () => void }).unref?.();
5953
}
@@ -133,60 +127,6 @@ function currentTerminalDimension(value: number | undefined, fallback: number):
133127
return String(value && value > 0 ? value : fallback);
134128
}
135129

136-
function signalWindowsProcessTree(
137-
pid: number,
138-
signal: NodeJS.Signals,
139-
runTaskkill: RunTaskkill = spawnSync,
140-
): boolean {
141-
const args = ["/PID", String(pid), "/T"];
142-
if (signal === "SIGKILL") {
143-
args.push("/F");
144-
}
145-
const result = runTaskkill(resolveWindowsTaskkillPath(), args, { stdio: "ignore" });
146-
return !result?.error && result?.status === 0;
147-
}
148-
149-
function signalWindowsProcessTreeOrForce(
150-
pid: number,
151-
signal: NodeJS.Signals,
152-
runTaskkill: RunTaskkill = spawnSync,
153-
): boolean {
154-
if (signalWindowsProcessTree(pid, signal, runTaskkill)) {
155-
return true;
156-
}
157-
return signal !== "SIGKILL" && signalWindowsProcessTree(pid, "SIGKILL", runTaskkill);
158-
}
159-
160-
function signalChildProcessTree(
161-
child: KillableChild,
162-
signal: NodeJS.Signals,
163-
{
164-
platform = process.platform,
165-
runTaskkill = spawnSync,
166-
useProcessGroup = platform !== "win32",
167-
}: {
168-
platform?: NodeJS.Platform;
169-
runTaskkill?: RunTaskkill;
170-
useProcessGroup?: boolean;
171-
} = {},
172-
): void {
173-
if (useProcessGroup && typeof child.pid === "number") {
174-
try {
175-
process.kill(-child.pid, signal);
176-
return;
177-
} catch {
178-
// Non-detached fallback or already-exited group; direct child signaling is
179-
// still useful on platforms without process groups.
180-
}
181-
}
182-
if (platform === "win32" && typeof child.pid === "number") {
183-
if (signalWindowsProcessTreeOrForce(child.pid, signal, runTaskkill)) {
184-
return;
185-
}
186-
}
187-
child.kill(signal);
188-
}
189-
190130
function createChildStopper(
191131
child: KillableChild,
192132
options: {
@@ -195,7 +135,15 @@ function createChildStopper(
195135
sigkillGraceMs?: number;
196136
} = {},
197137
): ChildStopper {
198-
const signalChild = options.signalChild ?? signalChildProcessTree;
138+
const signalChild =
139+
options.signalChild ??
140+
((targetChild, signal) =>
141+
terminateManagedChild(targetChild, signal, {
142+
onChildSignalError(error) {
143+
throw error;
144+
},
145+
taskkillTimeoutMs: null,
146+
}));
199147
const sigtermGraceMs = options.sigtermGraceMs ?? CHILD_SIGTERM_GRACE_MS;
200148
const sigkillGraceMs = options.sigkillGraceMs ?? CHILD_SIGKILL_GRACE_MS;
201149
let stopping = false;
@@ -523,5 +471,4 @@ export const testing = {
523471
drainNewMirrorData,
524472
parseOptions,
525473
readNewMirrorData,
526-
signalChildProcessTree,
527474
};

‎scripts/e2e/parallels/host-command.ts‎

Lines changed: 40 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,11 @@ import {
88
addTimerTimeoutGraceMs,
99
clampTimerTimeoutMs,
1010
} from "@openclaw/normalization-core/number-coercion";
11+
import {
12+
inspectManagedProcessGroup,
13+
terminateManagedChild,
14+
waitForManagedProcessGroupExit,
15+
} from "../../lib/managed-child-process.mts";
1116
import { resolveNpmRunner } from "../../npm-runner.mts";
1217
import { resolvePnpmRunner } from "../../pnpm-runner.mts";
1318
import { buildCmdExeCommandLine, resolveWindowsCmdExePath } from "../../windows-cmd-helpers.mjs";
@@ -20,7 +25,6 @@ const HOST_COMMAND_WRAPPER_EXTRA_BUFFER_BYTES = 1024 * 1024;
2025
const HOST_COMMAND_WRAPPER_BACKSTOP_MS = 5_000;
2126
const HOST_COMMAND_TIMEOUT_KILL_GRACE_MS = 100;
2227
const HOST_COMMAND_STREAMING_TIMEOUT_KILL_GRACE_MS = 2_000;
23-
const HOST_COMMAND_PROCESS_GROUP_EXIT_POLL_MS = 25;
2428
const HOST_COMMAND_POST_FORCE_KILL_WAIT_MS = 100;
2529
const HOST_COMMAND_CHILD_PID_PREFIX = "__OPENCLAW_HOST_COMMAND_CHILD_PID__";
2630
const HOST_COMMAND_SPAWN_ERROR_PREFIX = "__OPENCLAW_HOST_COMMAND_SPAWN_ERROR__";
@@ -79,36 +83,31 @@ function signalHostCommandProcess(pid: number | undefined, signal: NodeJS.Signal
7983
if (!pid) {
8084
return;
8185
}
82-
if (process.platform === "win32") {
83-
try {
84-
process.kill(pid, signal);
85-
} catch (error) {
86-
const code = (error as NodeJS.ErrnoException).code;
87-
if (code !== "ESRCH") {
88-
warn(`failed to send ${signal} to host command process ${pid}: ${code ?? String(error)}`);
89-
}
90-
}
91-
return;
92-
}
93-
try {
94-
process.kill(-pid, signal);
95-
} catch (error) {
96-
const code = (error as NodeJS.ErrnoException).code;
97-
if (code === "ESRCH") {
98-
return;
99-
}
100-
try {
101-
process.kill(pid, signal);
102-
} catch (fallbackError) {
103-
const fallbackCode = (fallbackError as NodeJS.ErrnoException).code;
104-
if (fallbackCode === "ESRCH") {
105-
return;
106-
}
107-
warn(
108-
`failed to send ${signal} to host command process ${pid}: group ${code ?? String(error)}, leader ${fallbackCode ?? String(fallbackError)}`,
109-
);
110-
}
111-
}
86+
let processGroupError: NodeJS.ErrnoException | undefined;
87+
terminateManagedChild(
88+
{
89+
kill: (childSignal) => process.kill(pid, childSignal),
90+
pid,
91+
},
92+
signal,
93+
{
94+
onChildSignalError(error) {
95+
const code = (error as NodeJS.ErrnoException).code;
96+
if (code === "ESRCH") {
97+
return;
98+
}
99+
const reason = processGroupError
100+
? `group ${processGroupError.code ?? processGroupError.toString()}, leader ${code ?? String(error)}`
101+
: (code ?? String(error));
102+
warn(`failed to send ${signal} to host command process ${pid}: ${reason}`);
103+
},
104+
onProcessGroupSignalError(error) {
105+
processGroupError = error as NodeJS.ErrnoException;
106+
},
107+
processGroupFallback: "nonmissing",
108+
useWindowsTaskkill: false,
109+
},
110+
);
112111
}
113112

114113
const POSIX_TIMEOUT_WRAPPER = String.raw`
@@ -604,40 +603,16 @@ export async function runStreaming(
604603
}
605604
}
606605
};
607-
const streamingProcessGroupAlive = (): boolean => {
608-
if (!detached || !childPid) {
609-
return false;
610-
}
611-
try {
612-
process.kill(-childPid, 0);
613-
return true;
614-
} catch (error) {
615-
if ((error as NodeJS.ErrnoException).code !== "EPERM") {
616-
return false;
617-
}
618-
if (child.exitCode !== null || child.signalCode !== null) {
619-
return false;
620-
}
621-
try {
622-
process.kill(childPid, 0);
623-
return true;
624-
} catch {
625-
return false;
626-
}
627-
}
628-
};
629-
const waitForStreamingProcessGroupExit = async (timeoutBudgetMs: number): Promise<boolean> => {
630-
const deadlineAt = Date.now() + timeoutBudgetMs;
631-
while (Date.now() < deadlineAt) {
632-
if (!streamingProcessGroupAlive()) {
633-
return true;
634-
}
635-
await new Promise((resolvePoll) => {
636-
setTimeout(resolvePoll, HOST_COMMAND_PROCESS_GROUP_EXIT_POLL_MS);
637-
});
638-
}
639-
return !streamingProcessGroupAlive();
640-
};
606+
const streamingProcessGroupAlive = (): boolean =>
607+
inspectManagedProcessGroup(child, {
608+
errorPolicy: "verify-leader",
609+
useProcessGroup: detached,
610+
}) === "live";
611+
const waitForStreamingProcessGroupExit = (timeoutBudgetMs: number): Promise<boolean> =>
612+
waitForManagedProcessGroupExit(child, timeoutBudgetMs, {
613+
errorPolicy: "verify-leader",
614+
useProcessGroup: detached,
615+
});
641616
logStream?.on("error", (error) => {
642617
logStreamError = error;
643618
signalStreamingChild("SIGTERM");

0 commit comments

Comments
 (0)