From c343e61823a2728a74f02e8c80055ebfa751e209 Mon Sep 17 00:00:00 2001 From: Dominic R Date: Wed, 7 Oct 2026 22:00:26 -0400 Subject: [PATCH 1/5] server/codex: recover Codex threads when the app-server exits When the shared Codex app-server exited, nothing noticed. The protocol only saw the end of the connection when its read loop reached end of input, and notification handlers run inside that loop, so a handler that never returned hid the exit. Even when the end of input was seen, CodexAdapterV2 ignored it and kept the dead session for every Codex thread until it had been idle for 30 minutes. The child-process client now also watches the process exit. After the exit, the read loop gets five seconds to reach end of input on its own, so output written before the exit is still handled; past that, the protocol terminates with the exit error and fails pending requests. The client exposes `terminated`, and the adapter fails its event stream when it completes, so the session manager releases the session and the next turn starts a new app-server. --- ...OrchestratorMcpToolkit.integration.test.ts | 11 +++- .../Adapters/CodexAdapterV2.test.ts | 22 +++++++ .../Adapters/CodexAdapterV2.ts | 21 ++++++- .../effect-codex-app-server/src/client.ts | 21 ++++++- .../src/protocol.test.ts | 58 +++++++++++++++++++ .../effect-codex-app-server/src/protocol.ts | 28 ++++++++- .../effect-codex-app-server/src/replay.ts | 2 +- 7 files changed, 153 insertions(+), 10 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 0b3d1b0e18cf2..90da30699090e 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -3809,9 +3809,14 @@ describe("orchestrator MCP toolkit", () => { Effect.gen(function* () { const cwd = yield* checkpointWorkspace("delegated-task-status"); const rawTranscript = yield* readDelegatedTaskStatusTranscript(); - const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript( - materializeReplayTranscriptWorkspace(rawTranscript, cwd), - ); + const workspaceTranscript = materializeReplayTranscriptWorkspace(rawTranscript, cwd); + // The recorder stopped Codex after its last frame, but this test keeps + // the parent turn running past the recording. Replaying that exit would + // end the session and fail the parent run. + const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript({ + ...workspaceTranscript, + entries: workspaceTranscript.entries.filter((entry) => entry.type !== "runtime_exit"), + }); const layerOrchestrator = ProviderReplayHarness.layerProviderReplay( { name: "delegated-task-status/codex", diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 9a1c8f6c900f0..9dbc6255f0953 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1763,12 +1763,34 @@ describe("CodexAdapterV2 session initialize", () => { runtimePolicy: CODEX_TEST_RUNTIME_POLICY, }), initializeRequests: () => initializeRequests, + events: runtime.events, }; }); const replayPreamble = (nativeThreadId: string) => codexReplayPreamble({ nativeThreadId, nativeTurnId: "unused", prompt: "unused" }); + it.effect("fails the event stream when the app-server exits", () => + Effect.gen(function* () { + const session = yield* openReplaySession( + makeCodexReplayTranscript({ + scenario: "app-server-exit", + entries: [{ type: "runtime_exit", status: "success" }], + }), + ); + + const error = yield* session.events.pipe(Stream.runDrain, Effect.flip); + + assert.instanceOf(error, ProviderAdapter.ProviderAdapterEventStreamError); + assert.instanceOf(error.cause, CodexError.CodexAppServerProcessExitedError); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + it.effect("sends one initialize when two threads start on a fresh session at once", () => Effect.gen(function* () { const initializeAwaitingResponse = yield* Deferred.make(); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index d8ef1461ef73c..ee70b49f1cc98 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1806,7 +1806,26 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( model: input.modelSelection.model, now, }); - const events = yield* Queue.unbounded(); + const events = yield* Queue.unbounded< + ProviderAdapter.ProviderAdapterV2Event, + ProviderAdapter.ProviderAdapterEventStreamError + >(); + // Every thread on this session shares the app-server. Once its + // connection ends, fail the stream so the session manager releases the + // session and the next turn starts a new app-server. + yield* client.terminated.pipe( + Effect.flatMap((cause) => + Queue.fail( + events, + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ), + Effect.forkIn(scope), + ); const rateLimitSnapshot = yield* Ref.make(undefined); const limitedTurnItems = yield* Ref.make( new Map>(), diff --git a/packages/effect-codex-app-server/src/client.ts b/packages/effect-codex-app-server/src/client.ts index e7c5f50b57045..97c8170669ba7 100644 --- a/packages/effect-codex-app-server/src/client.ts +++ b/packages/effect-codex-app-server/src/client.ts @@ -40,6 +40,8 @@ export class CodexAppServerClient extends Context.Service< CodexAppServerClient, { readonly raw: CodexAppServerClientRaw; + /** Completes with the error that ended the connection to the app-server. */ + readonly terminated: Effect.Effect; readonly request: ( method: M, payload: CodexRpc.ClientRequestParamsByMethod[M], @@ -94,10 +96,17 @@ const V2TurnStartParamsWithCollaborationMode = CodexSchema.V2TurnStartParams.pip }), ); +export interface CodexAppServerTermination { + /** Classifies the end of input. */ + readonly terminationError?: Effect.Effect; + /** Completes when the app-server process exits. */ + readonly processExit?: Effect.Effect; +} + export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make")(function* ( stdio: Stdio.Stdio, options: CodexAppServerClientOptions = {}, - terminationError?: Effect.Effect, + termination: CodexAppServerTermination = {}, ): Effect.fn.Return { const requestHandlers = new Map(); const notificationHandlers = new Map>(); @@ -197,7 +206,7 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio, - ...(terminationError ? { terminationError } : {}), + ...termination, ...(options.logIncoming !== undefined ? { logIncoming: options.logIncoming } : {}), ...(options.logOutgoing !== undefined ? { logOutgoing: options.logOutgoing } : {}), ...(options.logger ? { logger: options.logger } : {}), @@ -238,6 +247,7 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make respond: transport.respond, respondError: transport.respondError, }, + terminated: transport.terminated, request, notify, handleServerRequest: (method, handler) => @@ -271,5 +281,10 @@ const makeChildProcessClient = Effect.fn( "effect-codex-app-server/CodexAppServerClient.makeChildProcessClient", )(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) { yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped); - return yield* make(makeChildStdio(handle), options, makeTerminationError(handle)); + // Reaching the end of input and the process exiting both report the exit. + const exited = makeTerminationError(handle); + return yield* make(makeChildStdio(handle), options, { + terminationError: exited, + processExit: exited, + }); }); diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts index 7249afff10713..90877fb8b245c 100644 --- a/packages/effect-codex-app-server/src/protocol.test.ts +++ b/packages/effect-codex-app-server/src/protocol.test.ts @@ -5,6 +5,7 @@ import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Stdio from "effect/Stdio"; import * as Stream from "effect/Stream"; +import { TestClock } from "effect/testing"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -787,6 +788,63 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => { }), ); + it.effect("terminates on process exit while a notification handler holds the reader", () => + Effect.gen(function* () { + const { stdio, input } = yield* makeInMemoryStdio(); + const exited = yield* Deferred.make(); + const handlerStarted = yield* Deferred.make(); + const termination = yield* Deferred.make(); + const protocol = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ + stdio, + processExit: Deferred.await(exited), + onNotification: () => + Deferred.succeed(handlerStarted, undefined).pipe(Effect.andThen(Effect.never)), + onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid), + }); + + const pending = yield* protocol + .request("thread/read", {}) + .pipe(Effect.flip, Effect.orDie, Effect.forkChild); + yield* Queue.offer(input, encodeJsonl({ method: "item/agentMessage/delta", params: {} })); + yield* Deferred.await(handlerStarted); + const exitError = new CodexError.CodexAppServerProcessExitedError({ code: 137 }); + yield* Deferred.succeed(exited, exitError); + yield* TestClock.adjust(CodexProtocol.PROCESS_EXIT_INPUT_GRACE); + + assert.strictEqual(yield* Deferred.await(termination), exitError); + assert.strictEqual(yield* Fiber.join(pending), exitError); + assert.strictEqual(yield* protocol.terminated, exitError); + }), + ); + + it.effect("handles output the process wrote before it exited", () => + Effect.gen(function* () { + const { stdio, input } = yield* makeInMemoryStdio(); + const exited = yield* Deferred.make(); + const notifications: Array = []; + const termination = yield* Deferred.make(); + const inputEnded = new CodexError.CodexAppServerProcessExitedError({ code: 0 }); + yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ + stdio, + processExit: Deferred.await(exited), + terminationError: Effect.succeed(inputEnded), + onNotification: (notification) => + Effect.sync(() => { + notifications.push(notification.method); + }), + onTermination: (error) => Deferred.succeed(termination, error).pipe(Effect.asVoid), + }); + + // Node can report the exit before the pipe delivers the last output. + yield* Deferred.succeed(exited, new CodexError.CodexAppServerProcessExitedError({ code: 1 })); + yield* Queue.offer(input, encodeJsonl({ method: "turn/completed", params: {} })); + yield* Queue.end(input); + + assert.strictEqual(yield* Deferred.await(termination), inputEnded); + assert.deepEqual(notifications, ["turn/completed"]); + }), + ); + it.effect("classifies an input stream ending without inventing a cause", () => Effect.gen(function* () { const { stdio, input } = yield* makeInMemoryStdio(); diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts index 4a32973a988bd..268ca639c02e0 100644 --- a/packages/effect-codex-app-server/src/protocol.ts +++ b/packages/effect-codex-app-server/src/protocol.ts @@ -1,5 +1,6 @@ import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; @@ -17,6 +18,13 @@ const isJsonRpcResponseEnvelope = Schema.is(JsonRpcResponseEnvelope); const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError); const MAX_BUFFERED_RAW_MESSAGES = 32; +/** + * How long input may keep arriving after the process exits. The pipe can + * still hold output the process wrote before it exited; past this, a reader + * that has not reached the end of input is stuck and the exit ends the session. + */ +export const PROCESS_EXIT_INPUT_GRACE = Duration.seconds(5); + export interface CodexAppServerProtocolLogEvent { readonly direction: "incoming" | "outgoing"; readonly stage: "raw" | "decoded" | "decode_failed"; @@ -37,6 +45,11 @@ export interface CodexAppServerIncomingRequest { export interface CodexAppServerPatchedProtocolOptions { readonly stdio: Stdio.Stdio; readonly terminationError?: Effect.Effect; + /** + * Completes when the peer process exits. The protocol then terminates even + * if a message handler never returns and the input never reaches its end. + */ + readonly processExit?: Effect.Effect; readonly logIncoming?: boolean; readonly logOutgoing?: boolean; readonly logger?: (event: CodexAppServerProtocolLogEvent) => Effect.Effect; @@ -52,6 +65,8 @@ export interface CodexAppServerPatchedProtocolOptions { export interface CodexAppServerPatchedProtocol { readonly incomingNotifications: Stream.Stream; readonly incomingRequests: Stream.Stream; + /** Completes with the error that ended the connection. */ + readonly terminated: Effect.Effect; readonly request: ( method: string, payload?: unknown, @@ -167,7 +182,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa const remainder: Array = []; const terminationHandled = yield* Ref.make(false); const terminationFailure = yield* Ref.make(Option.none()); - const terminationSignal = yield* Deferred.make(); + const terminationSignal = yield* Deferred.make(); const activeRequestHandlers = yield* Ref.make(0); const logProtocol = (event: CodexAppServerProtocolLogEvent) => { @@ -204,7 +219,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa yield* Ref.set(terminationFailure, Option.some(error)); yield* failAllPending(error); yield* Queue.end(outgoing); - yield* Deferred.succeed(terminationSignal, undefined); + yield* Deferred.succeed(terminationSignal, error); yield* Scope.close(requestHandlerScope, Exit.void).pipe( Effect.forkIn(protocolScope, { startImmediately: true }), Effect.asVoid, @@ -445,6 +460,14 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa Effect.forkScoped, ); + if (options.processExit !== undefined) { + yield* options.processExit.pipe( + Effect.tap(() => Effect.sleep(PROCESS_EXIT_INPUT_GRACE)), + Effect.flatMap((error) => handleTermination(() => Effect.succeed(error))), + Effect.forkScoped, + ); + } + yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); const request = (method: string, payload?: unknown) => @@ -476,6 +499,7 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa return { incomingNotifications: Stream.fromQueue(incomingNotifications), incomingRequests: Stream.fromQueue(incomingRequests), + terminated: Deferred.await(terminationSignal), request, notify, respond, diff --git a/packages/effect-codex-app-server/src/replay.ts b/packages/effect-codex-app-server/src/replay.ts index 1c98c7bc3b8ad..e8d1b06916ccd 100644 --- a/packages/effect-codex-app-server/src/replay.ts +++ b/packages/effect-codex-app-server/src/replay.ts @@ -559,5 +559,5 @@ const makeReplayClientWithState = Effect.fn( yield* drainInbound(); - return yield* CodexClient.make(stdio, options, terminationError); + return yield* CodexClient.make(stdio, options, { terminationError }); }); From 0570cf776a62265f2495dd66bebbdc1faab3df8d Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 12 Oct 2026 20:00:43 -0400 Subject: [PATCH 2/5] server/codex: cover the child-process exit wiring The protocol tests pass the process exit in directly, so nothing covered the child-process client actually wiring it up. A fake child whose output never closes now proves a pending request fails once the process exits. The exit grace stays private to the protocol, its comment says that input still unhandled after it is dropped, and the MCP replay test only drops the recorder's trailing exit. --- ...OrchestratorMcpToolkit.integration.test.ts | 6 ++- .../src/client.test.ts | 40 +++++++++++++++++++ .../src/protocol.test.ts | 2 +- .../effect-codex-app-server/src/protocol.ts | 9 +++-- 4 files changed, 51 insertions(+), 6 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 90da30699090e..3cd560e66031e 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -3813,9 +3813,13 @@ describe("orchestrator MCP toolkit", () => { // The recorder stopped Codex after its last frame, but this test keeps // the parent turn running past the recording. Replaying that exit would // end the session and fail the parent run. + const lastEntry = workspaceTranscript.entries.at(-1); const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript({ ...workspaceTranscript, - entries: workspaceTranscript.entries.filter((entry) => entry.type !== "runtime_exit"), + entries: + lastEntry?.type === "runtime_exit" + ? workspaceTranscript.entries.slice(0, -1) + : workspaceTranscript.entries, }); const layerOrchestrator = ProviderReplayHarness.layerProviderReplay( { diff --git a/packages/effect-codex-app-server/src/client.test.ts b/packages/effect-codex-app-server/src/client.test.ts index 842f15c0e912c..19c6354c9841d 100644 --- a/packages/effect-codex-app-server/src/client.test.ts +++ b/packages/effect-codex-app-server/src/client.test.ts @@ -1,15 +1,21 @@ +import * as Deferred from "effect/Deferred"; import * as Exit from "effect/Exit"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as Effect from "effect/Effect"; import * as Ref from "effect/Ref"; import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; +import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { TestClock } from "effect/testing"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as CodexClient from "./client.ts"; +import * as CodexError from "./errors.ts"; const mockPeerPath = Effect.map(Effect.service(Path.Path), (path) => path.join(import.meta.dirname, "../test/fixtures/codex-app-server-mock-peer.ts"), @@ -155,4 +161,38 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => { assert.equal(initialized.userAgent, "mock-codex-app-server"); }), ); + + it.effect("ends the connection when the process exits but its output never closes", () => + Effect.gen(function* () { + const exitCode = yield* Deferred.make(); + const handle = ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(61), + exitCode: Deferred.await(exitCode), + isRunning: Effect.map(Deferred.isDone(exitCode), (done) => !done), + kill: () => Effect.void, + stdin: Sink.drain, + stdout: Stream.never, + stderr: Stream.empty, + all: Stream.never, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }); + const context = yield* Layer.build(CodexClient.layerChildProcess(handle)); + const client = yield* Effect.service(CodexClient.CodexAppServerClient).pipe( + Effect.provide(context), + ); + + const pending = yield* client.raw + .request("account/read", {}) + .pipe(Effect.flip, Effect.orDie, Effect.forkChild); + yield* Deferred.succeed(exitCode, ChildProcessSpawner.ExitCode(1)); + yield* TestClock.adjust("5 seconds"); + + const error = yield* Fiber.join(pending); + assert.instanceOf(error, CodexError.CodexAppServerProcessExitedError); + assert.equal(error.code, 1); + assert.strictEqual(yield* client.terminated, error); + }).pipe(Effect.scoped), + ); }); diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts index 90877fb8b245c..85de3d0aa87db 100644 --- a/packages/effect-codex-app-server/src/protocol.test.ts +++ b/packages/effect-codex-app-server/src/protocol.test.ts @@ -809,7 +809,7 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => { yield* Deferred.await(handlerStarted); const exitError = new CodexError.CodexAppServerProcessExitedError({ code: 137 }); yield* Deferred.succeed(exited, exitError); - yield* TestClock.adjust(CodexProtocol.PROCESS_EXIT_INPUT_GRACE); + yield* TestClock.adjust("5 seconds"); assert.strictEqual(yield* Deferred.await(termination), exitError); assert.strictEqual(yield* Fiber.join(pending), exitError); diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts index 268ca639c02e0..31676add63a8f 100644 --- a/packages/effect-codex-app-server/src/protocol.ts +++ b/packages/effect-codex-app-server/src/protocol.ts @@ -19,11 +19,12 @@ const isCodexAppServerError = Schema.is(CodexError.CodexAppServerError); const MAX_BUFFERED_RAW_MESSAGES = 32; /** - * How long input may keep arriving after the process exits. The pipe can - * still hold output the process wrote before it exited; past this, a reader - * that has not reached the end of input is stuck and the exit ends the session. + * How long the reader may keep handling input after the process exits. The + * pipe can still hold output written before the exit. Past this, the exit ends + * the connection and any input not yet handled is dropped, so a reader that is + * stuck in a handler cannot hold the connection open forever. */ -export const PROCESS_EXIT_INPUT_GRACE = Duration.seconds(5); +const PROCESS_EXIT_INPUT_GRACE = Duration.seconds(5); export interface CodexAppServerProtocolLogEvent { readonly direction: "incoming" | "outgoing"; From 9725ac781347cad6558af4bad23c87d45d815824 Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 12 Oct 2026 20:01:10 -0400 Subject: [PATCH 3/5] server/orchestration-v2: keep a replacement session's status on release A thread of a shared runtime can reopen a session under the same id while the failed one is still closing. The old release then wrote its failure after the replacement's own status, even when the replacement had already opened and closed in the meantime. The manager now remembers the latest runtime opened under each id until its release is recorded, and only that runtime writes the release status. The check and the write run under the open lock, so no replacement can open between them. Co-authored-by: Dara Adedeji --- .../ProviderSessionManager.test.ts | 148 +++++++++++++++++- .../ProviderSessionManager.ts | 48 +++++- 2 files changed, 185 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index ceb230b008940..78c60ed3801fb 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -318,7 +318,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( }) => Effect.Effect; readonly hasPendingBackgroundWork?: Effect.Effect; readonly hasPendingBackgroundWorkForThread?: Effect.Effect; - readonly hangSessionScopeClose?: boolean; + /** "first" wedges only the first session opened. */ + readonly hangSessionScopeClose?: boolean | "first"; readonly startTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; /** Registers the process's closeCount finalizer before `beforeOpen` runs. */ @@ -383,7 +384,11 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( }); if (options.spawnBeforeOpen !== true) { yield* countClose; - if (options.hangSessionScopeClose === true) yield* hangClose; + if ( + options.hangSessionScopeClose === true || + (options.hangSessionScopeClose === "first" && (yield* Ref.get(state)).openCount === 1) + ) + yield* hangClose; } return { @@ -465,7 +470,7 @@ function layerTest(input: { }; readonly hasPendingBackgroundWork?: Effect.Effect; readonly hasPendingBackgroundWorkForThread?: Effect.Effect; - readonly hangSessionScopeClose?: boolean; + readonly hangSessionScopeClose?: boolean | "first"; readonly startTurn?: Effect.Effect; readonly beforeUnload?: Effect.Effect; readonly spawnBeforeOpen?: boolean; @@ -3531,6 +3536,143 @@ it.effect("ProviderSessionManagerV2 release retries leave a replacement session }), ); +it.effect( + "ProviderSessionManagerV2 leaves a replacement's status to it when a failed release ends", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const scopeCloseReached = yield* Deferred.make(); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread-provider-session-manager-failed-replacement"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const now = yield* DateTime.now; + // The release settles this request right after recording the session. + const request = yield* makePendingRuntimeRequestEvents({ + idAllocator, + threadId, + providerSessionId, + providerThread: makeProviderThread({ idAllocator, threadId, providerSessionId, now }), + now, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + ...request.events, + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + + // The runtime's events end unexpectedly, and its release stalls in scope close. + const events = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(events); + yield* Queue.end(events!); + yield* Deferred.await(scopeCloseReached); + + // Another thread on the same runtime reopens it meanwhile; then the + // time-boxed close lets the release write its records. + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + const settled = yield* eventSink + .stream({ + threadId, + afterSequence: yield* eventSink.latestSequence({ threadId }), + eventType: "runtime-request.updated", + }) + .pipe(Stream.runHead, Effect.forkScoped); + yield* TestClock.adjust("30 seconds"); + yield* Fiber.join(settled); + const status = (yield* projectionStore.getThreadProjection(threadId)).providerSessions.at( + -1, + )?.status; + + // The replacement's close hangs as well; release it while the clock can move. + const stopping = yield* manager.shutdown.pipe(Effect.forkChild); + yield* TestClock.adjust("30 seconds"); + yield* Fiber.join(stopping); + + assert.isDefined(status); + assert.notEqual(status, "error"); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 60_000, + hangSessionScopeClose: true, + scopeCloseReached, + }), + ), + ); + }), +); + +it.effect("ProviderSessionManagerV2 leaves a closed replacement's status to it", () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const scopeCloseReached = yield* Deferred.make(); + yield* Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const threadId = ThreadId.make("thread-provider-session-manager-closed-replacement"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now: yield* DateTime.now }), + ], + }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + + // The first runtime's events end unexpectedly, and its release stalls in scope close. + const events = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(events); + yield* Queue.end(events!); + yield* Deferred.await(scopeCloseReached); + + // A replacement opens and closes meanwhile. + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + yield* manager.close(providerSessionId); + const statuses = yield* eventSink + .stream({ threadId, afterSequence: yield* eventSink.latestSequence({ threadId }) }) + .pipe( + Stream.filter( + ({ event }) => + event.type === "provider-session.updated" || + event.type === "provider-session.attached", + ), + Stream.takeUntil(({ event }) => event.type === "provider-session.attached"), + Stream.map(({ event }) => event.type), + Stream.runCollect, + Effect.forkScoped, + ); + + // The stalled close ends; the next open waits on the open lock until the + // first release has written its records. + yield* TestClock.adjust("30 seconds"); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + + assert.deepEqual(Array.from(yield* Fiber.join(statuses)), ["provider-session.attached"]); + }).pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 60_000, + hangSessionScopeClose: "first", + scopeCloseReached, + }), + ), + ); + }), +); + it.effect("ProviderSessionManagerV2 keeps each failed release's cleanup", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index f0ec5282ef5b5..02c2380074637 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -419,6 +419,10 @@ export const layerWithOptions = ( }), ); const sessions = yield* Ref.make(new Map()); + // The latest session opened under each id, kept until its release records it. + const latestOpened = yield* Ref.make( + new Map(), + ); // One retry per released entry, so a later release with the same id // cannot drop cleanup for threads only the earlier session served. const releaseRecordRetries = yield* FiberSet.make(); @@ -799,6 +803,27 @@ export const layerWithOptions = ( { concurrency: 1 }, ).pipe(Effect.flatMap(Exit.asVoidAll)); + // A replacement under the same id, like the next thread of a shared + // runtime, owns the session's status from its open on, even after it + // closes. Only the latest session opened under an id writes its release + // status; the entry is dropped once that is written. Callers hold the + // open lock, so no replacement opens mid-write. + const writeOwnReleaseRecords = ( + input: Omit[0], "replaced">, + ) => + Effect.gen(function* () { + const key = sessionKey(input.entry.runtime.providerSessionId); + const replaced = (yield* Ref.get(latestOpened)).get(key) !== input.entry.runtime; + yield* writeReleaseRecords({ ...input, replaced }); + if (replaced) return; + yield* Ref.update(latestOpened, (current) => { + if (current.get(key) !== input.entry.runtime) return current; + const updated = new Map(current); + updated.delete(key); + return updated; + }); + }); + // The session already left the live map, so a later release finds // nothing to do. Without a retry the UI would keep a ready session and // answerable approvals until a server restart. Each attempt holds the @@ -809,13 +834,7 @@ export const layerWithOptions = ( const providerSessionId = input.entry.runtime.providerSessionId; const attempt = Effect.gen(function* () { const exit = yield* Effect.exit( - sessionOpen.withLock( - providerSessionId, - Effect.gen(function* () { - const replaced = (yield* Ref.get(sessions)).has(sessionKey(providerSessionId)); - yield* writeReleaseRecords({ ...input, replaced }); - }), - ), + sessionOpen.withLock(providerSessionId, writeOwnReleaseRecords(input)), ); if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return yield* exit; yield* Effect.logWarning("orchestration-v2.provider-session-release-records-failed", { @@ -940,6 +959,8 @@ export const layerWithOptions = ( readonly cancelIdleFiber?: boolean; readonly onlyIfIdleGeneration?: number; readonly gracefulSubscribers?: boolean; + /** Set by callers inside `open`, which already hold this session's open lock. */ + readonly openLockHeld?: boolean; }) => Effect.acquireUseRelease( removeLiveEntry(input), @@ -971,8 +992,16 @@ export const layerWithOptions = ( ...(input.detail === undefined ? {} : { detail: input.detail }), releasedAt, }; + // A thread of a shared runtime can reopen it under the same + // id while this closes; the open lock orders that against + // this write. const recorded = yield* Effect.exit( - writeReleaseRecords({ ...records, replaced: false }), + input.openLockHeld === true + ? writeOwnReleaseRecords(records) + : sessionOpen.withLock( + input.providerSessionId, + writeOwnReleaseRecords(records), + ), ); if (Exit.isFailure(recorded)) { yield* retryReleaseRecords(records); @@ -2188,6 +2217,7 @@ export const layerWithOptions = ( updated.set(key, entry); return updated; }); + yield* Ref.update(latestOpened, (current) => new Map(current).set(key, runtime)); // The entry now guards the credential via its recorded id, so // the pre-open reservation can be dropped. yield* dropReservation; @@ -2209,11 +2239,13 @@ export const layerWithOptions = ( providerSessionId: input.providerSessionId, reason: "manual_shutdown", detail: "The provider session start was interrupted.", + openLockHeld: true, } : { providerSessionId: input.providerSessionId, reason: "runtime_error", detail: "Failed to persist the provider-session attachment.", + openLockHeld: true, }, ).pipe(logReleaseFailure(input.providerSessionId)), ), From a4a59b7b65321ac4dbfff099ba2426a9cc0f70a4 Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 12 Oct 2026 20:02:33 -0400 Subject: [PATCH 4/5] codex-app-server: fail pending requests when the client closes A request still waiting for a reply when the client's scope closed was never answered, so its caller waited forever. Closing the client now fails those requests with CodexAppServerInputStreamEndedError, unless the connection already ended with its own error. Co-authored-by: Dara Adedeji --- .../src/protocol.test.ts | 24 +++++++++++++++++++ .../effect-codex-app-server/src/protocol.ts | 12 ++++++++++ 2 files changed, 36 insertions(+) diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts index 85de3d0aa87db..2b2b01e6bfb7b 100644 --- a/packages/effect-codex-app-server/src/protocol.test.ts +++ b/packages/effect-codex-app-server/src/protocol.test.ts @@ -1,8 +1,10 @@ import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; +import * as Scope from "effect/Scope"; import * as Stdio from "effect/Stdio"; import * as Stream from "effect/Stream"; import { TestClock } from "effect/testing"; @@ -862,4 +864,26 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => { assert.equal("cause" in error, false); }), ); + + it.effect("fails requests still waiting for a reply when the client closes", () => + Effect.gen(function* () { + const { stdio, output } = yield* makeInMemoryStdio(); + const clientScope = yield* Scope.make(); + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio }).pipe( + Scope.provide(clientScope), + ); + const response = yield* transport.request("thread/start", {}).pipe(Effect.forkScoped); + yield* Queue.take(output); + + yield* Scope.close(clientScope, Exit.void); + + const error = yield* Fiber.join(response).pipe( + Effect.match({ + onFailure: (error) => error, + onSuccess: () => assert.fail("Expected the request to fail"), + }), + ); + assert.instanceOf(error, CodexError.CodexAppServerInputStreamEndedError); + }), + ); }); diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts index 31676add63a8f..0a75f82668cc9 100644 --- a/packages/effect-codex-app-server/src/protocol.ts +++ b/packages/effect-codex-app-server/src/protocol.ts @@ -471,6 +471,18 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped); + // Closing the client fails the requests still waiting on a reply, which + // would otherwise wait forever. + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const closed = new CodexError.CodexAppServerInputStreamEndedError({}); + yield* Ref.update(terminationFailure, (current) => + Option.isSome(current) ? current : Option.some(closed), + ); + yield* failAllPending(closed); + }), + ); + const request = (method: string, payload?: unknown) => Effect.gen(function* () { const requestId = yield* Ref.modify( From d23ca98925cebdb0cec90320eef3aa4470fa34fa Mon Sep 17 00:00:00 2001 From: Dominic R Date: Mon, 12 Oct 2026 20:10:09 -0400 Subject: [PATCH 5/5] server/codex: fail the session when the app-server stops answering An app-server that is alive but wedged never exits, so watching the process exit does not catch it. The adapter now sends a thread/loaded/list request once a minute and fails the event stream when no reply, not even an error, comes back within a minute. The session manager then fails the session's runs and the next turn starts a new app-server. Co-authored-by: Dara Adedeji --- .../Adapters/CodexAdapterV2.test.ts | 52 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 30 +++++++++-- 2 files changed, 79 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 9dbc6255f0953..05aa4614dfd2a 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -48,6 +48,8 @@ import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; +import * as Sink from "effect/Sink"; +import * as Stdio from "effect/Stdio"; import * as Stream from "effect/Stream"; import { TestClock } from "effect/testing"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -1919,6 +1921,56 @@ describe("CodexAdapterV2 session initialize", () => { ); }); +describe("CodexAdapterV2 unresponsive app-server", () => { + it.effect("fails the session when the app-server stops answering", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CODEX_SETTINGS, + environment: {}, + clientFactory: { + open: () => + CodexClient.make( + Stdio.make({ + args: Effect.succeed([]), + stdin: Stream.never, + stdout: () => Sink.drain, + stderr: () => Sink.drain, + }), + ), + }, + crypto: yield* Crypto.Crypto, + fileSystem: yield* FileSystem.FileSystem, + idAllocator: yield* IdAllocator.IdAllocatorV2, + serverConfig: yield* makeReplayServerConfig("codex-unresponsive-app-server").pipe( + Effect.orDie, + ), + }); + const runtime = yield* adapter.openSession({ + threadId: ThreadId.make("thread-codex-unresponsive-app-server"), + providerSessionId: ProviderSessionId.make("provider-session-codex-unresponsive-app-server"), + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + const failure = yield* runtime.events.pipe( + Stream.runDrain, + Effect.flip, + Effect.forkChild({ startImmediately: true }), + ); + yield* TestClock.adjust("1 minute"); + yield* TestClock.adjust("1 minute"); + + const error = yield* Fiber.join(failure); + assert.instanceOf(error, ProviderAdapter.ProviderAdapterEventStreamError); + assert.include(String(error.cause), "Codex stopped responding"); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); +}); + describe("CodexAdapterV2 post-settle continuation", () => { const awaitUntil = (predicate: () => boolean, label: string): Effect.Effect => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index ee70b49f1cc98..734daaaeacada 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -468,6 +468,11 @@ function codexMcpToolOutput( // Reading an app's resource is one MCP round trip; a server that hangs must not // hold the item (and the run's ingestion) open. const MCP_APP_CAPTURE_TIMEOUT = "20 seconds"; +// A wedged app-server stays alive but stops answering. The probe, +// thread/loaded/list, only reads Codex's in-memory thread list, and any reply +// to it, even an error, proves the app-server is still reading. +const CODEX_LIVENESS_PROBE_INTERVAL = "1 minute"; +const CODEX_LIVENESS_PROBE_TIMEOUT = "1 minute"; /** The UI resource a completed Codex MCP tool call names, under any field Codex reports it in. */ function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined { @@ -1811,9 +1816,28 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ProviderAdapter.ProviderAdapterEventStreamError >(); // Every thread on this session shares the app-server. Once its - // connection ends, fail the stream so the session manager releases the - // session and the next turn starts a new app-server. - yield* client.terminated.pipe( + // connection ends, or it stops answering a once-a-minute probe, fail + // the stream so the session manager releases the session and the next + // turn starts a new app-server. + const unresponsive = Effect.gen(function* () { + while (true) { + yield* Effect.sleep(CODEX_LIVENESS_PROBE_INTERVAL); + const answered = yield* client + .request("thread/loaded/list", { limit: 1 }) + .pipe( + Effect.catchTags({ CodexAppServerRequestError: () => Effect.void }), + Effect.timeoutOption(CODEX_LIVENESS_PROBE_TIMEOUT), + ); + if (Option.isNone(answered)) { + return `Codex stopped responding: it did not answer a liveness check within ${CODEX_LIVENESS_PROBE_TIMEOUT}.`; + } + } + }); + yield* Effect.raceFirst( + client.terminated.pipe(Effect.map((error): unknown => error)), + // A probe that fails with a transport error is the termination above. + unresponsive.pipe(Effect.catch(() => Effect.never)), + ).pipe( Effect.flatMap((cause) => Queue.fail( events,