Skip to content

fix(conversation): isolate Claude image disk reads - #2610

Merged
devswha merged 17 commits into
devswha:mainfrom
duytbp:fix/claude-image-disk-isolation
Nov 5, 2026
Merged

devswha merged 17 commits into
devswha:mainfrom
duytbp:fix/claude-image-disk-isolation

Conversation

@duytbp

@duytbp duytbp commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

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, fix(conversation): find a Claude picture's record without searching the transcript #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 statSyncs 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 fix(conversation): find a Claude picture's record without searching the transcript #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 fix(claude): read old command history without blocking on slow storage #2616's local fast path decides it may.
  • fix(conversation): find a Claude picture's record without searching the transcript #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. fix(conversation): find a Claude picture's record without searching the transcript #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 (fix(conversation): find a Claude picture's record without searching the transcript #2627's open note). It is now 10× faster: 6.0 s → 0.61 s on fix(conversation): find a Claude picture's record without searching the transcript #2627's big fixture.
  • When a lookup began (began/wall, which fix(conversation): find a Claude picture's record without searching the transcript #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. fix(conversation): find a Claude picture's record without searching the transcript #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 fix(conversation): find a Claude picture's record without searching the transcript #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-fix(conversation): find a Claude picture's record without searching the transcript #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.
  • fix(claude): reconcile background commands after cold history reads #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 (fix(conversation): find a Claude picture's record without searching the transcript #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 fix(conversation): find a Claude picture's record without searching the transcript #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.
  • fix(conversation): find a Claude picture's record without searching the transcript #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.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: devswha/ovis
  • Branch: main
  • File: .coderabbit.yaml
  • Commit: cbcb961
  • Layers: Repository YAML
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2ce9d0c2-bb15-48c6-807d-cd320933c42b

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Performance
    • Claude conversation images now load on a separate, bounded worker, helping keep terminal traffic, commands, task lists, and other file requests responsive during slow transcript reads.
  • Reliability
    • Image requests are revalidated against current pane and transcript state, and can be cancelled or stopped when they exceed their deadline.

Claude conversation image reads now run through a bounded worker pool. The request path applies deadlines and cancellation, and checks pane, transcript, and file-generation state before returning an image.

Changes: Claude image retrieval

Layer / File(s) Summary
Image read contract and worker
server/claude-image-file.ts, server/claude-image-worker.ts, server/claude-image-reader.fake.ts
Adds file-generation metadata and shared read state. The worker handles image reads and generation operations, then returns results to the pool.
Bounded pool and worker lifecycle
server/claude-image-pool.ts, server/claude-image-worker.fake.ts, server/claude-image-pool.test.ts
Adds a single-worker pool with queue and waiter limits, coalescing, cancellation, deadlines, reply validation, and worker retirement. Tests cover capacity, recovery, and responsiveness.
Authorization, generation checks, and route integration
server/conversation.ts, server/pane-routes.ts, server/index.ts, server/claude-image-isolation.test.ts, changelog.d/claude-image-disk-isolation.md
Adds deadline and abort handling, pane and transcript revalidation, and file-generation checks. The route passes its abort signal, and the server holds and releases the pool. Tests cover image results, stale reads, authorization changes, and cancellation.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Bug fix · Severity of issue fixed: Medium

Possibly related issues

  • devswha/ovis#2602 — The issue describes synchronous Claude image scans blocking the bridge event loop; this change moves image reads into a bounded worker.

Possibly related PRs

  • devswha/ovis#2604 — Adds the cooperative transcript image reader that this change moves into worker isolation.
  • devswha/ovis#1935 — Adds the Claude image retrieval path that this change updates.
  • devswha/ovis#1952 — Uses the conversation-image endpoint whose server-side retrieval this change updates.
Merge Risk: Minimal · previous review 80346

This change moves Claude image reads onto a separate bounded worker so slow transcript disk reads no longer stall the bridge. The reviewed evidence shows no concrete regression, and the remaining upstream CI checks are the normal merge gate.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 45.00% 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.
Passed Passed checks: 4 passed

Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: isolating Claude image disk reads from the bridge.
Linked Issues check Passed The PR addresses the coding requirements in #2602. server/claude-image-pool.ts provides a separate bounded worker pool with coalescing, 8 queued jobs, 8 waiters per job, 32 total waiters, shared dea…
Out of Scope Changes check Passed The changes stay within #2602. The new pool, worker, generation helpers, conversation fencing, server lifetime hold, route signal propagation, tests, fakes, and changelog entry directly support image-…
Description check Passed The description includes the required Change and Validation sections. It explains the implementation, behavior, performance results, known limits, validation commands, test results, skipped suites, an…
Full details: Linked Issues check

Explanation

The PR addresses the coding requirements in #2602. server/claude-image-pool.ts provides a separate bounded worker pool with coalescing, 8 queued jobs, 8 waiters per job, 32 total waiters, shared deadlines, cancellation, and retryable busy errors. The pool has no synchronous fallback and is separate from the file, command, and task pools. server/claude-image-worker.ts receives only explicit path and authorization metadata. It performs no pane discovery, authentication, or control RPC. server/conversation.ts revalidates pane, path, generation, and transcript state after awaited work. The implementation retains physical slots and opened descriptors until worker close. The reported focused and regression tests cover responsiveness, bytes and headers, authorization changes, /clear, generations, coalescing, limits, cleanup, recovery, and the 8 MiB boundary.

Full details: Out of Scope Changes check

Explanation

The changes stay within #2602. The new pool, worker, generation helpers, conversation fencing, server lifetime hold, route signal propagation, tests, fakes, and changelog entry directly support image-scan isolation, lifecycle safety, validation, or regression coverage. The PR explicitly limits the change to Claude image scanning and does not claim to isolate unrelated preexisting filesystem calls. No unrelated product behavior is demonstrated.

Full details: Description check

Explanation

The description includes the required Change and Validation sections. It explains the implementation, behavior, performance results, known limits, validation commands, test results, skipped suites, and HTTP route smoke coverage. It also identifies the related issues and prior work for this feature.

Full details: Docstring Coverage

Explanation

Docstring coverage is 45.00% 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 20 functions across 10 files. (1 skipped: 1 unsupported.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

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.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: devswha/ovis
  • Branch: main
  • File: .coderabbit.yaml
  • Commit: 7aecb24
  • Layers: Repository YAML
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4615d1e5-1238-4946-b4bb-5e78a8a4e665
Commits

Reviewing files that changed from the base of the PR and between 7aecb24 and 8034623.

Files selected for processing: 11

  • changelog.d/claude-image-disk-isolation.md
  • server/claude-image-file.ts
  • server/claude-image-isolation.test.ts
  • server/claude-image-pool.test.ts
  • server/claude-image-pool.ts
  • server/claude-image-reader.fake.ts
  • server/claude-image-worker.fake.ts
  • server/claude-image-worker.ts
  • server/conversation.ts
  • server/index.ts
  • server/pane-routes.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 2 remain after this review.

@duytbp

duytbp commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Independent pool and integration reviews completed before publication. Six confirmed findings were fixed:

  • Malformed worker results now fail validation without throwing on the bridge.
  • Shutdown unreferences the worker before termination; a real FIFO-blocked child exits normally without releasing the read. Physical capacity remains charged until actual close in a continuing process.
  • Initial authorization obeys the original deadline and cancellation signal.
  • Pane/global invalidation during initial authorization cannot be lost before dispatch.
  • An expected-generation rejection revokes the affected cached image boundary.
  • A failed final generation fence invalidates the stale private scanner boundary.

The final integration re-review independently reran the original authorization/invalidation/generation cases: 5 passed, 0 failed. The malformed-result reproductions also passed after the fix, and the shutdown correction was independently confirmed against the actual source. No introduced material findings remain in the reviewed scope.

The review covered exact owned buffer transfer, 8 MiB limits, shared opened-FD cleanup after actual close, bounded waiters/admission, cancellation/coalescing, strict physical-worker limits, pane reauthorization after awaits, and preservation of the CPU reader's exception rollback. Existing warm parsed-history caches are retained.

The preexisting tail-cache assumption for an arbitrary unobserved between-request prefix rewrite followed by growth remains documented in the PR; this review does not claim to fix all such history-rewriting semantics. Full fast/native contract and performance results are listed in the PR description.

@devswha

devswha commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Thanks @duytbp, this is careful work, and the measurement shows the problem it targets is real. We are keeping the PR open but not merging it as is.

We measured the image lookup against main (which has #2604) on a 125 MB and an 18 MB Claude transcript, 6 runs per cell, with a separate client pinging the server every 10 ms during each lookup. Medians; "ping max" is the longest any other request waited:

setup case main image / ping max this PR image / ping max
local SSD 125 MB, cold 297 ms / 23.8 ms 348 ms / 0.3 ms
local SSD 125 MB, warm 87 ms / 2.1 ms 58 ms / 0.2 ms
local SSD 18 MB, cold 482 ms / 17.3 ms 500 ms / 0.4 ms
local SSD 18 MB, warm 65 ms / 0.7 ms 63 ms / 0.3 ms
sshfs mount (LAN, 14 ms RTT, no cache) 125 MB, cold 5431 ms / 782.8 ms 5735 ms / 1.9 ms
sshfs mount 125 MB, warm 5509 ms / 135.4 ms 5260 ms / 2.4 ms
sshfs mount 18 MB, cold 1224 ms / 698.2 ms 1278 ms / 0.4 ms
sshfs mount 18 MB, warm 838 ms / 72.1 ms 827 ms / 0.3 ms

On a network-mounted ~/.claude main stalls every other request for 0.7-1 s and this PR removes that completely. On a local disk, the common case, main has no noticeable stall, and the PR currently makes some things worse there:

  • the first image takes about twice as long (worker start, and four herdr lookups per image instead of one);
  • an image answers 404 if Claude appends to the transcript during those lookups (the size/mtime fence), where main answers 200, and the chat hides the thumbnail;
  • a page of 24 images at once got 16 × 503 (8 queued jobs, three per image), which <img> never retries; main served all 24.
    Review also found a hung worker can hold every later image request until its deadline, and repeated worker failures restart it with no backoff.

The project's rule for performance changes is that they must be clearly better in every measured case. A future version that keeps the network-mount win would need no regression on local disks (first-image time, a transcript being appended to, a page of many images), no 503s for a normal page, and one shared transcript reader with the Claude command-history path from #2608 rather than a second process-wide worker. Thanks again for digging into this.

@duytbp

duytbp commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Pushed the test-only correction 645b38c. The failing CI assertion checked whether a descriptor number still existed after the replacement worker started; the OS could legally reuse that number for another file. The test now checks ownership of the original file before and after retirement. Independent mutation checks confirmed that both premature closure and an actual leak still fail. Full bun run check fast passed with CI-pinned Bun 1.4.2: 10,657 passed, 0 failed, 41 skipped, plus workflow/generated-file/type/build checks. No production code changed in this commit.

Thank you for the measurements and concrete review cases. I agree that the network-mount improvement does not justify those local and normal-page regressions. I have two read-only review lanes working on reproductions and a shared-reader design with the command-history path, including append tolerance, normal-page admission, and bounded failure recovery. I will bring back the design and evidence before further implementation changes. The PR description now records the outstanding concerns.

@duytbp

duytbp commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

I reproduced the append and gallery regressions on 645b38c with Bun 1.4.2. These are four isolated tests (34 assertions), using the actual route handler and image worker with mocked pane/transcript discovery; they do not measure HTTP or Herdr latency.

Case Current PR Merged reader baseline
Unchanged image 200; four snapshot/path-resolution rounds Exact image returned
Ordinary append between inspect and read 404 Exact image still returned
Ordinary append between read and final check 404 Exact image still returned
24 distinct image refs from one history 8 × 200, 16 × 503 All 24 exact images returned

Before replacing the implementation, would this shared-reader direction fit your requirement?

  • One in-process transcript reader owns pinned asynchronous positional I/O, bounded windows, file identity, invalidation and retry state. Both image and command-history readers use it; their parsing and authority rules remain separate. This removes the application Worker startup and inspect/read/check jobs.
  • Same-file image requests share boundary discovery and windows. Normal gallery admission is separate from physical read concurrency and active decoded-byte limits, so 24 distinct refs do not exhaust a queue of eight metadata phases. No decoded-image cache is needed.
  • A validated prefix remains usable after a harmless append, with appended clear/rewind records reconciled before publication. Replacement, truncation, rewritten evidence and changed pane/session binding still invalidate results. Collapse the four authorization rounds to initial and final checks, sharing only in-flight binding lookups where valid.
  • Preserve cooperative CPU slices. Use per-path single-flight and fair scheduling for history/images, with a small global native-I/O cap. A timed-out operation retains its physical charge and descriptor until it actually settles; repeated requests for a stuck path do not launch more syscalls, and failures use bounded backoff.

There is a resource limit to agree on: Bun 1.4.2 asynchronous filesystem dispatch uses a shared native pool, and FileHandle.read exposes no dedicated-pool selector. A two-operation cap permits scheduling another path beside one stuck operation; actual progress still depends on available native-pool capacity and other users. The explicit file/command/task Worker slots remain unused, but this cannot reserve native threads or guarantee progress after a permanently stuck syscall exhausts the available native capacity. I would not describe this as hard hang isolation. Is bounded native admission acceptable, or do you require a separately isolated shared backend?

The validation gate would repeat your 18/125 MB cold/warm local/network matrix with the independent 10 ms health client, including first-image and full-gallery time. It must also pass append-at-each-stage, all-24-images, blocked-path/healthy-path fairness, actual-settlement cleanup, and the existing clear/rewind/rewrite and #2608 evidence/shutdown regressions. Native async I/O is only a candidate; it still needs to demonstrate the local performance result.

Coordination record: owner duytbp (implementation) with an independent review lane; scope shared transcript I/O for images and command history; branch/worktree fix/claude-image-disk-isolation; start SHA 645b38c2cbaad8d52275d3fa1ab51ff54a7b2b3e; dependency #2608 landing, followed by an independent main-based update rather than an assumed stack; verification as above; status proposal only, awaiting approach agreement before extraction. No application source changes have been made for this redesign.

@duytbp

duytbp commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

The reusable HTTP benchmark harness is now working with real isolated Herdr process ownership and native PID-session discovery, without snapshot/path-resolution mocks. It uses synthetic transcripts and a Node stand-in named claude; it makes no model requests. Image requests pass through the actual application HTTP/access path, and a separate process sends health requests every 10 ms to the same server. Health figures are response latency around the image request, including small START/STOP IPC margins, rather than an exact event-loop-pause measurement.

A small local diagnostic sample (one repetition per source/size) also reproduces gallery admission failures:

Synthetic history Main a6aca2b Current PR 645b38c
18 MiB, 24 refs 24 × 200 22 × 200, 2 × 503
125 MiB, 24 refs 24 × 200 9 × 200, 15 × 503

Every successful body matched the exact synthetic image bytes. First/warm timing results were mixed, so I am not inferring a speedup or acceptance result from this sample. Startup is recorded separately; filesystem caches are not forcibly dropped. Runtime was Bun 1.4.2, Herdr 0.9.5, with a Node 26 stand-in.

The fixture-only SSHFS lab also passed a main-only 18 MiB HTTP smoke: measured SSH RTT 14.06 ms, first image 200 in 5.60 s, health maximum 1.86 s. HTTP stays outside the delayed network namespace. This mount disables data/metadata caches and readahead, so it is a stricter synthetic setup, not your exact physical network/mount or a candidate comparison. Normal exit and SIGTERM cleanup left no lab namespace processes, mounts or isolated Herdr state.

The tools and raw JSON are ready for the agreed implementation's repeated comparisons. Future baselines will include the now-merged #2608. Application code remains unchanged while the shared-reader/native-admission proposal above awaits approach agreement.

@devswha

devswha commented Nov 2, 2026

Copy link
Copy Markdown
Owner

Thanks @duytbp for reproducing our cases with the real route and for the HTTP benchmark harness; that is exactly the evidence this needs.

Yes, the shared-reader direction fits: one in-process transcript reader (pinned async positional I/O, bounded windows, file identity, invalidation and retry), used by both the image path and the Claude command-history path from #2608, with their parsing and authority rules kept separate and no application Worker. For it to merge:

  1. Same acceptance table, on the same harness, main vs the branch:
    • local SSD: first and warm image time no worse than main;
    • a page of 24 images never gets a 503;
    • an ordinary append during a lookup never turns an image into a 404 (a /clear or rewind appended meanwhile still hides it);
    • the network-mount (sshfs) stall on other requests is gone;
    • fix(claude): reconcile background commands after cold history reads #2608's cold-read guarantees stay intact (finished background commands shown finished, running ones running, ends matched to their own launch, session and unchanged line; unknown history never holds a pane's input).
  2. Keep it reviewable in steps: ideally first a PR that moves fix(claude): reconcile background commands after cold history reads #2608's command-history read onto the shared reader with no behaviour change, then the image path on top of it.
  3. Windows and the remote PC bundle must keep working, with the async positional reads there too (the Native Windows install job and the remote bundle smoke cover both).

We'll review each step with the same reviewers as before. Thanks again.

@duytbp

duytbp commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, I’ll follow the history-first split. The first PR will move command-history filesystem work onto the shared asynchronous reader while preserving #2608’s reconciliation and queue/rest rules. The image rewrite will follow after that foundation merges, so there is no assumed contributor-managed stack.

The implementation keeps one main-thread I/O controller. Existing task workers return bounded parsed snapshots for pure reconciliation, rather than creating separate per-worker reader queues. Terminal-line proof is awaited before publishing new historical conclusions; current turn/busy processing remains independent. Recent parent/subagent tail parsing is outside this first step, and the image path is unchanged.

Before pushing, I’ll check the existing cold-history/session/call/rewrite/append regressions, async-gap tracker shutdown and replacement cases, held-I/O accounting and cleanup, plus actual Windows test selection and a bundled-reader exercise. Native filesystem operations retain their physical charge until they settle; this does not claim a reserved runtime pool or forced syscall cancellation.

Coordination record:

  • owner: duytbp, with separate implementation and independent review lanes;
  • scope: shared async positional reader plus command-history migration only;
  • branch/worktree: fix/claude-shared-transcript-reader, a fresh manual worktree;
  • start SHA: 5456638ff5dfc1851bc7566cb641164daf7937eb from main;
  • dependencies: your approved direction above; image integration waits for this step to merge;
  • verification: targeted history/lifecycle/resource tests, native contracts, bun run check fast before push, and required Windows/remote-bundle CI;
  • status: design reviewed locally; implementation starting. Existing fix(conversation): isolate Claude image disk reads #2610 head remains untouched.

@duytbp
duytbp marked this pull request as draft November 2, 2026 15:03
devswha added a commit that referenced this pull request Nov 3, 2026
#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]>
devswha added a commit that referenced this pull request Nov 3, 2026
…he transcript (#2627)

## Change

Fixes #2623.

Every Claude picture lookup searched its transcript from the last
`/clear` to the end for the record its ref names. A tool's picture then
searched again, from the floor up to that record, for the call it
answers. The lookups of one transcript take turns, so a page of
screenshots read a long transcript up to twice per picture, one after
another. This PR targets main as it is and doesn't depend on #2610.

- **Picture index:** the boundary scan, which every lookup already runs
and caches, now notes where each user record holding a picture starts
(`PictureIndex`, `notePicture`). It does that for the first such record
since the `/clear` with that uuid. A lookup reads that one record and
judges it exactly as before.
- **Still searched as on main**, so the first record that qualifies
still decides:
- a uuid seen on an earlier record, followed by the branch or not
(`loose`);
  - any record after one too long for the scan to read (`blind`);
- any record after a record the endpoint may not judge (`unread`,
below);
  - any record after the `loose` cap (below);
  - the final unterminated line;
  - a record a rewind left behind (`hidden`).
- **Records the endpoint may not judge:** the scan notes each record
since the `/clear` whose shape could pass `SHAPE_MAX_BYTES` (a bound on
its strings that never undercounts, following `recordShapeSteps`'
escapes), or that is long enough to hold a call id `callIdSteps` doesn't
read (`mayBeUnread`). Only lines over about 3.9 MiB are looked at, by
`indexOf` jumps; a screenshot's single long string never qualifies. A
picture after such a record on the branch is searched for, and a call
before one is looked for forward from the floor
(`answersDrawnCallForwardSteps`, main's search), so main's refusal
holds.
- **A kept scan's bytes are checked before its index is trusted:** a
kept scan is checked by main only by the bytes just before where it
ended, so an in-place rewrite of an earlier line, followed by an append,
can keep it. The scan now also digests the bytes its index was built
from (`PictureBytes`: chained xxHash3 over 64 KiB pieces at fixed
offsets from the floor, digested from the windows the scan already
reads, so no extra reads). A lookup trusts the index only for a file
version (dev, ino, size, mtime, ctime) that a read of those bytes
vouched for (`vouchedPictureSteps`):
- a read that began after the lookup began, such as the lookup's own
fresh scan, or another lookup's check; or
- a read that began at least 3 s after the version's mtime and ctime,
when the ctime has a fraction of a second (`fineTimes`), so the
filesystem's times tick finer than that (`PICTURE_RACY_MS`, the
racy-clean rule of `RACY_MS` in claude-command-history from #2620, for a
same-size rewrite within one timestamp tick).

Otherwise the lookup reads the bytes once, in yielding steps, and
lookups of the same version that began before that read share it, so a
page pays one read per change. A lookup that began after a read, in
flight or done, never shares it: it reads the bytes itself. On a source
of whole-second times (sshfs/SFTP, ext3, HFS+, FAT), no read vouches for
a later lookup, so every warm lookup there pays one read of the bytes.
Bytes that differ turn the index off (`forgetPictures`) and the search
decides. This covers the indexed record too, so round 2's line-boundary
and record-digest checks are gone.
- **A picture the index holds no record of, in a version nothing vouched
for yet**, runs exactly as with the index off: the search for its record
and main's forward call search, with no use of `unread`, `loose` or
`blind`, and no read of the bytes on top.
- **`loose` is bounded:** uuids of records the branch doesn't follow are
kept as 32-bit marks (xxHash32), from the last `/clear` on. The scan
appends marks to a flat log; a picture's lookup checks a table, then the
log, and the log is folded into the table once lookups have read it 64
times over. Two uuids sharing a mark read as seen, which only sends that
lookup to the search. **Cap:** `MARKS_LIMIT` is 128 Ki marks since the
`/clear` (a 512 KiB log, or a 1 MiB table at most half full). Past it
the marks are freed, no uuid is hashed, no later record is indexed, and
every picture after that point is searched for, as on main.
- **Call search goes backward:** from the result one window at a time,
starting at 64 KiB and doubling up to `IMAGE_SEARCH_WINDOW`. The last
block before the result that names the call decides, as the forward
search did. A window starts at the start of the line its edge falls in,
found by reading back 64 KiB at a time.
- **Event loop:** each read of the back-walk and of the bytes check, and
the record read after the boundary scan's last window, is a step of its
own. A lookup still yields between bounded reads, as since #2604.

Where a kept scan's own floor, branch or hidden ranges are stale after
an in-place rewrite, the answer is main's, since the search uses the
same kept scan. Main keeps that blind spot (write a `/clear` in after a
picture, keep the tail, grow the file, and main still serves the
picture), and this PR doesn't change it.

Not changed: a key spelled `"uuid"`.

## Timing

Main 05c9133 against this PR, 7 interleaved runs each, a fresh process
per run with the page cache warm, median [min–max], ms. Synthetic
fixtures: **big**, 102 MB with 200 pictures of about 147 KB, half a
user's and half a tool's; **clear**, 106 MB with a `/clear` at about 90
MB and 40 pictures after it; **side**, 96 MB of 500,000 sidechain
records and a picture. **Append** rows model a live session: each
process works on its own copy and appends a line before each timed
lookup, so every timed lookup runs in the timestamp tick of the last
write and pays the bytes check. The host also runs a VM using about 8.5
cores, so treat differences under ~15% as noise.

Round 4 (1b61272) changes only when a read vouches; interleaved against
ec3b92b on the append rows it costs the same (big append page 610
against 612 ms, clear 714 against 729 ms, one bytes read per page on
both). Rows marked * are from 664db03, the head before the last commit.
That commit changes only pictures the index holds no record of and scans
past the cap, which these fixtures' rows don't reach; the big append
rows, re-timed on ec3b92b, moved with main's (+5–10% on both).

| row | main wall | PR wall | main CPU | PR CPU |
|---|---|---|---|---|
| big, first lookup (with the boundary scan) * | 398 [385–441] | 303
[251–334] | 520 | 389 |
| big, warm user / tool picture * | 100 / 145 | 24 / 20 | 141 / 189 | 26
/ 22 |
| big, user / tool picture right after an append | 104 / 147 | 64 / 52 |
146 / 205 | 72 / 67 |
| big, 24-picture page, warm * | 3542 [2831–4059] | 392 [324–486] | 4455
| 488 |
| big, 24-picture page right after an append | 3614 [3029–4713] | 488
[400–599] | 4548 | 620 |
| big, 24-picture page, fresh process * | 9743 [8512–13829] | 6494
[5999–8117] | 11759 | 7883 |
| clear, first lookup * | 349 [328–394] | 316 [284–408] | 428 | 402 |
| clear, warm user / tool picture * | 47 / 43 | 28 / 20 | 57 / 49 | 30 /
22 |
| clear, user / tool picture right after an append * | 51 / 49 | 36 / 34
| 61 / 57 | 41 / 35 |
| clear, 24-picture page, warm * | 1017 [887–1141] | 557 [437–707] |
1145 | 667 |
| clear, 24-picture page right after an append * | 1196 [1035–1438] |
536 [459–744] | 1375 | 624 |
| clear, 24-picture page, fresh process * | 8993 [7731–9433] | 8522
[7887–9450] | 10952 | 10376 |
| side, first lookup | 907 [876–1034] | 969 [876–1042] | 1114 | 1204 |
| side, warm user / tool picture | 359 / 344 | 357 / 356 | 450 / 423 |
456 / 442 |
| side, user / tool picture right after an append | 337 / 345 | 365 /
347 | 441 / 419 | 472 / 428 |
| big, cold history page * | 291 [252–368] | 283 [264–345] | 356 | 364 |
| clear, cold history page * | 329 [315–336] | 336 [312–394] | 397 | 410
|
| side, cold history page | 588 [576–655] | 651 [609–692] | 681 | 769 |

Warm history pages are 0.1 ms on both.

- **Cost of the check:** reading a version's bytes again is about 30 ms
wall and 40 ms CPU per 100 MB. That is what a lookup right after an
append gives back of the warm speedup: a big user picture goes from 24
ms warm to 54–64 ms right after an append, against main's 100–104 ms. A
page pays it once (392 → 438–488 ms, against main's 3.3–3.6 s). In a
session quiet for 3 s, lookups don't pay it.
- **Side is past the cap:** 500,000 sidechain records is more than 128
Ki marks, so the side picture is searched for as on main, and its warm
lookups are back to main's cost (round 2 had them at 1.8 ms). The other
side rows are within noise of main. In this run, cold CPU is +8% and the
cold history page +13%, with overlapping ranges. A second interleaved
run of 7 on the same trees gave the PR **1057 against 1086 ms** cold CPU
and **704 against 722 ms** for the history page, slightly under main. By
ablation in that run, what remains over main is the scan's digest and
the first 128 Ki marks, a few percent at most.
- **History pages:** big and clear are within 2–3% of main (the scan's
digest). Side's +16% from round 2 is gone, as above.
- A 24-picture page in a fresh process takes 6.5–10 s on both versions.
Every lookup that starts before the first boundary scan is published
runs a scan of its own. It behaves the same on main, and this PR doesn't
change it.

**Memory at 2M sidechain records** (384 MB file), each version in its
own process with `MIMALLOC_PURGE_DELAY=0 bun --smol`, one cold lookup
and 5 warm, then `Bun.gc(true)`; three runs, MiB. RSS before the first
lookup is about 46 MiB on all three. Past the cap nothing is allocated,
so 664db03's numbers stand for the head.

| version | RSS | JS heap | external | arrayBuffers |
|---|---|---|---|---|
| main 05c9133 | 74.2 / 70.3 / 74.1 | 3.0 | 1.3 | 0.0 |
| this PR (664db03) | 75.1 / 73.8 / 73.9 | 3.1 | 1.4 | 0.0 |
| a117343 (round 2) | 75.6 / 75.5 / 76.0 | 10.9 | 9.2 | 8.0 |

Bytes read per warm lookup, on a synthetic 40 MiB transcript (counting
`fs.readSync`; measured in round 2, and a warm lookup in a vouched
version reads the same):

| lookup | main | this PR |
|---|---|---|
| user picture | 40.05 MiB | 0.4 KiB |
| tool picture, call just before its result | 80.09 MiB | 128.8 KiB |
| tool picture, call far back, 64 KiB lines | 80.09 MiB | 42.73 MiB |
| tool picture, call far back, 1025 KiB lines | 78.08 MiB | 44.48 MiB |

#2623 has the field numbers that prompted this: on a 1.7 GB transcript,
the median image request went from 48 s to 0.7 s after a build with this
change. The caveats are in that issue: that build also carried other
changes, and the log has no timestamps.

## Validation

- Toolchain: Bun 1.4.2.
- `bun run check fast` on 1b61272: `unit: 10721 pass, 0 fail, 41 skip
in 662 files`. Workflow syntax, generated types and themes, typecheck
and build all ok.
- `server/claude-images.test.ts` and `server/conversation*.test.ts`: 264
pass, 0 fail. The image test file passes 43 of 43 with real main's
module as the reference.
- **Compared with main:** `both` compares three lookups: cooperative,
synchronous, and the search alone (`pictureIndexForTests(false)`: the
index off and the forward call search, which is main's lookup code, on
the same scan).
- **Repros for the round-3 case**, through `earlierRewritten`: warm a
lookup of B, rewrite an earlier line in place at the same length (more
than 64 KiB before the end, keeping B's record and the tail), append,
look B up again. The earlier line becomes (1) a record of B's uuid with
picture A: main and the PR serve A; (2) an unreadable line naming the
uuid: both refuse; (3) an unreadable line naming the call before its
call record: both refuse; (4) as (3), for a tool picture past the cap:
both refuse. On a117343, (1)–(3) serve B. Also: a same-size rewrite
that keeps the file's times (one timestamp tick); a page right after an
append, which reads the transcript once; times held on a 10 s tick,
whole or with only the ctime whole, with B warmed 5 s in and an earlier
line rewritten into A (both serve A); a rewrite landing right after a
shared check read its window, with a second lookup starting then (B,
then A, as main); and the ctime half of the 3 s rule (mtime an hour old,
ctime 1 s old, as `cp -p` leaves it).
- **Cap test:** 128 Ki sidechain records, then a sidechain uuid reused
by a picture, then a fresh picture. The reused uuid gives null, as on
main; the fresh picture is served, and its warm lookup and its lookup
after an append each read one search's worth (under 1.5× the file); a
picture before the cap reads under 1 MiB.
- **Seeded fuzz test:** seed 2627, 200 transcripts, 3 steps of 8 lookups
each, every lookup compared with the search alone. The transcripts hold
duplicate, sidechain and isMeta uuids, records written twice with
different pictures, `/clear`s and rewinds, numeric call ids, and
unreadable lines naming a uuid or call id before what they name. Between
lookups each is appended to or rewritten in place, keeping the size or
growing it behind the tail a kept scan is checked by. New this round: an
earlier line rewritten in place, at the same length, into another record
of a picture's uuid, or into an unreadable line naming that uuid or its
call; and half the rounds give every write its own mtime well in the
past, so vouches carry over and the trust-without-reading path runs; and
a fifth of the rounds report one whole second for every stat, held, as a
coarse timestamp source would. With real main as the reference, seeds
2627 and 1–10, 400 transcripts each: no differences on this head, and
differences from round 12 of seed 2627 on a117343, and at rounds 61 and
174 on ec3b92b.
- Each guard undone fails at least one test:

  | undone | fails |
  |---|---|
| the bytes check off (index always trusted), or the scan digesting
nothing | repros (1)–(3), the tick test, the append-page test, the
round-2 rewrite test, fuzz |
  | the chained digest not compared | repros (1)–(3) |
| the last partial piece not compared | the round-2 rewrite test, the
tick test, fuzz |
| `forgetPictures` off | repros (1)–(3), the tick test, the round-2
rewrite test, fuzz |
| the racy rule off (a vouch always carries) | the tick test, the
coarse-tick test |
| the fine-times guard off, or judged by the mtime | the coarse-tick
tests |
| a lookup sharing a read that began after it (round 3's rule) | the
shared-read rewrite test |
  | the ctime half of the 3 s rule off | the ctime test |
  | each lookup checking on its own | the append-page test |
| a fresh scan vouching for nothing | the far-call cost test, the cap
test |
| an unindexed picture in an unvouched version keeping the index | repro
(4) |
| an unindexed picture in an unvouched version checking the bytes | the
cap test |
  | the cap off, or uuids still hashed past it | the cap test |
| `unread` off (picture and call), or for the call only | fuzz; the
unread uuid and unread call tests |
| `loose` off, duplicate guard off, log never read, log folded without
inserting | fuzz; the duplicate and fold tests |
  | `blind` off | the 20 MiB test |
  | index off | the cost tests |
  | ranges judged forward in each backward window | the call test |
| a back-walk that reads its whole span, or forward pieces; main's
forward call search put back | the cost tests |

  Never folding the log changes only cost, which no test measures.
- `pictureIndexForTests` stays exported: conversation.ts already exports
test hooks the same way (`limitCodexHistoryForTests`), as do
codex-images.ts (`blobPlatformForTests`, `aroundBlobOpenForTests`) and
others. I'm happy to move it if you'd prefer another mechanism.
- Not run locally: the integration and browser suites, native Windows
and macOS. Upstream CI covers them.

All fixtures are synthetic files in temporary directories. No real
transcript, image or screenshot was used.

---------

Co-authored-by: devswha <[email protected]>
…path

TranscriptFile.stats() returns the pinned handle's whole fstat, for a reader
keyed on more than a TranscriptVersion (its change time, its numeric inode).
read(..., { follow: true }) checks the path by the file it names (stat), not by
its own entry (lstat), for a caller that opens a transcript through a link, as
openSync and statSync do. The default, and history, are unchanged.
…eader

The image lookup keeps its parser, its boundary scan, its picture index and
the checks that guard it, and now reads the transcript and its stats through
transcriptReader's lease: positional reads of the file it pinned, in windows of
at most a MiB, awaited as steps, so a slow disk no longer holds the event loop.
Every read the lookup makes goes this way, the bytes check of a kept index and
the walk back for a tool's call included. The synchronous lookup reads as
before.

Lookups of one transcript take the reader one after another. A lookup's version
is stamped when it was asked for, not when its turn came, so the pictures of a
page asked for together still share one check of the index's bytes, as lookups
made side by side do: a lookup takes a verdict only from a check begun after it
was asked for. The path is checked by the file it names, as statSync does, so a
linked transcript or store still serves.

The image tests read through a reader that uses fs's own calls, so their spies
on fs.readSync, fs.fstatSync and fs.statSync see every read and stat a lookup
makes; one test serves through the reader's own file access.
@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Now that #2616 and #2627 have merged, I'm picking this up as the image step we agreed on: Claude image reads go through the shared TranscriptReader, with no Worker.

About the branch. It still holds the old Worker design. Without a force-push, I'd add one merge commit whose tree is the new step on current main, so the diff against main is only that step and the old commits stay in history. If you'd rather have a fresh PR, or a force-push here, tell me and I'll do that instead. I'll mark this ready once the table is in.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

A question about your point 3, Windows and the remote bundle with async positional reads. I checked both jobs, and neither reads a transcript today:

  • Native Windows install: its bun test line runs windows-plugin, plugin-runtime, phone-setup, windows-native and omp-images.
  • The remote bundle smoke: it hits /api/bridge, /api/session and /api/workspace/create.

So they prove the server loads with transcript-reader.ts in its import graph, but not that a positional read works there. To check that for real, would you take either or both of these in this PR?

(a) Add server/transcript-reader.test.ts, and server/claude-images.test.ts with its symlink cases skipped on Windows, to the Windows bun test line.
(b) Add one Claude picture fetch from a synthetic transcript to remote-bundle-smoke.ts.

Or neither, if you'd rather keep CI as it is.

@devswha

devswha commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Good catch, thanks @duytbp. (b) yes: one Claude picture fetch from a synthetic transcript in scripts/remote-bundle-smoke.ts is welcome in this PR (a script change). (a) not in this PR: it edits the CI workflow, which waits for the owner's separate go. Instead, the merge pass will run server/transcript-reader.test.ts and server/claude-images.test.ts (symlink cases skipped) on your head in our Windows 11 VM and post the result here; if you want the Windows line extended for good, open it as its own small PR.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, I'll add (b) to this PR: a Claude picture fetch from a synthetic transcript in remote-bundle-smoke.ts, checking for a 200 and the exact bytes. The symlink cases in claude-images.test.ts will skip on Windows, so your VM run doesn't need to filter them. I'll leave (a) for a small follow-up PR, if you want the Windows line extended for good.

… way back to a Claude tool's call

The backward call walk looked for the start of the line each window cuts 64 KiB at a time, and
each window began twice as long as the one before, however far the line had taken the last one.
Over lines of a MiB that was a read per 64 KiB, and on a network home every read is a round trip:
a warm tool picture whose call is 18 MiB back took 108 reads, against 42 before the index.

Each piece back is now twice the one before, up to a search window, and each window twice what
the one before covered. The same lookup takes 63 reads and reads 21 MiB instead of 22. Which
lines are judged, and in which order, is unchanged.
…inding its line's start read

The piece that finds the start of the line a backward window cuts holds that line's first bytes;
the window read them again from the line's start, so a window of a MiB took a second, short read
for the rest of its line. It now begins with those bytes and reads from where the piece began.

A warm tool picture whose call is 18 MiB back over lines of a MiB takes 45 reads instead of 63.
A symbolic link there needs Developer Mode or the right to make one, which a test run may not
have. The reader's follow of a link is checked with injected IO, which runs everywhere.
…n its smoke

The bundle's own Bun now serves a picture from a synthetic Claude transcript written into the
smoke's home, through the route the chat view uses: the pane is reported to herdr as running
Claude with that session, and the picture's bytes must come back exact. The transcript reader's
positional reads then run on each bundle's platform, Windows included.
…ame what a lookup holds open

One renames the directory that holds the open transcript and one renames a file over it: both need
POSIX rename semantics, which Windows does not give a file another handle holds open.
…g a long one onto the text before it

The search for the lines that name a call tested each piece of a line with the end of the window
before it in front, so text a window's edge cut in two is still found. Joined to a piece of a MiB,
those few characters made the search copy the whole piece first: a line longer than a window paid
a copy of a MiB, and once the backward walk began its windows with what its probe had read, every
line did.

The piece is now searched alone, and the cut text in the end of the window before it and the
piece's first characters. What is found is unchanged; a test puts a call's id across a window's
edge.
…ed-reader image step

The Worker commits (8034623, 645b38c) stay in this branch's history, and the tree is the image step on the shared transcript reader, so the diff against main is only that step and nothing is force-pushed.
@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

This is ready for review. The branch is a merge commit whose tree is the image step on 77f8902, so the diff against main is 7 files. The description has the acceptance table, every changed test assertion with its reason, and the known limits.

Here is the part that most needs your judgement. On the SSHFS lab, the step on its own failed one item: a page of 24 pictures. The lookups of one transcript now take turns, and each warm far-call picture took about 3.3 s over the mount, so the end of the page went past the 60 s request budget. Main is at that edge too: 64 s, reset once in 3 runs. Two commits make #2627's backward call search read far less over the mount (45 reads instead of 108), and with them the page loads in 37.7 s.

Two checks on the final head are still running: the seeded fuzz with 77f8902's conversation.ts as the reference, and an SSHFS rerun. I'll post both here when they finish.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Before you spend review time on this, here's an honest picture of what it buys now that #2616 and #2627 are in. I'd like your call on the shape.

On a local disk it's about neutral. Against main 77f8902 in the HTTP harness, first and warm images, and pages of 24, are within noise (18 MiB first 161 against 181 ms, warm 19.2 against 18.2 ms; 24-page warm 563 against 577 ms). #2627 already removed the reading that made a large transcript slow. One in-process measurement shows a fresh-process page of 24 is 10× faster (6.0 s → 0.6 s), because the pictures now take turns instead of each running its own boundary scan. The HTTP harness's cold page didn't show that, so I wouldn't count on it.

What it changes is slow storage. On the SSHFS lab:

main this PR
event loop held during an image lookup 380–825 ms ≤ 9 ms
other requests' worst stall during a page of 24 8–9 s 0.6 s
page of 24 about 64 s, past the 60 s request budget in 1 of 3 runs 38 s, 24 × 200
warm image, 18 / 125 MiB 3.5 / 12.7 s 2.2 / 9.7 s

But part of that only undoes a regression #2627 brought to network mounts. Pre-#2627 main took 1.9 s for that warm image over SSHFS, and main now takes 3.5 s: the backward call search reads back 64 KiB at a time, and each read is a round trip there. The two back-walk commits here fix that, and they don't depend on the shared reader. Also, the 1.8 s /api/health stall on the first picture over SSHFS is the same on every version. It comes from claude-subagents.ts scanParent and session-plan-reader.ts planState reading synchronously, not from images.

So the shared-reader image step is mainly insurance: a slow or hung disk no longer freezes the server through the image path. That's the design you asked for, but it adds code (async steps through the lookup, imageTurn, request-time began) for a case most installs won't hit.

Which would you like?

(a) Review this PR as it is: the image step plus the back-walk fixes.
(b) Only the back-walk fix, as a small separate PR that restores #2627's SSHFS cost. I'd close this one.
(c) The back-walk fix as its own PR first, so it lands either way. Decide on the image step separately, later or not at all.

Separately, if you want, I can do a follow-up that moves readLines (subagents) and planState onto the shared reader. That's where the remaining first-picture stall on slow storage comes from.

@devswha

devswha commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Thanks @duytbp, that's a very useful picture. My recommendation is (c): the back-walk fix as its own small PR first, since it fixes a #2627 regression on network mounts and can land on our usual gate, with the image step decided separately. I'm getting the owner's call on the image step and will confirm here. Our review of this head is already running, and anything it finds in the back-walk commits will carry over to the new PR.

@devswha

devswha commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Decision: (c), thanks @duytbp.

  1. The back-walk fix as its own PR first. It undoes a fix(conversation): find a Claude picture's record without searching the transcript #2627 regression on network mounts, so it lands on our usual gate: review, and a main-vs-PR ABBA showing a local disk is no worse and a warm SSHFS image is back to at most the pre-fix(conversation): find a Claude picture's record without searching the transcript #2627 cost (1.9 s in your lab). Please open it from the back-walk commits alone, on current main, with your local and SSHFS numbers.
  2. The image step afterwards, here. You followed exactly the path we asked for, so it is judged on the bar we posted when we parked fix(conversation): isolate Claude image disk reads #2610: a local disk no worse, no 503s or 404s on a page of 24, the network-mount stall removed, the shared reader, and Windows plus the remote bundle working. If it meets that bar with clean reviews, it merges on our side's call; it doesn't wait on the owner. Once the back-walk PR is in, merge main here so this diff is only the image step.

Our review of this head keeps running; its back-walk findings will go on the new PR.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, I'll go with (c). I'll open the back-walk fix as its own PR on current main, from the back-walk commits alone, with a main-vs-PR ABBA: a local disk no worse, and a warm SSHFS image at most the pre-#2627 cost (1.9 s in the lab, measured in the same run). Once it's in, I'll merge main here so this diff is only the image step. If the warm SSHFS image stays over 1.9 s because of #2627's coarse-time bytes check (SFTP reports whole seconds), I'll show that part of the time separately rather than loosen the check.

…k cuts where its probe's bytes end

The backward walk's first window begins with the bytes its probe read of the call's line; here the
window's own read begins inside the call's id. The id is found only by the search across the edge.
@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

The two checks I said were still running have finished on the final head, 003b02d. That head adds only a test, a call id cut where the back-walk probe's bytes end, to the code your review is running on.

  • Seeded fuzz with 77f8902's conversation.ts as the reference, seeds 2627 and 1–10: no differences. check fast: 10871 pass, 0 fail.
  • SSHFS, 18 MiB, interleaved with main: warm 2321 [2070–2976] ms against 3524 [3178–3993] ms. A page of 24 took 37.4 s with health max 558 ms, against main's 64.0 s with health max 9.4 s.

The description has the rest. The back-walk PR comes next, as you asked.

@devswha

devswha commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Merge-pass review of 4b6c8d1/003b02db (Codex Terra xhigh + our own repros and measurements; the omo review will run on the next head). No correctness HIGH or MEDIUM. Thanks @duytbp, the fuzz and tests hold up: 0 differences from main in 656 lookups, and the new edge test fails when its match is removed.

Back-walk (main + e1bef63, 222b40a, c220c27 alone):

Image step:

  • No 503/404 on a page of 24 (1,152/1,152 served); event-loop block during a slow-mount lookup 2-5 ms vs 98-139 ms; shared reader; Windows VM 45/1/0 and the two test files 67 pass / 13 skip / 0 fail (the skipped rename tests fail on main too); smoke-windows with the picture fetch passes. Warm, page of 24 and appends are all better than main.
  • Local regression (blocks): the first image is +6.5 ms median (+5.4%) and +18 ms p95, n=30 per side per order, both orders. About 5 ms of it is the first lease's filesystem (statfs) lookup at transcript-reader.ts:213-232; doing that once ahead of the first lookup should close it. Please include a first-image-only ABBA, no worse than main.

LOW, for the description's known limits (no change needed): a request-time began lets a queued lookup reuse a check made before a same-size in-place rewrite (needs held times); a busy reader becomes a 404 at 34+ concurrent reads of different transcripts; the path check skips ctime between two stats (main has a matching window); a hung read holds only its own transcript's queue (main blocks the server). Also on main: appends every 50 ms or less on a 50 MB transcript make every lookup return null.

@devswha

devswha commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Update @duytbp: the whole-second-mount remainder on the back-walk fix is accepted (2011 ms against 1633 ms before #2627). It comes from #2627's bytes check, which stops a wrong picture, and it is still well under main today (~3.5 s), so it goes in the merge comment as a known limit; you don't need to chase it. The two local regressions still need to come back to no worse before either part merges: the warm page of 24 on the back-walk PR (your bisect) and the first image on the image step (the statfs pre-warm), each with a main-vs-PR ABBA.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough pass, and for accepting the whole-second remainder. Next, in order:

  1. Back-walk: I'll bisect the three commits with a process-level ABBA on a warm page of 24. Then I'll fix or drop the costly one, and open the PR with that table and the SSHFS numbers.
  2. Image step: I'll warm the reader's filesystem lookup for a transcript's directory ahead of the first image, keeping it from expiring before it's used. Then a first-image-only ABBA, main against the PR.

I'll add your LOW items to the description's known limits, including the one on main: appends every 50 ms or faster on a 50 MB transcript make every lookup return null.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

A question so I can reproduce your two local numbers. I've been bisecting the back-walk regression on a warm page of 24, process-level and rotated, with an identical-tree copy of main as the control. On my host (load 11–12) none of the three commits leaves noise: medians against main are 0.99–1.04 on the HTTP harness at 18 MiB, and 0.96–0.98 at 125 MiB.

What they do, counted, shows that on the harness's 18 MiB page, which has its call 18 MiB back over 1 MiB lines, each commit does strictly less IO:

version reads MiB event-loop turns
main 2592 531 2520
first commit 1512 503 1440
head reuse 1080 503 1440

The one added cost I found is in the head-reuse commit, on a page whose calls are near their results: one extra setImmediate turn per window (60 against 48 on #2627's big fixture), because linesWithSteps yields between the known head and the first read. I'm removing that yield.

Could you share the fixture behind your ~560 → ~585 ms page (size, and how far back its calls are) and how you run it? And for the first image's +6.5 ms: in process I measure the first lease's statfs + stat at about 0.1 ms and its async open at about 0.3 ms, so I'd like to know whether your 5 ms comes from the HTTP path or your VM's filesystem. A script or command line would let me check against exactly what you saw.

@devswha

devswha commented Nov 3, 2026

Copy link
Copy Markdown
Owner

Sure @duytbp, here is the harness: https://gist.github.com/devswha/1b798f5a8c475af4294536df2dfbe1e1 (bench.ts, abba-page15.sh, abba-first.sh, summarize.ts).

  • Fixture: bench.ts builds it when the file is missing. It holds a prompt, then 24 tool calls, then ~50 MB of 256 KiB progress lines (200 of them), then the 24 results with a picture each. So every call is ~50 MB before its result, in 256 KiB lines rather than your harness's 1 MiB lines. That is the case where your extra setImmediate turn per window would show, so removing that yield may be the whole fix.
  • How it runs: in process, not over HTTP: bun bench.ts <repo> <first|warm|page15|append> <fixture> calls transcriptImageAsync directly, one fresh Bun process per sample. The scripts run them ABBA (A B B A blocks): 6 processes per block for page15 (a warm page of 24, measured 15 times per process) and 30 for first. Usage: bash abba-page15.sh <tag> <repoA> <repoB>, then bun summarize.ts abba-<tag>.jsonl.
  • Host: this PC's local NVMe ext4, not a VM; the first-image number is in process too. If statfs + stat costs you 0.1 ms, the ~5 ms we saw may be the first trip through the thread pool (the open and the filesystem lookup queued behind it) rather than the calls themselves, but that is a guess, so please check it with abba-first.sh.

…straight into its buffer on the shared reader

A range longer than a lease's window (the boundary scan reads 16 MiB at a time) was read a window
at a time into the lease's buffer and copied out into a buffer allocated zeroed: on a transcript's
first picture, 16 MiB copied and zeroed that the synchronous read before did not copy. Each window
is now read straight into its place in a buffer that is not zeroed; what a short read leaves at the
end is cut off as before. The reader's `read` takes the buffer to read into.

The bytes, and the windows they come in, are the same: the scan's carry, its digest and its
handling of a record longer than it keeps are unchanged. Measured, a fresh process's first picture
of an 18 MiB transcript: 73.0 ms on the parent, 65.7 ms here, 61.3 ms on main (18 rounds).
@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, that helps. I'm running your harness now: page15 main against the back-walk branch, first main against this PR, and firstwarmfs to test your thread-pool guess. Results to follow.

Meanwhile I've pushed 0468f15 to fix the cause I found for the first image. statfs isn't it: it costs about 0.1 ms here. The boundary scan reads 16 MiB at a time, and on the shared reader that went through streamBytes' multi-window path. That path allocated a zeroed 16 MiB buffer, read 16 lease windows, and copied each one into it. Main's single readSync does neither the zeroing nor the copy. Each window is now read straight into its place in a buffer that isn't zeroed. On my in-process harness, a fresh process's first picture of an 18 MiB transcript takes 61.3 ms on main, 73.0 ms on 003b02d and 65.7 ms on 0468f15 (18 rounds). That recovers about 7 of the 12 ms. My guess for the remaining ~4 ms is the lease's own setup (~1.5 ms) plus the awaits per window. Your firstwarmfs mode should tell us whether it's really the first trip through the thread pool.

The back-walk fix will be its own PR, on current main, once its gate finishes. The yield per window is already gone there, and a scratch buffer replaces the allocation per piece that caused the warm-page regression.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

The back-walk fix is now #2668: three commits on current main, with your page15 numbers and the SSHFS ones in the description. On your fixture its warm page of 24 is level with main (470.7 against 480.6 ms pooled, n=168 each, with the spread between blocks around 30 ms). On lines of a MiB it's about 0.9× main.

On this PR's first image, your harness puts 0468f15 ahead of main in one run and behind in another, so it isn't settled. Each version was merged onto main 4bc043d, 30 processes per block, A B B A:

run load main PR
003b02d (before read-into) 13 133.2 ms 156.0 ms
0468f15 quieter 105.8 ms 100.3 ms
0468f15, rerun 13–15 130.3 ms 140.6 ms

So read-into recovers just over half of the gap, but under load the PR is still 8–14 ms behind. firstwarmfs doesn't move the PR's time (102.0 ms against 100.3), so a first trip through the thread pool doesn't look like the cause. My current guess is the 16 awaited 1 MiB reads of the boundary scan, against main's single readSync, which cost more when the pool is contended. I'm trying a single read into the caller's buffer and will post a run of the three versions together, all under one load.

…in a row, not the first

A lease on a local disk left the event loop for the thread pool once one call there was slower than
SLOW_MS. A garbage collection of a few ms that lands inside a call made it slow too, and sent the
rest of the lease through the thread pool: a pause of the process taken for slow storage. Now the
second slow call in a row does it, and a fast call in between starts the count again. A pause is a
one-off; a disk that does not have the transcript cached is slow again on the next call. The cost:
a slow local disk blocks the event loop for one more call before the lease leaves it. SLOW_MS, the
time a slow transcript's leases go through the thread pool and a call that throws are unchanged.

Measured: a fresh process's first image lookup in a 52 MB transcript at load 13 left the event loop
in 55 of 180 lookups before (a full collection of about 3 ms inside the first read after the first
16 MiB was scanned), and those took 140 ms against 120 ms; now in none. Over 6 rotating rounds of
30 processes the lookup is at main's time (median 127.2 ms both, 0.98x per round). Over SSHFS
nothing changes: the transcript is read through the thread pool from the start (no read on the
event loop, 63 through the pool), as before.
@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

I found the rest of the first-image gap, and it isn't storage. I pushed 62a9765 for it, but it changes a rule in the reader from #2616, so please check that you're happy with that.

Cause. On a local disk, a lease reads on the event loop and switches to the thread pool for the rest of the lease after the first call slower than SLOW_MS (2 ms). In about 30% of fresh-process first lookups on your fixture, a full collection of about 3 ms lands inside one of those calls, the first read after the first 16 MiB is scanned. BUN_JSC_logGC=1 shows the collection inside the slow call, and the read itself takes under 1 ms. Timing only the native call doesn't help, because Bun's fs.readSync runs JS around the native read and the collection lands there too. So the lease took a pause of the process for slow storage and did its remaining ~140 reads through the pool. Those lookups took about 140 ms against 120 ms. Main reads with readSync throughout, so it pays the same collection without any switch.

Change. The second slow call in a row switches; a fast call in between resets the count. A collection is a one-off, while a disk that hasn't cached the transcript is slow again on the next call. The cost is that a slow local disk blocks the event loop for one more call (≤ 1 MiB) before the lease leaves it. SLOW_MS, the 1 s slowed(path), a call that throws and slow opens are unchanged. Network filesystems are unaffected: near() returns a device only for a LOCAL filesystem type, so anything else reads through the pool from the first call. On the SSHFS lab both versions do 0 event-loop reads and 63 pool reads per lookup (1565 against 1549 ms).

Your harness, first, one rotating run of 6 rounds × 30 processes per version, each version merged onto main 4bc043d, load about 13, 0 nulls:

version median p95 per-round ratio to main
main 127.2 ms 145.9 ms 1
0468f15 (read-into) 129.2 ms 158.7 ms 1.002 [0.984–1.037]
62a9765 (this change) 127.2 ms 144.0 ms 0.981 [0.963–1.030]

Lookups that left the event loop, from a separate counting run (180 each): 55 on 0468f15, 0 on 62a9765.

statfs isn't on the critical path either. In a trace, the lease's statfs, stat and open run concurrently for about 0.3 ms of wall time, and the PR reaches its first read about 4 ms sooner than main does (4.3 against 8.9 ms).

For the record, the order of the earlier runs: 003b02d was +23 ms against main at load 13, and read-into (0468f15) recovered most of that by reading straight into the scan's buffer instead of a zeroed 16 MiB copy. This change removes the rest.

Tests: new "leaves the event loop on the second slow call in a row, not on one alone" (slow-fast, slow-slow and slow-fast-slow patterns, stall injected through the into buffer), and the three existing slow-read tests now use two slow reads. Removing the reset on a fast call fails the new test. check fast on 62a9765: 10874 pass, 0 fail, 41 skip; typecheck and build ok. The transcript-reader, claude-images and conversation tests: 273 pass.

If you'd rather keep "first slow call switches" as #2616 has it, the alternative is to accept read-into without it. That's between level and +10 ms across our runs, about +2% in the rotating ones, and worse under load. Your call.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

For completeness: I ran your page15 on this PR too (62a9765 merged onto main 4bc043d). Until now your page15 numbers were for the back-walk fix on its own, #2668. One rotating run under one lock, 6 rounds × 6 processes per version, load about 12, 0 nulls:

page of 24 main this PR per-round ratio to main
warm, median (14 per process) 537.0 ms 522.1 ms 0.968
cold, median (fresh process) 1825 ms 622 ms

The cold page is about 3× faster, because the 24 lookups take turns on the reader instead of each running its own boundary scan. The third version in the run was this PR plus #2668's skipped yield after the probe's bytes. It came out at 0.992 (warm median 527.2 ms), so it buys nothing here and I've left the PR as it is. When #2668 lands I'll merge main in and keep this PR's lease reads over #2668's scratch buffer.

So on your harness the two regressions you asked about are gone. The warm page of 24 is 0.97× main here (and #2668's is level with main), and the first image is at main's time with 62a9765. The open question is whether you're OK with the reader's two-slow-calls rule in 62a9765.

@duytbp

duytbp commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

Your summarize.ts on that same run also shows the event loop. Median of the longest gap per page, with each version's pair against main:

page of 24 main this PR
warm, loop max (both orders) 22–24 ms 4.6–4.9 ms
cold, loop max 374 ms 25–26 ms

The PR is ahead of main in both orders on the warm page (median 530.7 against 553.7 and 511.5 against 519.2 ms), and its p95 is lower (611/582 against 655/645 ms). 0 nulls of 12960 on each side.

@duytbp

duytbp commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@devswha a friendly nudge when you have a moment. On your harness this PR is now level with main on the first image and a little ahead on the warm page of 24, with the event loop's worst stall under 5 ms instead of 22–24 ms (details in my last few comments). The one open question is whether you're OK with the reader leaving the event loop on the second slow call in a row instead of the first (62a9765). If you'd rather keep #2616's rule, I'll drop that commit.

This head, with #2668, has been running on my fork's main across my PCs since this morning with no issues. I'd love to get both upstream so I can go back to the official release.

devswha added a commit that referenced this pull request Nov 5, 2026
…'s backward call search (#2668)

## Summary

#2627's backward call search made a warm tool picture over network
storage cost more than it did before #2627: 3.5 s against 1.9 s for an
18 MiB transcript over SSHFS. It looks for the start of the line each
backward window cuts 64 KiB at a time, and each read is a round trip
there. This PR restores that cost. It's split out of #2610 as you
suggested and doesn't depend on the shared reader.

Three commits, all in `server/conversation.ts`, each with a test in
`server/claude-images.test.ts`:

1. **Growing pieces into one scratch buffer.** The walk finds a cut
line's start in pieces that double, from 64 KiB up to a search window.
Each window is twice what the one before it covered. The pieces are read
into one buffer per walk (`readStreamInto`). Which lines are judged, and
in which order, is unchanged.
2. **No copy in `linesWithSteps`.** Each piece of a line is searched
alone, and so is the window's cut tail joined with the piece's first
`span` characters. A line longer than a window is no longer copied onto
the tail. The pattern has no lookarounds and `span` is its longest
match, so what is found is unchanged.
3. **Head reuse.** A window begins with the bytes the probe already read
of its line, from the scratch buffer, with no step between them and the
window's own read.

## The warm-page regression you saw

You measured a warm page of 24 at +4–7% on the earlier version. I
bisected it with a process-level ABBA, 12 rounds with rotating and
reversing order. Median per-round ratio to main, wall / CPU:

| version | 18 MiB page | 125 MiB page |
|---|---|---|
| control (main's tree) | 0.97 / 0.97 | 1.00 / 1.01 |
| growing pieces, as first pushed | 1.11 / 1.15 | 1.17 / 1.20 |
| growing pieces + scratch buffer | 0.95 / 0.94 | 1.03 / 1.00 |
| first version + no yield | 1.16 / 1.26 | 1.23 / 1.35 |
| this PR (no yield + scratch buffer) | 0.89 / 0.86 | 0.87 / 0.83 |

The cause was the growing probe allocating a fresh zeroed buffer for
each piece, up to 1 MiB. A line of a MiB cost about 2 MiB of allocation
every time a lookup crossed it. The extra `setImmediate` per window is
also gone.

## Measurements

**Your harness** (your gist and fixture, A B B A, 6 processes per
block), `page15`, main 4bc043d against this PR:

| page of 24 | main | this PR |
|---|---|---|
| warm, pooled median (n=168) | 470.7 ms | 480.6 ms |
| cold, pooled median (n=12) | 1681 ms | 1796 ms |

Block medians are 489.1, 464.5, 486.9 and 456.1 ms, so the ~30 ms spread
between blocks is wider than the gap between sides. Cold disagrees
between orders. On 256 KiB lines the walk does main's 132 reads and 48
turns per page, so there's nothing to gain or lose there. 0 nulls of
4320 on both.

**Lines of a MiB, in process** (process-level ABBA, 12 rounds), median
ratio to main [IQR]:

| version | 18 MiB wall | 18 MiB CPU | 125 MiB wall | 125 MiB CPU |
|---|---|---|---|---|
| control (main's tree) | 0.980 [0.939–1.038] | 1.010 [0.954–1.066] |
1.009 [0.995–1.026] | 1.008 [0.995–1.025] |
| this PR | 0.885 [0.837–0.995] | 0.860 [0.799–0.940] | 0.907
[0.876–0.946] | 0.862 [0.841–0.906] |

**HTTP harness** (20 repeats, warm gallery, load 12–14), medians in ms:

| size | case | main | control | this PR |
|---|---|---|---|---|
| 18 MiB | first image | 200 | 183 | 183 |
| 18 MiB | warm image | 24.1 | 23.1 | 23.8 |
| 18 MiB | warm page of 24 | 627 | 587 | 528 |
| 125 MiB | first image | 378 | 359 | 381 |
| 125 MiB | warm page of 24 | 1897 | 1883 | 1677 |

All 200, all bytes matching.

**Reads per lookup** (deterministic):

| version | warm far-call picture, 18 MiB | page of 24, 18 MiB: reads /
MiB / turns |
|---|---|---|
| main | 108 | 2592 / 531 / 2520 |
| this PR | 45 | 1080 / 503 / 1008 |
| before #2627 | 42 | |

**SSHFS** (the network lab; 2 runs × 7 repeats at 18 MiB, 2 × 4 at 125
MiB), medians in ms:

| size | case | main | this PR | before #2627 (05c9133) |
|---|---|---|---|---|
| 18 MiB | warm image (n=14) | 3482 | 2352 | 1909 |
| 18 MiB | first image (n=7) | 6888 | 5585 | 5623 |
| 125 MiB | warm image (n=8) | 13464 | 10100 | 7206 |
| 125 MiB | first image (n=4) | 21188 | 18187 | 18786 |

A warm image takes 0.68× main's time at 18 MiB and 0.75× at 125 MiB, and
the first image is back to pre-#2627's level. What's left of the warm
gap is the whole-second remainder you accepted on #2627: SSHFS gives
whole-second change times, so those lookups still check their bytes.
Worst `/api/health` stall is the same on every version: about 1.8 s on
the first image (from `scanParent` and `planState`, not images) and
0.4–0.5 s warm. All requests 200.

## Checks

- `bun run check fast` on 93da2e0: 10886 pass, 0 fail, 41 skip.
Typecheck and build ok.
- `claude-images.test.ts` and `conversation.test.ts`: 235 pass.
- Fuzz with 400 rounds each, seeds 2627 and 1–10: no differences against
main 4bc043d's module, and none against the plain search.
- Dropping the edge re-test (`hit = pattern.test(piece)` alone) fails
both edge tests.

## Known limit

As accepted on #2627: a version whose change time has whole-second
precision falls back to the search.

---------

Co-authored-by: devswha <[email protected]>
# Conflicts:
#	server/conversation.ts
… on the shared reader

The lease's path check compared identity, size and modification time only, so a same-size rewrite that put the modification time back, landing between the last stat of the pinned file and the path's, was served. TranscriptFile.pathStats gives the path's whole stat, and the check is sameImageFile again, as on the synchronous path.
…e event loop

With the second slow call in a row leaving the event loop, a fast stat between two slow reads reset the run: command history stats its file every window, so a slow local disk kept every window's read on the event loop. A stat now ends a run only when it is slow itself; only a fast read of the bytes resets it.
@devswha

devswha commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Thanks @duytbp. I took this the rest of the way on your branch: no force push, three commits on top of 62a9765.

What I changed

Checked

  • Bug on main: a FUSE passthrough that adds 20 ms to each read, with an 18 MiB transcript. The first lookup's longest event-loop stall is 513 ms on main and 25-31 ms on this branch (warm: 41 vs 3-35 ms, on a loaded host).
  • Supply chain: no dependency, lockfile, workflow or install-script changes. The smoke writes only into its temp home and fetches loopback.
  • bun run check fast on ca5751f: 11437 pass, 0 fail. The image, reader and command-history test files: 138 pass.

Left as known limits

  • An image lookup holds its transcript's lease for the whole lookup, so a command-history read of the same file can time out behind a lookup slower than 10 s (a slow network home). It retries a second later. Main blocks the whole server there instead. Follow-up: Command history of a Claude transcript can time out behind a slow image lookup on the shared reader #2874.
  • imageTurns has no cap and is not cancelled when a client disconnects (LOW, not reproduced; main doesn't cancel either).
  • A hung read holds its own transcript's queue (LOW; main blocks the server).

@devswha

devswha commented Nov 5, 2026

Copy link
Copy Markdown
Owner

Thanks @duytbp! The stall reproduced on main with a slow mount (513 ms vs about 30 ms with your change). We merged main in and added two small fixes (ctime in the path check, slow-read streak), each with a failing-first test. Merging. A related slow-mount case is tracked in #2874.

Merge note: external PR; supply-chain check done; omo CLEAR at this head; Codex findings fixed; required checks green; CodeRabbit skipped.

@devswha
devswha merged commit 47d8eb9 into devswha:main Nov 5, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants