Repository navigation
usockets: stop deriving eof from kqueue EV_EOF - #32257
Jarred-Sumner wants to merge 7 commits into
Conversation
|
Updated 1:26 PM PT - Jun 15th, 2026
✅ @Jarred-Sumner, your commit 7e18629b7eeb006d5a47746b9d6e5b9c32aad759 passed in 🧪 To try this PR locally: bunx bun-pr 32257That installs a local version of the PR into your bun-32257 --bun |
|
Found 2 issues this PR may fix:
🤖 Generated with Claude Code |
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (2)
WalkthroughRemoves ChangesSocket error handling and kqueue EV_EOF fix with regression test
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
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.
737b1ea to
25d02a5
Compare
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)
packages/bun-usockets/src/context.c (1)
710-735:⚠️ Potential issue | 🟠 MajorProbe 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. Sinceloop.c:387passeserror || eofas a boolean dispatch signal, any non-zero flag (epollEPOLLERR/EPOLLHUPoreof) skips the probe entirely, forwarding1instead of the actual errno. In the multi-address case, the probed error is also discarded — when exhausting all candidates fails,c->errorremains zero and the caller receives no error information.Always probe
SO_ERRORand store the result inc->errorbefore 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
📒 Files selected for processing (3)
packages/bun-usockets/src/context.cpackages/bun-usockets/src/eventing/epoll_kqueue.cpackages/bun-usockets/src/socket.c
There was a problem hiding this comment.
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_ERRORonly 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.
…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.)
…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.)
…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
|
The review threads on #33725 (an attempt at a minimal
Linking so they are on the checklist here. |
|
Related: #33974 gates the eof branch in |
What
On kqueue, stop deriving
eoffromEV_EOFfor any socket that is polling READABLE —recv()==0becomes the single source ofeofthere, matching epoll (which mapsEPOLLHUPbut neverEPOLLRDHUP).To keep the two cases that legitimately depended on
EV_EOFworking:EVFILT_WRITE + EV_EOF(notEV_ERROR).us_internal_socket_after_opennow probesgetsockopt(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.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 neverrecv()s.kqueue_changenow arms an edge-triggeredEVFILT_READforevents==0, and the dispatch loop forwards itsEV_EOFaseofonly whenus_poll_events==0 && POLL_TYPE_SOCKET_SHUT_DOWN. The recv loop is gated onevents & READABLE, so no buffered data is read or discarded — parity with epoll'sEPOLLHUPclose.us_socket_pauseon an already-raw-shut-down socket now goes toevents==0(notWRITABLE) so the sentinel arms in either order.Why
kqueue sets
EV_EOFonEVFILT_READfor a peer FIN (≈EPOLLRDHUP) and onEVFILT_WRITEwhen the peer's read side is gone. The dispatch loop OR'd it from either filter intoeof, whichloop.ctreats as "fireon_endand close after this tick". That diverged from Linux in two ways that could drop response bytes on macOS:events & LIBUS_SOCKET_READABLEis false, so the recv loop never runs and theeofblock atloop.c:654closes with the response still in the kernel buffer. The chunked decoder is mid-chunk →ConnectionClosedfromfetch().loop.c:599-611checkserrorbut noteof; on a busy loop (num_ready_polls ≥ 25) it stops after one ~512 KiB read, and the kqueue-suppliedeofthen closes before the next tick can drain the rest.EVFILT_READis level-triggered and keeps firing after a FIN, sorecv()==0reliably reports end-of-stream after the buffer is drained. RST and hard errors are still covered by therecv()-error branch.Test
test/js/web/fetch/fetch-chunked-fin-same-tick.test.tsruns 200 concurrentfetch()es against a rawnetserver 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