Skip to content

Commit 4a72e1b

Browse files
author
hcl
authored
fix(process): skip kill-tree group kill when child wasn't detached (#71662) (#71681)
* fix(process): skip kill-tree group kill when child wasn't detached (#71662) When the supervisor spawns a child with detached:false (service-managed runtime under launchd/systemd), the child shares the gateway's process group. On session abort or SIGKILL, killProcessTree was unconditionally issuing process.kill(-pid, 'SIGTERM') — which targets the entire process GROUP (negative pid is POSIX group-kill semantics) and therefore SIGTERMs the gateway parent along with the child. Reporter saw this on macOS (LaunchAgent + KeepAlive=true): aborting a claude-cli/claude-opus-4-7 session caused the gateway to receive SIGTERM, then auto-restart, dropping all in-flight sessions. Switching the primary model to a non-cli provider eliminated it because the non-cli paths don't go through this kill-tree call. Did not occur on Linux VPS where the gateway runs detached, because there useDetached === true and the child got its own process group. Fix: - killProcessTree now accepts opts.detached?: boolean. When detached:false, killProcessTreeUnix skips the `-pid` group-kill and goes straight to direct-pid SIGTERM/SIGKILL. Group-kill default (detached:true) is preserved so all existing callers behave exactly as before. - supervisor/adapters/child.ts:286 now threads the spawn-time `useDetached` flag into killProcessTree, so the kill-tree path matches the spawn-time detachment decision (line 45 of the same file already computes useDetached = process.platform !== 'win32' && !isServiceManagedRuntime()). Tests: - new: detached:false skips group kill and uses direct pid SIGTERM only. - new: default behaviour (detached:true) still uses group kill (regression guard so the existing test case isn't accidentally weakened). Existing tests still pass (6/6 in kill-tree.test.ts). Lint clean. Out of scope: other killProcessTree callers (mcp-stdio-transport, bash-tools.process, etc.) keep the default group-kill behaviour because those processes are typically detached from the gateway. Only the supervisor/adapters/child.ts path threads `detached` through, since it's the path that knows whether the child was actually spawned detached. * fixup(process): also gate kill-tree group-kill on the no-detach spawn fallback (#71662) Greptile review on the original PR caught a P1 gap: when spawnWithFallback's initial detached spawn fails and it retries with the no-detach fallback (label: "no-detach", options.detached: false), the child runs detached:false but my variable useDetached was still true. The kill closure then passed `detached: useDetached` = true to killProcessTree, which still group-killed the gateway — same bug, just on the fallback path. Compute the actual detachment as `useDetached && !spawned.usedFallback` after spawn returns, and pass that through. This closes the gap: the kill path now correctly skips group-kill in BOTH: 1. Service-managed runtime (useDetached=false from the start, original case) 2. Detached-spawn fallback to no-detach (useDetached=true at intent time but spawned.usedFallback=true) Tests: - existing 'uses process-tree kill for default SIGKILL' updated to assert the new {detached} option is forwarded. - new: passes detached:false to killProcessTree when spawn fell back. - new: passes detached:false in service-managed mode (regression guard for the original fix). 11/11 tests pass in child.test.ts. 6/6 in kill-tree.test.ts.
1 parent 1841dd9 commit 4a72e1b

4 files changed

Lines changed: 115 additions & 11 deletions

File tree

‎src/process/kill-tree.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,4 +139,44 @@ describe("killProcessTree", () => {
139139
expect(killSpy).toHaveBeenCalledWith(-4444, "SIGKILL");
140140
});
141141
});
142+
143+
it("on Unix skips group kill when detached:false to avoid SIGTERMing the parent's own process group (#71662)", async () => {
144+
killSpy.mockImplementation(((pid: number, signal?: NodeJS.Signals | number) => {
145+
if (pid === 5555 && signal === 0) {
146+
throw new Error("ESRCH");
147+
}
148+
return true;
149+
}) as typeof process.kill);
150+
151+
await withPlatform("linux", async () => {
152+
killProcessTree(5555, { graceMs: 10, detached: false });
153+
await vi.advanceTimersByTimeAsync(10);
154+
155+
// Direct pid kill is fine. Group kill (`-pid`) is FORBIDDEN here because
156+
// when the child wasn't spawned detached, its process group is the
157+
// gateway's group — `-pid` would SIGTERM the gateway itself.
158+
expect(killSpy).toHaveBeenCalledWith(5555, "SIGTERM");
159+
expect(killSpy).not.toHaveBeenCalledWith(-5555, "SIGTERM");
160+
expect(killSpy).not.toHaveBeenCalledWith(-5555, "SIGKILL");
161+
});
162+
});
163+
164+
it("on Unix uses group kill by default (detached:true preserved as the existing behavior)", async () => {
165+
killSpy.mockImplementation(((pid: number, signal?: NodeJS.Signals | number) => {
166+
if (pid === -6666 && signal === 0) {
167+
throw new Error("ESRCH");
168+
}
169+
if (pid === 6666 && signal === 0) {
170+
throw new Error("ESRCH");
171+
}
172+
return true;
173+
}) as typeof process.kill);
174+
175+
await withPlatform("linux", async () => {
176+
killProcessTree(6666, { graceMs: 10 });
177+
await vi.advanceTimersByTimeAsync(10);
178+
179+
expect(killSpy).toHaveBeenCalledWith(-6666, "SIGTERM");
180+
});
181+
});
142182
});

‎src/process/kill-tree.ts‎

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,16 @@ const MAX_GRACE_MS = 60_000;
1111
*
1212
* This gives child processes a chance to clean up (close connections, remove
1313
* temp files, terminate their own children) before being hard-killed.
14+
*
15+
* When the child was spawned with `detached: false` (e.g. service-managed
16+
* runtime under launchd/systemd), pass `detached: false` to skip the Unix
17+
* `process.kill(-pid, ...)` group-kill — it would otherwise target the
18+
* gateway's own process group and SIGTERM the gateway itself. (#71662)
1419
*/
15-
export function killProcessTree(pid: number, opts?: { graceMs?: number }): void {
20+
export function killProcessTree(
21+
pid: number,
22+
opts?: { graceMs?: number; detached?: boolean },
23+
): void {
1624
if (!Number.isFinite(pid) || pid <= 0) {
1725
return;
1826
}
@@ -24,7 +32,7 @@ export function killProcessTree(pid: number, opts?: { graceMs?: number }): void
2432
return;
2533
}
2634

27-
killProcessTreeUnix(pid, graceMs);
35+
killProcessTreeUnix(pid, graceMs, opts?.detached !== false);
2836
}
2937

3038
function normalizeGraceMs(value?: number): number {
@@ -43,12 +51,23 @@ function isProcessAlive(pid: number): boolean {
4351
}
4452
}
4553

46-
function killProcessTreeUnix(pid: number, graceMs: number): void {
47-
// Step 1: Try graceful SIGTERM to process group
48-
try {
49-
process.kill(-pid, "SIGTERM");
50-
} catch {
51-
// Process group doesn't exist or we lack permission - try direct
54+
function killProcessTreeUnix(pid: number, graceMs: number, useGroupKill: boolean): void {
55+
// Step 1: Try graceful SIGTERM. Prefer process-group kill (`-pid`) when the
56+
// child was spawned detached so it has its own group; otherwise stick to the
57+
// direct pid to avoid SIGTERMing our own process group (the gateway). (#71662)
58+
if (useGroupKill) {
59+
try {
60+
process.kill(-pid, "SIGTERM");
61+
} catch {
62+
// Process group doesn't exist or we lack permission - try direct
63+
try {
64+
process.kill(pid, "SIGTERM");
65+
} catch {
66+
// Already gone
67+
return;
68+
}
69+
}
70+
} else {
5271
try {
5372
process.kill(pid, "SIGTERM");
5473
} catch {
@@ -59,7 +78,7 @@ function killProcessTreeUnix(pid: number, graceMs: number): void {
5978

6079
// Step 2: Wait grace period, then SIGKILL if still alive
6180
setTimeout(() => {
62-
if (isProcessAlive(-pid)) {
81+
if (useGroupKill && isProcessAlive(-pid)) {
6382
try {
6483
process.kill(-pid, "SIGKILL");
6584
return;

‎src/process/supervisor/adapters/child.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,10 +122,46 @@ describe("createChildAdapter", () => {
122122

123123
adapter.kill();
124124

125-
expect(killProcessTreeMock).toHaveBeenCalledWith(4321);
125+
// Detachment flag is now passed to killProcessTree so it knows whether
126+
// it can safely group-kill via -pid. (#71662)
127+
const expectedDetached = process.platform !== "win32" && !process.env.OPENCLAW_SERVICE_MARKER;
128+
expect(killProcessTreeMock).toHaveBeenCalledWith(4321, { detached: expectedDetached });
126129
expect(killMock).toHaveBeenCalledWith("SIGKILL");
127130
});
128131

132+
it("passes detached:false to killProcessTree when spawn fell back to no-detach (#71662 follow-up)", async () => {
133+
// Simulate the fallback scenario: spawnWithFallback retried with
134+
// detached:false because the initial detached spawn failed. The kill
135+
// closure must NOT group-kill since the child shares the gateway's group.
136+
const { child, killMock } = createStubChild(8888);
137+
spawnWithFallbackMock.mockResolvedValue({
138+
child,
139+
usedFallback: true,
140+
fallbackLabel: "no-detach",
141+
});
142+
const adapter = await createChildAdapter({
143+
argv: ["node", "-e", "setTimeout(() => {}, 1000)"],
144+
stdinMode: "pipe-open",
145+
});
146+
147+
adapter.kill();
148+
149+
expect(killProcessTreeMock).toHaveBeenCalledWith(8888, { detached: false });
150+
expect(killMock).toHaveBeenCalledWith("SIGKILL");
151+
});
152+
153+
it("passes detached:false in service-managed mode where useDetached is false from the start (#71662)", async () => {
154+
process.env.OPENCLAW_SERVICE_MARKER = "1";
155+
try {
156+
const { adapter, killMock } = await createAdapterHarness({ pid: 9999 });
157+
adapter.kill();
158+
expect(killProcessTreeMock).toHaveBeenCalledWith(9999, { detached: false });
159+
expect(killMock).toHaveBeenCalledWith("SIGKILL");
160+
} finally {
161+
delete process.env.OPENCLAW_SERVICE_MARKER;
162+
}
163+
});
164+
129165
it("uses direct child.kill for non-SIGKILL signals", async () => {
130166
const { adapter, killMock } = await createAdapterHarness({ pid: 7654 });
131167

‎src/process/supervisor/adapters/child.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,11 +283,20 @@ export async function createChildAdapter(params: {
283283
return waitPromise;
284284
};
285285

286+
// The actual detachment of the spawned child can differ from `useDetached`:
287+
// when the detached spawn fails, `spawnWithFallback` retries with the
288+
// `no-detach` fallback (detached:false). In that case the child shares the
289+
// gateway's process group regardless of intent, so the kill must avoid
290+
// group-kill. (#71662 follow-up — caught by Greptile review)
291+
const childIsDetached = useDetached && !spawned.usedFallback;
286292
const kill = (signal?: NodeJS.Signals) => {
287293
const pid = child.pid ?? undefined;
288294
if (signal === undefined || signal === "SIGKILL") {
289295
if (pid) {
290-
killProcessTree(pid);
296+
// Pass through whether the child is actually detached. Without this,
297+
// `killProcessTree` group-kills via `-pid` and takes out the gateway's
298+
// own process group along with the child. (#71662)
299+
killProcessTree(pid, { detached: childIsDetached });
291300
}
292301
try {
293302
child.kill("SIGKILL");

0 commit comments

Comments
 (0)