Skip to content

Commit c642c4b

Browse files
fix(server): settling a Codex thread stops its MCP servers right away (pingdotgg#33767)
1 parent 04be2b3 commit c642c4b

4 files changed

Lines changed: 151 additions & 12 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3265,6 +3265,109 @@ describe("CodexAdapterV2 post-settle continuation", () => {
32653265
),
32663266
);
32673267

3268+
// regression: #33747 Codex refuses thread/resume until an unsubscribed thread finishes closing
3269+
it.effect.each([
3270+
{ name: "waits for thread/closed after a closing error", closedFirst: false },
3271+
{ name: "retries at once when the thread already closed", closedFirst: true },
3272+
])("$name", ({ name, closedFirst }) =>
3273+
Effect.scoped(
3274+
Effect.gen(function* () {
3275+
const nativeThreadId = "closing-thread";
3276+
const params = {
3277+
threadId: nativeThreadId,
3278+
excludeTurns: true,
3279+
cwd: CODEX_TEST_RUNTIME_POLICY.cwd,
3280+
model: CODEX_TEST_MODEL_SELECTION.model,
3281+
config: CodexAdapterV2.CODEX_THREAD_CONFIG,
3282+
};
3283+
const closed: CodexReplay.CodexAppServerReplayEntry = {
3284+
type: "emit_inbound",
3285+
label: "thread closed",
3286+
frame: { method: "thread/closed", params: { threadId: nativeThreadId } },
3287+
};
3288+
const closingError: CodexReplay.CodexAppServerReplayEntry = {
3289+
type: "emit_inbound",
3290+
label: "resume closing error",
3291+
frame: {
3292+
id: 4,
3293+
error: {
3294+
code: -32600,
3295+
message: `thread ${nativeThreadId} is closing; retry thread/resume after the thread is closed`,
3296+
},
3297+
},
3298+
};
3299+
const harness = yield* makeCodexReplayHarness(
3300+
makeCodexReplayTranscript({
3301+
scenario: name,
3302+
entries: [
3303+
...codexReplayPreamble({
3304+
nativeThreadId,
3305+
nativeTurnId: "unused-turn",
3306+
prompt: "unused-prompt",
3307+
}).slice(0, 5),
3308+
{
3309+
type: "expect_outbound",
3310+
label: "unsubscribe",
3311+
frame: {
3312+
id: 3,
3313+
method: "thread/unsubscribe",
3314+
params: { threadId: nativeThreadId },
3315+
},
3316+
},
3317+
{
3318+
type: "emit_inbound",
3319+
label: "unsubscribe result",
3320+
frame: { id: 3, result: { status: "unsubscribed" } },
3321+
},
3322+
{
3323+
type: "expect_outbound",
3324+
label: "resume closing thread",
3325+
frame: { id: 4, method: "thread/resume", params },
3326+
},
3327+
...(closedFirst ? [closed, closingError] : [closingError, closed]),
3328+
{
3329+
type: "expect_outbound",
3330+
label: "retry identical resume",
3331+
frame: { id: 5, method: "thread/resume", params },
3332+
},
3333+
{
3334+
type: "emit_inbound",
3335+
label: "retry result",
3336+
frame: {
3337+
id: 5,
3338+
result: {
3339+
thread: {
3340+
id: nativeThreadId,
3341+
updatedAt: 1782622450,
3342+
turns: [{ type: "unknown-history-item" }],
3343+
},
3344+
},
3345+
},
3346+
},
3347+
],
3348+
}),
3349+
);
3350+
yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread });
3351+
const resumed = yield* harness.runtime.resumeThread({
3352+
providerThread: harness.providerThread,
3353+
modelSelection: CODEX_TEST_MODEL_SELECTION,
3354+
runtimePolicy: CODEX_TEST_RUNTIME_POLICY,
3355+
});
3356+
assert.equal(resumed.nativeThreadRef?.nativeId, nativeThreadId);
3357+
assert.equal(resumed.status, "idle");
3358+
}).pipe(
3359+
Effect.provide(
3360+
Layer.mergeAll(
3361+
IdAllocator.layer,
3362+
McpProviderSessions.layer,
3363+
NodeServices.layer,
3364+
NodeCrypto.layer,
3365+
),
3366+
),
3367+
),
3368+
),
3369+
);
3370+
32683371
it.effect.each([
32693372
"recover",
32703373
"completion-only",

‎apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts‎

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1962,6 +1962,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
19621962
const pendingRuntimeRequests = yield* Ref.make(
19631963
new Map<string, PendingCodexRuntimeRequest>(),
19641964
);
1965+
/** Completed by thread/closed after this connection unsubscribes from the native thread. */
1966+
const threadClosings = new Map<string, Deferred.Deferred<void>>();
19651967
/** Codex acceptForSession covers only the exact command or patch, not future commands. */
19661968
const sessionApprovals = new Map<
19671969
string,
@@ -4998,6 +5000,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
49985000
// their command items, while the shared provider session stays alive.
49995001
yield* client.handleServerNotification("thread/closed", (payload) =>
50005002
Effect.gen(function* () {
5003+
const closing = threadClosings.get(payload.threadId);
5004+
threadClosings.delete(payload.threadId);
5005+
if (closing !== undefined) yield* Deferred.succeed(closing, undefined);
50015006
const completedAt = yield* DateTime.now;
50025007
for (const context of (yield* Ref.get(settledTurns)).values()) {
50035008
if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue;
@@ -7078,20 +7083,31 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
70787083
);
70797084
});
70807085

7081-
// Codex refuses to resume a session archived elsewhere until it is unarchived.
7086+
// Codex refuses to resume a session archived elsewhere until it is unarchived, and
7087+
// one it is still unloading after thread/unsubscribe until it emits thread/closed.
70827088
const resumeNativeThread = Effect.fn("CodexAdapterV2.resumeNativeThread")(function* (
70837089
threadId: string,
70847090
params: Record<string, unknown>,
70857091
) {
70867092
const resume = client.raw.request("thread/resume", { threadId, ...params });
70877093
return yield* resume.pipe(
70887094
Effect.catchTags({
7089-
CodexAppServerRequestError: (cause) =>
7090-
/\bsession \S+ is archived\b|\bcodex unarchive\b/i.test(cause.errorMessage)
7091-
? client.raw
7092-
.request("thread/unarchive", { threadId })
7093-
.pipe(Effect.andThen(resume))
7094-
: Effect.fail(cause),
7095+
CodexAppServerRequestError: (cause) => {
7096+
if (/\bsession \S+ is archived\b|\bcodex unarchive\b/i.test(cause.errorMessage)) {
7097+
return client.raw
7098+
.request("thread/unarchive", { threadId })
7099+
.pipe(Effect.andThen(resume));
7100+
}
7101+
if (/\bthread \S+ is closing\b/i.test(cause.errorMessage)) {
7102+
const closing = threadClosings.get(threadId);
7103+
return (
7104+
closing === undefined
7105+
? Effect.void
7106+
: Deferred.await(closing).pipe(Effect.timeoutOption("10 seconds"))
7107+
).pipe(Effect.andThen(resume));
7108+
}
7109+
return Effect.fail(cause);
7110+
},
70957111
}),
70967112
);
70977113
});
@@ -7634,6 +7650,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
76347650
function* (unloadInput) {
76357651
const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread);
76367652
sessionApprovals.delete(nativeThreadId);
7653+
// A resume may already wait on the pending entry; replacing it would strand that wait.
7654+
if (!threadClosings.has(nativeThreadId)) {
7655+
threadClosings.set(nativeThreadId, yield* Deferred.make<void>());
7656+
}
76377657
yield* client.request("thread/unsubscribe", { threadId: nativeThreadId });
76387658
},
76397659
(effect, unloadInput) =>

‎apps/server/src/provider/codexLaunchArgs.test.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,24 @@ import {
99
} from "./codexLaunchArgs.ts";
1010

1111
describe("codexAppServerArgs", () => {
12-
it("preserves escaped TOML quotes in config values", () => {
13-
NodeAssert.deepStrictEqual(
14-
codexAppServerArgs(String.raw`--config model=\"gpt-6.1-sol\" --strict-config`),
15-
["app-server", "--config", 'model="gpt-6.1-sol"', "--strict-config"],
16-
);
12+
it.each([
13+
{
14+
name: "preserves escaped TOML quotes in config values",
15+
launchArgs: String.raw`--config model=\"gpt-6.1-sol\" --strict-config`,
16+
expected: ["--config", 'model="gpt-6.1-sol"', "--strict-config"],
17+
},
18+
{
19+
name: "lets launch args override the unload delay",
20+
launchArgs: "-c thread_unload_delay_secs=1800",
21+
expected: ["-c", "thread_unload_delay_secs=1800"],
22+
},
23+
])("asks Codex to unload unsubscribed threads immediately and $name", (row) => {
24+
NodeAssert.deepStrictEqual(codexAppServerArgs(row.launchArgs), [
25+
"app-server",
26+
"-c",
27+
"thread_unload_delay_secs=0",
28+
...row.expected,
29+
]);
1730
});
1831
});
1932

‎apps/server/src/provider/codexLaunchArgs.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,11 @@ export const resolveCodexLaunchArgs = (
99

1010
const codexLaunchArgv = (launchArgs?: string): ReadonlyArray<string> => tokenizeCliArgs(launchArgs);
1111

12+
// T3 unsubscribes only when it unloads a thread; Codex's own unload delay would stack on that.
1213
export const codexAppServerArgs = (launchArgs?: string) => [
1314
"app-server",
15+
"-c",
16+
"thread_unload_delay_secs=0",
1417
...codexLaunchArgv(launchArgs),
1518
];
1619

0 commit comments

Comments
 (0)