From e90204d81126287dfc8567a3cc0b7625886e1410 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 31 Oct 2026 01:46:10 -0400 Subject: [PATCH 1/4] fix(server): free finished delegated Codex threads early Signed-off-by: Yordis Prieto --- .../Adapters/CodexAdapterV2.test.ts | 59 ++++++++ .../Adapters/CodexAdapterV2.ts | 27 +++- .../ProviderSessionManager.test.ts | 129 +++++++++++++++++- .../ProviderSessionManager.ts | 16 ++- .../src/server/ProviderAdapter.ts | 2 + 5 files changed, 223 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index e50b6689ef19a..3e3802ca8a087 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -3882,6 +3882,65 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("archives an eagerly unloaded thread and interrupts its leftover commands", () => + Effect.gen(function* () { + const exchange = (id: number, method: string, result: unknown, notified: string[]) => [ + { + type: "expect_outbound" as const, + label: method, + frame: { id, method, params: { threadId: BG_NATIVE_THREAD } }, + }, + ...notified.map((notifiedMethod) => ({ + type: "emit_inbound" as const, + label: notifiedMethod, + frame: { method: notifiedMethod, params: { threadId: BG_NATIVE_THREAD } }, + })), + { + type: "emit_inbound" as const, + label: `${method}-result`, + frame: { id, result }, + }, + ]; + const transcript = makeCodexReplayTranscript({ + scenario: "codex-background-thread-archived", + entries: [ + ...backgroundExecTranscript.entries.slice(0, -1), + ...exchange(4, "thread/archive", {}, ["thread/archived"]), + ...exchange(5, "thread/unarchive", { thread: { id: BG_NATIVE_THREAD } }, [ + "thread/unarchived", + ]), + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-codex-thread-archived"), + text: BG_PROMPT, + }), + ); + yield* harness.firstTerminal; + yield* harness.runtime.unloadThread!({ providerThread: harness.providerThread, eager: true }); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === BG_COMMAND_ITEM + ? [event.turnItem.status] + : [], + ), + ["running", "interrupted"], + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + const backgroundStopCases = [true, false, "still_running", "thread_unloaded"] as const; const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => { const stillRunning = terminated === "still_running"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 2e2fdd4331c1f..4e2381374975e 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -4691,11 +4691,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( // Unloading an idle thread kills its terminals without completing // their command items, while the shared provider session stays alive. - yield* client.handleServerNotification("thread/closed", (payload) => - Effect.gen(function* () { + const interruptClosedThreadCommands = Effect.fn( + "CodexAdapterV2.interruptClosedThreadCommands", + )( + function* (nativeThreadId: string) { const completedAt = yield* DateTime.now; for (const context of (yield* Ref.get(settledTurns)).values()) { - if (context.providerThread.nativeThreadRef?.nativeId !== payload.threadId) continue; + if (context.providerThread.nativeThreadRef?.nativeId !== nativeThreadId) continue; const commands = (yield* Ref.get(runningCommandItemsByTurn)).get( context.nativeTurnId, ); @@ -4715,7 +4717,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); yield* releaseSettledTurnIfIdle(context.nativeTurnId); } - }).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)), + }, + Effect.orDie, + turnTerminalizationPermit.withPermits(1), + ); + yield* client.handleServerNotification("thread/closed", (payload) => + interruptClosedThreadCommands(payload.threadId), ); yield* client.handleServerNotification("item/started", (payload) => @@ -7163,13 +7170,19 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ), ), ), - // Dropping this connection's subscription lets the shared app-server - // shut the native thread (and its MCP servers) down once it is idle. unloadThread: Effect.fn("CodexAdapterV2.unloadThread")( function* (unloadInput) { const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread); sessionApprovals.delete(nativeThreadId); - yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); + if (unloadInput.eager !== true) { + yield* client.request("thread/unsubscribe", { threadId: nativeThreadId }); + return; + } + // Codex closes an unsubscribed thread (and its MCP servers) only after a fixed + // 1800 s; archive is the only immediate unload, and it never sends thread/closed. + yield* client.request("thread/archive", { threadId: nativeThreadId }); + yield* interruptClosedThreadCommands(nativeThreadId); + yield* client.raw.request("thread/unarchive", { threadId: nativeThreadId }); }, (effect, unloadInput) => effect.pipe( diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 3428f37fed2d7..e8bd03d5daf3a 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -21,6 +21,7 @@ import { import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; 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 Fiber from "effect/Fiber"; @@ -177,6 +178,7 @@ interface TestProviderRuntimeState { readonly interruptCount: number; readonly resumeCount: number; readonly unloadedNativeThreadIds: ReadonlyArray; + readonly eagerUnloadedNativeThreadIds: ReadonlyArray; readonly eventQueues: ReadonlyMap< string, Queue.Queue @@ -189,6 +191,7 @@ const emptyState: TestProviderRuntimeState = { interruptCount: 0, resumeCount: 0, unloadedNativeThreadIds: [], + eagerUnloadedNativeThreadIds: [], eventQueues: new Map(), }; @@ -446,7 +449,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ...current, interruptCount: current.interruptCount + 1, })).pipe(Effect.andThen(options.interruptTurn ?? Effect.void)), - unloadThread: ({ providerThread }) => + unloadThread: ({ providerThread, eager }) => (options.beforeUnload ?? Effect.void).pipe( Effect.andThen( Ref.update(state, (current) => ({ @@ -455,6 +458,13 @@ const makeProviderAdapter = Effect.fnUntraced(function* ( ...current.unloadedNativeThreadIds, providerThread.nativeThreadRef?.nativeId ?? "", ], + eagerUnloadedNativeThreadIds: + eager === true + ? [ + ...current.eagerUnloadedNativeThreadIds, + providerThread.nativeThreadRef?.nativeId ?? "", + ] + : current.eagerUnloadedNativeThreadIds, })), ), ), @@ -3436,6 +3446,123 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 unloads a delegated child's thread eagerly and well before other threads", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const parentThreadId = ThreadId.make("thread-provider-session-manager-eager-parent"); + const normalThreadId = ThreadId.make("thread-provider-session-manager-eager-normal"); + const childThreadId = ThreadId.make("thread-provider-session-manager-eager-child"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId: normalThreadId, now }), + yield* makeThreadCreatedEvent({ + idAllocator, + threadId: childThreadId, + now, + delegatedBy: parentThreadId, + }), + ], + }); + const runtime = yield* manager.open({ + threadId: normalThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: childThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* runtime.events.pipe(Stream.runDrain, Effect.forkScoped); + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(queue); + const runTurn = Effect.fnUntraced(function* (threadId: ThreadId) { + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: String(threadId), + }); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }), + text: "work", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + return Queue.offer(queue!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: `native-turn-${threadId}`, + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + }); + const finishNormal = yield* runTurn(normalThreadId); + const finishChild = yield* runTurn(childThreadId); + const unloads = Effect.map(Ref.get(state), (current) => ({ + all: current.unloadedNativeThreadIds, + eager: current.eagerUnloadedNativeThreadIds, + })); + + yield* finishNormal; + yield* Effect.yieldNow; + yield* TestClock.adjust("1 minute"); + yield* finishChild; + yield* Effect.yieldNow; + yield* TestClock.adjust( + Duration.millis(ProviderSessionManager.DELEGATED_CHILD_IDLE_TIMEOUT_MS - 1), + ); + assert.deepEqual(yield* unloads, { all: [], eager: [] }); + yield* TestClock.adjust("1 millis"); + assert.deepEqual(yield* unloads, { all: [childThreadId], eager: [childThreadId] }); + yield* TestClock.adjust("7 minutes"); + assert.deepEqual(yield* unloads, { + all: [childThreadId, normalThreadId], + eager: [childThreadId], + }); + }); + + yield* effect.pipe( + Effect.provide(layerTest({ state, idleTimeoutMs: 10 * 60_000 })), + Effect.scoped, + ); + }), +); + it.effect( "ProviderSessionManagerV2 ignores a late turn.terminal from an earlier run on the same provider thread", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 94c38045a5d13..8b30588da425a 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -56,6 +56,8 @@ import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +/** Delegated children are rarely resumed, so their native threads are freed early. */ +export const DELEGATED_CHILD_IDLE_TIMEOUT_MS = 2 * 60 * 1000; const DEFAULT_MAX_IDLE_PIN_MS = 4 * 60 * 60 * 1000; const RELEASE_SCOPE_CLOSE_TIMEOUT_MS = 30 * 1000; /** Past adapters' own 10 s stop fallbacks, so they settle first when the provider answers at all. */ @@ -240,6 +242,7 @@ interface IdleThreadUnload { readonly providerThread: OrchestrationV2ProviderThread; readonly generation: number; readonly fiber: Fiber.Fiber | null; + readonly delegatedChild: boolean; } type ProviderSessionEventSignal = @@ -1515,6 +1518,7 @@ export const layerWithOptions = ( readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; + readonly delegatedChild?: boolean; }) { const entry = (yield* Ref.get(sessions)).get(sessionKey(input.providerSessionId)); if ( @@ -1532,6 +1536,7 @@ export const layerWithOptions = ( providerThread: input.providerThread, generation: (current?.generation ?? 0) + 1, fiber: null, + delegatedChild: input.delegatedChild ?? current?.delegatedChild ?? false, }), ); yield* cancelIdleFiber(previous?.fiber ?? null); @@ -1548,7 +1553,10 @@ export const layerWithOptions = ( if (tracked === undefined) return; const [threadId, pending] = tracked; const generation = pending.generation + 1; - const fiber = yield* Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + const delay = pending.delegatedChild + ? Math.min(DELEGATED_CHILD_IDLE_TIMEOUT_MS, idleTimeoutMs) + : idleTimeoutMs; + const fiber = yield* Effect.sleep(Duration.millis(delay)).pipe( Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), Effect.forkIn(layerScope), ); @@ -1617,7 +1625,10 @@ export const layerWithOptions = ( return [true, updated] as const; }); if (!unloading) return "skipped" as const; - yield* unloadThread({ providerThread: pending.providerThread }).pipe( + yield* unloadThread({ + providerThread: pending.providerThread, + eager: pending.delegatedChild, + }).pipe( Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), Effect.catchCause((cause) => Effect.logWarning("orchestration-v2.driver-session.idle-unload-failed", { @@ -1828,6 +1839,7 @@ export const layerWithOptions = ( providerSessionId, threadId: input.threadId, providerThread: input.providerThread, + delegatedChild: input.appThread.lineage.relationshipToParent === "subagent", }), ), Effect.andThen( diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index cadf4173a60b1..30c58a8c96b65 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -633,6 +633,8 @@ export interface ProviderAdapterV2SessionRuntime { }) => Effect.Effect; readonly unloadThread?: (input: { readonly providerThread: OrchestrationV2ProviderThread; + /** Free the native thread's resources now instead of after the provider's own idle delay. */ + readonly eager?: boolean; }) => Effect.Effect; readonly respondToRuntimeRequest: ( input: ProviderAdapterV2RuntimeRequestResponseInput, From c24f724690bd94a14b3edd6a5243e2fd90ea3107 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 31 Oct 2026 02:03:07 -0400 Subject: [PATCH 2/4] feat(server): make provider thread unloads queryable Signed-off-by: Yordis Prieto --- apps/server/src/observability/Metrics.ts | 4 + .../ProviderSessionManager.test.ts | 133 ++++++++++++++++++ .../ProviderSessionManager.ts | 88 ++++++++---- 3 files changed, 197 insertions(+), 28 deletions(-) diff --git a/apps/server/src/observability/Metrics.ts b/apps/server/src/observability/Metrics.ts index a14d614164d4e..ce877d7d941d1 100644 --- a/apps/server/src/observability/Metrics.ts +++ b/apps/server/src/observability/Metrics.ts @@ -64,6 +64,10 @@ export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", { description: "Time for the provider adapter to start a turn, not how long the turn runs.", }); +export const providerThreadUnloadsTotal = Metric.counter("t3_provider_thread_unloads_total", { + description: "Total idle provider thread unload attempts, by mode and outcome.", +}); + export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", { description: "Total canonical provider runtime events processed.", }); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index e8bd03d5daf3a..7f1dfe29b5204 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3446,6 +3446,20 @@ it.effect( }), ); +const threadUnloadCount = (mode: "eager" | "idle", outcome: string) => + Metric.snapshot.pipe( + Effect.map((snapshots) => { + const snapshot = snapshots.find( + (candidate) => + candidate.id === "t3_provider_thread_unloads_total" && + candidate.attributes?.provider === CODEX_DRIVER && + candidate.attributes?.mode === mode && + candidate.attributes?.outcome === outcome, + ); + return snapshot !== undefined && "count" in snapshot.state ? Number(snapshot.state.count) : 0; + }), + ); + it.effect( "ProviderSessionManagerV2 unloads a delegated child's thread eagerly and well before other threads", () => @@ -3537,6 +3551,8 @@ it.effect( all: current.unloadedNativeThreadIds, eager: current.eagerUnloadedNativeThreadIds, })); + const eagerBefore = yield* threadUnloadCount("eager", "unloaded"); + const idleBefore = yield* threadUnloadCount("idle", "unloaded"); yield* finishNormal; yield* Effect.yieldNow; @@ -3554,6 +3570,8 @@ it.effect( all: [childThreadId, normalThreadId], eager: [childThreadId], }); + assert.equal((yield* threadUnloadCount("eager", "unloaded")) - eagerBefore, 1); + assert.equal((yield* threadUnloadCount("idle", "unloaded")) - idleBefore, 1); }); yield* effect.pipe( @@ -3563,6 +3581,121 @@ it.effect( }), ); +it.effect( + "ProviderSessionManagerV2 keeps retrying an idle unload while work is pending and records a failed unload", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const pendingWork = yield* Ref.make(true); + const failUnload = yield* Ref.make(false); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-deferred-unload"); + const otherThreadId = ThreadId.make("thread-provider-session-manager-deferred-other"); + const providerSessionId = idAllocator.derive.providerSession({ + providerInstanceId: modelSelection.instanceId, + }); + yield* eventSink.write({ + events: [ + yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + yield* makeThreadCreatedEvent({ idAllocator, threadId: otherThreadId, now }), + ], + }); + const runtime = yield* manager.open({ + threadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* manager.open({ + threadId: otherThreadId, + providerSessionId, + modelSelection, + runtimePolicy, + }); + yield* runtime.events.pipe(Stream.runDrain, Effect.forkScoped); + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + assert.isDefined(queue); + const providerThread = makeProviderThread({ + idAllocator, + threadId, + providerSessionId, + now, + nativeThreadId: String(threadId), + }); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + yield* runtime.startTurn({ + appThread: (yield* projectionStore.getThreadProjection(threadId)).thread, + threadId, + runId, + runOrdinal: 1, + providerTurnOrdinal: 1, + attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }), + rootNodeId: idAllocator.derive.rootNode({ runId }), + providerThread, + message: { + createdBy: "user", + creationSource: "web", + messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }), + text: "work", + attachments: [], + }, + modelSelection, + runtimePolicy, + }); + const deferredBefore = yield* threadUnloadCount("idle", "deferred"); + const failedBefore = yield* threadUnloadCount("idle", "failed"); + const counts = Effect.all({ + deferred: Effect.map(threadUnloadCount("idle", "deferred"), (n) => n - deferredBefore), + failed: Effect.map(threadUnloadCount("idle", "failed"), (n) => n - failedBefore), + }); + + yield* Queue.offer(queue!, { + type: "turn.terminal", + driver: CODEX_DRIVER, + providerThreadId: providerThread.id, + providerTurnId: idAllocator.derive.providerTurn({ + driver: CODEX_DRIVER, + nativeTurnId: "native-turn-deferred-unload", + }), + runOrdinal: 1, + status: "completed", + failure: null, + threadDisposition: "reusable", + }); + yield* Effect.yieldNow; + yield* TestClock.adjust("1 second"); + assert.deepEqual(yield* counts, { deferred: 1, failed: 0 }); + yield* TestClock.adjust("1 second"); + assert.deepEqual(yield* counts, { deferred: 2, failed: 0 }); + yield* Ref.set(pendingWork, false); + yield* Ref.set(failUnload, true); + yield* TestClock.adjust("1 second"); + assert.deepEqual(yield* counts, { deferred: 2, failed: 1 }); + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, []); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 1000, + hasPendingBackgroundWork: Effect.succeed(true), + hasPendingBackgroundWorkForThread: Ref.get(pendingWork), + beforeUnload: Ref.get(failUnload).pipe( + Effect.flatMap((fail) => (fail ? Effect.die("unload failed") : Effect.void)), + ), + }), + ), + Effect.scoped, + ); + }), +); + it.effect( "ProviderSessionManagerV2 ignores a late turn.terminal from an earlier run on the same provider thread", () => diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 8b30588da425a..758a8be4a119d 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -37,6 +37,7 @@ import { normalizeModelMetricLabel, outcomeFromExit } from "../observability/Att import { increment, providerSessionsTotal, + providerThreadUnloadsTotal, providerTurnDuration, providerTurnsTotal, withMetrics, @@ -245,6 +246,14 @@ interface IdleThreadUnload { readonly delegatedChild: boolean; } +interface IdleThreadUnloadAttempt { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly generation: number; +} + +type IdleThreadUnloadOutcome = "unloaded" | "deferred" | "skipped" | "failed"; + type ProviderSessionEventSignal = | { readonly type: "event"; readonly event: ProviderAdapter.ProviderAdapterV2Event } | { @@ -1571,19 +1580,20 @@ export const layerWithOptions = ( }, ); - const unloadIdleThread = Effect.fn("ProviderSessionManager.unloadIdleThread")( - function* (input: { - readonly providerSessionId: ProviderSessionId; - readonly threadId: ThreadId; - readonly generation: number; - }): Effect.fn.Return { - const outcome = yield* threadAttachment.withLock( + const unloadIdleThreadAttempt = Effect.fn("ProviderSessionManager.unloadIdleThread")( + function* (input: IdleThreadUnloadAttempt) { + const attempt = yield* threadAttachment.withLock( threadAttachmentKey(input), Effect.gen(function* () { const key = sessionKey(input.providerSessionId); const entry = (yield* Ref.get(sessions)).get(key); const pending = entry?.idleThreadUnloads.get(input.threadId); const unloadThread = entry?.exposedRuntime.unloadThread; + const recorded = (outcome: IdleThreadUnloadOutcome) => ({ + outcome, + provider: entry?.runtime.driver, + mode: pending?.delegatedChild === true ? ("eager" as const) : ("idle" as const), + }); if ( entry === undefined || pending === undefined || @@ -1592,7 +1602,7 @@ export const layerWithOptions = ( !entry.attachedThreadIds.has(input.threadId) || hasBusyTurn(entry, pending.providerThread.id) ) { - return "skipped" as const; + return recorded("skipped"); } // Unloading kills background terminals; keep threads with pending work loaded. const hasPendingWork = @@ -1601,7 +1611,7 @@ export const layerWithOptions = ( : yield* entry.runtime .hasPendingBackgroundWorkForThread(pending.providerThread) .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (hasPendingWork) return "deferred" as const; + if (hasPendingWork) return recorded("deferred"); const unloading = yield* Ref.modify(sessions, (current) => { const latest = current.get(key); if ( @@ -1624,32 +1634,54 @@ export const layerWithOptions = ( }); return [true, updated] as const; }); - if (!unloading) return "skipped" as const; - yield* unloadThread({ - providerThread: pending.providerThread, - eager: pending.delegatedChild, - }).pipe( - Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), - Effect.catchCause((cause) => - Effect.logWarning("orchestration-v2.driver-session.idle-unload-failed", { - providerSessionId: input.providerSessionId, - threadId: input.threadId, - providerThreadId: pending.providerThread.id, - cause, - }), + if (!unloading) return recorded("skipped"); + return recorded( + yield* unloadThread({ + providerThread: pending.providerThread, + eager: pending.delegatedChild, + }).pipe( + Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS), + Effect.as("unloaded" as const), + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.driver-session.idle-unload-failed", { + providerSessionId: input.providerSessionId, + threadId: input.threadId, + providerThreadId: pending.providerThread.id, + cause, + }).pipe(Effect.as("failed" as const)), + ), ), ); - return "unloaded" as const; }), ); - // Wait outside the lock so the next attach is not blocked. - if (outcome === "deferred") { - yield* Effect.sleep(Duration.millis(idleTimeoutMs)); - return yield* unloadIdleThread(input); - } + yield* Effect.annotateCurrentSpan({ + "orchestration_v2.thread_id": input.threadId, + "orchestration_v2.provider_session_id": input.providerSessionId, + "orchestration_v2.provider": attempt.provider ?? null, + "orchestration_v2.unload_mode": attempt.mode, + "orchestration_v2.unload_outcome": attempt.outcome, + }); + yield* increment(providerThreadUnloadsTotal, { + provider: attempt.provider, + mode: attempt.mode, + outcome: attempt.outcome, + }); + return attempt.outcome; }, ); + // Each attempt is its own span; the wait sits outside the lock so the next attach is not blocked. + const unloadIdleThread = (input: IdleThreadUnloadAttempt): Effect.Effect => + unloadIdleThreadAttempt(input).pipe( + Effect.flatMap((outcome) => + outcome === "deferred" + ? Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + Effect.andThen(Effect.suspend(() => unloadIdleThread(input))), + ) + : Effect.void, + ), + ); + const observeActivity = ( providerSessionId: ProviderSessionId, activity: Effect.Effect, From 843d6c9c5852bcd2e619c9c46694d9e80de80d12 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 31 Oct 2026 02:16:53 -0400 Subject: [PATCH 3/4] fix(server): keep delegated thread release on its short delay and fallback Signed-off-by: Yordis Prieto --- .../Adapters/CodexAdapterV2.test.ts | 57 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 9 ++- .../ProviderSessionManager.test.ts | 31 ++++++---- .../ProviderSessionManager.ts | 18 +++--- 4 files changed, 96 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 3e3802ca8a087..e102733462a6c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1262,6 +1262,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { terminalEvents, subagentUpdates, hasPendingBackgroundWork, + replayState: driver.state, firstTerminal: Deferred.await(firstTerminal), until: changes.until, awaitTerminal: (count: number) => changes.until(() => terminalEvents().length >= count), @@ -3941,6 +3942,62 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("falls back to unsubscribing when an eager archive fails", () => + Effect.gen(function* () { + const transcript = makeCodexReplayTranscript({ + scenario: "codex-background-thread-archive-failed", + entries: [ + ...backgroundExecTranscript.entries.slice(0, -1), + { + type: "expect_outbound", + label: "thread/archive", + frame: { id: 4, method: "thread/archive", params: { threadId: BG_NATIVE_THREAD } }, + }, + { + type: "emit_inbound", + label: "thread/archive-error", + frame: { id: 4, error: { code: -32603, message: "archive failed" } }, + }, + { + type: "expect_outbound", + label: "thread/unsubscribe", + frame: { + id: 5, + method: "thread/unsubscribe", + params: { threadId: BG_NATIVE_THREAD }, + }, + }, + { + type: "emit_inbound", + label: "thread/unsubscribe-result", + frame: { id: 5, result: { status: "unsubscribed" } }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness(transcript); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-codex-thread-archive-failed"), + text: BG_PROMPT, + }), + ); + yield* harness.firstTerminal; + yield* harness.runtime.unloadThread!({ + providerThread: harness.providerThread, + eager: true, + }).pipe(Effect.flip); + assert.strictEqual((yield* Ref.get(harness.replayState)).cursor, transcript.entries.length); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + const backgroundStopCases = [true, false, "still_running", "thread_unloaded"] as const; const makeBackgroundStopTranscript = (terminated: (typeof backgroundStopCases)[number]) => { const stillRunning = terminated === "still_running"; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 4e2381374975e..b53e4cdb7c2fb 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -7180,7 +7180,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } // Codex closes an unsubscribed thread (and its MCP servers) only after a fixed // 1800 s; archive is the only immediate unload, and it never sends thread/closed. - yield* client.request("thread/archive", { threadId: nativeThreadId }); + yield* client.request("thread/archive", { threadId: nativeThreadId }).pipe( + // A failed archive keeps the thread subscribed, so Codex would never close it. + Effect.tapError(() => + client + .request("thread/unsubscribe", { threadId: nativeThreadId }) + .pipe(Effect.ignore), + ), + ); yield* interruptClosedThreadCommands(nativeThreadId); yield* client.raw.request("thread/unarchive", { threadId: nativeThreadId }); }, diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 7f1dfe29b5204..74f80ceff8503 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -3582,7 +3582,7 @@ it.effect( ); it.effect( - "ProviderSessionManagerV2 keeps retrying an idle unload while work is pending and records a failed unload", + "ProviderSessionManagerV2 retries a delegated child's deferred unload on its short delay and records a failed unload", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); @@ -3601,7 +3601,12 @@ it.effect( }); yield* eventSink.write({ events: [ - yield* makeThreadCreatedEvent({ idAllocator, threadId, now }), + yield* makeThreadCreatedEvent({ + idAllocator, + threadId, + now, + delegatedBy: ThreadId.make("thread-provider-session-manager-deferred-parent"), + }), yield* makeThreadCreatedEvent({ idAllocator, threadId: otherThreadId, now }), ], }); @@ -3647,11 +3652,11 @@ it.effect( modelSelection, runtimePolicy, }); - const deferredBefore = yield* threadUnloadCount("idle", "deferred"); - const failedBefore = yield* threadUnloadCount("idle", "failed"); + const deferredBefore = yield* threadUnloadCount("eager", "deferred"); + const failedBefore = yield* threadUnloadCount("eager", "failed"); const counts = Effect.all({ - deferred: Effect.map(threadUnloadCount("idle", "deferred"), (n) => n - deferredBefore), - failed: Effect.map(threadUnloadCount("idle", "failed"), (n) => n - failedBefore), + deferred: Effect.map(threadUnloadCount("eager", "deferred"), (n) => n - deferredBefore), + failed: Effect.map(threadUnloadCount("eager", "failed"), (n) => n - failedBefore), }); yield* Queue.offer(queue!, { @@ -3668,13 +3673,19 @@ it.effect( threadDisposition: "reusable", }); yield* Effect.yieldNow; - yield* TestClock.adjust("1 second"); + yield* TestClock.adjust( + Duration.millis(ProviderSessionManager.DELEGATED_CHILD_IDLE_TIMEOUT_MS), + ); assert.deepEqual(yield* counts, { deferred: 1, failed: 0 }); - yield* TestClock.adjust("1 second"); + yield* TestClock.adjust( + Duration.millis(ProviderSessionManager.DELEGATED_CHILD_IDLE_TIMEOUT_MS), + ); assert.deepEqual(yield* counts, { deferred: 2, failed: 0 }); yield* Ref.set(pendingWork, false); yield* Ref.set(failUnload, true); - yield* TestClock.adjust("1 second"); + yield* TestClock.adjust( + Duration.millis(ProviderSessionManager.DELEGATED_CHILD_IDLE_TIMEOUT_MS), + ); assert.deepEqual(yield* counts, { deferred: 2, failed: 1 }); assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, []); }); @@ -3683,7 +3694,7 @@ it.effect( Effect.provide( layerTest({ state, - idleTimeoutMs: 1000, + idleTimeoutMs: 10 * 60_000, hasPendingBackgroundWork: Effect.succeed(true), hasPendingBackgroundWorkForThread: Ref.get(pendingWork), beforeUnload: Ref.get(failUnload).pipe( diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 758a8be4a119d..d35736a2e82a1 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -1552,6 +1552,11 @@ export const layerWithOptions = ( }, ); + const idleUnloadDelay = (delegatedChild: boolean) => + Duration.millis( + delegatedChild ? Math.min(DELEGATED_CHILD_IDLE_TIMEOUT_MS, idleTimeoutMs) : idleTimeoutMs, + ); + const scheduleThreadUnload = Effect.fn("ProviderSessionManager.scheduleThreadUnload")( function* (providerSessionId: ProviderSessionId, providerThreadId: ProviderThreadId) { const entry = (yield* Ref.get(sessions)).get(sessionKey(providerSessionId)); @@ -1562,10 +1567,7 @@ export const layerWithOptions = ( if (tracked === undefined) return; const [threadId, pending] = tracked; const generation = pending.generation + 1; - const delay = pending.delegatedChild - ? Math.min(DELEGATED_CHILD_IDLE_TIMEOUT_MS, idleTimeoutMs) - : idleTimeoutMs; - const fiber = yield* Effect.sleep(Duration.millis(delay)).pipe( + const fiber = yield* Effect.sleep(idleUnloadDelay(pending.delegatedChild)).pipe( Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), Effect.forkIn(layerScope), ); @@ -1666,16 +1668,16 @@ export const layerWithOptions = ( mode: attempt.mode, outcome: attempt.outcome, }); - return attempt.outcome; + return attempt; }, ); // Each attempt is its own span; the wait sits outside the lock so the next attach is not blocked. const unloadIdleThread = (input: IdleThreadUnloadAttempt): Effect.Effect => unloadIdleThreadAttempt(input).pipe( - Effect.flatMap((outcome) => - outcome === "deferred" - ? Effect.sleep(Duration.millis(idleTimeoutMs)).pipe( + Effect.flatMap((attempt) => + attempt.outcome === "deferred" + ? Effect.sleep(idleUnloadDelay(attempt.mode === "eager")).pipe( Effect.andThen(Effect.suspend(() => unloadIdleThread(input))), ) : Effect.void, From 40f2b7ca42336b3cc2ab5ab7166cf2f352a4894d Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 31 Oct 2026 10:00:28 -0400 Subject: [PATCH 4/4] fix(server): label stale unload attempts with their scheduled mode Signed-off-by: Yordis Prieto --- .../src/orchestration-v2/ProviderSessionManager.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index d35736a2e82a1..ffafbbef7fb32 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -250,6 +250,7 @@ interface IdleThreadUnloadAttempt { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; readonly generation: number; + readonly delegatedChild: boolean; } type IdleThreadUnloadOutcome = "unloaded" | "deferred" | "skipped" | "failed"; @@ -1568,7 +1569,14 @@ export const layerWithOptions = ( const [threadId, pending] = tracked; const generation = pending.generation + 1; const fiber = yield* Effect.sleep(idleUnloadDelay(pending.delegatedChild)).pipe( - Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), + Effect.andThen( + unloadIdleThread({ + providerSessionId, + threadId, + generation, + delegatedChild: pending.delegatedChild, + }), + ), Effect.forkIn(layerScope), ); const previous = yield* updateIdleThreadUnload(providerSessionId, threadId, (current) => @@ -1594,7 +1602,7 @@ export const layerWithOptions = ( const recorded = (outcome: IdleThreadUnloadOutcome) => ({ outcome, provider: entry?.runtime.driver, - mode: pending?.delegatedChild === true ? ("eager" as const) : ("idle" as const), + mode: input.delegatedChild ? ("eager" as const) : ("idle" as const), }); if ( entry === undefined || @@ -1677,7 +1685,7 @@ export const layerWithOptions = ( unloadIdleThreadAttempt(input).pipe( Effect.flatMap((attempt) => attempt.outcome === "deferred" - ? Effect.sleep(idleUnloadDelay(attempt.mode === "eager")).pipe( + ? Effect.sleep(idleUnloadDelay(input.delegatedChild)).pipe( Effect.andThen(Effect.suspend(() => unloadIdleThread(input))), ) : Effect.void,