Skip to content

fix(files): read the disk for the file routes on bounded background threads (#790) - #2256

Merged
devswha merged 4 commits into
mainfrom
perf/file-access-workers
Oct 28, 2026
Merged

devswha merged 4 commits into
mainfrom
perf/file-access-workers

Conversation

@devswha

@devswha devswha commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

Closes #790.

Problem

The file routes made every filesystem call on the server's only thread: a file's stat and text
sniff (fileInfo), the Unicode-form name scan, the realpath containment check, the 5,000-entry
folder walk for a bare name, the whole HTML page render with its local files embedded
(pageWithLocalFiles), and Bun.file streaming, whose sendfile also runs on that thread. While one
of them waited on a slow or stalled disk (a network share, sshfs, a stalled NFS mount) or rendered a
large page, every terminal stream, WebSocket and HTTP request on the server waited with it.
Reproduced on main with a FUSE passthrough mount that waits 100 ms before each call: one stat held
the loop for 0.7 s, one name lookup for 7.1 s.

Change

  • server/file-pool.ts: at most 4 worker threads (server/file-worker.ts), one task each, at most
    64 waiting. A task has a deadline, waiting included: 3 s for one call (stat, sniff, realpath,
    open), 15 s for a task of many (a folder walk, a page render). With no room, or past the deadline,
    the request is answered 503 file_busy with retry-after: 1, never queued without bound. A thread
    past its deadline stays taken until its call actually returns (a thread cannot be stopped inside a
    system call), and a descriptor its late answer opened is closed, never handed out.
  • server/file-tasks.ts: the steps the routes ask a thread for (info, named, within, walk,
    render, open). file-view.ts's functions stay synchronous and are what the thread runs.
  • fileResponse (now async) renders a page on a thread; the page-media addresses that render mints
    come back as grants and are kept on the server's thread (keepPageMedia), with the same lifetime,
    cap and client binding; a device revoked or a client signed out while its request was finding or
    drawing the page gets none of that render's addresses (forgetPageMedia is numbered, the request
    notes the number when it begins, and a forget is kept exactly as long as a request begun before it
    is under way; no clock involved). On main a revocation during the file lookup's awaits had the
    same hole; this closes it too.
  • A plain file is opened on a thread, and everything before its headers runs in that one task,
    bounded by its deadline and ended at once when the client goes away (request.signal): the
    range (byteRange: GET Range, HEAD, 416), and a body of at most 256 KiB (or a range that short),
    read whole and sent with its Content-Length. A larger body is sent as a Bun.file slice, with
    its Content-Length and Content-Range exactly as on main, when opening, describing and reading
    its first 64 KiB took under 50 ms. From a disk slower than that it is streamed from the opened
    descriptor with asynchronous reads instead, so that disk never holds the server's thread. Bun
    sends every stream body chunked, without a length (checked on the wire, whatever headers are
    set), and reads a Bun.file body on the server's thread, so on a slow disk the length is the
    price of staying responsive.
  • A descriptor a thread opened is never lost: a late answer's is closed, and so is one whose thread
    failed or was ended before answering (the thread names it in a shared cell as soon as it opens).
  • Paths, MIME/kind rules, auth, CSP, sandboxing, download disposition, ambiguous-name 409 and the
    scratch-folder fallback are unchanged. No herdr RPC, attach, focus or takeover code is touched.

Measurements

bun scripts/bench-file-access.ts --runs 7 --slow-root <mnt> (added here): the server in a child
process (port 0, mkdtemp state dir, a stand-in herdr socket), an unrelated /api/health probed every
5 ms from its own thread, the server's event-loop lag sampled every 5 ms, and the file requests' own
time. "Slow mount" is a FUSE passthrough that waits 100 ms before each getattr/readdir/open/read.
Median [min-max] of 7 runs, run through dori heavy on a quiet host (128-core P620): main 84824f1
at 74% -> 52% CPU idle, this PR's head 0a063e2 at 68% -> 63% idle.

case max loop lag, main max loop lag, PR slowest /api/health, main slowest /api/health, PR file request, main file request, PR
stat a file on a slow mount (x4) 709 [607-719] 0.6 [0.1-1.5] 919 [817-926] 1.4 [0.8-1.5] 922 [820-930] 304 [302-403]
find a name in a slow mount (x2) 7106 [7088-7227] 13 [4.3-40] 7107 [7093-7228] 14 [6.3-50] 15526 [15290-15610] 8493 [8458-9164]
project icon on a slow mount (x2) 3745 [3637-7412] 20 [7.5-109] 7379 [7267-7502] 24 [7.3-138] 7384 [7272-7506] 6743 [6692-6862]
stream 2 MB from a slow mount (x2) 1326 [1318-2648] 3.0 [0.9-6.7] 2650 [2636-2671] 3.4 [2.2-7.5] 2651 [2641-2676] 1445 [1431-1553]
render a page with 28 MB of local files (x2) 311 [224-535] 63 [40-109] 540 [429-678] 57 [39-107] 672 [496-855] 411 [327-458]
find a name in a local 5,000-file folder (x2) 12 [8.7-18] 0.6 [0.1-1.9] 19 [11-28] 1.6 [0.3-3.4] 36 [30-47] 19 [18-24]
stream a local 512 MB file (x2) 5.9 [4.2-18] 2.4 [0.7-5.2] 20 [7.9-38] 6.6 [4.0-10] 1975 [1146-5707] 961 [817-1322]
stat a local file (x4) 0.0 [0-0.3] 0.0 [0-0.1] - - 1.2 [0.6-3.7] 0.9 [0.6-22]

All times in ms. The local 512 MB file is sent with its Content-Length, as on main (its disk answers at once); the 2 MB file on the slow mount is streamed without one.

Known trade-offs and limits

  • A body of more than 256 KiB from a disk that took 50 ms or more to open, describe and read its
    first 64 KiB (a network share, sshfs, a stalled mount) is sent chunked, without Content-Length,
    so its download shows no total size. From any other disk it is sent with its length, as on main.
    A disk that was fast for that probe and stalls afterwards stalls the server as it does on main.
  • The file threads are held by each server (holdFilePool) and ended when the last one stops.
  • Four threads stuck in calls that never return make every file route answer 503 until those calls
    return, local files included; the rest of the server keeps answering. The browser shows the 503
    as the file's error, with no automatic retry yet.
  • A descriptor-level stall after the headers (a read on a stalled mount) waits on Bun's own I/O
    threads, not the file threads, and ends when the client goes away.
  • A thread ended in the instant between open returning and it naming the descriptor would lose
    that descriptor. Only the test seam setFilePoolOptions ends a busy thread; production never does.
  • Not moved here (LOW, follow-up): pageMediaResponse (a rendered page's video too large to embed)
    still opens and authorizes on the server's thread, and checks the descriptor synchronously per
    chunk; a video kept on a slow share via OVIS_MEDIA_ROOTS can still stall it.

Reviews

omo-native-code-reviewer: PASS, three MEDIUM, all addressed (small files lost content-length;
the header comment overstated what moved, page media now documented as a follow-up; dead code
removed). Codex Sol 6.1 Fast xhigh, round 1: FAIL with one HIGH, a revocation undone by a render
in flight, fixed with a test that fails before; one MEDIUM, a descriptor leaked when a thread is
ended mid-open, fixed with a test that fails before; one LOW test timing assumption, fixed.
Round 2 (final, on the delta): FAIL with one HIGH, the revocation snapshot taken after the file
lookup rather than before it (a hole main also has); now taken when the request begins, with a test.
Three MEDIUM: the forget memory was kept by wall-clock time (now by the requests under way); a
descriptor the thread closed itself could be closed again by abandon after reuse (now one
compare-and-swap decides who closes); a thread ended between open and publishing its descriptor
leaks it (test seam only, listed above). The fixes after round 2 were not reviewed by Codex again
(the policy's last-round rule); the merge pass reviews them.

Merge pass on 689260e (omo + a behaviour/FUSE reviewer): BLOCK, fixed in 0a063e2. H1: small
bodies and short ranges were read after the thread answered, with no deadline and no abort; now
read on the thread inside the deadline, with every task ended by request.signal and a descriptor
still in use closed only when its thread answers. MEDIUM: bodies over 256 KiB lost
Content-Length; now kept from any disk that answers at once (above). M1: the pool outlived
createServer().stop(); now ended when the last server stops. M2: the pool tests polled with a
sleep; they wait on the fake thread's Atomics.notify. L1: the header comment now says which bodies
are read whole. The pre-existing scratch-folder containment race the merge pass reproduced on main
is filed separately as #2259.

Merge pass on 0a063e2: H1, M2, L1 verified, the slow-disk length case accepted; one new HIGH from
the M1 fix, fixed in 3788a0f: stopping the last server closed a thread's descriptor while that
thread could still be reading it, so its number could be reused under the read. Tasks are still
refused at once on stop, but the descriptor is now closed on the thread's close event, which Bun
sends only after a blocked system call returns (checked: a thread blocked in a FIFO open gets
close only once the open returns). The test stops the server while the thread is blocked inside
the read and fails with the old order.

Tests

  • server/file-pool.test.ts (new), with a stand-in thread (server/file-worker.fake.ts) that can
    hold an answer: refusal past the threads and waiting places, a deadline that keeps the thread taken
    until the call returns, a late answer's descriptor closed, a request abort that refuses at once
    while the thread's descriptor stays open until it answers, the open task reading small bodies and
    ranges itself and handing over only a slow disk's large one, a walk given the longer deadline, the
    threads ended when the last server holding them stops, a descriptor kept open (and its number
    unused) while its thread is blocked inside the read at stop, closed once the thread is gone, a
    waiting task refused at its deadline, and every task on a real thread.
  • server/file-routes.test.ts: 503 file_busy while the thread is stuck and /api/health answers
    meanwhile; an open held past its deadline answered 503; Range/HEAD/416, and the exact
    Content-Length of a large whole file and a large range (fails on 689260e); a page rendered on a
    thread whose video plays from the address that render gave out. server/file-view.test.ts: a
    slow disk's large file streamed from its descriptor, whole and by range, and closed once sent.
  • server/file-view.test.ts runs its tasks inline (its pageFileHooks reach only the thread they
    are set on); calls updated for the async fileResponse, and a test now cancels the bodies it does
    not read (each holds a descriptor).
  • Mutations: removing the thread cap fails 4 tests; dropping the late-descriptor close fails 1.
  • bun run check fast on 0a063e2: typecheck, build, generated files and 8,178 unit tests pass,
    0 fail. On 3788a0f: all pass, 8,179 unit tests, 0 fail. (Earlier heads each had one unrelated flake: server/omp.test.ts "an empty or trailing
    --cwd", which fails 1 in 5 on unchanged main, and a scripts/self-hosted-runner.test.ts timeout
    at load 82 that passes alone.)
  • The bench itself caught a regression in this branch before review: a slow-mount folder walk takes
    6-7 s, so a 3 s deadline turned a slow-but-working lookup into a 503; walks now share the 15 s bound.

…790)

scripts/bench-file-access.ts runs the server in a child process against a stand-in herdr socket and, while file requests run (a rendered page with 28 MB of local files, a name lookup in a 5,000-file folder, a 512 MB download, and with --slow-root the same on a slow mount), measures an unrelated /api/health latency from its own thread, the server's event-loop lag, and the file requests' own time: median and spread over --runs.
…hreads (#790)

A file's type and size, a folder walk for a name, a page rendered with its own files and a file opened to stream each ran synchronously on the server's thread: a slow or stalled disk (a network share) or a large page held every terminal and request until it returned. They now run on at most four worker threads (server/file-pool.ts), with a bounded wait, a deadline (3 s for one call, 15 s for a walk or a render) and 503 file_busy when none is free in time. A thread past its deadline stays taken until its call returns, and a descriptor its late answer opened is closed. Plain files stream from that descriptor with asynchronous reads and the existing Range handling instead of Bun.file, whose sendfile runs on the server's thread.
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 1 minute.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between adfdef6 and 3788a0f.

Files selected for processing: 14
  • changelog.d/file-access-threads.md
  • scripts/bench-file-access.ts
  • server/file-pool.test.ts
  • server/file-pool.ts
  • server/file-routes.test.ts
  • server/file-routes.ts
  • server/file-tasks.ts
  • server/file-view.test.ts
  • server/file-view.ts
  • server/file-worker.fake.ts
  • server/file-worker.ts
  • server/files.ts
  • server/http.ts
  • server/index.ts
  • 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

Comment @coderabbitai help to get the list of available commands.

…ownload's length, end the threads with the server (#790)

Review of #2256. A body of at most 256 KiB, and a short range of a large file, were read on the server after the file thread answered, with no deadline and no end when the client left: they are now read on the thread, inside the task's deadline, and every file task ends at once when its request is aborted (a descriptor its thread still uses is closed only once it answers). A larger body is sent as a file again, with its Content-Length and Content-Range as on main, when its disk answered within 50 ms; only from a disk slower than that is it streamed from the descriptor, without a length, so a stalled share still never holds the server's thread (Bun sends every stream body chunked). The file threads are held by each server and ended when the last one stops. The pool tests wait on the fake thread's Atomics.notify instead of polling, and the file-view header comment says which bodies are read whole.
… its thread is gone (#790)

Review of #2256 at 0a063e2. Stopping the last server failed each file task at once and also closed the descriptor its thread had opened, while that thread could still be inside a read of it: the number could be handed out again under the read. Tasks are still refused at once, but a descriptor a thread owned is now closed on that thread's close event, which Bun sends only after a blocked system call has returned. The test stops the server while the thread is blocked inside the read (a FIFO open in the read seam, which ending a thread cannot cut short) and checks the descriptor stays open and its number unused until the thread is gone.
@devswha

devswha commented Oct 28, 2026

Copy link
Copy Markdown
Owner Author

Merging 3788a0f after three review rounds (final round under the cap: merge unless a HIGH is reproduced). Codex was at capacity, so an omo reviewer on gpt-6.1-sol and an independent second reviewer reviewed it. What it fixes (#790): every filesystem call of the file routes ran on the server's only thread, so a slow or stalled disk stalled every terminal stream and request. Measured on a slow FUSE mount, the worst health-check latency during a file request went from 105 ms, 917 ms and 13.8 s to 11 ms, 13 ms and 40 ms; statuses, types and bodies match main; the pool keeps 4 threads and 64 waiting, then answers 503 file_busy. Rounds: round 1 found that small bodies were read before the headers with no deadline or abort handling (HIGH), that stop() left the threads alive, that tests polled with Bun.sleep, and that large downloads lost Content-Length. Round 2 fixed those, but stopping the server closed a descriptor under an in-flight read and its number was reused (HIGH). 3788a0f closes a thread's descriptor only on that thread's close event: with a read blocked inside a FIFO, stop() refuses the request in about 1 ms while the descriptor stays open and unused until the thread is gone; the new test fails with the old order. Accepted by the maintainer side (Dori) as a trade-off: bodies over 256 KiB keep their exact Content-Length/Content-Range as on main when the disk answers open+stat+64 KiB in under 50 ms; only from slower disks do they stream chunked without the total size (main stalls the whole server on such a disk). Direct file links opening any file the server user can read is the existing contract; the scratch-folder symlink race is #2259. Not filed (not user-visible): a syscall that never returns keeps its descriptor and thread until process exit, and repeated in-process stop/start cycles are not bounded in total (server/file-pool.ts ~80-98, ~201-205); the FIFO test signals before entering the blocking open and has no timeout on its writer open (server/file-worker.fake.ts ~25-29, server/file-pool.test.ts ~157-180); that test assumes POSIX mkfifo (~160).

@devswha
devswha merged commit d75d738 into main Oct 28, 2026
19 of 20 checks passed
@devswha
devswha deleted the perf/file-access-workers branch October 28, 2026 14:14
devswha added a commit that referenced this pull request Oct 28, 2026
…ed in its folder (#2259) (#2265)

Closes #2259

## Problem

The Claude Code scratch-folder fallback of `/api/fs/stat` and
`/api/fs/file` (`findFile` → `locateFileInFolder`) checked the folder's
containment on a **path**, and `fileResponse` then followed that path
**again** (`Bun.file(info.path)`). A symlink put in place of the file
between the check and the open served a file outside the folder. The
file viewer made the window wider still: it asks `/api/fs/stat` by the
name, then fetches `/api/fs/file` by the absolute path that answered,
which matched exactly and was served unconfined.

## Change

Built on #2256 (file reads on bounded file threads). Open first, then
check what was opened, with the helper rendered pages already use for
their own files (`openAuthorized`: `O_NOFOLLOW | O_NONBLOCK`, then the
opened descriptor's kernel path from `/proc/self/fd/N` on Linux, owned
non-group/other-writable folders on macOS), on the file thread:

- `locateFileInFolder` describes a single file (size, modification time,
text/binary sniff) on a file thread (`describe` task, `describeWithin`)
from a descriptor shown to lie in the folder, and returns that folder as
`within`.
- `fileResponse(..., watched, within)`: the `open` task opens such a
file through `openAuthorized` and every byte comes from that descriptor.
A small body is read before the headers as on #2256. A larger one is
never sent as `Bun.file(path)` (the "fast disk" branch would follow the
path again): on Linux with a fast disk it is sent as a file body named
by the descriptor's own path, `Bun.file("/proc/self/fd/N").slice(...)`,
which reopens the very file that descriptor holds whatever the path
names now, so the answer keeps its exact Content-Length / Content-Range;
Bun opens that path only when it sends the answer, so the descriptor is
released by a `FinalizationRegistry` once both the body and the answer
are collected, and past 256 such bodies waiting for collection one is
streamed from its descriptor instead, so held descriptors stay bounded.
On a slow disk, and on macOS and Windows (no `/proc`), it is streamed
from the descriptor (chunked), as #2256 streams every slow file. The
descriptor is named in the pool's cell the moment it is open, so a
thread ended mid-check leaves none open (`abandon`), and a refused one
is taken back from the cell before it is closed.
- A page (`render=1`) found there is drawn only when the page it opened
lies in the folder (`render` task → `pageWithLocalFiles(path, media,
grant, within)`).
- `findFile` takes a `mayBeScratch` predicate: a path that lies in the
pane's scratch folder (the viewer's second request, and a choice among
candidates) is found only there, exact and then in another Unicode form,
as the scratch fallback finds it, and never by a lookup that is not held
to the folder. A path given in full is looked for only where it points
(a missing one stays not found, as anywhere else); only a bare name is
also found deeper in the folder. `file-routes.ts` builds it from
`claudeTempBases()` (new in `claude-store.ts`), so herdr is asked for
the pane's session only for a path that can be in one.
- `rootOf`/`openAuthorized`/`openedWithin` take a `hidden` flag (default
`false`, the old behaviour for page assets) so the fallback keeps
allowing hidden names below the folder as before.

Direct file links outside the scratch folder keep opening any readable
file (existing contract). One behaviour change inside the folder: a
symlink in the scratch folder that leads out of it no longer opens by
its full path either (it already did not by its relative name).

## Verification

Rebased onto main after #2256 (d75d738); `git range-diff` showed the
first four commits unchanged from the ones reviewed on #2256's head, and
main changed none of the files they touch since. The last two commits
answer the merge pass's review of cd6cb60 (M1: a large scratch file
lost its Content-Length; M2: a missing full path matched a deeper file).

- Regression tests (`server/file-view.test.ts`, "Claude scratch fallback
served from what it opened in its folder (#2259)", and
`server/file-pool.test.ts`), deterministic: swaps happen directly or
through `pageFileHooks` hooks between the check and the open, the held
thread waits on atomics and a FIFO, no sleeps. Each fails without its
fix:
- after the file was found / between the check and the open / describing
/ a rendered page / the viewer's stat-then-absolute-path request: fail
on #2256 (the swap serves `OUTSIDE-SECRET`, the page
`<p>OUTSIDE-SECRET</p>`);
- "keeps sending the file it opened when a link is swapped in while it
is sent" (a small and a 300 KiB body): fails on #2256, whose fast-disk
branch sends the large body as `Bun.file(path)`;
- "finds a path in the folder only there, in any name form" (NFD→NFC and
NFC→NFD swaps): fails before 1947dd7;
- "sends a file larger than one read with its exact length, whole and by
range" (over HTTP): fails on cd6cb60 (no Content-Length); "finds a path
given in full in the folder only where it points": fails on cd6cb60
(served `<scratch>/sub/a.txt` for a missing `<scratch>/a.txt`);
- the cell tests for `open` and `describe`, and the pool test that ends
a thread held inside the check: fail when the cell take-back or
`abandon`'s `describe` case is removed (mutation checks); the pool test
passes 50 runs pinned to one core.
- `bun test server/file-view.test.ts server/file-routes.test.ts
server/claude-store.test.ts server/file-pool.test.ts`: 185 pass, 0 fail.
`bun run typecheck` clean. `bun run check fast`: green on e0da0aa (unit
8225 pass, 0 fail; typecheck, build, generated types and themes,
workflow syntax ok).
- HTTP, on a `Bun.serve` running the route's own steps with the real
file-thread pool against a temp scratch folder under
`<tmp>/claude-<uid>/…`: stat by name 200 → file by the returned absolute
path 200; `Range: bytes=2-4` 206 `bytes 2-4/10`; HEAD `content-length:
10`; a 300 KiB body arrives whole from the descriptor; `render=1` page
200. After swapping the three files for links outside: file, stat, the
large body and the page all 404; a direct link to the outside file still
200 (contract).
- No `REMOTE_BUNDLE_VERSION` change: only a release PR raises it.

## Reviews

omo-native-code-reviewer and Codex Sol 6.1 Fast xhigh, on the first
version and again on the port onto #2256; every HIGH and MEDIUM fixed,
final rounds PASS from both. Findings and resolutions are in the PR
comment.

## Known limits (LOW, not fixed here)

- Candidate flake in #2256's own test "keeps a descriptor its thread is
reading open until that thread is gone, when the last server stops": its
fake thread (`readGate`) says it is reading before it opens the FIFO,
and the test then opens the FIFO's writer blocking, so a thread ended in
between hangs the test (Bun's timeout cannot fire while the main thread
is blocked). Codex reproduced that gap with `taskset -c 0` in this PR's
first version of the new pool test; this PR's `authorizeGate` opens the
FIFO read-write before it says it ran and is released by a non-blocking
write, and the same change would fit `readGate`.
- On a slow disk (or macOS/Windows), a scratch file larger than one read
(256 KiB) is streamed from its descriptor without a Content-Length, as
#2256 streams every slow file; a fast disk on Linux keeps it.
- On Linux, the reopen through `/proc/self/fd/N` checks permissions
again: a scratch file made unreadable (chmod 000) after it was opened
answers 500, as does a Linux system without `/proc`. Both fail closed
(no other bytes are sent).
- When herdr cannot name the pane's scratch folder at the time of a
request (Claude exited, herdr busy, a new session), a full path into it
is a direct link like any other absolute path.
- A scratch file whose name starts with `~` or has leading/trailing
spaces is not found by its full path (the fallback's own name rules).
- A hardlink placed in the scratch folder to a file outside it is still
served: a descriptor cannot tell a hardlink, the page-asset path has the
same property, and making one needs write access to the folder and to
the target's filesystem.
- A scratch file whose name ends in ` (deleted)`, and on macOS a scratch
subfolder other users can write to, are now refused by the fallback
(same rules as page assets).
devswha added a commit that referenced this pull request Oct 28, 2026
…ading (#2296) (#2297)

Closes #2296

## Problem

`server/file-pool.test.ts` hung CI's Fast checks on run
[40779586477](https://github.com/devswha/ovis/actions/runs/40779586477)
(#2293, which does not touch it): the job was cancelled at its 10-minute
limit with this file the only one never reported.

The test "keeps a descriptor its thread is reading open until that
thread is gone, when the last server stops" holds its file thread with
the fake worker's `readGate` (`server/file-worker.fake.ts`, from #2256).
That gate said the thread was reading (`Atomics.notify` on cell 1)
**before** it opened the FIFO for reading, a blocking `open(2)`. The
test then ends the thread (`release()`) and opened the FIFO's writer
with a blocking `openSync(fifo, "w")` on its main thread. A thread ended
between the notify and its own open never opens the reader, so the
writer's open waits forever, and Bun's per-test timeout cannot fire
while the main thread is blocked in a system call. #2265's PR body named
this gap as a candidate flake.

## Change (test-only)

- `readGate` opens the FIFO read-write (an open that never waits)
**before** it records the descriptor and notifies, then blocks in a
one-byte read of it, as `authorizeGate` (#2265) already does. Once the
test sees the thread running, the FIFO always has a reader, even after
that thread is ended.
- The test releases the read with `O_WRONLY | O_NONBLOCK` and a one-byte
write, which never waits (and would fail with `ENXIO` rather than hang
if there were no reader).
- Both FIFO gates (`readGate`, `authorizeGate`, now one `holdOnFifo`)
name their FIFO descriptor in a third gate cell, and the test closes it
once the thread is gone: a worker ended inside that read never runs its
`finally` on Bun, so before this each run left 2 FIFO descriptors open
(found from CodeRabbit's review; `/proc/self/fd` count at the end of the
file: 2 -> 0).

`server/file-pool.ts` is not changed: the server's thread never waits on
a file thread (it posts a task, ends a thread with `terminate()` without
awaiting it, and closes descriptors), so the product cannot block this
way. Only the tests await `fileThreadsClosed()`.

## Verification

- Widened window, scratch only (a 500 ms `Atomics.wait` right after the
notify in `readGate`):
- on main 72f2edf: `timeout 30 bun test server/file-pool.test.ts` is
killed at 30 s (exit 124), stopped in that test;
  - with this fix: exit 0 in 1 s, 12 pass.
- 50 runs of `bun test server/file-pool.test.ts`, 10 at a time pinned to
2 cores (`taskset -c 0,1`), each under `timeout 60`: 50 pass, 0 hangs.
Again pinned to one core (`taskset -c 0`): 50 pass, 0 hangs.
- Leaked FIFO descriptors at the end of the file (`/proc/self/fd`,
scratch probe): 2 before, 0 after; on 80b8cb2 the widened window again
passes in 1 s and 50/50 runs pinned to one core pass.
- `bun run check fast`: green on 80b8cb2 (typecheck, build, generated
files, workflow syntax; unit 8380 pass, 0 fail, 34 skip in 535 files).

## Review

omo-native-code-reviewer: PASS (APPROVE), no CRITICAL/HIGH/MEDIUM. It
found no path left that blocks the test's main thread (the remaining
waits are the non-blocking open and write, `hold.ran()`'s 10 s bounded
wait, and awaited promises), confirmed the release cannot hit
ENXIO/EAGAIN, and checked that a failing assertion while the thread is
parked fails fast instead of hanging. A second omo round on 80b8cb2
(the FIFO-descriptor take-back): PASS (APPROVE), reproduced 2 leaked
FIFO descriptors at 65a8a71 and none at 80b8cb2. No Codex review:
test-only, `server/file-pool.ts` unchanged.

## Known limits (LOW, not fixed here)

- If the thread is ended after its notify but before it enters the FIFO
read, the test still passes but does not exercise a read in flight in
that run (a false pass, never a hang). Every gate that notifies before
it blocks has this window, `authorizeGate` included.


The reviewer's findings and how each was resolved are in a PR comment.
devswha added a commit that referenced this pull request Oct 29, 2026
…'s (#2254) (#2311)

Closes #2254. Thanks to @PayrollFuchs for the report and the
measurements.

## Problem

`GET /api/pane/commands` (and `/api/agent/commands`) built the slash
menu by scanning every skill and
command folder the agent reads (`paneCommands` ->
`AGENT_SOURCES[agent].discover` ->
`server/skills/walk.ts`), with synchronous
`readdirSync`/`statSync`/`openSync`/`realpathSync`, on the
server's only thread. With the folders on a slow filesystem (the
reporter's: a Windows folder
bind-mounted into a container over 9p, about 2.8 ms per `stat`, 95 skill
folders reached twice through
`~/.claude` links) one request took 10-27 s, and every terminal stream,
typed key, `/api/health` and
herdr RPC waited with it.

## Change

- The scan runs on #2256's file threads (`server/file-pool.ts`) as a new
`commands` task
(`server/file-tasks.ts`). At most 2 of the 4 threads run a scan at once
(`scans`), so the file
routes keep the others; a scan past the cap waits, and the tasks behind
it still take a free thread.
- `scanPaneCommands` (`server/commands.ts`):
- a request waits for its scan at most 45 s, counted from when the
request arrived (its herdr
lookups included), then gets `503 file_busy` with `retry-after: 1`,
before Bun's 60 s idle cutoff;
- the scan goes on: a request for the same scan made meanwhile (the menu
asks again after a failed
read, at 2/5/15/30 s) waits for that one instead of starting another; a
scan that finishes after
everyone waiting gave up is kept 35 s and handed to the next request
once, so a scan slower than
one request's wait still reaches the menu (at most 16 such answers,
about 8 MiB of text in all,
    the oldest dropped first);
- a scan still waiting for a thread when its last request leaves is
dropped, so it holds no waiting
    place;
- an answer a request received is never kept: the next request scans
again and sees a skill added
    on disk since (as before).
- A Bun thread keeps the environment the process started with, so the
scan is handed the server's
home and environment (`serverEnv`); pi, Codex and Claude read
`PI_CODING_AGENT_DIR`, `ProgramData`
  and `ProgramFiles` from it instead of `process.env`.
- The machine proxy passes on a PC's `Retry-After` with its 503.
- The New session dialog's skill list (`useAgentSkills`, moved out of
`NewSessionDialog.tsx`) asks again on
`503 file_busy` after the larger of `Retry-After` and a 1/2/5/15/30 s
pause, then shows the error;
the pane menu already retried (`usePaneCommands`). `ApiError` carries
`retryAfterMs`.
- `scripts/bench-file-access.ts` gains a commands case (`--slow-root`
with a `project/.claude`;
  `--cases` filters cases).

No herdr RPC, attach, focus, takeover or access-control code changes;
read-only devices are still
refused the rows before any scan (#2132).

## Measurements

`bun scripts/bench-file-access.ts --runs 3 --slow-root <mnt> --cases
'commands|^stat a file$'`, the
server in a child process (port 0, mkdtemp state, stand-in herdr
socket), `/api/health` probed every
5 ms from its own thread, event-loop lag sampled every 5 ms. Mount: a
FUSE passthrough that waits 2 ms
before each getattr/readdir/open/read/readlink (no attribute cache),
holding a project with 95 skill
folders and 5 command files, the server's `~/.claude/skills` and
`~/.claude/commands` linked to the
project's, as the reporter's were. The raw scan there takes 20.6 s.
Median [min-max] of 3 runs, ms:

| | main 9faf067 | this branch |
|---|---|---|
| max event-loop lag | 28725 [28452-33286] | 62 [35-65] |
| slowest `/api/health` | 28736 [28466-33298] | 67 [40-68] |
| `/api/health` answers during the scan | 2 [1-3] | 4923 [4697-5143] |
| the commands request itself | 28730 [28468-33322] | 26686
[24567-27799] |

## Known limits

- A scan stuck in a system call that never returns keeps its thread (and
one of the 2 scan slots)
until that call returns, as #2256's file tasks do; requests for it get
503, the rest of the server
  keeps answering.
- LOW, not changed: `server/skills/omo.ts` also bounds its walk by
`os.homedir()`, which on a thread is
the process's starting HOME (the same unless HOME changes after the
server starts); on Windows the
handed-over environment is read with the variables' exact names
(`ProgramFiles`, `ProgramData`), as
  Windows sets them.

## Tests

- `server/pane-routes.test.ts`: a Claude pane whose
`.claude/settings.json` is a FIFO held by a writer
thread, which the test lets go only from its own thread while the scan
is blocked: on main the
writer times out (`timed-out`, the server thread was held for the whole
read); here it is released
and the route lists the project's skill. A request past its wait gets
503 and a request for the same
scan joins it (one thread). A scan that finished after its request gave
up goes to the next request
once (without a skill added since), and the request after that scans
again.
- `server/file-pool.test.ts`: at most `scans` scans run while a file
task takes a free thread; a scan's
own deadline; the server's `PI_CODING_AGENT_DIR` reaches the thread; a
request's wait counts from its
  start, and a queued scan nobody waits for frees its waiting place.
- `server/machine-proxy.test.ts`: a PC's 503 keeps its `Retry-After`.
- `src/lib/useAgentSkills.hook.test.ts`: a busy answer is asked again
and listed, a longer `Retry-After`
is honoured, tries are bounded, and closing stops them.
`scripts/new-session-skills-browser-qa.ts`
  answers Codex's skill list busy once and still shows its chips.
- Mutations: each fix removed (scan cap, serverEnv, scan deadline, join,
abort of a queued scan, wait
from start, unclaimed hand-over, its entry and size bounds, Retry-After)
fails its test.
- Targeted suites (commands, all `server/skills`, pane routes, file
pool/routes/view, http idle
timeout, machine proxy, catalog sources): 529 pass; the three changed
test files 11 runs in a row,
  8 of them 4 at once, all green.
- `bun run check fast` on e35141e (this head): all steps pass, 8,411
unit tests, 0 fail. (Runs
started from a shell that exported `PYTHONUNBUFFERED=1` failed
`server/codex-processes.test.ts`,
untouched here: its `holding()` helper reads one chunk of a python3
child's stdout and expects the
whole `READY\n`, which unbuffered Python writes in two parts under load.
LOW, test-only.)

## Reviews

- omo-native-code-reviewer on 8144a77: PASS, two MEDIUM, both fixed in
628c9ce with tests (a queued
scan nobody waits for kept a shared waiting place; a scan finishing
between the menu's retries was
  thrown away). LOWs listed above.
- Codex Sol 6.1 Fast xhigh on 8144a77: FAIL, one MEDIUM (the wait began
after the herdr lookups and
could pass the 60 s idle cutoff), fixed in 628c9ce with a test; one LOW
(the machine proxy dropped
  `Retry-After`), fixed with a test.
- Codex Sol 6.1 Fast xhigh, final round on the delta 8144a77..628c9ce:
FAIL, one MEDIUM (unclaimed
answers had no size bound: 32 abandoned scans of large catalogs held 136
MiB for 35 s), fixed in the
last commit with a test that fails without either bound. Per the review
policy that fix was not sent
  to Codex again; the merge pass reviews it.

---------

Co-authored-by: sisyphus-dev-ai <[email protected]>
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.

Isolate blocking file access with bounded owned workers

1 participant