perf(server): commands on busy threads stop decoding thousands of finished tool nodes (#19675)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5.5 authored and GitHub committed 2026-10-14 17:05:21 -07:00
1 parent 742c229957
commit ab3a3cd162
3 files changed
+147 -4

No files matched your search

@@ -940,6 +940,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
// Command decisions need control records, not historical assistant/tool output.
// Handoff preparation explicitly reads its history after choosing a strategy.
// This runs inside the write transaction for every command, so finished leaf
// nodes of finished runs stay unread: busy threads hold thousands of them.
const readCommandProjection = (threadId: ThreadId) =>
projectionStore
.getThreadRecords(
@@ -958,7 +960,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
"checkpointScopes",
"contextTransfers",
],
{ turnItemTypes: ["user_message", "error"], messageRoles: ["user"] },
{
turnItemTypes: ["user_message", "error"],
messageRoles: ["user"],
omitSettledLeafNodes: true,
},
)
.pipe(
Effect.map((records): OrchestrationV2ThreadProjection => ({
@@ -382,6 +382,89 @@ const threadWorktreePathsReadActiveThreads = Effect.gen(function* () {
]);
});
const commandReadsSkipSettledLeafNodes = Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
const now = yield* DateTime.now;
const threadId = yield* addRolledBackRecoveryCandidate("settled-leaf-nodes");
const settledRun = (yield* store.getThreadProjection(threadId)).runs[0]!;
const activeRun = {
...settledRun,
id: RunId.make("run:settled-leaf-nodes:active"),
ordinal: 2,
userMessageId: MessageId.make("message:settled-leaf-nodes:active"),
rootNodeId: NodeId.make("node:settled-leaf-nodes:active-root"),
status: "running" as const,
completedAt: null,
};
yield* store.apply({
id: EventId.make("event:settled-leaf-nodes:active-run"),
type: "run.created",
threadId,
runId: activeRun.id,
nodeId: activeRun.rootNodeId,
driver,
providerInstanceId,
occurredAt: now,
payload: activeRun,
});
const nodes = [
["settled-root", settledRun, "root_turn", "completed"],
["settled-tool", settledRun, "tool_call", "completed"],
["settled-message", settledRun, "assistant_message", "failed"],
["settled-reasoning", settledRun, "reasoning", "cancelled"],
["settled-subagent", settledRun, "subagent", "completed"],
["settled-run-live-tool", settledRun, "tool_call", "running"],
["active-run-done-tool", activeRun, "tool_call", "completed"],
] as const;
for (const [name, run, kind, status] of nodes) {
const id = NodeId.make(`node:settled-leaf-nodes:${name}`);
yield* store.apply({
id: EventId.make(`event:settled-leaf-nodes:${name}`),
type: "node.updated",
threadId,
runId: run.id,
nodeId: id,
driver,
occurredAt: now,
payload: {
id,
threadId,
runId: run.id,
rootNodeId: kind === "root_turn" ? id : run.rootNodeId!,
parentNodeId: kind === "root_turn" ? null : run.rootNodeId,
kind,
status,
countsForRun: kind === "root_turn",
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: now,
completedAt: status === "running" ? null : now,
},
});
}
const nodeNames = (records: { readonly nodes: ReadonlyArray<{ readonly id: string }> }) =>
records.nodes
.map((node) => node.id.replace("node:settled-leaf-nodes:", ""))
.filter((name) => nodes.some(([candidate]) => candidate === name))
.toSorted();
assert.deepEqual(
nodeNames(yield* store.getThreadRecords(threadId, ["nodes"], { omitSettledLeafNodes: true })),
["active-run-done-tool", "settled-root", "settled-run-live-tool", "settled-subagent"],
);
assert.deepEqual(
nodeNames(yield* store.getThreadRecords(threadId, ["nodes"])),
nodes.map(([name]) => name).toSorted(),
);
});
it.effect("memory command reads skip finished leaf nodes of finished runs", () =>
commandReadsSkipSettledLeafNodes.pipe(Effect.provide(ProjectionStore.layerMemory)),
);
it.effect("memory worktree path lookup reads only active threads", () =>
threadWorktreePathsReadActiveThreads.pipe(Effect.provide(ProjectionStore.layerMemory)),
);
@@ -657,6 +740,10 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
assert.deepEqual(recovery?.restartCancelledBackgroundWork, work);
}),
);
it.effect(
"command reads skip finished leaf nodes of finished runs",
() => commandReadsSkipSettledLeafNodes,
);
it.effect("limits turn-start history to the requested runs, including an empty selection", () =>
Effect.gen(function* () {
const store = yield* ProjectionStore.ProjectionStoreV2;
@@ -304,7 +304,39 @@ export interface ProjectionRecordFilter {
readonly runIds?: ReadonlyArray<RunId>;
readonly turnItemTypes?: ReadonlyArray<OrchestrationV2TurnItem["type"]>;
readonly turnItemStatuses?: ReadonlyArray<OrchestrationV2TurnItem["status"]>;
// Skips finished tool call, assistant message and reasoning nodes of finished
// runs. Command decisions only read root, subagent and active-run nodes.
readonly omitSettledLeafNodes?: boolean;
}
type ProjectionNode = OrchestrationV2ThreadProjection["nodes"][number];
type ProjectionRun = OrchestrationV2ThreadProjection["runs"][number];
const settledLeafNodeKinds: ReadonlySet<ProjectionNode["kind"]> = new Set([
"tool_call",
"assistant_message",
"reasoning",
]);
const settledNodeStatuses: ReadonlySet<ProjectionNode["status"]> = new Set([
"completed",
"interrupted",
"failed",
"cancelled",
"rolled_back",
]);
const activeRunStatuses: ReadonlySet<ProjectionRun["status"]> = new Set([
"preparing",
"queued",
"starting",
"running",
"waiting",
]);
// In-memory twin of the omitSettledLeafNodes SQL clause in readCanonicalProjection.
const isSettledLeafNode = (node: ProjectionNode, runs: ReadonlyArray<ProjectionRun>) =>
settledLeafNodeKinds.has(node.kind) &&
settledNodeStatuses.has(node.status) &&
node.runId !== null &&
!runs.some((run) => run.id === node.runId && activeRunStatuses.has(run.status));
export type ProjectionRecordField = Exclude<
keyof OrchestrationV2ThreadProjection,
"thread" | "updatedAt" | "visibleTurnItems"
@@ -3069,9 +3101,23 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
: window === undefined
? sql<PayloadRow>`
SELECT payload_json
FROM orchestration_v2_projection_nodes
WHERE thread_id = ${threadId}
ORDER BY COALESCE(started_at, ''), node_id ASC
FROM orchestration_v2_projection_nodes AS node
WHERE node.thread_id = ${threadId}
${
filter?.omitSettledLeafNodes === true
? sql`AND NOT (
node.kind IN ('tool_call', 'assistant_message', 'reasoning')
AND node.status IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back')
AND node.run_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM orchestration_v2_projection_runs AS run
WHERE run.run_id = node.run_id
AND run.status IN ('preparing', 'queued', 'starting', 'running', 'waiting')
)
)`
: sql``
}
ORDER BY COALESCE(node.started_at, ''), node.node_id ASC
`
: sql<PayloadRow & { readonly position: number }>`
-- Keep retained IDs outermost so SQLite looks up each node by its
@@ -6423,6 +6469,10 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
filter.turnItemStatuses.includes(row.status)) &&
(filter?.turnItemRunId === undefined || filter.turnItemRunId === row.runId),
),
nodes:
filter?.omitSettledLeafNodes === true
? projection.nodes.filter((node) => !isSettledLeafNode(node, projection.runs))
: projection.nodes,
};
return Object.fromEntries([
["thread", projection.thread],