Skip to content

usockets: stop deriving eof from kqueue EV_EOF - #32257

Open
Jarred-Sumner wants to merge 7 commits into
mainfrom
claude/kqueue-ev-eof-drain
Open

Jarred-Sumner wants to merge 7 commits into
mainfrom
claude/kqueue-ev-eof-drain

Conversation

@Jarred-Sumner

@Jarred-Sumner Jarred-Sumner commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

What

On kqueue, stop deriving eof from EV_EOF for any socket that is polling READABLE — recv()==0 becomes the single source of eof there, matching epoll (which maps EPOLLHUP but never EPOLLRDHUP).

To keep the two cases that legitimately depended on EV_EOF working:

  • Async-connect failure is reported by kqueue via EVFILT_WRITE + EV_EOF (not EV_ERROR). us_internal_socket_after_open now probes getsockopt(SO_ERROR) on POSIX when the dispatch flag is zero — the portable contract for non-blocking connect completion, and what the Windows branch already effectively does.
  • A paused-then-shut-down socket (us_socket_pause → us_socket_shutdown, which node:http does for every request with a body whose handler ends the socket) watches nothing and so never recv()s. kqueue_change now arms an edge-triggered EVFILT_READ for events==0, and the dispatch loop forwards its EV_EOF as eof only when us_poll_events==0 && POLL_TYPE_SOCKET_SHUT_DOWN. The recv loop is gated on events & READABLE, so no buffered data is read or discarded — parity with epoll's EPOLLHUP close. us_socket_pause on an already-raw-shut-down socket now goes to events==0 (not WRITABLE) so the sentinel arms in either order.

Why

kqueue sets EV_EOF on EVFILT_READ for a peer FIN (≈ EPOLLRDHUP) and on EVFILT_WRITE when the peer's read side is gone. The dispatch loop OR'd it from either filter into eof, which loop.c treats as "fire on_end and close after this tick". That diverged from Linux in two ways that could drop response bytes on macOS:

  • EVFILT_WRITE-only event with EV_EOF skips recv. events & LIBUS_SOCKET_READABLE is false, so the recv loop never runs and the eof block at loop.c:654 closes with the response still in the kernel buffer. The chunked decoder is mid-chunk → ConnectionClosed from fetch().
  • Recv-loop bail-out with EV_EOF already flagged. The continue gate at loop.c:599-611 checks error but not eof; on a busy loop (num_ready_polls ≥ 25) it stops after one ~512 KiB read, and the kqueue-supplied eof then closes before the next tick can drain the rest.

EVFILT_READ is level-triggered and keeps firing after a FIN, so recv()==0 reliably reports end-of-stream after the buffer is drained. RST and hard errors are still covered by the recv()-error branch.

Test

test/js/web/fetch/fetch-chunked-fin-same-tick.test.ts runs 200 concurrent fetch()es against a raw net server that writes a single ~600 KiB chunked body and immediately FINs, with concurrency 32 so kevent batches routinely exceed the 25-ready-poll bail-out threshold. Every request must receive the full body. Passes on Linux unchanged; the kqueue path is exercised on macOS CI.

Fixes #12730
Fixes #29515

@robobun

robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator
Updated 1:26 PM PT - Jun 15th, 2026

✅ @Jarred-Sumner, your commit 7e18629b7eeb006d5a47746b9d6e5b9c32aad759 passed in Build #62603! 🎉


🧪   To try this PR locally:

bunx bun-pr 32257

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

bun-32257 --bun

@github-actions

Copy link
Copy Markdown
Contributor

Found 2 issues this PR may fix:

  1. next start under Bun returns 200 empty bodies for server-side fetch to local PostgREST, while Node returns real data #29515 - fetch() on macOS returns 200 with empty body for non-chunked responses, consistent with EV_EOF causing premature socket close before recv drains the kernel buffer
  2. bun fetch to wrangler dev server crashes server and fails with "socket connection was closed unexpectedly" #12730 - macOS-specific ConnectionClosed on fetch to localhost server, regressed in a version window consistent with kqueue socket handling changes

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

Fixes #29515
Fixes #12730

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Jarred-Sumner, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 1 minute and 19 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9a7da2d2-fb27-4591-87b0-1102e260b3ee

📥 Commits

Reviewing files that changed from the base of the PR and between eb448fb and 7e18629.

📒 Files selected for processing (2)
  • packages/bun-usockets/src/internal/internal.h
  • packages/bun-usockets/src/socket.c

Walkthrough

Removes EV_EOF from kqueue's ready-poll coalescing by refactoring kevent_flags to separate EV_EOF tracking as ev_eof instead of a dispatch eof flag, stripping the first-pass decode mapping, removing it from the merge step, and changing dispatch gating to compute eof conditionally only for socket shutdown poll types. Eliminates the EVFILT_WRITE oneshot special-case. Guards us_socket_pause() to handle shut-down sockets by zeroing the poll mask. Adds SO_ERROR probing in non-Windows async connect completion. Includes a TCP fixture and Bun test reproducing chunked-body drain failures under concurrent load.

Changes

Socket error handling and kqueue EV_EOF fix with regression test

Layer / File(s) Summary
kqueue EV_EOF coalescing and dispatch fix
packages/bun-usockets/src/eventing/epoll_kqueue.c
Refactors kevent_flags to track EV_EOF as ev_eof separate from dispatch's eof flag. Strips EV_EOF→bits.eof mapping from first-pass decode and removes eof from the coalescing merge. Changes dispatch condition to trigger only on events || bits.error and computes eof conditionally based on shutdown state. Removes EVFILT_WRITE oneshot special-case and refactors event updates to toggle EVFILT_READ/EVFILT_WRITE strictly by readable/writable bit differences.
Socket shutdown guard for FIN observation
packages/bun-usockets/src/socket.c
Modifies us_socket_pause() to set is_paused flag and conditionally switch poll registration: when shut down, clears the poll mask to watch nothing; otherwise keeps the previous pause-readable behavior. Comments updated to describe shutdown case handling.
Socket error probing for non-Windows async connect completion
packages/bun-usockets/src/context.c
Adds SO_ERROR socket probing via us_socket_get_error(s) in us_internal_socket_after_open when the passed error is 0 on the non-Windows path, ensuring the real async connect outcome is detected before continuing error handling flow.
Concurrent chunked-FIN fixture and Bun regression test
test/js/web/fetch/fetch-chunked-fin-same-tick-fixture.ts, test/js/web/fetch/fetch-chunked-fin-same-tick.test.ts
Adds a TCP server fixture that constructs and sends a ~600 KiB chunked HTTP/1.1 response followed by immediate FIN via socket.end(), drives 200 iterations across 32 concurrent fetch workers to validate response body byte length, and a Bun test that spawns the fixture and asserts empty stderr, stdout "OK 200", and exit code 0.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: removing the derivation of EOF from kqueue's EV_EOF flag.
Linked Issues check ✅ Passed The code changes directly address both linked issues: fixes kqueue EV_EOF handling (#12730) that caused socket closure before buffer drain, and removes EVFILT_WRITE one-shot registration (#29515) that caused empty response bodies on non-chunked responses.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the kqueue EV_EOF handling issue and maintaining async connect detection. No unrelated modifications were introduced.
Description check ✅ Passed The PR description comprehensively covers the problem, solution, and verification details required by the template.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

kqueue mapped EV_EOF on either filter to dispatch's eof flag, which
loop.c treats as "close after this tick". That diverged from the epoll
path (which only maps EPOLLHUP and discovers half-close via recv()==0)
in two observable ways:

  - An EVFILT_WRITE-only event carrying EV_EOF closed the socket
    without ever entering the recv loop, dropping any response bytes
    still buffered in the kernel.
  - When the recv loop bails early (full 512 KiB read on a busy loop),
    the kqueue-supplied eof flag closed the socket before the next tick
    could drain the rest.

EVFILT_READ is level-triggered and keeps firing after a FIN, so
recv()==0 is now the single source of eof on kqueue, matching Linux.
RST/hard errors remain covered by EV_ERROR and the recv-error path.
A refused/unreachable non-blocking connect() is reported by kqueue as
EVFILT_WRITE with EV_EOF (errno in fflags), not EV_ERROR. With EV_EOF no
longer mapped to dispatch's eof flag, the semi-socket path saw error=0
and fired on_open on a dead socket. Probe getsockopt(SO_ERROR) instead —
the portable contract for async connect completion, already what the
Windows branch effectively does.

Also drop the now-dead new_events==0 one-shot EVFILT_WRITE in
kqueue_change (it relied on EV_EOF and fired immediately on any idle
socket anyway), and switch the new test to a combined-object assertion.
us_socket_pause() drops READABLE, and us_internal_socket_raw_shutdown()
then masked the existing events with READABLE — yielding 0 for a paused
socket. epoll could still observe full close via EPOLLHUP in that state,
but kqueue has no equivalent now that EV_EOF is no longer mapped, so the
socket never woke and never closed.

After SHUT_WR the socket can only terminate via recv()==0 or a recv()
error, so shutdown now arms READABLE unconditionally and clears the
paused flag (pause is meaningless once we've sent FIN — the on_data path
for a SHUT_DOWN socket discards what it reads). us_socket_pause() is
made a no-op on an already-shut-down socket for the same reason.

Also corrects the EV_ERROR comment in epoll_kqueue.c (it only flags
changelist failures; the wait kevent64 calls pass a NULL changelist) and
notes that EV_DELETE on an already-fired one-shot is benign.
@Jarred-Sumner
Jarred-Sumner force-pushed the claude/kqueue-ev-eof-drain branch from 737b1ea to 25d02a5 Compare June 15, 2026 06:46

@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)
packages/bun-usockets/src/context.c (1)

710-735: ⚠️ Potential issue | 🟠 Major

Probe SO_ERROR unconditionally and preserve it for multi-address connect errors.

The current code contradicts its own comment (line 711-717): it says "Probe SO_ERROR unconditionally" but gates the probe on error == 0. Since loop.c:387 passes error || eof as a boolean dispatch signal, any non-zero flag (epoll EPOLLERR/EPOLLHUP or eof) skips the probe entirely, forwarding 1 instead of the actual errno. In the multi-address case, the probed error is also discarded — when exhausting all candidates fails, c->error remains zero and the caller receives no error information.

Always probe SO_ERROR and store the result in c->error before closing a failed candidate socket, so the final error reported reflects the actual connect failure.

Proposed fix
 `#else`
-    if (error == 0) {
-        error = us_socket_get_error(s);
-    }
+    const int poll_error = error;
+    error = us_socket_get_error(s);
+    if (error == 0 && poll_error) {
+        error = poll_error;
+    }
 `#endif`
     if (error) {
         if (c) {
+            if (c->error == 0) {
+                c->error = error;
+            }
             for (struct us_socket_t **next = &c->connecting_head; *next; next = &(*next)->connect_next) {
🤖 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 `@packages/bun-usockets/src/context.c` around lines 710 - 735, Remove the
conditional gate on `error == 0` so that `us_socket_get_error(s)` is always
called to unconditionally probe SO_ERROR, matching the intent stated in the
comment. Store the probed error value in `c->error` before calling
`us_socket_close` on the failed candidate socket, ensuring that when all
connection candidates are exhausted in the multi-address connect scenario, the
actual errno is preserved and available to the caller rather than remaining as
zero or a boolean flag.

Source: Coding guidelines

🤖 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 `@packages/bun-usockets/src/context.c`:
- Around line 710-735: Remove the conditional gate on `error == 0` so that
`us_socket_get_error(s)` is always called to unconditionally probe SO_ERROR,
matching the intent stated in the comment. Store the probed error value in
`c->error` before calling `us_socket_close` on the failed candidate socket,
ensuring that when all connection candidates are exhausted in the multi-address
connect scenario, the actual errno is preserved and available to the caller
rather than remaining as zero or a boolean flag.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6ed94ab2-4407-48c5-8ff6-91a6c7310b85

📥 Commits

Reviewing files that changed from the base of the PR and between 737b1ea and 25d02a5.

📒 Files selected for processing (3)
  • packages/bun-usockets/src/context.c
  • packages/bun-usockets/src/eventing/epoll_kqueue.c
  • packages/bun-usockets/src/socket.c

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

All my earlier feedback has been addressed (SO_ERROR probe, dead one-shot removal, and the EV_ERROR comment fix) and I found nothing new this round — but this reworks core kqueue dispatch semantics for every macOS socket and 25d02a5 additionally changes the shutdown/pause interaction in socket.c, so it's worth a human pass before merge.

Extended reasoning...

Overview

The PR drops the EV_EOF → eof mapping from the kqueue coalescing pass so that end-of-stream is derived solely from recv()==0, matching the epoll path. To compensate it (1) adds an unconditional getsockopt(SO_ERROR) probe in us_internal_socket_after_open on POSIX so refused connects are still detected, (2) removes the now-inert new_events==0 one-shot EVFILT_WRITE registration in kqueue_change, and (3) in 25d02a5 makes us_internal_socket_raw_shutdown unconditionally arm READABLE and clear is_paused (with us_socket_pause becoming a no-op on shut-down sockets) so a paused-then-shutdown socket can still observe the peer's FIN on kqueue. A new fixture/test exercises 200×32-concurrent chunked fetches with same-tick FIN.

Security risks

None identified — this is event-dispatch / lifecycle plumbing with no parsing, auth, or untrusted-input surface. The risk profile is correctness/liveness (dropped bytes, hung sockets, mis-routed connect errors), not security.

Level of scrutiny

High. This is the hot path for every TCP socket on macOS/FreeBSD, the semantics are platform-specific and subtle (EV_EOF vs EV_ERROR vs EPOLLHUP/EPOLLRDHUP), and the PR already needed three follow-up commits to fix regressions surfaced during review (connect-failure detection, dead one-shot, paused+shutdown hang). The final commit introduces a behavioral change to us_socket_shutdown — it now force-resumes a paused socket — which is reasonable per the inline comment but is the kind of cross-cutting lifecycle change a maintainer should sign off on.

Other factors

  • All three of my prior inline comments were addressed; the dispatch comment block now correctly states that EV_ERROR only flags changelist failures and is kept for symmetry.
  • The bug-hunting pass on the current revision found nothing.
  • The new test is well-targeted at the ≥25-ready-poll bail-out and uses the combined {stdout, stderr, exitCode} assertion form.
  • Net: looks correct to me, but the blast radius (all macOS socket I/O) and the iteration history argue for a human reviewer rather than bot approval.

Replaces the previous approach of arming READABLE in raw_shutdown (which
read-and-discarded data the caller had paused for). Instead:

  - kqueue_change(new_events==0) registers EVFILT_READ with EV_CLEAR so a
    paused+shut-down socket gets one wake per state transition (data
    arrival or FIN) without level-triggered spinning on buffered bytes.
  - The dispatch loop forwards EV_EOF as eof only when us_poll_events==0;
    any poll watching READABLE still discovers eof via recv()==0, so the
    original premature-close fix is unchanged.
  - The recv loop is gated on events & READABLE, so the watched==0 case
    never reads — buffered data the caller paused for stays in the kernel
    buffer, matching epoll's EPOLLHUP behavior.

socket.c is reverted to main; the SO_ERROR comment wording is also
tightened per review.
Two refinements to the watched==0 sentinel:

  - Forward EV_EOF as eof only for POLL_TYPE_SOCKET_SHUT_DOWN. An
    allow_half_open socket transitions to watched==0 via loop.c:666 right
    after recv()==0, and the freshly-armed EV_CLEAR EVFILT_READ is
    immediately re-activated by the already-latched FIN — which would
    re-enter on_end. A plain pause (not shut down) likewise stays inert
    until JS resumes it.
  - us_socket_pause() on a shut-down socket now goes to events==0 (not
    WRITABLE) so the sentinel arms in shutdown→pause order too.
Comment thread packages/bun-usockets/src/socket.c Resolved
…tinel gate

us_socket_is_shut_down() is SSL-aware and true after close_notify even
when us_internal_ssl_shutdown left the poll type at POLL_TYPE_SOCKET, so
the arm side and the dispatch gate disagreed for SSL sockets. Use the
raw poll type so both sides key on the same predicate. (The SSL
shutdown→pause strand is pre-existing and unchanged here.)
Comment thread packages/bun-usockets/src/socket.c Resolved
…ady idle

If a tick lands between us_socket_pause() and us_socket_shutdown() —
e.g. an async node:http handler that awaits before res.socket.end() —
the one-shot WRITE pause armed has already fired and loop.c:475 stripped
POLLING_OUT, so us_poll_events==0 and us_poll_change(0) early-returns on
old==new without ever reaching kqueue_change. Call kqueue_change
directly in that case so the EV_CLEAR EVFILT_READ sentinel is armed.

(Pre-existing strand, but the same pause↔shutdown class this PR closes.)
robobun added a commit that referenced this pull request Jul 8, 2026
…d-pipe await fix

Three review rounds each found a new level-triggered busy-loop variant the
targeted is_paused defer introduces (paused+shut_down EPOLLHUP, AF_UNIX
peer-close EPOLLHUP, partial-write-rearms-READABLE + recv()==0). The class
is exactly what #32257 addresses by making recv()==0 the sole eof source for
readable polls on kqueue, so deferring the test-net-write-slow.js fix there.

This PR now only:
- widens the release RSS bound in net-mongodb-pattern-leak.test.ts from 8 to
  24 MB (observed 8-13 MB with flat heapSize and object counts since the
  WebKit upgrade in 00a93bd)
- awaits the floating expectMaxObjectTypeCount in the Windows named-pipe test
  and fixes its TLSSocket vs TCPSocket baseline, so its rejection stops being
  attributed to whatever test is running ~1.5s later
@robobun

robobun commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

The review threads on #33725 (an attempt at a minimal is_paused defer in loop.c for the #29831-introduced test-net-write-slow.js macOS failure) surfaced four level-triggered variants a targeted fix has to handle and that this PR's recv()==0-only approach should cover for free:

  • paused + shut_down TCP: SHUT_WR + peer FIN asserts EPOLLHUP at poll events==0
  • AF_UNIX peer close(): unix_release_sock sets our sk_shutdown = SHUTDOWN_MASK so EPOLLHUP fires with poll type still POLL_TYPE_SOCKET
  • us_socket_write* on partial write re-arms R|W without checking is_paused, so a paused socket can have events & READABLE at entry and hit recv()==0 without on_data ever running
  • end() then >512 KB response under backpressure: is_shut_down fast-close truncates with bytes still buffered (pre-existing since http: couple fetch() receive backpressure to JS body consumption (h1/h2/h3) #29831)

Linking so they are on the checklist here.

@robobun

robobun commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

Related: #33974 gates the eof branch in us_internal_dispatch_ready_poll on !is_paused, which also covers the epoll EPOLLHUP path (both-FIN with buffered data) that this PR does not touch. The two changes are complementary.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants