Skip to content
TypeScript

perf(server): bound runtime recovery reads by thread ownership (#29429)

Yash Singhd833184115ec
diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts
index 4df71fd5a9d..f1169f1e910 100644
--- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts
@@ -22,6 +22,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/sql/SqlClient";
+import * as Statement from "effect/sql/Statement";
import * as SqlitePersistence from "../persistence/Sqlite.ts";
import * as ServerSettings from "../serverSettings.ts";
@@ -657,6 +658,151 @@ it.effect("includes shared sessions and provider-owned background rosters in rec
}).pipe(Effect.provide(layerTest)),
);
+it.effect("bounds runtime provider-thread reads by ownership and preserves recovery liveness", () =>
+ Effect.gen(function* () {
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const sql = yield* SqlClient.SqlClient;
+ const now = yield* DateTime.now;
+ const threadId = yield* createThread("ownership");
+ const other = yield* createThread("other-owner");
+ const ownerNodeId = NodeId.make("node:recovery:owner");
+ yield* projections.apply({
+ id: EventId.make("event:recovery:owner"),
+ type: "node.updated",
+ threadId,
+ nodeId: ownerNodeId,
+ driver,
+ occurredAt: now,
+ payload: {
+ id: ownerNodeId,
+ threadId,
+ runId: null,
+ parentNodeId: null,
+ rootNodeId: ownerNodeId,
+ kind: "root_turn",
+ status: "completed",
+ countsForRun: false,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ runtimeRequestId: null,
+ checkpointScopeId: null,
+ startedAt: now,
+ completedAt: now,
+ },
+ });
+ const cases = [
+ { name: "direct", ownership: "direct", status: "active", ordinal: 2, included: true },
+ { name: "owner", ownership: "owner", status: "active", ordinal: null, included: true },
+ { name: "owner-only", ownership: "owner", status: "active", ordinal: 1, included: true },
+ { name: "subagent", ownership: "subagent", status: "active", ordinal: 1, included: true },
+ { name: "duplicate", ownership: "all", status: "active", ordinal: 1, included: true },
+ { name: "roster", ownership: "direct", status: "idle", ordinal: 3, included: true },
+ { name: "run", ownership: "owner", status: "idle", ordinal: 4, included: true },
+ { name: "item", ownership: "subagent", status: "idle", ordinal: 5, included: true },
+ { name: "waiting-run", ownership: "direct", status: "idle", ordinal: 6, included: true },
+ { name: "settled", ownership: "all", status: "idle", ordinal: 7, included: false },
+ { name: "unrelated", ownership: "none", status: "active", ordinal: 8, included: false },
+ { name: "unrelated-run", ownership: "none", status: "idle", ordinal: 9, included: false },
+ ] as const;
+ for (const entry of cases) {
+ const id = ProviderThreadId.make(`provider-thread:ownership:${entry.name}`);
+ yield* projections.apply({
+ id: EventId.make(`event:${id}`),
+ type: "provider-thread.updated",
+ threadId,
+ driver,
+ providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id,
+ appThreadId:
+ entry.name === "owner-only"
+ ? null
+ : entry.ownership === "direct" || entry.ownership === "all"
+ ? threadId
+ : other,
+ ownerNodeId:
+ entry.ownership === "owner" || entry.ownership === "all" ? ownerNodeId : null,
+ driver,
+ providerInstanceId,
+ providerSessionId: null,
+ nativeThreadRef: null,
+ nativeConversationHeadRef: null,
+ status: entry.status,
+ firstRunOrdinal: entry.ordinal,
+ lastRunOrdinal: entry.ordinal,
+ handoffIds: [],
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ pendingBackgroundTasks:
+ entry.name === "roster"
+ ? [{ taskId: "shell", description: "background", kind: "command" }]
+ : [],
+ },
+ });
+ if (entry.ownership === "subagent" || entry.ownership === "all") {
+ for (const suffix of ["a", "b"]) {
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_subagents
+ (subagent_id, thread_id, parent_node_id, provider, provider_thread_id,
+ origin, status, updated_at, payload_json)
+ VALUES (${`${id}:${suffix}`}, ${threadId}, ${ownerNodeId}, 'codex', ${id},
+ 'provider_native', 'completed', '', '{}')
+ `;
+ }
+ }
+ if (entry.name === "run" || entry.name === "unrelated-run") {
+ yield* createRun(threadId, "waiting", { ordinal: entry.ordinal, providerThreadId: id });
+ }
+ }
+ const waitingProviderThreadId = ProviderThreadId.make("provider-thread:ownership:waiting-run");
+ const waitingRunId = yield* createRun(threadId, "completed", {
+ ordinal: 6,
+ providerThreadId: waitingProviderThreadId,
+ });
+ yield* sql`
+ INSERT INTO orchestration_v2_projection_turn_items
+ (turn_item_id, thread_id, run_id, node_id, provider_thread_id, ordinal, type,
+ status, updated_at, payload_json)
+ VALUES ('item:ownership', ${threadId}, ${waitingRunId}, ${ownerNodeId},
+ ${ProviderThreadId.make("provider-thread:ownership:item")}, 1, 'assistant_message', 'waiting', '', '{}')
+ `;
+ const statements: Array<ReturnType<Statement.Statement<unknown>["compile"]>> = [];
+ const observe: Statement.Transformer = (statement) => {
+ const compiled = statement.compile();
+ if (compiled[0].includes("SELECT provider_thread.payload_json")) statements.push(compiled);
+ return Effect.succeed(statement);
+ };
+ const projection = yield* projections
+ .getRuntimeRecoveryProjection(threadId)
+ .pipe(Effect.provideService(Statement.CurrentTransformer, observe));
+ assert.deepEqual(
+ projection.providerThreads.map((row) => row.id),
+ cases
+ .filter((entry) => entry.included)
+ .toSorted((a, b) => (a.ordinal ?? 0) - (b.ordinal ?? 0) || a.name.localeCompare(b.name))
+ .map((entry) => ProviderThreadId.make(`provider-thread:ownership:${entry.name}`)),
+ );
+ assert.equal(statements.length, 1);
+ const [query, params] = statements[0]!;
+ const plan = yield* sql.unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${query}`, params);
+ assert.isFalse(
+ plan.some((row) => /^SCAN provider_thread(?:$| )/.test(row.detail)),
+ JSON.stringify(plan),
+ );
+ assert.isTrue(
+ plan.some((row) => row.detail.includes("provider_threads_owner_idx")),
+ JSON.stringify(plan),
+ );
+ assert.isFalse(
+ plan.some((row) => /SEARCH (owner|n) USING INDEX .*nodes_thread/.test(row.detail)),
+ JSON.stringify(plan),
+ );
+ }).pipe(Effect.provide(layerTest)),
+);
+
it.effect("reads the run that owns a background roster, not a queued or resumed one", () =>
Effect.gen(function* () {
const projections = yield* ProjectionStore.ProjectionStoreV2;
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 451a917770e..90a9582cb64 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -4586,18 +4586,20 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
sql<PayloadRow>`
SELECT provider_thread.payload_json
FROM orchestration_v2_projection_provider_threads AS provider_thread
- WHERE (
- provider_thread.thread_id = ${threadId}
- OR EXISTS (
- SELECT 1 FROM orchestration_v2_projection_nodes AS owner
- WHERE owner.node_id = provider_thread.owner_node_id
- AND owner.thread_id = ${threadId}
- )
- OR EXISTS (
- SELECT 1 FROM orchestration_v2_projection_subagents AS subagent
- WHERE subagent.provider_thread_id = provider_thread.provider_thread_id
- AND subagent.thread_id = ${threadId}
- )
+ WHERE provider_thread.provider_thread_id IN (
+ SELECT provider_thread_id FROM orchestration_v2_projection_provider_threads
+ WHERE thread_id = ${threadId}
+ UNION
+ -- Start with non-null owners; a thread can have a large settled node history.
+ SELECT owned.provider_thread_id
+ FROM orchestration_v2_projection_provider_threads AS owned
+ INDEXED BY orchestration_v2_projection_provider_threads_owner_idx
+ CROSS JOIN orchestration_v2_projection_nodes AS owner
+ ON owner.node_id = owned.owner_node_id
+ WHERE owned.owner_node_id IS NOT NULL AND owner.thread_id = ${threadId}
+ UNION
+ SELECT provider_thread_id FROM orchestration_v2_projection_subagents
+ WHERE thread_id = ${threadId} AND provider_thread_id IS NOT NULL
)
AND (
provider_thread.status = 'active'