Skip to content

usockets: propagate epoll_ctl(EPOLL_CTL_ADD) failure instead of going silently deaf - #32706

Merged
Jarred-Sumner merged 11 commits into
mainfrom
farm/d04cbd43/epoll-add-fail
Jun 26, 2026
Merged

Jarred-Sumner merged 11 commits into
mainfrom
farm/d04cbd43/epoll-add-fail

Conversation

@robobun

@robobun robobun commented Jun 25, 2026

Copy link
Copy Markdown
Collaborator

Repro

With an LD_PRELOAD shim that makes epoll_ctl(EPOLL_CTL_ADD) return ENOSPC for the listen socket (what the real kernel does when fs.epoll.max_user_watches is exhausted):

Bun.serve returned ok, port 41949        <- no error thrown
TCP handshake COMPLETED (kernel backlog)  <- connect()-based health checks pass
fetch -> TimeoutError                     <- forever, for every client

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, no error callback, nothing on stderr. Accepted and connecting sockets have the same failure mode.

Cause

us_poll_start() in packages/bun-usockets/src/eventing/epoll_kqueue.c discards the epoll_ctl return code. us_poll_start_rc() exists but only us_socket_from_fd uses it; us_socket_group_listen, us_socket_group_listen_unix, the accept loop in loop.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 *error and restore thread-local errno, return NULL. Both Bun.listen (which reads the out-param) and Bun.serve (which reads errno in on_listen_failed) now throw.
  • accept loop in 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.
  • connect paths: close the fd, free the poll, return NULL / continue. Callers already handle NULL as a connect failure.
  • libuv.c gains a us_poll_start_rc that returns 0 so Windows links; no behaviour change there.
  • on_listen_failed (TCP) now surfaces the real errno when it is neither SUCCESS nor EADDRINUSE, instead of hardcoding EADDRINUSE for everything that is not EACCES. ENOSPC now shows up as ENOSPC. (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 new epoll_ctl failure path and will resolve cleanly against that PR.)

Verification

USE_SYSTEM_BUN=1 bun test test/js/bun/http/serve-epoll-add-fail.test.ts
  (fail) Bun.serve throws ...   -> received { ok: true, port: 33517 }
  (fail) Bun.listen throws ...  -> received { ok: true }
  (fail) accepted connection is closed ... -> timed out after 5000ms

bun bd test test/js/bun/http/serve-epoll-add-fail.test.ts
  (pass) Bun.serve throws when epoll_ctl(EPOLL_CTL_ADD) for the listen socket fails
  (pass) Bun.listen throws when epoll_ctl(EPOLL_CTL_ADD) for the listen socket fails
  (pass) accepted connection is closed when epoll_ctl(EPOLL_CTL_ADD) fails for it
  3 pass, 0 fail

The test compiles a tiny LD_PRELOAD shim that fails epoll_ctl(EPOLL_CTL_ADD) with ENOSPC for 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-fuzz syscall-level fault injector (listener.epoll_add.0:E28).

… 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.
@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Poll-registration failures now return checked errors across listen, connect, accept, and deferred connection paths. TCP listen failure handling preserves errno and distinguishes EACCES, EADDRINUSE, and other system errors. Kqueue error events now propagate errno data, and Linux tests exercise listener and accepted-socket EPOLL_CTL_ADD failures.

Changes

Poll start failure handling

Layer / File(s) Summary
Poll start path updates
packages/bun-usockets/src/eventing/libuv.c, packages/bun-usockets/src/context.c, packages/bun-usockets/src/loop.c
Adds us_poll_start_rc and uses it to close sockets and free polls when listen, connect, accept, or deferred connection poll registration fails.
Listen errno reporting
src/runtime/server/mod.rs
Stores listen failure errno and changes non-EACCES handling to emit either a real system error or the existing EADDRINUSE message.
Kqueue errno propagation
packages/bun-usockets/src/eventing/epoll_kqueue.c
Sets errno from kevent64 error data when per-filter failures are reported through KEVENT_FLAG_ERROR_EVENTS.
Epoll failure test harness
test/js/bun/http/serve-epoll-add-fail.test.ts
Builds the LD_PRELOAD shim, prepares the fixture scripts, and wires environment helpers for forcing EPOLL_CTL_ADD failures.
Epoll failure test cases
test/js/bun/http/serve-epoll-add-fail.test.ts
Adds skipped Bun subprocess tests for listener failure handling and accepted-socket close or reset behavior when EPOLL_CTL_ADD fails.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: propagating epoll_ctl add failures instead of silently ignoring them.
Description check ✅ Passed The description is detailed and includes problem, cause, fix, and verification, covering the template's intent well.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

@robobun

robobun commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 8:28 PM PT - Jun 25th, 2026

❌ @robobun, your commit 6b68a6f has 2 failures in Build #64799 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32706

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

bun-32706 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. binding privileged port incorrectly reports EADDRINUSE instead of EACCES on macos #30363 - PR fixes on_listen_failed to surface the real errno instead of hardcoding EADDRINUSE, which would correctly report EACCES for privileged port binds
  2. Bun.serve failed to start on localhost subdomain #25765 - PR's errno-reporting fix would surface the actual error instead of showing errno: 0 with code: "EADDRINUSE" for non-port-conflict listen failures

If this is helpful, copy the block below into the PR description to auto-close these issues on merge.

Fixes #30363
Fixes #25765

🤖 Generated with Claude Code

@robobun

robobun commented Jun 25, 2026

Copy link
Copy Markdown
Collaborator Author

Re the find-issues suggestion above: this PR does not reliably fix #30363 / #25765. Those are about bind() failures on macOS, where thread-local errno gets clobbered by cleanup before on_listen_failed reads it. #30364 plumbs the errno through the callback signature and is the right fix for those.

This PR is narrower: it makes the epoll_ctl(EPOLL_CTL_ADD) failure path return NULL at all (it previously returned a non-null listen socket that was never registered), and explicitly saves/restores errno around the cleanup for that specific path so the existing on_listen_failed can read it. The on_listen_failed change here is the minimum needed to surface ENOSPC on Linux; #30364 supersedes it with proper plumbing if/when it lands.

@coderabbitai coderabbitai 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5621c5d and 9a530e1.

📒 Files selected for processing (5)
  • packages/bun-usockets/src/context.c
  • packages/bun-usockets/src/eventing/libuv.c
  • packages/bun-usockets/src/loop.c
  • src/runtime/server/mod.rs
  • test/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)
Comment thread packages/bun-usockets/src/context.c Resolved
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.

@coderabbitai coderabbitai 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.

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 win

Preserve existing LD_PRELOAD entries when adding the shim.

Setting LD_PRELOAD only to shimPath drops any preload already present in bunEnv, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9a530e1 and 333ff01.

📒 Files selected for processing (2)
  • packages/bun-usockets/src/eventing/epoll_kqueue.c
  • test/js/bun/http/serve-epoll-add-fail.test.ts

Comment thread packages/bun-usockets/src/context.c Resolved
robobun and others added 2 commits June 26, 2026 00:22
…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.
Comment thread src/runtime/server/mod.rs Resolved
… 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.

@coderabbitai coderabbitai 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.

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 win

Scope real-errno reporting to the preserved-errno failure path.

This branch now runs for ordinary TCP bind/listen failures too, but on_listen_failed() still reads thread-local errno. The PR notes that macOS bind failures can reach this callback after errno was clobbered, so this can now surface a stale unrelated SystemError instead of the previous stable fallback. Keep the new mapping limited to the poll-start/preserved-errno path 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

📥 Commits

Reviewing files that changed from the base of the PR and between 076a98f and e76669e.

📒 Files selected for processing (3)
  • packages/bun-usockets/src/context.c
  • src/runtime/server/mod.rs
  • test/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'.
@robobun

robobun commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

Re the outside-diff review on on_listen_failed (mod.rs:1758-1765): addressed in 3faf626. The real-errno branch is now gated #[cfg(linux)], matching the existing EACCES special-case. On macOS/Windows/FreeBSD the previous EADDRINUSE fallback is unchanged, so there is no risk of surfacing a stale errno from a clobbered thread-local. The epoll_ctl failure path on Linux explicitly restores errno in us_socket_group_listen before returning NULL, so the read is reliable there. Cross-platform errno plumbing through the callback signature is #30364's scope.

@robobun

robobun commented Jun 26, 2026 •

Copy link
Copy Markdown
Collaborator Author

CI status as of 6b68a6f (build #64799): the diff is green. The new test file test/js/bun/http/serve-epoll-add-fail.test.ts (6 cases: Bun.serve, Bun.listen, accepted-conn, fetch, Bun.connect, Bun.udpSocket) passes on every Linux lane and is skipped elsewhere as intended. All review threads are resolved.

The remaining red lanes are all Windows flakes unrelated to this diff:

  • bun-install.test.ts / bun-install-registry.test.ts / update_interactive_install.test.ts on Windows 2019 x64/x64-baseline/11 aarch64 (install path; this PR does not touch install)
  • spawn-pipe-leak.test.ts / spawn-stdin-readable-stream.test.ts on Windows (spawn path; untouched)
  • node-http-connect.test.ts on Windows 2019 x64 (node:http compat; untouched)
  • napi.test.ts on Windows 2019 x64/x64-baseline (N-API; untouched)

On Windows this PR is a no-op: the libuv backend's us_poll_start_rc returns 0 unconditionally, and the on_listen_failed errno-reporting change is gated #[cfg(linux)]. Earlier builds on this branch (#64732, #64762, #64787) saw different unrelated Windows/ASAN flakes, none touching the changed files.

Ready for a maintainer to merge.

Comment thread packages/bun-usockets/src/context.c Resolved
…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.
@Jarred-Sumner
Jarred-Sumner merged commit 2b1d61d into main Jun 26, 2026
75 of 77 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the farm/d04cbd43/epoll-add-fail branch June 26, 2026 02:15
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.

2 participants