Skip to content

Commit 1180a53

Browse files
authored
fix(codex): scope startup inspection to registered process owners (#133111)
Avoid blocking known-PID registration on unrelated unreadable processes and distinguish deadline failures from access denial. Preserve full-tree containment, command fingerprints, and fresh signal identity checks. Fixes #133101.
1 parent 357078c commit 1180a53

11 files changed

Lines changed: 507 additions & 125 deletions

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

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,21 @@ or discover descendants that independently reparented before inspection.
9292

9393
Linux reads process identities directly from `/proc`, including the boot ID
9494
and process start ticks, so Alpine/BusyBox installations do not need `procps`.
95-
macOS uses its native `ps` with a fixed locale and timezone.
96-
97-
If process inspection or bounded cleanup cannot confirm that the registered
98-
orphan is gone, the new stdio connection fails instead of spawning another
99-
child. Follow the reported action: check `/proc` access on Linux or `ps` on
100-
macOS, or verify and stop
101-
the reported orphan process, then retry. If the cleanup budget expires, retry
102-
to finish the remaining registrations.
95+
macOS uses its native `ps` with a fixed locale and timezone. Registration checks
96+
inspect only the observer and the relevant parent and child processes; an
97+
unrelated unreadable process does not block those checks. Destructive cleanup
98+
still requires full process-tree inspection and fresh identity checks before
99+
signaling.
100+
101+
If a required process cannot be inspected or bounded cleanup cannot confirm that
102+
the registered orphan is gone, the new stdio connection fails instead of spawning
103+
another child. Follow the reported reason: a deadline failure calls for checking
104+
host load and Gateway logs, while an access-denied failure calls for checking
105+
`/proc` access on Linux or `ps` permissions on macOS. Other inspection failures
106+
require checking that the process-inspection facility is available and returning
107+
usable data. Do not broaden permissions to address a timeout. If cleanup cannot
108+
stop a verified orphan, inspect and stop that process before retrying. If the
109+
cleanup budget expires, retry to finish the remaining registrations.
103110

104111
This recovery requires a spawn-time registration. It does not discover
105112
unregistered children left by an older OpenClaw version or scan command names

‎extensions/codex/src/app-server/attempt-startup-retry.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ describe("Codex app-server startup retry", () => {
250250
expect(exited).toBe(true);
251251
expect(exitDelivered).toBe(false);
252252
expect(firstChild.exitCode).toBeNull();
253-
return undefined;
253+
throw new processSnapshot.ProcessInspectionError("unavailable");
254254
});
255255
try {
256256
const result = await startFixtureAttempt(fixture, factory);
@@ -402,7 +402,7 @@ describe("Codex app-server startup retry", () => {
402402
expect(error).toBeInstanceOf(Error);
403403
expect(isCodexAppServerConnectionClosedError(error)).toBe(false);
404404
expect((error as Error).message).toContain(
405-
failure === "commit" ? "512-row limit" : "Cannot register the Codex child process",
405+
failure === "commit" ? "512-row limit" : "Process inspection exceeded its deadline",
406406
);
407407
expect((error as Error).message).toContain("startup diagnostic: inspection probe");
408408
expect(await fs.readFile(fixture.spawnCountPath, "utf8")).toBe("1");

‎extensions/codex/src/app-server/transport-orphan.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ describe.skipIf(process.platform === "win32")("Codex stdio crash recovery", () =
135135

136136
if (process.platform !== "linux") {
137137
await expect(start(stateDir, unavailablePs)).rejects.toThrow(
138-
"Cannot inspect registered Codex processes",
138+
"Cannot inspect Codex processes. Process identity is unavailable or invalid.",
139139
);
140140
expect(isAlive(old.tree.child)).toBe(true);
141141
}

‎extensions/codex/src/app-server/transport-process-containment.ts‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,17 @@ export async function terminateCodexAppServerOrphan(
3838
let gone = false;
3939
try {
4040
if (contained) {
41-
const current = await readCodexAppServerProcess(expected.pid, deadline);
41+
const current = await readCodexAppServerProcess(expected.pid, deadline).catch(
42+
() => undefined,
43+
);
4244
if (current && isSameLiveRoot(current, contained.root, true)) {
4345
// Keep the verified leader stopped until its whole group is killed;
4446
// a QA-owned child may share its parent's group and must use its PID.
4547
signalProcess(current.pgid === current.pid ? -current.pid : current.pid, "SIGKILL");
4648
}
4749
}
4850
while (Date.now() < deadline) {
49-
const snapshot = await readCodexAppServerProcessSnapshot(deadline);
51+
const snapshot = await readCodexAppServerProcessSnapshot(deadline).catch(() => undefined);
5052
if (!snapshot?.some((row) => row.pid === process.pid)) {
5153
return false;
5254
}
@@ -82,7 +84,8 @@ async function containDescendants(
8284
if (process.platform === "win32" || !rootPid || !child.kill) {
8385
return undefined;
8486
}
85-
const snapshot = await readCodexAppServerProcessSnapshot(deadline);
87+
// Inspection failures never grant containment or signal authority.
88+
const snapshot = await readCodexAppServerProcessSnapshot(deadline).catch(() => undefined);
8689
if (!snapshot || Date.now() >= deadline) {
8790
return undefined;
8891
}
@@ -177,7 +180,7 @@ async function quiesceDescendants(
177180
if (Date.now() >= deadline) {
178181
return undefined;
179182
}
180-
const snapshot = await readCodexAppServerProcessSnapshot(deadline);
183+
const snapshot = await readCodexAppServerProcessSnapshot(deadline).catch(() => undefined);
181184
if (!snapshot || Date.now() >= deadline) {
182185
return undefined;
183186
}
@@ -325,7 +328,7 @@ async function signalSameRoot(
325328
signal: NodeJS.Signals,
326329
deadline: number,
327330
): Promise<boolean> {
328-
const current = await readCodexAppServerProcess(root.pid, deadline);
331+
const current = await readCodexAppServerProcess(root.pid, deadline).catch(() => undefined);
329332
return Boolean(current && isSameLiveRoot(current, root) && signalProcess(current.pid, signal));
330333
}
331334

@@ -358,7 +361,7 @@ async function signalSameProcess(
358361
): Promise<boolean> {
359362
// Portable Node POSIX signals are PID-based, so never retain numeric authority:
360363
// take this final identity snapshot synchronously immediately before every signal.
361-
const current = await readCodexAppServerProcess(expected.pid, deadline);
364+
const current = await readCodexAppServerProcess(expected.pid, deadline).catch(() => undefined);
362365
return Boolean(
363366
current && isSameLiveProcess(current, expected) && signalProcess(current.pid, signal),
364367
);
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
import { ChildProcess } from "node:child_process";
2+
import { createHash } from "node:crypto";
3+
import { PassThrough } from "node:stream";
4+
import { createPluginStateSyncKeyedStore } from "openclaw/plugin-sdk/plugin-state-store-runtime";
5+
import { createOpenClawTestState } from "openclaw/plugin-sdk/test-state";
6+
import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from "vitest";
7+
import { terminateCodexAppServerOrphan } from "./transport-process-containment.js";
8+
import { prepareCodexAppServerProcessRegistration } from "./transport-process-registration.js";
9+
import { readCodexAppServerProcessSnapshot } from "./transport-process-snapshot.js";
10+
11+
const procfs = vi.hoisted(() => ({ files: new Map<string, string | Error>() }));
12+
vi.mock("node:fs/promises", async (importOriginal) => {
13+
const original = await importOriginal<typeof import("node:fs/promises")>();
14+
return {
15+
...original,
16+
readFile: (...args: Parameters<typeof original.readFile>) => {
17+
const file = args[0];
18+
if (typeof file !== "string" || !file.startsWith("/proc/")) {
19+
return original.readFile(...args);
20+
}
21+
const value = procfs.files.get(file);
22+
return typeof value === "string"
23+
? Promise.resolve(value)
24+
: Promise.reject(value ?? Object.assign(new Error("gone"), { code: "ENOENT" }));
25+
},
26+
readdir: (...args: Parameters<typeof original.readdir>) =>
27+
args[0] === "/proc"
28+
? Promise.resolve(
29+
[...procfs.files.keys()].flatMap(
30+
(file) => /^\/proc\/(\d+)\/stat$/.exec(file)?.[1] ?? [],
31+
),
32+
)
33+
: original.readdir(...args),
34+
};
35+
});
36+
37+
const bootId = "00000000-0000-0000-0000-000000000001";
38+
const identity = (pid: number) => ({ pid, pgid: pid, startedAt: `${bootId}:12345` });
39+
const parent = identity(500001);
40+
const child = identity(500002);
41+
const neighbor = 500003;
42+
const command = "/opt/codex app-server --listen stdio://";
43+
const commandFingerprint = createHash("sha256").update(command).digest("hex");
44+
45+
function addProcess(pid: number, ppid: number) {
46+
procfs.files.set(
47+
`/proc/${pid}/stat`,
48+
`${pid} (worker) S ${ppid} ${pid}${" 0".repeat(16)} 12345\n`,
49+
);
50+
procfs.files.set(`/proc/${pid}/cmdline`, command.replaceAll(" ", "\0"));
51+
}
52+
53+
describe("Codex registration procfs boundary", () => {
54+
let state: Awaited<ReturnType<typeof createOpenClawTestState>>;
55+
let store: ReturnType<
56+
typeof createPluginStateSyncKeyedStore<{
57+
parent: ReturnType<typeof identity>;
58+
child: ReturnType<typeof identity> & { commandFingerprint: string };
59+
}>
60+
>;
61+
let kill: MockInstance<typeof process.kill>;
62+
63+
beforeEach(async () => {
64+
state = await createOpenClawTestState({ prefix: "codex-registration-procfs-" });
65+
store = createPluginStateSyncKeyedStore("codex", {
66+
namespace: "app-server-processes",
67+
maxEntries: 512,
68+
overflowPolicy: "reject-new",
69+
});
70+
vi.spyOn(process, "platform", "get").mockReturnValue("linux");
71+
// Synthetic PIDs must never reach the real signal syscall, even on regression.
72+
kill = vi.spyOn(process, "kill").mockImplementation(() => {
73+
throw new Error("unexpected signal");
74+
});
75+
procfs.files.set("/proc/sys/kernel/random/boot_id", bootId);
76+
addProcess(process.pid, process.ppid);
77+
addProcess(parent.pid, 1);
78+
addProcess(child.pid, parent.pid);
79+
procfs.files.set(
80+
`/proc/${neighbor}/stat`,
81+
Object.assign(new Error("unreadable neighbor"), { code: "EACCES" }),
82+
);
83+
});
84+
85+
afterEach(async () => {
86+
store.clear();
87+
vi.restoreAllMocks();
88+
procfs.files.clear();
89+
await state.cleanup();
90+
});
91+
92+
it("preserves a live owner's registration despite an unreadable unrelated process", async () => {
93+
const registration = { parent, child: { ...child, commandFingerprint } };
94+
store.register("owned", registration);
95+
96+
await expect(
97+
Promise.all([
98+
prepareCodexAppServerProcessRegistration(),
99+
prepareCodexAppServerProcessRegistration(),
100+
]),
101+
).resolves.toHaveLength(2);
102+
103+
expect(store.lookup("owned")).toEqual(registration);
104+
expect(kill).not.toHaveBeenCalled();
105+
});
106+
107+
it.for(["readable", "permission", "malformed", "deadline", "missing-observer"])(
108+
"registers a direct child despite an unreadable unrelated process only with usable ownership: %s",
109+
async (mode, ctx) => {
110+
addProcess(child.pid, process.pid);
111+
const stdin = new PassThrough();
112+
const stdout = new PassThrough();
113+
const stderr = new PassThrough();
114+
const spawned = Object.assign(new ChildProcess(), {
115+
pid: child.pid,
116+
stdin,
117+
stdout,
118+
stderr,
119+
stdio: [stdin, stdout, stderr, null, null] as [
120+
PassThrough,
121+
PassThrough,
122+
PassThrough,
123+
null,
124+
null,
125+
],
126+
});
127+
ctx.onTestFinished(() => {
128+
stdin.destroy();
129+
stdout.destroy();
130+
stderr.destroy();
131+
spawned.removeAllListeners();
132+
});
133+
const register = await prepareCodexAppServerProcessRegistration();
134+
if (mode === "missing-observer") {
135+
procfs.files.delete(`/proc/${process.pid}/stat`);
136+
} else if (mode !== "readable") {
137+
procfs.files.set(
138+
`/proc/${child.pid}/stat`,
139+
mode === "malformed"
140+
? ""
141+
: Object.assign(new Error("child inspection failed"), {
142+
code: mode === "deadline" ? "ABORT_ERR" : "EACCES",
143+
}),
144+
);
145+
}
146+
const registered = register(spawned);
147+
spawned.emit("spawn");
148+
149+
if (mode !== "readable") {
150+
await expect(registered).rejects.toMatchObject({
151+
reason: mode === "permission" || mode === "deadline" ? mode : "unavailable",
152+
});
153+
expect(store.entries()).toEqual([]);
154+
expect(kill).not.toHaveBeenCalled();
155+
return;
156+
}
157+
await registered;
158+
159+
expect(store.entries().map((entry) => entry.value)).toEqual([
160+
{ parent: identity(process.pid), child: { ...child, commandFingerprint } },
161+
]);
162+
expect(kill).not.toHaveBeenCalled();
163+
spawned.emit("exit", 0, null);
164+
expect(store.entries()).toEqual([]);
165+
},
166+
);
167+
168+
it.for([
169+
["permission", "EACCES"],
170+
["unavailable", "EIO"],
171+
["deadline", "ABORT_ERR"],
172+
["unavailable", "empty"],
173+
["unavailable", "group-zero"],
174+
["unavailable", "missing-observer"],
175+
] as const)(
176+
"retains registrations when required identity inspection fails: %s/%s",
177+
async ([reason, fault]) => {
178+
const registration = { parent, child: { ...child, commandFingerprint } };
179+
store.register("owned", registration);
180+
if (fault === "missing-observer") {
181+
procfs.files.delete(`/proc/${process.pid}/stat`);
182+
} else {
183+
procfs.files.set(
184+
`/proc/${parent.pid}/stat`,
185+
fault === "empty"
186+
? ""
187+
: fault === "group-zero"
188+
? `${parent.pid} (worker) S 1 0${" 0".repeat(16)} 12345\n`
189+
: Object.assign(new Error("required inspection failed"), { code: fault }),
190+
);
191+
}
192+
193+
await expect(prepareCodexAppServerProcessRegistration()).rejects.toMatchObject({ reason });
194+
expect(store.lookup("owned")).toEqual(registration);
195+
expect(kill).not.toHaveBeenCalled();
196+
},
197+
);
198+
199+
it("keeps full-tree inspection fail-closed with the same unreadable neighbor", async () => {
200+
await expect(readCodexAppServerProcessSnapshot()).rejects.toMatchObject({
201+
reason: "permission",
202+
});
203+
await expect(terminateCodexAppServerOrphan(child)).resolves.toBe(false);
204+
expect(kill).not.toHaveBeenCalled();
205+
});
206+
207+
it.for(["ENOENT", "ESRCH"])(
208+
"retires verified disappeared identities only after full containment inspection: %s",
209+
async (code) => {
210+
store.register("orphan", { parent, child: { ...child, commandFingerprint } });
211+
for (const pid of [parent.pid, child.pid]) {
212+
procfs.files.set(`/proc/${pid}/stat`, Object.assign(new Error("gone"), { code }));
213+
}
214+
// Selected identities are gone, but an unreadable full tree still blocks retirement.
215+
await expect(prepareCodexAppServerProcessRegistration()).rejects.toThrow(
216+
"Cannot reap registered Codex process",
217+
);
218+
expect(store.lookup("orphan")).toBeDefined();
219+
procfs.files.delete(`/proc/${neighbor}/stat`);
220+
await prepareCodexAppServerProcessRegistration();
221+
expect(store.lookup("orphan")).toBeUndefined();
222+
expect(kill).not.toHaveBeenCalled();
223+
},
224+
);
225+
});

0 commit comments

Comments
 (0)