Skip to content
TypeScript

perf(server): busy threads stop decoding settled subagents and idle pollers skip work (#27711)

Julius Marminge9b1d351ba0f6
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index d8dacb35a06..02f63741728 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -513,6 +513,21 @@ function pendingTaskApproval(
return approval;
}
+/** Every task `directAppOwnedChildTasks` can return, so callers load only those. */
+function directChildTaskIds(
+ target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
+ returnedRunIds: ReadonlySet<RunId | null>,
+): ReadonlyArray<NodeId> {
+ const ids = new Set<NodeId>();
+ if (target.thread.forkedFrom?.type === "node") ids.add(target.thread.forkedFrom.nodeId);
+ for (const run of target.runs) {
+ if (returnedRunIds.has(run.id) && run.delegatedTaskId !== undefined) {
+ ids.add(run.delegatedTaskId);
+ }
+ }
+ return [...ids];
+}
+
function directAppOwnedChildTasks(
parent: Pick<OrchestrationV2ThreadProjection, "thread" | "subagents">,
target: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
@@ -1016,7 +1031,6 @@ const make = Effect.gen(function* () {
[
"runs",
"messages",
- "subagents",
"providerThreads",
"providerTurns",
"runtimeRequests",
@@ -1034,6 +1048,15 @@ const make = Effect.gen(function* () {
),
);
+ // A dispatcher thread holds thousands of tasks, each with its full prompt; read only the ones named.
+ const loadTasks = (threadId: ThreadId, taskIds: ReadonlyArray<NodeId>) =>
+ threadManagement.getThreadRecords(threadId, ["subagents"], { subagentIds: taskIds }).pipe(
+ Effect.map(({ subagents }) => subagents),
+ Effect.mapError((error) =>
+ failure("orchestration_error", `Unable to read thread ${threadId}: ${errorMessage(error)}`),
+ ),
+ );
+
// Task waits read on every wake of a parent that may hold thousands of
// tasks, so they read only the task they watch and what its status needs.
const loadTaskParent = (threadId: ThreadId, taskId: NodeId) =>
@@ -2385,7 +2408,7 @@ const make = Effect.gen(function* () {
const childThreadId = current.childThreadId;
if (childThreadId === null) {
// The task runs in a linked environment: its thread there is stopped through the link.
- const { subagents } = yield* loadProjection(scope.thread.threadId);
+ const subagents = yield* loadTasks(scope.thread.threadId, [input.taskId]);
const remoteTask = subagents.find(
(task) =>
task.id === input.taskId &&
@@ -2428,7 +2451,7 @@ const make = Effect.gen(function* () {
}
});
yield* assertStoppable(childThreadId);
- const parentTask = parentProjection.subagents.find(
+ const parentTask = (yield* loadTasks(scope.thread.threadId, [input.taskId])).find(
(task) => task.id === input.taskId && task.origin === "app_owned",
);
const disposeCompletionDelivery =
@@ -2548,9 +2571,11 @@ const make = Effect.gen(function* () {
runId: parentTask.runId,
subagentId: parentTask.id,
});
- const { subagents } = yield* threadManagement.getThreadRecords(scope.thread.threadId, [
- "subagents",
- ]);
+ const { subagents } = yield* threadManagement.getThreadRecords(
+ scope.thread.threadId,
+ ["subagents"],
+ { subagentIds: [input.taskId] },
+ );
return subagents.some((task) => task.id === input.taskId && task.status === "cancelled");
}).pipe(Effect.mapError(threadManagementFailure));
if (isTerminalTaskStatus(current.status)) {
@@ -2847,7 +2872,19 @@ const make = Effect.gen(function* () {
page.filter((row) => row.sourceThreadId === target.thread.id).map((row) => row.item.runId),
);
const tasks =
- parent === undefined ? [] : directAppOwnedChildTasks(parent, target, returnedRunIds);
+ parent === undefined
+ ? []
+ : directAppOwnedChildTasks(
+ {
+ thread: parent.thread,
+ subagents: yield* loadTasks(
+ parent.thread.id,
+ directChildTaskIds(target, returnedRunIds),
+ ),
+ },
+ target,
+ returnedRunIds,
+ );
if (
parent !== undefined &&
scope.thread !== undefined &&
@@ -2978,14 +3015,16 @@ const make = Effect.gen(function* () {
const ownedTask =
result.timedOut &&
status !== "waiting" &&
- parent?.subagents.some(
+ parent !== undefined &&
+ taskId !== undefined &&
+ (yield* loadTasks(parent.thread.id, [taskId])).some(
(task) =>
task.id === taskId &&
task.origin === "app_owned" &&
task.threadId === parent.thread.id &&
task.childThreadId === input.threadId &&
task.completionDelivery?.state !== "disposed",
- ) === true;
+ );
// A child waiting on a question or approval needs an answer, not a wake.
const childRequests = ownedTask
? (yield* threadManagement
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
index 428e44e1902..f42f37d1ab1 100644
--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
@@ -4944,7 +4944,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
});
// Claude has no recovered frame; the next assistant message proves recovery.
- const completeProviderRetry = Effect.fn("ClaudeAdapterV2.completeProviderRetry")(function* (
+ // Runs on every model output frame and is almost always a no-op; only a pending retry gets a span.
+ const completeProviderRetry = Effect.fnUntraced(function* (
context: ActiveClaudeTurnContext,
updatedAt: DateTime.Utc,
) {
@@ -4977,7 +4978,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
startedAt: providerRetry.startedAt,
updatedAt,
}),
- });
+ }).pipe(Effect.withSpan("ClaudeAdapterV2.completeProviderRetry"));
});
const rememberProviderThread =
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
index 59c26bd40b9..4f960b6593c 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -1945,7 +1945,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
});
// Only new model output proves recovery; local item/completed can arrive during upstream retries.
- const completeProviderRetry = Effect.fn("CodexAdapterV2.completeProviderRetry")(function* (
+ // Runs on every model output frame and is almost always a no-op; only a pending retry gets a span.
+ const completeProviderRetry = Effect.fnUntraced(function* (
context: ActiveCodexTurnContext,
updatedAt: DateTime.Utc,
) {
@@ -1965,7 +1966,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem: codexRetryTurnItem(context, providerRetry, "completed", updatedAt),
- });
+ }).pipe(Effect.withSpan("CodexAdapterV2.completeProviderRetry"));
});
const registerRootTurn = Effect.fn("CodexAdapterV2.registerRootTurn")(function* (input: {
diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
index ad2bc395d08..5053e8d5687 100644
--- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
@@ -159,6 +159,11 @@ const seedParentWithTerminalTask = (input: {
readonly deliveryState: "delivered" | "claimed" | "acknowledged" | "disposed";
readonly completionWake?: "always" | "settled_only";
readonly deliveryTaskIds?: ReadonlyArray<NodeId>;
+ readonly parentRunStatus?: "running" | "completed";
+ readonly siblingTasks?: ReadonlyArray<{
+ readonly id: NodeId;
+ readonly deliveryState: "delivered" | "claimed";
+ }>;
readonly now: DateTime.Utc;
}) =>
Effect.gen(function* () {
@@ -241,10 +246,10 @@ const seedParentWithTerminalTask = (input: {
userMessageId: MessageId.make(`message:seed-user:${input.threadId}`),
rootNodeId: input.rootNodeId,
activeAttemptId: null,
- status: "running",
+ status: input.parentRunStatus ?? "running",
requestedAt: input.now,
startedAt: input.now,
- completedAt: null,
+ completedAt: input.parentRunStatus === "completed" ? input.now : null,
checkpointId: null,
contextHandoffId: null,
delegatedCompletion: {
@@ -261,22 +266,25 @@ const seedParentWithTerminalTask = (input: {
},
},
},
- {
- id: EventId.make(`event:seed-task:${input.threadId}`),
- type: "subagent.updated",
+ ...[
+ { id: input.taskId, deliveryState: input.deliveryState },
+ ...(input.siblingTasks ?? []),
+ ].map((task) => ({
+ id: EventId.make(`event:seed-task:${input.threadId}:${task.id}`),
+ type: "subagent.updated" as const,
threadId: input.threadId,
runId: input.runId,
- nodeId: input.taskId,
+ nodeId: task.id,
driver,
providerInstanceId: modelSelection.instanceId,
occurredAt: input.now,
payload: {
- id: input.taskId,
+ id: task.id,
threadId: input.threadId,
runId: input.runId,
parentNodeId: input.rootNodeId,
- origin: "app_owned",
- createdBy: "agent",
+ origin: "app_owned" as const,
+ createdBy: "agent" as const,
driver,
providerInstanceId: modelSelection.instanceId,
providerThreadId: null,
@@ -287,16 +295,16 @@ const seedParentWithTerminalTask = (input: {
model: null,
completionWake: input.completionWake ?? "settled_only",
completionDelivery: {
- state: input.deliveryState,
- observedByRunId: input.deliveryState === "acknowledged" ? input.runId : null,
+ state: task.deliveryState,
+ observedByRunId: task.deliveryState === "acknowledged" ? input.runId : null,
},
- status: "completed",
+ status: "completed" as const,
result: "child finished",
startedAt: input.now,
completedAt: input.now,
updatedAt: input.now,
},
- },
+ })),
],
});
});
@@ -683,6 +691,57 @@ it.layer(layerTest)("delegated completion delivery repairs", (it) => {
}),
);
+ it.effect("counts already delivered siblings in the completion notice", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const now = yield* DateTime.now;
+ const threadId = ThreadId.make("thread:delegated-delivery-notice-count");
+ const runId = RunId.make("run:delegated-delivery-notice-count");
+ const firstTaskId = NodeId.make("node:delegated-delivery-notice-count-first");
+ const secondTaskId = NodeId.make("node:delegated-delivery-notice-count-second");
+
+ yield* seedParentWithTerminalTask({
+ threadId,
+ projectId: ProjectId.make("project:delegated-delivery-notice-count"),
+ runId,
+ rootNodeId: NodeId.make("node:delegated-delivery-notice-count-root"),
+ taskId: firstTaskId,
+ deliveryState: "claimed",
+ completionWake: "always",
+ deliveryTaskIds: [firstTaskId, secondTaskId],
+ parentRunStatus: "completed",
+ siblingTasks: [
+ { id: secondTaskId, deliveryState: "claimed" },
+ {
+ id: NodeId.make("node:delegated-delivery-notice-count-earlier"),
+ deliveryState: "delivered",
+ },
+ ],
+ now,
+ });
+
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("command:delegated-delivery-notice-count"),
+ threadId,
+ messageId: MessageId.make(`message:delegated-delivery:${threadId}`),
+ text: "Delegated tasks reached a terminal state.",
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "agent",
+ creationSource: "server",
+ delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [firstTaskId] },
+ });
+
+ const projection = yield* orchestrator.getThreadProjection(threadId);
+ const notice = projection.turnItems.find((item) => item.type === "notification");
+ assert.match(
+ notice?.type === "notification" ? notice.summary : "",
+ /^2 of 3 delegated tasks finished:/,
+ );
+ }),
+ );
+
it.effect.each([
{
name: "oversized UTF-8 result",
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 50f9a2acc0f..ce43fef58a4 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -1153,6 +1153,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
turnItemTypes: ["user_message", "error"],
messageRoles: ["user"],
omitSettledLeafNodes: true,
+ // Commands here read only undelivered or active tasks; a dispatcher thread keeps
+ // thousands of delivered ones, each carrying its full prompt.
+ omitSettledSubagents: true,
},
)
.pipe(
@@ -1167,6 +1170,23 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
);
+ // Command reads omit settled tasks, but a completion notice counts its whole cohort.
+ const notificationTasks = (
+ threadId: ThreadId,
+ message: Pick<OrchestrationV2ConversationMessage, "delegatedCompletion">,
+ loaded: ReadonlyArray<OrchestrationV2Subagent>,
+ ) =>
+ message.delegatedCompletion === undefined
+ ? Effect.succeed(loaded)
+ : projectionStore
+ .getThreadRecords(threadId, ["subagents"], {
+ subagentRunIds: [message.delegatedCompletion.parentRunId],
+ })
+ .pipe(
+ Effect.map((records) => records.subagents),
+ Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })),
+ );
+
const readHandoffItems = (threadId: ThreadId, runIds?: ReadonlyArray<RunId | null>) =>
projectionStore
.getThreadRecords(
@@ -2174,7 +2194,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nodeId: rootNodeId,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
- payload: notificationTurnItem(userTurnItem, queuedMessage, projection.subagents),
+ payload: notificationTurnItem(
+ userTurnItem,
+ queuedMessage,
+ yield* notificationTasks(threadId, queuedMessage, projection.subagents),
+ ),
},
{
type: "run.updated",
@@ -4677,7 +4701,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nodeId: messageInput.nodeId,
providerInstanceId: messageInput.providerInstanceId,
occurredAt: now,
- payload: notificationTurnItem(turnItem, message, input.projection.subagents),
+ payload: notificationTurnItem(
+ turnItem,
+ message,
+ yield* notificationTasks(input.command.threadId, message, input.projection.subagents),
+ ),
});
},
);
@@ -6328,7 +6356,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: notificationTurnItem(turnItem, message, projection.subagents),
+ payload: notificationTurnItem(
+ turnItem,
+ message,
+ yield* notificationTasks(command.threadId, message, projection.subagents),
+ ),
});
if (preparationTurnItem !== null) {
yield* emitEvent({
@@ -7222,7 +7254,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
- payload: notificationTurnItem(turnItem, message, projection.subagents),
+ payload: notificationTurnItem(
+ turnItem,
+ message,
+ yield* notificationTasks(command.threadId, message, projection.subagents),
+ ),
});
const forkResolution = nativeForkResolution ?? portableForkResolution;
if (pendingForkTransfer !== undefined && forkResolution !== null) {
@@ -7289,14 +7325,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
) {
const parentProjection = yield* projectionStore
- .getThreadRecords(command.parentThreadId, [
- "runs",
- "nodes",
- "subagents",
- "providerThreads",
- "providerTurns",
- "attempts",
- ])
+ .getThreadRecords(
+ command.parentThreadId,
+ ["runs", "nodes", "providerThreads", "providerTurns", "attempts"],
+ // The parent node must belong to the active run, whose nodes this keeps.
+ { omitSettledLeafNodes: true },
+ )
.pipe(
Effect.mapError(
(cause) =>
@@ -7366,7 +7400,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
parentTitle: parentProjection.thread.title,
prompt: command.task,
...(command.title === undefined ? {} : { title: command.title }),
- ordinal: parentProjection.subagents.length + 1,
+ ordinal: (yield* subagentCount(command.parentThreadId)) + 1,
});
const childThread: OrchestrationV2AppThread = {
...makeSubagentChildThread({
@@ -7601,7 +7635,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
);
if (run === undefined || run.delegatedTaskId !== undefined) return;
const parent = yield* projectionStore
- .getThreadRecords(parentThreadId, ["runs", "subagents", "providerTurns", "attempts"])
+ .getThreadRecords(parentThreadId, ["runs", "subagents", "providerTurns", "attempts"], {
+ subagentIds: child.forkedFrom?.type === "node" ? [child.forkedFrom.nodeId] : [],
+ })
.pipe(mapDispatchError(command));
const original = parent.subagents.find(
(task) =>
@@ -7729,13 +7765,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) {
const parentProjection = yield* projectionStore
- .getThreadRecords(command.parentThreadId, [
- "runs",
- "nodes",
- "subagents",
- "providerTurns",
- "attempts",
- ])
+ .getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts"])
.pipe(
Effect.mapError(
(cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }),
@@ -7767,7 +7797,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
parentTitle: parentProjection.thread.title,
prompt: command.task,
...(command.title === undefined ? {} : { title: command.title }),
- ordinal: parentProjection.subagents.length + 1,
+ ordinal: (yield* subagentCount(command.parentThreadId)) + 1,
});
const common = {
threadId: command.parentThreadId,
@@ -7872,11 +7902,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) {
+ // Delivery planning reads only this task and the undelivered tasks of the queued delivery;
+ // the task's own node and turn item are all it updates besides.
const parentProjection = yield* projectionStore
.getThreadRecords(
command.parentThreadId,
["runs", "messages", "subagents", "providerTurns", "nodes", "turnItems"],
- { turnItemTypes: ["subagent"], messageRoles: ["user"] },
+ {
+ turnItemTypes: ["subagent"],
+ messageRoles: ["user"],
+ omitSettledSubagents: { except: [command.taskId] },
+ nodeIds: [command.taskId],
+ turnItemNodeIds: [command.taskId],
+ },
)
.pipe(
Effect.mapError(
@@ -8102,8 +8140,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
command: Extract<OrchestrationV2Command, { readonly type: "delegated_task.wake-policy" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) {
+ // Delivery planning reads only this task and the undelivered tasks of the queued delivery.
const parentProjection = yield* projectionStore
- .getThreadRecords(command.parentThreadId, ["subagents", "runs", "messages", "providerTurns"])
+ .getThreadRecords(
+ command.parentThreadId,
+ ["subagents", "runs", "messages", "providerTurns"],
+ {
+ omitSettledSubagents: { except: [command.taskId] },
+ },
+ )
.pipe(
Effect.mapError(
(cause) =>
@@ -9546,6 +9591,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}
});
+ const subagentCount = (threadId: ThreadId) =>
+ projectionStore
+ .getSubagentCount(threadId)
+ .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
+
const loadProjectionForCommand = <K extends ProjectionRecordField>(
command: OrchestrationV2Command,
fields: ReadonlyArray<K>,
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
index 1dc7c912e77..cfe57ab2c0c 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts
@@ -850,6 +850,121 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () {
nodeNames(yield* store.getThreadRecords(threadId, ["nodes"])),
nodes.map(([name]) => name).toSorted(),
);
+
+ const subagents = [
+ ["delivered", settledRun, "completed", "delivered"],
+ ["acknowledged", settledRun, "failed", "acknowledged"],
+ ["disposed", settledRun, "cancelled", "disposed"],
+ ["pending-delivery", settledRun, "completed", "pending"],
+ ["claimed", settledRun, "completed", "claimed"],
+ ["no-delivery", settledRun, "interrupted", null],
+ ["running", settledRun, "running", null],
+ ["active-run-delivered", activeRun, "completed", "delivered"],
+ ] as const;
+ for (const [index, [name, run, status, delivery]] of subagents.entries()) {
+ const id = NodeId.make(`node:settled-subagents:${name}`);
+ yield* store.apply({
+ id: EventId.make(`event:settled-subagents:item:${name}`),
+ type: "turn-item.updated",
+ threadId,
+ runId: run.id,
+ nodeId: id,
+ driver,
+ occurredAt: now,
+ payload: {
+ id: TurnItemId.make(`item:settled-subagents:${name}`),
+ type: "subagent",
+ threadId,
+ runId: run.id,
+ nodeId: id,
+ providerThreadId: null,
+ providerTurnId: null,
+ nativeItemRef: null,
+ parentItemId: null,
+ ordinal: 100 + index,
+ status: status === "running" ? "running" : "completed",
+ title: name,
+ startedAt: now,
+ completedAt: status === "running" ? null : now,
+ updatedAt: now,
+ subagentId: id,
+ origin: "app_owned",
+ driver,
+ providerInstanceId,
+ childThreadId: null,
+ prompt: "Do the work",
+ result: null,
+ },
+ });
+ yield* store.apply({
+ id: EventId.make(`event:settled-subagents:${name}`),
+ type: "subagent.updated",
+ threadId,
+ runId: run.id,
+ nodeId: id,
+ driver,
+ providerInstanceId,
+ occurredAt: now,
+ payload: {
+ id,
+ threadId,
+ runId: run.id,
+ parentNodeId: run.rootNodeId!,
+ origin: "app_owned",
+ createdBy: "agent",
+ driver,
+ providerInstanceId,
+ providerThreadId: null,
+ childThreadId: null,
+ nativeTaskRef: null,
+ prompt: "Do the work",
+ title: name,
+ model: null,
+ ...(delivery === null
+ ? {}
+ : { completionDelivery: { state: delivery, observedByRunId: null } }),
+ status,
+ result: null,
+ startedAt: now,
+ completedAt: status === "running" ? null : now,
+ updatedAt: now,
+ },
+ });
+ }
+ const subagentNames = (records: {
+ readonly subagents: ReadonlyArray<{ readonly title: string | null }>;
+ }) => records.subagents.map((subagent) => subagent.title ?? "").toSorted();
+ assert.deepEqual(
+ subagentNames(
+ yield* store.getThreadRecords(threadId, ["subagents"], { omitSettledSubagents: true }),
+ ),
+ ["active-run-delivered", "claimed", "no-delivery", "pending-delivery", "running"],
+ );
+ assert.deepEqual(
+ subagentNames(yield* store.getThreadRecords(threadId, ["subagents"])),
+ subagents.map(([name]) => name).toSorted(),
+ );
+ // A command about one settled task keeps it, and reads only its node and turn item.
+ const deliveredId = NodeId.make("node:settled-subagents:delivered");
+ const forTask = yield* store.getThreadRecords(threadId, ["subagents", "nodes", "turnItems"], {
+ omitSettledSubagents: { except: [deliveredId] },
+ nodeIds: [NodeId.make("node:settled-leaf-nodes:settled-tool")],
+ turnItemNodeIds: [deliveredId],
+ });
+ assert.deepEqual(subagentNames(forTask), [
+ "active-run-delivered",
+ "claimed",
+ "delivered",
+ "no-delivery",
+ "pending-delivery",
+ "running",
+ ]);
+ assert.deepEqual(nodeNames(forTask), ["settled-tool"]);
+ assert.deepEqual(
+ forTask.turnItems.map((item) => item.title),
+ ["delivered"],
+ );
+ assert.strictEqual(yield* store.getSubagentCount(threadId), subagents.length);
});
const backgroundThreadUpdatesKeepTimestamp = Effect.gen(function* () {
@@ -3535,6 +3650,12 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
const projection = yield* projectionStore.getThreadProjection(threadId);
assert.deepEqual(projection.runs[0]?.delegatedCompletion, run.delegatedCompletion);
assert.deepEqual(projection.subagents[0]?.completionDelivery, task.completionDelivery);
+ assert.deepEqual(
+ (yield* projectionStore.getThreadRecords(threadId, ["subagents"], {
+ omitSettledSubagents: true,
+ })).subagents,
+ [],
+ );
}),
);
@@ -4428,6 +4549,8 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
(row) => row.id === threadId,
),
);
+ assert.strictEqual(yield* store.getLimitRecoveryWakeAt(now), DateTime.toEpochMillis(reset));
+ assert.isNull(yield* store.getLimitRecoveryWakeAt(reset));
const due = (yield* store.getLimitRecoveryCandidates({
...recoveryOptions,
now: reset,
@@ -4450,9 +4573,14 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
(row) => row.id === threadId,
),
);
+ assert.strictEqual(
+ yield* store.getLimitRecoveryWakeAt(reset),
+ DateTime.toEpochMillis(DateTime.add(reset, { minutes: 1 })),
+ );
yield* sql`UPDATE orchestration_v2_projection_threads
SET payload_json = json_set(payload_json, '$.snoozedUntil', NULL, '$.limitRecovery.autoResume', json('false'))
WHERE thread_id = ${threadId}`;
+ assert.isNull(yield* store.getLimitRecoveryWakeAt(now));
assert.isUndefined(
(yield* store.getLimitRecoveryCandidates({
...recoveryOptions,
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts
index 88a9073117d..805828064b4 100644
--- a/apps/server/src/orchestration-v2/ProjectionStore.ts
+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts
@@ -332,11 +332,19 @@ export interface ProjectionRecordFilter {
readonly messageIds?: ReadonlyArray<MessageId>;
readonly messageRunIds?: ReadonlyArray<RunId>;
readonly turnItemRunIds?: ReadonlyArray<RunId | null>;
+ readonly turnItemNodeIds?: ReadonlyArray<NodeId>;
readonly runIds?: ReadonlyArray<RunId>;
readonly subagentIds?: ReadonlyArray<NodeId>;
+ readonly subagentRunIds?: ReadonlyArray<RunId>;
+ readonly nodeIds?: ReadonlyArray<NodeId>;
readonly turnItemTypes?: ReadonlyArray<OrchestrationV2TurnItem["type"]>;
readonly turnItemStatuses?: ReadonlyArray<OrchestrationV2TurnItem["status"]>;
readonly omitSettledLeafNodes?: boolean;
+ /**
+ * Skips ended subagents whose completion was acknowledged, delivered or disposed, unless their
+ * run is active or `except` names them.
+ */
+ readonly omitSettledSubagents?: true | { readonly except: ReadonlyArray<NodeId> };
}
// A fork inherits its source's history before it has messages of its own,
@@ -436,6 +444,7 @@ export interface ProjectionStoreV2Shape {
options: ProjectionTimelinePageOptions,
) => Effect.Effect<ProjectionTimelinePage, ProjectionStoreV2Error>;
readonly getMessageCount: (threadId: ThreadId) => Effect.Effect<number, ProjectionStoreV2Error>;
+ readonly getSubagentCount: (threadId: ThreadId) => Effect.Effect<number, ProjectionStoreV2Error>;
readonly getNextTurnItemOrdinal: (
threadId: ThreadId,
) => Effect.Effect<number, ProjectionStoreV2Error>;
@@ -496,6 +505,10 @@ export interface ProjectionStoreV2Shape {
readonly autoResume: boolean;
readonly snooze: boolean;
}) => Effect.Effect<ReadonlyArray<ProjectionLimitRecoveryCandidate>, ProjectionStoreV2Error>;
+ /** Epoch ms of the next armed reset or snooze end after `now`, when a waiting thread becomes a candidate. */
+ readonly getLimitRecoveryWakeAt: (
+ now: DateTime.Utc,
+ ) => Effect.Effect<number | null, ProjectionStoreV2Error>;
readonly getSettlementCandidates: (
threadId?: ThreadId,
) => Effect.Effect<ReadonlyArray<ProjectionSettlementCandidate>, ProjectionStoreV2Error>;
@@ -2107,6 +2120,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
started_at,
completed_at,
updated_at,
+ completion_delivery_state,
payload_json
)
VALUES (
@@ -2124,6 +2138,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${nullableStringField(payload, "startedAt")},
${nullableStringField(payload, "completedAt")},
${stringField(payload, "updatedAt")},
+ ${event.payload.completionDelivery?.state ?? null},
${payloadJson}
)
ON CONFLICT(subagent_id)
@@ -2141,6 +2156,10 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
started_at = excluded.started_at,
completed_at = excluded.completed_at,
updated_at = excluded.updated_at,
+ completion_delivery_state = COALESCE(
+ excluded.completion_delivery_state,
+ orchestration_v2_projection_subagents.completion_delivery_state
+ ),
payload_json = CASE
WHEN json_type(excluded.payload_json, '$.completionDelivery') IS NULL
AND json_type(orchestration_v2_projection_subagents.payload_json, '$.completionDelivery') IS NOT NULL
@@ -2980,7 +2999,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
const boundedTurnItemRows: ReadonlyArray<WindowPayloadRow> =
(fields !== undefined && !fields.includes("turnItems")) ||
(window === undefined &&
- matchesNothing(filter?.turnItemTypes, filter?.turnItemStatuses, filter?.turnItemRunIds))
+ matchesNothing(
+ filter?.turnItemTypes,
+ filter?.turnItemStatuses,
+ filter?.turnItemRunIds,
+ filter?.turnItemNodeIds,
+ ))
? []
: window === undefined
? yield* sql<PayloadRow>`
@@ -2990,6 +3014,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
${filter?.turnItemTypes === undefined ? sql`` : sql`AND type IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemTypes)}))`}
${filter?.turnItemStatuses === undefined ? sql`` : sql`AND status IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemStatuses)}))`}
${filter?.turnItemRunId === undefined ? sql`` : sql`AND run_id = ${filter.turnItemRunId}`}
+ ${filter?.turnItemNodeIds === undefined ? sql`` : sql`AND node_id IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemNodeIds)}))`}
${filter?.turnItemRunIds === undefined ? sql`` : sql`AND (run_id IN (SELECT value FROM json_each(${encodeIdList(filter.turnItemRunIds.filter((id): id is RunId => id !== null))})) OR (${filter.turnItemRunIds.includes(null) ? 1 : 0} = 1 AND run_id IS NULL))`}
ORDER BY ordinal ASC, turn_item_id ASC
`
@@ -3216,13 +3241,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
OR run_id IN (SELECT value FROM json_each(${cohortRunIds})))
ORDER BY run_id ASC, attempt_ordinal ASC
`,
- fields !== undefined && !fields.includes("nodes")
+ (fields !== undefined && !fields.includes("nodes")) ||
+ (window === undefined && matchesNothing(filter?.nodeIds))
? Effect.succeed([])
: window === undefined
? sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_nodes AS node
WHERE node.thread_id = ${threadId}
+ ${filter?.nodeIds === undefined ? sql`` : sql`AND node.node_id IN (SELECT value FROM json_each(${encodeIdList(filter.nodeIds)}))`}
${
filter?.omitSettledLeafNodes === true
? sql`AND NOT (
@@ -3253,14 +3280,34 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
),
),
(fields !== undefined && !fields.includes("subagents")) ||
- (window === undefined && matchesNothing(filter?.subagentIds))
+ (window === undefined &&
+ (matchesNothing(filter?.subagentIds) || matchesNothing(filter?.subagentRunIds)))
? Effect.succeed([])
: window === undefined
? sql<PayloadRow>`
SELECT payload_json
- FROM orchestration_v2_projection_subagents
+ FROM orchestration_v2_projection_subagents AS subagent
WHERE thread_id = ${threadId}
${filter?.subagentIds === undefined ? sql`` : sql`AND subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentIds)}))`}
+ ${filter?.subagentRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentRunIds)}))`}
+ ${
+ filter?.omitSettledSubagents !== undefined
+ ? sql`AND (${
+ filter.omitSettledSubagents === true
+ ? sql`0`
+ : sql`subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.omitSettledSubagents.except)}))`
+ } OR NOT (
+ subagent.status IN ('completed', 'failed', 'cancelled', 'interrupted')
+ AND COALESCE(subagent.completion_delivery_state, '')
+ IN ('acknowledged', 'delivered', 'disposed')
+ AND NOT EXISTS (
+ SELECT 1 FROM orchestration_v2_projection_runs AS run
+ WHERE run.run_id = subagent.run_id
+ AND run.status IN ('preparing', 'queued', 'starting', 'running', 'waiting')
+ )
+ ))`
+ : sql``
+ }
ORDER BY COALESCE(started_at, ''), subagent_id ASC
`
: sql<PayloadRow>`
@@ -3863,6 +3910,34 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
);
+ const getLimitRecoveryWakeAt = Effect.fn("ProjectionStore.getLimitRecoveryWakeAt")(
+ function* (now: DateTime.Utc) {
+ const nowIso = DateTime.formatIso(now);
+ const rows = yield* sql<{
+ readonly reset_ms: number | null;
+ readonly snooze_ms: number | null;
+ }>`
+ SELECT
+ MIN(CASE WHEN julianday(reset_at) > julianday(${nowIso})
+ THEN (julianday(reset_at) - 2440587.5) * 86400000 END) AS reset_ms,
+ MIN(CASE WHEN julianday(snoozed_until) > julianday(${nowIso})
+ THEN (julianday(snoozed_until) - 2440587.5) * 86400000 END) AS snooze_ms
+ FROM (
+ SELECT json_extract(payload_json, '$.limitRecovery.resetAt') AS reset_at,
+ json_extract(payload_json, '$.snoozedUntil') AS snoozed_until
+ FROM orchestration_v2_projection_threads
+ WHERE deleted_at IS NULL
+ AND json_extract(payload_json, '$.limitRecovery.autoResume') = 1
+ )
+ `;
+ const wakes = [rows[0]?.reset_ms, rows[0]?.snooze_ms].filter(
+ (value): value is number => value != null,
+ );
+ return wakes.length === 0 ? null : Math.round(Math.min(...wakes));
+ },
+ Effect.mapError((cause) => new ProjectionStoreSetupError({ cause })),
+ );
+
const getRecoveryThreadIds = Effect.fn("ProjectionStore.getRecoveryThreadIds")(
function* (kind: ProjectionRecoveryKind) {
const candidates = (() => {
@@ -5204,6 +5279,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
Effect.map((rows) => rows[0]?.count ?? 0),
Effect.mapError(controlReadError(threadId)),
);
+ const getSubagentCount: ProjectionStoreV2Shape["getSubagentCount"] = (threadId) =>
+ sql<{
+ count: number;
+ }>`SELECT COUNT(*) AS count FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId}`.pipe(
+ Effect.map((rows) => rows[0]?.count ?? 0),
+ Effect.mapError(controlReadError(threadId)),
+ );
const getNextTurnItemOrdinal: ProjectionStoreV2Shape["getNextTurnItemOrdinal"] = (threadId) =>
sql<{ ordinal: number | null }>`SELECT MAX(ordinal) AS ordinal
FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}`.pipe(
@@ -6918,6 +7000,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
hasUnpairedRunInterruptRequest: readOnReader(hasUnpairedRunInterruptRequest),
isNodeStored: readOnReader(isNodeStored),
getMessageCount: readOnReader(getMessageCount),
+ getSubagentCount: readOnReader(getSubagentCount),
getNextTurnItemOrdinal: readOnReader(getNextTurnItemOrdinal),
getTurnItem: readOnReader(getTurnItem),
getThreadRecords: (threadId, fields, filter) =>
@@ -6926,6 +7009,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
getPlan: readOnReader(getPlan),
getProviderControlContext: readOnReader(getProviderControlContext),
getLimitRecoveryCandidates: readOnReader(getLimitRecoveryCandidates),
+ getLimitRecoveryWakeAt: readOnReader(getLimitRecoveryWakeAt),
getRecoveryThreadIds: readOnReader(getRecoveryThreadIds),
getUnreadableThreadIds: readOnReader(getUnreadableThreadIds),
getThreadSnapshot: readOnReader(getThreadSnapshot),
diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
index 65da8b23676..7932a03809c 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
@@ -210,6 +210,7 @@ it.effect(
ProjectionStore.ProjectionStoreV2.of({
apply: () => Effect.void,
getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),
+ getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"),
getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),
getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),
@@ -235,6 +236,7 @@ it.effect(
getThreadHistoryPage: () => Effect.die("unused"),
getTimelinePage: () => Effect.die("Unused timeline read"),
getMessageCount: () => Effect.die("unused message count"),
+ getSubagentCount: () => Effect.die("unused subagent count"),
getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
getTurnItem: () => Effect.die("unused turn item read"),
getThreadRecords: () => Effect.die("unused record read"),
diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
index eccb107bc25..a0a284b5db5 100644
--- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
@@ -222,6 +222,7 @@ const makeHarness = Effect.fn("makePullRequestSyncHarness")(function* (options:
const layerDependencies = Layer.mergeAll(
Layer.mock(PullRequestService.PullRequestService)({
+ withSharedProjectReads: (effect) => effect,
summary,
stack,
invalidate: options.invalidate ?? (() => Effect.void),
diff --git a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
index ab3c0dca08a..2c97b1867ef 100644
--- a/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
+++ b/apps/server/src/orchestration-v2/PullRequestSyncReactor.ts
@@ -599,7 +599,7 @@ export const make = Effect.gen(function* () {
const worker = yield* makeDrainableWorker((scope: "all" | "requested") =>
Effect.suspend(() => {
if (scope === "requested") requestedSweepQueued = false;
- return sweep(scope);
+ return pullRequests.withSharedProjectReads(sweep(scope));
}).pipe(Effect.catchCause(logSkipped("pull request sync sweep failed", {}))),
);
diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts
new file mode 100644
index 00000000000..2e077314b82
--- /dev/null
+++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.test.ts
@@ -0,0 +1,70 @@
+import { assert, it } from "@effect/vitest";
+import type { OrchestrationV2DomainEvent } from "@t3tools/contracts";
+import * as Clock from "effect/Clock";
+import * as DateTime from "effect/DateTime";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Queue from "effect/Queue";
+import * as Stream from "effect/Stream";
+import * as TestClock from "effect/testing/TestClock";
+
+import * as Scheduler from "../scheduling/Scheduler.ts";
+import * as ServerSettings from "../serverSettings.ts";
+import * as Orchestrator from "./Orchestrator.ts";
+import * as ProjectionStore from "./ProjectionStore.ts";
+import * as ThreadManagement from "./ThreadManagementService.ts";
+import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts";
+
+it.effect("idle sweeps skip SQL until the next wake time or a relevant event", () =>
+ Effect.gen(function* () {
+ yield* TestClock.setTime(Date.parse("2026-07-01T09:00:00.000Z"));
+ const startMs = Date.parse("2026-07-01T09:00:00.000Z");
+ const queries = yield* Queue.unbounded<number>();
+ const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
+ const layer = UsageLimitRecoveryWorker.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Scheduler.layer,
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
+ getLimitRecoveryCandidates: () =>
+ Clock.currentTimeMillis.pipe(
+ Effect.flatMap((nowMs) => Queue.offer(queries, nowMs - startMs)),
+ Effect.as([]),
+ ),
+ // One armed thread resets at 60s.
+ getLimitRecoveryWakeAt: (now) =>
+ Effect.succeed(
+ DateTime.toEpochMillis(now) < startMs + 60_000 ? startMs + 60_000 : null,
+ ),
+ }),
+ Layer.mock(ThreadManagement.ThreadManagementService)({}),
+ Layer.mock(Orchestrator.OrchestratorV2)({
+ streamDomainEvents: Stream.fromQueue(events),
+ }),
+ Layer.mock(ServerSettings.ServerSettingsService)({
+ getSettings: Effect.succeed({
+ autoResumeLimitedThreads: true,
+ snoozeLimitedThreads: false,
+ } as never),
+ streamChanges: Stream.never,
+ }),
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ assert.equal(yield* Queue.take(queries), 0);
+ // Eleven idle ticks before the recorded wake time, then the wake tick itself.
+ yield* TestClock.adjust("60 seconds");
+ assert.equal(yield* Queue.take(queries), 60_000);
+ yield* Queue.offer(events, {
+ type: "turn-item.updated",
+ payload: { type: "assistant_message" },
+ } as never);
+ yield* TestClock.adjust("30 seconds");
+ yield* Queue.offer(events, { type: "run.updated", payload: { status: "failed" } } as never);
+ yield* TestClock.adjust("5 seconds");
+ // A streaming item at 90s does not wake it; the failed run does on the 95s tick.
+ assert.equal(yield* Queue.take(queries), 95_000);
+ }).pipe(Effect.provide(layer));
+ }),
+);
diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
index b6ebedfec4c..224eecbbe5f 100644
--- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
+++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts
@@ -2,7 +2,11 @@ import { CommandId, MessageId, type OrchestrationV2Command } from "@t3tools/cont
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
+import * as Stream from "effect/Stream";
+import type { OrchestrationV2DomainEvent } from "@t3tools/contracts";
+import * as DueHint from "../scheduling/DueHint.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
+import { forkParked } from "../serverActivation.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as ProjectionStore from "./ProjectionStore.ts";
import * as Orchestrator from "./Orchestrator.ts";
@@ -71,20 +75,39 @@ export function limitRecoveryCommand(
};
}
+// Events that can make a thread a candidate or change its command; streaming items cannot.
+const affectsLimitRecovery = (event: OrchestrationV2DomainEvent) =>
+ event.type.startsWith("thread.") ||
+ event.type === "run.created" ||
+ event.type === "run.updated" ||
+ event.type === "runtime-request.updated" ||
+ event.type.startsWith("provider-session.") ||
+ (event.type === "turn-item.updated" && event.payload.type === "error");
+
const makeSweep = Effect.gen(function* () {
const projections = yield* ProjectionStore.ProjectionStoreV2;
const threads = yield* ThreadManagement.ThreadManagementService;
const orchestrator = yield* Orchestrator.OrchestratorV2;
const settings = yield* ServerSettings.ServerSettingsService;
+ const due = DueHint.make();
+ yield* forkParked(
+ Stream.runForEach(orchestrator.streamDomainEvents, (event) =>
+ affectsLimitRecovery(event) ? due.invalidate : Effect.void,
+ ),
+ );
+ yield* forkParked(Stream.runForEach(settings.streamChanges, () => due.invalidate));
return Effect.fn("UsageLimitRecoveryWorker.sweep")(function* () {
- const preferences = yield* settings.getSettings;
const now = yield* DateTime.now;
+ const nowMs = DateTime.toEpochMillis(now);
+ if (yield* due.isIdle(nowMs)) return;
+ const readVersion = yield* due.version;
+ const preferences = yield* settings.getSettings;
const candidates = yield* projections.getLimitRecoveryCandidates({
now,
autoResume: preferences.autoResumeLimitedThreads,
snooze: preferences.snoozeLimitedThreads,
});
- const nowMs = DateTime.toEpochMillis(now);
+ let acted = false;
for (const thread of candidates) {
const command = limitRecoveryCommand(
thread,
@@ -93,6 +116,7 @@ const makeSweep = Effect.gen(function* () {
preferences.snoozeLimitedThreads,
);
if (command === null) continue;
+ acted = true;
yield* Effect.gen(function* () {
if (command.type === "thread.metadata.update" && command.limitRecovery != null) {
yield* orchestrator.autoArmLimitRecovery({
@@ -112,6 +136,10 @@ const makeSweep = Effect.gen(function* () {
),
);
}
+ // A sweep that acted, or failed to, re-checks on the next tick.
+ if (acted) return;
+ const wakeAt = yield* projections.getLimitRecoveryWakeAt(now);
+ yield* due.record(readVersion, wakeAt ?? Infinity, nowMs);
});
});
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 6a865a8fc89..1f3fb4bc6b8 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -77,6 +77,7 @@ import Migration0071 from "./Migrations/071_PeerLinkFence.ts";
import Migration0072 from "./Migrations/072_WaitingLinkRequestIndex.ts";
import Migration0073 from "./Migrations/073_ActiveTurnItemIndexes.ts";
import Migration0074 from "./Migrations/074_ExcludeAttachmentPlaceholdersFromSearch.ts";
+import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -154,6 +155,7 @@ const migrationEntries = [
[72, "WaitingLinkRequestIndex", Migration0072],
[73, "ActiveTurnItemIndexes", Migration0073],
[74, "ExcludeAttachmentPlaceholdersFromSearch", Migration0074],
+ [75, "SubagentDeliveryState", Migration0075],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts
new file mode 100644
index 00000000000..4406911cc8a
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/075_SubagentDeliveryState.ts
@@ -0,0 +1,20 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ // Command reads skip settled subagents by delivery state. Read from payload_json, that parsed
+ // every stored prompt; an added column sits after the payload's overflow pages, so the index
+ // must cover the whole filter.
+ yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN completion_delivery_state TEXT`;
+ yield* sql`
+ UPDATE orchestration_v2_projection_subagents
+ SET completion_delivery_state = json_extract(payload_json, '$.completionDelivery.state')
+ WHERE json_type(payload_json, '$.completionDelivery') IS NOT NULL
+ `;
+ yield* sql`
+ CREATE INDEX orchestration_v2_projection_subagents_settled_idx
+ ON orchestration_v2_projection_subagents(thread_id, status, completion_delivery_state, run_id)
+ `;
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index 472c09d728a..4fefa61ec01 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -54,6 +54,7 @@ describe("V2 preview upgrade", () => {
[72, "WaitingLinkRequestIndex"],
[73, "ActiveTurnItemIndexes"],
[74, "ExcludeAttachmentPlaceholdersFromSearch"],
+ [75, "SubagentDeliveryState"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -151,6 +152,7 @@ describe("V2 preview upgrade", () => {
[72, "WaitingLinkRequestIndex"],
[73, "ActiveTurnItemIndexes"],
[74, "ExcludeAttachmentPlaceholdersFromSearch"],
+ [75, "SubagentDeliveryState"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts
index 3c511b292af..49060afb275 100644
--- a/apps/server/src/pullRequest/PullRequestService.test.ts
+++ b/apps/server/src/pullRequest/PullRequestService.test.ts
@@ -257,6 +257,7 @@ function makeService(input: {
readonly providers: ReadonlyArray<PullRequestProviderApi>;
readonly resolveHandle?: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"]["resolveHandle"];
readonly resolveRepositoryIdentity?: RepositoryIdentityResolver.RepositoryIdentityResolver["Service"]["resolve"];
+ readonly onProjectRead?: () => void;
}) {
// Build in the test scope; per-call Effect.provide would close the marks database on service acquisition.
return Effect.flatMap(
@@ -280,11 +281,17 @@ function makeService(input: {
}),
Layer.mock(ProjectService.ProjectService)({
listShells: (options) =>
- Effect.succeed(
- input.projects.filter((project) => options?.projectIds?.includes(project.id) ?? true),
- ),
+ Effect.sync(() => {
+ input.onProjectRead?.();
+ return input.projects.filter(
+ (project) => options?.projectIds?.includes(project.id) ?? true,
+ );
+ }),
getShell: (projectId) =>
- Effect.succeed(Option.fromNullishOr(input.projects.find((p) => p.id === projectId))),
+ Effect.sync(() => {
+ input.onProjectRead?.();
+ return Option.fromNullishOr(input.projects.find((p) => p.id === projectId));
+ }),
}),
Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
resolve: input.resolveRepositoryIdentity ?? (() => Effect.succeed(null)),
@@ -1708,7 +1715,11 @@ it.effect("resolves a project's repository identity when its shell has none cach
it.effect("routes a hosted reference to another repository through a project on that host", () =>
Effect.gen(function* () {
const seen: Array<{ cwd: string; repository: string; host: string }> = [];
+ let projectReads = 0;
const service = yield* makeService({
+ onProjectRead: () => {
+ projectReads += 1;
+ },
projects: [
project({ id: "frontend", title: "web", workspaceRoot: "/web", repository: "acme/web" }),
],
@@ -1730,6 +1741,20 @@ it.effect("routes a hosted reference to another repository through a project on
assert.strictEqual(summary.number, 7);
assert.deepStrictEqual(seen, [{ cwd: "/web", repository: "acme/api", host: "github.com" }]);
+
+ // A sync sweep resolves the project once for all of its references, then reads fresh again.
+ const readsPerReference = projectReads;
+ const read = (number: number) =>
+ service.summary(
+ { projectId: "frontend" as ProjectId, host: "github.com", repository: "acme/api", number },
+ { recoverTransientFailure: false },
+ );
+ assert.isAbove(readsPerReference, 2);
+ yield* service.withSharedProjectReads(Effect.all([read(8), read(9), read(10)]));
+ // One read of the project and one of the host's projects, for all three references.
+ assert.strictEqual(projectReads, readsPerReference + 2);
+ yield* read(11);
+ assert.strictEqual(projectReads, readsPerReference * 2 + 2);
}),
);
diff --git a/apps/server/src/pullRequest/PullRequestService.ts b/apps/server/src/pullRequest/PullRequestService.ts
index e1f0f6525fb..a3ce2e75dda 100644
--- a/apps/server/src/pullRequest/PullRequestService.ts
+++ b/apps/server/src/pullRequest/PullRequestService.ts
@@ -215,6 +215,10 @@ export class PullRequestService extends Context.Service<
) => Effect.Effect<void, PullRequestError>;
readonly subscribeRefreshes: Stream.Stream<number>;
readonly refreshAfterTurn: (projectId: ProjectId) => Effect.Effect<void>;
+ /** Project and remote lookups inside `effect` read once per filter, e.g. across one sync sweep. */
+ readonly withSharedProjectReads: <A, E, R>(
+ effect: Effect.Effect<A, E, R>,
+ ) => Effect.Effect<A, E, R>;
readonly detail: (input: PullRequestRef) => Effect.Effect<PullRequestDetail, PullRequestError>;
readonly preview: (
input: PullRequestRef,
@@ -334,6 +338,12 @@ interface WorkspaceProjects {
readonly viewerRoots: ReadonlyMap<string, ReadonlyArray<string>>;
}
+// Inherited by fibers forked inside the scope, so it is closed, not just dropped, when the scope ends.
+const sharedProjectReads = Context.Reference<{
+ open: boolean;
+ readonly reads: Map<string, Effect.Effect<WorkspaceProjects, PullRequestError>>;
+} | null>("t3/PullRequestService/sharedProjectReads", { defaultValue: () => null });
+
interface RepositoryBatch {
readonly key: string;
readonly entries: ReadonlyArray<PullRequestListEntry>;
@@ -828,6 +838,34 @@ export const make = Effect.gen(function* () {
const listWorkspaceProjects = (
filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
+ ): Effect.Effect<WorkspaceProjects, PullRequestError> =>
+ Effect.flatMap(sharedProjectReads, (shared) => {
+ if (shared === null || !shared.open) return readWorkspaceProjects(filter);
+ const key = JSON.stringify([filter.projectId, filter.projectIds, filter.host]);
+ const existing = shared.reads.get(key);
+ if (existing !== undefined) return existing;
+ return Effect.cached(readWorkspaceProjects(filter)).pipe(
+ Effect.tap((read) => Effect.sync(() => shared.reads.set(key, read))),
+ Effect.flatten,
+ );
+ });
+
+ const withSharedProjectReads = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
+ Effect.suspend(() => {
+ const shared = { open: true, reads: new Map() };
+ return effect.pipe(
+ Effect.provideService(sharedProjectReads, shared),
+ Effect.ensuring(
+ Effect.sync(() => {
+ shared.open = false;
+ shared.reads.clear();
+ }),
+ ),
+ );
+ });
+
+ const readWorkspaceProjects = (
+ filter: Pick<PullRequestListInput, "projectId" | "projectIds" | "host">,
): Effect.Effect<WorkspaceProjects, PullRequestError> =>
(filter.projectId === undefined
? projects.listShells(
@@ -3660,6 +3698,7 @@ export const make = Effect.gen(function* () {
);
return PullRequestService.of({
+ withSharedProjectReads,
routing,
routingIdentity,
withRoutingCredential,
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index f05811ed651..7bdfef9cab6 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -49,6 +49,7 @@ import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
import * as Metrics from "../observability/Metrics.ts";
import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
+import * as DueHint from "../scheduling/DueHint.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
import {
@@ -396,35 +397,6 @@ export const listDueTasks = Effect.fn("ScheduledTaskService.listDueTasks")(funct
return tasks;
});
-// Backstop for a write path that forgets to invalidate; the tick still runs every few seconds.
-const DUE_HINT_MAX_AGE_MS = 10 * 60 * 1_000;
-
-/**
- * Remembers when a poller next has work so idle scheduler ticks skip SQL.
- * `invalidate` after every write that can move work earlier; a tick records
- * only if no write happened since it read `version`.
- */
-const makeDueHint = () => {
- let version = 0;
- let hint: { readonly dueAtMs: number; readonly checkedAtMs: number } | null = null;
- return {
- invalidate: Effect.sync(() => {
- version++;
- hint = null;
- }),
- version: Effect.sync(() => version),
- isIdle: (nowMs: number) =>
- Effect.sync(
- () =>
- hint !== null && hint.dueAtMs > nowMs && nowMs - hint.checkedAtMs < DUE_HINT_MAX_AGE_MS,
- ),
- record: (readVersion: number, dueAtMs: number, nowMs: number) =>
- Effect.sync(() => {
- if (readVersion === version) hint = { dueAtMs, checkedAtMs: nowMs };
- }),
- };
-};
-
export const layer = Layer.effect(
ScheduledTaskService,
Effect.gen(function* () {
@@ -455,8 +427,8 @@ export const layer = Layer.effect(
const activeRuns = yield* Ref.make<ReadonlySet<ScheduledTaskId>>(new Set());
// Notifications re-emit the full list; slow subscribers need only the newest dirty signal.
const changesPubSub = yield* PubSub.sliding<void>(1);
- const dueTasks = makeDueHint();
- const pendingWebhooks = makeDueHint();
+ const dueTasks = DueHint.make();
+ const pendingWebhooks = DueHint.make();
// Every scheduled_tasks write that can change next_run_at, enabled or run state notifies.
const notifyChanged = dueTasks.invalidate.pipe(
Effect.andThen(PubSub.publish(changesPubSub, undefined)),
diff --git a/apps/server/src/scheduling/DueHint.ts b/apps/server/src/scheduling/DueHint.ts
new file mode 100644
index 00000000000..2df8af5f0c5
--- /dev/null
+++ b/apps/server/src/scheduling/DueHint.ts
@@ -0,0 +1,30 @@
+import * as Effect from "effect/Effect";
+
+// Backstop for a write path that forgets to invalidate; the tick still runs every few seconds.
+const DUE_HINT_MAX_AGE_MS = 10 * 60 * 1_000;
+
+/**
+ * Remembers when a poller next has work so idle scheduler ticks skip SQL.
+ * `invalidate` after every write that can move work earlier; a tick records
+ * only if no write happened since it read `version`.
+ */
+export const make = () => {
+ let version = 0;
+ let hint: { readonly dueAtMs: number; readonly checkedAtMs: number } | null = null;
+ return {
+ invalidate: Effect.sync(() => {
+ version++;
+ hint = null;
+ }),
+ version: Effect.sync(() => version),
+ isIdle: (nowMs: number) =>
+ Effect.sync(
+ () =>
+ hint !== null && hint.dueAtMs > nowMs && nowMs - hint.checkedAtMs < DUE_HINT_MAX_AGE_MS,
+ ),
+ record: (readVersion: number, dueAtMs: number, nowMs: number) =>
+ Effect.sync(() => {
+ if (readVersion === version) hint = { dueAtMs, checkedAtMs: nowMs };
+ }),
+ };
+};