From 0ceed9a2534795a0c11cd7f3e3aa60a5305f7985 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 19:52:47 +0000 Subject: [PATCH 1/3] fix(claude): steers sent during compaction no longer abort it A steer offered at priority "now" while Claude compacts context aborts the compaction, and Claude starts it over. A coordinator thread that other threads steer often could keep restarting its own compaction. steerTurn now waits for the running compaction to end (its status result, its boundary, or the end of the turn) before it offers the steer, and only then reports success. A turn that ends first fails the steer with the existing "ended before the steer was sent" error, so the orchestrator's follow-up path delivers the message and a delegated completion is not acknowledged before Claude has it. A thread's effects run in order, so a waiting steer would keep Stop's interrupt behind it. Stop now cancels steers that have not reached the provider and marks their messages cancelled. Fixes pingdotgg/t3code#25796 Co-Authored-By: Claude Fable 5.2 --- .../Adapters/ClaudeAdapterV2.test.ts | 131 +++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 36 ++++- .../src/orchestration-v2/EffectOutbox.ts | 23 +++ .../src/orchestration-v2/Orchestrator.ts | 47 ++++++- .../SteeringCompletion.integration.test.ts | 65 ++++++++- 5 files changed, 292 insertions(+), 10 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 155370da1757d..dba2aa9fdc331 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3788,10 +3788,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - if (outcome === "release-before") { - yield* Deferred.succeed(release, undefined); - yield* Fiber.join(pending); - } + if (outcome === "release-before") yield* Deferred.succeed(release, undefined); yield* harness.offerAndWait( claudeSdkFrame({ type: "system", @@ -3801,6 +3798,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); + // Ready while compacting, the steer is held until the boundary. + if (outcome === "release-before") yield* Fiber.join(pending); if (outcome === "cancel-after") { yield* Fiber.interrupt(pending); assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(pending))); @@ -5418,6 +5417,130 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #25796 a steer offered while Claude compacts aborts the + // compaction, which then starts over. + it.effect.each(["compact_result", "compact_boundary", "turn end"] as const)( + "holds steers sent during compaction until it ends: %s", + (ending) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attemptId = RunAttemptId.make("attempt-steer-compacting"); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Summarize the long log.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000025796", + text: "Reading.", + }), + user_message_uuids: [harness.promptUuid(0)], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000025797", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const steer = (id: string) => + harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(id), + text: `Steer ${id}`, + attachments: [], + }, + }); + const steerStatus = (id: string) => + harness.events + .flatMap((event) => + event.type === "steer.updated" && event.messageId === id ? [event.status] : [], + ) + .at(-1); + // One after the other, as the effect outbox runs a thread's steers. + const steers = yield* Effect.forkScoped( + Effect.exit(steer("held-first").pipe(Effect.andThen(steer("held-second")))), + ); + yield* harness.until(() => steerStatus("held-first") !== undefined); + assert.lengthOf(harness.offeredMessages, 1); + assert.isUndefined(steers.pollUnsafe()); + + yield* harness.offerAndWait( + ending === "compact_result" + ? claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + compact_result: "success", + uuid: "00000000-0000-4000-8000-000000025798", + session_id: WAKE_NATIVE_SESSION, + }) + : ending === "compact_boundary" + ? claudeSdkFrame({ + type: "system", + subtype: "compact_boundary", + compact_metadata: { trigger: "auto", pre_tokens: 1500, post_tokens: 400 }, + uuid: "00000000-0000-4000-8000-000000025798", + session_id: WAKE_NATIVE_SESSION, + }) + : claudeSdkFrame({ + ...makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000025798", + result: "Summarized.", + }), + user_message_uuid: harness.promptUuid(0), + }), + ); + const exit = yield* Fiber.join(steers); + const steered = harness.offeredMessages + .slice(1) + .map((message) => `${message.priority}:${JSON.stringify(message.message.content)}`); + if (ending === "turn end") { + // Failing, not succeeding unsent, is what makes the orchestrator send it as a follow-up. + assert.match( + Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "sent", + /ended before the steer was sent/, + ); + assert.deepEqual(steered, []); + yield* harness.until(() => steerStatus("held-first") === "completed"); + return; + } + assert.isTrue(Exit.isSuccess(exit)); + assert.lengthOf(steered, 2); + assert.match(steered[0] ?? "", /^now:.*Steer held-first/); + assert.match(steered[1] ?? "", /^now:.*Steer held-second/); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // Claude can answer a steer while its offer is still being logged. it.effect("settles a turn whose result echoes only a steer before the offer returns", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index b3c1fd1c1fed4..1565b9f8f02de 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4755,6 +4755,8 @@ interface ActiveClaudeTurnContext { readonly toolCalls: Map; // A successful status can precede the boundary that supplies its token counts. compaction: Extract | null; + // Set while a compaction runs. A steer offered then aborts it and Claude starts it over. + compactionEnded: Deferred.Deferred | null; readonly ignoredTaskIds: Set; readonly announcedUsageLimits: Set; authenticationFailureMessage: string | undefined; @@ -8636,6 +8638,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( status, }); + const endCompactionHold = (context: ActiveClaudeTurnContext) => + Effect.suspend(() => { + const ended = context.compactionEnded; + context.compactionEnded = null; + return ended === null ? Effect.void : Deferred.succeed(ended, undefined); + }); + const markSteersAccepted = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, message: SDKMessage, @@ -8669,6 +8678,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly result?: SDKResultMessage; }) { input.context.steersClosed = true; + yield* endCompactionHold(input.context); yield* reasoningDeltas.flushTurn(input.context.nativeTurnId); if (input.status === "completed") { yield* assistantDeltas.flushTurn(input.context.nativeTurnId); @@ -10290,6 +10300,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( context.compactionFailure = failed ? { message: message.compact_error } : null; } if (context.compaction?.status === "running") { + yield* endCompactionHold(context); const now = yield* DateTime.now; context.compaction = { ...context.compaction, @@ -10363,6 +10374,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // removes. Pending reservations must survive its boundary too. if (budget !== undefined) budget.compacting = { ...budget.committed }; context.compaction = compaction; + context.compactionEnded ??= yield* Deferred.make(); yield* emitProviderEvent({ type: "turn_item.updated", driver: CLAUDE_PROVIDER, @@ -10370,6 +10382,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); return; } + yield* endCompactionHold(context); const budget = pdfBudgets.get(context.nativeThreadId); if (budget !== undefined) { // Aggregate persisted usage cannot identify attachments in a @@ -12507,6 +12520,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( compactionFailure: null, steeredSegmentUsage: [], steersClosed: false, + compactionEnded: null, steeredLedgerUsage: { inputTokens: 0, outputTokens: 0 }, rootModels: new Set(), subagentsByTaskId: new Map(), @@ -12964,22 +12978,36 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (liveSteerSelection !== undefined) { yield* applySelectionLive(existing, liveSteerSelection); } - // The turn can end while the moves or the selection change are answered. - // A steer offered then would start a new turn the orchestrator never - // asked for, so the steer fails and the orchestrator starts the follow-up turn. + const messageId = turnInput.message.messageId; + // Held here, not acknowledged: the steer succeeds only once Claude has it. + const held = currentTurn.compactionEnded !== null; + if (held) { + yield* emitSteerStatus(currentTurn, messageId, "pending"); + yield* Effect.gen(function* () { + while (currentTurn.compactionEnded !== null) { + yield* Deferred.await(currentTurn.compactionEnded); + } + }).pipe( + Effect.onInterrupt(() => emitSteerStatus(currentTurn, messageId, "completed")), + ); + } + // The turn can end while the moves or the selection change are answered, or + // while the steer is held. A steer offered then would start a new turn the + // orchestrator never asked for, so the steer fails and the orchestrator + // starts the follow-up turn. if ( (yield* Ref.get(activeTurn))?.providerTurnId !== turnInput.providerTurnId || (yield* Ref.get(queryContext)) !== existing || // No yield between this check and the set below. currentTurn.steersClosed ) { + if (held) yield* emitSteerStatus(currentTurn, messageId, "completed"); return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`, }); } // Register before offering: Claude can start the steer and end the turn before offer returns. - const messageId = turnInput.message.messageId; currentTurn.steerUuids.add(steerUuid); currentTurn.pendingSteers.set(steerUuid, { messageId, diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index eb1209158cc74..1f9beb808d318 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -218,6 +218,10 @@ export interface EffectOutboxV2Shape { readonly listByCommandId: ( commandId: CommandId, ) => Effect.Effect, EffectOutboxError>; + readonly listUnsettled: (input: { + readonly threadId: ThreadId; + readonly effectTypes: ReadonlyArray; + }) => Effect.Effect, EffectOutboxError>; readonly cancelUnsettled: (input: { readonly threadId: ThreadId; readonly effectTypes: ReadonlyArray; @@ -464,6 +468,25 @@ export const layer: Layer.Layer = La : new EffectOutboxError({ operation: "list", cause }), ), ), + listUnsettled: ({ threadId, effectTypes }) => + (effectTypes.length === 0 + ? Effect.succeed>([]) + : sql` + SELECT * + FROM orchestration_v2_effect_outbox + WHERE thread_id = ${threadId} + AND status IN ('pending', 'running') + AND effect_type IN ${sql.in(effectTypes)} + ORDER BY rowid ASC + `.pipe(NodeSqliteClient.readOnly) + ).pipe( + Effect.flatMap((rows) => decodeRows("list-unsettled", rows)), + Effect.mapError((cause) => + isEffectOutboxError(cause) + ? cause + : new EffectOutboxError({ operation: "list-unsettled", cause }), + ), + ), cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")( function* ({ threadId, effectTypes, reason }) { if (effectTypes.length === 0) return []; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00f9dfae8d9e1..eab0d724f20f9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -13154,6 +13154,43 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: interruptRequestItem, }); yield* stopRemainingWork(); + // A thread's effects run in order, so a steer still waiting to reach the provider + // (Claude holds steers while it compacts) would keep this interrupt waiting behind it. + const undeliveredSteers = yield* effectOutbox + .listUnsettled({ threadId: command.threadId, effectTypes: ["provider-turn.steer"] }) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + for (const { request } of undeliveredSteers) { + if (request.type !== "provider-turn.steer") continue; + const item = yield* projectionStore + .getTurnItem({ + threadId: command.threadId, + itemId: idAllocator.derive.userTurnItem({ messageId: request.messageId }), + }) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + if ( + item?.type !== "user_message" || + (item.status !== "pending" && item.status !== "completed") + ) { + continue; + } + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + ...(item.runId === null ? {} : { runId: item.runId }), + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now }, + }); + } yield* Ref.update(effects, (existing) => [ ...existing, { @@ -13169,7 +13206,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ...otherProviderInterrupts, ]); - return undefined; + return undeliveredSteers.length === 0 + ? undefined + : ({ + effectTypes: ["provider-turn.steer"], + reason: `Run ${run.id} was stopped before the steer reached its provider.`, + } satisfies { + readonly effectTypes: ReadonlyArray; + readonly reason: string; + }); }); /** Writes a parent's app-owned task, and sets its node and turn items to the task's status. */ diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index acfd20af78749..fffff309e1ebe 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1488,7 +1488,8 @@ it.effect.each(["complete", "stop-before-decline", "stop-after-decline", "queued ); assert.deepEqual( effects.map((effect) => [effect.request.type, effect.status]), - [["provider-turn.steer", "succeeded"]], + // Stop cancels a steer its provider has not answered. + [["provider-turn.steer", timing === "stop-before-decline" ? "cancelled" : "succeeded"]], ); assert.equal(started.length, 1); if (timing === "stop-before-decline") { @@ -2448,6 +2449,68 @@ it.effect("keeps a queued message queued when promoted into a run that Stop reac }), ); +// regression: #25796 a thread's effects run in order, so a steer its provider +// holds (Claude, while it compacts) must not keep Stop waiting behind it. +it.effect("Stop cancels steers that have not reached the provider", () => + Effect.gen(function* () { + const holding = yield* Deferred.make(); + const { started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness( + "stop-undelivered-steers", + false, + true, + Effect.void, + true, + undefined, + () => Deferred.succeed(holding, undefined).pipe(Effect.andThen(Effect.never)), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + for (const id of ["held", "waiting"]) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId, + messageId: MessageId.make(`message:${id}`), + text: id, + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "steer_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + } + const draining = yield* worker.drain().pipe(Effect.forkScoped); + yield* Deferred.await(holding); + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: first.runId, + }); + yield* Fiber.join(draining); + + assert.deepEqual(steered, ["held"]); + assert.lengthOf(interrupted, 1); + const { turnItems } = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + turnItems.flatMap((item) => + item.type === "user_message" && item.inputIntent === "steer" + ? [[item.messageId, item.status]] + : [], + ), + [ + [MessageId.make("message:held"), "cancelled"], + [MessageId.make("message:waiting"), "cancelled"], + ], + ); + }).pipe(Effect.provide(layer)); + }), +); + // regression: #32891 a restart that Stop already reached is lost it.effect.each([false, true])( "refuses a steer after Stop (provider turn ready: %s)", From 1544e0fb8f010f33fa32fa73085b2f827cb99312 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 20:09:24 +0000 Subject: [PATCH 2/3] fix(server): Stop keeps a steer the provider already read as delivered Stop cancelled every unsettled steer effect and marked its message cancelled, but an unsettled effect is not an unread steer: Claude can confirm a steer before the offer call returns. Stop now marks a message cancelled only when the provider still reports it pending or its effect never ran. Co-Authored-By: Claude Fable 5.2 --- .../src/orchestration-v2/Orchestrator.ts | 8 +- .../SteeringCompletion.integration.test.ts | 144 +++++++++++------- 2 files changed, 95 insertions(+), 57 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index eab0d724f20f9..5c472c6c894b0 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -13163,7 +13163,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), ), ); - for (const { request } of undeliveredSteers) { + for (const { request, status, attemptCount } of undeliveredSteers) { if (request.type !== "provider-turn.steer") continue; const item = yield* projectionStore .getTurnItem({ @@ -13175,9 +13175,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), ), ); + // An unsettled effect is not an unread steer: a provider can confirm one before its + // call returns. Only a steer the provider still reports pending, or one whose effect + // never ran, is known not to have been read. + const neverSent = status === "pending" && attemptCount === 0; if ( item?.type !== "user_message" || - (item.status !== "pending" && item.status !== "completed") + !(item.status === "pending" || (neverSent && item.status === "completed")) ) { continue; } diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index fffff309e1ebe..99815e67b5680 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2451,64 +2451,98 @@ it.effect("keeps a queued message queued when promoted into a run that Stop reac // regression: #25796 a thread's effects run in order, so a steer its provider // holds (Claude, while it compacts) must not keep Stop waiting behind it. -it.effect("Stop cancels steers that have not reached the provider", () => - Effect.gen(function* () { - const holding = yield* Deferred.make(); - const { started, steered, interrupted, layer, startFirstTurn } = - yield* nextTurnSelectionHarness( - "stop-undelivered-steers", - false, - true, - Effect.void, - true, - undefined, - () => Deferred.succeed(holding, undefined).pipe(Effect.andThen(Effect.never)), - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const first = started[0]!; - for (const id of ["held", "waiting"]) { +it.effect.each(["pending", "completed"] as const)( + "Stop cancels steers that have not reached the provider (running steer %s)", + (reported) => + Effect.gen(function* () { + let report: ( + turn: ProviderAdapter.ProviderAdapterV2SteerInput, + ) => Effect.Effect = () => Effect.void; + const { events, started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness( + `stop-undelivered-steers-${reported}`, + false, + true, + Effect.void, + true, + undefined, + (turn) => Effect.suspend(() => report(turn)).pipe(Effect.andThen(Effect.never)), + ); + // The provider reports on the steer while its call is still unanswered. + report = (turn) => + Effect.forEach( + reported === "pending" ? (["pending"] as const) : (["pending", "completed"] as const), + (status) => + Queue.offer(events, { + type: "steer.updated", + driver, + threadId: turn.threadId, + runId: turn.runId, + messageId: turn.message.messageId, + status, + }), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const first = started[0]!; + const running = MessageId.make("message:running"); + const waiting = MessageId.make("message:waiting"); + const steerStatuses = Effect.map( + orchestrator.getThreadProjection(threadId), + ({ turnItems }) => + turnItems.flatMap((item) => + item.type === "user_message" && item.inputIntent === "steer" + ? [[item.messageId, item.status]] + : [], + ), + ); + for (const messageId of [running, waiting]) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(messageId), + threadId, + messageId, + text: messageId, + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "steer_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + } + const reportedSteer = yield* orchestrator.streamDomainEvents.pipe( + Stream.filter( + (event) => + event.type === "turn-item.updated" && + event.payload.type === "user_message" && + event.payload.messageId === running && + event.payload.status === reported, + ), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const draining = yield* worker.drain().pipe(Effect.forkScoped); + yield* Fiber.join(reportedSteer); yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make(id), + type: "run.interrupt", + commandId: CommandId.make("stop"), threadId, - messageId: MessageId.make(`message:${id}`), - text: id, - attachments: [], - modelSelection: runSelection, - dispatchMode: { type: "steer_active", targetRunId: first.runId }, - createdBy: "user", - creationSource: "web", + runId: first.runId, }); - } - const draining = yield* worker.drain().pipe(Effect.forkScoped); - yield* Deferred.await(holding); - yield* orchestrator.dispatch({ - type: "run.interrupt", - commandId: CommandId.make("stop"), - threadId, - runId: first.runId, - }); - yield* Fiber.join(draining); - - assert.deepEqual(steered, ["held"]); - assert.lengthOf(interrupted, 1); - const { turnItems } = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual( - turnItems.flatMap((item) => - item.type === "user_message" && item.inputIntent === "steer" - ? [[item.messageId, item.status]] - : [], - ), - [ - [MessageId.make("message:held"), "cancelled"], - [MessageId.make("message:waiting"), "cancelled"], - ], - ); - }).pipe(Effect.provide(layer)); - }), + yield* Fiber.join(draining); + + assert.deepEqual(steered, [running]); + assert.lengthOf(interrupted, 1); + // A steer the provider confirmed stays read; one whose effect never ran is cancelled. + assert.deepEqual(yield* steerStatuses, [ + [running, reported === "pending" ? "cancelled" : "completed"], + [waiting, "cancelled"], + ]); + }).pipe(Effect.provide(layer)); + }), ); // regression: #32891 a restart that Stop already reached is lost From e3dc62c2b0d74d258ec1edaa8de424f2cf5cd4b6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 20:32:55 +0000 Subject: [PATCH 3/3] fix(server): Stop during a pending restart also cancels undelivered steers Stop on a run whose restart has not started its provider turn takes an earlier branch that skipped the steer cancellation, so the interrupt of the superseded turn stayed queued behind a steer held for compaction. Both branches now cancel undelivered steers. Co-Authored-By: Claude Fable 5.2 --- .../src/orchestration-v2/Orchestrator.ts | 91 ++++++++++--------- .../SteeringCompletion.integration.test.ts | 32 +++++-- 2 files changed, 74 insertions(+), 49 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5c472c6c894b0..99d5b6ea064a6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12856,6 +12856,50 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); const emitEvent = emit(events, command); + // A thread's effects run in order, so a steer still waiting to reach the provider + // (Claude holds steers while it compacts) would keep this interrupt waiting behind it. + const cancelUndeliveredSteers = Effect.gen(function* () { + const undeliveredSteers = yield* effectOutbox + .listUnsettled({ threadId: command.threadId, effectTypes: ["provider-turn.steer"] }) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + for (const { request, status, attemptCount } of undeliveredSteers) { + if (request.type !== "provider-turn.steer") continue; + const item = yield* projectionStore + .getTurnItem({ + threadId: command.threadId, + itemId: idAllocator.derive.userTurnItem({ messageId: request.messageId }), + }) + .pipe( + Effect.mapError( + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), + ), + ); + // An unsettled effect is not an unread steer: a provider can confirm one before its + // call returns. Only a steer the provider still reports pending, or one whose effect + // never ran, is known not to have been read. + const neverSent = status === "pending" && attemptCount === 0; + if ( + item?.type !== "user_message" || + !(item.status === "pending" || (neverSent && item.status === "completed")) + ) { + continue; + } + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + ...(item.runId === null ? {} : { runId: item.runId }), + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now }, + }); + } + return undeliveredSteers.length > 0; + }); const interruptRequestItem: OrchestrationV2TurnItem = { id: idAllocator.derive.runSignalTurnItem({ runId: run.id, @@ -13074,9 +13118,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } yield* stopRemainingWork(); + yield* cancelUndeliveredSteers; yield* Ref.update(effects, (existing) => [...existing, ...otherProviderInterrupts]); return { - effectTypes: ["provider-turn.start", "provider-turn.restart"], + effectTypes: ["provider-turn.start", "provider-turn.restart", "provider-turn.steer"], reason: `Run ${run.id} was interrupted before its provider turn started.`, } satisfies { readonly effectTypes: ReadonlyArray; @@ -13154,47 +13199,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: interruptRequestItem, }); yield* stopRemainingWork(); - // A thread's effects run in order, so a steer still waiting to reach the provider - // (Claude holds steers while it compacts) would keep this interrupt waiting behind it. - const undeliveredSteers = yield* effectOutbox - .listUnsettled({ threadId: command.threadId, effectTypes: ["provider-turn.steer"] }) - .pipe( - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), - ), - ); - for (const { request, status, attemptCount } of undeliveredSteers) { - if (request.type !== "provider-turn.steer") continue; - const item = yield* projectionStore - .getTurnItem({ - threadId: command.threadId, - itemId: idAllocator.derive.userTurnItem({ messageId: request.messageId }), - }) - .pipe( - Effect.mapError( - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }), - ), - ); - // An unsettled effect is not an unread steer: a provider can confirm one before its - // call returns. Only a steer the provider still reports pending, or one whose effect - // never ran, is known not to have been read. - const neverSent = status === "pending" && attemptCount === 0; - if ( - item?.type !== "user_message" || - !(item.status === "pending" || (neverSent && item.status === "completed")) - ) { - continue; - } - yield* emitEvent({ - type: "turn-item.updated", - threadId: command.threadId, - ...(item.runId === null ? {} : { runId: item.runId }), - ...(item.nodeId === null ? {} : { nodeId: item.nodeId }), - providerInstanceId: run.providerInstanceId, - occurredAt: now, - payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now }, - }); - } + const steersCancelled = yield* cancelUndeliveredSteers; yield* Ref.update(effects, (existing) => [ ...existing, { @@ -13210,7 +13215,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ...otherProviderInterrupts, ]); - return undeliveredSteers.length === 0 + return !steersCancelled ? undefined : ({ effectTypes: ["provider-turn.steer"], diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 99815e67b5680..32dd2730f9659 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -2451,17 +2451,22 @@ it.effect("keeps a queued message queued when promoted into a run that Stop reac // regression: #25796 a thread's effects run in order, so a steer its provider // holds (Claude, while it compacts) must not keep Stop waiting behind it. -it.effect.each(["pending", "completed"] as const)( - "Stop cancels steers that have not reached the provider (running steer %s)", - (reported) => +it.effect.each([ + { reported: "pending", restarting: false }, + { reported: "completed", restarting: false }, + // Stop then reaches a run whose restart has not started its provider turn yet. + { reported: "pending", restarting: true }, +] as const)( + "Stop cancels steers that have not reached the provider (running steer $reported, restarting: $restarting)", + ({ reported, restarting }) => Effect.gen(function* () { let report: ( turn: ProviderAdapter.ProviderAdapterV2SteerInput, ) => Effect.Effect = () => Effect.void; const { events, started, steered, interrupted, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `stop-undelivered-steers-${reported}`, - false, + `stop-undelivered-steers-${reported}-${restarting}`, + restarting, true, Effect.void, true, @@ -2493,7 +2498,8 @@ it.effect.each(["pending", "completed"] as const)( orchestrator.getThreadProjection(threadId), ({ turnItems }) => turnItems.flatMap((item) => - item.type === "user_message" && item.inputIntent === "steer" + item.type === "user_message" && + (item.messageId === running || item.messageId === waiting) ? [[item.messageId, item.status]] : [], ), @@ -2526,6 +2532,20 @@ it.effect.each(["pending", "completed"] as const)( ); const draining = yield* worker.drain().pipe(Effect.forkScoped); yield* Fiber.join(reportedSteer); + if (restarting) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("restart"), + threadId, + messageId: MessageId.make("message:restart"), + text: "restart", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "restart_active", targetRunId: first.runId }, + createdBy: "user", + creationSource: "web", + }); + } yield* orchestrator.dispatch({ type: "run.interrupt", commandId: CommandId.make("stop"),