Skip to content

Bun.serve: stop a file response whose reader failed to start - #46684

Closed
robobun wants to merge 3 commits into
mainfrom
robobun/1dedb473/file-response-failed-start
Closed

robobun wants to merge 3 commits into
mainfrom
robobun/1dedb473/file-response-failed-start

Conversation

@robobun

@robobun robobun commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • A Bun.file response whose fd the event loop refuses to watch is closed, but still reads the fd. new Response(Bun.file("/dev/urandom")) leaks one fd per request.
  • Two new Response(Bun.file(fd)) over one pipe: the refused one takes all 1000 bytes. At 200000 bytes LeakSanitizer reports Direct leak of 216 byte(s) from FileResponseStream::start.
  • Cause: PosixBufferedReader::start() (src/io/PipeReader.rs:553) reports a failed poll registration through on_reader_error, then returns Ok. FileResponseStream::start() (src/runtime/server/FileResponseStream.rs:250) checks only Err.

Fix

  • FileResponseStream::start() returns when the stream has already finished. It no longer reads, or takes the ref that kept the stream allocated.
  • Correct: on_reader_error has closed the connection and told the owner, so nothing is left to start.
  • Verified: test/js/bun/http/bun-serve-file.test.ts (3 new tests fail on main), serve.test.ts, bun-serve-static.
  • Self-reviewed: 26 concerns raised, 16 addressed. 10 are about a reader-wide change that is not in this PR (Notes).

Background

  • FileResponseStream streams an fd into a response. For a pipe, socket or device its reader waits on a FilePoll, an epoll or kqueue registration.
  • epoll refuses a second registration of one fd (EEXIST) and a device without poll support (EPERM).
  • Considered a start() that returns the error. It changes a contract that bun lint, bun fmt: write a child's stdin from the event loop #45424 builds on, so it waits for a maintainer.

Downsides

  • A file response not sent with sendfile runs 2 more instructions in start() (495 against 493 for a 4 KiB file). Release .text is unchanged.
  • Still hit: the refused request ends in a connection reset.
  • Not covered: kqueue accepts a second registration, so macOS never refuses the second response.
Notes

Where this comes from. No user reported it. A review of #41874 found the read after a failed registration, and #41874 carried this same check (546703b) until it was closed, because #46021 had landed its other parts. #42654 looked at this site with a FIFO and saw no leaked fd. The leak needs a read that ends without EAGAIN and without EOF: a device, or more than 128 KiB in the pipe.

Releases (Linux x64, fetch() against new Response(Bun.file("/dev/urandom")), open fds before and after):

build answer 20 requests 40 requests
1.3.0 500 from the error handler, File must be regular or FIFO 18 -> 18 18 -> 18
1.4.0 ECONNRESET 12 -> 32 12 -> 52
1.4.4 ECONNRESET 10 -> 30 10 -> 50

The handler of docs/guides/http/stream-file.mdx serves the path of the URL, so GET /dev/urandom is this case: 20 requests take the fds from 7 to 27 on main and from 7 to 7 here.

Main 7d240c1 against this branch (Linux x64, debug build with ASAN):

  • Two responses on one FIFO fd, with 1000, 200000 and 900000 bytes written: the live response gets 0, 0 and 637856 bytes on main. Here it gets all of them.
  • The refused stream on main makes 2 poll probes and 2 registration attempts, and finish runs twice. Here: 0, 1 and 1.
  • /dev/zero, /dev/urandom, /dev/full: 20 requests take the fds from 7 to 27 on main and from 7 to 7 here. /dev/null does not leak on main, because its first read is an EOF.
  • LeakSanitizer at 200000 bytes: Direct leak of 216 byte(s) in 1 object(s) on main, clean here.

Cost (release builds of 5c6d4e2 with and without the change):

  • llvm-size: .text is 82,231,705 bytes in both. FileResponseStream::start is 1154 bytes, against 1156.
  • Instructions executed in FileResponseStream::start and in the reader's own functions, with other calls stepped over in gdb: 493 -> 495 for a 4 KiB regular file, 725 -> 727 for a FIFO with data and EOF, 734 -> 736 for a FIFO with data and a writer.

The reader-wide change. The contract behind this bug is in PosixBufferedReader::start(). It reports a failed registration by callback and returns Ok, so each parent has to check its own state afterwards. Four parents do: SubprocessPipeReader.rs:211, shell/subproc.rs:1836, Terminal.rs:446, and the start_err adapter of shell/IOReader.rs. This PR adds the fifth check.

I also built the change where start() returns the error and all 19 POSIX call sites handle it. It is the branch robobun/1dedb473/pipe-reader-start-returns-err: one commit on top of this PR, 14 source files, +80/-86. It removes all five checks. Numbers for that branch:

  • Release .text: +2,304 bytes.
  • Instructions: 493 -> 493 for a file response, 128 -> 133 for a Bun.spawn pipe start.
  • With an epoll_ctl failure injected, 14 of 16 parent fixtures print the same as main in 20 runs each. The other two are bun run --filter, where a debug assertion on main no longer fires, and a fixture with two racing scripts.

It is not in this PR, for three reasons:

That change needs a maintainer decision on those three points first.

Other open PRs on these lines.

Tests.

  • The pipe test is Linux only. kqueue registers with EV_ADD (src/io/posix_event_loop.rs:687), which replaces the first registration and does not fail. The first response then gets no more events, and its EV_DELETE at teardown (:998) removes the watch that the second response uses. A fix for that belongs in the kqueue registration of FilePoll, not in this PR. I read this from the code and did not run macOS.
  • There is no test for the 200000-byte case. It needs a pipe of 256 KiB. The kernel refuses fcntl(F_SETPIPE_SZ) with EPERM for a user that holds more pipe pages than fs.pipe-user-pages-soft, and the first version of that test failed for such a user.
  • The two device tests cover that leak. They count the open fds after 16 requests and do not assert how a request ends. On main, with the LeakSanitizer settings of scripts/runner.node.ts, the test process also reports Direct leak of 3456 byte(s) in 16 object(s) from FileResponseStream::start. They also run on macOS.
  • should use correct error when using a root range port(#7187) in serve.test.ts fails in my container on main too: the container runs as root.

no test proof · iteration 2 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/bun/http/bun-serve-file.test.ts

The POSIX reader reports a failed poll registration through
on_reader_error and then returns Ok from start(). FileResponseStream
went on after that Ok: it took a read ref on a stream that had already
finished and read the fd. The bytes were dropped, and the stream stayed
allocated, with its fd, when that read did not end in EAGAIN or EOF.

start() now returns when the stream has finished.
@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

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 10 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 7d240c1 and 427f418.

Files selected for processing: 2
  • src/runtime/server/FileResponseStream.rs
  • test/js/bun/http/bun-serve-file.test.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.

@robobun

robobun commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:31 AM PT - Oct 24th, 2026

✅ @robobun, your commit 427f4189e9a65193b1eb004fdf424296a5e9b537 passed in Build #131762! 🎉


🧪   To try this PR locally:

bunx bun-pr 46684

That installs a local version of the PR into your bun-46684 executable, so you can run:

bun-46684 --bun

@robobun

robobun commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: open, ready for a maintainer review. PR: #46684.

How I reproduced the bug (Linux x64, main at 7d240c1, debug build with ASAN):

  • A Bun.serve fetch handler that returns new Response(Bun.file("/dev/urandom")), 20 requests: the number of open fds goes from 7 to 27. With this PR it stays at 7.
  • Two new Response(Bun.file(fd)) over one FIFO fd, with 1000 bytes written when the second response starts: the first response gets 0 of them. With this PR it gets all 1000.
  • The same with 200000 bytes and LeakSanitizer: Direct leak of 216 byte(s) from FileResponseStream::start. With this PR the run is clean.

The three new tests in test/js/bun/http/bun-serve-file.test.ts fail on main and pass with this PR.

CI for 427f418 (build 131762):

  • 179 of 181 jobs passed. No test failed on every retry.
  • The two darwin x64 - test-bun jobs got no agent. They expired after two hours and are in the queue again.
  • No lane reports a failure of bun-serve-file.test.ts. I read its result on x64-asan (179 pass, 0 fail) and on macOS aarch64 (175 pass, 0 fail).
  • These tests failed once and passed on the retry. This diff does not touch them: spawn-pipe-leak.test.ts, nth-anplusb-ident.test.ts, spawn_waiter_thread.test.ts, node-net.test.ts, worker_threads.test.ts.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings (both on the test side), I also checked the new early return in FileResponseStream::start for ref balance: fail_with -> finish has already released the owner ref and dropped any read ref, hold_read_ref is never taken on this path, and the frame-level _guard is the only remaining ref, so the stream (and its fd via Drop) is released when start returns. The fixture's until loops waiting on the second connection closing are bounded by the test timeout, so a regression surfaces as a timeout rather than a hang.

Extended reasoning...

The Rust change is a four-line #[cfg(unix)] early return in src/runtime/server/FileResponseStream.rs after BufferedReader::start, skipping update_ref, hold_read_ref and read when on_reader_error already finished the stream; the rest of the diff is two new Linux/POSIX tests in test/js/bun/http/bun-serve-file.test.ts. No security-sensitive surface is touched. The two inline findings concern test robustness (F_SETPIPE_SZ EPERM on restricted runners, a per-test timeout under ASAN) rather than the fix itself, and the fix sits in refcounted unsafe lifecycle code that a maintainer should still eyeball.

Comment thread test/js/bun/http/bun-serve-file.test.ts Resolved
Comment thread test/js/bun/http/bun-serve-file.test.ts Resolved
The 200000-byte case set the pipe size with fcntl(F_SETPIPE_SZ). The
kernel refuses that with EPERM for a user that holds more pipe pages
than fs.pipe-user-pages-soft, so the case could fail on a busy runner.
It also carried a per-test timeout for the LeakSanitizer report.

The two device tests cover the same leak and need no pipe size.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

The two points from my earlier review (the F_SETPIPE_SZ-dependent 200000-byte variant and the per-test ASAN timeout) are addressed by the latest push, which drops both. Beyond the inline finding, I also checked that the new early return at src/runtime/server/FileResponseStream.rs:256 cannot read freed memory: finish() releases only the owner ref while the _guard from RefPtr::init_ref at line 187 still holds one, so the stream is freed (and its fd closed by Drop via auto_close) when the guard drops after the return, not inside on_reader_error. The later re-registration sites (watch()/read() from on_writable) run after hold_read_ref, so their on_reader_error already balances via take_read_ref and need no equivalent check.

Extended reasoning...

The PR adds a 5-line unix-only early return in FileResponseStream::start after the POSIX BufferedReader reports a failed poll registration through on_reader_error and returns Ok, plus two tests in test/js/bun/http/bun-serve-file.test.ts (a Linux-only shared-FIFO fixture and a /dev/zero fd-count test over fetch handler and static route). It touches native refcount and fd lifecycle in the HTTP server but no auth, crypto, or input-parsing surface. The refcount path checks out and the prior review feedback was addressed; the remaining inline finding is pre-existing macOS kqueue behavior outside this fix, and the PR itself flags a reader-contract decision for a maintainer, so a human look is still warranted.

@robobun

robobun commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR has had no review and no new commit since 2026-10-24.

The branch stays, so the work is not lost. To pick it up again, update the branch from main and reopen this PR.

@robobun robobun closed this Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant