Skip to content

Commit 4b50aaa

Browse files
authored
fix(codex): reaper could kill a recycled-pid process and skipped cleanup until next use (#132745)
* fix(codex): gate orphan reaper kills on command identity and sweep at boot The reaper landed in #132610 authorizes SIGKILL from pid+pgid+startedAt. On macOS, startedAt comes from ps lstart and is only second-granular, so a registered child that dies and has its pid recycled within the same second could hand its identity to an unrelated process that then gets killed (group-killed when it is a leader); Linux is already tick-granular with a boot id. Registration now also records the child's exact command line (/proc cmdline on Linux, ps -o command= elsewhere) and the reap loop compares it before entering containment: a mismatch deletes only the stale row, an unreadable command with a still-matching identity refuses the spawn fail-closed, and rows written by earlier unreleased builds keep identity-only reaping via an optional schema field. Verified against pinned codex 0.150.1 (rust-v0.150.1) that the app-server never retitles its argv. The regression "never kills a same-second replacement process running a different command" fails without the gate. Also registers a best-effort boot sweep service (codex-app-server-process-reaper) so orphans from a hard-killed gateway die at the next startup instead of waiting for the next codex spawn; the before-spawn fail-closed check remains authoritative. Docs updated. Follow-up to #132610 from #132621's review findings. * fix(codex): persist only a command fingerprint in reaper registrations appServer.args is operator-configurable and can carry secrets, and the spawn-identity precedent (argsFingerprint) deliberately hashes argv. Durable reaper rows now store a sha256 fingerprint of the observed command line instead of the raw string; the kill gate reads the live command fresh and compares digests, and the registration test asserts raw argv never reaches the durable store. Addresses the ClawSweeper P1 on #132745; the companion final-signal finding is refuted in the PR thread (identity monotonicity: a post-gate replacement cannot carry the registered start time, and containment revalidates identity before every signal).
1 parent 0270a71 commit 4b50aaa

7 files changed

Lines changed: 486 additions & 37 deletions

File tree

‎docs/plugins/codex-harness-runtime.md‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -72,16 +72,20 @@ Code Mode execution.
7272
## Recovery after a hard Gateway stop
7373

7474
On POSIX systems, OpenClaw checks for registered orphaned Codex app-server
75-
processes before spawning each fresh stdio child. This runs when the connection
76-
is needed, not necessarily at Gateway boot. OpenClaw records the parent and
77-
child process identities in the current state directory's SQLite plugin store
75+
processes before spawning each fresh stdio child. Gateway startup also runs a
76+
best-effort background sweep; the before-spawn check remains authoritative.
77+
OpenClaw records the parent and child process identities in the current state
78+
directory's SQLite plugin store
7879
before sending Codex `initialize`, so a child cannot start a native turn before
7980
its registration is durable.
8081

8182
Cleanup only targets a registered child whose original OpenClaw parent is no
8283
longer running. It checks process IDs, start times, and process groups before
83-
terminating the orphan and its discoverable descendants. Another live OpenClaw
84-
instance, processes registered under another state directory, and externally
84+
terminating the orphan and its discoverable descendants. When recorded, a
85+
fingerprint of the child command line must also match the live process before
86+
signaling; the durable registration stores only that digest, never the raw
87+
arguments. Another live
88+
OpenClaw instance, processes registered under another state directory, and externally
8589
managed WebSocket or Unix-socket app-servers are left alone. These portable
8690
process checks do not provide an atomic operating-system ownership guarantee
8791
or discover descendants that independently reparented before inspection.

‎extensions/codex/index.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,13 @@ describe("codex plugin", () => {
154154
}),
155155
);
156156

157-
expect(registerService).toHaveBeenCalledTimes(2);
157+
expect(registerService).toHaveBeenCalledTimes(3);
158+
expect(registerService.mock.calls.map(([service]) => service)).toContainEqual(
159+
expect.objectContaining({
160+
id: "codex-app-server-process-reaper",
161+
start: expect.any(Function),
162+
}),
163+
);
158164
expect(registerService.mock.calls.map(([service]) => service)).toContainEqual(
159165
expect.objectContaining({
160166
id: "codex-app-server-connection-health",
@@ -180,12 +186,16 @@ describe("codex plugin", () => {
180186
}),
181187
);
182188

183-
expect(registerService).toHaveBeenCalledOnce();
189+
expect(registerService).toHaveBeenCalledTimes(2);
184190
expect(mockCallArg(registerService)).toMatchObject({
185191
id: "codex-desktop-generation",
186192
start: expect.any(Function),
187193
stop: expect.any(Function),
188194
});
195+
expect(mockCallArg(registerService, 1)).toMatchObject({
196+
id: "codex-app-server-process-reaper",
197+
start: expect.any(Function),
198+
});
189199
}
190200
});
191201

‎extensions/codex/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
type StoredCodexAppServerBinding,
3434
} from "./src/app-server/session-binding-store.js";
3535
import { retireSharedCodexAppServerClientsBeforeDesktopGeneration } from "./src/app-server/shared-client.js";
36+
import { createCodexAppServerProcessReaperService } from "./src/app-server/transport-process-registration.js";
3637
import type { CodexPluginsConfigBlock } from "./src/command-plugins-management.js";
3738
import { createCodexCommand } from "./src/commands.js";
3839
import { codexConversationBindingRuntime } from "./src/conversation-binding.js";
@@ -110,6 +111,7 @@ export default definePluginEntry({
110111
onGenerationChange: retireSharedCodexAppServerClientsBeforeDesktopGeneration,
111112
}),
112113
);
114+
api.registerService(createCodexAppServerProcessReaperService());
113115
if (appServerConfig?.transport === "websocket") {
114116
api.registerService(
115117
createCodexAppServerConnectionHealthService({
Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
import { ChildProcess } from "node:child_process";
2+
import { createHash } from "node:crypto";
3+
import fs from "node:fs/promises";
4+
import os from "node:os";
5+
import path from "node:path";
6+
import { PassThrough } from "node:stream";
7+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
8+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9+
import { terminateCodexAppServerOrphan } from "./transport-process-containment.js";
10+
import {
11+
createCodexAppServerProcessReaperService,
12+
prepareCodexAppServerProcessRegistration,
13+
} from "./transport-process-registration.js";
14+
import {
15+
readCodexAppServerProcess,
16+
readCodexAppServerProcessCommand,
17+
readCodexAppServerProcessSnapshot,
18+
type PosixProcess,
19+
} from "./transport-process-snapshot.js";
20+
21+
vi.mock("./transport-process-snapshot.js", async (importOriginal) => ({
22+
...(await importOriginal<typeof import("./transport-process-snapshot.js")>()),
23+
readCodexAppServerProcessSnapshot: vi.fn(),
24+
readCodexAppServerProcess: vi.fn(),
25+
readCodexAppServerProcessCommand: vi.fn(),
26+
}));
27+
28+
vi.mock("./transport-process-containment.js", async (importOriginal) => ({
29+
...(await importOriginal<typeof import("./transport-process-containment.js")>()),
30+
terminateCodexAppServerOrphan: vi.fn(),
31+
}));
32+
33+
const observer: PosixProcess = {
34+
pid: process.pid,
35+
ppid: process.ppid,
36+
pgid: process.pid,
37+
state: "S",
38+
startedAt: "Sat Aug 29 10:00:00 2026",
39+
};
40+
const parent = { pid: process.pid + 1, pgid: process.pid + 1, startedAt: observer.startedAt };
41+
const child = { pid: process.pid + 2, pgid: process.pid + 2, startedAt: observer.startedAt };
42+
const liveChild: PosixProcess = { ...child, ppid: 1, state: "S" };
43+
const command = "/opt/codex app-server --listen stdio://";
44+
const commandFingerprint = createHash("sha256").update(command).digest("hex");
45+
46+
async function openStore() {
47+
const { createPluginStateSyncKeyedStore } =
48+
await import("openclaw/plugin-sdk/plugin-state-store-runtime");
49+
return createPluginStateSyncKeyedStore<{
50+
parent: typeof parent;
51+
child: typeof child & { commandFingerprint?: string };
52+
}>("codex", {
53+
namespace: "app-server-processes",
54+
maxEntries: 512,
55+
overflowPolicy: "reject-new",
56+
});
57+
}
58+
59+
describe("Codex process registration", () => {
60+
let root: string;
61+
let store: Awaited<ReturnType<typeof openStore>>;
62+
63+
beforeEach(async () => {
64+
root = await fs.mkdtemp(path.join(os.tmpdir(), "codex-process-registration-"));
65+
vi.stubEnv("OPENCLAW_STATE_DIR", root);
66+
vi.spyOn(process, "platform", "get").mockReturnValue("darwin");
67+
store = await openStore();
68+
vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([
69+
observer,
70+
{ ...parent, ppid: 1, state: "Z" },
71+
liveChild,
72+
]);
73+
vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue(command);
74+
vi.mocked(terminateCodexAppServerOrphan).mockResolvedValue(true);
75+
});
76+
77+
afterEach(async () => {
78+
store.clear();
79+
vi.restoreAllMocks();
80+
vi.resetAllMocks();
81+
vi.unstubAllEnvs();
82+
await fs.rm(root, { recursive: true, force: true });
83+
});
84+
85+
it("never kills a same-second replacement process running a different command", async () => {
86+
store.register("orphan", { parent, child: { ...child, commandFingerprint } });
87+
vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue("/usr/bin/unrelated-worker");
88+
89+
await expect(prepareCodexAppServerProcessRegistration()).resolves.toBeTypeOf("function");
90+
91+
expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled();
92+
expect(store.lookup("orphan")).toBeUndefined();
93+
});
94+
95+
it.for(["legacy", "matching command"])("reaps a %s registration", async (mode) => {
96+
const registeredChild = mode === "legacy" ? child : { ...child, commandFingerprint };
97+
store.register("orphan", { parent, child: registeredChild });
98+
99+
await expect(prepareCodexAppServerProcessRegistration()).resolves.toBeTypeOf("function");
100+
101+
expect(terminateCodexAppServerOrphan).toHaveBeenCalledExactlyOnceWith(registeredChild);
102+
expect(store.lookup("orphan")).toBeUndefined();
103+
expect(readCodexAppServerProcessCommand).toHaveBeenCalledTimes(mode === "legacy" ? 0 : 1);
104+
});
105+
106+
it.for(["gone", "replaced"])(
107+
"lets containment settle a %s child after command inspection fails",
108+
async (mode) => {
109+
store.register("orphan", { parent, child: { ...child, commandFingerprint } });
110+
vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue(undefined);
111+
vi.mocked(readCodexAppServerProcess).mockResolvedValue(
112+
mode === "gone" ? undefined : { ...liveChild, startedAt: "a later start" },
113+
);
114+
115+
await expect(prepareCodexAppServerProcessRegistration()).resolves.toBeTypeOf("function");
116+
117+
expect(terminateCodexAppServerOrphan).toHaveBeenCalledExactlyOnceWith({
118+
...child,
119+
commandFingerprint,
120+
});
121+
expect(store.lookup("orphan")).toBeUndefined();
122+
},
123+
);
124+
125+
it("refuses a spawn and retains the row when the matching child's command is unreadable", async () => {
126+
const registration = { parent, child: { ...child, commandFingerprint } };
127+
store.register("orphan", registration);
128+
vi.mocked(readCodexAppServerProcessCommand).mockResolvedValue(undefined);
129+
vi.mocked(readCodexAppServerProcess).mockResolvedValue(liveChild);
130+
131+
await expect(prepareCodexAppServerProcessRegistration()).rejects.toThrow(
132+
`Cannot inspect registered Codex process ${child.pid} command. Check process command inspection permissions (/proc on Linux, ps on macOS), then retry.`,
133+
);
134+
135+
expect(store.lookup("orphan")).toEqual(registration);
136+
expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled();
137+
});
138+
139+
it.for(["gone", "zombie", "replaced"])(
140+
"skips command inspection when the snapshot child is %s",
141+
async (mode) => {
142+
store.register("orphan", { parent, child: { ...child, commandFingerprint } });
143+
vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([
144+
observer,
145+
...(mode === "gone"
146+
? []
147+
: [{ ...liveChild, ...(mode === "zombie" ? { state: "Z" } : { startedAt: "later" }) }]),
148+
]);
149+
150+
await prepareCodexAppServerProcessRegistration();
151+
152+
expect(readCodexAppServerProcessCommand).not.toHaveBeenCalled();
153+
expect(terminateCodexAppServerOrphan).toHaveBeenCalledOnce();
154+
expect(store.lookup("orphan")).toBeUndefined();
155+
},
156+
);
157+
158+
it("leaves a live parent's child registered without inspecting its command", async () => {
159+
const registration = { parent, child: { ...child, commandFingerprint } };
160+
store.register("owned", registration);
161+
vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([
162+
observer,
163+
{ ...parent, ppid: 1, state: "S" },
164+
liveChild,
165+
]);
166+
167+
await prepareCodexAppServerProcessRegistration();
168+
169+
expect(readCodexAppServerProcessCommand).not.toHaveBeenCalled();
170+
expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled();
171+
expect(store.lookup("owned")).toEqual(registration);
172+
});
173+
174+
it.for(["live", "unreadable command", "exited during inspection"])(
175+
"registers only a live child with its command: %s",
176+
async (mode, ctx) => {
177+
const stdin = new PassThrough();
178+
const stdout = new PassThrough();
179+
const stderr = new PassThrough();
180+
// The typed stdio tuple makes this fixture structurally a
181+
// ChildProcessWithoutNullStreams without widening casts.
182+
const spawned = Object.assign(new ChildProcess(), {
183+
pid: child.pid,
184+
stdin,
185+
stdout,
186+
stderr,
187+
stdio: [stdin, stdout, stderr, null, null] as [
188+
PassThrough,
189+
PassThrough,
190+
PassThrough,
191+
null,
192+
null,
193+
],
194+
});
195+
ctx.onTestFinished(() => {
196+
spawned.stdin.destroy();
197+
spawned.stdout.destroy();
198+
spawned.stderr.destroy();
199+
spawned.removeAllListeners();
200+
});
201+
const kill = vi.spyOn(spawned, "kill").mockReturnValue(true);
202+
vi.mocked(readCodexAppServerProcessSnapshot).mockResolvedValue([
203+
observer,
204+
{ ...liveChild, ppid: process.pid },
205+
]);
206+
vi.mocked(readCodexAppServerProcessCommand).mockImplementation(async () => {
207+
if (mode === "exited during inspection") {
208+
Object.defineProperty(spawned, "exitCode", { value: 0, configurable: true });
209+
spawned.emit("exit", 0, null);
210+
}
211+
return mode === "unreadable command" ? undefined : command;
212+
});
213+
const register = await prepareCodexAppServerProcessRegistration();
214+
const registered = register(spawned);
215+
spawned.emit("spawn");
216+
217+
if (mode === "live") {
218+
await registered;
219+
expect(store.entries().map((entry) => entry.value)).toEqual([
220+
{
221+
parent: { pid: observer.pid, pgid: observer.pgid, startedAt: observer.startedAt },
222+
child: { ...child, commandFingerprint },
223+
},
224+
]);
225+
// Durable rows must never expose the raw argv (appServer.args can carry secrets).
226+
expect(JSON.stringify(store.entries())).not.toContain(command);
227+
expect(kill).not.toHaveBeenCalled();
228+
spawned.emit("exit", 0, null);
229+
expect(store.entries()).toEqual([]);
230+
} else {
231+
await expect(registered).rejects.toThrow("Cannot register the Codex child process command");
232+
expect(kill).toHaveBeenCalledExactlyOnceWith("SIGKILL");
233+
expect(
234+
[spawned.stdin, spawned.stdout, spawned.stderr].every((stream) => stream.destroyed),
235+
).toBe(true);
236+
expect(store.entries()).toEqual([]);
237+
}
238+
},
239+
);
240+
241+
it.for(["success", "failure", "win32"])(
242+
"starts a nonblocking best-effort boot sweep: %s",
243+
async (mode) => {
244+
store.register("orphan", { parent, child: { ...child, commandFingerprint } });
245+
const warn = vi.fn();
246+
const service = createCodexAppServerProcessReaperService();
247+
const sweep = createDeferred<boolean>();
248+
vi.mocked(terminateCodexAppServerOrphan).mockReturnValue(sweep.promise);
249+
if (mode === "win32") {
250+
vi.spyOn(process, "platform", "get").mockReturnValue("win32");
251+
}
252+
253+
expect(
254+
service.start({
255+
config: {},
256+
stateDir: root,
257+
logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() },
258+
}),
259+
).toBeUndefined();
260+
261+
if (mode === "win32") {
262+
expect(readCodexAppServerProcessSnapshot).not.toHaveBeenCalled();
263+
expect(terminateCodexAppServerOrphan).not.toHaveBeenCalled();
264+
expect(store.lookup("orphan")).toBeDefined();
265+
expect(warn).not.toHaveBeenCalled();
266+
return;
267+
}
268+
await expect.poll(() => vi.mocked(terminateCodexAppServerOrphan).mock.calls.length).toBe(1);
269+
if (mode === "failure") {
270+
sweep.reject(new Error("inspection unavailable"));
271+
await expect
272+
.poll(() => warn.mock.calls)
273+
.toEqual([["Codex app-server orphan cleanup failed: Error: inspection unavailable"]]);
274+
expect(store.lookup("orphan")).toBeDefined();
275+
} else {
276+
sweep.resolve(true);
277+
await expect.poll(() => store.lookup("orphan")).toBeUndefined();
278+
expect(warn).not.toHaveBeenCalled();
279+
}
280+
},
281+
);
282+
});

0 commit comments

Comments
 (0)