Skip to content

Commit 10ee252

Browse files
authored
fix(codex): reap orphaned app-servers before reconnect (#132610)
* fix(codex): reap orphaned app-servers before reconnect * style(codex): avoid returning the containment timer handle * fix(codex): inspect Linux children without requiring procps * fix(codex): tolerate processes exiting during procfs reads * test(codex): normalize socket fixture binary frames * fix(codex): preserve startup errors during process registration
1 parent c0d853b commit 10ee252

23 files changed

Lines changed: 1326 additions & 555 deletions

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,39 @@ marked `catalogMode: "direct-only"` use `openclaw_direct`, which Codex keeps
6969
directly model-visible as `DirectModelOnly` instead of exposing it to nested
7070
Code Mode execution.
7171

72+
## Recovery after a hard Gateway stop
73+
74+
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
78+
before sending Codex `initialize`, so a child cannot start a native turn before
79+
its registration is durable.
80+
81+
Cleanup only targets a registered child whose original OpenClaw parent is no
82+
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
85+
managed WebSocket or Unix-socket app-servers are left alone. These portable
86+
process checks do not provide an atomic operating-system ownership guarantee
87+
or discover descendants that independently reparented before inspection.
88+
89+
Linux reads process identities directly from `/proc`, including the boot ID
90+
and process start ticks, so Alpine/BusyBox installations do not need `procps`.
91+
macOS uses its native `ps` with a fixed locale and timezone.
92+
93+
If process inspection or bounded cleanup cannot confirm that the registered
94+
orphan is gone, the new stdio connection fails instead of spawning another
95+
child. Follow the reported action: check `/proc` access on Linux or `ps` on
96+
macOS, or verify and stop
97+
the reported orphan process, then retry. If the cleanup budget expires, retry
98+
to finish the remaining registrations.
99+
100+
This recovery requires a spawn-time registration. It does not discover
101+
unregistered children left by an older OpenClaw version or scan command names
102+
to infer ownership. Windows does not yet have equivalent orphan registration
103+
and recovery.
104+
72105
## Thread bindings and model changes
73106

74107
When an OpenClaw session is attached to an existing Codex thread, the next

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

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1+
import * as childProcess from "node:child_process";
12
import { randomUUID } from "node:crypto";
3+
import { once } from "node:events";
24
import fs from "node:fs/promises";
35
import os from "node:os";
46
import path from "node:path";
@@ -27,6 +29,11 @@ import {
2729
releaseLeasedSharedCodexAppServerClient,
2830
} from "./shared-client.js";
2931
import { createCodexTestModel } from "./test-support.js";
32+
import * as processSnapshot from "./transport-process-snapshot.js";
33+
34+
vi.mock("node:child_process", async (importOriginal) => ({
35+
...(await importOriginal<typeof import("node:child_process")>()),
36+
}));
3037

3138
vi.mock("./desktop-generation.js", () => ({
3239
isCodexDesktopGenerationCurrent: () => false,
@@ -172,10 +179,35 @@ describe("Codex app-server startup retry", () => {
172179
tempRoots.clear();
173180
});
174181

175-
it("retries a real app-server after transient sqlite state initialization failure", async () => {
182+
it("retries a real app-server that fails sqlite initialization before registration completes", async (ctx) => {
176183
const fixture = await createStartupFailureFixture("transient");
184+
let firstChildExit: Promise<unknown> | undefined;
185+
const spawn = childProcess.spawn;
186+
const snapshot = processSnapshot.readCodexAppServerProcessSnapshot;
187+
const spawnSpy = vi.spyOn(childProcess, "spawn").mockImplementation((...args) => {
188+
const child = spawn(...args);
189+
if (
190+
Array.isArray(args[1]) &&
191+
args[1].includes(path.join(fixture.root, "startup-failure.mjs"))
192+
) {
193+
firstChildExit ??= once(child, "exit");
194+
}
195+
return child;
196+
});
197+
const snapshotSpy = vi
198+
.spyOn(processSnapshot, "readCodexAppServerProcessSnapshot")
199+
.mockImplementation(async (...args) => {
200+
// A slow inspector must not replace the child's retryable startup error.
201+
await firstChildExit;
202+
return await snapshot(...args);
203+
});
204+
ctx.onTestFinished(() => {
205+
spawnSpy.mockRestore();
206+
snapshotSpy.mockRestore();
207+
});
177208
const result = await startFixtureAttempt(fixture);
178209

210+
expect(firstChildExit).toBeDefined();
179211
expect(result.thread.threadId).toBe("thread-recovered");
180212
expect(await fs.readFile(fixture.spawnCountPath, "utf8")).toBe("2");
181213
result.turnRoute.release();

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

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ function startThreadWithHarness(
161161
const paths = overrides?.paths ?? createAttemptPaths();
162162
const startSpy = overrides?.skipStartSpy
163163
? undefined
164-
: vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
164+
: vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
165165
const effectivePluginConfig = overrides?.pluginConfig ?? pluginConfig;
166166

167167
const run = startCodexAttemptThread({
@@ -383,8 +383,8 @@ describe("startCodexAttemptThread", () => {
383383
};
384384
const startSpy = vi
385385
.spyOn(CodexAppServerClient, "start")
386-
.mockReturnValueOnce(first.client)
387-
.mockReturnValueOnce(second.client);
386+
.mockResolvedValueOnce(first.client)
387+
.mockResolvedValueOnce(second.client);
388388
const paths = createAttemptPaths();
389389
let persistedComputerUse = false;
390390
const { run } = startThreadWithHarness(10_000, new AbortController().signal, {
@@ -455,8 +455,8 @@ describe("startCodexAttemptThread", () => {
455455
const second = createClientHarness();
456456
const startSpy = vi
457457
.spyOn(CodexAppServerClient, "start")
458-
.mockReturnValueOnce(first.client)
459-
.mockReturnValueOnce(second.client);
458+
.mockResolvedValueOnce(first.client)
459+
.mockResolvedValueOnce(second.client);
460460
desktopGeneration.current = { epoch: 1, fingerprint: "desktop-x" };
461461
if (changeStage === "Computer Use readiness") {
462462
computerUseReadinessFailure.next = Object.assign(new Error("desktop selection changed"), {
@@ -511,7 +511,7 @@ describe("startCodexAttemptThread", () => {
511511

512512
it("retires the startup generation when context restart sees a new executable owner", async () => {
513513
const harness = createClientHarness();
514-
vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
514+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
515515
const paths = createAttemptPaths();
516516
const { run } = startThreadWithHarness(5_000, new AbortController().signal, {
517517
harness,
@@ -547,8 +547,8 @@ describe("startCodexAttemptThread", () => {
547547
const replacement = createClientHarness();
548548
const startSpy = vi
549549
.spyOn(CodexAppServerClient, "start")
550-
.mockReturnValueOnce(retained.client)
551-
.mockReturnValueOnce(replacement.client);
550+
.mockResolvedValueOnce(retained.client)
551+
.mockResolvedValueOnce(replacement.client);
552552
const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig });
553553
const paths = createAttemptPaths();
554554

@@ -610,7 +610,7 @@ describe("startCodexAttemptThread", () => {
610610

611611
it("closes indeterminate thread startup even when another lease shares the app-server", async () => {
612612
const retained = createClientHarness();
613-
vi.spyOn(CodexAppServerClient, "start").mockReturnValue(retained.client);
613+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(retained.client);
614614
const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig });
615615
const paths = createAttemptPaths();
616616

@@ -798,7 +798,7 @@ describe("startCodexAttemptThread", () => {
798798
const clients = [createClientHarness(), createClientHarness(), createClientHarness()];
799799
const start = vi.spyOn(CodexAppServerClient, "start");
800800
for (const harness of clients) {
801-
start.mockReturnValueOnce(harness.client);
801+
start.mockResolvedValueOnce(harness.client);
802802
}
803803
const environmentIds = new Set<string>();
804804

@@ -831,7 +831,7 @@ describe("startCodexAttemptThread", () => {
831831
const runtime = createPairedAttemptRuntime();
832832
const firstPaths = createAttemptPaths();
833833
const secondPaths = createAttemptPaths();
834-
const start = vi.spyOn(CodexAppServerClient, "start").mockImplementation((options) => {
834+
const start = vi.spyOn(CodexAppServerClient, "start").mockImplementation(async (options) => {
835835
const codexHome = options?.env?.CODEX_HOME;
836836
if (codexHome?.startsWith(`${firstPaths.agentDir}${path.sep}`)) {
837837
return first.client;

‎extensions/codex/src/app-server/client.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,10 @@ export class CodexAppServerClient {
273273
}
274274

275275
/** Starts a new app-server client using resolved runtime start options. */
276-
static start(options?: Partial<CodexAppServerStartOptions>): CodexAppServerClient {
276+
static async start(
277+
options?: Partial<CodexAppServerStartOptions>,
278+
assertCurrent?: () => void,
279+
): Promise<CodexAppServerClient> {
277280
const defaults = resolveCodexAppServerRuntimeOptions().start;
278281
const startOptions = {
279282
...defaults,
@@ -286,7 +289,17 @@ export class CodexAppServerClient {
286289
if (startOptions.transport === "websocket" || startOptions.transport === "unix") {
287290
return new CodexAppServerClient(createWebSocketTransport(startOptions));
288291
}
289-
return new CodexAppServerClient(createStdioTransport(startOptions));
292+
// The spawn callback runs synchronously before registration; initialization
293+
// stays blocked until registration finishes, without losing startup errors.
294+
let client!: CodexAppServerClient;
295+
try {
296+
await createStdioTransport(startOptions, process.env, assertCurrent, (child) => {
297+
client = new CodexAppServerClient(child);
298+
});
299+
return client;
300+
} catch (error) {
301+
throw client?.getCloseError() ?? error;
302+
}
290303
}
291304

292305
/** Builds a client around a fake transport for tests. */

‎extensions/codex/src/app-server/models.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ describe("listCodexAppServerModels", () => {
166166
},
167167
])("rejects $label through the app-server JSON-RPC boundary", async ({ response }) => {
168168
const harness = createClientHarness();
169-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
169+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
170170

171171
const listPromise = listCodexAppServerModels({ timeoutMs: 1000 });
172172
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));
@@ -187,7 +187,7 @@ describe("listCodexAppServerModels", () => {
187187

188188
it("lists app-server models through the typed helper", async () => {
189189
const harness = createClientHarness();
190-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
190+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
191191

192192
const listPromise = listCodexAppServerModels({ limit: 12, timeoutMs: 1000 });
193193
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));
@@ -257,7 +257,7 @@ describe("listCodexAppServerModels", () => {
257257

258258
it("lists all app-server model pages through one client", async () => {
259259
const harness = createClientHarness();
260-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
260+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
261261

262262
const listPromise = listAllCodexAppServerModels({ limit: 1, timeoutMs: 1000 });
263263
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));
@@ -337,7 +337,7 @@ describe("listCodexAppServerModels", () => {
337337

338338
it("marks all-model listing truncated after the page cap", async () => {
339339
const harness = createClientHarness();
340-
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
340+
const startSpy = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
341341

342342
const listPromise = listAllCodexAppServerModels({ limit: 1, timeoutMs: 1000, maxPages: 1 });
343343
await vi.waitFor(() => expect(harness.writes.length).toBeGreaterThanOrEqual(1));

‎extensions/codex/src/app-server/run-attempt-thread-cleanup.test.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ describe("Codex app-server main thread cleanup", () => {
188188
b: path.join(tempDir, "session-b.jsonl"),
189189
};
190190
const harness = createClientHarness();
191-
vi.spyOn(CodexAppServerClient, "start").mockReturnValue(harness.client);
191+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(harness.client);
192192

193193
for (const [index, label] of (["a", "b", "a", "b"] as const).entries()) {
194194
const sessionKey = `agent:main:session-${label}`;
@@ -284,7 +284,7 @@ describe("Codex app-server main thread cleanup", () => {
284284

285285
it("preserves a quiet long-running native tool while a distinct shared-client turn completes", async () => {
286286
const physical = createClientHarness();
287-
const startClient = vi.spyOn(CodexAppServerClient, "start").mockReturnValue(physical.client);
287+
const startClient = vi.spyOn(CodexAppServerClient, "start").mockResolvedValue(physical.client);
288288
const firstParams = createParams(
289289
path.join(tempDir, "concurrent-first.jsonl"),
290290
path.join(tempDir, "concurrent-first-workspace"),
@@ -441,7 +441,7 @@ describe("Codex app-server main thread cleanup", () => {
441441
const workspaceDir = path.join(tempDir, "incognito-workspace");
442442
const sessionKey = "agent:main:dashboard:incognito-live-thread";
443443
const harness = createClientHarness();
444-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
444+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
445445
const run = runCodexAppServerAttempt(createParams(sessionFile, workspaceDir, sessionKey), {
446446
bindingStore: testCodexAppServerBindingStore,
447447
});
@@ -547,7 +547,7 @@ describe("Codex app-server main thread cleanup", () => {
547547
const workspaceDir = path.join(tempDir, "cancelled-start-workspace");
548548
const harness = createClientHarness();
549549
const abort = new AbortController();
550-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
550+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
551551

552552
const params = createParams(sessionFile, workspaceDir);
553553
params.abortSignal = abort.signal;
@@ -655,7 +655,7 @@ describe("Codex app-server main thread cleanup", () => {
655655
const harness = createClientHarness();
656656
const abort = new AbortController();
657657
const close = vi.spyOn(harness.client, "close");
658-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
658+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
659659

660660
const params = createParams(sessionFile, workspaceDir, sessionKey);
661661
params.abortSignal = abort.signal;
@@ -759,7 +759,7 @@ describe("Codex app-server main thread cleanup", () => {
759759

760760
it("rejects late cancellation after failed finalization enters cleanup", async () => {
761761
const harness = createClientHarness();
762-
vi.spyOn(CodexAppServerClient, "start").mockReturnValueOnce(harness.client);
762+
vi.spyOn(CodexAppServerClient, "start").mockResolvedValueOnce(harness.client);
763763
const abort = new AbortController();
764764
const params = createParams(
765765
path.join(tempDir, "failed-finalization.jsonl"),
@@ -803,8 +803,8 @@ describe("Codex app-server main thread cleanup", () => {
803803
const replacement = createClientHarness();
804804
const startClient = vi
805805
.spyOn(CodexAppServerClient, "start")
806-
.mockReturnValueOnce(contaminated.client)
807-
.mockReturnValueOnce(replacement.client);
806+
.mockResolvedValueOnce(contaminated.client)
807+
.mockResolvedValueOnce(replacement.client);
808808

809809
const failedRun = runCodexAppServerAttempt(
810810
createParams(sessionFile, workspaceDir, sessionKey),

0 commit comments

Comments
 (0)