Skip to content

udp: retry unconnected send once when a stale ICMP poisons sk_err - #36249

Closed
robobun wants to merge 3 commits into
mainfrom
farm/463b37fb/udp-send-stale-icmp
Closed

robobun wants to merge 3 commits into
mainfrom
farm/463b37fb/udp-send-stale-icmp

Conversation

@robobun

@robobun robobun commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

Repro

const live = await Bun.udpSocket({ hostname: "127.0.0.1", socket: { data(_s, d) { got.push(d.toString()); } } });
const dead = /* port nothing listens on */;
const s = await Bun.udpSocket({ hostname: "127.0.0.1", socket: { error() {} } });
s.send("to-dead", dead, "127.0.0.1");          // bounces (ICMP port-unreachable)
s.send("victim", live.port, "127.0.0.1");      // HEALTHY destination
// -> throws ECONNREFUSED synchronously; victim never delivered

On main, 50/50 trials: the second send throws ECONNREFUSED and the datagram is lost. A following sendMany of 10 healthy datagrams throws outright (0/10 delivered), and a batch with a dead port at index 1 short-counts at 2 and drops the healthy tail. node:dgram under Bun hits the same path (50/50 callbacks get ECONNREFUSED, 50/50 lost). Node itself: 0/50.

Cause

Bun enables IP_RECVERR on every UDP socket (us_create_udp_socket sets LIBUS_UDP_LINUX_RECVERR whenever an on_recv_error callback exists, which is always). With it armed, Linux mirrors an ICMP port-unreachable into sk_err. The next sendmsg/sendmmsg on the same socket hits sock_error() inside sock_alloc_send_pskb, which consumes sk_err and fails that send with ECONNREFUSED for a datagram whose own destination was never tried. On loopback the ICMP lands between two back-to-back sends, so the bounce poisons exactly the next send. sendmmsg returns a short count (without setting errno) when this happens mid-batch, which us_udp_socket_send treated as send-buffer-full and stopped.

This is the same mechanism as #4500 seen from the send side; the open PRs for that (#35922 / #35923 / #29135) handle the receive/dispatch path but not the same-tick send-send case, which is poisoned before any epoll pass can drain the error queue.

Fix

packages/bun-usockets/src/udp.c:

  • us_udp_socket_send: when a send on an unconnected socket fails with ECONNREFUSED / EHOSTUNREACH / ENETUNREACH, retry once. sock_error() already cleared sk_err, so the retry reaches the real destination. After a short count on an unconnected socket, resume at the failed index instead of re-arming writable; the next iteration distinguishes a genuine EAGAIN (re-arms) from a cleared sk_err (proceeds). sent > 0 guarantees forward progress so the resume cannot spin, and stale_icmp_retried bounds the -1 retry to once between progress.
  • us_udp_socket_connect / us_udp_socket_disconnect: maintain s->connected (the field existed but was never set). Connected sockets keep the error: there the ICMP is about the only peer.

Verification

New Linux-only tests in test/js/bun/udp/udp_socket.test.ts and test/js/bun/udp/dgram.test.ts (the bug is IP_RECVERR-specific), each failing on main and passing here, 5/5 runs:

  • same-tick send after a bounce reaches a healthy peer: 0/30 lost (was 30/30 threw and lost)
  • sendMany() after a bounce delivers the whole healthy batch: returns 10, 10/10 delivered (was threw ECONNREFUSED, 0/10)
  • sendMany() resumes past a dead destination inside the batch: returns 8, 6/6 live delivered (was returned 2)
  • connected socket still surfaces ECONNREFUSED on the next same-tick send: 30/30 (unchanged)
  • node:dgram unconnected send after a bounce: 0/20 callback errors, 0/20 lost (was 20/20 each)

264/264 in test/js/bun/udp/, 75/75 test/js/node/test/parallel/test-dgram-*.js.


no test proof · iteration 1 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/udp/dgram.test.ts test/js/bun/udp/udp_socket.test.ts

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. udp: only enable IP_RECVERR on connected sockets #29135 - Also fixes IP_RECVERR poisoning unconnected UDP sockets, by disabling IP_RECVERR on unconnected sockets entirely
  2. udp: stop setting IP_RECVERR on UDP sockets #35922 - Stops IP_RECVERR on unconnected sockets and makes recv errors non-fatal by default
  3. udp: do not let remote ICMP kill an unconnected socket #35923 - Prevents remote ICMP from killing unconnected UDP sockets

🤖 Generated with Claude Code

@robobun

robobun commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

Not a duplicate. Those three fix the receive/dispatch side of the same IP_RECVERR mechanism (ICMP reaching on_recv_error / uncaught_exception). This one fixes the send side: two back-to-back sends in the same tick, where the second sendmsg consumes the mirrored sk_err before any epoll pass can drain the error queue, so no amount of errqueue-drain or IP_RECVERR-on-connect gating reaches it.

The diffs do not overlap: this PR touches only us_udp_socket_send and the connected flag in udp.c; those touch loop.c, the IP_RECVERR setsockopt in bsd.c, and on_recv_error in udp_socket.rs. Applies cleanly on top of any of them (and whichever lands first, the send-path retry is still needed for the same-tick case on a socket that was ever connected-then-disconnected, or for ICMP arriving between a reply send and the next one inside the same callback).

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 8 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2dd419d4-bd06-444f-8072-de3117805108

📥 Commits

Reviewing files that changed from the base of the PR and between 2ba6a30 and a2072aa.

📒 Files selected for processing (3)
  • packages/bun-usockets/src/udp.c
  • test/js/bun/udp/dgram.test.ts
  • test/js/bun/udp/udp_socket.test.ts

Walkthrough

Changes

The UDP implementation retries selected stale ICMP send errors for unconnected sockets, continues eligible partial batches, and tracks connection state across connect/disconnect. Linux-only tests cover single sends, sendMany(), dead destinations, and connected socket errors.

UDP stale ICMP recovery

Layer / File(s) Summary
Native UDP recovery and connection state
packages/bun-usockets/src/udp.c
Adds non-Windows ICMP error handling and one-time retries for unconnected sends, resumes eligible partial batches, and updates the socket’s connected state after successful connect or disconnect.
Linux regression coverage
test/js/bun/udp/dgram.test.ts, test/js/bun/udp/udp_socket.test.ts
Adds Linux-only tests for stale ICMP behavior across callback sends, sendMany(), dead destinations, healthy deliveries, and connected sockets.

Possibly related PRs

  • oven-sh/bun#35922: Modifies the same UDP ICMP error-recovery path, including IP_RECVERR handling and clearing pending errors on disconnect.

Suggested reviewers: cirospaciari

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly matches the main change: retrying unconnected UDP sends after stale ICMP errors on Linux.
Description check ✅ Passed The description is detailed and covers both the change and verification, though it uses different headings than the template.

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

Comment thread test/js/bun/udp/udp_socket.test.ts Resolved
Comment thread packages/bun-usockets/src/udp.c Resolved

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

Both earlier inline comments are addressed in 1c2eaa1 — the retry/resume paths are now __linux__-gated and the hard-error fallthrough re-arms writable, and the connected-socket test's toBe(30) was loosened to toBeGreaterThan(0). I didn't find further issues, but this reworks the native us_udp_socket_send control flow (retry loop, pointer-advance-by-sent) and sits in the same design space as three open PRs (#29135 / #35922 / #35923) that instead gate IP_RECVERR itself — worth a human deciding which approach (or combination) lands.

What was reviewed:

  • Loop termination: sent > 0 gate on the resume path plus stale_icmp_retried reset only on progress, so no spin; sent == 0 on Linux still falls through to re-arm.
  • Non-Linux behavior: pointer advancement moved from pre-send-by-count to post-send-by-sent is equivalent on the paths that reach the next iteration; the only delta is the new re-arm on hard-error-after-progress (an improvement).
  • s->connected is set via us_udp_socket_connect for both the creation-time connect: option and the runtime connect() call (both route through uws::udp::Socket::connect).
Extended reasoning...

Overview

Touches packages/bun-usockets/src/udp.c (us_udp_socket_send, us_udp_socket_connect, us_udp_socket_disconnect) and adds five Linux-only tests across test/js/bun/udp/udp_socket.test.ts and test/js/bun/udp/dgram.test.ts. The send loop now advances pointers by sent after the syscall (instead of by count before it), retries once on an unconnected Linux socket when sendmsg fails with ECONNREFUSED/EHOSTUNREACH/ENETUNREACH, and resumes at the failed index after a short-counted sendmmsg. s->connected (previously declared but never written) is now maintained by the connect/disconnect wrappers.

Security risks

None identified. The retry is bounded to one attempt between progress (stale_icmp_retried), the resume path requires sent > 0 so it cannot spin, and the change is read-path only over errno — no new user-controlled input reaches native code.

Level of scrutiny

High. This is native C in the UDP send hot path shared by Bun.udpSocket, node:dgram, and QUIC's non-packets_out fallback, with platform-specific kernel reasoning (Linux sk_err / sock_error() semantics under IP_RECVERR). The control-flow rewrite (moving pointer advancement, adding two continue targets) is small but subtle enough that a regression would silently drop or duplicate datagrams.

Other factors

  • Both of my earlier inline comments (deferred-softirq flake in the connected test; __linux__ vs _WIN32 gating and re-arm on the total_sent > 0 fallthrough) were applied in 1c2eaa1 and verified in the current diff.
  • Three open PRs (#29135, #35922, #35923) address the receive/dispatch side of the same IP_RECVERR mechanism, some by disabling IP_RECVERR on unconnected sockets entirely. The author's timeline reply argues this send-side retry is still needed for the same-tick case even on top of those, which reads correct to me, but the choice of which combination to land is a maintainer call.
  • I checked that both the creation-time connect: { ... } option and the runtime .connect() method route through us_udp_socket_connect (via uws::udp::Socket::connect at src/runtime/socket/udp_socket.rs:743 and :1915), so s->connected is set for both. Adopted-fd sockets (us_create_udp_socket_from_fd) don't get IP_RECVERR, so a stale connected = 0 there doesn't reach the retry in practice.

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

Both prior review points are addressed in 1c2eaa1 — the retry/resume paths are now __linux__-only, the hard-errno fallthrough re-arms writable, and the connected-socket assertion is loosened to > 0. I didn't find anything new, but this reworks the us_udp_socket_send loop's control flow and pointer advancement, and there are three open sibling PRs (#29135, #35922, #35923) touching the same IP_RECVERR mechanism from the receive side — a human should confirm the approach and landing order.

What was reviewed:

  • Pointer advancement moved from pre-send-by-count to post-send-by-sent — equivalent on non-resume paths, enables the Linux resume
  • s->connected now maintained by us_udp_socket_connect/disconnect; both Rust call sites (creation-time connect: option and runtime .connect()) route through it
  • stale_icmp_retried reset on every progress point; the sent > 0 gate on the partial-batch resume prevents a spin
  • Non-Linux sent < count still takes the pre-PR unconditional re-arm-and-return
Extended reasoning...

Overview

The PR changes us_udp_socket_send in packages/bun-usockets/src/udp.c to retry once when an unconnected Linux UDP send fails with ECONNREFUSED/EHOSTUNREACH/ENETUNREACH (a stale sk_err mirrored by IP_RECVERR from a previous datagram's ICMP bounce), and to resume a sendmmsg batch past a mid-batch short count instead of treating it as buffer-full. It also wires s->connected in us_udp_socket_connect/disconnect (the field existed but was never set) so the retry can be gated to unconnected sockets. Five new Linux-only tests cover single send, sendMany after a bounce, sendMany with a dead destination mid-batch, connected-socket-still-errors, and the node:dgram path.

Security risks

None identified. The change is confined to send-side error handling on a socket the caller already owns; no new input parsing, no new resource acquisition. The retry is bounded to once between progress points and gated on three specific errno values, so it cannot spin or amplify.

Level of scrutiny

Moderate-to-high. This is native C in the UDP send hot path with a control-flow rework: pointer advancement moved from before the syscall (by count) to after (by sent), the sent < 0 branch gained a Linux-only continue, the sent < count branch gained a Linux-only resume, and the total_sent > 0 hard-error fallthrough now re-arms writable. I traced each path on Linux and non-Linux and the non-Linux behavior is preserved (partial batch → re-arm and return, exactly as before), but the reasoning leans on Linux sendmmsg/sock_error() semantics that a maintainer familiar with the usockets layer should confirm.

Other factors

  • My two prior inline comments (softirq-timing flakiness in the connected test; #ifndef _WIN32 → #ifdef __linux__ and re-arm on hard-errno fallthrough) were both applied in 1c2eaa1 and the threads are resolved.
  • Three open PRs (#29135, #35922, #35923) address the receive/dispatch side of the same IP_RECVERR mechanism with different strategies (disabling IP_RECVERR on unconnected sockets, draining the errqueue). The author's rebuttal that this send-side fix is orthogonal is convincing, but landing order and the combined behavior are a maintainer call.
  • The s->connected field is now load-bearing for the first time; I verified both the creation-time connect: option (udp_socket.rs:743) and the runtime .connect() method (udp_socket.rs:1915) call us_udp_socket_connect, so the gate is correct for both.
  • Tests are Linux-only (skipIf(!isLinux)), so CI on Linux is the proof; the PR body reports 264/264 in test/js/bun/udp/ and 75/75 vendored test-dgram-*.

robobun added 3 commits July 28, 2026 21:01
Bun enables IP_RECVERR on every UDP socket, so on Linux an ICMP
port-unreachable from a previous datagram is mirrored into sk_err. The
next sendmsg/sendmmsg on the same unconnected socket consumes that via
sock_error() and fails with ECONNREFUSED for a datagram whose own
destination was never tried. On loopback this is deterministic: a send
to a dead port poisons the very next send to a healthy one, and a
following sendMany either throws outright or short-counts and drops the
healthy tail. node:dgram never enables IP_RECVERR and is unaffected.

us_udp_socket_send now retries once when an unconnected send fails with
ECONNREFUSED/EHOSTUNREACH/ENETUNREACH (sock_error() already cleared
sk_err, so the retry reaches the real destination), and resumes at the
failed index after a short count instead of treating it as buffer-full.
Connected sockets keep the error: there the ICMP is about the only peer.
us_udp_socket_connect/disconnect now track s->connected so the gate is
accurate.
…h; loosen connected-control assertion

The sk_err poisoning is IP_RECVERR-specific (Linux only), so the retry
and resume paths are now under __linux__ instead of !_WIN32, restoring
the pre-PR unconditional re-arm on macOS/BSD where ENOBUFS is common and
there is no sk_err to clear. The total_sent>0 error fallthrough now
re-arms writable so on_drain still fires when the resumed index hits a
persistent per-message errno (EMSGSIZE/EACCES/EPERM).

The connected-socket control test now asserts threw > 0: the invariant
it guards (retry not applied to connected sockets) would yield threw==0,
and requiring 30/30 assumed loopback softirq is never deferred.
@robobun
robobun force-pushed the farm/463b37fb/udp-send-stale-icmp branch from 18dd25d to a2072aa Compare July 28, 2026 21:01

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

No new issues found — both earlier inline comments were addressed in 8d10897 (retry/resume gated to __linux__, hard-error fallthrough now re-arms writable, connected control test loosened to toBeGreaterThan(0)). Deferring to a human because this reworks the native us_udp_socket_send loop and there are three overlapping open PRs (#29135, #35922, #35923) on the same IP_RECVERR mechanism that a maintainer should coordinate.

What was reviewed:

  • Pointer-advancement move from pre-send-by-count to post-send-by-sent — behavior-preserving on every non-resume path (full batch: sent==count; partial on non-Linux/connected: returns before pointers matter; sent==0: falls through the sent>0 guard to re-arm+return).
  • Termination: stale_icmp_retried bounds the -1 retry to once between progress; the partial-resume requires sent>0 so it cannot spin.
  • s->connected is set only via us_udp_socket_connect/disconnect, which is the sole path the Rust side (uws_sys/udp.rs) uses; both us_create_udp_socket* already zero it.
Extended reasoning...

Overview

Touches packages/bun-usockets/src/udp.c (the native us_udp_socket_send loop plus us_udp_socket_connect/disconnect) and adds five Linux-only tests across test/js/bun/udp/udp_socket.test.ts and test/js/bun/udp/dgram.test.ts. The send loop is restructured: pointer advancement moves from before the syscall (by count) to after (by sent), a one-shot retry is added on ECONNREFUSED/E*UNREACH for unconnected sockets, and short-counted batches on unconnected Linux sockets now resume at the failed index instead of re-arming immediately. s->connected (an existing but never-written bitfield) is now maintained.

Security risks

None identified. The retry is bounded to once between forward progress and gated to a fixed errno set on unconnected sockets, so it cannot be induced into a spin or a duplicate send by remote input. No new user-controlled data reaches a syscall.

Level of scrutiny

High. This is C code in the UDP send hot path, reasoning about Linux sk_err/sendmmsg short-count semantics, and it restructures control flow (pointer advancement timing) rather than making a purely additive change. The PR description also notes the tests are platform-specific and were not proven locally ("Deferring to CI"). Three other open PRs address the same IP_RECVERR poisoning from different angles (disabling IP_RECVERR on unconnected sockets vs. retrying the send), which is a design choice a maintainer should weigh — the author's argument that this is orthogonal (same-tick send-send, connect-then-disconnect) is plausible but that's exactly the kind of coordination call a human should make.

Other factors

Both of my earlier inline concerns were applied in 8d10897 and are reflected in the current diff. I traced the pointer-advancement refactor against every exit path (EAGAIN, hard error at index 0, hard error after progress, partial batch on connected/non-Linux, sent==0) and it preserves pre-PR behavior everywhere the new resume/retry doesn't apply. The connected flag is only read on Linux and only written via the two functions the Rust FFI wrapper calls, and both socket constructors already zero it. Test structure follows the file's conventions (bounded polling, skipIf(!isLinux), dead-port helper matches the existing getDeadPort pattern in dgram.test.ts).

@robobun

robobun commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: the diff itself is green on every lane that actually built.

  • Build 84258: only red lane was darwin-14-x64 on no-orphans.test.ts (perl daemon timeout) and streams-leak.test.ts (RSS threshold), both unrelated to UDP; the other 19 failures were parallel-batch-only and passed alone.
  • Build 84341 (after rebase onto ci(runner): cap parallel test width at 4 on macOS (x64 and arm64) #36231): the linux x64/x64-asan/aarch64 and darwin-x64 build-cpp steps expired waiting for an agent (never ran), which cascaded into the build-bun and test lanes on those targets showing Expired/Failed. Every build-cpp that did run (darwin-aarch64, musl x64/aarch64, android, freebsd, windows x64/aarch64) passed. The 5 test failures that did run are all tagged flaky and passed alone.

No UDP or dgram test failed on any lane in either build. Ready for review; needs a rebuild or retry on the expired lanes.

@robobun

robobun commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 5:24 PM PT - Jul 28th, 2026

❌ @robobun, your commit a2072aa has 1 failures in Build #84341 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 36249

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

bun-36249 --bun

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-28, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

@robobun robobun closed this Sep 13, 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.

2 participants