Skip to content

Commit 92b4af2

Browse files
authored
improve(codex): reuse live app-server threads safely (#115089)
1 parent 086d17d commit 92b4af2

14 files changed

Lines changed: 1155 additions & 52 deletions

‎extensions/codex/media-understanding-provider.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,9 @@ describe("codex media understanding provider", () => {
465465
});
466466

467467
it("clamps oversized image understanding turn timeouts", async () => {
468+
// The bounded timer subtracts startup time from its clamped deadline.
469+
// Freeze the clock so the clamp assertion cannot lose a real millisecond.
470+
const dateNowSpy = vi.spyOn(Date, "now").mockReturnValue(1_700_000_000_000);
468471
const setTimeoutSpy = vi.spyOn(globalThis, "setTimeout");
469472
try {
470473
const { client } = createFakeClient();
@@ -486,6 +489,7 @@ describe("codex media understanding provider", () => {
486489
expect(result?.text).toBe("A red square.");
487490
expect(setTimeoutSpy).toHaveBeenCalledWith(expect.any(Function), MAX_TIMER_TIMEOUT_MS);
488491
} finally {
492+
dateNowSpy.mockRestore();
489493
vi.restoreAllMocks();
490494
vi.clearAllTimers();
491495
vi.useRealTimers();

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

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,11 @@ vi.mock("./rate-limit-cache.js", () => ({
1515
mergeCodexRateLimitsUpdate: mocks.mergeRateLimitUpdate,
1616
}));
1717

18-
const { ensureCodexAppServerClientRuntime } = await import("./client-runtime.js");
18+
const {
19+
consumeCodexAppServerLiveThread,
20+
ensureCodexAppServerClientRuntime,
21+
retainCodexAppServerLiveThread,
22+
} = await import("./client-runtime.js");
1923

2024
describe("Codex app-server client runtime", () => {
2125
const clients: CodexAppServerClient[] = [];
@@ -99,4 +103,77 @@ describe("Codex app-server client runtime", () => {
99103
},
100104
});
101105
});
106+
107+
it("retains and consumes only one subscribed thread per physical client", async () => {
108+
const harness = createClientHarness();
109+
clients.push(harness.client);
110+
111+
await expect(
112+
retainCodexAppServerLiveThread(harness.client, "thread-before-runtime"),
113+
).resolves.toBeUndefined();
114+
ensureCodexAppServerClientRuntime(harness.client, { agentDir: "/tmp/agent" });
115+
116+
await expect(retainCodexAppServerLiveThread(harness.client, "thread-1")).resolves.toEqual({});
117+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-2")).resolves.toBe(false);
118+
await expect(retainCodexAppServerLiveThread(harness.client, "thread-2")).resolves.toEqual({
119+
previousThreadId: "thread-1",
120+
});
121+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-1")).resolves.toBe(false);
122+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-2")).resolves.toBe(true);
123+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-2")).resolves.toBe(false);
124+
});
125+
126+
it("waits for the old subscription to release before another thread can acquire it", async () => {
127+
const harness = createClientHarness();
128+
clients.push(harness.client);
129+
ensureCodexAppServerClientRuntime(harness.client, { agentDir: "/tmp/agent" });
130+
await retainCodexAppServerLiveThread(harness.client, "thread-1");
131+
132+
let finishRelease: (() => void) | undefined;
133+
const previousRelease = new Promise<void>((resolve) => {
134+
finishRelease = resolve;
135+
});
136+
const transition = retainCodexAppServerLiveThread(
137+
harness.client,
138+
"thread-2",
139+
async () => previousRelease,
140+
);
141+
const oldThreadAcquisition = consumeCodexAppServerLiveThread(harness.client, "thread-1");
142+
143+
finishRelease?.();
144+
await expect(transition).resolves.toEqual({ previousThreadId: "thread-1" });
145+
await expect(oldThreadAcquisition).resolves.toBe(false);
146+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-2")).resolves.toBe(true);
147+
});
148+
149+
it("does not expose either thread after a previous subscription release fails", async () => {
150+
const harness = createClientHarness();
151+
clients.push(harness.client);
152+
ensureCodexAppServerClientRuntime(harness.client, { agentDir: "/tmp/agent" });
153+
await retainCodexAppServerLiveThread(harness.client, "thread-1");
154+
155+
await expect(
156+
retainCodexAppServerLiveThread(harness.client, "thread-2", async () => {
157+
throw new Error("unsubscribe unavailable");
158+
}),
159+
).rejects.toThrow("unsubscribe unavailable");
160+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-1")).resolves.toBe(false);
161+
await expect(consumeCodexAppServerLiveThread(harness.client, "thread-2")).resolves.toBe(false);
162+
});
163+
164+
it("reuses a retained subscription only for its complete configuration fingerprint", async () => {
165+
const harness = createClientHarness();
166+
clients.push(harness.client);
167+
ensureCodexAppServerClientRuntime(harness.client, { agentDir: "/tmp/agent" });
168+
169+
await expect(
170+
retainCodexAppServerLiveThread(harness.client, "thread-1", undefined, "config-before"),
171+
).resolves.toEqual({});
172+
await expect(
173+
consumeCodexAppServerLiveThread(harness.client, "thread-1", "config-after"),
174+
).resolves.toBe(false);
175+
await expect(
176+
consumeCodexAppServerLiveThread(harness.client, "thread-1", "config-before"),
177+
).resolves.toBe(true);
178+
});
102179
});

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ type ClientRuntimeContext = Omit<CodexAppServerAuthProfileLookup, "agentDir"> &
1212

1313
type ClientRuntime = {
1414
context: ClientRuntimeContext;
15+
retainedThreadId?: string;
16+
retainedThreadConfigFingerprint?: string;
17+
retainedThreadRelease?: Promise<void>;
1518
};
1619

1720
const configuredClients = new WeakMap<CodexAppServerClient, ClientRuntime>();
@@ -52,3 +55,65 @@ export function ensureCodexAppServerClientRuntime(
5255
}
5356
});
5457
}
58+
59+
/** Keep at most one idle, still-subscribed thread on a physical Codex client. */
60+
export async function retainCodexAppServerLiveThread(
61+
client: CodexAppServerClient,
62+
threadId: string,
63+
releasePreviousThread?: (previousThreadId: string) => Promise<void>,
64+
configFingerprint?: string,
65+
): Promise<{ previousThreadId?: string } | undefined> {
66+
const runtime = configuredClients.get(client);
67+
if (!runtime) {
68+
return undefined;
69+
}
70+
if (runtime.retainedThreadRelease) {
71+
await runtime.retainedThreadRelease;
72+
}
73+
const previousThreadId = runtime.retainedThreadId;
74+
if (previousThreadId && previousThreadId !== threadId && releasePreviousThread) {
75+
// Keep the old owner visible until its unsubscribe settles; concurrent
76+
// lifecycle acquisition must never resume a thread being released.
77+
const release = releasePreviousThread(previousThreadId);
78+
runtime.retainedThreadRelease = release;
79+
try {
80+
await release;
81+
} catch (error) {
82+
runtime.retainedThreadId = undefined;
83+
runtime.retainedThreadConfigFingerprint = undefined;
84+
throw error;
85+
} finally {
86+
if (runtime.retainedThreadRelease === release) {
87+
runtime.retainedThreadRelease = undefined;
88+
}
89+
}
90+
}
91+
runtime.retainedThreadId = threadId;
92+
runtime.retainedThreadConfigFingerprint = configFingerprint;
93+
return previousThreadId ? { previousThreadId } : {};
94+
}
95+
96+
/** A warm turn can skip resume only when this exact subscription was retained. */
97+
export async function consumeCodexAppServerLiveThread(
98+
client: CodexAppServerClient,
99+
threadId: string,
100+
configFingerprint?: string,
101+
): Promise<boolean> {
102+
const runtime = configuredClients.get(client);
103+
if (!runtime) {
104+
return false;
105+
}
106+
if (runtime.retainedThreadRelease) {
107+
await runtime.retainedThreadRelease;
108+
}
109+
if (
110+
runtime.retainedThreadId !== threadId ||
111+
(configFingerprint !== undefined &&
112+
runtime.retainedThreadConfigFingerprint !== configFingerprint)
113+
) {
114+
return false;
115+
}
116+
runtime.retainedThreadId = undefined;
117+
runtime.retainedThreadConfigFingerprint = undefined;
118+
return true;
119+
}

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

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,12 @@ import {
66
import { isIncognitoSessionKey } from "../incognito-session.js";
77
import {
88
CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
9+
closeCodexStartupClientBestEffort,
10+
CodexAppServerUnsafeSubscriptionError,
911
unsubscribeCodexThreadBestEffort,
1012
} from "./attempt-client-cleanup.js";
13+
import { retainCodexAppServerLiveThread } from "./client-runtime.js";
14+
import { resolveCodexAppServerClientInstanceId } from "./client.js";
1115
import { scheduleCodexNativeHookRelayUnregister } from "./native-hook-relay.js";
1216
import type { CodexAttemptActiveTurn } from "./run-attempt-active-turn.js";
1317
import type { CodexAttemptLifecycleController } from "./run-attempt-lifecycle-controller.js";
@@ -79,15 +83,48 @@ export async function cleanupCodexAttempt(
7983
}
8084
const retainLiveIncognitoThread =
8185
terminalState.turnSucceeded && isIncognitoSessionKey(params.sessionKey);
86+
// Native-preserved and supervision threads have separate ownership and can
87+
// never enter the ordinary persistent warm-thread cache.
88+
const retainedPersistentThread =
89+
terminalState.turnSucceeded &&
90+
!isIncognitoSessionKey(params.sessionKey) &&
91+
params.cleanupBundleMcpOnRunEnd !== true &&
92+
!params.contextEngine &&
93+
resourceState.thread.liveThreadConfigFingerprint !== undefined &&
94+
resourceState.thread.clientId === resolveCodexAppServerClientInstanceId(resourceState.client) &&
95+
resourceState.thread.preserveNativeModel !== true &&
96+
resourceState.thread.connectionScope !== "supervision" &&
97+
!resourceState.thread.ringZeroConfigFingerprint &&
98+
!resourceState.thread.contextEngine
99+
? await retainCodexAppServerLiveThread(
100+
resourceState.client,
101+
resourceState.thread.threadId,
102+
async (previousThreadId) => {
103+
const released = await unsubscribeCodexThreadBestEffort(resourceState.client, {
104+
threadId: previousThreadId,
105+
timeoutMs: CODEX_APP_SERVER_UNSUBSCRIBE_TIMEOUT_MS,
106+
});
107+
if (!released) {
108+
await closeCodexStartupClientBestEffort(resourceState.client);
109+
throw new CodexAppServerUnsafeSubscriptionError(
110+
`Codex retained thread subscription could not be released: ${previousThreadId}`,
111+
);
112+
}
113+
},
114+
resourceState.thread.liveThreadConfigFingerprint,
115+
)
116+
: undefined;
117+
// Replacement waits for the prior unsubscribe before publishing a new slot.
118+
const retainLiveThread = retainLiveIncognitoThread || retainedPersistentThread !== undefined;
82119
const bindingReleased =
83120
isIncognitoSessionKey(params.sessionKey) && !retainLiveIncognitoThread
84121
? await bindingStore.mutate(bindingIdentity, {
85122
kind: "clear",
86123
threadId: resourceState.thread.threadId,
87124
})
88125
: true;
89-
// Successful incognito turns retain the live subscription for cross-turn continuity.
90-
if (!state.timedOut && !retainLiveIncognitoThread) {
126+
// Only explicitly retained live threads may skip the next thread/resume.
127+
if (!state.timedOut && !retainLiveThread) {
91128
// Clear first: if a newer owner won the binding, its live subscription must remain intact.
92129
if (bindingReleased) {
93130
await unsubscribeCodexThreadBestEffort(resourceState.client, {

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

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ describe("Codex app-server main thread cleanup", () => {
169169
await fs.rm(tempDir, { recursive: true, force: true });
170170
});
171171

172-
it("unsubscribes the main Codex thread after a completed turn", async () => {
172+
it("retains a subscribed persistent Codex thread after a completed turn", async () => {
173173
const sessionFile = path.join(tempDir, "session.jsonl");
174174
const workspaceDir = path.join(tempDir, "workspace");
175175
const requests: Array<{ method: string; params: unknown }> = [];
@@ -217,16 +217,26 @@ describe("Codex app-server main thread cleanup", () => {
217217

218218
const result = await run;
219219
expect(readAttemptTerminal(result).aborted).toBe(false);
220-
expect(request).toHaveBeenCalledWith(
221-
"thread/unsubscribe",
222-
{ threadId: "thread-1" },
223-
{ timeoutMs: 5_000 },
224-
);
225-
expect(requests.map((entry) => entry.method)).toEqual([
226-
"thread/start",
227-
"turn/start",
228-
"thread/unsubscribe",
229-
]);
220+
const firstBinding = await readCodexAppServerBinding(sessionFile);
221+
expect({
222+
clientId: firstBinding?.clientId,
223+
threadId: firstBinding?.threadId,
224+
preserveNativeModel: firstBinding?.preserveNativeModel,
225+
connectionScope: firstBinding?.connectionScope,
226+
ringZeroConfigFingerprint: firstBinding?.ringZeroConfigFingerprint,
227+
contextEngine: firstBinding?.contextEngine,
228+
pluginAppsFingerprint: firstBinding?.pluginAppsFingerprint,
229+
}).toEqual({
230+
clientId: "test-client-1",
231+
threadId: "thread-1",
232+
preserveNativeModel: undefined,
233+
connectionScope: undefined,
234+
ringZeroConfigFingerprint: undefined,
235+
contextEngine: undefined,
236+
pluginAppsFingerprint: expect.any(String),
237+
});
238+
239+
expect(requests.map((entry) => entry.method)).toEqual(["thread/start", "turn/start"]);
230240
});
231241

232242
it("keeps an incognito thread subscribed for live in-process reuse", async () => {

‎extensions/codex/src/app-server/run-attempt.context-engine.test.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
import { MESSAGE_TOOL_DELIVERY_HINTS } from "openclaw/plugin-sdk/message-tool-delivery-hints";
1919
import { createMockPluginRegistry } from "openclaw/plugin-sdk/plugin-test-runtime";
2020
import { registerSandboxBackend } from "openclaw/plugin-sdk/sandbox";
21+
import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
2122
import { formatSqliteSessionFileMarker } from "openclaw/plugin-sdk/sqlite-runtime-testing";
2223
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2324
import { readAttemptTerminal } from "./attempt-terminal.test-helper.js";
@@ -123,7 +124,10 @@ function createParams(sessionFile: string, workspaceDir: string): EmbeddedRunAtt
123124
} as EmbeddedRunAttemptParams;
124125
}
125126

126-
function createSqliteParams(workspaceDir: string, storeName: string): EmbeddedRunAttemptParams {
127+
async function createSqliteParams(
128+
workspaceDir: string,
129+
storeName: string,
130+
): Promise<EmbeddedRunAttemptParams> {
127131
const sessionId = "session-1";
128132
const sessionKey = "agent:main:session-1";
129133
const storePath = path.join(tempDir, `${storeName}.sqlite`);
@@ -133,6 +137,12 @@ function createSqliteParams(workspaceDir: string, storeName: string): EmbeddedRu
133137
storePath,
134138
});
135139
const params = createParams(sessionFile, workspaceDir);
140+
await upsertSessionEntry({
141+
agentId: "main",
142+
sessionKey,
143+
storePath,
144+
entry: { sessionFile, sessionId, updatedAt: Date.now() },
145+
});
136146
params.sessionTarget = {
137147
agentId: "main",
138148
sessionId,
@@ -1981,7 +1991,7 @@ describe("runCodexAppServerAttempt context-engine lifecycle", () => {
19811991
const maintain = vi.fn(async () => ({ changed: false, bytesFreed: 0, rewrittenEntries: 0 }));
19821992
const contextEngine = createContextEngine({ afterTurn, maintain, bootstrap: undefined });
19831993
const harness = createStartedThreadHarness();
1984-
const params = createSqliteParams(
1994+
const params = await createSqliteParams(
19851995
workspaceDir,
19861996
`heartbeat-${testCase.bootstrapContextRunKind}`,
19871997
);
@@ -2113,7 +2123,7 @@ describe("runCodexAppServerAttempt context-engine lifecycle", () => {
21132123
bootstrap: undefined,
21142124
});
21152125
const harness = createStartedThreadHarness();
2116-
const params = createSqliteParams(workspaceDir, "prompt-failure");
2126+
const params = await createSqliteParams(workspaceDir, "prompt-failure");
21172127
params.contextEngine = contextEngine;
21182128

21192129
const run = runCodexAppServerAttempt(params);

0 commit comments

Comments
 (0)