TypeScript
fix(server): resume fallback keeps the latest turn when an older handoff is pending (#22902)
Theo Browne7ee8a5b12374
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.tsindex 6b851bb26a2..23721c27233 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts@@ -693,6 +693,7 @@ export const layer: Layer.Layer<return undefined;});let effectiveHandoffs = handoffs;+ let resumeFellBack = false;const loadedProviderThread = yield* Effect.gen(function* () {if (nativeForkTransfer !== undefined) {const sourceProjection = yield* projectionStore.getThreadRecords(@@ -818,7 +819,15 @@ export const layer: Layer.Layer<),createdAt,});- effectiveHandoffs = [handoff, ...effectiveHandoffs];+ // Delivery ranks later handoffs as newer history. Pending handoffs from+ // earlier runs predate this summary; handoffs for this run (provider-switch+ // delta, merge-back) are newer and must stay last.+ effectiveHandoffs = [+ ...effectiveHandoffs.filter((candidate) => candidate.targetRunId !== run.id),+ handoff,+ ...effectiveHandoffs.filter((candidate) => candidate.targetRunId === run.id),+ ];+ resumeFellBack = true;yield* eventSink.write({events: [{@@ -1145,8 +1154,11 @@ export const layer: Layer.Layer<...runningProviderThread,contextUsage: handoffUsage,};+ // The resume fallback summary already covers every earlier run in order. A+ // retry copy after it would rank older missed requests as the newest history.const missedRuns = projection.runs.filter((source) =>+ !resumeFellBack &&source.ordinal < run.ordinal &&source.providerThreadId === providerThread.id &&(source.status === "failed" || source.status === "interrupted") &&diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.tsindex 72aae60c0d0..452509bb97b 100644--- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts+++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts@@ -1182,6 +1182,132 @@ describe("orchestration v2 provider switching", () => {),);+ it.live.each(["an older handoff", "a missed request"] as const)(+ "keeps the latest turn when a resume fallback also delivers %s",+ (older) =>+ Effect.scoped(+ Effect.gen(function* () {+ // A run that fails before its provider turn starts is retried as a missed request.+ const missed = older === "a missed request";+ const name = `resume-fallback-handoff-order${missed ? "-missed" : ""}`;+ const cwd = yield* checkpointWorkspace(name);+ const failStartOnce = yield* Ref.make(false);+ const capturedTurns = yield* Ref.make<ReadonlyArray<CapturedTurn>>([]);+ const injectedHistory = yield* Ref.make<ReadonlyArray<unknown>>([]);+ const oldResult = `old result ${"o".repeat(2_500)}`;+ const latestResult = `latest result ${"l".repeat(2_500)}`;+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([+ makeTestAdapter({+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,+ driver: CLAUDE_DRIVER,+ capabilities: ClaudeProviderCapabilitiesV2,+ modelSelection: CLAUDE_MODEL_SELECTION,+ responseByRunOrdinal: { 1: oldResult, 3: latestResult },+ capturedTurns,+ injectedHistory,+ failResume: true,+ ...(missed ? { failStartOnce } : { failedRunOrdinals: new Set([2]) }),+ nativeThreadGeneration: yield* Ref.make(0),+ }),+ ]);+ yield* Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;+ const runAfterDetach = Effect.fn("runAfterDetach")(function* (+ ordinal: number,+ text: string,+ ) {+ const providerSessionId = (yield* orchestrator.getThreadProjection(threadId))+ .providerThreads[0]?.providerSessionId;+ if (providerSessionId != null) {+ yield* orchestrator.dispatch({+ type: "provider-session.detach",+ commandId: CommandId.make(`handoff-order:detach:${ordinal}`),+ threadId,+ providerSessionId,+ });+ yield* worker.drain();+ }+ yield* orchestrator.dispatch({+ type: "message.dispatch",+ commandId: CommandId.make(`handoff-order:${ordinal}`),+ threadId,+ messageId: MessageId.make(`handoff-order:${ordinal}`),+ createdBy: "user",+ creationSource: "web",+ text,+ attachments: [],+ modelSelection: CLAUDE_MODEL_SELECTION,+ dispatchMode: { type: "start_immediately" },+ });+ yield* orchestrator.streamStoredEvents.pipe(+ Stream.filter(+ ({ event }) =>+ event.type === "run.updated" &&+ event.payload.ordinal === ordinal &&+ (event.payload.status === "completed" || event.payload.status === "failed"),+ ),+ Stream.runHead,+ );+ yield* worker.drain();+ });+ yield* orchestrator.dispatch({+ type: "thread.create",+ commandId: CommandId.make("handoff-order:create"),+ threadId,+ projectId,+ createdBy: "user",+ creationSource: "web",+ title: "Resume fallback handoff order",+ modelSelection: CLAUDE_MODEL_SELECTION,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ });+ yield* runAfterDetach(1, `Original brief ${"b".repeat(9_000)}`);+ yield* Ref.set(failStartOnce, missed);+ yield* runAfterDetach(2, missed ? `Request 2 ${"r".repeat(6_000)}` : "Request 2");+ yield* runAfterDetach(3, "Request 3");+ const historyBeforeRun4 = (yield* Ref.get(injectedHistory)).length;+ yield* runAfterDetach(4, "Request 4");++ const projection = yield* orchestrator.getThreadProjection(threadId);+ assert.deepEqual(+ projection.runs.map((run) => run.status),+ ["completed", "failed", "completed", "completed"],+ );+ const run4NativeThreadId = (yield* Ref.get(capturedTurns)).at(-1)?.nativeThreadId;+ assert.equal(+ projection.contextHandoffs.find(+ (handoff) => handoff.targetRunId === projection.runs[1]?.id,+ )?.delivery?.nativeThreadId,+ run4NativeThreadId,+ );+ const run4History = yield* encodeJson(+ (yield* Ref.get(injectedHistory)).slice(historyBeforeRun4),+ );+ assert.include(run4History, "Original brief");+ assert.include(run4History, latestResult);+ }).pipe(+ Effect.provide(+ ProviderReplayHarness.layerWithRegistry(+ {+ name,+ runtimePolicyOverride: {+ cwd,+ approvalPolicy: "never",+ sandboxPolicy: { type: "readOnly" },+ },+ },+ layerRegistry,+ ),+ ),+ );+ }),+ ),+ );+it.live.each([["background work", new ClaudeBackgroundWorkBlocksQueryReplacementError()],["an unreadable append file", new ClaudeAppendSystemPromptFileError({ path: "missing.md" })],