diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index b6539e46344f1..3832c3ff84217 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -7435,6 +7435,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, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a42679d304765..71df58e22d3ae 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -5603,6 +5603,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')