diff --git a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts index e2ea6850b..67759836e 100644 --- a/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.history-load.test.ts @@ -99,6 +99,74 @@ describe("ClaudeAgentSession persisted history load", () => { rmSync(tempRoot, { recursive: true, force: true }); }); + test("resumes many records within a chunk-sized event-loop turn budget", async () => { + const count = 3_072; + const text = "🙂".repeat(128); + const entries = Array.from({ length: count }, (_, index) => + JSON.stringify({ type: "assistant", message: { content: `${index}:${text}` } }), + ); + entries.splice(count / 2, 0, JSON.stringify({ type: "system", subtype: "compact_boundary" })); + mkdirSync(path.dirname(transcriptPath()), { recursive: true }); + writeFileSync(transcriptPath(), entries.join("\n")); + + let turns = 0; + let ticker: NodeJS.Immediate; + function tick() { + turns++; + const deadline = performance.now() + 2; + while (performance.now() < deadline) {} + ticker = setImmediate(tick); + } + ticker = setImmediate(tick); + + const session = await resume().finally(() => clearImmediate(ticker)); + + try { + const messages = []; + for await (const event of session.streamHistory()) { + if (event.type === "timeline" && event.item.type === "assistant_message") { + messages.push(event.item.text); + } + } + expect(messages).toEqual(Array.from({ length: count }, (_, index) => `${index}:${text}`)); + expect(turns).toBeLessThan(count); + } finally { + await session.close(); + } + }, 30_000); + + test("yields during replay of a dense window with an expensive consumer", async () => { + const file = transcriptPath(); + const count = 500; + const record = JSON.stringify({ type: "assistant", message: { content: "saved reply" } }); + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, (record + "\n").repeat(count)); + + await withClaudeReplayHistory(file, async (history) => { + let turns = 0; + let ticker: NodeJS.Immediate | undefined; + function tick() { + turns++; + ticker = setImmediate(tick); + } + + let entries = 0; + try { + for await (const _entry of history.parentEntries) { + // Start counting after the read so only yields within the window count. + ticker ??= setImmediate(tick); + const deadline = performance.now() + 1; + while (performance.now() < deadline) {} + entries++; + } + } finally { + if (ticker) clearImmediate(ticker); + } + expect(entries).toBe(count); + expect(turns).toBeGreaterThanOrEqual(20); + }); + }); + test("serves unrelated health requests while resuming 32 MiB of ordered history", async () => { const startedAt = performance.now(); mkdirSync(path.dirname(transcriptPath()), { recursive: true }); @@ -700,6 +768,75 @@ describe("ClaudeAgentSession persisted history load", () => { }, ); + test.each(["return", "throw"])( + "replays oversized records and closes every source after callback %s", + async (exit) => { + const parent = transcriptPath(); + const directory = path.join(parent.slice(0, -".jsonl".length), "subagents"); + const child = path.join(directory, "agent-child.jsonl"); + const workflow = path.join(directory, "workflows", "wf_test", "agent-child.jsonl"); + const notification = { + type: "system", + subtype: "task_notification", + task_id: "task-id", + status: "completed", + }; + const result = { + type: "user", + message: { + content: [ + { type: "tool_result", tool_use_id: "tool-id", content: "é".repeat(600 * 1024) }, + ], + }, + }; + const parentRecords = [notification, result, notification]; + const childRecords = parentRecords.map((entry) => ({ + ...entry, + isSidechain: true, + agentId: "child", + })); + mkdirSync(path.dirname(workflow), { recursive: true }); + writeFileSync(parent, parentRecords.map((entry) => JSON.stringify(entry)).join("\n")); + writeFileSync(child, childRecords.map((entry) => JSON.stringify(entry)).join("\n")); + writeFileSync(workflow, childRecords.map((entry) => JSON.stringify(entry)).join("\n")); + + const sources: AsyncIterable[] = []; + const failure = new Error("consumer failed"); + const replay = withClaudeReplayHistory(parent, async (history) => { + const parentEntries = await Array.fromAsync(history.parentEntries); + const firstId = expect.stringMatching(/^task_notification_.*_1$/); + const secondId = expect.stringMatching(/^task_notification_.*_2$/); + expect(parentEntries).toEqual([ + { ...notification, notificationId: firstId }, + result, + { ...notification, notificationId: secondId }, + ]); + const [first, , last] = parentEntries; + const childEntries = history.subagents[0]!.entries; + const workflowEntries = history.workflowEntriesByRunId.get("wf_test")!; + sources.push(history.parentEntries, childEntries, workflowEntries); + const expectedChildEntries = [ + { ...childRecords[0], notificationId: first!.notificationId }, + childRecords[1], + { ...childRecords[2], notificationId: last!.notificationId }, + ]; + expect(await Array.fromAsync(childEntries)).toEqual(expectedChildEntries); + expect(await Array.fromAsync(workflowEntries)).toEqual(expectedChildEntries); + expect(await Array.fromAsync(history.parentEntries)).toEqual(parentEntries); + if (exit === "throw") throw failure; + }); + if (exit === "throw") await expect(replay).rejects.toBe(failure); + else await replay; + + // Reading again probes whether replay released each descriptor when the callback ended. + for (const source of sources) { + await expect(source[Symbol.asyncIterator]().next()).rejects.toMatchObject({ + code: "EBADF", + }); + } + }, + ); + // chmod does not remove read access on Windows, or for root. test.skipIf(process.platform === "win32" || process.getuid?.() === 0)( "logs a warning with the error when Claude's project folders cannot be listed", diff --git a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts index 91007aa7c..31a4c60c4 100644 --- a/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts +++ b/packages/server/src/server/agent/providers/claude/agent.sub-agent-replay.test.ts @@ -878,11 +878,12 @@ describe("ClaudeAgentSession persisted subagent replay", () => { const text = "é🙂".repeat(30_000); const historyDir = claudeProjectDirSync(cwd, { configDir }); mkdirSync(historyDir, { recursive: true }); + const first = parentEntry([{ type: "text", text }]); + // Put the first byte of é at the end of a 1 MiB read. + const padding = " ".repeat(1024 * 1024 - 1 - first.indexOf(text)); writeFileSync( path.join(historyDir, "replay-session.jsonl"), - parentEntry([{ type: "text", text }]) + - "\r\nnot json\r\n" + - parentEntry([{ type: "text", text: "final row" }]), + padding + first + "\r\nnot json\r\n" + parentEntry([{ type: "text", text: "final row" }]), ); const events = await replayEvents(); expect(events.filter((event) => event.type === "timeline").map((event) => event.item)).toEqual([ diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts index edb673c66..86a4900d3 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.test.ts @@ -41,6 +41,34 @@ function parentEntries( } describe("Claude workflow replay", () => { + it("skips parent history when there are no workflow summaries", async () => { + const entries = { + [Symbol.iterator](): Iterator { + throw new Error("parent history must not be read"); + }, + }; + await expect( + observeReplayWorkflows({ workflows: [], parentEntries: entries }), + ).resolves.toEqual([]); + }); + + it("links workflow results from a single traversal, including results before their calls", async () => { + const [call, result] = parentEntries(); + const entries = (async function* () { + yield result!; + yield call!; + })(); + const observations = await observeReplayWorkflows({ + workflows: [{ runId: RUN_ID, status: "completed" }], + parentEntries: entries, + }); + expect(observations).toEqual([ + { kind: "declared", id: TOOL_CALL_ID, toolCallId: TOOL_CALL_ID, title: "Workflow" }, + { kind: "subtitle", id: TOOL_CALL_ID, subtitle: "Workflow" }, + { kind: "status", id: TOOL_CALL_ID, status: "completed" }, + ]); + }); + it("parses the persisted run summary observed from Claude Code 2.1.220", async () => { expect( parseClaudeWorkflowRun( diff --git a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts index 17a278d00..3addf8a05 100644 --- a/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts +++ b/packages/server/src/server/agent/providers/claude/subagents/workflow-replay-source.ts @@ -55,7 +55,9 @@ export async function observeReplayWorkflows(input: { >; convertEntry?: (entry: ClaudeReplayEntry) => AgentTimelineItem[] | Promise; }): Promise { - const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries); + if (input.workflows.length === 0) return []; + const runIds = new Set(input.workflows.map((workflow) => workflow.runId)); + const toolCallIdByRunId = await readWorkflowLinks(input.parentEntries, runIds); const observations: SubagentObservation[] = []; for (const workflow of input.workflows) { @@ -155,34 +157,33 @@ async function observeWorkflowTimeline(input: { async function readWorkflowLinks( entries: Iterable | AsyncIterable, + runIds: ReadonlySet, ): Promise> { const workflowToolCallIds = new Set(); - const toolCallIdByRunId = new Map(); - - for await (const entry of entries) { - const content = entry.message?.content; - if (!Array.isArray(content)) continue; - for (const value of content) { - const block = toRecord(value); - if (block?.type !== "tool_use" || block.name !== "Workflow") continue; - const id = readString(block.id); - if (id) workflowToolCallIds.add(id); - } - } + const results: { runId: string; toolCallId: string }[] = []; for await (const entry of entries) { const content = entry.message?.content; if (!Array.isArray(content)) continue; for (const value of content) { const block = toRecord(value); + if (block?.type === "tool_use" && block.name === "Workflow") { + const id = readString(block.id); + if (id) workflowToolCallIds.add(id); + } if (block?.type !== "tool_result") continue; const toolCallId = readString(block.tool_use_id); - if (!toolCallId || !workflowToolCallIds.has(toolCallId)) continue; + if (!toolCallId) continue; const runId = readRunId(block.content); - if (runId) toolCallIdByRunId.set(runId, toolCallId); + if (runId && runIds.has(runId)) results.push({ runId, toolCallId }); } } + // Resolve IDs in result order after all calls are known, even if a result precedes its call. + const toolCallIdByRunId = new Map(); + for (const { runId, toolCallId } of results) { + if (workflowToolCallIds.has(toolCallId)) toolCallIdByRunId.set(runId, toolCallId); + } return toolCallIdByRunId; } diff --git a/packages/server/src/server/agent/providers/claude/transcript-history.ts b/packages/server/src/server/agent/providers/claude/transcript-history.ts index 09882b76d..bef0e147d 100644 --- a/packages/server/src/server/agent/providers/claude/transcript-history.ts +++ b/packages/server/src/server/agent/providers/claude/transcript-history.ts @@ -13,6 +13,10 @@ import { type ClaudeWorkflowRun, } from "./subagents/workflow-replay-source.js"; +const READ_CHUNK_BYTES = 1024 * 1024; +// Async iteration between reads uses microtasks, including work inside the consumer. +const REPLAY_SLICE_MS = 10; + interface TranscriptEntry extends ClaudeReplayEntry { isSidechain?: unknown; } @@ -43,13 +47,18 @@ async function* locatedRecords( let pieces: Buffer[] = []; let length = 0; while (remaining > 0) { - const buffer = Buffer.allocUnsafe(Math.min(64 * 1024, remaining)); + const buffer = Buffer.allocUnsafe(Math.min(READ_CHUNK_BYTES, remaining)); const { bytesRead: count } = await fd.read(buffer, 0, buffer.length, null); if (count === 0) break; remaining -= count; + let sliceStartedAt = performance.now(); let start = 0; let end: number; while ((end = buffer.indexOf(10, start)) !== -1 && end < count) { + if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) { + await setImmediate(); + sliceStartedAt = performance.now(); + } pieces.push(buffer.subarray(start, end)); length += end - start; const entry = parseRecord(Buffer.concat(pieces, length).toString("utf8")); @@ -65,8 +74,6 @@ async function* locatedRecords( if (entry) yield { entry, location }; start = end + 1; } - // Bound parsing work as well as IO; microtasks alone do not service timers or sockets. - await setImmediate(); if (start < count) { pieces.push(buffer.subarray(start, count)); length += count - start; @@ -96,27 +103,52 @@ function indexedRecords( }, }; async function* readEntries(): AsyncGenerator { + const chunk = Buffer.allocUnsafe(READ_CHUNK_BYTES); + let window: { file: string; offset: number; bytes: Buffer } | undefined; + let sliceStartedAt = performance.now(); for (const location of locations) { - const fd = descriptors.get(location.file)!; - const buffer = Buffer.allocUnsafe(location.length); - let read = 0; - while (read < buffer.length) { - const { bytesRead: count } = await fd.read( - buffer, - read, - buffer.length - read, - location.offset + read, - ); - if (count === 0) - throw new Error(`Claude transcript was truncated during replay: ${location.file}`); - read += count; + if ( + window?.file !== location.file || + location.offset < window.offset || + location.offset + location.length > window.offset + window.bytes.length + ) { + const fd = descriptors.get(location.file)!; + const buffer = location.length > chunk.length ? Buffer.allocUnsafe(location.length) : chunk; + // Read ahead from the next indexed record. The index still owns selection and order, + // including sparse sidechains and workflow records sorted across files. + window = { + file: location.file, + offset: location.offset, + bytes: await readRecordWindow(fd, buffer, location), + }; + sliceStartedAt = performance.now(); } - const entry = parseRecord(buffer.toString("utf8")); + if (performance.now() - sliceStartedAt >= REPLAY_SLICE_MS) { + await setImmediate(); + sliceStartedAt = performance.now(); + } + const start = location.offset - window.offset; + const entry = parseRecord(window.bytes.toString("utf8", start, start + location.length)); if (entry) yield entry; } } } +async function readRecordWindow( + fd: FileHandle, + buffer: Buffer, + location: RecordLocation, +): Promise { + let read = 0; + while (read < location.length) { + const { bytesRead } = await fd.read(buffer, read, buffer.length - read, location.offset + read); + if (bytesRead === 0) + throw new Error(`Claude transcript was truncated during replay: ${location.file}`); + read += bytesRead; + } + return buffer.subarray(0, read); +} + function isToolResult(entry: TranscriptEntry): boolean { return ( Array.isArray(entry.message?.content) &&