diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 9dc129c7aa0d8..e938fbac3df69 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2172,7 +2172,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const makeWakeHarnessWithOptions = (options?: { readonly close?: (sdkMessages: Queue.Queue) => Effect.Effect; - readonly interrupt?: Effect.Effect; + readonly interrupt?: Effect.Effect; readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"]; readonly stopTask?: ( taskId: string, @@ -3454,6 +3454,301 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each(["hang", "error"] as const)( + "closes the query and permits another turn when Claude interrupt returns %s", + (behavior) => + Effect.gen(function* () { + const interruptStarted = yield* Deferred.make(); + const queryClosed = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + interrupt: Deferred.succeed(interruptStarted, undefined).pipe( + Effect.andThen( + behavior === "hang" + ? Effect.never + : Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "interrupt", + cause: new Error("Claude transport stopped responding"), + }), + ), + ), + ), + close: (sdkMessages) => + Queue.shutdown(sdkMessages).pipe( + Effect.andThen(Deferred.succeed(queryClosed, undefined)), + ), + }); + const attemptId = RunAttemptId.make("attempt-claude-unresponsive-interrupt"); + const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Stop this task.", + attachments: [], + }), + ); + const interrupt = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* Deferred.await(interruptStarted); + yield* TestClock.adjust("5 seconds"); + yield* Deferred.await(queryClosed); + yield* Fiber.join(interrupt); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "interrupted"); + assert.lengthOf(harness.terminalEvents(), 1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-after-unresponsive-interrupt"), + providerTurnOrdinal: 2, + text: "Start fresh.", + attachments: [], + }), + ); + assert.lengthOf(harness.offeredMessages, 2); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + TestClock.layer(), + ), + ), + ), + ); + + it.effect.each(["close", "stream"] as const)( + "terminalizes Stop when Claude %s shutdown does not finish", + (behavior) => + Effect.gen(function* () { + const closeStarted = yield* Deferred.make(); + const closeGate = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: () => + Deferred.succeed(closeStarted, undefined).pipe( + Effect.andThen(behavior === "close" ? Deferred.await(closeGate) : Effect.void), + ), + }); + const attemptId = RunAttemptId.make("attempt-claude-unresponsive-close"); + const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Stop this task.", + attachments: [], + }), + ); + const interrupt = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* Deferred.await(closeStarted); + yield* TestClock.adjust("10 seconds"); + yield* Fiber.join(interrupt); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "interrupted"); + assert.lengthOf(harness.terminalEvents(), 1); + yield* Deferred.succeed(closeGate, undefined); + yield* Queue.shutdown(harness.sdkMessages); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + TestClock.layer(), + ), + ), + ), + ); + + it.effect.each([{ status: "compacting" }, { status: "requesting" }] as const)( + "terminalizes a stalled Claude $status phase and marks its session invalid", + (input) => + Effect.gen(function* () { + const closeRequested = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Deferred.succeed(closeRequested, undefined).pipe( + Effect.andThen(Queue.shutdown(sdkMessages)), + ), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`attempt-claude-stalled-${input.status}`), + text: input.status === "compacting" ? "/compact" : "Continue.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: input.status, + uuid: `status-${input.status}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + + yield* TestClock.adjust("2 minutes"); + yield* Deferred.await(closeRequested); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status === "failed") { + assert.equal(terminal.failure.code, "native_session_stalled"); + assert.equal(terminal.failure.retryable, true); + } + assert.lengthOf(harness.terminalEvents(), 1); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + TestClock.layer(), + ), + ), + ), + ); + + it.effect("does not let rate-limit telemetry extend a stalled request deadline", () => + Effect.gen(function* () { + const closeRequested = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Deferred.succeed(closeRequested, undefined).pipe( + Effect.andThen(Queue.shutdown(sdkMessages)), + ), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-stalled-through-rate-limit-event"), + text: "Continue.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "requesting", + uuid: "status-requesting-before-rate-limit-event", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* TestClock.adjust("1 minute"); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "rate_limit_event", + rate_limit_info: { status: "allowed" }, + uuid: "00000000-0000-4000-8000-0000000002f3", + session_id: WAKE_NATIVE_SESSION, + }), + ); + + yield* TestClock.adjust("1 minute"); + assert.isTrue(yield* Deferred.isDone(closeRequested)); + yield* Deferred.await(closeRequested); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "failed"); + if (terminal.status === "failed") { + assert.equal(terminal.failure.code, "native_session_stalled"); + } + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + TestClock.layer(), + ), + ), + ), + ); + + it.effect("keeps a completed Claude compaction from tripping the stall timeout", () => + Effect.gen(function* () { + const closeRequested = yield* Deferred.make(); + const harness = yield* makeWakeHarnessWithOptions({ + close: () => Deferred.succeed(closeRequested, undefined), + }); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-completed-compaction-timeout"), + text: "/compact", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "status-completing-compaction", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* TestClock.adjust("1 minute"); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "manual", pre_tokens: 1500, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-0000000002f1", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* TestClock.adjust("2 minutes"); + assert.isFalse(yield* Deferred.isDone(closeRequested)); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-0000000002f2", + result: "Compacted conversation.", + }), + ); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "completed"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + TestClock.layer(), + ), + ), + ), + ); + it.effect.each(["completed", "interrupted"] as const)( "projects Claude thinking blocks when %s", (status) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 9dea43bf9e710..8a50e3f5f8118 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -176,6 +176,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import { makeProviderFailure, makeProviderRetryTurnItem, + NATIVE_SESSION_STALLED_FAILURE_CODE, } from "@t3tools/provider-core/server/failure"; import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition"; import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt"; @@ -312,6 +313,7 @@ const WORKFLOW_MEMBER_TRANSCRIPT_FLUSH_MS = 500; // A steer waits at most this long, from its request, for its foreground // subagents to move to the background before it is sent. const BACKGROUND_MOVE_TIMEOUT_MS = 5_000; +const CLAUDE_STALLED_PHASE_TIMEOUT = "2 minutes"; const CLAUDE_GROUP_WATCH_SCRIPT = [ "{ trap '' TERM; read -r _ <&3; kill -TERM 0; sleep 5; kill -KILL 0; } /dev/null 2>&1 &", @@ -3477,6 +3479,13 @@ interface ActiveClaudeTurnContext { nativeWakeStarted: boolean; gatedFramesBeforeEcho: number; readonly heldRootFrames: Array; + stalledPhase: ClaudeStalledPhase | null; +} + +type ClaudeStalledPhaseKind = "compaction" | "request"; + +interface ClaudeStalledPhase { + readonly kind: ClaudeStalledPhaseKind; } interface ActiveClaudeProviderRetry { @@ -3519,6 +3528,10 @@ interface ClaudeLiveQueryContext { receivedInit: boolean; permissionMode: PermissionMode; stopping: boolean; + terminalFailure: OrchestrationV2ProviderFailure | undefined; + // Registry entries still running when this process opened. Their process + // is gone and never reports their end; any later task_started replaces the + // entry, so an entry still in this set runs nowhere. readonly subagentsFromEarlierProcesses: ReadonlySet; } @@ -7031,10 +7044,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ...(interrupted ? {} : { - failure: makeProviderFailure({ - cause: cause === undefined ? undefined : Cause.squash(cause), - class: "transport_error", - }), + failure: + closedQuery.terminalFailure ?? + makeProviderFailure({ + cause: cause === undefined ? undefined : Cause.squash(cause), + class: "transport_error", + }), }), }); } else { @@ -8724,6 +8739,98 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); + const stalledPhaseFailure = (kind: ClaudeStalledPhaseKind) => + makeProviderFailure({ + class: "transport_error", + code: NATIVE_SESSION_STALLED_FAILURE_CODE, + message: + kind === "compaction" + ? "Claude context compaction made no progress for two minutes. T3 closed the stalled session; the next turn will continue in a fresh Claude session." + : "Claude returned no model or tool activity for two minutes. T3 closed the stalled session; the next turn will continue in a fresh Claude session.", + retryable: true, + }); + + const closeStalledQuery = Effect.fn("ClaudeAdapterV2.closeStalledQuery")(function* ( + context: ActiveClaudeTurnContext, + liveQuery: ClaudeLiveQueryContext, + phase: ClaudeStalledPhase, + ) { + if ( + (yield* Ref.get(activeTurn)) !== context || + (yield* Ref.get(queryContext)) !== liveQuery || + context.stalledPhase !== phase + ) { + return; + } + context.stalledPhase = null; + liveQuery.terminalFailure = stalledPhaseFailure(phase.kind); + yield* Effect.logWarning("orchestration-v2.claude-stalled-phase-timeout", { + providerSessionId: input.providerSessionId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeThreadId: context.nativeThreadId, + phase: phase.kind, + }); + const closed = yield* liveQuery.query.close.pipe( + Effect.ignore, + Effect.andThen(Deferred.await(liveQuery.closed)), + Effect.timeoutOption("10 seconds"), + ); + if (Option.isSome(closed)) return; + + yield* Effect.logWarning("orchestration-v2.claude-stalled-query-close-timeout", { + providerSessionId: input.providerSessionId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeThreadId: context.nativeThreadId, + phase: phase.kind, + }); + const ownsLiveQuery = yield* Ref.modify(queryContext, (current) => + current?.query === liveQuery.query ? [true, null] : [false, current], + ); + if (ownsLiveQuery) { + yield* finalizeActiveTurnAfterQueryExit(liveQuery); + yield* endSubagentCallsOfClosedQuery(liveQuery.nativeThreadId, "failed"); + } + yield* Deferred.succeed(liveQuery.closed, undefined); + }); + + // This runs for every SDK frame, including streaming events; avoid a span per frame. + const observeClaudeStalledPhase = Effect.fnUntraced(function* (observation: { + readonly query: ClaudeAgentSdkQuerySession; + readonly message: SDKMessage; + }) { + const context = yield* Ref.get(activeTurn); + const liveQuery = yield* Ref.get(queryContext); + if (context === null || liveQuery?.query !== observation.query) return; + const message = observation.message; + const kind: ClaudeStalledPhaseKind | null = + message.type === "system" && + message.subtype === "status" && + message.status === "compacting" + ? "compaction" + : (message.type === "system" && + message.subtype === "status" && + message.status === "requesting") || + (message.type === "system" && message.subtype === "api_retry") + ? "request" + : null; + if (kind === null) { + if (message.type === "rate_limit_event") return; + context.stalledPhase = null; + return; + } + if (context.stalledPhase?.kind === kind) return; + + const phase: ClaudeStalledPhase = { kind }; + context.stalledPhase = phase; + yield* Effect.sleep(CLAUDE_STALLED_PHASE_TIMEOUT).pipe( + Effect.andThen(closeStalledQuery(context, liveQuery, phase)), + Effect.forkIn(sessionScope), + ); + }); + + // Gives held root output to the pending prompt turn. const releaseHeldRootFrames = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, ) { @@ -8743,6 +8850,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly message: SDKMessage; }) { const message = input.message; + yield* observeClaudeStalledPhase(input); const context = yield* Ref.get(activeTurn); const liveQuery = yield* Ref.get(queryContext); if ( @@ -9413,6 +9521,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( receivedInit: false, permissionMode: queryOptions.permissionMode, stopping: false, + terminalFailure: undefined, subagentsFromEarlierProcesses: new Set( [...(yield* Ref.get(sessionSubagentsByTaskId)).values()].filter( (subagent) => subagent.task.status === "running", @@ -9580,6 +9689,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeWakeStarted: false, gatedFramesBeforeEcho: 0, heldRootFrames: [], + stalledPhase: null, }; const attachTurn = Effect.gen(function* () { querySession.lastTurn = context; @@ -9822,9 +9932,30 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( next.add(turnInput.providerTurnId); return next; }); - yield* existing.query.interrupt; - yield* existing.query.close.pipe(Effect.ignore); - const closed = yield* Deferred.await(existing.closed).pipe( + existing.stopping = true; + yield* existing.query.interrupt.pipe( + Effect.timeoutOption("5 seconds"), + Effect.tap((interrupted) => + Option.isNone(interrupted) + ? Effect.logWarning("orchestration-v2.claude-query-interrupt-request-timeout", { + providerSessionId: input.providerSessionId, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + }) + : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.claude-query-interrupt-request-failed", { + providerSessionId: input.providerSessionId, + providerThreadId: turnInput.providerThread.id, + providerTurnId: turnInput.providerTurnId, + cause, + }), + ), + ); + const closed = yield* existing.query.close.pipe( + Effect.ignore, + Effect.andThen(Deferred.await(existing.closed)), Effect.timeoutOption("10 seconds"), ); if (Option.isSome(closed)) { @@ -10019,8 +10150,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } existing.stopping = true; - yield* existing.query.close.pipe(Effect.ignore); - const closed = yield* Deferred.await(existing.closed).pipe( + const closed = yield* existing.query.close.pipe( + Effect.ignore, + Effect.andThen(Deferred.await(existing.closed)), Effect.timeoutOption("10 seconds"), ); if (Option.isSome(closed)) { diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index 6e0dd990ce388..0acbbf9337e0c 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -12,6 +12,8 @@ import { ProviderInstanceId, ProviderSessionId, ProviderThreadId, + ProviderTurnId, + RunAttemptId, RunId, RuntimeRequestId, ThreadId, @@ -30,6 +32,11 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as EventSink from "./EventSink.ts"; import * as EventStore from "./EventStore.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { + makeProviderFailure, + makeProviderFailureTurnItem, + NATIVE_SESSION_STALLED_FAILURE_CODE, +} from "@t3tools/provider-core/server/failure"; import * as ProviderRuntimeRecovery from "./ProviderRuntimeRecoveryService.ts"; import { restartContinuationRun } from "./RestartContinuation.ts"; @@ -369,6 +376,92 @@ it.effect("selects unfinished recovery work without reading settled thread histo }).pipe(Effect.provide(layerTest)), ); +it.effect("retains stalled native-session evidence for the next run", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = yield* createThread("stalled-native-session"); + const previousRootNodeId = NodeId.make("node:recovery:stalled-native-session"); + const previousAttemptId = RunAttemptId.make("attempt:recovery:stalled-native-session"); + const providerThreadId = ProviderThreadId.make( + "provider-thread:recovery:stalled-native-session", + ); + const providerTurnId = ProviderTurnId.make("provider-turn:recovery:stalled-native-session"); + const previousRunId = yield* createRun(threadId, "failed", { + rootNodeId: previousRootNodeId, + activeAttemptId: previousAttemptId, + providerThreadId, + completedAt: now, + }); + yield* projections.apply({ + id: EventId.make("event:recovery:stalled-native-session:attempt"), + type: "run-attempt.created", + threadId, + runId: previousRunId, + nodeId: previousRootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: previousAttemptId, + nativeThreadId: "native:recovery:stalled-native-session", + runId: previousRunId, + attemptOrdinal: 1, + rootNodeId: previousRootNodeId, + providerInstanceId, + providerThreadId, + providerTurnId, + reason: "initial", + status: "failed", + startedAt: now, + completedAt: now, + }, + }); + const stalledFailure = makeProviderFailureTurnItem({ + driver, + threadId, + runId: previousRunId, + nodeId: previousRootNodeId, + providerThreadId, + providerTurnId, + itemOrdinal: 1, + failure: makeProviderFailure({ + class: "transport_error", + code: NATIVE_SESSION_STALLED_FAILURE_CODE, + retryable: true, + }), + occurredAt: now, + }); + yield* projections.apply({ + id: EventId.make("event:recovery:stalled-native-session:error"), + type: "turn-item.updated", + threadId, + runId: previousRunId, + nodeId: previousRootNodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: stalledFailure, + }); + yield* createRun(threadId, "starting", { + ordinal: 2, + providerThreadId, + completedAt: null, + }); + + const recovery = yield* projections.getRuntimeRecoveryProjection(threadId); + + assert.deepEqual( + recovery.attempts.map((attempt) => attempt.id), + [previousAttemptId], + ); + assert.deepEqual( + recovery.turnItems.map((item) => item.id), + [stalledFailure.id], + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("recovers terminal subagent results until their cross-thread transfer exists", () => Effect.gen(function* () { const projections = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 700395facd79d..3d2a8de285c14 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1,4 +1,5 @@ import { pendingGuestMessageCount } from "@t3tools/contracts"; +import { NATIVE_SESSION_STALLED_FAILURE_CODE } from "@t3tools/provider-core/server/failure"; import { applyThreadPullRequestLinkUpdate } from "../sourceControl/threadPullRequests.ts"; import { projectTurnItemForWire } from "./WireProjection.ts"; import * as Stream from "effect/Stream"; @@ -4456,6 +4457,14 @@ export const layer: Layer.Layer = AND item.status IN ('pending', 'running', 'waiting') AND item.run_id IS NOT NULL ) + OR run.run_id IN ( + SELECT item.run_id FROM orchestration_v2_projection_turn_items AS item + WHERE item.thread_id = ${threadId} + AND item.type = 'error' + AND item.status = 'failed' + AND item.run_id IS NOT NULL + AND json_extract(item.payload_json, '$.failure.code') = ${NATIVE_SESSION_STALLED_FAILURE_CODE} + ) ) ORDER BY run.ordinal ASC `, @@ -4467,6 +4476,13 @@ export const layer: Layer.Layer = SELECT run_id FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} AND status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + UNION + SELECT item.run_id FROM orchestration_v2_projection_turn_items AS item + WHERE item.thread_id = ${threadId} + AND item.type = 'error' + AND item.status = 'failed' + AND item.run_id IS NOT NULL + AND json_extract(item.payload_json, '$.failure.code') = ${NATIVE_SESSION_STALLED_FAILURE_CODE} ) ORDER BY attempt.run_id ASC, attempt.attempt_ordinal ASC `, @@ -4634,23 +4650,32 @@ export const layer: Layer.Layer = sql` SELECT item.payload_json FROM orchestration_v2_projection_turn_items AS item WHERE item.thread_id = ${threadId} - AND item.status IN ('pending', 'running', 'waiting') AND ( - item.run_id IN ( - SELECT run_id FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} - AND status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + ( + item.status IN ('pending', 'running', 'waiting') + AND ( + item.run_id IN ( + SELECT run_id FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + AND status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + ) + OR item.type IN ('command_execution', 'dynamic_tool', 'subagent') + OR ( + item.run_id IS NULL + AND item.node_id IN ( + SELECT node_id FROM orchestration_v2_projection_nodes + WHERE thread_id = ${threadId} + AND run_id IS NULL + AND kind = 'root_turn' + AND status IN ('pending', 'running', 'waiting') + ) + ) + ) ) - OR item.type IN ('command_execution', 'dynamic_tool', 'subagent') OR ( - item.run_id IS NULL - AND item.node_id IN ( - SELECT node_id FROM orchestration_v2_projection_nodes - WHERE thread_id = ${threadId} - AND run_id IS NULL - AND kind = 'root_turn' - AND status IN ('pending', 'running', 'waiting') - ) + item.type = 'error' + AND item.status = 'failed' + AND json_extract(item.payload_json, '$.failure.code') = ${NATIVE_SESSION_STALLED_FAILURE_CODE} ) ) ORDER BY item.ordinal ASC, item.turn_item_id ASC diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 18d217403b393..f9f38b4e4b018 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -39,6 +39,11 @@ import * as ServerSettings from "../serverSettings.ts"; import * as ContextHandoffService from "./ContextHandoffService.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { + makeProviderFailure, + makeProviderFailureTurnItem, + NATIVE_SESSION_STALLED_FAILURE_CODE, +} from "@t3tools/provider-core/server/failure"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; @@ -270,6 +275,7 @@ function makeLocalCommandHarness(input: { readonly interruptRunBeforeOpenFailure?: boolean; readonly writeFailure?: unknown; readonly failReadsAfterRunning?: boolean; + readonly stalledNativeSession?: boolean; readonly previousTurn?: { readonly runStatus: "failed" | "completed"; readonly turnStatus: "running" | "completed" | "interrupted"; @@ -678,15 +684,21 @@ function makeLocalCommandHarness(input: { m.role === "user" && (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), ), + turnItems: projection.turnItems.filter((item) => item.runId === runId), }), ); const layer = ProviderTurnStart.layer.pipe( Layer.provide( Layer.mergeAll( - Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({ - prepareProviderHandoff: () => Effect.die("history read must fail first"), + input.stalledNativeSession === true + ? ContextHandoffService.layer.pipe(Layer.provide(IdAllocator.layer)) + : Layer.mock(ContextHandoffService.ContextHandoffServiceV2)({ + prepareProviderHandoff: () => Effect.die("history read must fail first"), + }), + Layer.mock(EventSink.EventSinkV2)({ + write: () => Effect.succeed([]), + writeIfRunCurrent, }), - Layer.mock(EventSink.EventSinkV2)({ writeIfRunCurrent }), IdAllocator.layer, layerWorktreeLocation(input.worktreesDir), input.fileSystem === undefined @@ -704,21 +716,58 @@ function makeLocalCommandHarness(input: { getThreadRecords, getTurnStartContext, getRuntimeRecoveryProjection: () => - Effect.as(failReadIfRunning, { - ...projection, - hasConversation: projection.messages.some( - (m) => - m.role === "user" && - (m.text.trim().toLowerCase() !== "/compact" || m.attachments.length > 0), - ), - }), - getTurnStartHistory: () => - Effect.fail( - new ProjectionStore.ProjectionStoreReadError({ - threadId, - cause: input.historyReadFailureAfterFallback, - }), + Effect.as( + failReadIfRunning, + (() => { + if (input.stalledNativeSession !== true) return projection; + const stalledRunIds = new Set( + projection.turnItems.flatMap((item) => + item.type === "error" && + item.status === "failed" && + item.runId !== null && + item.failure.code === NATIVE_SESSION_STALLED_FAILURE_CODE + ? [item.runId] + : [], + ), + ); + const activeRunIds = new Set( + projection.runs.flatMap((candidate) => + candidate.status === "queued" || + candidate.status === "preparing" || + candidate.status === "starting" || + candidate.status === "running" || + candidate.status === "waiting" + ? [candidate.id] + : [], + ), + ); + return { + ...projection, + attempts: projection.attempts.filter( + (attempt) => + activeRunIds.has(attempt.runId) || stalledRunIds.has(attempt.runId), + ), + turnItems: projection.turnItems.filter( + (item) => + item.status === "pending" || + item.status === "running" || + item.status === "waiting" || + (item.type === "error" && + item.status === "failed" && + item.failure.code === NATIVE_SESSION_STALLED_FAILURE_CODE), + ), + }; + })(), ), + getTurnStartHistory: () => + input.stalledNativeSession === true + ? Effect.succeed(projection.turnItems) + : Effect.fail( + new ProjectionStore.ProjectionStoreReadError({ + threadId, + cause: input.historyReadFailureAfterFallback, + }), + ), }), Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open, @@ -794,6 +843,88 @@ effectIt.effect("recovers an abandoned failed turn before continuing its native }), ); +effectIt.effect("starts a fresh native session after a previous run stalled", () => + Effect.gen(function* () { + const harness = makeLocalCommandHarness({ + text: "Continue", + stalledNativeSession: true, + previousTurn: { runStatus: "failed", turnStatus: "completed" }, + }); + const projection = harness.projection(); + const previousRun = projection.runs.find((candidate) => candidate.ordinal === 1)!; + const currentAttempt = projection.attempts[0]!; + const providerThread = projection.providerThreads[0]!; + const previousProviderTurn = projection.providerTurns[0]!; + const previousAttempt: OrchestrationV2ThreadProjection["attempts"][number] = { + ...currentAttempt, + id: RunAttemptId.make("previous-failed-attempt"), + runId: previousRun.id, + rootNodeId: previousProviderTurn.nodeId, + providerThreadId: providerThread.id, + providerTurnId: previousProviderTurn.id, + status: "failed", + nativeThreadId: "existing-native-conversation", + startedAt: projection.updatedAt, + completedAt: projection.updatedAt, + }; + const stalledFailure = makeProviderFailureTurnItem({ + driver: providerThread.driver, + threadId: projection.thread.id, + runId: previousRun.id, + nodeId: previousRun.rootNodeId, + providerThreadId: providerThread.id, + providerTurnId: previousProviderTurn.id, + itemOrdinal: 1, + failure: makeProviderFailure({ + class: "transport_error", + code: NATIVE_SESSION_STALLED_FAILURE_CODE, + retryable: true, + }), + occurredAt: projection.updatedAt, + }); + harness.setProjection({ + ...projection, + attempts: [previousAttempt, ...projection.attempts], + turnItems: [stalledFailure], + }); + + const resumeThread = vi.fn(() => Effect.succeed(providerThread)); + const ensureThread = vi.fn( + ({ existingProviderThread }: ProviderAdapter.ProviderAdapterV2EnsureThreadInput) => + Effect.succeed({ + ...existingProviderThread, + nativeThreadRef: { + driver: providerThread.driver, + nativeId: "fresh-native-conversation", + strength: "strong" as const, + }, + }), + ); + const open = harness.open.getMockImplementation()!; + harness.open.mockImplementation(() => + open().pipe( + Effect.map((session) => ({ ...(session as object), ensureThread, resumeThread }) as never), + ), + ); + + yield* harness.start; + + expect(resumeThread).not.toHaveBeenCalled(); + expect(ensureThread).toHaveBeenCalledWith( + expect.objectContaining({ + existingProviderThread: expect.objectContaining({ nativeThreadRef: null }), + }), + ); + expect(harness.startRootRun).toHaveBeenCalledWith( + expect.objectContaining({ + providerThread: expect.objectContaining({ + nativeThreadRef: expect.objectContaining({ nativeId: "fresh-native-conversation" }), + }), + }), + ); + }), +); + effectIt.effect.each([ { runStatus: "failed", turnStatus: "completed" }, { runStatus: "completed", turnStatus: "completed" }, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 6b851bb26a230..4731d50647462 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -50,6 +50,7 @@ import * as ProviderSessionManager from "./ProviderSessionManager.ts"; import { knownProviderFailureMessage, makeProviderFailure, + nativeSessionInvalidatedByProviderFailure, } from "@t3tools/provider-core/server/failure"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; @@ -530,9 +531,11 @@ export const layer: Layer.Layer< runs: current.runs, turnItems: current.turnItems, }); - const inheritedBackgroundTurnItems = yield* projectionStore - .getRuntimeRecoveryProjection(projection.thread.id) - .pipe(Effect.map(selectInheritedBackgroundItems)); + const runtimeRecoveryProjection = yield* projectionStore.getRuntimeRecoveryProjection( + projection.thread.id, + ); + const inheritedBackgroundTurnItems = + selectInheritedBackgroundItems(runtimeRecoveryProjection); const providerSessionId = providerThread.providerSessionId; const runControls = makeRunControls({ threadId: projection.thread.id, @@ -751,15 +754,26 @@ export const layer: Layer.Layer< handoff.delivery?.nativeThreadId === providerThread.nativeThreadRef?.nativeId && handoff.delivery?.status === "pending", ); + const providerNativeThreadId = providerThread.nativeThreadRef?.nativeId; + const invalidatedNativeSession = + providerNativeThreadId != null && + nativeSessionInvalidatedByProviderFailure({ + providerThreadId: providerThread.id, + nativeThreadId: providerNativeThreadId, + attempts: runtimeRecoveryProjection.attempts, + turnItems: runtimeRecoveryProjection.turnItems, + }); const resumed = yield* Effect.result( - uncertainDelivery + uncertainDelivery || invalidatedNativeSession ? Effect.fail( new ProviderAdapter.ProviderAdapterTurnStartError({ driver: session.driver, threadId: projection.thread.id, providerThreadId: providerThread.id, runId, - cause: "Uncertain native history injection", + cause: uncertainDelivery + ? "Uncertain native history injection" + : "Native provider session invalidated after a stalled turn", }), ) : session.resumeThread({ @@ -777,7 +791,11 @@ export const layer: Layer.Layer< driver: session.driver, providerThreadId: providerThread.id, runId, - reason: uncertainDelivery ? "uncertain_history_delivery" : "resume_failed", + reason: uncertainDelivery + ? "uncertain_history_delivery" + : invalidatedNativeSession + ? "native_session_invalidated" + : "resume_failed", errorTag: resumed.failure._tag, }); const replacement = yield* loadFromProvider( diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index 16f0f871ccc26..3a5690666b2c7 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -9,15 +9,16 @@ import { } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; -import * as Effect from "effect/Effect"; import { makeProviderFailure, makeProviderFailureTurnItem, MAX_PROVIDER_FAILURE_MESSAGE_LENGTH, + nativeSessionInvalidatedByProviderFailure, + NATIVE_SESSION_STALLED_FAILURE_CODE, + providerFailureInvalidatesNativeSession, ContextHandoffBudgetError, } from "./failure.ts"; -import * as IdAllocator from "./IdAllocator.ts"; import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; it("redacts credentials and URL secrets from provider failures", () => { @@ -174,42 +175,92 @@ it("does not serialize arbitrary provider causes", () => { }); }); -it.effect("keys terminal failure items by provider turn across retries and fallback paths", () => - Effect.gen(function* () { - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const driver = ProviderDriverKind.make("codex"); - const runId = RunId.make("run:provider-failure-id"); - const base = { - idAllocator, - driver, - threadId: ThreadId.make("thread:provider-failure-id"), - runId, - nodeId: NodeId.make("node:provider-failure-id"), - providerThreadId: ProviderThreadId.make("provider-thread:provider-failure-id"), - itemOrdinal: 101, - failure: makeProviderFailure({ message: "Provider failed" }), - occurredAt: DateTime.makeUnsafe("2026-06-22T12:00:00.000Z"), - } as const; - const firstTurnId = ProviderTurnId.make("provider-turn:provider-failure-id:first"); - const secondTurnId = ProviderTurnId.make("provider-turn:provider-failure-id:second"); - - const firstAttempt = makeProviderFailureTurnItem({ - ...base, - providerTurnId: firstTurnId, - }); - const retriedAttempt = makeProviderFailureTurnItem({ - ...base, - providerTurnId: secondTurnId, - }); - const ingestorFallback = makeProviderFailureTurnItem({ - ...base, - runId: null, - nodeId: null, - providerTurnId: firstTurnId, - }); - - assert.notEqual(firstAttempt.id, retriedAttempt.id); - assert.equal(firstAttempt.id, ingestorFallback.id); - assert.equal(firstAttempt.ordinal, 101); - }).pipe(Effect.provide(IdAllocator.layer)), -); +it("marks only stalled native-session failures for replacement", () => { + assert.isTrue( + providerFailureInvalidatesNativeSession( + makeProviderFailure({ code: NATIVE_SESSION_STALLED_FAILURE_CODE }), + ), + ); + assert.isFalse( + providerFailureInvalidatesNativeSession(makeProviderFailure({ code: "api_error_529" })), + ); + assert.isFalse(providerFailureInvalidatesNativeSession(makeProviderFailure({}))); +}); + +it("keys terminal failure items by provider turn across retries and fallback paths", () => { + const driver = ProviderDriverKind.make("codex"); + const runId = RunId.make("run:provider-failure-id"); + const base = { + driver, + threadId: ThreadId.make("thread:provider-failure-id"), + runId, + nodeId: NodeId.make("node:provider-failure-id"), + providerThreadId: ProviderThreadId.make("provider-thread:provider-failure-id"), + itemOrdinal: 101, + failure: makeProviderFailure({ message: "Provider failed" }), + occurredAt: DateTime.makeUnsafe("2026-06-22T12:00:00.000Z"), + } as const; + const firstTurnId = ProviderTurnId.make("provider-turn:provider-failure-id:first"); + const secondTurnId = ProviderTurnId.make("provider-turn:provider-failure-id:second"); + + const firstAttempt = makeProviderFailureTurnItem({ + ...base, + providerTurnId: firstTurnId, + }); + const retriedAttempt = makeProviderFailureTurnItem({ + ...base, + providerTurnId: secondTurnId, + }); + const ingestorFallback = makeProviderFailureTurnItem({ + ...base, + runId: null, + nodeId: null, + providerTurnId: firstTurnId, + }); + + assert.notEqual(firstAttempt.id, retriedAttempt.id); + assert.equal(firstAttempt.id, ingestorFallback.id); + assert.equal(firstAttempt.ordinal, 101); +}); + +it("invalidates only the native session that produced a stalled failure", () => { + const providerThreadId = ProviderThreadId.make("provider-thread:stalled-native-session"); + const runId = RunId.make("run:stalled-native-session"); + const turnItem = makeProviderFailureTurnItem({ + driver: ProviderDriverKind.make("claudeAgent"), + threadId: ThreadId.make("thread:stalled-native-session"), + runId, + nodeId: NodeId.make("node:stalled-native-session"), + providerThreadId, + providerTurnId: ProviderTurnId.make("provider-turn:stalled-native-session"), + itemOrdinal: 1, + failure: makeProviderFailure({ code: NATIVE_SESSION_STALLED_FAILURE_CODE }), + occurredAt: DateTime.makeUnsafe("2026-10-25T08:00:00.000Z"), + }); + const input = { + providerThreadId, + nativeThreadId: "native-session-a", + attempts: [{ runId, providerThreadId, nativeThreadId: "native-session-a" }], + turnItems: [turnItem], + }; + + assert.isTrue(nativeSessionInvalidatedByProviderFailure(input)); + assert.isFalse( + nativeSessionInvalidatedByProviderFailure({ + ...input, + nativeThreadId: "native-session-b", + }), + ); + assert.isFalse( + nativeSessionInvalidatedByProviderFailure({ + ...input, + attempts: [ + { + runId: RunId.make("run:other"), + providerThreadId, + nativeThreadId: "native-session-a", + }, + ], + }), + ); +}); diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index 1fead586062e9..cf0017b276a1d 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -3,6 +3,7 @@ import type { OrchestrationV2ProviderFailure, OrchestrationV2ProviderFailureClass, OrchestrationV2ProviderRetry, + OrchestrationV2RunAttempt, OrchestrationV2TurnItem, ProviderDriverKind, ProviderThreadId, @@ -28,6 +29,7 @@ export class ContextHandoffBudgetError extends Schema.TaggedError + >; + readonly turnItems: ReadonlyArray; +}): boolean { + const invalidatedRunIds = new Set( + input.turnItems.flatMap((item) => + item.type === "error" && + item.status === "failed" && + item.providerThreadId === input.providerThreadId && + item.runId !== null && + providerFailureInvalidatesNativeSession(item.failure) + ? [item.runId] + : [], + ), + ); + return input.attempts.some( + (attempt) => + attempt.providerThreadId === input.providerThreadId && + attempt.nativeThreadId === input.nativeThreadId && + invalidatedRunIds.has(attempt.runId), + ); +} + export function makeProviderFailureTurnItem(input: { readonly driver: ProviderDriverKind; readonly threadId: ThreadId;