Skip to content

Commit dc797d6

Browse files
TARSDrakonsteipete
andauthored
fix(process): Gateway survives late CLI output after timeout (#132582)
* fix(process): fence late output after run settlement * test(process): satisfy Promise executor lint * fix(process): release settled output at its lifecycle owners * test(process): type decoder mocks and separate output fence cases --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent d2ddada commit dc797d6

10 files changed

Lines changed: 510 additions & 54 deletions

‎src/process/decoded-output.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export function onDecodedOutput(
55
stream: Readable,
66
listener: (chunk: string) => void,
77
onRaw?: (chunk: Buffer) => void,
8-
): void {
8+
): () => void {
99
const decoder = createWindowsOutputDecoder();
1010
const emit = (text: string) => {
1111
if (text) {
@@ -20,10 +20,18 @@ export function onDecodedOutput(
2020
flushed = true;
2121
emit(decoder.flush());
2222
};
23-
stream.on("data", (chunk: Buffer | string) => {
23+
const onData = (chunk: Buffer | string) => {
2424
onRaw?.(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
2525
emit(decoder.decode(chunk));
26-
});
26+
};
27+
stream.on("data", onData);
2728
stream.once("end", flush);
2829
stream.once("close", flush);
30+
return () => {
31+
// A queued close may still invoke its copied listener, so suppress flush before detaching.
32+
flushed = true;
33+
stream.off("data", onData);
34+
stream.off("end", flush);
35+
stream.off("close", flush);
36+
};
2937
}

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

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ import {
1717
mockLinuxOomWrapperShell,
1818
} from "./test-support.js";
1919

20+
type CreateWindowsOutputDecoder =
21+
typeof import("../../../infra/windows-encoding.js").createWindowsOutputDecoder;
22+
2023
const {
2124
spawnWithFallbackMock,
2225
signalProcessTreeMock,
@@ -29,7 +32,7 @@ const {
2932
opts?.onComplete?.();
3033
},
3134
),
32-
createWindowsOutputDecoderMock: vi.fn(() => ({
35+
createWindowsOutputDecoderMock: vi.fn<CreateWindowsOutputDecoder>(() => ({
3336
decode: (chunk: Buffer | string) => (Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk),
3437
flush: () => "",
3538
})),
@@ -71,7 +74,7 @@ async function createAdapterHarness(params?: {
7174
env: params?.env,
7275
stdinMode: "pipe-open",
7376
});
74-
return { adapter, killMock };
77+
return { adapter, child, killMock };
7578
}
7679

7780
function expectedTrustedCmdExe(): string {
@@ -633,13 +636,56 @@ describe("createChildAdapter", () => {
633636
expect(adapter.stdin?.writableEnded).toBe(true);
634637
});
635638

636-
it("wait does not settle immediately on SIGKILL", async () => {
639+
it("disposes only decoder-owned output listeners after the SIGKILL fallback", async () => {
637640
vi.useFakeTimers();
638-
const { adapter } = await createAdapterHarness({ pid: 4567 });
641+
const flush = vi.fn(() => "flushed tail");
642+
createWindowsOutputDecoderMock.mockImplementation(() => ({
643+
decode: (chunk: Buffer | string) => (Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk),
644+
flush,
645+
}));
646+
const { adapter, child } = await createAdapterHarness({ pid: 4567 });
647+
const stdout = vi.fn();
648+
const stderr = vi.fn();
649+
const stdoutClose = vi.fn();
650+
const stderrClose = vi.fn();
651+
const stdoutPipe = child.stdout as PassThrough;
652+
const stderrPipe = child.stderr as PassThrough;
653+
stdoutPipe.on("close", stdoutClose);
654+
stderrPipe.on("close", stderrClose);
655+
adapter.onStdout(stdout);
656+
adapter.onStderr(stderr);
657+
658+
stdoutPipe.write("drained stdout");
659+
stderrPipe.write("drained stderr");
660+
expect(stdout).toHaveBeenCalledExactlyOnceWith("drained stdout");
661+
expect(stderr).toHaveBeenCalledExactlyOnceWith("drained stderr");
639662

640663
await expectWaitStaysPendingUntilSigkillFallback(adapter.wait(), () => {
641664
adapter.kill();
642665
});
666+
667+
const stdoutCloseListeners = stdoutPipe.listenerCount("close");
668+
const stderrCloseListeners = stderrPipe.listenerCount("close");
669+
const queuedError = new Error("queued output stream error");
670+
expect(stderrPipe.destroy(queuedError)).toBe(stderrPipe);
671+
expect(adapter.dispose()).toBeUndefined();
672+
673+
expect(stdoutPipe.destroyed).toBe(true);
674+
expect(stderrPipe.destroyed).toBe(true);
675+
expect(stderrPipe.errored).toBe(queuedError);
676+
expect(stderrPipe.listenerCount("error")).toBe(1);
677+
expect(stdoutPipe.listenerCount("close")).toBe(stdoutCloseListeners - 1);
678+
expect(stderrPipe.listenerCount("close")).toBe(stderrCloseListeners - 1);
679+
680+
stdoutPipe.emit("data", Buffer.from("late stdout"));
681+
stderrPipe.emit("data", Buffer.from("late stderr"));
682+
await vi.runAllTimersAsync();
683+
684+
expect(stdout).toHaveBeenCalledOnce();
685+
expect(stderr).toHaveBeenCalledOnce();
686+
expect(flush).not.toHaveBeenCalled();
687+
expect(stdoutClose).toHaveBeenCalledOnce();
688+
expect(stderrClose).toHaveBeenCalledOnce();
643689
});
644690

645691
it("prefers real child close over the SIGKILL fallback settle", async () => {

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

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,14 @@ export async function createChildAdapter(params: ChildAdapterInput): Promise<Wor
215215
stdin?.end();
216216
}
217217

218-
const onStdout: ChildAdapter["onStdout"] = (listener, onRaw) =>
219-
onDecodedOutput(child.stdout, listener, onRaw);
218+
const outputUnsubscribers: Array<() => void> = [];
219+
const onStdout: ChildAdapter["onStdout"] = (listener, onRaw) => {
220+
outputUnsubscribers.push(onDecodedOutput(child.stdout, listener, onRaw));
221+
};
220222

221-
const onStderr: ChildAdapter["onStderr"] = (listener, onRaw) =>
222-
onDecodedOutput(child.stderr, listener, onRaw);
223+
const onStderr: ChildAdapter["onStderr"] = (listener, onRaw) => {
224+
outputUnsubscribers.push(onDecodedOutput(child.stderr, listener, onRaw));
225+
};
223226

224227
const completion = createDeferredCore<{ code: number | null; signal: NodeJS.Signals | null }>();
225228
// Worker errors can precede wait(), including while secret delivery is still pending.
@@ -456,6 +459,12 @@ export async function createChildAdapter(params: ChildAdapterInput): Promise<Wor
456459
if (params.ownedWorker !== undefined) {
457460
disconnectWorkerIpc();
458461
}
462+
for (const unsubscribe of outputUnsubscribers.splice(0)) {
463+
unsubscribe();
464+
}
465+
// Error handling and Node's child-close bookkeeping must remain attached during destroy.
466+
child.stdout.destroy();
467+
child.stderr.destroy();
459468
child.removeAllListeners();
460469
};
461470

‎src/process/supervisor/registry.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,22 @@ function addRecord(
2929
}
3030

3131
describe("process supervisor run registry", () => {
32+
it("keeps retrieved snapshots detached while output timestamps advance", () => {
33+
const registry = createRunRegistry();
34+
addRecord(registry, { runId: "r1", sessionId: "s1", startedAtMs: 1 });
35+
const snapshot = registry.get("r1");
36+
37+
registry.touchOutput("r1");
38+
const touched = registry.get("r1");
39+
40+
expect(snapshot).toMatchObject({ lastOutputAtMs: 1, updatedAtMs: 1 });
41+
expect(touched?.lastOutputAtMs).toBeGreaterThan(1);
42+
if (touched) {
43+
touched.backendId = "caller-owned";
44+
}
45+
expect(registry.get("r1")?.backendId).toBe("b1");
46+
});
47+
3248
it("finalize is idempotent and preserves first terminal metadata", () => {
3349
const registry = createRunRegistry();
3450
addRecord(registry, { runId: "r1", sessionId: "s1", startedAtMs: 1 });

‎src/process/supervisor/registry.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,11 +104,8 @@ export function createRunRegistry(options?: { maxExitedRecords?: number }): RunR
104104
return;
105105
}
106106
const ts = nowMs();
107-
records.set(runId, {
108-
...current,
109-
lastOutputAtMs: ts,
110-
updatedAtMs: ts,
111-
});
107+
current.lastOutputAtMs = ts;
108+
current.updatedAtMs = ts;
112109
};
113110

114111
const finalize: RunRegistry["finalize"] = (runId, exit) => {
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
// A detached descendant can retain stdio after forced settlement. Callers
2+
// finalize output hashes after wait(), so no later output may reach them.
3+
import crypto from "node:crypto";
4+
import { statSync } from "node:fs";
5+
import { writeFile } from "node:fs/promises";
6+
import path from "node:path";
7+
import { afterEach, describe, expect, it } from "vitest";
8+
import { waitForDead, waitForPidFile } from "../../../test/helpers/process-wait.js";
9+
import { createTempDirTracker } from "../../../test/helpers/temp-dir.js";
10+
import { killPidIfAlive } from "../../test-utils/process-tree.js";
11+
import { createProcessSupervisor } from "./supervisor.js";
12+
13+
// SIGTERM plus the adapter's kill-wait fallback is a fixed ~9s production window.
14+
const FORCED_SETTLEMENT_TEST_TIMEOUT_MS = 60_000;
15+
const LATE_OUTPUT_OBSERVATION_MS = 500;
16+
const CLEANUP_PID_RESOLVE_MS = 250;
17+
18+
const activePids = new Set<number>();
19+
const activePidFiles = new Set<string>();
20+
const tempDirs = createTempDirTracker();
21+
22+
afterEach(async () => {
23+
try {
24+
for (const pidFile of activePidFiles) {
25+
const pid = await waitForPidFile(pidFile, CLEANUP_PID_RESOLVE_MS).catch(() => undefined);
26+
if (pid !== undefined) {
27+
activePids.add(pid);
28+
}
29+
}
30+
for (const pid of activePids) {
31+
killPidIfAlive(pid);
32+
}
33+
await Promise.all([...activePids].map((pid) => waitForDead(pid, 5_000).catch(() => {})));
34+
} finally {
35+
activePidFiles.clear();
36+
activePids.clear();
37+
tempDirs.cleanup();
38+
}
39+
});
40+
41+
async function createLeakedPipeScope() {
42+
const cwd = tempDirs.make("openclaw-forced-settlement-");
43+
const leakPath = path.join(cwd, "leak.cjs");
44+
const leakPidPath = path.join(cwd, "leak.pid");
45+
const leakTickPath = path.join(cwd, "leak.ticks");
46+
const rootPath = path.join(cwd, "root.cjs");
47+
await writeFile(
48+
leakPath,
49+
`
50+
const { appendFileSync, writeFileSync } = require("node:fs");
51+
// Adapter disposal closes the parent-side pipes. Keep the escaped process
52+
// alive so its independent tick file proves output attempts continue.
53+
process.stdout.on("error", () => {});
54+
process.stderr.on("error", () => {});
55+
let tick = 0;
56+
setInterval(() => {
57+
tick += 1;
58+
appendFileSync(process.argv[3], ".");
59+
process.stdout.write("leaked-stdout-" + tick + "\\n");
60+
process.stderr.write("leaked-stderr-" + tick + "\\n");
61+
}, 50);
62+
writeFileSync(process.argv[2], String(process.pid));
63+
`,
64+
"utf8",
65+
);
66+
await writeFile(
67+
rootPath,
68+
`
69+
const { spawn } = require("node:child_process");
70+
process.stdout.write("live-stdout\\n");
71+
process.stderr.write("live-stderr\\n");
72+
// Inherit this root's stdout/stderr so the pipes outlive it, and detach so
73+
// the supervisor's process-group kill cannot reach the descendant. This is
74+
// the shipped CLI shape that would leave stdio open without terminal disposal.
75+
const leak = spawn(
76+
process.execPath,
77+
[${JSON.stringify(leakPath)}, ${JSON.stringify(leakPidPath)}, ${JSON.stringify(leakTickPath)}],
78+
{ stdio: ["ignore", "inherit", "inherit"], detached: true },
79+
);
80+
leak.unref();
81+
setInterval(() => {}, 1_000);
82+
`,
83+
"utf8",
84+
);
85+
return { cwd, rootPath, leakPidPath, leakTickPath };
86+
}
87+
88+
function readTickCount(tickPath: string): number {
89+
try {
90+
return statSync(tickPath).size;
91+
} catch {
92+
return 0;
93+
}
94+
}
95+
96+
describe.skipIf(process.platform === "win32")("supervisor forced settlement output fence", () => {
97+
it(
98+
"delivers nothing after forced settlement with inherited pipes held by a descendant",
99+
async () => {
100+
const { cwd, rootPath, leakPidPath, leakTickPath } = await createLeakedPipeScope();
101+
activePidFiles.add(leakPidPath);
102+
const stdoutHash = crypto.createHash("sha256");
103+
const stderrHash = crypto.createHash("sha256");
104+
const delivered: string[] = [];
105+
// Production crashes uncaught inside the stream "data" handler; recording
106+
// the failure keeps the fence regression assertable instead of killing
107+
// the worker, and an empty list is the shipped contract.
108+
const hashFailures: string[] = [];
109+
const consume = (hash: crypto.Hash, label: string) => (chunk: string) => {
110+
delivered.push(`${label}:${chunk.trim()}`);
111+
try {
112+
hash.update(chunk);
113+
} catch (error) {
114+
hashFailures.push(`${label}:${(error as NodeJS.ErrnoException).code ?? String(error)}`);
115+
}
116+
};
117+
118+
const supervisor = createProcessSupervisor();
119+
const run = await supervisor.spawn({
120+
mode: "child",
121+
argv: [process.execPath, rootPath],
122+
sessionId: "forced-settlement-real",
123+
backendId: "forced-settlement-real",
124+
cwd,
125+
captureOutput: false,
126+
onStdout: consume(stdoutHash, "stdout"),
127+
onStderr: consume(stderrHash, "stderr"),
128+
onStdoutRaw: (raw) => delivered.push(`stdout-raw:${raw.toString("utf8").trim()}`),
129+
onStderrRaw: (raw) => delivered.push(`stderr-raw:${raw.toString("utf8").trim()}`),
130+
});
131+
if (run.pid !== undefined) {
132+
activePids.add(run.pid);
133+
}
134+
135+
const leakedPid = await waitForPidFile(leakPidPath, 15_000);
136+
activePidFiles.delete(leakPidPath);
137+
activePids.add(leakedPid);
138+
run.cancel("manual-cancel");
139+
140+
const exit = await run.wait();
141+
// Exactly what the CLI runner does with the terminal result it just read.
142+
const digests = [stdoutHash.digest("hex"), stderrHash.digest("hex")];
143+
const settledDelivered = [...delivered];
144+
const settledOutputAtMs = supervisor.getRecord(run.runId)?.lastOutputAtMs;
145+
const settledTicks = readTickCount(leakTickPath);
146+
await new Promise<void>((resolve) => {
147+
setTimeout(resolve, LATE_OUTPUT_OBSERVATION_MS);
148+
});
149+
150+
expect(exit.reason).toBe("manual-cancel");
151+
expect(digests.every((digest) => digest.length === 64)).toBe(true);
152+
expect(settledDelivered).toContain("stdout:live-stdout");
153+
expect(settledDelivered).toContain("stderr-raw:live-stderr");
154+
// The descendant stayed alive and attempted output across the terminal
155+
// boundary even though adapter disposal closed the parent-side pipes.
156+
expect(readTickCount(leakTickPath)).toBeGreaterThan(settledTicks);
157+
expect(hashFailures).toEqual([]);
158+
expect(delivered).toEqual(settledDelivered);
159+
expect(supervisor.getRecord(run.runId)?.lastOutputAtMs).toBe(settledOutputAtMs);
160+
},
161+
FORCED_SETTLEMENT_TEST_TIMEOUT_MS,
162+
);
163+
});

0 commit comments

Comments
 (0)