Repository navigation
fix(claude): reconcile background commands after cold history reads - #2608
Conversation
|
| Layer / File(s) | Summary |
|---|---|
History checkpoint scanning server/claude-command-history.ts, server/claude-command-history-worker.ts, server/claude-command-history.test.ts |
The worker reads bounded history chunks, validates file versions and checkpoint witnesses, and reports command endings with coverage status. Tests cover parsing, cache invalidation, and partial records. |
Bounded history worker lifecycle server/claude-command-history.ts, server/claude-command-history-worker.fake.ts, server/claude-command-history.test.ts, server/index.ts |
The manager schedules history work through one worker lane, tracks bounded session evidence, and provides reset and hold controls. Tests cover worker lifecycle, queue limits, and scheduling. Server startup and shutdown acquire and release a history hold. |
Subagent history reconciliation server/claude-subagents.ts, server/claude-subagents.test.ts, changelog.d/fix-claude-command-lifecycle.md |
Subagent status merges matching historical endings with transcript results and remains pending while evidence is incomplete. The status tracker watches for history changes. Tests cover cold reads, unresolved commands, and queue holds. |
Task scan history and cancellation server/file-tasks.ts, server/claude-task-scan.ts, server/claude-task-scan.test.ts |
Task scans can wait for history on large transcripts with running or lost shell tasks, then pass evidence to subagent analysis. Shared scans abort when their final waiter cancels. |
Estimated code review effort: 4 (Complex) | ~60 minutes
Severity of issue fixed: Medium
Suggested reviewers: devswha, kilhyeonjun
Merge Risk: 
Moderate · up to 0a3c9
-
When many sessions are tracked, a session denied admission can reconcile background commands slowly on large histories. Queued input can stay held longer than needed. The registration retry should be fixed before merge.
Pre-merge checks: 
3 · 
1 · 
1
-
Failed checks: 1 warning · 1 inconclusiveCheck name Status Explanation Resolution Docstring Coverage Docstring coverage is 29.17% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold. Linked Issues check Directly linked issue #2601is active. Its coding objectives are implemented at head 0a3c933.
Implemented and evidenced:
- Coverage-aware state: server/claude-command-history.ts tracks offset, comple…Provide evidence of a test that exercises failed-chunk retry behavior and shows retries stay bounded. Locate or add it in server/claude-subagents.test.ts or server/claude-command-history.test.ts. Also confirm whether the sampled-witness lim… Passed checks: 3 passed-
Full details: Out of Scope Changes check
-
Explanation
Every changed file ties to the
#2601objectives or to their validation:- server/claude-command-history.ts and server/claude-command-history-worker.ts: core history reconciliation, worker chunks and the physical slot.
- server/claude-subagents.ts: command terminal extraction and historyPending, which feed the task list and pane tracker.
- server/claude-task-scan.ts and its test: shared scan cancellation for the task-list route.
- server/file-tasks.ts: passes history evidence to the claude-tasks file route.
- server/index.ts: holds the history worker during server lifetime. This supports the retained-slot requirement.
- Tests and fake worker: validate the listed regressions. The fake worker is test-only.
- changelog.d entry: documentation of the fix.
No change is shown to be unrelated to the issue.
Full details: Description check
-
Explanation
The description follows the template's two sections, Change and Validation. The Change section explains the problem (cold reads of long Claude sessions miss terminal notices outside the 16 MiB tail, so completed commands appear running), the approach (shared resumable history evidence, cooperative slicing, validation against stored digests), and links issue
#2601. The Validation section lists concrete checks run on a specific head commit with results (354 targeted tests, 10,621 fast-check tests, 0 failed), notes which checks were not run (full integration/browser, SSH, native Windows locally), and reports one browser script timeout that passed on retry. The template's comment asks for the changelog entry in changelog.d/, and the raw summary shows changelog.d/fix-claude-command-lifecycle.md is present, so that requirement is met. The description is dense and uses some internal terms (for example 'independent busy-signal barriers', 'frozen-source') without definitions, and the validation section mixes many numbers that are hard to reproduce from the text alone, but the required information is present.
-
Full details: Docstring Coverage
-
Explanation
Docstring coverage is 29.17% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 24 functions across 10 files. (1 skipped: 1 unsupported.)
Resolution
Write docstrings for the functions missing them to satisfy the coverage threshold.
Full details: Linked Issues check
-
Explanation
Directly linked issue
#2601is active. Its coding objectives are implemented at head 0a3c933.Implemented and evidenced:
- Coverage-aware state: server/claude-command-history.ts tracks offset, complete, uncertain and waiting. Unresolved work stays conservative. Age alone does not drop a launch.
- Version binding: HistoryVersion uses dev:ino, size and mtimeMs. sameHistory() rejects replacement and truncation. Worker checkpoints carry a witness hash and throw "rewritten" on prefix change.
- Incremental work: historyChunk reads bounded chunks. Each chunk requeues behind other sessions, which gives fairness.
- Shared view: claude-subagents, file-tasks and claude-task-scan consume the same HistoryEvidence.
- Notice semantics: the test "shares accepted notice and successful TaskStop semantics" covers accepted notices and removed or quoted records.
- Worker slot: the single physical thread stays charged until close. The test "keeps a blocked physical slot..." covers this. File-pool work proceeds meanwhile.
- Cancellation: a cancelled waiter does not discard the checkpoint.
- Bounds: MAX_SESSIONS 16, MAX_ENDS 5000, queue admission limit.
- Test coverage: cold/warm agreement, partial-record resume, oversized and malformed records, replacement and same-size rewrite, saturation, and a queue/fairness test.
Open points:
- Bounded retries. The issue requires regression coverage for bounded retries. Code bounds retry rate: a failed chunk sets retryAt to now + 2000 ms. The retry count is not capped. No retry-bound test appears in claude-command-history.test.ts. claude-subagents.test.ts was truncated at 16000 bytes, so its retry coverage is unknown.
- Interior rewrites. The PR states that sampled witness checks do not fully validate arbitrary interior rewrites combined with growth. The issue requires rejecting stale evidence after "relevant history changes". Append-only Claude histories are assumed. This limit is disclosed but not covered by the issue's own wording.
- Fairness. The queue test asserts only that the large session has not finished before the small one. It shows weak evidence of fair scheduling.
Resolution
Provide evidence of a test that exercises failed-chunk retry behavior and shows retries stay bounded. Locate or add it in server/claude-subagents.test.ts or server/claude-command-history.test.ts. Also confirm whether the sampled-witness limit on interior rewrites with growth meets the issue's stale-evidence requirement. A reviewer must decide whether the disclosed limit is acceptable for append-only histories.
-
Finishing Touches
-
Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
|
Independent agent review completed before publishing this PR and was repeated after the fixes. The review found four reproducible defects, all resolved before the final frozen-source checks:
The reviewer independently reran the original history, reset/reacquisition, and cancellation reproductions successfully, reviewed the six new regression cases, and reported no remaining blockers. The review also covered the dedicated lane's retained physical capacity, bounded queues, shared task-list/status evidence, conservative queue holds, accepted terminal carriers, and terminal-only parsing. Final focused tests: 146 passed, 0 failed. Final frozen-source The documented generation limit remains: sampled checkpoints do not prove arbitrary unseen interior rewrites combined with growth. The PR does not claim full content-addressed history validation. |
|
Thanks @duytbp, this fixes #2601: the cold task-list scan reports finished commands on this branch and |
… launch Replace the history Worker with a cooperative drain on the main thread (finishAsync slices of about 4 ms), so a crash or hang can no longer respawn or wedge a thread. It starts lazily and leaves nothing scheduled once the last server lets go. A failed read wakes waiting requests and retries with backoff while watched, giving up after five failures; a replaced transcript wakes its waiters, who follow the new one. - An end closes only a launch at or before it: a reused id is a new command, and each transcript keeps the last few ends of an id. - Every byte read is kept as per-span xxHash3 digests and checked again after a change, so a rewrite anywhere in it drops its ends. - A row whose sessionId names another session ends nothing. - History never holds a pane's queue or keeps it from resting; records too large or not JSON are passed over without a validating parse. - The session cap evicts the least recently used unwatched read; a refused watch is asked for again at the next poll. - Tests wait on events instead of fixed sleeps. Fixes #2601
|
Pushed the maintainers' fix round as 8e1ecbe on top of your f2b6948 (fast-forward, your intent kept: a refused watch is asked for again at the next poll).
16 new tests fail on 0a3c933; the three test files pass 135/0 and |
|
Re-review of 8e1ecbe (Codex Terra xhigh; omo still running). Confirmed fixed: an end older than its launch never closes it, the digest catches a rewrite after a completed check, history rows from another session end nothing, history that cannot be fully read no longer holds a pane's queue (#2069), waiters follow a replaced transcript. Still open on this branch (a maintainer lane will push these here, no force push):
Behaviour that is the same on main, noted here and not part of this PR: a row from another session inside the recent 16 MiB window still feeds command reconciliation, and when the parent and a subagent both use an id, the parent's earlier command wins over the subagent's later one. |
|
One remaining P2 on In The synthetic reproduction below completes the initial read, changes an interior task ID from Could the changed-version evidence expose terminal authority only after current-version verification, or explicitly identify the pending snapshot so the main parser cannot treat unverified cached ends as current? I have made no code changes or pushes while your round is in progress. Synthetic reproduction — temporary files onlySave this as import {
appendFileSync, closeSync, mkdirSync, mkdtempSync, openSync,
rmSync, statSync, writeFileSync, writeSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
claudeSubagentState, forgetSubagents, wholeClaudeSubagents,
} from "./server/claude-subagents.ts";
import {
commandHistory, waitCommandHistory,
} from "./server/claude-command-history.ts";
const root = mkdtempSync(join(tmpdir(), "ovis-history-authority-"));
const path = join(root, "synthetic.jsonl");
const dir = join(root, "synthetic", "subagents");
const now = Date.now();
const json = (value: unknown) => `${JSON.stringify(value)}\n`;
mkdirSync(dir, { recursive: true });
try {
const lead = json({ type: "progress", value: "x".repeat(4096) });
const notice = json({
type: "queue-operation", operation: "enqueue",
timestamp: new Date(now - 1000).toISOString(),
content: "<task-notification><task-id>shell</task-id><status>completed</status><summary>Background command finished</summary></task-notification>",
});
const filler = json({ type: "progress", value: "x".repeat(1024) });
writeFileSync(path, lead + notice + filler.repeat(18000));
const limit = statSync(path).size;
writeFileSync(join(dir, "agent-a.meta.json"), JSON.stringify({
agentType: "reviewer", description: "Synthetic task",
requestShape: "background",
}));
writeFileSync(join(dir, "agent-a.jsonl"), json({
type: "user", timestamp: new Date(now - 2000).toISOString(),
message: { content: [{
type: "tool_result", tool_use_id: "bash", content: "running",
}] },
toolUseResult: { backgroundTaskId: "shell" },
}));
wholeClaudeSubagents(path, true, now);
await waitCommandHistory(path, limit);
const status = () => claudeSubagentState(path, true, now)
.tasks.find((task) => task.id === "shell")?.status;
console.log("initial:", status());
const fd = openSync(path, "r+");
try {
writeSync(fd, Buffer.from("other"), 0, 5,
Buffer.byteLength(lead) + notice.indexOf("shell"));
} finally { closeSync(fd); }
appendFileSync(path, json({ type: "progress", value: "appended" }));
const immediate = claudeSubagentState(path, true, now);
const evidence = commandHistory(path, limit, false);
console.log("before digest:", {
status: immediate.tasks.find((task) => task.id === "shell")?.status,
historyPending: immediate.historyPending,
complete: evidence?.complete,
ends: evidence?.ends.map((end) => end.id),
});
await waitCommandHistory(path, statSync(path).size);
console.log("after digest:", status());
} finally {
forgetSubagents();
await new Promise<void>((resolve) => setImmediate(resolve));
rmSync(root, { recursive: true, force: true });
}Observed on Independent validation on this head: the three history/subagent/task-scan suites passed 135/0; |
|
Thanks for the maintainer fix round. Independent re-review confirms the pre-launch/foreign-session cases and awaited prefix-digest validation are corrected; 343 targeted history/status/pending tests passed, including the existing busy-signal guards. The remaining transient cached-authority case matches the synthetic reproduction I posted below. I will hold further code pushes on this branch while your lane addresses that and the equal-timestamp/shutdown findings, then review the updated head. |
…d to its launch - Each history end keeps the line it came from: its offsets and an xxHash3 of it with the newlines on both sides. Unless every byte read was checked at the transcript's current version, an end is told only if its own line reads the same now, re-read before and after a stat. A rewrite that also grew the file no longer shows a live command finished for up to 5 s, and a transcript that only grows keeps its ends without waiting for a check. Evidence handed to the task list's file thread is vouched for again the same way, and at most 4 MiB of lines are re-read at once (past that, unknown: running). - An end closes a launch only when it is strictly after it, or in the same millisecond when both name the same Bash call, and never when they name different calls: an older use's end leaves a reuse running. - A stopped tracker polls nothing, and a history watcher let go of before its queued callback runs is not called, so no read starts after the last server lets go.
|
Thanks again @duytbp for this fix and for bearing with the review rounds. The maintainers pushed one more fix round on top of 8e1ecbe (fast-forward, no force push) for the three points left open in the re-review:
Ten new tests use events, not sleeps. The nine that cover these fixes fail on 8e1ecbe, and mutation checks confirmed that undoing each guard fails a test. The three test files pass 145/0, and |
…ends it TaskStop and KillShell answers name no Bash call, so the tie guard left a command stopped in its launch's own millisecond running forever. In the same transcript the order of its rows decides a tie: an end written after the launch closes it. Across transcripts a tie still closes a launch only when both name the same call.
|
Independent review of I then reviewed the additional
I have made no code changes and am still respecting the maintainer push hold. On exact head |
|
Thanks @duytbp, this fixes #2601: in a long Claude session, background commands whose end notices sit before the parent transcript's last 16 MiB showed as running forever after a cold read (task list and pane count). The cold task-list scan reports them finished on this branch and running on main. How it works now (after the maintainers' rounds on this branch): the older history is read on the main thread in ~4 ms slices through the cooperative step runner (no Worker: total time matched the Worker in our measurements, 200 MB worst case ~1.3 s with no slice over ~5 ms, and there is no thread to crash or hang). Ends found there are matched to the launch they close (an end before its launch never closes it; a same-millisecond tie is decided by row order inside one transcript and needs the same Bash call id across transcripts), each end is trusted only while its own line is unchanged, rows naming another session end nothing, and history that cannot be fully read never holds a pane's queued input or keeps it working (#2069's behaviour is unchanged). Review (omo + Codex Terra xhigh on every round): every HIGH reproduced on this PR's own changes is fixed, with tests that fail on the earlier heads; the last round was checked by Terra (APPROVE) and the omo re-review approved. Known, pre-existing on main, not part of this PR: a row from another session inside the recent 16 MiB window still feeds command reconciliation, and when the parent and a subagent both use an id, the parent's earlier command wins over the subagent's later one. LOW, left as is: past 16 watched sessions a further session falls back to main's behaviour (#2601 unfixed for that pane); only the newest 5000 ends per transcript are kept; the 5-second follow-up check of an idle transcript waits for its next change; a same-size CodeRabbit's check shows skipping on these heads; the merge pass and both reviewers reviewed every head. |
#2616) ## Change This is the history-first step [requested in #2610](#2610 (comment)), cut down to the smallest move after the [review](#2616 (comment)). Only the bulk reads of `server/claude-command-history.ts` change. Everything else is main's code. - **Reverted to main exactly:** `claude-subagents.ts`, `claude-task-scan.ts`, `file-tasks.ts` and their tests. `claude-task-state.ts`, `claude-task-history.ts` and their tests are gone, along with the proof/revision/pending overlay and the task-scan retry. Also reverted: `ci.yml`, `remote-bundles.yml` and `scripts/remote-bundle-smoke.ts`. The remote bundle copies `server/` whole, so it carries the new file without them. - **Kept as on main:** the synchronous API (`historyVersion`, `sameHistory`, `commandHistory`, `evidence`, `vouchedEnds`, `waitCommandHistory` and the rest). `vouchedEnds` still rechecks known ends against a grown transcript synchronously, so an ordinary append keeps an ended command ended and #2069 holds. #2620's parts are main's code too, merged in unchanged: `evidence`'s 3 s rule and its start over on a rewritten line, `since`, the shared recheck per tick, and `vouchLines`' coalesced, budgeted re-reads. They stay synchronous on `readSync`, on the request path. - **Changed:** the drain's `scan` and `check` read through `transcriptReader` (`server/transcript-reader.ts`) instead of calling `readSync` themselves. On network filesystems and on macOS and Windows, the reader reads through the thread pool. On local Linux filesystems it still reads synchronously inside the slice (below). The drain still runs one slice at a time, with a `setImmediate` between slices, except when a slice is stuck (below). - **Local filesystems** (the round after the review of c5103d0): a call through the thread pool costs more CPU than a read the page cache answers: a wake of the pool thread, a copy on another core and a wake of the event loop. So on Linux, a transcript whose directory is on ext2/3/4, btrfs, xfs, tmpfs, zfs, f2fs or bcachefs (`statfs` type, `LOCAL`) is opened, statted, read and closed on the event loop, inside the same lease, slices and turns. - FUSE (SSHFS, virtiofs), NFS, SMB, 9p (WSL's Windows drives), overlayfs and any type not listed keep the thread pool. So do macOS and Windows. - The `statfs` itself is async, since it can block on a hung NFS mount. It is cached for 60 s per directory, and a lease that has to look it up opens the transcript at the same time, so a network filesystem pays no extra round trips before its open. - Any call on the event loop that takes over 2 ms is taken as answered by the disk, not the page cache. The rest of that lease and that transcript's leases for the next second then go through the thread pool, with the read ahead. A 1 MiB read from the page cache takes about 0.2 ms here. The open and the close on the event loop are timed the same way, and a call that throws counts as slow too. - The lookup also takes the directory's device (`stat` beside the `statfs`), and the lease's first stat compares the transcript's own device with it before any read. A transcript on another device, such as a file bind-mounted from NFS or FUSE into a local directory, goes through the thread pool, and its later leases do too for 60 s. - The reader tells the drain whether the event loop ran while the lease's last call waited (`waited()`). A slice reading on the event loop counts from the start of its step and stops at its 4 ms, as main's does; reads through the thread pool keep the rules above. - No read ahead starts while reads are on the event loop. Every byte taken in is still read between two equal stats, from `fstatSync` on the same descriptor. Cancellation and the deadline are checked before and after every call. - **Slices:** - A slice ends after 4 ms of wall time from its start, as on main, so a large session on slow storage hands over after each read. - Parsing a chunk that arrives after the slice is up through the thread pool stops 4 ms after its bytes arrive, not 4 ms after the slice started. On main the read is inside the slice. On storage where one 1 MiB read takes longer than that (SSHFS), the parse stops after a single record and the next slice reads the same chunk again from there. A chunk read on the event loop gets no such extension, since the loop had no turn while it was read. A slice on the event loop counts from the start of its step, as main's does, so its open and first stats come out of its 4 ms. - When nobody else is waiting, the session keeps its transcript open into the next slice. Opening a transcript and checking it is the path it was let in for costs several round trips on remote storage. It lets go at the end of the slice in which nobody watches or waits for the history any more, another session that can have a slice is queued, another reader waits for the reader, the read starts over, or a watcher has a new end to hear. It also lets go once half the read's 10 s deadline has passed, counted from when the read was asked for. A request for the same session does not end it. In production both readers keep it: the subagent tracker watches the history while it needs it (`watchCommandHistory`), and the task scan waits for it (`waitCommandHistory`). - A turn inside a held lease waits for two `setImmediate`s, not one. An immediate set while an I/O callback runs comes before the timers already due. With one, a slice that needs no read (the rest of a window, below) could follow the last slice before them: 44–51 event-loop stalls over 8 ms per dense read in profiling, against 0–1 with two. - **Read-ahead and reuse** (kept, re omo M1): they carry the thread-pool path that network filesystems take, which the fast path doesn't touch. Over SSHFS, without them the 276 MB sparse transcript took 9.55 s and the 95 MB dense one 9.2 s; with them, 5.1–5.6 s and 2.7–2.9 s. - A lease can start one read ahead into a second buffer, beside the operation it awaits. After a window is read, the next window, from that window's last whole line, is read while the stat after it is on its way and the window is scanned. A `window()` that asks for those bytes gets them with no second read. One that asks for other bytes lets the read ahead settle first. A lease has at most two native operations in flight, so the reader has at most four. - The check reads the next span ahead the same way, while it hashes the current one. - No read ahead starts when nobody listens, since the read then ends with that slice and a read ahead left over would hold up the lease's close. None starts when the window already reached the end, since there is nothing past it to read yet. - A slice that ends inside a window leaves that window's whole lines for the next slice. The next slice takes them in with no read and no stat, as long as no stat came since the one after they were read. On the dense transcript this cuts the reads from about three times the file to once. - Every byte taken in is still bracketed by two equal stats: a read ahead starts after a stat equal to `checked`, and reused bytes come from a read that did. A rewrite is still caught by the next stat or check. - **A stuck transcript holds up only its own history** (the review's HIGH): - A slice is taken as stuck when it has neither ended nor taken a turn for 50 ms (`STALL_MS`) while another session that can have a slice waits. The drain leaves it to end by itself and starts the next session's slice beside it. - Turns are counted per session. A held lease that takes its turns is reading, not stuck, and lets go at the end of its next turn, so healthy storage still runs one slice at a time. - At most the reader's capacity (2) of slices run at once, one per transcript. A held lease lets go only for a session that can have a slice, not for one whose transcript a stuck slice still reads. - A healthy lease's open and its checks on remote storage, several round trips, can outlast 50 ms too. The next slice then starts beside it. - **Cancel on the last release** (the review's first MEDIUM): `resetCommandHistory()` aborts the reads of every slice begun before it. The slice gives up at once, and the drain ends. What it cannot do: the native operation already started keeps its reader lease until it settles, since a syscall cannot be interrupted, and a new read of that transcript waits for that lease. `commandHistorySettled()` resolves once no slice runs and none waits to start. `commandHistorySize().draining` counts the slices left running too. - **Guards the async reads need:** - A stat is compared with the transcript as it was known when the stat was asked for. A stat older than one a status poll took in between is no news. A transcript cut short in place, even back to the size a poll saw, is read anew. - A chunk's offset, ends and checked range are published together, after the stat that follows the read. A request in between sees the read as it was. - A read that gives up on that stat (deadline or busy) keeps the chunks it already read and checked. - A session asked for again while its slice waits is queued once. - If the path names another file by the time the reader admits it, the read starts anew, as main's stat would. - Since #2620, a request that finds an end's line rewritten starts the history over (`evidence`) while a slice may be waiting for the disk. The slice drops the window or check it was reading then and reads again from the start. Without this, it took in a window read from the old position as the transcript's first bytes, until the next request or check corrected it. - **Busy reads:** a `TranscriptBusyError` (reader queue full, or a read past its 10 s deadline) backs off without using the failure budget (CodeRabbit thread on `claude-command-history.ts:98`). Other errors count as on main. - **Reader:** one shared in-process reader, for this history now and the image path later. It uses plain stats, the same form `lstatSync` gives, so its versions compare with `historyVersion`. `window()` reads into one of two 1 MiB buffers per lease, taken from a pool of the buffers of leases that ended. A buffer goes back to the pool only once every native read into it has settled, a read ahead included. The deadline timer does not keep the process alive. ## Known limits Not fixed here; each is written in the code's comments: - A local disk that stops answering inside a call on the event loop blocks the loop, as main's `readSync` does. The fallback notices a slow call only once it returns. Network filesystems can't hit this, since they never take the fast path. - A network file bind-mounted into a local directory is opened and statted once on the event loop before its device gives it away, once per 60 s for that path. The open is timed, so a slow one also sends it to the thread pool. - macOS and Windows have no fast path, so their local reads keep the thread pool's CPU cost. On macOS, `statfs` gives no fixed type for APFS; comparing the transcript directory's type with that of `/` should work, but I haven't tried it on a Mac, so it's left for a follow-up. - A native operation that never settles keeps its lease. Two of them, on two paths, keep both of the reader's leases, and every later read waits out its 10 s deadline. A read ahead counts as one. - A cancelled lease keeps its path until its operations settle. A new read of that transcript waits behind it. - Transcript identities use number stats (`dev:ino`, as `lstatSync` gives them). On a filesystem whose numbers pass 2^53, two files may share an identity. - A transcript whose reads keep running into the 10 s limit is tried again every second while it is watched, with no longer backoff. A busy reader is no failure of the transcript. ## Tests Every assertion from main's `claude-command-history.test.ts` is unchanged: against main, that file changes only its imports. At the review's request (the second MEDIUM), the assertions on lease and turn counts in tests this PR added earlier now assert outcomes: | Test | Asserted | Asserts now | |---|---|---| | keeps a transcript open across turns while no other session waits | 1 lease | each open costs 100 ms of a controlled clock, and the read took less than its reads plus two opens | | lets go of a transcript it keeps open at the end of the turn another session is asked for in | small answered at read 3; 2 leases | small answered with its end while the large one still had reads to go | | lets go of a transcript it keeps open well before the read's deadline | 2 leases | the clock moves 5 s at read 2 and 5 s more at read 4; the read still comes back complete in one wait (a lease held past half its deadline would run out of time and give up) | | gives each turn of a transcript it keeps open a slice of its own | fewer `setImmediate` calls than reads / 2 | each turn's held time on a controlled clock: at most 5 ms, and every turn but the last at least 2 ms | | reads on in the same lease when the session it reads is asked for again | 1 lease at each read | at its last read, the clock shows its reads plus exactly one open | | reads one slice for a request nobody watches or waits for | polled up to 1000 event-loop turns; 1 read, 1 lease | waits on `commandHistorySettled()`; read on some way but not through, nothing left queued, draining or timed | | reads on in one lease for a tracker's watch after it hears the first end | 2 leases | the watcher hears the first end before the read is through | | lets go of a transcript it keeps open at the end of the turn it started over in | heard before read 8 | heard while the restarted read is not through | | counts the time it keeps a transcript open from when its read was asked for | 2 leases | the clock moves 6 s before the lease opens and 5 s more at read 3; the read still comes back complete | Merging main with #2620 changed two of this PR's own tests (none of #2620's, none of main's), because of #2620's rules: - "lets go of a transcript it keeps open at the end of the turn it started over in" rewrote the first record. Under #2620 the next request's `evidence` finds that rewrite first and starts over before any slice, so the turn-break went untested. It now rewrites the record after the end's line, so only a check finds it, and its `ends` assertion is `["a"]`, not `["b"]`. Dropping `|| restarted` from the turn-break still fails it. - "keeps the chunks it read and checked when a read gives up on its stat after a chunk" now sets its file's mtime a minute back. Read within 3 s of the write, it got #2620's shared recheck, 5 more windows. No assertion changed. Every other assertion of those tests, and of every other test, is unchanged. This round also moves the tests off real time (Terra LOW): - The reader's event-loop tests run on a clock only they move (`stillClock()`), so a preempted read can't cross the 2 ms bar. 48 parallel runs of `transcript-reader.test.ts` beside 64 CPU spinners: 42 of 48 passed on 93f74fb, 48 of 48 now (also 48 of 48 with 16 spinners). - The test helpers that stand in for slow or held storage (`slowReads`, `holdWindows`) now say their reads waited off the event loop, and the one that answers at once says they didn't, so the tests behave the same whatever filesystem the host's `/tmp` is on. - "reads another transcript while one transcript's read is stuck on its disk" and "starts no more slices beside stuck ones than the reader has room for" used a real 150 ms wait. They now move a fake clock past the 50 ms stall instead. - The two reader tests that spun on `Date.now()` past a deadline now set the system time inside the callback, or while the close is pending. - "reads on by whole chunks when every read outlasts a slice" did not catch its fix: with the parse stop counted from the slice start it still passed, at c5103d0 too, because reusing a window's rest kept its read count in bounds. It now runs on a clock that moves only with the reads, and also asserts that the ends known each time the event loop runs grow by more than 100 at a time (a chunk holds about 450), not a record at a time. With the fix undone it fails. - "reads no other session beside a transcript it keeps open that takes its turns, however long it reads" no longer intercepts every 50 ms timer. The small session now asks between two turns of the large one, on a fake clock. With the old timing it passed with its fix undone, at c5103d0 too; it fails now. Each test below fails with its fix undone; I undid each fix and ran the files: | Test | Fails when | |---|---| | backs off a read the reader is too busy for… | a busy read counts as a failure | | keeps the chunks it read and checked when a read gives up on its stat… | offset and ends are published before the stat | | queues a session asked for while its slice reads only once | the requeue guard is removed | | keeps what it read when a slice's stat is older than one a poll took… | an older stat discards the read | | starts over on a transcript cut short in place while a slice reads it | a stat matching the poll's version is accepted though the transcript shrank | | reads on by whole chunks when every read outlasts a slice | the parse stop counts from the slice start | | lets a small session have its turn after each slow read of a large one | the slice counts only CPU time, or the queue is not checked | | never keeps the process alive for a read's deadline alone | the deadline timer is not unref'd | | keeps a transcript open across turns while no other session waits | each slice ends the lease | | lets go of a transcript it keeps open at the end of the turn another session is asked for in | the queue is not checked | | lets go of a transcript it keeps open at the end of the turn another reader waits for it in | the reader's waiting count is not checked | | lets go of a transcript it keeps open at the end of a turn that told a watcher of an end | a new end for a watcher is not checked, or a waiter counts as a watcher | | lets go of a transcript it keeps open well before the read's deadline | the half-deadline is not checked | | reads on in the same lease when the session it reads is asked for again | any queued session ends the lease, or each slice ends it | | gives each turn of a transcript it keeps open a slice of its own | the slice is not renewed after a turn, or there is no turn | | reads one slice for a request nobody watches or waits for | a read with no listener is kept open | | reads on in one lease for a tracker's watch after it hears the first end | a new end for a watcher does not end the lease | | lets go of a transcript it keeps open at the end of the turn it started over in | a start over does not end the lease | | counts the time it keeps a transcript open from when its read was asked for | the half-deadline counts from when the lease opened, or is not checked | | takes in the rest of a window a slice ended in without reading it again | the rest of a window is read again | | reads another transcript while one transcript's read is stuck on its disk | the drain waits for a stuck slice | | reads no other session beside a transcript it keeps open that takes its turns, however long it reads | a turn does not count as progress | | starts no more slices beside stuck ones than the reader has room for | both capacity checks are removed, the drain's and `next()`'s (either alone holds the bound) | | gives up a read stuck in flight once the last server lets go | a reset does not abort the slice's read | | reads ahead while the lease awaits a stat, and hands the bytes to the window that asks for them | the buffers are not swapped, so the next read ahead overwrites the window just returned | | lets a read ahead settle before a window that asks for other bytes | that window does not wait for the read ahead | | closes a lease and gives its buffers to another only once a read ahead nobody asked for settled | the lease does not track its read ahead | | ends a cancelled lease's read ahead without an unhandled rejection | the lease does not track its read ahead | | drops a window read across a start over that a request made while the window waited for the disk | the slice takes in a window read across a start over | | reader: reads a transcript on a local filesystem on the event loop, and one on any other through the thread pool (btrfs, ext4, tmpfs; NFS, FUSE, 9p) | every filesystem counts as local, or there is no fast path | | reader: reads through the thread pool for a second once a read on the event loop was slow, then tries the event loop again | a slow call doesn't switch the lease, or the transcript's second isn't checked | | reader: gives up a read on the event loop between windows once cancelled | the cancel checks around a sync call are removed | | reader: opens a transcript while its filesystem is looked up, and reads it on the event loop once that says local | the open waits for the lookup, or the lease stays on the thread pool after it | | reads another transcript while one on a network filesystem is stuck in its native read | every filesystem counts as local, so the stuck read blocks the event loop; or the drain waits for a stuck slice | | holds the event loop no longer than a slice and the call that ended it when it reads on the event loop | a window read on the event loop after the slice's end gets a slice of its own, or the first slice counts from when the work starts instead of from the step's start, or the reader says every call waited | | reader: reads through the thread pool for a second once an open on the event loop was slow or threw | a slow open or one that throws isn't counted, or the lease whose open was slow reads on the event loop | | reader: reads through the thread pool for a second once a close on the event loop was slow or threw | a slow close or one that throws isn't counted | | reader: reads a transcript on another device than its local directory through the thread pool | there is no device comparison, or a mismatch doesn't mark the path | | reader: reads through the thread pool for a second once a read on the event loop threw | a call that throws isn't counted | | reader: tells the work whether the event loop ran while the lease waited | a queued lease counts as not having waited, a call on the event loop doesn't clear it, or a call through the thread pool doesn't set it | Three tests have no fix to undo: - "lets the event loop run while a slice waits for the disk" checks that the drain yields while a read is held. Main's sync read cannot be held. - "starts over on a transcript rewritten and grown while it reads a window ahead" guards the read-ahead against a rewrite. Main reads no window ahead, and passes it too. - Removing the read ahead's own `.catch` does not fail "ends a cancelled lease's read ahead…": the lease's operation bookkeeping also handles that rejection. Four lines have no unit test: - The 2 ms bar's value. The tests inject slow calls far past it; where it sits between a page-cache read (about 0.2 ms per MiB) and a cold NVMe read (1.9 ms typical) is a measurement, below. - A chunk that arrives within a slice is parsed until that slice ends, not for 4 ms from its arrival. It bounds event-loop delay, and none of the tests' clocks shows a difference. Without it, event-loop p95 on SSHFS rose to 14 ms in the profiling run. - The second immediate of a turn. It orders the turn after the timers already due, which no test clock shows. Profiling measured it (see Slices). - A check pass whose check a start over cleared returns at once. Without it, the pass ends on the emptied spans and marks offset 0 checked, which the next scan's start overwrites before any end can be told, so no test can see it. It is there so check and scan treat a start over alike. One of #2620's tests sees less here: "shares one recheck within a version's tick among the requests that wait…" counts `fs.readSync`, which on this branch is only `vouchLines`; the drain reads through the reader. Its assertion holds. A probe wrapping the reader's `window()` around the same five waits found no drain reads, as on main. The inherited same-millisecond matching issue is out of scope. Possible follow-up, not in this PR: `waitCommandHistory` and `commandHistory` still call `lstatSync` through `historyVersion`, as on main. On SSHFS that holds the event loop about 100 ms per call. #2620's `vouchLines` is the same kind of read: synchronous, up to 4 MiB per call, run whenever the history is not vouched, which since #2620 includes any transcript checked within 3 s of its mtime. Moving either off the request path is a change to main's synchronous API. ## Validation - Toolchain: Bun 1.4.2, Node 22.23.4, herdr 0.9.3. The head is 7edf4df: c5103d0 (which merged main 05c9133) plus the test rework, the local-filesystem fast path, the changelog, opening during the filesystem lookup, the slice clock on the event loop, two commits strengthening one test, the reader tests' clock, and timing the open and close with the device check. The full benchmark below ran on b9b2acd; a local run on 7edf4df is after it. - `bun run check fast` on 7edf4df: 10755 passed, 0 failed, 41 skipped in 663 files; workflow syntax, generated types and themes, typecheck and build all ok. It includes #2608's tests (`claude-subagents`, `claude-task-scan`) and `file-view` and `file-pool`, which use `file-tasks.ts`. - `server/transcript-reader.test.ts` and `server/claude-command-history.test.ts`: 82 passed, 0 failed. The history tests, 8 copies at once, 3 rounds: 24 of 24 passed. - `GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=core.excludesFile GIT_CONFIG_VALUE_0=/dev/null bun run check run bun test server/claude-session.contract.test.ts server/api.contract.test.ts`: 207 passed, 0 failed, on an isolated herdr 0.9.3. - `git diff upstream/main -- server/claude-subagents.ts server/claude-task-scan.ts server/file-tasks.ts server/claude-subagents.test.ts server/claude-task-scan.test.ts .github scripts` is empty against 05c9133. - The review's cases ran as synthetic scripts against main and c5103d0 with the same output on both (listed in the earlier round). The review's repro, a held read of A while B is asked for, is the test "reads another transcript while one transcript's read is stuck on its disk", and its network-filesystem twin covers the stuck native read. - Measured with the same synthetic benchmark as before (gist below): b9b2acd against main 05c9133, interleaved, median [min–max]. The host also runs a VM using about 8.5 cores, so load was 9–13 and every sample is flagged; treat local differences under ~20% as noise, and CPU as the steadier figure. - Local disk, 5 runs each. Ratios are this branch over main per interleaved pair, so <1 is faster: | | main | this branch | ratio | |---|---|---|---| | 276 MB sparse, page cache warm | 65 ms [57–70] | 74 ms [66–79] | 1.15 [0.96–1.34] | | 276 MB sparse, cold | 158 ms [154–189] | 164 ms [146–203] | 1.02 [0.85–1.28] | | 95 MB dense, warm | 1027 ms [961–1166] | 949 ms [915–1124] | 0.94 [0.89–0.96] | | 95 MB dense, cold | 854 ms [759–994] | 819 ms [735–854] | 0.93 [0.86–1.03] | | CPU (user + sys), sparse warm | 64 ms | 90 ms | 1.25 [1.06–1.40] | | CPU, sparse cold / dense warm | 157 / 1172 ms | 190 / 1104 ms | 1.22 / 0.96 | | longest event-loop gap, sparse warm / dense warm | 4.7 / 7.3 ms | 4.7 / 7.3 ms | | | other requests during the sparse read, p95 | 4.1 ms | 4.1 ms | | | 1 MB session, warm / cold | 5 / 5 ms | 8 / 7 ms | 1.60 / 1.63 | Sparse warm CPU is the figure the last review blocked on: 78 ms on main against 165 on c5103d0 in your run. Three full runs across this round's commits on this host put it at 1.16, 1.10 and 1.25 times main's (fd22a07, b994f29, b9b2acd), against 1.48 for c5103d0 in the same harness here. The branch's own sparse warm CPU held at 77–93 ms across those runs; main's moved between 64 and 88, which is most of the spread in the ratio. What remains is mostly JIT time for the extra code paths: in a profile of the second read in one process, main-thread work matched main's within 2 ms, and the pool threads did none. Sparse warm read time overlaps main's in every run (1.02–1.15). Cold sparse costs ~20% more CPU than main: on a cold read the first slow call (over 2 ms) moves the rest of the lease to the thread pool, which is what keeps a local disk that stalls from blocking the event loop for more than one call. The longest event-loop gap now matches main's. On the fast path, slices take only what fits in their 4 ms, as main's do. Loop-gap max for the 1 MB session reads 4.6–4.8 ms against main's ~1 ms, but that is how the harness samples, not a longer block. The sampler records a gap only when its 2 ms tick fires before the read resolves, so a read that ends on sync work never has its last gap counted. Main's small read usually ends inside its first gap. One main run that got a second tick recorded 5.4 ms. A probe that also counts the last gap found the longest block at 4.3–5.1 ms on main and 3.3–5.4 ms here: parsing the 1 MiB window inside one slice. - Local disk on 7edf4df against main 05c9133, 5 runs each: sparse warm 61 → 67 ms (ratio 1.15 [1.04–1.62]), CPU ratio 1.22 [1.13–1.68]; dense warm 0.95, dense cold 0.86; longest event-loop gap, sparse warm 4.6 / 4.7 ms and dense warm 6.6 / 6.4 ms. Sparse cold CPU came out 1.39 [1.07–1.76] in this run (1.22 on b9b2acd); a cache miss now also stats the directory beside its `statfs`, and every bench read is a fresh process, so each pays it once. I haven't separated that from load; your spot-check on a quiet host will show it better. - Over SSHFS: sshfs 3.7.6 with `cache=no,direct_io,no_readahead`, 14 ms round trip, 3 runs each. These are unchanged from c5103d0; network filesystems never take the fast path. An interleaved SSHFS run of c5103d0 against b9b2acd's parent gave ratios of 1.00 and 1.02 for the small-session rows. | | main | this branch | |---|---|---| | 276 MB sparse, total | 61.6 s [61.5–61.7] | 5.18 s [5.14–5.20] | | other requests during it, p95 / max | 155 / 275–345 ms | 1.0–1.8 / 101–103 ms | | longest event-loop stall | 177–247 ms | 101–102 ms | | 95 MB dense, total | not done after 300 s, 3 of 3 (1.0 MB read) | 2.58 s [2.54–2.71] | | other requests during it, p95 / max | 153 / 274–276 ms | 33–42 / 100–102 ms | | 1 MB session alone | 7.75 s | 0.49 s | | 1 MB session while the 276 MB one reads | 15.3 s | 0.47 s | | 1 MB session while the 95 MB one reads | 15.4 s | 0.48 s | | CPU, sparse (user + sys) | 0.36 s | 0.31 s | Main sets the slice's 4 ms clock before its blocking read, and one 1 MiB read over SSHFS takes ~110 ms, so each slice parses about one record and the next slice reads the same chunk again. This branch's single ~100 ms stall per read fits one round trip of the synchronous `lstatSync` in `historyVersion` (see the follow-up). - System calls on the transcript, page cache warm, under strace: | | main | this branch | |---|---|---| | dense: reads / MiB read / opens | 668 / 422.7 / 341 | 91 / 90.6 / 2 | | sparse: reads / fstats / opens | 286 / 573 / 35 | 282 / 283 / 2 | Main with #2620 reads the dense transcript about 4.6 times over; this branch reads it once. - A small session's extra ~3 ms is once per process: starting Bun's thread pool for the first `statfs` and open of a directory, and the first run of the reader's code paths. After that, on a local filesystem, a read makes no thread-pool round trip, and compiled it is within noise of main's (2.3 against 2.1 ms in the profile). - Not run locally: the integration and browser suites, SSH, native Windows and macOS. Upstream CI covers them. - The benchmark is a standalone harness anyone can run: https://gist.github.com/duytbp/470e90421331b31ccd953de200d6aae0 (synthetic transcripts only; `bench.sh <rev>` for local, `MODES=sshfs` adds the SSHFS lab, which needs Linux and sudo). - Optional follow-up for the owner: adding `server/transcript-reader.test.ts` and `server/claude-command-history.test.ts` to the Native Windows and remote Windows test lists. That is a workflow change, so it is left out until approved. All fixtures are synthetic files in temporary directories. No live herdr session or real transcript was used. --------- Co-authored-by: devswha <[email protected]>
## Change This is the image step of the shared-reader direction agreed in this PR's comments, after #2616 (the reader, with command history on it) and #2627 (the picture index) merged. It replaces this PR's earlier image Worker design (8034623, 645b38c): there is no application Worker. Claude conversation images are read through the same in-process `TranscriptReader` that #2616 introduced. The branch's diff against main is only this step. The old Worker commits stay in its history under a merge commit whose tree is this step on current main, so nothing was force-pushed. **Commits** - `feat(claude): give the transcript reader a whole stat and a followed path` (`server/transcript-reader.ts` and its test): - `TranscriptFile.stats()`: the pinned handle's whole `fstat`. The image lookup keys on the change time and the numeric inode (`sameImageFile`, the stream id, #2627's version key), which `TranscriptVersion` does not carry. - `read(path, work, { follow: true })`: the admission check and `pathVersion()` use `stat` (the file a link names) instead of `lstat`. Main's image path opens and `statSync`s the path, so it serves a transcript named by a symlink and notices a link moved to another file during a lookup; `follow` keeps both. History's default is unchanged and still refuses a linked transcript. - `fix(conversation): read Claude images through the shared transcript reader` (`server/conversation.ts`, `server/codex-images.ts`, `server/claude-images.test.ts`, a changelog fragment). - Three commits that make #2627's backward call search cheaper: two on a network mount (below), and one that stops searching a long line by first joining it onto the text before it (the regex then copied up to 1 MiB per line; found when the second commit made it happen on every line, and also paid on main for any line longer than a window). - Test commits: Windows skips, and a picture fetch in the remote bundle smoke, as you asked. **What changes for images** - `transcriptImageAsync` takes a lease on the transcript from `transcriptReader`, and every read and stat of the lookup goes through it: async positional reads of at most 1 MiB of the file the lease pinned, plus its `fstat`/path checks. Nothing in the lookup reads the disk on the event loop unless #2616's local fast path decides it may. - **#2627's logic is unchanged:** the index, `unread`/`loose`/`blind`, the bytes check with its vouching and `fineTimes`, the mark cap, and the backward and forward call searches. Where a step reads bytes it now `yield*`s a step that waits for the lease's read (`streamBytes`). With no lease, `streamBytes` is `readStream`, so `transcriptImage` (sync) and history pages are untouched. `finishAsync` awaits a read and throws a failed one back into the steps, so their cleanup (taking back a published boundary) runs as before. `finish` refuses an asynchronous step. - A read of one window comes back in the lease's own buffer, valid until its next read. Every caller takes it in before reading again: the scan digests and concatenates it, the searches decode it, the shape reader copies what it keeps, and the back-walk copies the line head it carries forward. #2627 already copies everything it keeps. - **Lookups of one transcript take turns** (`imageTurn`). The reader leases a path to one read at a time anyway. Queuing them before it means a page of pictures holds one place in its bounded queue, so it is never refused for room, and every picture after the first finds the boundary the first one kept. A side effect: a page in a fresh process no longer runs one boundary scan per picture (#2627's open note). It is now 10× faster: 6.0 s → 0.61 s on #2627's big fixture. - **When a lookup began** (`began`/`wall`, which #2627's vouching compares) is taken when the lookup is asked for, before its turn, and the version key still comes from the lease's stat. #2627's page lookups ran side by side and shared a check begun after each one's stat. Here they take turns, so stamping at the turn would make every picture of a page read the index's bytes again (24 reads instead of one after an append). Stamped at the request, a lookup still takes a verdict only from a check begun after it was asked for, so the answer reflects the file at a moment between request and response, as with #2627's concurrent lookups. The comment at the stamp says so. A mutation that stamps after the stat fails the page-after-append test (75.5 MB read against its bound of 29.4 MB). - **The current-file check** compares the pinned `fstat` (with ctime) and the path's `pathVersion` (dev:ino, size, mtime). If the path names the same inode, its stat is that inode's, which the `fstat` just compared with ctime. A ctime-only change between the two stats lands after the read's last byte, so a later request judges it, as with a change just after main's `statSync`. - The boundary is published only if what is kept is still unchanged after the file check answers, since that check now waits for the disk. - No deadline and no cancellation were added: like main, an image request waits for its disk. **Backward call search on a network mount.** #2627 finds the start of the line a backward window cuts by reading back 64 KiB at a time, and then reads that window again. On a mount with no read-ahead, each probe is a round trip. On the SSHFS lab, a warm tool picture whose call is 18 MiB back over 1 MiB lines takes 108 reads (90 of them ≤ 64 KiB) on main, against 42 before #2627. The two commits: - `find a long line's start in growing pieces`: probes grow 64 KiB → 1 MiB, and the next window grows from what the last one covered; - `read a tool call's window back from what finding its line's start read`: the window reuses the probe's bytes. That makes 45 reads (23 small) for the same bytes. A new cost test bounds it (114 reads on the step without them, bound 60). The rest of the gap to pre-#2627 is #2627's coarse-time guard: SFTP reports whole seconds, so `fineTimes` is false and each warm lookup reads the index's bytes again. I left that as it is. ## Acceptance table v4 image HTTP benchmark: synthetic fixtures and PNGs only, the HTTP route through the real access gate, herdr RPCs and native PID session discovery, `/api/health` pinged every 10 ms. Main is 77f8902. Elapsed is the median [min–max] in ms; health is the median of per-case max, then p95. The host runs VMs (load 7–14), so treat differences under ~15% as noise. | | main 77f8902 | this PR (222b40a; see below) | |---|---|---| | Local, first image, 18 MiB (n=7) | 161 [65–266] | 181 [173–288] | | Local, first image, 125 MiB (n=7) | 394 [265–552] | 433 [313–589] | | Local, warm image, 18 MiB (n=49) | 19.2 [14.0–146] | 18.2 [11.0–131] | | Local, warm image, 125 MiB (n=49) | 90.0 [65–808] | 85.2 [61–416] | | Local, page of 24, warm, 18 / 125 MiB (n=7) | 563 / 1846 | 577 / 2044 | | Local, page of 24, cold, 18 / 125 MiB (n=7) | 657 / 1971 | 638 / 2278 | | Local, pages: statuses | 672 × 200, 0 × 503 | 672 × 200, 0 × 503 | | Append during a lookup: served (18 / 125 MiB) | 54/54, 29/29 | 42/42, 28/28 | | `/clear` during a lookup: hidden | 53/53, 29/29 | 30/30, 28/28 | | Rewind during a lookup: hidden | 51/51, 30/30 | 35/35, 29/29 | | Race trials (only changes landing in flight counted) | 0 × 404 | 0 × 404 | | SSHFS 18 MiB, first: elapsed, health max / p95 (n=7) | 6735, 1792 / 1463 | 5588, 1817 / 1549 | | SSHFS 18 MiB, warm (n=21 / 14) | 3516, 398 / 249 | 2224, 186 / 117 | | SSHFS 125 MiB, first (n=3) | 20213, 1929 / 1602 | 18149, 1825 / 1495 | | SSHFS 125 MiB, warm (n=6) | 12704, 487 / 208 | 9687, 473 / 192 | | SSHFS 18 MiB, page of 24, warm | 64 s, 24 × 200 twice, reset at the 60 s request budget once; health max 8.2–9.4 s | 24 × 200 in 37.7 s; health max 556 ms | | #2608 history case (image + cold history), 18 / 125 MiB | 200 exact, overlap seen | 200 exact, overlap seen | - **The table's PR column** is 222b40a, before the last perf commit (c220c27). That commit removes CPU copies only and reads the same bytes. In process, a warm far-call lookup on the 125 MiB fixture takes 66.6 [61.5–81.8] ms on c220c27, against 71.5 [59.4–84.2] on the step alone and 85.4 [76.0–112.1] on 222b40a (9 interleaved processes, host at load 14). On the final server code (c220c27/003b02db), 15 interleaved processes give 52.7 [46.2–62.4] ms against 59.2 [46.9–75.3] on the step alone. The SSHFS rerun on the final code, interleaved with main (18 MiB): warm 2321 [2070–2976] against 3524 [3178–3993] ms (health max 187 against 404 ms); first 5627 against 6818 ms; page of 24 37.4 s, 24 × 200, health max 558 ms, against main's 64.0 s, 24 × 200, health max 9.4 s. - **Local:** first and warm times overlap main's. - **SSHFS page of 24:** this is the row the turns change most. Without the two back-walk commits, the step alone took about 3.3 s per warm far-call picture over the lab mount, and the tail of a page went past the 60 s request budget in 2 of 2 runs. Main sits at that edge too (64 s, reset once in 3 runs). With them, the page takes 37.7 s, and health stays under 0.6 s instead of 8–9 s. - **The SSHFS stall on other requests:** in process, a lookup over the mount now holds the event loop for at most 9 ms, against 380–825 ms on main. In the harness, `/api/health` still peaks at about 1.8 s on the *first* picture, the same on main, pre-#2627 main and this PR. Traced over the mount, that time isn't the image path. Two pollers that start when a pane is first looked at read synchronously: `claude-subagents.ts` `scanParent` reads the last 16 MiB (`readLines`, about 730 ms), and `session-plan-reader.ts` `planState` reads the whole transcript (about 700 ms). They're outside this step. I can move `readLines` onto the shared reader as a follow-up PR if you want it. - **#2608:** the harness's history readiness precondition tripped twice when 18 and 125 MiB ran in one invocation, once on main and once on this PR, before any image request. Run alone, 125 MiB passed 6/6 on both. **#2627's timing rows**, in process, main 77f8902 against the step (7 interleaved runs): the warm lookups stay at 12–24 ms on both, so the speedup is intact. A fresh-process 24-picture page is 10× faster (big 6001 → 608 ms, clear 7249 → 701 ms), as above. The rest is within noise. ## Validation - Toolchain: Bun 1.4.2. - `bun run check fast` on the final head (2 workers, frozen tree): `unit: 10871 pass, 0 fail, 41 skip`; typecheck, build and generated checks ok. - `server/claude-images.test.ts`, `server/transcript-reader.test.ts`, `server/claude-command-history*.test.ts`, `server/claude-subagents*.test.ts`, `server/claude-task-scan*.test.ts`: 259 pass, 0 fail on the step; `claude-images.test.ts` 50/50 on the final head. - Seeded fuzz (#2627's generator, every lookup against the search alone), seeds 2627 and 1–10, 400 rounds each: no differences. The same with 77f8902's own `conversation.ts` as the reference, on 322369d and on the final head: no differences (11/11 seeds each). - **Test changes in `server/claude-images.test.ts`, and why:** - **File-wide harness:** async lookups read through a `TranscriptReader` whose IO calls `fs.openSync`/`readSync`/`fstatSync`/`statSync`/`lstatSync` through the `fs` namespace. That way the existing spies on `fs.readSync`/`fstatSync`/`statSync`, your `readSync`-spy race triggers, and `holdTimes` see every read and stat the lease makes. It's set in `beforeEach` and restored in `afterEach`, using only the existing exports `TranscriptReader` and `transcriptReader`. No assertion changed for it. Reads arrive in windows of at most 1 MiB. - "bounds record judgments between event-loop turns even with a warm boundary" counts `JSON.parse` instead of `Buffer.alloc`, with the thresholds unchanged: a lease's window reads reuse their buffer, so a window no longer allocates. - "a lookup rejected after an in-place rewrite and growth leaves no stale boundary behind…": its trigger's "boundary scan" read is now the first read at position 0, not a read longer than 1 MiB, since the scan reads 1 MiB windows instead of one 16 MiB read. The assertions are unchanged, including that the change happened. - "reads a kept scan's bytes again when a later lookup would share a read begun before it…" (round 4): the held times are 1 s old (fine) instead of an hour old. With turns, the later lookup runs after the first one's check has finished. With hour-old fine times, the quiet rule would then vouch for it, and the test would no longer reach the `began` rule it is about. That outcome needs a same-size rewrite that keeps a fine ctime, which no writer can make. "Join any check" and "join a check begun before me" each still fail it. - The page-after-append test keeps #2627's bound unchanged. - **Added:** - "serves through the shared reader's own file access, warm and cold" (the real native IO, fast path included); - "serves a record read over several windows, whose shape keeps bytes of its first window" (buffer reuse); - "a transcript reached through a link": serves through a linked file and a linked directory, and refuses when the link is moved mid-lookup; - the back-walk read-count test (114 reads without the two SSHFS commits, bound 60); - a call id cut by a window edge, at the forward search's 1 MiB edge and where the back-walk probe's bytes end (each fails if the edge match is dropped; no test covered that edge before). - **Skipped on Windows,** each with a comment: the link tests, plus the two tests that need POSIX rename semantics (renaming a directory that holds an open file, and renaming over an open file). - `server/transcript-reader.test.ts`: `stats()` matches `stat()` on a real file, and `follow` is checked with injected IO (no real symlinks, since that file runs on Windows). - **`scripts/remote-bundle-smoke.ts`:** the bundle smoke now writes a synthetic Claude transcript with one picture, reports the pane to herdr as Claude with that session, and fetches the picture through the same route the UI uses. It asserts 200, `image/png` and the exact bytes, and a ref with no picture fails it with 404 `image_not_found`. It uses only builtins before `bun install`, so it runs on smoke-windows. I ran it locally against a built linux-x64 bundle. - Not run locally: the integration and browser suites, native Windows and macOS. You said the merge pass will run the reader and image tests in your Windows 11 VM. **Known limits** - **A mount that stops answering:** a lookup holds one of the reader's slots until its read returns, and later lookups of that transcript wait behind it in their turn. Main blocks the whole event loop there, so this is strictly better. Still, two hung transcripts at once would hold both pool slots, and history reads would queue (up to 32) and then get busy errors. - **A lookup refused as busy** (`TranscriptBusyError`) returns 404, as a failed read does on main. - **Request-time `began`:** a lookup that waited in its turn can reuse a check made before a same-size in-place rewrite, which needs the file's times held fixed. - **A busy reader:** at 34 or more concurrent reads of different transcripts, the reader is full and a lookup returns 404. - **Path check:** it skips ctime between the two stats (main has a matching window). - **On main too:** appends every 50 ms or faster to a 50 MB transcript make every lookup return null. - **#2627's limits stand:** a rewrite that keeps the file's times can be missed by a later lookup until the times move, and a coarse timestamp source pays a bytes read per warm lookup. All fixtures are synthetic files in temporary directories. No real transcript, image or screenshot was used. --------- Co-authored-by: devswha <[email protected]>
Change
A cold read of a long Claude session found old background Bash launches in subagent files but missed terminal notices before the parent's 16 MiB tail. Completed commands then appeared running indefinitely in the task list and pane count.
Share resumable historical terminal evidence between the task-list reader and pane tracker. Reads and consumed-span validation run cooperatively on the main thread in roughly 4 ms slices, with bounded session/terminal metadata and fair scheduling. Existing file/command/task pool capacity is unchanged.
Match historical ends to the session, launch time and Bash call. Before using cached evidence at a changed transcript version, validate the needed terminal lines, including newline boundaries, against their stored digests. Same-transcript row order also permits a stop written after its launch in the same millisecond. Released watchers and stopped trackers cannot restart reads after shutdown.
Incomplete, malformed, oversized or capped history does not hold queued input or keep a pane working; existing independent busy-signal barriers retain that policy (#2069). History never replays prompts or turn state. Refused watches retry after admission, partial records resume after append, and reads retry with bounded backoff.
Fixes #2601.
Validation
ce789b9, independent history/subagent/task-scan suites passed 146 tests and core status/background-wait/pending suites passed 208: 354 passed, 0 failed. All three prior rewrite/timestamp/shutdown reproductions and five additional row-order controls pass.bun run check fastonce789b9with CI-pinned Bun 1.4.2 passed 10,621 tests, 0 failed, 41 skipped in 658 files, plus workflow syntax, generated files, typecheck and build. The independently reproduced same-millisecond repeated-stop deduplication edge remains open. Upstream CI succeeded, including integration/browser and native Windows. One browser script (device-security-demo-regression.ts:283) timed out once and passed on its automatic retry.