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..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,6 +13199,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: interruptRequestItem, }); yield* stopRemainingWork(); + const steersCancelled = yield* cancelUndeliveredSteers; yield* Ref.update(effects, (existing) => [ ...existing, { @@ -13169,7 +13215,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ...otherProviderInterrupts, ]); - return undefined; + return !steersCancelled + ? 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..32dd2730f9659 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,122 @@ 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([ + { 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}-${restarting}`, + restarting, + 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.messageId === running || item.messageId === waiting) + ? [[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); + 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"), + threadId, + runId: first.runId, + }); + 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 it.effect.each([false, true])( "refuses a steer after Stop (provider turn ready: %s)",