TypeScript
fix(server): speed up shell snapshots on large databases (#23751)
Yash Singhc7e3993fe9fb
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 83f33269f39..6f87afb2eb2 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -2374,6 +2374,170 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {}),);+ it.effect("looks up shell stop requests through the interrupt request index", () =>+ Effect.gen(function* () {+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;+ const sql = yield* SqlClient.SqlClient;+ const { projectId } = yield* assertProjectScopedShells("sql-shell-stop-index");+ const { statements, tracer } = traceSqlStatements();+ yield* projectionStore+ .getShellSnapshot({ projectId, location: "active" })+ .pipe(Effect.withTracer(tracer));++ const threadQuery = statements.find((statement) =>+ statement.includes("AS latest_run_stop_requested"),+ );+ assert.isDefined(threadQuery);+ const stopRequestLookups = (yield* sql.unsafe<{ readonly detail: string }>(+ `EXPLAIN QUERY PLAN ${threadQuery}`,+ ))+ .map((row) => row.detail)+ .filter((detail) => detail.startsWith("SEARCH stop_request "));+ assert.lengthOf(stopRequestLookups, 2);+ for (const lookup of stopRequestLookups) {+ assert.include(lookup, "orchestration_v2_projection_turn_items_stop_request_idx");+ }+ }),+ );++ it.effect(+ "counts each shell's own runless and live-run items, skipping rolled back and missing runs",+ () =>+ Effect.gen(function* () {+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;+ const now = yield* DateTime.now;+ const projectId = ProjectId.make("project:shell-item-counts");+ const busyThreadId = ThreadId.make("thread:shell-item-counts:busy");+ const emptyThreadId = ThreadId.make("thread:shell-item-counts:empty");+ const otherThreadId = ThreadId.make("thread:shell-item-counts:other");+ for (const threadId of [busyThreadId, emptyThreadId, otherThreadId]) {+ yield* projectionStore.apply({+ id: EventId.make(`event:${threadId}:created`),+ type: "thread.created",+ threadId,+ occurredAt: now,+ payload: {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId,+ title: threadId,+ providerInstanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ });+ }+ const applyRun = (+ threadId: ThreadId,+ suffix: string,+ ordinal: number,+ rolledBack: boolean,+ ) => {+ const runId = RunId.make(`run:shell-item-counts:${suffix}`);+ const rootNodeId = NodeId.make(`node:shell-item-counts:${suffix}`);+ return projectionStore+ .apply({+ id: EventId.make(`event:shell-item-counts:${suffix}:run`),+ type: "run.created",+ threadId,+ runId,+ nodeId: rootNodeId,+ driver,+ occurredAt: now,+ payload: {+ id: runId,+ threadId,+ ordinal,+ providerInstanceId,+ modelSelection,+ providerThreadId: null,+ userMessageId: MessageId.make(`message:shell-item-counts:${suffix}:user`),+ rootNodeId,+ activeAttemptId: null,+ status: rolledBack ? "rolled_back" : "completed",+ requestedAt: now,+ startedAt: now,+ completedAt: now,+ checkpointId: null,+ contextHandoffId: null,+ },+ })+ .pipe(Effect.as(runId));+ };+ let ordinal = 0;+ const applyItem = (threadId: ThreadId, runId: RunId | null) => {+ ordinal += 1;+ return projectionStore.apply({+ id: EventId.make(`event:shell-item-counts:item:${ordinal}`),+ type: "turn-item.updated",+ threadId,+ ...(runId === null ? {} : { runId }),+ occurredAt: now,+ payload: {+ id: TurnItemId.make(`turn-item:shell-item-counts:${ordinal}`),+ threadId,+ runId,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ status: "completed",+ title: null,+ startedAt: now,+ completedAt: now,+ updatedAt: now,+ type: "assistant_message",+ messageId: MessageId.make(`message:shell-item-counts:${ordinal}`),+ text: `item ${ordinal}`,+ streaming: false,+ },+ });+ };++ const completedRunId = yield* applyRun(busyThreadId, "busy-completed", 1, false);+ const rolledBackRunId = yield* applyRun(busyThreadId, "busy-rolled-back", 2, true);+ const otherRunId = yield* applyRun(otherThreadId, "other", 1, false);+ yield* applyItem(busyThreadId, null);+ yield* applyItem(busyThreadId, null);+ yield* applyItem(busyThreadId, completedRunId);+ yield* applyItem(busyThreadId, completedRunId);+ yield* applyItem(busyThreadId, rolledBackRunId);+ yield* applyItem(busyThreadId, RunId.make("run:shell-item-counts:missing"));+ yield* applyItem(otherThreadId, otherRunId);++ const snapshot = yield* projectionStore.getShellSnapshot({ projectId });+ const expected = [+ [busyThreadId, 4],+ [emptyThreadId, 0],+ [otherThreadId, 1],+ ] as const;+ for (const [threadId, itemCount] of expected) {+ const shell = yield* projectionStore.getThreadShell(threadId);+ assert.deepEqual(+ snapshot.threads.find((thread) => thread.id === threadId),+ shell ?? undefined,+ );+ assert.equal(shell?.itemCount, itemCount);+ }+ }),+ );+it.effect("does not treat visited or marked-unread state as thread activity", () =>Effect.gen(function* () {const projectionStore = yield* ProjectionStore.ProjectionStoreV2;diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 40ff180d274..92ef73ebf1b 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -1076,8 +1076,6 @@ type ShellThreadRow = {readonly latest_user_message_at: string | null;readonly latest_user_authored_message_at: string | null;readonly has_actionable_proposed_plan: number;- readonly item_count: number;- readonly runless_item_count: number;};type ShellRunRow = {@@ -1105,6 +1103,12 @@ type ShellRunItemCountRow = {readonly item_count: number;};+type ShellItemCountRow = {+ readonly thread_id: string;+ readonly item_count: number;+ readonly runless_item_count: number;+};+const encodeTimelineSources = Schema.encodeEffect(Schema.fromJsonString(Schema.Array(Schema.Struct({ threadId: Schema.String, id: Schema.String })),@@ -5763,27 +5767,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =WHERE plan.thread_id = t.thread_idAND plan.kind = 'proposed_plan'AND plan.status = 'active'- ) AS has_actionable_proposed_plan,- -- Count per run on the covering (thread_id, run_id) index, then- -- look up each run once, instead of one run lookup per item.- (- SELECT COALESCE(SUM(per_run.item_count), 0)- FROM (- SELECT i.run_id, COUNT(*) AS item_count- FROM orchestration_v2_projection_turn_items i- WHERE i.thread_id = t.thread_id- GROUP BY i.run_id- ) per_run- LEFT JOIN orchestration_v2_projection_runs r- ON r.run_id = per_run.run_id- WHERE per_run.run_id IS NULL OR r.status <> 'rolled_back'- ) AS item_count,- (- SELECT COUNT(*)- FROM orchestration_v2_projection_turn_items i- WHERE i.thread_id = t.thread_id- AND i.run_id IS NULL- ) AS runless_item_count+ ) AS has_actionable_proposed_planFROM orchestration_v2_projection_threads tLEFT JOIN orchestration_v2_projection_runs active ON active.run_id = (SELECT r.run_id@@ -5847,21 +5831,31 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =WHERE thread_id IN ${sql.in(threadIds)}`;- const selectShellRunItemCounts = (threadIds?: ReadonlyArray<ThreadId>) =>- threadIds === undefined- ? sql<ShellRunItemCountRow>`- SELECT thread_id, run_id, COUNT(*) AS item_count- FROM orchestration_v2_projection_turn_items- WHERE run_id IS NOT NULL- GROUP BY thread_id, run_id- `- : sql<ShellRunItemCountRow>`- SELECT thread_id, run_id, COUNT(*) AS item_count- FROM orchestration_v2_projection_turn_items- WHERE run_id IS NOT NULL- AND thread_id IN ${sql.in(threadIds)}- GROUP BY thread_id, run_id- `;+ const selectShellRunItemCounts = (threadIds: ReadonlyArray<ThreadId>) =>+ sql<ShellRunItemCountRow>`+ SELECT thread_id, run_id, COUNT(*) AS item_count+ FROM orchestration_v2_projection_turn_items+ WHERE run_id IS NOT NULL AND thread_id IN ${sql.in(threadIds)}+ GROUP BY thread_id, run_id+ `;++ // Count all selected threads in one index walk; fork sources still need per-run counts.+ const selectShellItemCounts = (threadIds: ReadonlyArray<ThreadId>) =>+ sql<ShellItemCountRow>`+ SELECT counts.thread_id,+ SUM(CASE WHEN counts.run_id IS NULL OR r.status <> 'rolled_back'+ THEN counts.item_count ELSE 0 END) AS item_count,+ SUM(CASE WHEN counts.run_id IS NULL THEN counts.item_count ELSE 0 END)+ AS runless_item_count+ FROM (+ SELECT thread_id, run_id, COUNT(*) AS item_count+ FROM orchestration_v2_projection_turn_items+ WHERE thread_id IN ${sql.in(threadIds)}+ GROUP BY thread_id, run_id+ ) counts+ LEFT JOIN orchestration_v2_projection_runs r ON r.run_id = counts.run_id+ GROUP BY counts.thread_id+ `;const selectShellProviderThreadRows = (threadIds?: ReadonlyArray<ThreadId>) =>threadIds === undefined@@ -5928,6 +5922,17 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =return { runOrdinalsByThreadId, itemCountsByThreadId };};+ const shellItemCountMap = (rows: ReadonlyArray<ShellItemCountRow>) =>+ new Map(+ rows.map(+ (row) =>+ [+ ThreadId.make(row.thread_id),+ { itemCount: row.item_count, runlessItemCount: row.runless_item_count },+ ] as const,+ ),+ );+const pendingBackgroundDataByThreadId = Effect.fn("ProjectionStore.pendingBackgroundDataByThreadId",)(function* (input: {@@ -6131,6 +6136,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =readonly row: ShellThreadRow;readonly runOrdinalsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;readonly itemCountsByThreadId: ReadonlyMap<ThreadId, Map<RunId, number>>;+ readonly shellItemCountsByThreadId: ReadonlyMap<+ ThreadId,+ { readonly itemCount: number; readonly runlessItemCount: number }+ >;readonly providerThreadsByThreadId: ReadonlyMap<ThreadId,ReadonlyArray<OrchestrationV2ThreadProjection["providerThreads"][number]>@@ -6144,6 +6153,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =row,runOrdinalsByThreadId,itemCountsByThreadId,+ shellItemCountsByThreadId,providerThreadsByThreadId,pendingTurnItemsByThreadId,} = input;@@ -6277,8 +6287,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =providerThreadsByThreadId.get(thread.id) ?? [],thread.activeProviderThreadId,),- itemCount: row.item_count,- runlessItemCount: row.runless_item_count,+ itemCount: shellItemCountsByThreadId.get(thread.id)?.itemCount ?? 0,+ runlessItemCount: shellItemCountsByThreadId.get(thread.id)?.runlessItemCount ?? 0,updatedAt: thread.updatedAt,runOrdinalById: runOrdinalsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),itemCountByRunId: itemCountsByThreadId.get(ThreadId.make(row.thread_id)) ?? new Map(),@@ -6318,33 +6328,41 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =read: (ids: ReadonlyArray<ThreadId>) => Effect.Effect<ReadonlyArray<A>, unknown>,ids: ReadonlyArray<ThreadId> = threadIds,) => (ids.length === 0 ? Effect.succeed([] as ReadonlyArray<A>) : read(ids));- const [runRows, itemCountRows, sequenceRows, providerThreadRows, pendingTurnItemRows] =- yield* Effect.all([- readForThreadIds(selectShellRunRows, forkSourceIds),- readForThreadIds(selectShellRunItemCounts, forkSourceIds),- sql<{ readonly snapshot_sequence: number | null }>`+ const [+ runRows,+ itemCountRows,+ shellItemCountRows,+ sequenceRows,+ providerThreadRows,+ pendingTurnItemRows,+ ] = yield* Effect.all([+ readForThreadIds(selectShellRunRows, forkSourceIds),+ readForThreadIds(selectShellRunItemCounts, forkSourceIds),+ readForThreadIds(selectShellItemCounts),+ sql<{ readonly snapshot_sequence: number | null }>`SELECT MAX(sequence) AS snapshot_sequenceFROM orchestration_eventsWHERE application_event_version = 2AND aggregate_kind = 'thread'`,- readForThreadIds(selectShellProviderThreadRows),- readForThreadIds((ids) =>- selectShellPendingTurnItemRows(- ids,- threadRows.flatMap((row) =>- row.active_run_id !== null && row.active_run_status === "running"- ? [row.active_run_id]- : [],- ),+ readForThreadIds(selectShellProviderThreadRows),+ readForThreadIds((ids) =>+ selectShellPendingTurnItemRows(+ ids,+ threadRows.flatMap((row) =>+ row.active_run_id !== null && row.active_run_status === "running"+ ? [row.active_run_id]+ : [],),),- ]);+ ),+ ]);return {targetThreadIds,threadRows,runRows,itemCountRows,+ shellItemCountRows,sequenceRows,providerThreadRows,pendingTurnItemRows,@@ -6356,6 +6374,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =threadRows,runRows,itemCountRows,+ shellItemCountRows,sequenceRows,providerThreadRows,pendingTurnItemRows,@@ -6364,6 +6383,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =runRows,itemCountRows,});+ const shellItemCountsByThreadId = shellItemCountMap(shellItemCountRows);const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });const states = yield* Effect.forEach(threadRows, (row) =>@@ -6371,6 +6391,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =row,runOrdinalsByThreadId,itemCountsByThreadId,+ shellItemCountsByThreadId,providerThreadsByThreadId,pendingTurnItemsByThreadId,}),@@ -6435,28 +6456,35 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =const threadIds = [...rowsByThreadId.keys()];const forkSourceIds = shellForkSourceIds([...rowsByThreadId.values()]);- const [runRows, itemCountRows, providerThreadRows, pendingTurnItemRows] =- yield* Effect.all([- forkSourceIds.length === 0- ? Effect.succeed([] as ReadonlyArray<ShellRunRow>)- : selectShellRunRows(forkSourceIds),- forkSourceIds.length === 0- ? Effect.succeed([] as ReadonlyArray<ShellRunItemCountRow>)- : selectShellRunItemCounts(forkSourceIds),- selectShellProviderThreadRows(threadIds),- selectShellPendingTurnItemRows(- threadIds,- [...rowsByThreadId.values()].flatMap((row) =>- row.active_run_id !== null && row.active_run_status === "running"- ? [row.active_run_id]- : [],- ),+ const [+ runRows,+ itemCountRows,+ shellItemCountRows,+ providerThreadRows,+ pendingTurnItemRows,+ ] = yield* Effect.all([+ forkSourceIds.length === 0+ ? Effect.succeed([] as ReadonlyArray<ShellRunRow>)+ : selectShellRunRows(forkSourceIds),+ forkSourceIds.length === 0+ ? Effect.succeed([] as ReadonlyArray<ShellRunItemCountRow>)+ : selectShellRunItemCounts(forkSourceIds),+ selectShellItemCounts(threadIds),+ selectShellProviderThreadRows(threadIds),+ selectShellPendingTurnItemRows(+ threadIds,+ [...rowsByThreadId.values()].flatMap((row) =>+ row.active_run_id !== null && row.active_run_status === "running"+ ? [row.active_run_id]+ : [],),- ]);+ ),+ ]);const { runOrdinalsByThreadId, itemCountsByThreadId } = runMapsByThreadId({runRows,itemCountRows,});+ const shellItemCountsByThreadId = shellItemCountMap(shellItemCountRows);const { providerThreadsByThreadId, pendingTurnItemsByThreadId } =yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows });@@ -6465,6 +6493,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =row,runOrdinalsByThreadId,itemCountsByThreadId,+ shellItemCountsByThreadId,providerThreadsByThreadId,pendingTurnItemsByThreadId,}),diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 5979eee6c18..5b8ca15241b 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -70,6 +70,7 @@ import Migration0064 from "./Migrations/064_CanonicalizeThreadPullRequestLinks.timport Migration0065 from "./Migrations/065_CodexUsageNativeTurnIndex.ts";import Migration0066 from "./Migrations/066_RepairClientSettlementTimestamps.ts";import Migration0067 from "./Migrations/067_WebhookDedupe.ts";+import Migration0068 from "./Migrations/068_ShellStopRequestIndex.ts";const migrationEntries = [[1, "OrchestrationEvents", Migration0001],@@ -140,6 +141,7 @@ const migrationEntries = [[65, "CodexUsageNativeTurnIndex", Migration0065],[66, "RepairClientSettlementTimestamps", Migration0066],[67, "WebhookDedupe", Migration0067],+ [68, "ShellStopRequestIndex", Migration0068],] as const;export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);diff --git a/apps/server/src/persistence/Migrations/068_ShellStopRequestIndex.ts b/apps/server/src/persistence/Migrations/068_ShellStopRequestIndex.tsnew file mode 100644index 00000000000..2b58b846b20--- /dev/null+++ b/apps/server/src/persistence/Migrations/068_ShellStopRequestIndex.ts@@ -0,0 +1,12 @@+import * as Effect from "effect/Effect";+import * as SqlClient from "effect/sql/SqlClient";++export default Effect.gen(function* () {+ const sql = yield* SqlClient.SqlClient;++ yield* sql`+ CREATE INDEX orchestration_v2_projection_turn_items_stop_request_idx+ ON orchestration_v2_projection_turn_items(thread_id, run_id)+ WHERE type = 'run_interrupt_request'+ `;+});diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.tsindex 990d450cde6..64f1d9e3ae2 100644--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts@@ -47,6 +47,7 @@ describe("V2 preview upgrade", () => {[65, "CodexUsageNativeTurnIndex"],[66, "RepairClientSettlementTimestamps"],[67, "WebhookDedupe"],+ [68, "ShellStopRequestIndex"],]);assert.deepStrictEqual(yield* runMigrations(), []);assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);@@ -137,6 +138,7 @@ describe("V2 preview upgrade", () => {[65, "CodexUsageNativeTurnIndex"],[66, "RepairClientSettlementTimestamps"],[67, "WebhookDedupe"],+ [68, "ShellStopRequestIndex"],]);}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),);