diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index afb1d08147111..e59e049c14708 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -6032,6 +6032,230 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("keeps a native Codex capacity reconnect running past the retry watchdog budget", () => + Effect.gen(function* () { + const scenario = "codex-native-capacity-reconnect"; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + { + type: "emit_inbound", + label: "error/capacity-retry-1", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 1/5", + additionalDetails: "Selected model is at capacity. Please try a different model.", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: null } }, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "turn/completed", + afterMs: 11 * 60 * 1000, + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + ], + }); + const retryShown = yield* Deferred.make(); + let interruptCount = 0; + const harness = yield* makeCodexReplayHarness( + transcript, + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? Deferred.succeed(retryShown, undefined) + : Effect.void, + (method) => + Effect.sync(() => { + if (method === "turn/interrupt") interruptCount += 1; + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-${scenario}`), + }), + ); + yield* Deferred.await(retryShown); + yield* TestClock.adjust("10 minutes"); + assert.isEmpty(harness.terminalEvents()); + assert.equal(interruptCount, 0); + yield* TestClock.adjust("1 minute"); + yield* harness.firstTerminal; + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "completed"); + assert.equal(interruptCount, 0); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("resets the retry watchdog window around a native Codex capacity reconnect", () => + Effect.gen(function* () { + const scenario = "codex-capacity-retry-watchdog-reset"; + const nativeThreadId = `native-${scenario}-thread`; + const nativeTurnId = `native-${scenario}-turn`; + const transcript = makeCodexReplayTranscript({ + scenario, + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }), + { + type: "emit_inbound", + label: "error/non-capacity-1", + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 1/5", + additionalDetails: "stream closed before response.completed", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: null } }, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "error/capacity-2", + afterMs: 5 * 60 * 1000, + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 2/5", + additionalDetails: "Selected model is at capacity. Please try a different model.", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: null } }, + }, + }, + }, + }, + { + type: "emit_inbound", + label: "error/non-capacity-3", + afterMs: 7 * 60 * 1000, + frame: { + method: "error", + params: { + threadId: nativeThreadId, + turnId: nativeTurnId, + willRetry: true, + error: { + message: "Reconnecting... 3/5", + additionalDetails: "exceeded retry limit, last status: 429 Too Many Requests", + codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 429 } }, + }, + }, + }, + }, + { + type: "expect_outbound", + label: "turn/interrupt", + frame: { + id: 4, + method: "turn/interrupt", + params: { threadId: nativeThreadId, turnId: nativeTurnId }, + }, + }, + { type: "emit_inbound", label: "turn/interrupt", frame: { id: 4, result: {} } }, + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "interrupted" }), + }, + }, + }, + ], + }); + const retryShown = yield* Deferred.make(); + const interruptSent = yield* Deferred.make(); + let interruptCount = 0; + const harness = yield* makeCodexReplayHarness( + transcript, + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "error" + ? Deferred.succeed(retryShown, undefined) + : Effect.void, + (method) => + Effect.gen(function* () { + if (method === "turn/interrupt") { + interruptCount += 1; + yield* Deferred.succeed(interruptSent, undefined); + } + }), + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + text: "Continue.", + attemptId: RunAttemptId.make(`attempt-${scenario}`), + }), + ); + yield* Deferred.await(retryShown); + // Minute 5: capacity reconnect replaces the non-capacity state; minute 10 must not fire. + yield* TestClock.adjust("10 minutes"); + assert.isEmpty(harness.terminalEvents()); + assert.equal(interruptCount, 0); + // Minute 12: non-capacity 429 retry arrives and gets a fresh 10-minute budget (minute 22). + yield* TestClock.adjust("11 minutes"); + assert.isEmpty(harness.terminalEvents()); + assert.equal(interruptCount, 0); + yield* TestClock.adjust("1 minute"); + yield* harness.firstTerminal; + yield* Deferred.await(interruptSent); + assert.equal(interruptCount, 1); + const terminal = harness.terminalEvents()[0]; + assert.equal(terminal?.status, "failed"); + if (terminal?.status !== "failed") return; + assert.equal(terminal.failure.class, "usage_limit"); + assert.equal(terminal.retry?.attempt, 3); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect.each(["completed", "interrupted"] as const)( "retains Codex reasoning parts when the turn is %s", (terminalStatus) => diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 91dbb2f534970..55027a6c58685 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -1323,6 +1323,31 @@ function codexUsageLimitError( ); } +const CODEX_NATIVE_CAPACITY_DETAILS = new Set([ + "Selected model is at capacity. Please try a different model.", + "Policy-restricted capacity is unavailable. Please try again later.", +]); + +/** + * Codex surfaces server-directed capacity retries (whose Retry-After waits can + * exceed `PROVIDER_RETRY_BUDGET_MS`) through `responseStreamDisconnected` with + * the overload display string in `additionalDetails`. Leave those native waits + * running rather than letting the generic retry watchdog interrupt the turn. + */ +function codexNativeCapacityRetry( + code: string | null, + additionalDetails: string | undefined, +): boolean { + if (code === "serverOverloaded" || code === "policyCapacityUnavailable") { + return true; + } + return ( + code === "responseStreamDisconnected" && + additionalDetails !== undefined && + CODEX_NATIVE_CAPACITY_DETAILS.has(additionalDetails) + ); +} + function codexTerminalFailureClass( errorInfo: CodexErrorInfo | null | undefined, code: string | null, @@ -1433,6 +1458,7 @@ interface ActiveCodexProviderRetry { readonly retry: OrchestrationV2ProviderRetry; readonly failure: OrchestrationV2ProviderFailure; readonly startedAt: DateTime.Utc; + readonly watchdogStartedAt?: DateTime.Utc; readonly itemOrdinal: number; readonly id: TurnItemId | undefined; } @@ -5451,6 +5477,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const itemOrdinal = previous?.itemOrdinal ?? (yield* resolveItemOrdinal(context, codexFailureItemKey(context))); + const nativeCapacityRetry = codexNativeCapacityRetry(code, additionalDetails); + const watchdogStartedAt = nativeCapacityRetry + ? undefined + : (previous?.watchdogStartedAt ?? updatedAt); const state: ActiveCodexProviderRetry = { id: previous === undefined ? codexFailureItemId(context) : previous.id, ...(previous?.context === undefined ? {} : { context: previous.context }), @@ -5465,6 +5495,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( retry, failure, startedAt: previous?.startedAt ?? updatedAt, + ...(watchdogStartedAt === undefined ? {} : { watchdogStartedAt }), itemOrdinal, }; yield* Ref.update(providerRetries, (current) => { @@ -5472,17 +5503,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.set(context.providerTurnId, state); return updated; }); - yield* failStalledProviderRetry(context, state, payload.error.codexErrorInfo).pipe( - // Every notice aims at the same deadline, so repeated notices cannot extend it. - Effect.delay( - Math.max( - 0, - PROVIDER_RETRY_BUDGET_MS - - (DateTime.toEpochMillis(updatedAt) - DateTime.toEpochMillis(state.startedAt)), + if (watchdogStartedAt !== undefined) { + yield* failStalledProviderRetry(context, state, payload.error.codexErrorInfo).pipe( + // Every notice aims at the same deadline, so repeated notices cannot extend it. + Effect.delay( + Math.max( + 0, + PROVIDER_RETRY_BUDGET_MS - + (DateTime.toEpochMillis(updatedAt) - + DateTime.toEpochMillis(watchdogStartedAt)), + ), ), - ), - Effect.forkIn(scope, { startImmediately: true }), - ); + Effect.forkIn(scope, { startImmediately: true }), + ); + } yield* emitProviderEvent({ type: "turn_item.updated", driver: CODEX_PROVIDER,