From 0064c7bd82685186deffe663295d8e833f6df731 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 18:43:57 +0000 Subject: [PATCH 1/3] perf(server): finalizing a delegated task no longer reads the child's whole turn history finalizeAppOwnedSubagent read every user message, attempt and provider turn the child ever had while holding the parent's lock. Its decisions only read monitor notifications and delegated-completion wakes among the user messages, and the attempt and provider turns of the run the result comes from. Read just those. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 25 ++++++++++--- .../orchestration-v2/ProjectionStore.test.ts | 37 ++++++++++++++----- .../src/orchestration-v2/ProjectionStore.ts | 3 ++ 3 files changed, 49 insertions(+), 16 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6a72d8a6a7f5..03ea1dfcb957 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14649,9 +14649,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio */ const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")( function* ( - childControls: ProjectionRecords< - "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts" - >, + childControls: ProjectionRecords<"runs" | "messages" | "subagents" | "providerThreads">, options: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId; @@ -14760,19 +14758,34 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const resultRunIds = [childRun.id, ...reportRuns.map((run) => run.id)]; const childResult = yield* projectionStore.getThreadRecords( childThreadId, - ["messages", "turnItems"], + ["messages", "turnItems", "providerTurns", "attempts"], { messageRoles: ["assistant"], messageRunIds: resultRunIds, turnItemRunIds: resultRunIds, turnItemTypes: ["assistant_message", "error", "system_notice"], + providerTurnAttemptIds: [childRun, ...reportRuns].flatMap( + (run) => run.activeAttemptId ?? [], + ), + attemptIds: childRun.activeAttemptId === null ? [] : [childRun.activeAttemptId], }, ); + // A steered run's attempt can point at a provider turn that another attempt started. + const attemptTurnId = childResult.attempts[0]?.providerTurnId; + const steeredTurns = + attemptTurnId == null || + childResult.providerTurns.some((turn) => turn.runAttemptId === childRun.activeAttemptId) + ? [] + : (yield* projectionStore.getThreadRecords(childThreadId, ["providerTurns"], { + providerTurnIds: [attemptTurnId], + })).providerTurns; const childProjection = { ...childControls, runs: reportRuns, messages: childResult.messages, turnItems: childResult.turnItems, + providerTurns: [...childResult.providerTurns, ...steeredTurns], + attempts: childResult.attempts, }; const parentThreadId = childControls.thread.lineage.parentThreadId; // The task's node and turn item share its id. @@ -14960,8 +14973,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { const childControls = yield* projectionStore.getThreadRecords( childThreadId, - ["runs", "messages", "subagents", "providerThreads", "providerTurns", "attempts"], - { messageRoles: ["user"] }, + ["runs", "messages", "subagents", "providerThreads"], + { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, ); const parentThreadId = childControls.thread.lineage.parentThreadId; if ( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 5a1baf63d997..13eeb4a075dd 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1385,6 +1385,7 @@ it.effect("record reads filter notification sources without dropping matching me ["monitor", "user", "monitor"], ["system", "user", "system"], ["assistant-monitor", "assistant", "monitor"], + ["wake", "user", "wake"], ] as const) { yield* store.apply({ id: EventId.make(`notification-filter:${id}`), @@ -1406,13 +1407,21 @@ it.effect("record reads filter notification sources without dropping matching me updatedAt: now, ...(kind === null ? {} - : { - notification: { - source: { kind }, - outcome: "updated", - summary: "Background notification", - }, - }), + : kind === "wake" + ? { + delegatedCompletion: { + parentRunId: RunId.make("run:wake-parent"), + generation: 1, + taskIds: [], + }, + } + : { + notification: { + source: { kind }, + outcome: "updated", + summary: "Background notification", + }, + }), }, }); } @@ -1424,11 +1433,19 @@ it.effect("record reads filter notification sources without dropping matching me matching.messages.map((message) => [message.id, message.text]), [["monitor", "Complete body for monitor"]], ); + const delegatedTaskMessages = yield* store.getThreadRecords(threadId, ["messages"], { + messageRoles: ["user"], + delegatedTaskMessagesOnly: true, + }); + assert.deepEqual( + delegatedTaskMessages.messages.map((message) => message.id), + ["monitor", "wake"], + ); const { statements, tracer } = traceSqlStatements(); const userMessages = yield* store .getThreadRecords(threadId, ["messages"], { messageRoles: ["user"] }) .pipe(Effect.withTracer(tracer)); - assert.lengthOf(userMessages.messages, 3); + assert.lengthOf(userMessages.messages, 4); const ordinalLookup = statements.find((statement) => statement.includes("MIN(ordinal)")); // User-only reads must seek the message-ordinal index instead of scanning every turn item. yield* assertReadsThroughMessageOrdinalIndex(ordinalLookup, ["thread_id=?", "=?"]); @@ -1442,7 +1459,7 @@ it.effect("record reads filter notification sources without dropping matching me .pipe(Effect.withTracer(withItems.tracer)); assert.deepEqual(ordered.messages, userMessages.messages); assert.isFalse(withItems.statements.some((statement) => statement.includes("MIN(ordinal)"))); - assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 4); + assert.lengthOf((yield* store.getThreadRecords(threadId, ["messages"])).messages, 5); assert.lengthOf( (yield* store.getThreadRecords(threadId, ["messages"], { monitorNotificationsOnly: true, @@ -1453,7 +1470,7 @@ it.effect("record reads filter notification sources without dropping matching me (yield* store.getThreadRecords(threadId, ["messages"], { monitorNotificationsOnly: false, })).messages, - 4, + 5, ); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 33e1355ec15c..e0e0ed48cac9 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -375,6 +375,8 @@ export interface ProjectionRecordFilter { readonly attemptIds?: ReadonlyArray; readonly messageRoles?: ReadonlyArray; readonly monitorNotificationsOnly?: boolean; + /** Monitor notifications and delegated-completion wakes: what `delegatedTaskRuns` and `delegatedTaskProgress` read. */ + readonly delegatedTaskMessagesOnly?: true; readonly turnItemRunId?: RunId; readonly messageIds?: ReadonlyArray; readonly messageRunIds?: ReadonlyArray; @@ -4437,6 +4439,7 @@ export const layer: Layer.Layer = ${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`} ${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`} ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``} + ${filter?.delegatedTaskMessagesOnly === true ? sql`AND (json_extract(payload_json, '$.notification.source.kind') = 'monitor' OR json_extract(payload_json, '$.delegatedCompletion') IS NOT NULL)` : sql``} ${filter?.messageRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageRunIds)}))`} ORDER BY created_at ASC, message_id ASC ` From 895766bafe1a27cbe83b3ba963c7b03d55ac3923 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 19:23:38 +0000 Subject: [PATCH 2/3] perf(server): finalizing a delegated task reads only the child's recent and open runs finalizeAppOwnedSubagent still read every run of the child under the parent's lock. It now reads, in one snapshot, the runs that ended last, every unfinished run, the runs of the tasks it may settle and their wakes, through indexes. When a decision reaches past that window (the latest result ended earlier, or a report walk runs off its end) it reads the whole child as before. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 116 +++++++++++++----- .../orchestration-v2/ProjectionStore.test.ts | 49 ++++++++ .../src/orchestration-v2/ProjectionStore.ts | 97 ++++++++++++++- .../ProviderTurnControlService.test.ts | 1 + .../orchestration-v2/delegatedTaskMessage.ts | 9 ++ apps/server/src/persistence/Migrations.ts | 2 + .../101_DelegatedTaskReadIndexes.ts | 22 ++++ .../reconcileV2PreviewMigration.test.ts | 2 + .../src/server/subagentProjection.ts | 2 +- 9 files changed, 269 insertions(+), 31 deletions(-) create mode 100644 apps/server/src/orchestration-v2/delegatedTaskMessage.ts create mode 100644 apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 03ea1dfcb957..0f203f9a8934 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -201,6 +201,7 @@ import { subagentResultForRun, delegatedTaskProgress, delegatedTaskReportRuns, + monitorUpdateRunIds, subagentThreadTitle, } from "@t3tools/provider-core/server/subagentProjection"; import { @@ -1284,6 +1285,41 @@ function runForSourcePoint( } } +const DELEGATED_CHILD_RUN_WINDOW = 20; + +type DelegatedChildControls = ProjectionRecords< + "runs" | "messages" | "subagents" | "providerThreads" +> & { + /** Set when `runs` holds only what ran since this run, plus older unfinished and task runs. */ + readonly runsFloor?: OrchestrationV2Run | undefined; +}; + +function ranSince(run: OrchestrationV2Run, floor: OrchestrationV2Run): boolean { + return run.id === floor.id || runRanAfter(run, floor); +} + +/** The walk back to a report is exact when it stops at a run that ran since the floor. */ +function reportRunsRead( + controls: DelegatedChildControls, + run: OrchestrationV2Run, + reportRuns: ReadonlyArray, +): boolean { + const floor = controls.runsFloor; + if (floor === undefined || run.status !== "completed") return true; + const oldest = reportRuns.at(-1) ?? run; + if (!ranSince(oldest, floor)) return false; + const monitorRuns = monitorUpdateRunIds(controls.messages); + return controls.runs.some( + (candidate) => + candidate.id !== run.id && + candidate.startedAt !== null && + candidate.status !== "rolled_back" && + !monitorRuns.has(candidate.id) && + runRanAfter(oldest, candidate) && + ranSince(candidate, floor), + ); +} + function providerThreadForRun( projection: Pick, run: OrchestrationV2Run, @@ -14643,13 +14679,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + const readAllDelegatedChildControls = (childThreadId: ThreadId) => + projectionStore.getThreadRecords( + childThreadId, + ["runs", "messages", "subagents", "providerThreads"], + { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, + ); + /** * Callers must hold the parent thread's dispatch lock: wake-policy updates the same * subagent row with full-row payloads, so unserialized writers clobber policy or terminal status. */ const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")( function* ( - childControls: ProjectionRecords<"runs" | "messages" | "subagents" | "providerThreads">, + childControls: DelegatedChildControls, options: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId; @@ -14754,7 +14797,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } // A run queued behind the report can end the task without saying anything. - const reportRuns = delegatedTaskReportRuns(childControls, { ...childRun, status: outcome }); + const reportFrom = { ...childRun, status: outcome }; + let reportRuns = delegatedTaskReportRuns(childControls, reportFrom); + if (!reportRunsRead(childControls, reportFrom, reportRuns)) { + reportRuns = delegatedTaskReportRuns( + yield* readAllDelegatedChildControls(childThreadId), + reportFrom, + ); + } const resultRunIds = [childRun.id, ...reportRuns.map((run) => run.id)]; const childResult = yield* projectionStore.getThreadRecords( childThreadId, @@ -14971,41 +15021,50 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio childThreadId: ThreadId, options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId }, ) { - const childControls = yield* projectionStore.getThreadRecords( - childThreadId, - ["runs", "messages", "subagents", "providerThreads"], - { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, - ); - const parentThreadId = childControls.thread.lineage.parentThreadId; + const child = yield* projectionStore.getThreadRecords(childThreadId, ["contextTransfers"]); + const parentThreadId = child.thread.lineage.parentThreadId; + const forkedFrom = child.thread.forkedFrom; if ( - childControls.thread.lineage.relationshipToParent !== "subagent" || + child.thread.lineage.relationshipToParent !== "subagent" || parentThreadId === null || - childControls.thread.forkedFrom?.type !== "node" + forkedFrom?.type !== "node" ) return; - const progress = delegatedTaskProgress(childControls); // Each task of this child names it, so the parent's other tasks stay unread. const parent = yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], { subagentChildThreadIds: [childThreadId], }); - const { contextTransfers } = yield* projectionStore.getThreadRecords(childThreadId, [ - "contextTransfers", - ]); - for (const task of parent.subagents) { + const resultSent = child.contextTransfers.some( + (transfer) => + transfer.type === "subagent_result" && + transfer.sourceThreadId === childThreadId && + transfer.targetThreadId === parentThreadId, + ); + const openTasks = parent.subagents.filter( + (task) => + task.origin === "app_owned" && + task.childThreadId === childThreadId && + !(task.result !== null && resultSent), + ); + let childControls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls( + childThreadId, + { taskIds: openTasks.map((task) => task.id), windowSize: DELEGATED_CHILD_RUN_WINDOW }, + ); + let progress = delegatedTaskProgress(childControls); + // The latest result may have ended before the runs read above; then read them all. + if ( + childControls.runsFloor !== undefined && + (progress.resultRun === undefined || !ranSince(progress.resultRun, childControls.runsFloor)) + ) { + childControls = yield* readAllDelegatedChildControls(childThreadId); + progress = delegatedTaskProgress(childControls); + } + for (const task of openTasks) { // A cancelled task does not wait for the work its cancel is stopping. const cancelled = task.cancelledRunId !== undefined; if ( - task.origin !== "app_owned" || - task.childThreadId !== childThreadId || - (task.id === childControls.thread.forkedFrom.nodeId && - (cancelled ? progress.state === "working" : progress.state !== "result_available")) || - (task.result !== null && - contextTransfers.some( - (transfer) => - transfer.type === "subagent_result" && - transfer.sourceThreadId === childThreadId && - transfer.targetThreadId === parentThreadId, - )) + task.id === forkedFrom.nodeId && + (cancelled ? progress.state === "working" : progress.state !== "result_available") ) continue; yield* finalizeAppOwnedSubagentTask(childControls, { @@ -15018,7 +15077,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // Only the run a cancelled task settled from ends with it. The row read above has no // such run yet when this call settled the task, from the same result run. const { resultRun } = progress; - const resultTaskId = resultRun?.delegatedTaskId ?? childControls.thread.forkedFrom.nodeId; + const resultTaskId = resultRun?.delegatedTaskId ?? forkedFrom.nodeId; const resultTask = parent.subagents.find((task) => task.id === resultTaskId); const taskCancelled = resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id; @@ -15057,7 +15116,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio run = previousRunId === undefined ? undefined - : childControls.runs.find((candidate) => candidate.id === previousRunId); + : (childControls.runs.find((candidate) => candidate.id === previousRunId) ?? + (yield* projectionStore.getRun(childThreadId, previousRunId))); } for (const request of pendingQuestions) { if ( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 13eeb4a075dd..dabe53aeae46 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1475,6 +1475,55 @@ it.effect("record reads filter notification sources without dropping matching me }).pipe(Effect.provide(layerTest)), ); +it.effect("reads a delegated child's recent, unfinished and task runs without its history", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* addRolledBackRecoveryCandidate("delegated-child-runs"); + const first = (yield* store.getThreadRecords(threadId, ["runs"])).runs[0]!; + const at = (minutes: number) => DateTime.add(first.requestedAt, { minutes: minutes + 60 }); + const id = (ordinal: number) => RunId.make(`run:delegated-child-runs:${ordinal}`); + const unstartedCancel = { status: "cancelled", startedAt: null } as const; + for (const [ordinal, patch] of [ + [3, { status: "running", completedAt: null }], + // Unstarted cancelled runs are outside the window's index: one ends after the floor. + [4, { ...unstartedCancel, completedAt: at(20) }], + [5, { ...unstartedCancel, completedAt: at(1) }], + ...[2, 6, 7, 8, 9, 10, 11, 12].map((ordinal) => [ordinal, {}] as const), + ] as const) { + yield* store.apply({ + id: EventId.make(`event:delegated-child-runs:${ordinal}`), + type: "run.created", + threadId, + runId: id(ordinal), + occurredAt: first.requestedAt, + payload: { + ...first, + id: id(ordinal), + ordinal, + status: "completed", + startedAt: at(ordinal), + completedAt: at(ordinal), + delegatedTaskId: NodeId.make(`node:delegated-child-runs:task:${ordinal}`), + ...patch, + }, + }); + } + const taskIds = [NodeId.make("node:delegated-child-runs:task:2")]; + const bounded = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 3 }); + assert.equal(bounded.runsFloor?.id, id(11)); + assert.deepEqual( + bounded.runs.map((run) => run.id), + [2, 3, 4, 11, 12].map(id), + ); + const whole = yield* store.getDelegatedChildControls(threadId, { taskIds, windowSize: 100 }); + assert.isUndefined(whole.runsFloor); + assert.deepEqual( + whole.runs.map((run) => run.id), + (yield* store.getThreadRecords(threadId, ["runs"])).runs.map((run) => run.id), + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("shells flag a latest run triggered by a provider background wake", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e0e0ed48cac9..53199015079e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -103,6 +103,7 @@ import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; +import { DELEGATED_TASK_MESSAGE_CONDITION } from "./delegatedTaskMessage.ts"; import { DEFERRED_COMMAND_MESSAGE_CONDITION, JAVASCRIPT_TRIM_WHITESPACE, @@ -375,7 +376,7 @@ export interface ProjectionRecordFilter { readonly attemptIds?: ReadonlyArray; readonly messageRoles?: ReadonlyArray; readonly monitorNotificationsOnly?: boolean; - /** Monitor notifications and delegated-completion wakes: what `delegatedTaskRuns` and `delegatedTaskProgress` read. */ + /** User messages that are monitor notifications or delegated-completion wakes, through their partial index. */ readonly delegatedTaskMessagesOnly?: true; readonly turnItemRunId?: RunId; readonly messageIds?: ReadonlyArray; @@ -818,6 +819,20 @@ export interface ProjectionStoreV2Shape { threadId: ThreadId, runId: RunId, ) => Effect.Effect; + /** + * One snapshot: the `windowSize` runs that ended last, unfinished runs, the runs of `taskIds` and + * their wakes. `runsFloor` is set when older runs were left out; every run that ran after it is + * in `runs`. + */ + readonly getDelegatedChildControls: ( + threadId: ThreadId, + input: { readonly taskIds: ReadonlyArray; readonly windowSize: number }, + ) => Effect.Effect< + ProjectionRecords<"runs" | "messages" | "subagents" | "providerThreads"> & { + readonly runsFloor: OrchestrationV2Run | undefined; + }, + ProjectionStoreV2Error + >; readonly canStartQueuedRun: ( threadId: ThreadId, ) => Effect.Effect; @@ -4439,7 +4454,7 @@ export const layer: Layer.Layer = ${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`} ${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`} ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``} - ${filter?.delegatedTaskMessagesOnly === true ? sql`AND (json_extract(payload_json, '$.notification.source.kind') = 'monitor' OR json_extract(payload_json, '$.delegatedCompletion') IS NOT NULL)` : sql``} + ${filter?.delegatedTaskMessagesOnly === true ? sql`AND ${sql.literal(DELEGATED_TASK_MESSAGE_CONDITION)}` : sql``} ${filter?.messageRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageRunIds)}))`} ORDER BY created_at ASC, message_id ASC ` @@ -6455,6 +6470,83 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + const getDelegatedChildControls: ProjectionStoreV2Shape["getDelegatedChildControls"] = ( + threadId, + { taskIds, windowSize }, + ) => + sql + .withTransaction( + Effect.gen(function* () { + const records = yield* getThreadRecords( + threadId, + ["messages", "subagents", "providerThreads"], + { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, + ); + // Spells migration 84's order and predicate so the window walks that index. + const windowRows = yield* sql` + SELECT payload_json, completed_at FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + AND status <> 'queued' + AND NOT (status = 'cancelled' AND json_extract(payload_json, '$.startedAt') IS NULL) + ORDER BY (completed_at IS NULL) DESC, completed_at DESC, ordinal DESC, run_id DESC + LIMIT ${windowSize} + `; + const window = yield* decodeRows(decodeRunPayload, threadId)(windowRows); + const last = window.length < windowSize ? undefined : window.at(-1); + const floorCompletedAt = windowRows.at(-1)?.completed_at ?? null; + // A window ending in unfinished runs bounds nothing, so read the whole thread. + const floor = floorCompletedAt === null ? undefined : last; + const rest = yield* ( + last !== undefined && floor === undefined + ? sql` + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId}` + : sql` + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} + AND status IN ('preparing', 'queued', 'starting', 'running', 'waiting') + UNION + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND json_valid(payload_json) + AND json_extract(payload_json, '$.delegatedTaskId') IS NOT NULL + AND json_extract(payload_json, '$.delegatedTaskId') + IN (SELECT value FROM json_each(${encodeIdList(taskIds)})) + UNION + -- Unstarted cancelled runs are outside the window's index. + SELECT payload_json FROM orchestration_v2_projection_runs + WHERE thread_id = ${threadId} AND status = 'cancelled' + ${floor === undefined ? sql`` : sql`AND (completed_at IS NULL OR completed_at >= ${floorCompletedAt})`}` + ).pipe(Effect.flatMap(decodeRows(decodeRunPayload, threadId))); + const runs = new Map([...window, ...rest].map((run) => [run.id, run])); + const requested = new Set(); + for (;;) { + const wakeRunIds = [ + ...new Set( + records.messages.flatMap((message) => + message.runId !== null && + message.delegatedCompletion !== undefined && + runs.has(message.delegatedCompletion.parentRunId) && + !runs.has(message.runId) && + !requested.has(message.runId) + ? [message.runId] + : [], + ), + ), + ]; + if (wakeRunIds.length === 0) break; + for (const id of wakeRunIds) requested.add(id); + const wakes = yield* getThreadRecords(threadId, ["runs"], { runIds: wakeRunIds }); + for (const run of wakes.runs) runs.set(run.id, run); + } + return { + ...records, + runs: [...runs.values()].toSorted((a, b) => a.ordinal - b.ordinal), + runsFloor: floor, + }; + }), + ) + .pipe(Effect.mapError(controlReadError(threadId))); + const getRun: ProjectionStoreV2Shape["getRun"] = (threadId, runId) => sql .withTransaction( @@ -9649,6 +9741,7 @@ export const layer: Layer.Layer = getCheckpointCaptureContext: readOnReader(getCheckpointCaptureContext), getCheckpointRollbackContext: readOnReader(getCheckpointRollbackContext), getRunMessage: readOnReader(getRunMessage), + getDelegatedChildControls: readOnReader(getDelegatedChildControls), getRun: readOnReader(getRun), canStartQueuedRun: readOnReader(canStartQueuedRun), getHeldQueuedRuns: readOnReader(getHeldQueuedRuns), diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index cb9550efe579..1bd06d278722 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -187,6 +187,7 @@ function layerProjectionStore( getCheckpointRollbackContext: () => Effect.die("unused rollback context"), getCheckpointCaptureContext: () => Effect.die("not used"), getRunMessage: () => Effect.die("not used"), + getDelegatedChildControls: () => Effect.die("not used"), getRun: () => Effect.die("not used"), isNodeStored: () => Effect.die("not used"), canStartQueuedRun: () => Effect.die("not used"), diff --git a/apps/server/src/orchestration-v2/delegatedTaskMessage.ts b/apps/server/src/orchestration-v2/delegatedTaskMessage.ts new file mode 100644 index 000000000000..df98b47dc379 --- /dev/null +++ b/apps/server/src/orchestration-v2/delegatedTaskMessage.ts @@ -0,0 +1,9 @@ +/** + * A user message that marks its run as a monitor update or a delegated-completion wake: what + * `delegatedTaskProgress` and `delegatedTaskRuns` read. The partial index on it is only used when + * the read spells this text the same way. + */ +export const DELEGATED_TASK_MESSAGE_CONDITION = `role = 'user' AND json_valid(payload_json) AND ( + json_extract(payload_json, '$.notification.source.kind') = 'monitor' + OR json_extract(payload_json, '$.delegatedCompletion') IS NOT NULL +)`; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index dcf435b670ca..c3fc7aacef05 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -108,6 +108,7 @@ import Migration0097 from "./Migrations/097_IssueTrackerBindings.ts"; import Migration0098 from "./Migrations/098_ActiveShellIndexIndexes.ts"; import Migration0099 from "./Migrations/099_BackgroundRecoveryIndexes.ts"; import Migration0100 from "./Migrations/100_TurnStartReadIndexes.ts"; +import Migration0101 from "./Migrations/101_DelegatedTaskReadIndexes.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -211,6 +212,7 @@ const migrationEntries = [ [98, "ActiveShellIndexIndexes", Migration0098], [99, "BackgroundRecoveryIndexes", Migration0099], [100, "TurnStartReadIndexes", Migration0100], + [101, "DelegatedTaskReadIndexes", Migration0101], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts b/apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts new file mode 100644 index 000000000000..e057296dafab --- /dev/null +++ b/apps/server/src/persistence/Migrations/101_DelegatedTaskReadIndexes.ts @@ -0,0 +1,22 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +import { DELEGATED_TASK_MESSAGE_CONDITION } from "../../orchestration-v2/delegatedTaskMessage.ts"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Finalizing a delegated task finds its tasks' runs and the child's wakes without reading the + // child's history. ProjectionStore.getDelegatedChildControls and the delegatedTaskMessagesOnly read + // must spell the same expressions. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_runs_delegated_task_idx + ON orchestration_v2_projection_runs(thread_id, json_extract(payload_json, '$.delegatedTaskId')) + WHERE json_valid(payload_json) AND json_extract(payload_json, '$.delegatedTaskId') IS NOT NULL + `; + yield* sql.unsafe(` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_messages_delegated_task_idx + ON orchestration_v2_projection_messages(thread_id, created_at, message_id) + WHERE ${DELEGATED_TASK_MESSAGE_CONDITION} + `); +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index 982ea60a2b34..b9feabbf89b8 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -80,6 +80,7 @@ describe("V2 preview upgrade", () => { [98, "ActiveShellIndexIndexes"], [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], + [101, "DelegatedTaskReadIndexes"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -203,6 +204,7 @@ describe("V2 preview upgrade", () => { [98, "ActiveShellIndexIndexes"], [99, "BackgroundRecoveryIndexes"], [100, "TurnStartReadIndexes"], + [101, "DelegatedTaskReadIndexes"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index 88b124bf5fb7..e0ac009f5731 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -206,7 +206,7 @@ function stopNotice( type MonitorNotice = Pick; /** Runs that only acknowledge a monitor update are never a task's work. */ -function monitorUpdateRunIds(messages: ReadonlyArray) { +export function monitorUpdateRunIds(messages: ReadonlyArray) { return new Set( messages .filter( From ef270bdfe811dc1a77c3256951fcd6d49281bbdd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 20:15:04 +0000 Subject: [PATCH 3/3] perf(server): releasing a finished delegate's session reads only its recent runs The provider-session cleanup after each delegated task still read every run and user message of the child under the parent's lock. It now uses the same bounded control read (with the same full-read fallback) as finalization, and reads provider sessions on their own. Co-Authored-By: Claude Opus 5.5 --- .../src/orchestration-v2/Orchestrator.ts | 51 +++++++++++-------- 1 file changed, 31 insertions(+), 20 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0f203f9a8934..c39f1d6d7a67 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14637,23 +14637,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A finished delegate otherwise keeps its provider process until the idle timeout. Callers hold // the parent lock; the child lock orders this after any follow-up that started a run meanwhile. const releaseFinishedDelegateSessions = Effect.fn("Orchestrator.releaseFinishedDelegateSessions")( - function* (childThreadId: ThreadId, resultRunId: RunId) { + function* (childThreadId: ThreadId, resultRunId: RunId, taskId: NodeId) { yield* threadDispatch.withLock( childThreadId, Effect.gen(function* () { - const child = yield* projectionStore.getThreadRecords( - childThreadId, - ["runs", "messages", "subagents", "providerThreads", "providerSessions"], - { messageRoles: ["user"] }, - ); + const { controls: child, progress } = yield* readDelegatedChildControls(childThreadId, [ + taskId, + ]); // Unawaited background tasks still allow a result but die with the process; the idle // timer keeps their process pinned. if ( - delegatedTaskProgress(child).state !== "result_available" || + progress.state !== "result_available" || child.providerThreads.some((thread) => (thread.pendingBackgroundTasks ?? []).length > 0) ) return; - for (const session of child.providerSessions) { + const { providerSessions } = yield* projectionStore.getThreadRecords(childThreadId, [ + "providerSessions", + ]); + for (const session of providerSessions) { // Shared processes unload their threads themselves; only a per-thread process lingers. if ( session.status === "stopped" || @@ -14686,6 +14687,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio { messageRoles: ["user"], delegatedTaskMessagesOnly: true }, ); + const readDelegatedChildControls = Effect.fn("Orchestrator.readDelegatedChildControls")( + function* (childThreadId: ThreadId, taskIds: ReadonlyArray) { + const controls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls( + childThreadId, + { taskIds, windowSize: DELEGATED_CHILD_RUN_WINDOW }, + ); + const progress = delegatedTaskProgress(controls); + // The latest result may have ended before the runs read above; then read them all. + if ( + controls.runsFloor !== undefined && + (progress.resultRun === undefined || !ranSince(progress.resultRun, controls.runsFloor)) + ) { + const all = yield* readAllDelegatedChildControls(childThreadId); + return { controls: all, progress: delegatedTaskProgress(all) }; + } + return { controls, progress }; + }, + ); + /** * Callers must hold the parent thread's dispatch lock: wake-policy updates the same * subagent row with full-row payloads, so unserialized writers clobber policy or terminal status. @@ -15000,7 +15020,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }, ]; yield* writeSystemEvents(completionEvents, [], { updateDelegatedCompletionOnly: true }); - yield* releaseFinishedDelegateSessions(childThreadId, childRun.id); + yield* releaseFinishedDelegateSessions(childThreadId, childRun.id, task.id); if (completionPlan.offer && completionPlan.parentRun !== undefined) { yield* offerDelegatedCompletionDelivery(parentThreadId, completionPlan.parentRun.id); @@ -15046,19 +15066,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio task.childThreadId === childThreadId && !(task.result !== null && resultSent), ); - let childControls: DelegatedChildControls = yield* projectionStore.getDelegatedChildControls( + const { controls: childControls, progress } = yield* readDelegatedChildControls( childThreadId, - { taskIds: openTasks.map((task) => task.id), windowSize: DELEGATED_CHILD_RUN_WINDOW }, + openTasks.map((task) => task.id), ); - let progress = delegatedTaskProgress(childControls); - // The latest result may have ended before the runs read above; then read them all. - if ( - childControls.runsFloor !== undefined && - (progress.resultRun === undefined || !ranSince(progress.resultRun, childControls.runsFloor)) - ) { - childControls = yield* readAllDelegatedChildControls(childThreadId); - progress = delegatedTaskProgress(childControls); - } for (const task of openTasks) { // A cancelled task does not wait for the work its cancel is stopping. const cancelled = task.cancelledRunId !== undefined;