diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 0a3424735a67..059671b306fa 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 { @@ -1286,6 +1287,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, @@ -14621,23 +14657,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" || @@ -14663,15 +14700,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); + const readAllDelegatedChildControls = (childThreadId: ThreadId) => + projectionStore.getThreadRecords( + childThreadId, + ["runs", "messages", "subagents", "providerThreads"], + { 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. */ const finalizeAppOwnedSubagentTask = Effect.fn("Orchestrator.finalizeAppOwnedSubagentTask")( function* ( - childControls: ProjectionRecords< - "runs" | "messages" | "subagents" | "providerThreads" | "providerTurns" | "attempts" - >, + childControls: DelegatedChildControls, options: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId; @@ -14776,23 +14837,45 @@ 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, - ["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. @@ -14957,7 +15040,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); @@ -14978,41 +15061,41 @@ 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", "providerTurns", "attempts"], - { messageRoles: ["user"] }, - ); - 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), + ); + const { controls: childControls, progress } = yield* readDelegatedChildControls( + childThreadId, + openTasks.map((task) => task.id), + ); + 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, { @@ -15025,7 +15108,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; @@ -15064,7 +15147,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 5a1baf63d997..dabe53aeae46 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,56 @@ 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)), +); + +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)), ); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 7824fce056c4..930639b5d6bb 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,6 +376,8 @@ export interface ProjectionRecordFilter { readonly attemptIds?: ReadonlyArray; readonly messageRoles?: ReadonlyArray; readonly monitorNotificationsOnly?: boolean; + /** User messages that are monitor notifications or delegated-completion wakes, through their partial index. */ + readonly delegatedTaskMessagesOnly?: true; readonly turnItemRunId?: RunId; readonly messageIds?: ReadonlyArray; readonly messageRunIds?: ReadonlyArray; @@ -816,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; @@ -4437,6 +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 ${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 ` @@ -6475,6 +6493,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( @@ -9669,6 +9764,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 df80f2ded583..51c38efa8a41 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(