From 4600a83e980b06ec387499222122e88c912544ba Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 27 Jul 2026 19:30:29 +0200 Subject: [PATCH] fix(server): preserve imported history across retries and forks Co-authored-by: codex --- .../Orchestrator.migration.test.ts | 34 +++++++++ .../src/orchestration-v2/Orchestrator.ts | 71 ++++++++++++------- .../orchestration-v2/ProjectionStore.test.ts | 48 ++++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 24 +++++-- 4 files changed, 146 insertions(+), 31 deletions(-) create mode 100644 apps/server/src/orchestration-v2/Orchestrator.migration.test.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.migration.test.ts b/apps/server/src/orchestration-v2/Orchestrator.migration.test.ts new file mode 100644 index 0000000000..706f8427ed --- /dev/null +++ b/apps/server/src/orchestration-v2/Orchestrator.migration.test.ts @@ -0,0 +1,34 @@ +import { assert, it } from "@effect/vitest"; + +import { shouldPrepareLegacyImportHandoff } from "./Orchestrator.ts"; + +it("reissues imported context until the provider thread is materialized", () => { + assert.isTrue( + shouldPrepareLegacyImportHandoff({ + historyOrigin: "v1_import", + hasNativeThreadRef: false, + legacyImportItemCount: 2, + }), + ); + assert.isFalse( + shouldPrepareLegacyImportHandoff({ + historyOrigin: "v1_import", + hasNativeThreadRef: true, + legacyImportItemCount: 2, + }), + ); + assert.isFalse( + shouldPrepareLegacyImportHandoff({ + historyOrigin: undefined, + hasNativeThreadRef: false, + legacyImportItemCount: 2, + }), + ); + assert.isFalse( + shouldPrepareLegacyImportHandoff({ + historyOrigin: "v1_import", + hasNativeThreadRef: false, + legacyImportItemCount: 0, + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 5e7fe4c7f8..16068de0b2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -42,7 +42,12 @@ import { EventSinkV2 } from "./EventSink.ts"; import type { OrchestrationEffectRequestV2, PendingOrchestrationEffectV2 } from "./EffectOutbox.ts"; import { IdAllocatorV2 } from "./IdAllocator.ts"; import { makeKeyedSerialExecutor } from "./KeyedSerialExecutor.ts"; -import { applyToProjection, emptyProjection, ProjectionStoreV2 } from "./ProjectionStore.ts"; +import { + applyToProjection, + emptyProjection, + isTurnItemAtOrBeforeRun, + ProjectionStoreV2, +} from "./ProjectionStore.ts"; import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts"; import { ProviderAdapterRegistryV2 } from "./ProviderAdapterRegistry.ts"; import { @@ -442,6 +447,18 @@ function visibleDeltaRunOrdinals( }; } +export function shouldPrepareLegacyImportHandoff(input: { + readonly hasNativeThreadRef: boolean; + readonly historyOrigin: OrchestrationV2AppThread["historyOrigin"]; + readonly legacyImportItemCount: number; +}): boolean { + return ( + input.historyOrigin === "v1_import" && + !input.hasNativeThreadRef && + input.legacyImportItemCount > 0 + ); +} + function rootProviderThreadsForProvider( projection: OrchestrationV2ThreadProjection, providerInstanceId: ModelSelection["instanceId"], @@ -2569,21 +2586,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio driver: adapter.driver, nativeThreadId: `pending:${runId}`, }); - const legacyImportHandoff = - projection.thread.historyOrigin === "v1_import" && - projection.runs.length === 0 && - legacyImportItems.length > 0 - ? yield* contextHandoffService - .prepareLegacyImport({ - threadId: command.threadId, - targetRunId: runId, - toProviderThreadId: providerThreadId, - toProviderInstanceId: modelSelection.instanceId, - items: legacyImportItems, - createdAt: now, - }) - .pipe(mapDispatchError(command)) - : null; + const legacyImportHandoff = shouldPrepareLegacyImportHandoff({ + historyOrigin: projection.thread.historyOrigin, + hasNativeThreadRef: + activeProviderThread !== undefined && activeProviderThread.nativeThreadRef !== null, + legacyImportItemCount: legacyImportItems.length, + }) + ? yield* contextHandoffService + .prepareLegacyImport({ + threadId: command.threadId, + targetRunId: runId, + toProviderThreadId: providerThreadId, + toProviderInstanceId: modelSelection.instanceId, + items: legacyImportItems, + createdAt: now, + }) + .pipe(mapDispatchError(command)) + : null; const providerThread: OrchestrationV2ProviderThread = activeProviderThread === undefined ? { @@ -3006,18 +3025,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerSessionId, updatedAt: now, }; + const sourceRunOrdinalById = new Map( + (sourceProjection?.runs ?? []).map((run) => [run.id, run.ordinal]), + ); const portableForkItems = !requiresPortableFork || sourceProjection === null || sourceRun === null ? [] - : sourceProjection.turnItems.filter((item) => { - if (item.runId === null) { - return false; - } - const itemRun = sourceProjection.runs.find( - (candidate) => candidate.id === item.runId, - ); - return itemRun !== undefined && itemRun.ordinal <= sourceRun.ordinal; - }); + : sourceProjection.turnItems.filter((item) => + isTurnItemAtOrBeforeRun({ + historyOrigin: sourceProjection.thread.historyOrigin, + itemRunId: item.runId, + runOrdinalById: sourceRunOrdinalById, + sourceRunOrdinal: sourceRun.ordinal, + }), + ); const portableForkHandoff = !requiresPortableFork || pendingForkTransfer === undefined || diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 4ca2193061..0d3950cc49 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -23,7 +23,11 @@ import * as SqlClient from "effect/unstable/sql/SqlClient"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; -import { ProjectionStoreV2, layer as projectionStoreLayer } from "./ProjectionStore.ts"; +import { + isTurnItemAtOrBeforeRun, + ProjectionStoreV2, + layer as projectionStoreLayer, +} from "./ProjectionStore.ts"; const TestLayer = Layer.mergeAll( projectionStoreLayer.pipe(Layer.provideMerge(SqlitePersistenceMemory)), @@ -37,6 +41,48 @@ const driver = ProviderDriverKind.make("codex"); const providerInstanceId = modelSelection.instanceId; const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown)); +it("includes imported runless history when selecting fork context through a run", () => { + const firstRunId = RunId.make("run:projection-imported-fork:1"); + const secondRunId = RunId.make("run:projection-imported-fork:2"); + const runOrdinalById = new Map([ + [firstRunId, 1], + [secondRunId, 2], + ]); + + assert.isTrue( + isTurnItemAtOrBeforeRun({ + historyOrigin: "v1_import", + itemRunId: null, + runOrdinalById, + sourceRunOrdinal: 1, + }), + ); + assert.isFalse( + isTurnItemAtOrBeforeRun({ + historyOrigin: undefined, + itemRunId: null, + runOrdinalById, + sourceRunOrdinal: 1, + }), + ); + assert.isTrue( + isTurnItemAtOrBeforeRun({ + historyOrigin: "v1_import", + itemRunId: firstRunId, + runOrdinalById, + sourceRunOrdinal: 1, + }), + ); + assert.isFalse( + isTurnItemAtOrBeforeRun({ + historyOrigin: "v1_import", + itemRunId: secondRunId, + runOrdinalById, + sourceRunOrdinal: 1, + }), + ); +}); + it.layer(TestLayer)("ProjectionStoreV2", (it) => { it.effect("projects one shared provider session into multiple thread bindings", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 7d780085ce..63cc7837cc 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -647,6 +647,19 @@ function makeForkMarkerTurnItem(input: { }; } +export function isTurnItemAtOrBeforeRun(input: { + readonly historyOrigin: OrchestrationV2ThreadProjection["thread"]["historyOrigin"]; + readonly itemRunId: OrchestrationV2TurnItem["runId"]; + readonly runOrdinalById: ReadonlyMap, number>; + readonly sourceRunOrdinal: number; +}): boolean { + if (input.itemRunId === null) { + return input.historyOrigin === "v1_import"; + } + const ordinal = input.runOrdinalById.get(input.itemRunId); + return ordinal !== undefined && ordinal <= input.sourceRunOrdinal; +} + function visibleTurnItemsThroughRun(input: { readonly sourceProjection: OrchestrationV2ThreadProjection; readonly sourceRunId: NonNullable; @@ -678,11 +691,12 @@ function visibleTurnItemsThroughRun(input: { ) { return false; } - if (item.runId === null) { - return false; - } - const ordinal = runOrdinalById.get(item.runId); - return ordinal !== undefined && ordinal <= sourceRun.ordinal; + return isTurnItemAtOrBeforeRun({ + historyOrigin: input.sourceProjection.thread.historyOrigin, + itemRunId: item.runId, + runOrdinalById, + sourceRunOrdinal: sourceRun.ordinal, + }); }), );