diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 9daad8e1cdae..5b8a636cc24f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -9038,6 +9038,16 @@ export const layer: Layer.Layer = return rows[0]?.count ?? 0; }, Effect.mapError(shellSnapshotReadError)); + // Migration 98 indexes these exact expressions, so the read takes them from the index instead + // of parsing every active thread's payload. Changing one here needs a matching index change. + const indexedField = (path: string, read: "json_extract" | "json_type" = "json_extract") => + sql.literal( + `CASE WHEN json_valid(t.payload_json) THEN ${read}(t.payload_json, '${path}') END`, + ); + // The planner otherwise scans the whole (thread_id, type, status) index for this list. + const PENDING_ITEMS_INDEX = sql.literal( + "INDEXED BY orchestration_v2_projection_turn_items_shell_pending_idx", + ); const listActiveShellIndex = Effect.fn("ProjectionStore.listActiveShellIndex")(function* () { const rows = yield* sql<{ readonly thread_id: string; @@ -9057,48 +9067,53 @@ export const layer: Layer.Layer = SELECT t.thread_id, t.project_id, - json_extract(t.payload_json, '$.lineage.relationshipToParent') AS relationship_to_parent, - json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id, - json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id, - json_extract(t.payload_json, '$.lineage.sideChat') AS side_chat, - json_extract(t.payload_json, '$.settledOverride') AS settled_override, - json_extract(t.payload_json, '$.settledAt') AS settled_at, - json_extract(t.payload_json, '$.pinnedAt') AS pinned_at, - json_extract(t.payload_json, '$.pinOrderKey') AS pin_order_key, - json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until, + ${indexedField("$.lineage.relationshipToParent")} AS relationship_to_parent, + ${indexedField("$.lineage.parentThreadId")} AS parent_thread_id, + ${indexedField("$.lineage.rootThreadId")} AS root_thread_id, + ${indexedField("$.lineage.sideChat")} AS side_chat, + ${indexedField("$.settledOverride")} AS settled_override, + ${indexedField("$.settledAt")} AS settled_at, + ${indexedField("$.pinnedAt")} AS pinned_at, + ${indexedField("$.pinOrderKey")} AS pin_order_key, + ${indexedField("$.snoozedUntil")} AS snoozed_until, -- A superset of isLiveSubagentShell: the sources of its run status, pending request, - -- and pending background work. + -- and pending background work. Each source is one list for the whole read, found + -- through its partial index, so finished threads cost no lookups. ( - EXISTS ( - SELECT 1 FROM orchestration_v2_projection_runs r - WHERE r.thread_id = t.thread_id - AND r.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + t.thread_id IN ( + SELECT r.thread_id FROM orchestration_v2_projection_runs r + WHERE r.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_runtime_requests request - WHERE request.thread_id = t.thread_id AND request.status = 'pending' + OR t.thread_id IN ( + SELECT request.thread_id FROM orchestration_v2_projection_runtime_requests request + WHERE request.status = 'pending' ) -- Same predicates as the shell's pending item and link reads, for their partial indexes. - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_turn_items item - WHERE item.thread_id = t.thread_id - AND item.type IN ('command_execution', 'dynamic_tool', 'subagent') + OR t.thread_id IN ( + SELECT item.thread_id + FROM orchestration_v2_projection_turn_items item ${PENDING_ITEMS_INDEX} + WHERE item.type IN ('command_execution', 'dynamic_tool', 'subagent') AND item.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled') ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_turn_items link_request - WHERE link_request.thread_id = t.thread_id - AND link_request.type = 'link_request' AND link_request.status = 'waiting' - ) - OR EXISTS ( - SELECT 1 FROM orchestration_v2_projection_provider_threads provider_thread - WHERE provider_thread.thread_id = t.thread_id - AND json_array_length(provider_thread.payload_json, '$.pendingBackgroundTasks') > 0 + OR t.thread_id IN ( + SELECT link_request.thread_id FROM orchestration_v2_projection_turn_items link_request + WHERE link_request.type = 'link_request' AND link_request.status = 'waiting' ) - OR EXISTS ( - SELECT 1 FROM json_each(t.payload_json, '$.pullRequests') link - WHERE json_type(link.value, '$.watch') IS NOT NULL + OR t.thread_id IN ( + SELECT provider_thread.thread_id + FROM orchestration_v2_projection_provider_threads provider_thread + WHERE CASE WHEN json_valid(provider_thread.payload_json) + THEN json_array_length(provider_thread.payload_json, '$.pendingBackgroundTasks') > 0 + ELSE 0 END ) + -- Only a thread with a pull request link reads its payload. CASE, not AND: SQLite + -- 3.50 evaluates both AND operands here. + OR CASE WHEN ${indexedField("$.pullRequests[0]", "json_type")} IS NOT NULL + THEN EXISTS ( + SELECT 1 FROM json_each(t.payload_json, '$.pullRequests') link + WHERE json_type(link.value, '$.watch') IS NOT NULL + ) + ELSE 0 END ) AS may_be_live, -- One list for the whole read, found through the child_thread_id index. A lookup per -- thread would parse the payload of every subagent row. diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 8cde1a34a035..e2c62dd79379 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -105,6 +105,7 @@ import Migration0094 from "./Migrations/094_TurnItemMessageOrdinalIndex.ts"; import Migration0095 from "./Migrations/095_TurnItemInlineWorkOutput.ts"; import Migration0096 from "./Migrations/096_RepairStaleTitleRegeneration.ts"; import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts"; +import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -205,6 +206,7 @@ const migrationEntries = [ [95, "TurnItemInlineWorkOutput", Migration0095], [96, "RepairStaleTitleRegeneration", Migration0096], [97, "IssueTrackerBindings", Migration0097], + [98, "ActiveShellIndexIndexes", Migration0098], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts b/apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts new file mode 100644 index 000000000000..da25d04c6ebf --- /dev/null +++ b/apps/server/src/persistence/Migrations/098_ActiveShellIndexIndexes.ts @@ -0,0 +1,35 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // ProjectionStore.listActiveShellIndex reads these fields from the index instead of parsing + // every active thread's payload. Keep the expressions identical to that query's. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_threads_active_shell_idx + ON orchestration_v2_projection_threads( + updated_at, + thread_id, + project_id, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.relationshipToParent') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.parentThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.rootThreadId') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.lineage.sideChat') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledOverride') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.settledAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinnedAt') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.pinOrderKey') END, + CASE WHEN json_valid(payload_json) THEN json_extract(payload_json, '$.snoozedUntil') END, + CASE WHEN json_valid(payload_json) THEN json_type(payload_json, '$.pullRequests[0]') END + ) + WHERE deleted_at IS NULL AND archived_at IS NULL + `; + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_provider_threads_pending_tasks_idx + ON orchestration_v2_projection_provider_threads(thread_id) + WHERE CASE WHEN json_valid(payload_json) + THEN json_array_length(payload_json, '$.pendingBackgroundTasks') > 0 + ELSE 0 END + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 79e52b517f65..fbe47613c87e 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -77,6 +77,7 @@ describe("V2 preview upgrade", () => { [95, "TurnItemInlineWorkOutput"], [96, "RepairStaleTitleRegeneration"], [97, "IssueTrackerBindings"], + [98, "ActiveShellIndexIndexes"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -197,6 +198,7 @@ describe("V2 preview upgrade", () => { [95, "TurnItemInlineWorkOutput"], [96, "RepairStaleTitleRegeneration"], [97, "IssueTrackerBindings"], + [98, "ActiveShellIndexIndexes"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), );