The best way to control Claude Code, Codex and more from any computer or phone
perf(server): index delegated recovery candidates (#30359)
Add guarded partial indexes for delegated recovery candidate selectors and retain existing recovery eligibility. Include migration and query-plan regression coverage, plus preview-upgrade expectations. GPT 6.1 Sol, Codex.
Yash Singh committed
Nov 3, 2026 at 15:35 UTC
96e887b6a866ba62ed3d6c2276651b4abb3441b1
5 files changed
+133
-3
apps/server/src/orchestration-v2/ProjectionRecovery.test.ts
+101
-2
@@ -24,6 +24,7 @@ import * as Layer from "effect/Layer";
24
import * as SqlClient from "effect/sql/SqlClient";
25
import * as Statement from "effect/sql/Statement";
26
27
+import delegatedRecoveryIndexes from "../persistence/Migrations/079_DelegatedRecoveryIndexes.ts";
28
import * as SqlitePersistence from "../persistence/Sqlite.ts";
29
import * as ServerSettings from "../serverSettings.ts";
30
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
@@ -357,8 +358,28 @@ it.effect("selects unfinished recovery work without reading settled thread histo
358
new Set(yield* projections.getRecoveryThreadIds("runtime")),
359
new Set([queued, archived, blocked, background, outboxOnly, requestOnly]),
360
);
360
- assert.deepEqual(yield* projections.getRecoveryThreadIds("delegated-completions"), [delivery]);
361
- assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), []);
361
+ for (const [kind, expected, index] of [
362
+ ["delegated-completions", [delivery], "runs_delegated_delivery_idx"],
363
+ ["subagent-results", [], "threads_subagent_result_idx"],
364
+ ] as const) {
365
+ const statements: Array<ReturnType<Statement.Statement<unknown>["compile"]>> = [];
366
+ const observe: Statement.Transformer = (statement) => {
367
+ statements.push(statement.compile());
368
+ return Effect.succeed(statement);
369
+ };
370
+ assert.deepEqual(
371
+ yield* projections
372
+ .getRecoveryThreadIds(kind)
373
+ .pipe(Effect.provideService(Statement.CurrentTransformer, observe)),
374
+ expected,
375
+ );
376
+ const [query, params] = statements[0]!;
377
+ const plan = yield* sql.unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${query}`, params);
378
+ assert.isTrue(
379
+ plan.some((row) => row.detail.includes(index)),
380
+ JSON.stringify(plan),
381
+ );
382
+ }
383
const recoveryState = yield* projections.getRuntimeRecoveryProjection(queued);
384
assert.deepEqual(
385
recoveryState.runs.map((run) => run.id),
@@ -371,6 +392,84 @@ it.effect("selects unfinished recovery work without reading settled thread histo
392
}).pipe(Effect.provide(layerTest)),
393
);
394
395
+it.effect("maintains delegated candidate indexes across legacy rows and payload transitions", () =>
396
+ Effect.gen(function* () {
397
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
398
+ const sql = yield* SqlClient.SqlClient;
399
+ const parent = yield* createThread("index-parent");
400
+ const child = yield* createThread("index-child");
401
+ const run = yield* createRun(child, "completed");
402
+ const rows = yield* sql<{ payload_json: string }>`
403
+ SELECT payload_json FROM orchestration_v2_projection_threads WHERE thread_id = ${child}
404
+ `;
405
+ const original = JSON.parse(rows[0]!.payload_json);
406
+ for (const payload of [
407
+ "{broken",
408
+ JSON.stringify({
409
+ ...original,
410
+ lineage: { parentThreadId: parent, relationshipToParent: "subagent" },
411
+ forkedFrom: { type: "provider_thread" },
412
+ }),
413
+ JSON.stringify({
414
+ ...original,
415
+ lineage: { parentThreadId: parent, relationshipToParent: "subagent" },
416
+ forkedFrom: { type: "node", nodeId: "node:index" },
417
+ }),
418
+ JSON.stringify({
419
+ ...original,
420
+ lineage: { parentThreadId: child, relationshipToParent: "subagent" },
421
+ forkedFrom: { type: "node", nodeId: "node:index" },
422
+ }),
423
+ JSON.stringify(original),
424
+ ]) {
425
+ yield* sql`UPDATE orchestration_v2_projection_threads SET payload_json = ${payload}
426
+ WHERE thread_id = ${child}`;
427
+ const expected = payload.includes('"type":"node"') ? [child] : [];
428
+ assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), expected);
429
+ }
430
+ for (const entry of [
431
+ ["{broken", false],
432
+ ["{}", false],
433
+ ['{"delegatedCompletion":{"delivery":null}}', false],
434
+ ['{"delegatedCompletion":{"delivery":[]}}', false],
435
+ ['{"delegatedCompletion":{"delivery":{}}}', true],
436
+ ["{}", false],
437
+ ] as const) {
438
+ const [payload, included] = entry;
439
+ yield* sql`UPDATE orchestration_v2_projection_runs SET payload_json = ${payload}
440
+ WHERE run_id = ${run}`;
441
+ assert.deepEqual(
442
+ yield* projections.getRecoveryThreadIds("delegated-completions"),
443
+ included ? [child] : [],
444
+ );
445
+ }
446
+ yield* sql`UPDATE orchestration_v2_projection_threads SET payload_json = '{broken'
447
+ WHERE thread_id = ${parent}`;
448
+ yield* sql`UPDATE orchestration_v2_projection_runs SET payload_json = '{broken'
449
+ WHERE run_id = ${run}`;
450
+ const existing = yield* createThread("index-existing", {
451
+ lineage: { parentThreadId: child, relationshipToParent: "subagent", rootThreadId: parent },
452
+ forkedFrom: { type: "node", nodeId: NodeId.make("node:index-existing") },
453
+ });
454
+ yield* createRun(existing, "completed", {
455
+ delegatedCompletion: {
456
+ disposition: "open",
457
+ nextGeneration: 2,
458
+ delivery: {
459
+ generation: 1,
460
+ messageId: MessageId.make("message:index-existing"),
461
+ taskIds: [],
462
+ },
463
+ },
464
+ });
465
+ yield* sql`DROP INDEX orchestration_v2_projection_threads_subagent_result_idx`;
466
+ yield* sql`DROP INDEX orchestration_v2_projection_runs_delegated_delivery_idx`;
467
+ yield* delegatedRecoveryIndexes;
468
+ assert.deepEqual(yield* projections.getRecoveryThreadIds("subagent-results"), [existing]);
469
+ assert.deepEqual(yield* projections.getRecoveryThreadIds("delegated-completions"), [existing]);
470
+ }).pipe(Effect.provide(layerTest)),
471
+);
472
+
473
it.effect("recovers terminal subagent results until their cross-thread transfer exists", () =>
474
Effect.gen(function* () {
475
const projections = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+1
-1
@@ -4121,6 +4121,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4121
json_extract(child.payload_json, '$.lineage.relationshipToParent') = 'subagent'
4122
AND json_extract(child.payload_json, '$.lineage.parentThreadId') IS NOT NULL
4123
AND json_extract(child.payload_json, '$.forkedFrom.type') = 'node'
4124
+ ELSE 0 END
4125
AND (EXISTS (
4126
SELECT 1 FROM orchestration_v2_projection_runs AS requested
4127
JOIN orchestration_v2_projection_subagents AS task
@@ -4143,7 +4144,6 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4144
AND target_thread_id = json_extract(child.payload_json, '$.lineage.parentThreadId')
4145
AND type = 'subagent_result'
4146
)))
4146
- ELSE 0 END
4147
`;
4148
case "runtime":
4149
return sql`
apps/server/src/persistence/Migrations.ts
+3
@@ -82,6 +82,8 @@ import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
82
import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts";
83
import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts";
84
85
+import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts";
86
+
87
const migrationEntries = [
88
[1, "OrchestrationEvents", Migration0001],
89
[2, "OrchestrationCommandReceipts", Migration0002],
@@ -162,6 +164,7 @@ const migrationEntries = [
164
[76, "ProjectionProjectsPinArchive", Migration0076],
165
[77, "RepairBooleanSettledOverride", Migration0077],
166
[78, "DropOrchestrationEventCorrelationIndex", Migration0078],
167
+ [79, "DelegatedRecoveryIndexes", Migration0079],
168
] as const;
169
170
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/079_DelegatedRecoveryIndexes.ts
new
+26
@@ -0,0 +1,26 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/sql/SqlClient";
3
+
4
+export default Effect.gen(function* () {
5
+ const sql = yield* SqlClient.SqlClient;
6
+
7
+ // Include the parent ID so transfer checks do not reread each child payload.
8
+ yield* sql`
9
+ CREATE INDEX orchestration_v2_projection_threads_subagent_result_idx
10
+ ON orchestration_v2_projection_threads(
11
+ thread_id, json_extract(payload_json, '$.lineage.parentThreadId')
12
+ )
13
+ WHERE CASE WHEN json_valid(payload_json) THEN
14
+ json_extract(payload_json, '$.lineage.relationshipToParent') = 'subagent'
15
+ AND json_extract(payload_json, '$.lineage.parentThreadId') IS NOT NULL
16
+ AND json_extract(payload_json, '$.forkedFrom.type') = 'node'
17
+ ELSE 0 END
18
+ `;
19
+ yield* sql`
20
+ CREATE INDEX orchestration_v2_projection_runs_delegated_delivery_idx
21
+ ON orchestration_v2_projection_runs(thread_id)
22
+ WHERE CASE WHEN json_valid(payload_json)
23
+ THEN json_type(payload_json, '$.delegatedCompletion.delivery') = 'object'
24
+ ELSE 0 END
25
+ `;
26
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -58,6 +58,7 @@ describe("V2 preview upgrade", () => {
58
[76, "ProjectionProjectsPinArchive"],
59
[77, "RepairBooleanSettledOverride"],
60
[78, "DropOrchestrationEventCorrelationIndex"],
61
+ [79, "DelegatedRecoveryIndexes"],
62
]);
63
assert.deepStrictEqual(yield* runMigrations(), []);
64
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -159,6 +160,7 @@ describe("V2 preview upgrade", () => {
160
[76, "ProjectionProjectsPinArchive"],
161
[77, "RepairBooleanSettledOverride"],
162
[78, "DropOrchestrationEventCorrelationIndex"],
163
+ [79, "DelegatedRecoveryIndexes"],
164
]);
165
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
166
);