The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 06:00 UTC
perf(server): finalizing a delegated task no longer reads the child's whole turn history (#39325)
Julius Marminge committed
Nov 19, 2026 at 13:46 UTC
66b8a94f8d10e6ef123c134852c94642c4f1324c
9 files changed
+333
-51
apps/server/src/orchestration-v2/Orchestrator.ts
+124
-40
@@ -201,6 +201,7 @@ import {
201
subagentResultForRun,
202
delegatedTaskProgress,
203
delegatedTaskReportRuns,
204
+ monitorUpdateRunIds,
205
subagentThreadTitle,
206
} from "@t3tools/provider-core/server/subagentProjection";
207
import {
@@ -1286,6 +1287,41 @@ function runForSourcePoint(
1287
}
1288
}
1289
1290
+const DELEGATED_CHILD_RUN_WINDOW = 20;
1291
+
1292
+type DelegatedChildControls = ProjectionRecords<
1293
+ "runs" | "messages" | "subagents" | "providerThreads"
1294
+> & {
1295
+ /** Set when `runs` holds only what ran since this run, plus older unfinished and task runs. */
1296
+ readonly runsFloor?: OrchestrationV2Run | undefined;
1297
+};
1298
+
1299
+function ranSince(run: OrchestrationV2Run, floor: OrchestrationV2Run): boolean {
1300
+ return run.id === floor.id || runRanAfter(run, floor);
1301
+}
1302
+
1303
+/** The walk back to a report is exact when it stops at a run that ran since the floor. */
1304
+function reportRunsRead(
1305
+ controls: DelegatedChildControls,
1306
+ run: OrchestrationV2Run,
1307
+ reportRuns: ReadonlyArray<OrchestrationV2Run>,
1308
+): boolean {
1309
+ const floor = controls.runsFloor;
1310
+ if (floor === undefined || run.status !== "completed") return true;
1311
+ const oldest = reportRuns.at(-1) ?? run;
1312
+ if (!ranSince(oldest, floor)) return false;
1313
+ const monitorRuns = monitorUpdateRunIds(controls.messages);
1314
+ return controls.runs.some(
1315
+ (candidate) =>
1316
+ candidate.id !== run.id &&
1317
+ candidate.startedAt !== null &&
1318
+ candidate.status !== "rolled_back" &&
1319
+ !monitorRuns.has(candidate.id) &&
1320
+ runRanAfter(oldest, candidate) &&
1321
+ ranSince(candidate, floor),
1322
+ );
1323
+}
1324
+
1325
function providerThreadForRun(
1326
projection: Pick<OrchestrationV2ThreadProjection, "providerThreads">,
1327
run: OrchestrationV2Run,
@@ -14621,23 +14657,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14657
// A finished delegate otherwise keeps its provider process until the idle timeout. Callers hold
14658
// the parent lock; the child lock orders this after any follow-up that started a run meanwhile.
14659
const releaseFinishedDelegateSessions = Effect.fn("Orchestrator.releaseFinishedDelegateSessions")(
14624
- function* (childThreadId: ThreadId, resultRunId: RunId) {
14660
+ function* (childThreadId: ThreadId, resultRunId: RunId, taskId: NodeId) {
14661
yield* threadDispatch.withLock(
14662
childThreadId,
14663
Effect.gen(function* () {
14628
- const child = yield* projectionStore.getThreadRecords(
14629
- childThreadId,
14630
- ["runs", "messages", "subagents", "providerThreads", "providerSessions"],
14631
- { messageRoles: ["user"] },
14632
- );
14664
+ const { controls: child, progress } = yield* readDelegatedChildControls(childThreadId, [
14665
+ taskId,
14666
+ ]);
14667
// Unawaited background tasks still allow a result but die with the process; the idle
14668
// timer keeps their process pinned.
14669
if (
14636
- delegatedTaskProgress(child).state !== "result_available" ||
14670
+ progress.state !== "result_available" ||
14671
child.providerThreads.some((thread) => (thread.pendingBackgroundTasks ?? []).length > 0)
14672
)
14673
return;
14640
- for (const session of child.providerSessions) {
14674
+ const { providerSessions } = yield* projectionStore.getThreadRecords(childThreadId, [
14675
+ "providerSessions",
14676
+ ]);
14677
+ for (const session of providerSessions) {
14678
// Shared processes unload their threads themselves; only a per-thread process lingers.
14679
if (
14680
session.status === "stopped" ||
@@ -14663,15 +14700,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14700
),
14701
);
14702
14703
+ const readAllDelegatedChildControls = (childThreadId: ThreadId) =>
14704
+ projectionStore.getThreadRecords(
14705
+ childThreadId,
14706
+ ["runs", "messages", "subagents", "providerThreads"],
14707
+ { messageRoles: ["user"], delegatedTaskMessagesOnly: true },
14708
+ );
14709
+
14710
+ const readDelegatedChildControls = Effect.fn("Orchestrator.readDelegatedChildControls")(
14711
+ function* (childThreadId: ThreadId, taskIds: ReadonlyArray<NodeId>) {
14712
+ const controls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls(
14713
+ childThreadId,
14714
+ { taskIds, windowSize: DELEGATED_CHILD_RUN_WINDOW },
14715
+ );
14716
+ const progress = delegatedTaskProgress(controls);
14717
+ // The latest result may have ended before the runs read above; then read them all.
14718
+ if (
14719
+ controls.runsFloor !== undefined &&
14720
+ (progress.resultRun === undefined || !ranSince(progress.resultRun, controls.runsFloor))
14721
+ ) {
14722
+ const all = yield* readAllDelegatedChildControls(childThreadId);
14723
+ return { controls: all, progress: delegatedTaskProgress(all) };
14724
+ }
14725
+ return { controls, progress };
14726
+ },
14727
+ );
14728
+
14729
/**
14730
* Callers must hold the parent thread's dispatch lock: wake-policy updates the same
14731
* subagent row with full-row payloads, so unserialized writers clobber policy or terminal status.
14732
*/
14733
const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")(
14734
function* (
14672
- childControls: ProjectionRecords<
14673
- "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts"
14674
- >,
14735
+ childControls: DelegatedChildControls,
14736
options: {
14737
readonly settledContinuationOf?: RunId;
14738
readonly syncRunId?: RunId;
@@ -14776,23 +14837,45 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14837
}
14838
14839
// A run queued behind the report can end the task without saying anything.
14779
- const reportRuns = delegatedTaskReportRuns(childControls, { ...childRun, status: outcome });
14840
+ const reportFrom = { ...childRun, status: outcome };
14841
+ let reportRuns = delegatedTaskReportRuns(childControls, reportFrom);
14842
+ if (!reportRunsRead(childControls, reportFrom, reportRuns)) {
14843
+ reportRuns = delegatedTaskReportRuns(
14844
+ yield* readAllDelegatedChildControls(childThreadId),
14845
+ reportFrom,
14846
+ );
14847
+ }
14848
const resultRunIds = [childRun.id, ...reportRuns.map((run) => run.id)];
14849
const childResult = yield* projectionStore.getThreadRecords(
14850
childThreadId,
14783
- ["messages", "turnItems"],
14851
+ ["messages", "turnItems", "providerTurns", "attempts"],
14852
{
14853
messageRoles: ["assistant"],
14854
messageRunIds: resultRunIds,
14855
turnItemRunIds: resultRunIds,
14856
turnItemTypes: ["assistant_message", "error", "system_notice"],
14857
+ providerTurnAttemptIds: [childRun, ...reportRuns].flatMap(
14858
+ (run) => run.activeAttemptId ?? [],
14859
+ ),
14860
+ attemptIds: childRun.activeAttemptId === null ? [] : [childRun.activeAttemptId],
14861
},
14862
);
14863
+ // A steered run's attempt can point at a provider turn that another attempt started.
14864
+ const attemptTurnId = childResult.attempts[0]?.providerTurnId;
14865
+ const steeredTurns =
14866
+ attemptTurnId == null ||
14867
+ childResult.providerTurns.some((turn) => turn.runAttemptId === childRun.activeAttemptId)
14868
+ ? []
14869
+ : (yield* projectionStore.getThreadRecords(childThreadId, ["providerTurns"], {
14870
+ providerTurnIds: [attemptTurnId],
14871
+ })).providerTurns;
14872
const childProjection = {
14873
...childControls,
14874
runs: reportRuns,
14875
messages: childResult.messages,
14876
turnItems: childResult.turnItems,
14877
+ providerTurns: [...childResult.providerTurns, ...steeredTurns],
14878
+ attempts: childResult.attempts,
14879
};
14880
const parentThreadId = childControls.thread.lineage.parentThreadId;
14881
// The task's node and turn item share its id.
@@ -14957,7 +15040,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15040
},
15041
];
15042
yield* writeSystemEvents(completionEvents, [], { updateDelegatedCompletionOnly: true });
14960
- yield* releaseFinishedDelegateSessions(childThreadId, childRun.id);
15043
+ yield* releaseFinishedDelegateSessions(childThreadId, childRun.id, task.id);
15044
15045
if (completionPlan.offer && completionPlan.parentRun !== undefined) {
15046
yield* offerDelegatedCompletionDelivery(parentThreadId, completionPlan.parentRun.id);
@@ -14978,41 +15061,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15061
childThreadId: ThreadId,
15062
options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId },
15063
) {
14981
- const childControls = yield* projectionStore.getThreadRecords(
14982
- childThreadId,
14983
- ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"],
14984
- { messageRoles: ["user"] },
14985
- );
14986
- const parentThreadId = childControls.thread.lineage.parentThreadId;
15064
+ const child = yield* projectionStore.getThreadRecords(childThreadId, ["contextTransfers"]);
15065
+ const parentThreadId = child.thread.lineage.parentThreadId;
15066
+ const forkedFrom = child.thread.forkedFrom;
15067
if (
14988
- childControls.thread.lineage.relationshipToParent !== "subagent" ||
15068
+ child.thread.lineage.relationshipToParent !== "subagent" ||
15069
parentThreadId === null ||
14990
- childControls.thread.forkedFrom?.type !== "node"
15070
+ forkedFrom?.type !== "node"
15071
)
15072
return;
14993
- const progress = delegatedTaskProgress(childControls);
15073
// Each task of this child names it, so the parent's other tasks stay unread.
15074
const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], {
15075
subagentChildThreadIds: [childThreadId],
15076
});
14998
- const { contextTransfers } = yield* projectionStore.getThreadRecords(childThreadId, [
14999
- "contextTransfers",
15000
- ]);
15001
- for (const task of parent.subagents) {
15077
+ const resultSent = child.contextTransfers.some(
15078
+ (transfer) =>
15079
+ transfer.type === "subagent_result" &&
15080
+ transfer.sourceThreadId === childThreadId &&
15081
+ transfer.targetThreadId === parentThreadId,
15082
+ );
15083
+ const openTasks = parent.subagents.filter(
15084
+ (task) =>
15085
+ task.origin === "app_owned" &&
15086
+ task.childThreadId === childThreadId &&
15087
+ !(task.result !== null && resultSent),
15088
+ );
15089
+ const { controls: childControls, progress } = yield* readDelegatedChildControls(
15090
+ childThreadId,
15091
+ openTasks.map((task) => task.id),
15092
+ );
15093
+ for (const task of openTasks) {
15094
// A cancelled task does not wait for the work its cancel is stopping.
15095
const cancelled = task.cancelledRunId !== undefined;
15096
if (
15005
- task.origin !== "app_owned" ||
15006
- task.childThreadId !== childThreadId ||
15007
- (task.id === childControls.thread.forkedFrom.nodeId &&
15008
- (cancelled ? progress.state === "working" : progress.state !== "result_available")) ||
15009
- (task.result !== null &&
15010
- contextTransfers.some(
15011
- (transfer) =>
15012
- transfer.type === "subagent_result" &&
15013
- transfer.sourceThreadId === childThreadId &&
15014
- transfer.targetThreadId === parentThreadId,
15015
- ))
15097
+ task.id === forkedFrom.nodeId &&
15098
+ (cancelled ? progress.state === "working" : progress.state !== "result_available")
15099
)
15100
continue;
15101
yield* finalizeAppOwnedSubagentTask(childControls, {
@@ -15025,7 +15108,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15108
// Only the run a cancelled task settled from ends with it. The row read above has no
15109
// such run yet when this call settled the task, from the same result run.
15110
const { resultRun } = progress;
15028
- const resultTaskId = resultRun?.delegatedTaskId ?? childControls.thread.forkedFrom.nodeId;
15111
+ const resultTaskId = resultRun?.delegatedTaskId ?? forkedFrom.nodeId;
15112
const resultTask = parent.subagents.find((task) => task.id === resultTaskId);
15113
const taskCancelled =
15114
resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id;
@@ -15064,7 +15147,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15147
run =
15148
previousRunId === undefined
15149
? undefined
15067
- : childControls.runs.find((candidate) => candidate.id === previousRunId);
15150
+ : (childControls.runs.find((candidate) => candidate.id === previousRunId) ??
15151
+ (yield* projectionStore.getRun(childThreadId, previousRunId)));
15152
}
15153
for (const request of pendingQuestions) {
15154
if (
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+76
-10
@@ -1385,6 +1385,7 @@ it.effect("record reads filter notification sources without dropping matching me
1385
["monitor", "user", "monitor"],
1386
["system", "user", "system"],
1387
["assistant-monitor", "assistant", "monitor"],
1388
+ ["wake", "user", "wake"],
1389
] as const) {
1390
yield* store.apply({
1391
id: EventId.make(`notification-filter:${id}`),
@@ -1406,13 +1407,21 @@ it.effect("record reads filter notification sources without dropping matching me
1407
updatedAt: now,
1408
...(kind === null
1409
? {}
1409
- : {
1410
- notification: {
1411
- source: { kind },
1412
- outcome: "updated",
1413
- summary: "Background notification",
1414
- },
1415
- }),
1410
+ : kind === "wake"
1411
+ ? {
1412
+ delegatedCompletion: {
1413
+ parentRunId: RunId.make("run:wake-parent"),
1414
+ generation: 1,
1415
+ taskIds: [],
1416
+ },
1417
+ }
1418
+ : {
1419
+ notification: {
1420
+ source: { kind },
1421
+ outcome: "updated",
1422
+ summary: "Background notification",
1423
+ },
1424
+ }),
1425
},
1426
});
1427
}
@@ -1424,11 +1433,19 @@ it.effect("record reads filter notification sources without dropping matching me
1433
matching.messages.map((message) => [message.id, message.text]),
1434
[["monitor", "Complete body for monitor"]],
1435
);
1436
+ const delegatedTaskMessages = yield* store.getThreadRecords(threadId, ["messages"], {
1437
+ messageRoles: ["user"],
1438
+ delegatedTaskMessagesOnly: true,
1439
+ });
1440
+ assert.deepEqual(
1441
+ delegatedTaskMessages.messages.map((message) => message.id),
1442
+ ["monitor", "wake"],
1443
+ );
1444
const { statements, tracer } = traceSqlStatements();
1445
const userMessages = yield* store
1446
.getThreadRecords(threadId, ["messages"], { messageRoles: ["user"] })
1447
.pipe(Effect.withTracer(tracer));
1431
- assert.lengthOf(userMessages.messages, 3);
1448
+ assert.lengthOf(userMessages.messages, 4);
1449
const ordinalLookup = statements.find((statement) => statement.includes("MIN(ordinal)"));
1450
// User-only reads must seek the message-ordinal index instead of scanning every turn item.
1451
yield* assertReadsThroughMessageOrdinalIndex(ordinalLookup, ["thread_id=?", "<expr>=?"]);
@@ -1442,7 +1459,7 @@ it.effect("record reads filter notification sources without dropping matching me
1459
.pipe(Effect.withTracer(withItems.tracer));
1460
assert.deepEqual(ordered.messages, userMessages.messages);
1461
assert.isFalse(withItems.statements.some((statement) => statement.includes("MIN(ordinal)")));
1445
- assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 4);
1462
+ assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 5);
1463
assert.lengthOf(
1464
(yield* store.getThreadRecords(threadId, ["messages"], {
1465
monitorNotificationsOnly: true,
@@ -1453,7 +1470,56 @@ it.effect("record reads filter notification sources without dropping matching me
1470
(yield* store.getThreadRecords(threadId, ["messages"], {
1471
monitorNotificationsOnly: false,
1472
})).messages,
1456
- 4,
1473
+ 5,
1474
+ );
1475
+ }).pipe(Effect.provide(layerTest)),
1476
+);
1477
+
1478
+it.effect("reads a delegated child's recent, unfinished and task runs without its history", () =>
1479
+ Effect.gen(function* () {
1480
+ const store = yield* ProjectionStore.ProjectionStoreV2;
1481
+ const threadId = yield* addRolledBackRecoveryCandidate("delegated-child-runs");
1482
+ const first = (yield* store.getThreadRecords(threadId, ["runs"])).runs[0]!;
1483
+ const at = (minutes: number) => DateTime.add(first.requestedAt, { minutes: minutes + 60 });
1484
+ const id = (ordinal: number) => RunId.make(`run:delegated-child-runs:${ordinal}`);
1485
+ const unstartedCancel = { status: "cancelled", startedAt: null } as const;
1486
+ for (const [ordinal, patch] of [
1487
+ [3, { status: "running", completedAt: null }],
1488
+ // Unstarted cancelled runs are outside the window's index: one ends after the floor.
1489
+ [4, { ...unstartedCancel, completedAt: at(20) }],
1490
+ [5, { ...unstartedCancel, completedAt: at(1) }],
1491
+ ...[2, 6, 7, 8, 9, 10, 11, 12].map((ordinal) => [ordinal, {}] as const),
1492
+ ] as const) {
1493
+ yield* store.apply({
1494
+ id: EventId.make(`event:delegated-child-runs:${ordinal}`),
1495
+ type: "run.created",
1496
+ threadId,
1497
+ runId: id(ordinal),
1498
+ occurredAt: first.requestedAt,
1499
+ payload: {
1500
+ ...first,
1501
+ id: id(ordinal),
1502
+ ordinal,
1503
+ status: "completed",
1504
+ startedAt: at(ordinal),
1505
+ completedAt: at(ordinal),
1506
+ delegatedTaskId: NodeId.make(`node:delegated-child-runs:task:${ordinal}`),
1507
+ ...patch,
1508
+ },
1509
+ });
1510
+ }
1511
+ const taskIds = [NodeId.make("node:delegated-child-runs:task:2")];
1512
+ const bounded = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 3 });
1513
+ assert.equal(bounded.runsFloor?.id, id(11));
1514
+ assert.deepEqual(
1515
+ bounded.runs.map((run) => run.id),
1516
+ [2, 3, 4, 11, 12].map(id),
1517
+ );
1518
+ const whole = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 100 });
1519
+ assert.isUndefined(whole.runsFloor);
1520
+ assert.deepEqual(
1521
+ whole.runs.map((run) => run.id),
1522
+ (yield* store.getThreadRecords(threadId, ["runs"])).runs.map((run) => run.id),
1523
);
1524
}).pipe(Effect.provide(layerTest)),
1525
);
apps/server/src/orchestration-v2/ProjectionStore.ts
+96
@@ -103,6 +103,7 @@ import type * as Statement from "effect/sql/Statement";
103
104
import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp";
105
import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts";
106
+import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts";
107
import {
108
DEFERRED_COMMAND_MESSAGE_CONDITION,
109
JAVASCRIPT_TRIM_WHITESPACE,
@@ -375,6 +376,8 @@ export interface ProjectionRecordFilter {
376
readonly attemptIds?: ReadonlyArray<RunAttemptId>;
377
readonly messageRoles?: ReadonlyArray<OrchestrationV2ConversationMessage["role"]>;
378
readonly monitorNotificationsOnly?: boolean;
379
+ /** User messages that are monitor notifications or delegated-completion wakes, through their partial index. */
380
+ readonly delegatedTaskMessagesOnly?: true;
381
readonly turnItemRunId?: RunId;
382
readonly messageIds?: ReadonlyArray<MessageId>;
383
readonly messageRunIds?: ReadonlyArray<RunId>;
@@ -816,6 +819,20 @@ export interface ProjectionStoreV2Shape {
819
threadId: ThreadId,
820
runId: RunId,
821
) => Effect.Effect<OrchestrationV2Run | undefined, ProjectionStoreV2Error>;
822
+ /**
823
+ * One snapshot: the `windowSize` runs that ended last, unfinished runs, the runs of `taskIds` and
824
+ * their wakes. `runsFloor` is set when older runs were left out; every run that ran after it is
825
+ * in `runs`.
826
+ */
827
+ readonly getDelegatedChildControls: (
828
+ threadId: ThreadId,
829
+ input: { readonly taskIds: ReadonlyArray<NodeId>; readonly windowSize: number },
830
+ ) => Effect.Effect<
831
+ ProjectionRecords<"runs" | "messages" | "subagents" | "providerThreads"> & {
832
+ readonly runsFloor: OrchestrationV2Run | undefined;
833
+ },
834
+ ProjectionStoreV2Error
835
+ >;
836
readonly canStartQueuedRun: (
837
threadId: ThreadId,
838
) => Effect.Effect<boolean, ProjectionStoreV2Error>;
@@ -4437,6 +4454,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4454
${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`}
4455
${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`}
4456
${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``}
4457
+ ${filter?.delegatedTaskMessagesOnly === true ? sql`AND ${sql.literal(DELEGATED_TASK_MESSAGE_CONDITION)}` : sql``}
4458
${filter?.messageRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageRunIds)}))`}
4459
ORDER BY created_at ASC, message_id ASC
4460
`
@@ -6475,6 +6493,83 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6493
)
6494
.pipe(Effect.mapError(controlReadError(threadId)));
6495
6496
+ const getDelegatedChildControls: ProjectionStoreV2Shape["getDelegatedChildControls"] = (
6497
+ threadId,
6498
+ { taskIds, windowSize },
6499
+ ) =>
6500
+ sql
6501
+ .withTransaction(
6502
+ Effect.gen(function* () {
6503
+ const records = yield* getThreadRecords(
6504
+ threadId,
6505
+ ["messages", "subagents", "providerThreads"],
6506
+ { messageRoles: ["user"], delegatedTaskMessagesOnly: true },
6507
+ );
6508
+ // Spells migration 84's order and predicate so the window walks that index.
6509
+ const windowRows = yield* sql<PayloadRow & { readonly completed_at: string | null }>`
6510
+ SELECT payload_json, completed_at FROM orchestration_v2_projection_runs
6511
+ WHERE thread_id = ${threadId}
6512
+ AND status <> 'queued'
6513
+ AND NOT (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL)
6514
+ ORDER BY (completed_at IS NULL) DESC, completed_at DESC, ordinal DESC, run_id DESC
6515
+ LIMIT ${windowSize}
6516
+ `;
6517
+ const window = yield* decodeRows(decodeRunPayload, threadId)(windowRows);
6518
+ const last = window.length < windowSize ? undefined : window.at(-1);
6519
+ const floorCompletedAt = windowRows.at(-1)?.completed_at ?? null;
6520
+ // A window ending in unfinished runs bounds nothing, so read the whole thread.
6521
+ const floor = floorCompletedAt === null ? undefined : last;
6522
+ const rest = yield* (
6523
+ last !== undefined && floor === undefined
6524
+ ? sql<PayloadRow>`
6525
+ SELECT payload_json FROM orchestration_v2_projection_runs
6526
+ WHERE thread_id = ${threadId}`
6527
+ : sql<PayloadRow>`
6528
+ SELECT payload_json FROM orchestration_v2_projection_runs
6529
+ WHERE thread_id = ${threadId}
6530
+ AND status IN ('preparing', 'queued', 'starting', 'running', 'waiting')
6531
+ UNION
6532
+ SELECT payload_json FROM orchestration_v2_projection_runs
6533
+ WHERE thread_id = ${threadId} AND json_valid(payload_json)
6534
+ AND json_extract(payload_json, '$.delegatedTaskId') IS NOT NULL
6535
+ AND json_extract(payload_json, '$.delegatedTaskId')
6536
+ IN (SELECT value FROM json_each(${encodeIdList(taskIds)}))
6537
+ UNION
6538
+ -- Unstarted cancelled runs are outside the window's index.
6539
+ SELECT payload_json FROM orchestration_v2_projection_runs
6540
+ WHERE thread_id = ${threadId} AND status = 'cancelled'
6541
+ ${floor === undefined ? sql`` : sql`AND (completed_at IS NULL OR completed_at >= ${floorCompletedAt})`}`
6542
+ ).pipe(Effect.flatMap(decodeRows(decodeRunPayload, threadId)));
6543
+ const runs = new Map([...window, ...rest].map((run) => [run.id, run]));
6544
+ const requested = new Set<RunId>();
6545
+ for (;;) {
6546
+ const wakeRunIds = [
6547
+ ...new Set(
6548
+ records.messages.flatMap((message) =>
6549
+ message.runId !== null &&
6550
+ message.delegatedCompletion !== undefined &&
6551
+ runs.has(message.delegatedCompletion.parentRunId) &&
6552
+ !runs.has(message.runId) &&
6553
+ !requested.has(message.runId)
6554
+ ? [message.runId]
6555
+ : [],
6556
+ ),
6557
+ ),
6558
+ ];
6559
+ if (wakeRunIds.length === 0) break;
6560
+ for (const id of wakeRunIds) requested.add(id);
6561
+ const wakes = yield* getThreadRecords(threadId, ["runs"], { runIds: wakeRunIds });
6562
+ for (const run of wakes.runs) runs.set(run.id, run);
6563
+ }
6564
+ return {
6565
+ ...records,
6566
+ runs: [...runs.values()].toSorted((a, b) => a.ordinal - b.ordinal),
6567
+ runsFloor: floor,
6568
+ };
6569
+ }),
6570
+ )
6571
+ .pipe(Effect.mapError(controlReadError(threadId)));
6572
+
6573
const getRun: ProjectionStoreV2Shape["getRun"] = (threadId, runId) =>
6574
sql
6575
.withTransaction(
@@ -9669,6 +9764,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
9764
getCheckpointCaptureContext: readOnReader(getCheckpointCaptureContext),
9765
getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext),
9766
getRunMessage: readOnReader(getRunMessage),
9767
+ getDelegatedChildControls: readOnReader(getDelegatedChildControls),
9768
getRun: readOnReader(getRun),
9769
canStartQueuedRun: readOnReader(canStartQueuedRun),
9770
getHeldQueuedRuns: readOnReader(getHeldQueuedRuns),
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+1
@@ -187,6 +187,7 @@ function layerProjectionStore(
187
getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
188
getCheckpointCaptureContext: () => Effect.die("not used"),
189
getRunMessage: () => Effect.die("not used"),
190
+ getDelegatedChildControls: () => Effect.die("not used"),
191
getRun: () => Effect.die("not used"),
192
isNodeStored: () => Effect.die("not used"),
193
canStartQueuedRun: () => Effect.die("not used"),
apps/server/src/orchestration-v2/delegatedTaskMessage.ts
new
+9
@@ -0,0 +1,9 @@
1
+/**
2
+ * A user message that marks its run as a monitor update or a delegated-completion wake: what
3
+ * `delegatedTaskProgress` and `delegatedTaskRuns` read. The partial index on it is only used when
4
+ * the read spells this text the same way.
5
+ */
6
+export const DELEGATED_TASK_MESSAGE_CONDITION = `role = 'user' AND json_valid(payload_json) AND (
7
+ json_extract(payload_json, '$.notification.source.kind') = 'monitor'
8
+ OR json_extract(payload_json, '$.delegatedCompletion') IS NOT NULL
9
+)`;
apps/server/src/persistence/Migrations.ts
+2
@@ -108,6 +108,7 @@ import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts";
108
import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts";
109
import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts";
110
import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts";
111
+import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts";
112
113
const migrationEntries = [
114
[1, "OrchestrationEvents", Migration0001],
@@ -211,6 +212,7 @@ const migrationEntries = [
212
[98, "ActiveShellIndexIndexes", Migration0098],
213
[99, "BackgroundRecoveryIndexes", Migration0099],
214
[100, "TurnStartReadIndexes", Migration0100],
215
+ [101, "DelegatedTaskReadIndexes", Migration0101],
216
] as const;
217
218
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts
new
+22
@@ -0,0 +1,22 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/sql/SqlClient";
3
+
4
+import { DELEGATED_TASK_MESSAGE_CONDITION } from "../../orchestration-v2/delegatedTaskMessage.ts";
5
+
6
+export default Effect.gen(function* () {
7
+ const sql = yield* SqlClient.SqlClient;
8
+
9
+ // Finalizing a delegated task finds its tasks' runs and the child's wakes without reading the
10
+ // child's history. ProjectionStore.getDelegatedChildControls and the delegatedTaskMessagesOnly read
11
+ // must spell the same expressions.
12
+ yield* sql`
13
+ CREATE INDEX IF NOT EXISTS orchestration_v2_projection_runs_delegated_task_idx
14
+ ON orchestration_v2_projection_runs(thread_id, json_extract(payload_json, '$.delegatedTaskId'))
15
+ WHERE json_valid(payload_json) AND json_extract(payload_json, '$.delegatedTaskId') IS NOT NULL
16
+ `;
17
+ yield* sql.unsafe(`
18
+ CREATE INDEX IF NOT EXISTS orchestration_v2_projection_messages_delegated_task_idx
19
+ ON orchestration_v2_projection_messages(thread_id, created_at, message_id)
20
+ WHERE ${DELEGATED_TASK_MESSAGE_CONDITION}
21
+ `);
22
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -80,6 +80,7 @@ describe("V2 preview upgrade", () => {
80
[98, "ActiveShellIndexIndexes"],
81
[99, "BackgroundRecoveryIndexes"],
82
[100, "TurnStartReadIndexes"],
83
+ [101, "DelegatedTaskReadIndexes"],
84
]);
85
assert.deepStrictEqual(yield* runMigrations(), []);
86
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -203,6 +204,7 @@ describe("V2 preview upgrade", () => {
204
[98, "ActiveShellIndexIndexes"],
205
[99, "BackgroundRecoveryIndexes"],
206
[100, "TurnStartReadIndexes"],
207
+ [101, "DelegatedTaskReadIndexes"],
208
]);
209
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
210
);
packages/provider-core/src/server/subagentProjection.ts
+1
-1
@@ -206,7 +206,7 @@ function stopNotice(
206
type MonitorNotice = Pick<OrchestrationV2ConversationMessage, "runId" | "notification">;
207
208
/** Runs that only acknowledge a monitor update are never a task's work. */
209
-function monitorUpdateRunIds(messages: ReadonlyArray<MonitorNotice>) {
209
+export function monitorUpdateRunIds(messages: ReadonlyArray<MonitorNotice>) {
210
return new Set(
211
messages
212
.filter(