Skip to content
24 changes: 24 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5603,6 +5603,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
function* (threadId, runIds) {
const rows = yield* sql<PayloadRow>`
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')
Expand Down
Loading