Skip to content

Commit 3495ce5

Browse files
committed
fix(process): keep signal forwarding through child errors
1 parent e741649 commit 3495ce5

8 files changed

Lines changed: 213 additions & 7 deletions

‎src/fleet/containers.runtime.test.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,14 @@
1+
import type { ChildProcess } from "node:child_process";
2+
import { EventEmitter } from "node:events";
13
import fs from "node:fs/promises";
24
import { beforeEach, describe, expect, it, vi } from "vitest";
35

6+
const spawnMock = vi.hoisted(() => vi.fn());
7+
8+
vi.mock("node:child_process", () => ({
9+
spawn: spawnMock,
10+
}));
11+
412
const profileMocks = vi.hoisted(() => ({
513
buildCellRunArgs: vi.fn((_profile: unknown, options: { environmentFile: string }) => [
614
"run",
@@ -34,6 +42,23 @@ function successfulExecutor() {
3442
}));
3543
}
3644

45+
function createStreamChild(pid?: number): ChildProcess {
46+
const stdout = Object.assign(new EventEmitter(), {
47+
pause: vi.fn(),
48+
resume: vi.fn(),
49+
});
50+
const stderr = Object.assign(new EventEmitter(), {
51+
pause: vi.fn(),
52+
resume: vi.fn(),
53+
});
54+
return Object.assign(new EventEmitter(), {
55+
pid,
56+
stdout,
57+
stderr,
58+
kill: vi.fn(() => true),
59+
}) as unknown as ChildProcess;
60+
}
61+
3762
describe("fleet container runtime", () => {
3863
beforeEach(() => {
3964
vi.clearAllMocks();
@@ -464,6 +489,39 @@ describe("fleet container runtime", () => {
464489
).rejects.toThrow(/podman logs failed with signal SIGSEGV/iu);
465490
});
466491

492+
it("rejects a log stream spawn error when the child has no pid", async () => {
493+
const child = createStreamChild();
494+
spawnMock.mockReturnValue(child);
495+
const runtime = createFleetContainerRuntime(successfulExecutor());
496+
497+
const logs = runtime.logs("podman", "cell-acme", { follow: true, redactValues: [] });
498+
child.emit("error", new Error("spawn failed"));
499+
500+
await expect(logs).rejects.toThrow("spawn failed");
501+
child.emit("close", -2, null);
502+
});
503+
504+
it("waits for log stream close across repeated operational errors", async () => {
505+
const child = createStreamChild(4242);
506+
spawnMock.mockReturnValue(child);
507+
const runtime = createFleetContainerRuntime(successfulExecutor());
508+
let settled = false;
509+
510+
const logs = runtime
511+
.logs("podman", "cell-acme", { follow: true, redactValues: [] })
512+
.finally(() => {
513+
settled = true;
514+
});
515+
child.emit("error", new Error("first signal delivery failed"));
516+
child.emit("error", new Error("second signal delivery failed"));
517+
await Promise.resolve();
518+
519+
expect(settled).toBe(false);
520+
521+
child.emit("close", 0, null);
522+
await expect(logs).resolves.toBeUndefined();
523+
});
524+
467525
it("creates and removes a labeled per-cell network", async () => {
468526
const executor = successfulExecutor();
469527
const runtime = createFleetContainerRuntime(executor);

‎src/fleet/containers.runtime.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -521,7 +521,11 @@ const defaultFleetContainerStreamExecutor: FleetContainerStreamExecutor = (
521521
};
522522
pipeWithBackpressure(child.stdout, process.stdout, stdout);
523523
pipeWithBackpressure(child.stderr, process.stderr, stderr);
524-
child.once("error", reject);
524+
child.on("error", (error) => {
525+
if (child.pid === undefined) {
526+
reject(error);
527+
}
528+
});
525529
child.once("close", (code, signal) => {
526530
stdout.flush();
527531
stderr.flush();
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import type { ChildProcess } from "node:child_process";
2+
import { EventEmitter } from "node:events";
3+
import { describe, expect, it, vi } from "vitest";
4+
import { attachChildProcessBridge } from "./child-process-bridge.js";
5+
6+
describe("attachChildProcessBridge", () => {
7+
it.each(["exit", "close"] as const)(
8+
"keeps forwarding after operational errors until child %s",
9+
(terminalEvent) => {
10+
const signal: NodeJS.Signals = "SIGTERM";
11+
const existingListeners = new Set(process.listeners(signal));
12+
const kill = vi.fn(() => true);
13+
const child = Object.assign(new EventEmitter(), {
14+
pid: 4242,
15+
kill,
16+
}) as unknown as ChildProcess;
17+
child.on("error", () => {});
18+
19+
const { detach } = attachChildProcessBridge(child, { signals: [signal] });
20+
const signalListener = process
21+
.listeners(signal)
22+
.find((listener) => !existingListeners.has(listener));
23+
24+
try {
25+
expect(signalListener).toBeDefined();
26+
child.emit("error", new Error("signal delivery failed"));
27+
expect(process.listeners(signal)).toContain(signalListener);
28+
29+
signalListener?.(signal);
30+
expect(kill).toHaveBeenCalledWith(signal);
31+
32+
child.emit(terminalEvent, 0, null);
33+
expect(process.listeners(signal)).not.toContain(signalListener);
34+
} finally {
35+
detach();
36+
}
37+
},
38+
);
39+
});

‎src/process/child-process-bridge.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const defaultSignals: NodeJS.Signals[] =
1313
? ["SIGTERM", "SIGINT", "SIGBREAK"]
1414
: ["SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT"];
1515

16-
/** Forwards process termination signals to a child and detaches on child exit/error. */
16+
/** Forwards process termination signals to a child and detaches on terminal lifecycle events. */
1717
export function attachChildProcessBridge(
1818
child: ChildProcess,
1919
{ signals = defaultSignals, onSignal }: ChildProcessBridgeOptions = {},
@@ -43,8 +43,10 @@ export function attachChildProcessBridge(
4343
listeners.clear();
4444
};
4545

46+
// Child errors can report failed signal/IPC operations while the PID stays live.
47+
// Keep forwarding until exit, with close covering failed spawn and final handle cleanup.
4648
child.once("exit", detach);
47-
child.once("error", detach);
49+
child.once("close", detach);
4850

4951
return { detach };
5052
}

‎src/process/respawn-child-runner.test.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,4 +205,68 @@ describe("runRespawnChildWithSignalBridge", () => {
205205
},
206206
);
207207
});
208+
209+
it("settles a spawn error when the child has no pid", () => {
210+
const { child } = createChild();
211+
const onError = vi.fn();
212+
const exit = vi.fn();
213+
214+
runRespawnChildWithSignalBridge({
215+
command: "missing-command",
216+
args: [],
217+
env: {},
218+
runtime: {
219+
spawn: vi.fn(() => child) as unknown as typeof spawn,
220+
attachChildProcessBridge: vi.fn(),
221+
exit: exit as unknown as (code?: number) => never,
222+
},
223+
onError,
224+
});
225+
226+
const error = new Error("spawn failed");
227+
child.emit("error", error);
228+
229+
expect(onError).toHaveBeenCalledWith(error);
230+
expect(exit).toHaveBeenCalledWith(1);
231+
});
232+
233+
it("keeps escalation active across repeated operational errors", () => {
234+
vi.useFakeTimers();
235+
const { child, kill } = createChild(5678);
236+
const onError = vi.fn();
237+
const exit = vi.fn();
238+
let onSignal: ((signal: NodeJS.Signals) => void) | undefined;
239+
240+
try {
241+
runRespawnChildWithSignalBridge({
242+
command: "/usr/bin/node",
243+
args: ["/repo/openclaw/dist/entry.js"],
244+
env: {},
245+
runtime: {
246+
spawn: vi.fn(() => child) as unknown as typeof spawn,
247+
attachChildProcessBridge: vi.fn((_child, options) => {
248+
onSignal = options?.onSignal;
249+
return { detach: vi.fn() };
250+
}),
251+
exit: exit as unknown as (code?: number) => never,
252+
},
253+
onError,
254+
});
255+
256+
onSignal?.("SIGTERM");
257+
child.emit("error", new Error("first signal delivery failed"));
258+
child.emit("error", new Error("second signal delivery failed"));
259+
vi.advanceTimersByTime(2_000);
260+
261+
expect(onError).not.toHaveBeenCalled();
262+
expect(exit).not.toHaveBeenCalled();
263+
expect(kill).toHaveBeenNthCalledWith(1, "SIGTERM");
264+
expect(kill).toHaveBeenNthCalledWith(2, process.platform === "win32" ? "SIGTERM" : "SIGKILL");
265+
266+
child.emit("exit", null, "SIGKILL");
267+
expect(exit).toHaveBeenCalledWith(1);
268+
} finally {
269+
vi.useRealTimers();
270+
}
271+
});
208272
});

‎src/process/respawn-child-runner.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,10 @@ export function runRespawnChildWithSignalBridge(params: {
120120
runtime.exit(code ?? 1);
121121
});
122122

123-
child.once("error", (error) => {
123+
child.on("error", (error) => {
124+
if (child.pid !== undefined) {
125+
return;
126+
}
124127
clearSignalTimers();
125128
onError(error);
126129
runtime.exit(1);

‎src/tui/tui-launch.test.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ import { launchTuiCli } from "./tui-launch.js";
2121
const originalArgv = [...process.argv];
2222
const originalExecArgv = [...process.execArgv];
2323

24-
function createChildProcess(): ChildProcess {
25-
return new EventEmitter() as ChildProcess;
24+
function createChildProcess(pid?: number): ChildProcess {
25+
return Object.assign(new EventEmitter(), { pid }) as ChildProcess;
2626
}
2727

2828
function expectSpawned(expectedArgs: string[]): SpawnOptions {
@@ -187,4 +187,37 @@ describe("launchTuiCli", () => {
187187
]);
188188
expect(options.env).toBe(process.env);
189189
});
190+
191+
it("rejects a spawn error when the child has no pid", async () => {
192+
const child = createChildProcess();
193+
spawnMock.mockImplementation(() => {
194+
queueMicrotask(() => child.emit("error", new Error("spawn failed")));
195+
return child;
196+
});
197+
198+
await expect(launchTuiCli({ deliver: false })).rejects.toThrow(
199+
"failed to launch TUI: spawn failed",
200+
);
201+
expect(detachMock).toHaveBeenCalledOnce();
202+
});
203+
204+
it("waits for terminal exit across repeated operational errors", async () => {
205+
const child = createChildProcess(4242);
206+
spawnMock.mockReturnValue(child);
207+
let settled = false;
208+
209+
const launched = launchTuiCli({ deliver: false }).finally(() => {
210+
settled = true;
211+
});
212+
child.emit("error", new Error("first signal delivery failed"));
213+
child.emit("error", new Error("second signal delivery failed"));
214+
await Promise.resolve();
215+
216+
expect(settled).toBe(false);
217+
expect(detachMock).not.toHaveBeenCalled();
218+
219+
child.emit("exit", 0, null);
220+
await expect(launched).resolves.toBeUndefined();
221+
expect(detachMock).toHaveBeenCalledOnce();
222+
});
190223
});

‎src/tui/tui-launch.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,10 @@ export async function launchTuiCli(opts: TuiOptions): Promise<void> {
5959
});
6060
const { detach } = attachChildProcessBridge(child);
6161

62-
child.once("error", (error) => {
62+
child.on("error", (error) => {
63+
if (child.pid !== undefined) {
64+
return;
65+
}
6366
detach();
6467
reject(new Error(`failed to launch TUI: ${formatErrorMessage(error)}`));
6568
});

0 commit comments

Comments
 (0)