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/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index e50b6689ef19a..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), @@ -3882,6 +3883,121 @@ 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), + ), + ), + ); + + 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 2e2fdd4331c1f..b53e4cdb7c2fb 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,26 @@ 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 }).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 }); }, (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..74f80ceff8503 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,267 @@ 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", + () => + 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, + })); + const eagerBefore = yield* threadUnloadCount("eager", "unloaded"); + const idleBefore = yield* threadUnloadCount("idle", "unloaded"); + + 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], + }); + assert.equal((yield* threadUnloadCount("eager", "unloaded")) - eagerBefore, 1); + assert.equal((yield* threadUnloadCount("idle", "unloaded")) - idleBefore, 1); + }); + + yield* effect.pipe( + Effect.provide(layerTest({ state, idleTimeoutMs: 10 * 60_000 })), + Effect.scoped, + ); + }), +); + +it.effect( + "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); + 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, + delegatedBy: ThreadId.make("thread-provider-session-manager-deferred-parent"), + }), + 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("eager", "deferred"); + const failedBefore = yield* threadUnloadCount("eager", "failed"); + const counts = Effect.all({ + deferred: Effect.map(threadUnloadCount("eager", "deferred"), (n) => n - deferredBefore), + failed: Effect.map(threadUnloadCount("eager", "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( + Duration.millis(ProviderSessionManager.DELEGATED_CHILD_IDLE_TIMEOUT_MS), + ); + assert.deepEqual(yield* counts, { deferred: 1, failed: 0 }); + 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( + Duration.millis(ProviderSessionManager.DELEGATED_CHILD_IDLE_TIMEOUT_MS), + ); + assert.deepEqual(yield* counts, { deferred: 2, failed: 1 }); + assert.deepEqual((yield* Ref.get(state)).unloadedNativeThreadIds, []); + }); + + yield* effect.pipe( + Effect.provide( + layerTest({ + state, + idleTimeoutMs: 10 * 60_000, + 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 94c38045a5d13..ffafbbef7fb32 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, @@ -56,6 +57,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,8 +243,18 @@ interface IdleThreadUnload { readonly providerThread: OrchestrationV2ProviderThread; readonly generation: number; readonly fiber: Fiber.Fiber | null; + readonly delegatedChild: boolean; } +interface IdleThreadUnloadAttempt { + readonly providerSessionId: ProviderSessionId; + readonly threadId: ThreadId; + readonly generation: number; + readonly delegatedChild: boolean; +} + +type IdleThreadUnloadOutcome = "unloaded" | "deferred" | "skipped" | "failed"; + type ProviderSessionEventSignal = | { readonly type: "event"; readonly event: ProviderAdapter.ProviderAdapterV2Event } | { @@ -1515,6 +1528,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,12 +1546,18 @@ export const layerWithOptions = ( providerThread: input.providerThread, generation: (current?.generation ?? 0) + 1, fiber: null, + delegatedChild: input.delegatedChild ?? current?.delegatedChild ?? false, }), ); yield* cancelIdleFiber(previous?.fiber ?? null); }, ); + 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)); @@ -1548,8 +1568,15 @@ 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( - Effect.andThen(unloadIdleThread({ providerSessionId, threadId, generation })), + const fiber = yield* Effect.sleep(idleUnloadDelay(pending.delegatedChild)).pipe( + Effect.andThen( + unloadIdleThread({ + providerSessionId, + threadId, + generation, + delegatedChild: pending.delegatedChild, + }), + ), Effect.forkIn(layerScope), ); const previous = yield* updateIdleThreadUnload(providerSessionId, threadId, (current) => @@ -1563,19 +1590,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: input.delegatedChild ? ("eager" as const) : ("idle" as const), + }); if ( entry === undefined || pending === undefined || @@ -1584,7 +1612,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 = @@ -1593,7 +1621,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 ( @@ -1616,29 +1644,54 @@ export const layerWithOptions = ( }); return [true, updated] as const; }); - if (!unloading) return "skipped" as const; - yield* unloadThread({ providerThread: pending.providerThread }).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; }, ); + // 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((attempt) => + attempt.outcome === "deferred" + ? Effect.sleep(idleUnloadDelay(input.delegatedChild)).pipe( + Effect.andThen(Effect.suspend(() => unloadIdleThread(input))), + ) + : Effect.void, + ), + ); + const observeActivity = ( providerSessionId: ProviderSessionId, activity: Effect.Effect, @@ -1828,6 +1881,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,