From edfd3e2c00c77d7b417a467fd59b2a29dca70086 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 23:58:23 +0000 Subject: [PATCH 1/3] test(server): a retry handoff's history read stays on the thread's run index Reproduces #35597: getTurnStartHistory with run ids walks every turn item of the thread through thread_ordinal_idx. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/ProjectionStore.test.ts | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 26d0c9aa192b8..4af78e3bc5850 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -6791,6 +6791,30 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { lookupPlans.push(plan); } + // A retry handoff reads its missed runs' history; that must not walk every item of the thread. + const history = traceSqlStatements(); + const missedItems = yield* projectionStore + .getTurnStartHistory(threadId, [selectedRunId]) + .pipe(Effect.withTracer(history.tracer)); + assert.deepEqual( + missedItems.map((item) => item.id), + selectedIds, + ); + const historyLookup = history.statements.find((statement) => + statement.includes("FROM orchestration_v2_projection_turn_items"), + ); + assert.isDefined(historyLookup); + const historyPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${historyLookup}`, + [threadId, selectedRunId], + )) + .map((row) => row.detail) + .join("\n"); + assert.match( + historyPlan, + /^SEARCH .*\((?:thread_id=\? AND )?run_id=\?(?: AND thread_id=\?)?\)/m, + ); + assert.deepEqual((yield* readItems(threadId, emptyRunId)).ids, []); assert.deepEqual( (yield* readItems(threadId, RunId.make("run:turn-start-items:missing"))).ids, From 8fac7596991381bbdad2b3b3245f8631ffa20f5c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 00:04:22 +0000 Subject: [PATCH 2/3] fix(server): turn starts in long threads no longer read the whole thread A retry handoff's history read for a few runs ordered by ordinal, so without planner statistics SQLite walked the thread's ordinal index and tested run_id on every item. It now uses the thread/run index. The turn-start context also read every non-failed subagent and every context transfer touching the thread; it now reads only the completed subagents turn start routes, forks into the thread, and transfers the thread's handoffs reference. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/ProjectionStore.ts | 10 +++- .../orchestration-v2/TurnStartReads.test.ts | 58 ++++++++++++++++++- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index f8f822489ddd5..ca4dd64be3a23 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -5038,7 +5038,8 @@ export const layer: Layer.Layer = `.pipe(Effect.flatMap(decodeRows(decodeNodePayload, threadId))); const subagents = yield* sql` SELECT payload_json FROM orchestration_v2_projection_subagents - WHERE thread_id = ${threadId} AND status NOT IN ('interrupted','failed','cancelled') ORDER BY subagent_id ASC + -- Turn start routes only completed subagents (RunExecutionService.canRouteRelatedSubagent). + WHERE thread_id = ${threadId} AND status = 'completed' ORDER BY subagent_id ASC `.pipe(Effect.flatMap(decodeRows(decodeSubagentPayload, threadId))); const providerThreads = yield* sql` SELECT payload_json FROM orchestration_v2_projection_provider_threads @@ -5058,7 +5059,10 @@ export const layer: Layer.Layer = `.pipe(Effect.flatMap(decodeRows(decodeContextHandoffPayload, threadId))); const contextTransfers = yield* sql` SELECT payload_json FROM orchestration_v2_projection_context_transfers - WHERE source_thread_id = ${threadId} OR target_thread_id = ${threadId} ORDER BY rowid ASC + -- Turn start reads forks into this thread and the transfers its handoffs reference. + WHERE (target_thread_id = ${threadId} AND type = 'fork') + OR context_transfer_id IN (SELECT json_extract(payload_json, '$.transferId') FROM orchestration_v2_projection_context_handoffs WHERE thread_id = ${threadId}) + ORDER BY rowid ASC `.pipe(Effect.flatMap(decodeRows(decodeContextTransferPayload, threadId))); const turnItems = yield* sql` SELECT payload_json FROM orchestration_v2_projection_turn_items @@ -5125,6 +5129,8 @@ export const layer: Layer.Layer = function* (threadId, runIds) { const rows = yield* sql` SELECT payload_json FROM orchestration_v2_projection_turn_items + -- Without planner statistics SQLite would test run_id on every item via the ordinal index. + ${runIds === undefined ? sql`` : sql`INDEXED BY orchestration_v2_projection_turn_items_thread_run_idx`} WHERE thread_id = ${threadId} AND type IN ('user_message','assistant_message','command_execution','error', 'run_interrupt_result','file_change','proposed_plan') diff --git a/apps/server/src/orchestration-v2/TurnStartReads.test.ts b/apps/server/src/orchestration-v2/TurnStartReads.test.ts index cfc362c9db080..5a7aee569d926 100644 --- a/apps/server/src/orchestration-v2/TurnStartReads.test.ts +++ b/apps/server/src/orchestration-v2/TurnStartReads.test.ts @@ -1,6 +1,7 @@ import { assert, it } from "@effect/vitest"; import { CheckpointScopeId, + ContextHandoffId, ContextTransferId, NodeId, EventId, @@ -8,6 +9,7 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + ProviderThreadId, RunId, RuntimeRequestId, ThreadId, @@ -570,7 +572,61 @@ it.effect( }, }); yield* userMessage(forkId, forkRunId, "/compact"); + // Of other transfers, turn start reads only those a handoff of this thread references. + for (const id of ["transfer:handed-off-result", "transfer:unreferenced-result"]) { + yield* store.apply({ + id: EventId.make(`event:${id}`), + type: "context-transfer.created", + threadId: forkId, + occurredAt: now, + payload: { + id: ContextTransferId.make(id), + type: "subagent_result", + sourceThreadId: sourceId, + targetThreadId: forkId, + sourcePoint: { threadId: sourceId }, + basePoint: null, + sourceProviderInstanceId: instanceId, + targetProviderInstanceId: instanceId, + targetRunId: null, + status: "consumed", + resolution: null, + createdBy: "system", + error: null, + createdAt: now, + updatedAt: now, + consumedAt: now, + }, + }); + } + yield* store.apply({ + id: EventId.make("event:handoff:handed-off-result"), + type: "context-handoff.updated", + threadId: forkId, + occurredAt: now, + payload: { + id: ContextHandoffId.make("handoff:handed-off-result"), + transferId: ContextTransferId.make("transfer:handed-off-result"), + threadId: forkId, + targetRunId: forkRunId, + fromProviderThreadIds: [], + toProviderThreadId: ProviderThreadId.make("provider-thread:fork"), + coveredRunOrdinals: { from: 1, to: 1 }, + strategy: "delta_since_target_last_seen", + status: "ready", + summaryMessageId: null, + summaryText: "", + createdByProviderInstanceId: instanceId, + createdAt: now, + updatedAt: now, + }, + }); - assert.isTrue((yield* store.getTurnStartContext(forkId, forkRunId)).hasConversation); + const context = yield* store.getTurnStartContext(forkId, forkRunId); + assert.isTrue(context.hasConversation); + assert.deepEqual( + context.contextTransfers.map((transfer) => transfer.id), + ["transfer:fork-compact", "transfer:handed-off-result"], + ); }).pipe(Effect.provide(layerDatabase)), ); From 11814075a1972e653a5776cb1975c77938e4488e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 13 Nov 2026 00:15:19 +0000 Subject: [PATCH 3/3] fix(server): turn starts find /compact turns and subagent routes by index getTurnStartContext still parsed every user message of the thread to find /compact and /goal turns, and decoded every completed subagent's payload though turn start only routes by its child and provider thread ids. A partial index now holds exactly the /compact and /goal user messages, and the message read is split so each arm uses its own index: the run's message by key, the commands through the partial index. A covering index on the subagent routing columns lets the context return just those ids. Co-Authored-By: Claude Opus 5.5 --- .../orchestration-v2/ProjectionStore.test.ts | 30 ++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 59 +++++++++++++------ .../ProviderTurnStartService.test.ts | 2 + .../ProviderTurnStartService.ts | 11 ++-- apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/087_TurnStartReadIndexes.ts | 22 +++++++ .../reconcileV2PreviewMigration.test.ts | 2 + 7 files changed, 103 insertions(+), 25 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/087_TurnStartReadIndexes.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 4af78e3bc5850..2e5280370ada8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -6815,6 +6815,36 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { /^SEARCH .*\((?:thread_id=\? AND )?run_id=\?(?: AND thread_id=\?)?\)/m, ); + // Turn start finds earlier /compact and /goal messages and routable subagents through indexes, + // without parsing every user message or reading subagent payloads. + const context = traceSqlStatements(); + yield* projectionStore + .getTurnStartContext(threadId, selectedRunId) + .pipe(Effect.withTracer(context.tracer)); + const contextPlan = Effect.fn("contextPlan")(function* ( + table: string, + params: ReadonlyArray, + ) { + const statement = context.statements.find((candidate) => + candidate.includes(`FROM orchestration_v2_projection_${table}\n`), + ); + assert.isDefined(statement); + return (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${statement}`, + params, + )) + .map((row) => row.detail) + .join("\n"); + }); + assert.include( + yield* contextPlan("messages", [threadId, threadId, selectedRunId, threadId]), + "USING INDEX orchestration_v2_projection_messages_turn_start_command_idx", + ); + assert.include( + yield* contextPlan("subagents", [threadId]), + "USING COVERING INDEX orchestration_v2_projection_subagents_routing_idx", + ); + assert.deepEqual((yield* readItems(threadId, emptyRunId)).ids, []); assert.deepEqual( (yield* readItems(threadId, RunId.make("run:turn-start-items:missing"))).ids, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index ca4dd64be3a23..99292ebdeea53 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -631,7 +631,6 @@ export interface ProjectionStoreV2Shape { | "runs" | "attempts" | "nodes" - | "subagents" | "providerSessions" | "providerThreads" | "providerTurns" @@ -640,7 +639,14 @@ export interface ProjectionStoreV2Shape { | "contextHandoffs" | "contextTransfers" | "turnItems" - > & { readonly hasConversation: boolean }, + > & { + readonly hasConversation: boolean; + /** Child and provider thread ids of the thread's completed subagents. */ + readonly subagentRoutes: ReadonlyArray<{ + readonly childThreadId: ThreadId | null; + readonly providerThreadId: ProviderThreadId | null; + }>; + }, ProjectionStoreV2Error >; readonly getTurnStartHistory: ( @@ -5014,8 +5020,16 @@ export const layer: Layer.Layer = ); // SQLite trim defaults to ASCII spaces; compact recognition uses JavaScript trim. - const javascriptTrimWhitespace = - " \t\n\r\v\f\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"; + const JAVASCRIPT_TRIM_WHITESPACE = + "char(32, 9, 10, 13, 11, 12, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279)"; + const COMPACT_COMMAND_TEXT = `lower(trim(json_extract(payload_json, '$.text'), ${JAVASCRIPT_TRIM_WHITESPACE})) = '/compact'`; + // Must match migration 087's partial index exactly for SQLite to use it. + const TURN_START_COMMAND_MESSAGE = sql.literal( + `role = 'user' AND ( + ${COMPACT_COMMAND_TEXT} + OR trim(json_extract(payload_json, '$.text'), ${JAVASCRIPT_TRIM_WHITESPACE}) GLOB '/goal*' + )`, + ); const getTurnStartContext: ProjectionStoreV2Shape["getTurnStartContext"] = (threadId, runId) => sql @@ -5036,11 +5050,15 @@ export const layer: Layer.Layer = INDEXED BY sqlite_autoindex_orchestration_v2_projection_nodes_1 WHERE thread_id = ${threadId} AND node_id IN (SELECT json_extract(payload_json, '$.rootNodeId') FROM orchestration_v2_projection_runs WHERE thread_id = ${threadId} AND run_id = ${runId}) ORDER BY node_id ASC `.pipe(Effect.flatMap(decodeRows(decodeNodePayload, threadId))); - const subagents = yield* sql` - SELECT payload_json FROM orchestration_v2_projection_subagents - -- Turn start routes only completed subagents (RunExecutionService.canRouteRelatedSubagent). + // Turn start routes only completed subagents (RunExecutionService.canRouteRelatedSubagent). + const subagentRoutes = yield* sql<{ + readonly child_thread_id: ThreadId | null; + readonly provider_thread_id: ProviderThreadId | null; + }>` + SELECT child_thread_id, provider_thread_id FROM orchestration_v2_projection_subagents + INDEXED BY orchestration_v2_projection_subagents_routing_idx WHERE thread_id = ${threadId} AND status = 'completed' ORDER BY subagent_id ASC - `.pipe(Effect.flatMap(decodeRows(decodeSubagentPayload, threadId))); + `; const providerThreads = yield* sql` SELECT payload_json FROM orchestration_v2_projection_provider_threads WHERE thread_id = ${threadId} ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC @@ -5078,20 +5096,22 @@ export const layer: Layer.Layer = ORDER BY sessions.updated_at ASC, sessions.provider_session_id ASC `.pipe(Effect.flatMap(decodeRows(decodeProviderSessionPayload, threadId))); const messages = yield* sql` - SELECT payload_json FROM orchestration_v2_projection_messages - WHERE thread_id = ${threadId} AND ( - message_id IN (SELECT json_extract(payload_json, '$.userMessageId') FROM orchestration_v2_projection_runs - WHERE thread_id = ${threadId} AND run_id = ${runId}) - OR (role = 'user' AND lower(trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace})) = '/compact') - -- Earlier /goal turns defer context too; parseGoalCommand narrows this prefix match. - OR (role = 'user' AND trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace}) GLOB '/goal*') - ) ORDER BY created_at ASC, message_id ASC + SELECT payload_json, created_at, message_id FROM orchestration_v2_projection_messages + INDEXED BY sqlite_autoindex_orchestration_v2_projection_messages_1 + WHERE thread_id = ${threadId} AND message_id IN (SELECT json_extract(payload_json, '$.userMessageId') FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND run_id = ${runId}) + UNION + -- Earlier /compact and /goal turns defer context too; parseGoalCommand narrows the prefix match. + SELECT payload_json, created_at, message_id FROM orchestration_v2_projection_messages + INDEXED BY orchestration_v2_projection_messages_turn_start_command_idx + WHERE thread_id = ${threadId} AND ${TURN_START_COMMAND_MESSAGE} + ORDER BY created_at ASC, message_id ASC `.pipe(Effect.flatMap(decodeRows(decodeMessagePayload, threadId))); const conversation = yield* sql<{ present: number }>` SELECT EXISTS( SELECT 1 FROM orchestration_v2_projection_messages WHERE thread_id = ${threadId} AND role = 'user' - AND (lower(trim(json_extract(payload_json, '$.text'), ${javascriptTrimWhitespace})) <> '/compact' + AND (NOT (${sql.literal(COMPACT_COMMAND_TEXT)}) OR json_array_length(payload_json, '$.attachments') > 0) ) AS present `; @@ -5103,7 +5123,10 @@ export const layer: Layer.Layer = runs, attempts, nodes, - subagents, + subagentRoutes: subagentRoutes.map((route) => ({ + childThreadId: route.child_thread_id, + providerThreadId: route.provider_thread_id, + })), providerSessions, providerThreads, providerTurns, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 17d40cf05162e..8d2f21279b490 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -172,6 +172,7 @@ function startWithMissingWorktree( projectionReadCount += 1; return Effect.succeed({ ...projection, + subagentRoutes: [], hasConversation: projection.messages.some( (m) => m.role === "user" && @@ -918,6 +919,7 @@ function makeLocalCommandHarness(input: { const getTurnStartContext = vi.fn(() => Effect.succeed({ ...projection, + subagentRoutes: [], hasConversation: projection.messages.some( (m) => m.role === "user" && diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index f8d78f708773d..ed41105c0a4c4 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1584,9 +1584,6 @@ export const layer: Layer.Layer< if (!runningWrite.committed) { return; } - const routableSubagents = projection.subagents.filter((subagent) => - RunExecutionService.canRouteRelatedSubagent(subagent.status), - ); const persistHandoff = Effect.fn("ProviderTurnStartService.persist")(function* ( handoff: OrchestrationV2ContextHandoff, ) { @@ -1716,11 +1713,11 @@ export const layer: Layer.Layer< attempt: runningAttempt, attemptId: attempt.id, loadInheritedBackgroundTurnItems: runControls.loadInheritedBackgroundTurnItems, - relatedThreadIds: routableSubagents.flatMap((subagent) => - subagent.childThreadId === null ? [] : [subagent.childThreadId], + relatedThreadIds: projection.subagentRoutes.flatMap((route) => + route.childThreadId === null ? [] : [route.childThreadId], ), - relatedProviderThreadIds: routableSubagents.flatMap((subagent) => - subagent.providerThreadId === null ? [] : [subagent.providerThreadId], + relatedProviderThreadIds: projection.subagentRoutes.flatMap((route) => + route.providerThreadId === null ? [] : [route.providerThreadId], ), providerTurnOrdinal: Math.max( diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 9b6e2b3e0fc76..476ae4b2ba89b 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -89,6 +89,7 @@ import Migration0083 from "./Migrations/083_CommandReadIndexes.ts"; import Migration0084 from "./Migrations/084_LastExecutedRunIndex.ts"; import Migration0085 from "./Migrations/085_TurnItemCounts.ts"; import Migration0086 from "./Migrations/086_QueuedTurnInputIndex.ts"; +import Migration0087 from "./Migrations/087_TurnStartReadIndexes.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -178,6 +179,7 @@ const migrationEntries = [ [84, "LastExecutedRunIndex", Migration0084], [85, "TurnItemCounts", Migration0085], [86, "QueuedTurnInputIndex", Migration0086], + [87, "TurnStartReadIndexes", Migration0087], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/087_TurnStartReadIndexes.ts b/apps/server/src/persistence/Migrations/087_TurnStartReadIndexes.ts new file mode 100644 index 0000000000000..1f595d2304fac --- /dev/null +++ b/apps/server/src/persistence/Migrations/087_TurnStartReadIndexes.ts @@ -0,0 +1,22 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this predicate identical to ProjectionStore's TURN_START_COMMAND_MESSAGE, or turn + // starts parse every user message of the thread again. + yield* sql` + CREATE INDEX orchestration_v2_projection_messages_turn_start_command_idx + ON orchestration_v2_projection_messages(thread_id) + WHERE role = 'user' AND ( + lower(trim(json_extract(payload_json, '$.text'), char(32, 9, 10, 13, 11, 12, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279))) = '/compact' + OR trim(json_extract(payload_json, '$.text'), char(32, 9, 10, 13, 11, 12, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288, 65279)) GLOB '/goal*' + ) + `; + // Turn start routes completed subagents by these ids without reading their payloads. + yield* sql` + CREATE INDEX orchestration_v2_projection_subagents_routing_idx + ON orchestration_v2_projection_subagents(thread_id, status, subagent_id, child_thread_id, provider_thread_id) + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 98a79e7a7370d..e12ca48bc2078 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -66,6 +66,7 @@ describe("V2 preview upgrade", () => { [84, "LastExecutedRunIndex"], [85, "TurnItemCounts"], [86, "QueuedTurnInputIndex"], + [87, "TurnStartReadIndexes"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -175,6 +176,7 @@ describe("V2 preview upgrade", () => { [84, "LastExecutedRunIndex"], [85, "TurnItemCounts"], [86, "QueuedTurnInputIndex"], + [87, "TurnStartReadIndexes"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), );