Repository navigation
usockets: propagate epoll_ctl(EPOLL_CTL_ADD) failure instead of going silently deaf - #32706
Conversation
… silently deaf When epoll_ctl(EPOLL_CTL_ADD) fails (e.g. ENOSPC because fs.epoll.max_user_watches is exhausted), us_poll_start() discarded the return code. For a listen socket this left Bun.serve() returning a healthy-looking server whose listener was never registered with the event loop: the kernel kept completing TCP handshakes into the backlog while no request was ever answered. Accepted and connecting sockets had the same failure mode, silently becoming a black hole to the peer. Check us_poll_start_rc() at every listen/accept/connect call site: - us_socket_group_listen / _listen_unix: close the fd, free the poll, write the saved errno to *error and restore thread-local errno, return NULL. Bun.listen (reads *error) and Bun.serve (reads errno) both throw. - accept loop: close the fd (peer gets RST/FIN instead of a hang), free the poll, skip to the next pending accept. - connect (resolved-DNS, unix, start_connections): close the fd, free the poll, return NULL / continue so the caller's existing connect-failed path fires. Bun.serve's on_listen_failed now surfaces the real errno on the TCP path instead of hardcoding EADDRINUSE for anything that is not EACCES. Add a Linux-only test that compiles a tiny LD_PRELOAD shim to make epoll_ctl(ADD) fail with ENOSPC for either listening or connected TCP sockets, and asserts Bun.serve/Bun.listen throw ENOSPC and an accepted connection is closed rather than left parked.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughPoll-registration failures now return checked errors across listen, connect, accept, and deferred connection paths. TCP listen failure handling preserves errno and distinguishes ChangesPoll start failure handling
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 8:28 PM PT - Jun 25th, 2026
❌ @robobun, your commit 6b68a6f has 2 failures in
🧪 To try this PR locally: bunx bun-pr 32706That installs a local version of the PR into your bun-32706 --bun |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
Re the find-issues suggestion above: this PR does not reliably fix #30363 / #25765. Those are about This PR is narrower: it makes the |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/js/bun/http/serve-epoll-add-fail.test.ts`:
- Line 8: The tempDir fixture in serve-epoll-add-fail.test.ts is created in
beforeAll but never disposed, so add cleanup using its disposable behavior.
Update the test setup around beforeAll to register disposal for the tempDir
result, either by using a using declaration or by storing it and releasing it in
afterAll, so the shim directory is always removed even if compile/test setup
fails.
- Around line 1-7: The new comments in the test file are too long and include
historical bug context that should not live in code comments. Trim the comments
near the affected test cases and the LD_PRELOAD shim setup so each stays within
3 lines and only states the durable invariant: the shim forces ENOSPC and
Bun.serve/Bun.listen must throw. Use the surrounding test blocks and helper
setup as the anchors when shortening the comments.
- Around line 168-220: The accepted-socket test currently pipes stderr from
Bun.spawn but only reads it at the end, which can deadlock if the child writes
enough diagnostics. In the test around Bun.spawn/readLine/proc.stderr.text,
start draining proc.stderr concurrently as soon as the subprocess is created
(for example by kicking off an async read promise alongside stdout handling) and
keep the existing final assertion on the collected stderr content. This ensures
the accepted-connection scenario in the test stays non-blocking while preserving
the current checks on open() not being reached.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 0752cef4-0588-4f5a-8c5d-b6ca9176a930
📒 Files selected for processing (5)
packages/bun-usockets/src/context.cpackages/bun-usockets/src/eventing/libuv.cpackages/bun-usockets/src/loop.csrc/runtime/server/mod.rstest/js/bun/http/serve-epoll-add-fail.test.ts
- trim comments to the 3-line cap - dispose tempDir in afterAll - start draining stderr concurrently in the accept test - avoid asserting stderr is exactly empty (ASAN builds may emit warnings)
KEVENT_FLAG_ERROR_EVENTS makes kevent64 report per-filter failures as EV_ERROR entries with the real errno in .data; the syscall returns the count and leaves thread-local errno untouched. Mirror the epoll contract (non-zero return implies errno is set) so the new us_poll_start_rc callers capture the real error code on macOS instead of a stale value.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/js/bun/http/serve-epoll-add-fail.test.ts (1)
119-129: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winPreserve existing
LD_PRELOADentries when adding the shim.Setting
LD_PRELOADonly toshimPathdrops any preload already present inbunEnv, which can change sanitizer/instrumented subprocess behavior. Prepend the shim instead.Proposed fix
+ const existingLDPreload = bunEnv.LD_PRELOAD; const proc = Bun.spawn({ cmd: [bunExe(), script], env: { ...bunEnv, - LD_PRELOAD: shimPath, + LD_PRELOAD: existingLDPreload ? `${shimPath}:${existingLDPreload}` : shimPath, FAIL_EPOLL_ADD: mode, },🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/js/bun/http/serve-epoll-add-fail.test.ts` around lines 119 - 129, The subprocess setup in runWithShim currently overwrites LD_PRELOAD with only shimPath, which drops any existing preload from bunEnv. Update the env construction in runWithShim to preserve any pre-existing LD_PRELOAD value by prepending shimPath to it instead of replacing it. Keep the change localized to the Bun.spawn env object so sanitizer/instrumented behavior remains intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@test/js/bun/http/serve-epoll-add-fail.test.ts`:
- Around line 119-129: The subprocess setup in runWithShim currently overwrites
LD_PRELOAD with only shimPath, which drops any existing preload from bunEnv.
Update the env construction in runWithShim to preserve any pre-existing
LD_PRELOAD value by prepending shimPath to it instead of replacing it. Keep the
change localized to the Bun.spawn env object so sanitizer/instrumented behavior
remains intact.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: cb07e02b-a972-4fbd-ae38-52a5bcf40f01
📒 Files selected for processing (2)
packages/bun-usockets/src/eventing/epoll_kqueue.ctest/js/bun/http/serve-epoll-add-fail.test.ts
…nnect The connect-path changes in us_socket_group_connect_resolved_dns / _connect_unix / start_connections already make these return NULL on a failed EPOLL_CTL_ADD, which propagates through ConnectResult::Failed to a rejected promise. Add fixtures that run fetch() and Bun.connect under the shim's connected-socket mode to prove both reject instead of pending forever. Also trim the us_socket_group_listen comment to the 3-line cap.
… at EOF The readLine helper returned a trailing partial line at stream close without clearing the buffer, so a subsequent call would return the same string forever and the drain loop would spin instead of failing.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime/server/mod.rs (1)
1758-1765: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winScope real-
errnoreporting to the preserved-errnofailure path.This branch now runs for ordinary TCP bind/listen failures too, but
on_listen_failed()still reads thread-localerrno. The PR notes that macOS bind failures can reach this callback aftererrnowas clobbered, so this can now surface a stale unrelatedSystemErrorinstead of the previous stable fallback. Keep the new mapping limited to the poll-start/preserved-errnopath until the callback carries the failure code explicitly.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/server/mod.rs` around lines 1758 - 1765, Scope the real-errno mapping in on_listen_failed() so it only applies to the preserved-errno poll-start failure path, not the ordinary TCP bind/listen failure branch. Keep the existing stable fallback for the direct bind/listen path and ensure the new bun_sys::Error::from_code(errno, bun_sys::Tag::listen) conversion is only used where the failure code is explicitly preserved or passed through.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/js/bun/http/serve-epoll-add-fail.test.ts`:
- Around line 281-286: Strengthen the Bun.connect rejection test by asserting
the specific client-side failure identity in addition to settled being rejected.
In the test that calls runWithShim("connect.js", "accepted"), parse the JSON
result from stdout and check the stable failure code/value exposed by
Bun.connect so the test proves the outbound socket registration path failed for
the intended reason. Use the existing Bun.connect shim test block and the result
object’s failure fields to make the assertion more specific than a generic
rejection.
---
Outside diff comments:
In `@src/runtime/server/mod.rs`:
- Around line 1758-1765: Scope the real-errno mapping in on_listen_failed() so
it only applies to the preserved-errno poll-start failure path, not the ordinary
TCP bind/listen failure branch. Keep the existing stable fallback for the direct
bind/listen path and ensure the new bun_sys::Error::from_code(errno,
bun_sys::Tag::listen) conversion is only used where the failure code is
explicitly preserved or passed through.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 33a912c1-7e67-4760-a3c9-170ae80e795b
📒 Files selected for processing (3)
packages/bun-usockets/src/context.csrc/runtime/server/mod.rstest/js/bun/http/serve-epoll-add-fail.test.ts
…un.connect assertion On non-Linux platforms thread-local errno is not reliably preserved through the C++/callback chain between the failing bind()/listen() and on_listen_failed, so reading it could surface a stale unrelated code. Scope the new errno-based branch to Linux (where the epoll_ctl failure path explicitly restores errno) and keep the previous EADDRINUSE fallback elsewhere; PR #30364 plumbs the errno through the callback signature for the cross-platform case. Also assert the full Bun.connect rejection shape (ECONNREFUSED, errno -111, syscall 'connect') instead of only settled == 'rejected'.
|
Re the outside-diff review on |
|
CI status as of 6b68a6f (build #64799): the diff is green. The new test file The remaining red lanes are all Windows flakes unrelated to this diff:
On Windows this PR is a no-op: the libuv backend's Ready for a maintainer to merge. |
…cket us_create_udp_socket was the last socket-fd caller of the void us_poll_start(); Bun.udpSocket / node:dgram / QUIC would return a bound but never-registered handle on ENOSPC. Same fix shape: check us_poll_start_rc, close fd, free poll, write *err + errno, return NULL. Callers (quic.c, Rust udp wrapper) already NULL-check. Extend the LD_PRELOAD shim with a SOCK_DGRAM mode and add a Bun.udpSocket test.
Repro
With an
LD_PRELOADshim that makesepoll_ctl(EPOLL_CTL_ADD)returnENOSPCfor the listen socket (what the real kernel does whenfs.epoll.max_user_watchesis exhausted):Bun.serve()returns a healthy-looking server object; the kernel keeps completing handshakes into the listen backlog; the event loop never hears about the listener. No exception, noerrorcallback, nothing on stderr. Accepted and connecting sockets have the same failure mode.Cause
us_poll_start()inpackages/bun-usockets/src/eventing/epoll_kqueue.cdiscards theepoll_ctlreturn code.us_poll_start_rc()exists but onlyus_socket_from_fduses it;us_socket_group_listen,us_socket_group_listen_unix, the accept loop inloop.c, and all three connect paths (us_socket_group_connect_resolved_dns,us_socket_group_connect_unix,start_connections) call the void variant and carry on as if registration succeeded.Fix
Check
us_poll_start_rc()at every listen/accept/connect site:us_socket_group_listen/_listen_unix: close the fd, free the poll, write the saved errno to*errorand restore thread-localerrno, returnNULL. BothBun.listen(which reads the out-param) andBun.serve(which readserrnoinon_listen_failed) now throw.loop.c: close the accepted fd so the peer sees RST/FIN instead of a connection that never answers; free the poll; continue draining the backlog.NULL/continue. Callers already handleNULLas a connect failure.libuv.cgains aus_poll_start_rcthat returns0so Windows links; no behaviour change there.on_listen_failed(TCP) now surfaces the real errno when it is neitherSUCCESSnorEADDRINUSE, instead of hardcodingEADDRINUSEfor everything that is notEACCES.ENOSPCnow shows up asENOSPC. (fix(serve): propagate real errno from listen failure (EACCES, EADDRNOTAVAIL, …) #30364 plumbs the errno through the callback signature properly; this change is the minimal version that works for the newepoll_ctlfailure path and will resolve cleanly against that PR.)Verification
The test compiles a tiny
LD_PRELOADshim that failsepoll_ctl(EPOLL_CTL_ADD)withENOSPCfor either listening sockets (SO_ACCEPTCONN == 1) or connected TCP sockets, selected via an env var; timerfd/eventfd pass through so the event loop itself starts. Linux-only.Found by the
bun-sys-fuzzsyscall-level fault injector (listener.epoll_add.0:E28).