From b95ccdffd399a949477b65e5f2c6e29a6681eee0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 09:40:29 +0000 Subject: [PATCH 1/5] test(server): takeover tests for Codex process exit --- .../Adapters/CodexAdapterV2.test.ts | 169 ++++++++++++++++++ 1 file changed, 169 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 1e762543a13a..b672ac8aec4f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -31,6 +31,7 @@ import { import { assert, describe, it } from "@effect/vitest"; import * as CodexClient from "effect-codex-app-server/client"; import * as CodexReplay from "effect-codex-app-server/replay"; +import * as CodexError from "effect-codex-app-server/errors"; import type * as CodexSchema from "effect-codex-app-server/schema"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -47,6 +48,11 @@ import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; +import * as Sink from "effect/Sink"; +import * as Stdio from "effect/Stdio"; +import * as Exit from "effect/Exit"; +import type * as Cause from "effect/Cause"; +import * as PlatformError from "effect/PlatformError"; import { TestClock } from "effect/testing"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -609,6 +615,7 @@ function codexReplayPreamble(input: { thread: { id: input.nativeThreadId, sessionId: input.nativeThreadId, + projectId: null, forkedFromId: null, preview: "", ephemeral: false, @@ -702,6 +709,168 @@ function withReplayRequestId( : entry; } +describe("CodexAdapterV2 process exit", () => { + it.effect.each([ + { exit: "numeric", active: false }, + { exit: "SIGKILL", active: false }, + { exit: "numeric", active: true }, + { exit: "SIGKILL", active: true }, + ] as const)("retires the shared session after $exit (active turn: $active)", ({ exit, active }) => + Effect.gen(function* () { + const scenario = `process-exit-${exit}-${active}`; + const nativeThreadId = `native-${scenario}`; + const nativeTurnId = `turn-${scenario}`; + const input = yield* Queue.unbounded(); + const emit = (frame: unknown) => + Queue.offer(input, new TextEncoder().encode(JSON.stringify(frame) + "\n")); + const outputEnded = yield* Deferred.make(); + const turnStarted = yield* Deferred.make(); + const turnCompleted = yield* Deferred.make(); + const events: Array = []; + const preamble = codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "work" }); + const terminationError = + exit === "numeric" + ? new CodexError.CodexAppServerProcessExitedError({ code: 17, pid: 52 }) + : new CodexError.CodexAppServerTransportError({ + operation: "read-process-exit-status", + pid: 52, + cause: PlatformError.systemError({ + _tag: "Unknown", + module: "ChildProcess", + method: "exitCode", + cause: new Error("Process terminated by SIGKILL"), + }), + }); + const client = yield* CodexClient.make( + Stdio.make({ + args: Effect.succeed([]), + stdin: Stream.fromQueue(input), + stdout: () => + Sink.forEach((chunk: string | Uint8Array) => + Effect.gen(function* () { + const frame = JSON.parse( + typeof chunk === "string" ? chunk : new TextDecoder().decode(chunk), + ) as { readonly id?: number; readonly method: string }; + const response = preamble.find( + (entry) => + entry.type === "emit_inbound" && + entry.label === frame.method && + Predicate.isObject(entry.frame) && + "id" in entry.frame, + ); + if (response?.type === "emit_inbound") { + yield* emit(response.frame); + } + }), + ).pipe(Sink.ensuring(Deferred.succeed(outputEnded, undefined))), + stderr: () => Sink.drain, + }), + {}, + Effect.succeed(terminationError), + ); + const adapter = yield* CodexAdapterV2.makeCodexAdapterV2({ + instanceId: CodexAdapterV2.CODEX_DEFAULT_INSTANCE_ID, + settings: DEFAULT_CODEX_SETTINGS, + environment: {}, + clientFactory: { open: () => Effect.succeed(client) }, + crypto: yield* Crypto.Crypto, + fileSystem: yield* FileSystem.FileSystem, + idAllocator: yield* IdAllocator.IdAllocatorV2, + serverConfig: yield* makeReplayServerConfig(scenario).pipe(Effect.orDie), + }); + const threadId = ThreadId.make(`thread-${scenario}`); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make(`session-${scenario}`), + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + const eventReader = yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => events.push(event)).pipe( + Effect.andThen( + event.type === "provider_turn.updated" && event.providerTurn.status === "running" + ? Deferred.succeed(turnStarted, undefined) + : event.type === "turn.terminal" + ? Deferred.succeed(turnCompleted, undefined) + : Effect.void, + ), + ), + ), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection: CODEX_TEST_MODEL_SELECTION, + runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + }); + yield* runtime.startTurn( + makeCodexTestTurnInput({ + threadId, + providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-${scenario}`), + text: "work", + }), + ); + yield* emit({ + method: "turn/started", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "inProgress" }), + }, + }); + yield* Deferred.await(turnStarted); + if (!active) { + yield* emit({ + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }); + yield* Deferred.await(turnCompleted); + assert.isTrue( + events.some((event) => event.type === "turn.terminal" && event.status === "completed"), + ); + } + + yield* Queue.end(input); + // Output closes only after the protocol records the process termination. + yield* Deferred.await(outputEnded); + const rpcError = yield* client.request("thread/list", {}).pipe(Effect.flip); + assert.strictEqual(rpcError, terminationError); + // Drain runnable lifecycle work before inspecting the reader; no wall-clock deadline. + yield* TestClock.adjust(0); + const readerExit = eventReader.pollUnsafe(); + assert.isDefined(readerExit, "dead Codex sessions must end their event stream"); + assert.isTrue( + readerExit !== undefined && + (Exit.isFailure(readerExit) || + events.some( + (event) => + event.type === "provider_session.updated" && + (event.providerSession.status === "error" || + event.providerSession.status === "stopped"), + )), + "the session manager must receive process death so it can retire the shared process", + ); + if (active) { + assert.isTrue( + (readerExit !== undefined && Exit.isFailure(readerExit)) || + events.some((event) => event.type === "turn.terminal" && event.status === "failed"), + "an active turn must fail or its subscriber must receive the process failure", + ); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); +}); + describe("CodexAdapterV2 session initialize", () => { const openReplaySession = ( transcript: CodexReplay.CodexAppServerReplayTranscript, From ec811b87f29b0ec8a18197793a61fff73e8cc4fd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 21 Oct 2026 09:47:15 +0000 Subject: [PATCH 2/5] fix(server): retire Codex sessions when app-server exits --- .../Adapters/CodexAdapterV2.ts | 19 ++++++++++++++++++- .../effect-codex-app-server/src/client.ts | 5 +++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 74c4b46646e3..f5c15eab5ac9 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1746,7 +1746,24 @@ 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 + >(); + // Drain final notifications before the session manager retires the dead process. + yield* client.awaitTermination.pipe( + Effect.catch((cause) => + Queue.fail( + events, + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: CODEX_PROVIDER, + providerSessionId: input.providerSessionId, + cause, + }), + ), + ), + Effect.forkScoped, + ); 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 d872b9fa8473..508a9d00b3be 100644 --- a/packages/effect-codex-app-server/src/client.ts +++ b/packages/effect-codex-app-server/src/client.ts @@ -1,4 +1,5 @@ import * as Context from "effect/Context"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; @@ -40,6 +41,7 @@ export class CodexAppServerClient extends Context.Service< CodexAppServerClient, { readonly raw: CodexAppServerClientRaw; + readonly awaitTermination: Effect.Effect; readonly request: ( method: M, payload: CodexRpc.ClientRequestParamsByMethod[M], @@ -100,6 +102,7 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make terminationError?: Effect.Effect, ): Effect.fn.Return { const requestHandlers = new Map(); + const termination = yield* Deferred.make(); const notificationHandlers = new Map>(); let unknownRequestHandler: | ((method: string, params: unknown) => Effect.Effect) @@ -203,6 +206,7 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make ...(options.logger ? { logger: options.logger } : {}), onNotification: dispatchNotification, onRequest: dispatchRequest, + onTermination: (error) => Deferred.fail(termination, error).pipe(Effect.asVoid), }); const request = ( @@ -230,6 +234,7 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make ); return CodexAppServerClient.of({ + awaitTermination: Deferred.await(termination), raw: { notifications: transport.incomingNotifications, requests: transport.incomingRequests, From ee594bc3079e90a8997d7735a63715851002125e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 22 Oct 2026 13:05:25 +0000 Subject: [PATCH 3/5] test(server): keep the replayed app-server alive past the delegated-task recording The delegated_task_status recording ends with the recorder closing the app-server while the parent turn is still open. The MCP integration test keeps acting as that parent afterwards, so replaying the exit now (correctly) fails the parent run and task_status reports parent_not_active. Drop the recorded exit in that test's loader instead of changing what the app-server exit does. Also assert that a dead process fails the event stream with ProviderAdapterEventStreamError, since a clean end reads as manual_shutdown. Co-Authored-By: Claude Opus 5.5 --- ...OrchestratorMcpToolkit.integration.test.ts | 11 ++++++++- .../Adapters/CodexAdapterV2.test.ts | 23 ++++++------------- .../Adapters/CodexAdapterV2.ts | 1 + 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index dde77d484094..dba3bf7c08ee 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -99,7 +99,16 @@ const readDelegatedTaskStatusTranscript = Effect.fn("readDelegatedTaskStatusTran const text = yield* fs.readFileString( decodeURIComponent(delegatedTaskStatusTranscriptFile.pathname), ); - return yield* decodeProviderReplayNdjson(text.replaceAll(queuedFollowupResult, followupResult)); + const transcript = yield* decodeProviderReplayNdjson( + text.replaceAll(queuedFollowupResult, followupResult), + ); + // The recording ends when the recorder closes the app-server while the parent + // turn is still open. This test keeps acting as that parent afterwards, and + // replaying the exit would kill the shared process and fail the parent run. + return { + ...transcript, + entries: transcript.entries.filter((entry) => entry.type !== "runtime_exit"), + }; }, Effect.provide(NodeServices.layer)); function makeProviderSnapshot(input: { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index b672ac8aec4f..33f476b97a66 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -51,7 +51,7 @@ import * as Stream from "effect/Stream"; import * as Sink from "effect/Sink"; import * as Stdio from "effect/Stdio"; import * as Exit from "effect/Exit"; -import type * as Cause from "effect/Cause"; +import * as Cause from "effect/Cause"; import * as PlatformError from "effect/PlatformError"; import { TestClock } from "effect/testing"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; @@ -843,25 +843,16 @@ describe("CodexAdapterV2 process exit", () => { // Drain runnable lifecycle work before inspecting the reader; no wall-clock deadline. yield* TestClock.adjust(0); const readerExit = eventReader.pollUnsafe(); - assert.isDefined(readerExit, "dead Codex sessions must end their event stream"); + // A clean end of stream reads as manual_shutdown to the session manager, so + // only a stream failure retires the dead process as a runtime error. assert.isTrue( readerExit !== undefined && - (Exit.isFailure(readerExit) || - events.some( - (event) => - event.type === "provider_session.updated" && - (event.providerSession.status === "error" || - event.providerSession.status === "stopped"), - )), + Exit.isFailure(readerExit) && + Schema.is(ProviderAdapter.ProviderAdapterEventStreamError)( + Cause.squash(readerExit.cause), + ), "the session manager must receive process death so it can retire the shared process", ); - if (active) { - assert.isTrue( - (readerExit !== undefined && Exit.isFailure(readerExit)) || - events.some((event) => event.type === "turn.terminal" && event.status === "failed"), - "an active turn must fail or its subscriber must receive the process failure", - ); - } }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index f5c15eab5ac9..1d6b4c8586b7 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1751,6 +1751,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ProviderAdapter.ProviderAdapterEventStreamError >(); // Drain final notifications before the session manager retires the dead process. + // Queue.fail lets readers take items already buffered before they see the failure. yield* client.awaitTermination.pipe( Effect.catch((cause) => Queue.fail( From 7f608d9c668bbcccf52799ccf8847eadf23fa619 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 27 Oct 2026 15:54:29 -0700 Subject: [PATCH 4/5] test(server): hoist the event-stream error guard for the new lint rule Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Adapters/CodexAdapterV2.test.ts | 7 ++++--- 1 file changed, 4 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 33f476b97a66..3290ea906f1b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -73,6 +73,9 @@ const replayTranscriptJson = Schema.fromJsonString(CodexReplay.CodexAppServerRep const encodeReplayTranscriptJson = Schema.encodeEffect(replayTranscriptJson); const decodeReplayTranscriptJson = Schema.decodeUnknownEffect(replayTranscriptJson); const encodeStringJson = Schema.encodeEffect(Schema.fromJsonString(Schema.String)); +const isProviderAdapterEventStreamError = Schema.is( + ProviderAdapter.ProviderAdapterEventStreamError, +); describe("CodexAdapterV2 context usage", () => { it("uses the current context rather than cumulative processed tokens", () => { @@ -848,9 +851,7 @@ describe("CodexAdapterV2 process exit", () => { assert.isTrue( readerExit !== undefined && Exit.isFailure(readerExit) && - Schema.is(ProviderAdapter.ProviderAdapterEventStreamError)( - Cause.squash(readerExit.cause), - ), + isProviderAdapterEventStreamError(Cause.squash(readerExit.cause)), "the session manager must receive process death so it can retire the shared process", ); }).pipe( From 66f96aaa7907c87d3602daeb6b979d32dc5a5b06 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Tue, 27 Oct 2026 16:13:26 -0700 Subject: [PATCH 5/5] test(server): await the event reader instead of one scheduler hop The process-exit test now waits for the reader fiber to end, as the testing rules require, and its comment gives the real reason a stream failure is used. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/Adapters/CodexAdapterV2.test.ts | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 3290ea906f1b..b9abb27f8f4f 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -843,14 +843,11 @@ describe("CodexAdapterV2 process exit", () => { yield* Deferred.await(outputEnded); const rpcError = yield* client.request("thread/list", {}).pipe(Effect.flip); assert.strictEqual(rpcError, terminationError); - // Drain runnable lifecycle work before inspecting the reader; no wall-clock deadline. - yield* TestClock.adjust(0); - const readerExit = eventReader.pollUnsafe(); - // A clean end of stream reads as manual_shutdown to the session manager, so - // only a stream failure retires the dead process as a runtime error. + // Without the fix the stream never ends, so this waits until the project timeout. + const readerExit = yield* Fiber.await(eventReader); + // A failure, not a clean end, carries the Codex error into the session's lastError. assert.isTrue( - readerExit !== undefined && - Exit.isFailure(readerExit) && + Exit.isFailure(readerExit) && isProviderAdapterEventStreamError(Cause.squash(readerExit.cause)), "the session manager must receive process death so it can retire the shared process", );