Repository navigation
fetch: add an RFC 8305 per-attempt connect timer so a blackholed address does not stall for ~130 s - #32949
fetch: add an RFC 8305 per-attempt connect timer so a blackholed address does not stall for ~130 s#32949robobun wants to merge 10 commits into
Conversation
WalkthroughImplements RFC 8305 Happy Eyeballs connect staggering for ChangesHappy Eyeballs RFC 8305 Implementation
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
be7dec3 to
962c023
Compare
|
Updated 4:42 PM PT - Jul 10th, 2026
❌ @robobun, your commit 1539877 has 3 failures in
🧪 To try this PR locally: bunx bun-pr 32949That installs a local version of the PR into your bun-32949 --bun |
54fa87b to
2306c37
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@src/runtime/dns_jsc/dns.rs`:
- Around line 3009-3014: Cap the JS-provided addresses length in the dns_jsc
path before any native allocation. In the code that reads
args[1].get_length(global) and then calls Box::new_uninit_slice(count), add an
upper-bound validation for count (using the existing DNS seed test limit or a
similar constant) and reject oversized inputs before allocating results. Keep
the empty-array check, but ensure the new limit check happens first in this
validation flow.
In `@test/js/web/fetch/fetch-happy-eyeballs.test.ts`:
- Around line 93-95: The fallback in the fetch-happy-eyeballs test is
incorrectly using bail() when dnsCacheSeed is missing and the fixture is
non-root, which lets USE_SYSTEM_BUN=1 skip the regression instead of failing.
Update the affected test branches in fetch-happy-eyeballs.test.ts (including the
related non-root path around the later matching block) so they either produce a
deterministic non-root fallback or return an explicit failing result, and avoid
any skip/bail behavior in the test setup.
🪄 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: db6b8019-c779-444a-b603-c68e75e73085
📒 Files selected for processing (8)
packages/bun-usockets/src/context.cpackages/bun-usockets/src/internal/internal.hpackages/bun-usockets/src/loop.cpackages/bun-usockets/src/socket.csrc/codegen/generate-js2native.tssrc/js/internal-for-testing.tssrc/runtime/dns_jsc/dns.rstest/js/web/fetch/fetch-happy-eyeballs.test.ts
2306c37 to
d454dde
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/web/fetch/fetch-happy-eyeballs.test.ts`:
- Around line 77-83: The fallback in the fetch happy-eyeballs test mutates the
system hosts file, which breaks hermetic test behavior. Update the missing-hook
path in fetch-happy-eyeballs.test.ts so it does not call
fs.readFileSync/fs.writeFileSync on /etc/hosts or register restoreHosts on exit;
instead, have this branch return an explicit failing JSON result or other
deterministic test outcome that avoids changing host configuration. Keep the
change localized around the root-only fallback logic that currently uses
process.getuid and the addrs/host setup.
🪄 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: c448124e-c139-4023-894f-7ebc8de10c8f
📒 Files selected for processing (9)
packages/bun-usockets/src/context.cpackages/bun-usockets/src/eventing/epoll_kqueue.cpackages/bun-usockets/src/internal/internal.hpackages/bun-usockets/src/loop.cpackages/bun-usockets/src/socket.csrc/codegen/generate-js2native.tssrc/js/internal-for-testing.tssrc/runtime/dns_jsc/dns.rstest/js/web/fetch/fetch-happy-eyeballs.test.ts
There was a problem hiding this comment.
The 1f4cf3c fix addresses the re-entrancy concern I raised and the new abort test is a good addition — I have nothing further, but given this adds a new timer lifecycle into the core usockets connect/close path it's worth a human pass.
Extended reasoning...
Overview
This PR adds an RFC 8305 per-attempt connect timer to bun-usockets so that when the first CONCURRENT_CONNECTIONS (4) resolved addresses blackhole SYNs, later addresses are tried after 300 ms instead of waiting ~130 s for kernel SYN-retry exhaustion. It touches context.c (timer arm/callback, hooked into us_internal_socket_after_resolve), socket.c / loop.c / internal.h (timer storage on us_connecting_socket_t, deferred close in us_internal_free_closed_sockets, addrinfo_head neutralization on both retirement paths), and epoll_kqueue.c (a pre-existing leak fix in us_create_timer). It also adds a test-only dnsCacheSeed binding (dns.rs + codegen + internal-for-testing.ts) and a Linux-only hermetic test that builds 4 blackholed listeners + 1 live server and asserts the fetch succeeds before the 4 s abort, plus a second test that aborts mid-connect with the timer still armed.
Security risks
No auth/crypto/permissions surface. The new dnsCacheSeed is gated behind bun:internal-for-testing (CI/debug-only), validates each entry via ares_inet_pton, and caps the array at 64 entries before allocation. The unsafe Rust block fully initializes each MaybeUninit<ResultEntry> before assume_init; on parse failure the partially-initialized Box<[MaybeUninit<_>]> is dropped without running element destructors (correct, since ResultEntry holds only POD addrinfo/sockaddr_storage). The C changes are the more sensitive part: a new heap timer holding a raw us_connecting_socket_t* whose lifetime spans event-loop batches and JS re-entry.
Level of scrutiny
High. This is production-critical native networking code with manual lifetime management across three teardown paths (us_connecting_socket_free, us_connecting_socket_close, us_internal_free_closed_sockets) and an explicit dependency on event-loop batch ordering and re-entrancy semantics. I previously flagged a UAF on the re-entered-tick path; the author fixed it correctly in 1f4cf3c by nulling addrinfo_head at the top of us_connecting_socket_close (before Bun__addrinfo_freeRequest and the JS dispatch), and the redundant neutralization in _free covers the success path (us_internal_socket_after_open). The design is well-reasoned and well-commented, but the interaction between connect_timer, the deferred-free list, kqueue's lack of ready-poll scrubbing for timers, and tick_depth re-entry is subtle enough that a maintainer familiar with the usockets lifecycle should sign off.
Other factors
All four prior review threads (CodeRabbit ×3, mine ×2) are resolved with code changes. The bug-hunting system found nothing on the current revision. Tests pass under ASAN per the PR description, and the new abort test specifically exercises the close-with-live-timer path. The robobun build-status comment shows a failure on an earlier commit (97a2d8a) but two commits have landed since. None of this changes the fact that the change is non-trivial new lifecycle code in a hot path, which is outside my approval bar.
There was a problem hiding this comment.
Both of my earlier concerns are addressed and I found no further issues, but this adds new timer-lifecycle state to the core usockets connect path (with deferred-close ordering and event-loop re-entrancy invariants), so it warrants a human sign-off.
Extended reasoning...
Overview
This PR adds an RFC 8305 per-attempt connect timer to bun-usockets so that when the first CONCURRENT_CONNECTIONS (4) resolved addresses silently drop SYNs, later addresses in the same DNS answer are still tried after ~300 ms instead of stalling for ~130 s on kernel SYN-retry exhaustion. It touches context.c (timer arm/callback), internal.h (new connect_timer field), loop.c (deferred timer close in us_internal_free_closed_sockets), socket.c (neutralize addrinfo_head on both retirement paths), and epoll_kqueue.c (fixes a pre-existing leak in us_create_timer on timerfd_create failure). It also adds a test-only dnsCacheSeed hook (unsafe Rust in dns.rs plus a codegen/JS binding) and a Linux-only hermetic test that builds blackholed listeners via raw libc and seeds the DNS cache.
Security risks
None that affect untrusted input. The new seed_cache_for_testing host function is only reachable via bun:internal-for-testing, validates argument types, caps the address count at 64, and parses each entry with ares_inet_pton before writing into the result buffer. The C-side changes do not parse external data; they manage timer/pointer lifetimes around the existing connect path.
Level of scrutiny
High. This is core C networking code with subtle lifecycle invariants: the timer is intentionally closed only in us_internal_free_closed_sockets (after the ready-poll dispatch batch) rather than from a socket callback, and addrinfo_head must be nulled on both us_connecting_socket_close (before the JS error dispatch, which can re-enter the loop) and us_connecting_socket_free so a same-batch or inner-tick timer fire becomes a no-op. I previously flagged a UAF on the re-entrant path; it was fixed in 1f4cf3c by neutralizing addrinfo_head at the top of us_connecting_socket_close, and a second test was added that aborts an 8-address connect with the timer still armed so the teardown runs under ASAN. The reasoning in the PR description and code comments is careful and matches the implementation, but getting this ordering wrong is a heap-use-after-free in production networking code, so a maintainer familiar with the usockets eventing model should confirm the design.
Other factors
All prior review threads (CodeRabbit and mine) are resolved with corresponding commits. The bug-hunting pass on the latest revision found nothing. The Rust seed_cache_for_testing uses MaybeUninit and raw-pointer writes but each slot is fully initialized before assume_init, the early-return on a bad literal only leaks MaybeUninit slots (no drop needed), and the ai_addr/ai_next fixup is done in a second pass after the boxed slice's final address is settled. The test is Linux+glibc-only via static skipIf and emits a deterministic failing JSON when dnsCacheSeed is unavailable, so older builds fail rather than skip.
There was a problem hiding this comment.
Both of my earlier concerns are addressed and I didn't find anything new, but this is subtle timer-lifecycle work in the core usockets connect path (plus new unsafe DNS-cache plumbing), so it's worth a human pass before merging.
Extended reasoning...
Overview
This PR adds an RFC 8305 per-attempt connect timer to bun-usockets so a blackholed first batch of resolved addresses doesn't stall fetch()/Bun.connect() for ~130 s. It touches the C event-loop core (context.c, loop.c, socket.c, internal.h, epoll_kqueue.c), adds a test-only dnsCacheSeed Rust binding (dns.rs with MaybeUninit/raw-pointer initialization, plus codegen and internal-for-testing.ts wiring), and a Linux-only hermetic test.
Security risks
No auth/crypto/permission surfaces. The new dnsCacheSeed is gated behind bun:internal-for-testing and validates inputs (string/array types, ≤64 entries, ares_inet_pton per element), so it isn't reachable from untrusted code. The main risk class here is memory safety in the new C timer lifecycle — the same-batch / re-entered-tick UAF I flagged earlier was real and has been fixed by neutralizing addrinfo_head at the top of us_connecting_socket_close and deferring us_timer_close to us_internal_free_closed_sockets.
Level of scrutiny
High. This is production-critical networking that runs on every multi-address connect, and the correctness depends on event-loop dispatch-batch ordering, kqueue vs. epoll timer-close semantics, and loop re-entrancy from JS callbacks. The fact that one genuine UAF was found and fixed during review is itself a signal that the lifecycle is subtle enough to deserve a maintainer's eyes on the final shape (particularly the deferred-close in loop.c and the dual neutralization in socket.c).
Other factors
All four prior inline threads (mine and CodeRabbit's) are resolved, the test fixture is now hermetic (no /etc/hosts mutation, no root requirement), and the PR description documents an ASAN proof that the deferred timer close is load-bearing. The new Rust seed_cache_for_testing uses a fair amount of unsafe but each block is commented and the early-return on invalid literals correctly drops the partially-uninit Box<[MaybeUninit<_>]> without running destructors. Nothing blocking from me; deferring on complexity rather than any open issue.
Jarred-Sumner
left a comment
There was a problem hiding this comment.
This is not the correct approach. To do it in fetch, we should put it on AsyncHTTP and make it an EventLoop.Timer. us_timer_t is extremely slow. And I thought this already existed?
|
You're right, and thanks. Moving it. On "I thought this already existed": it exists for I'll drop the |
|
Done in 2234350. The attempt delay is now an To make every fetch addressable (not just abortable ones), All of the earlier |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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 `@src/event_loop/EventLoopTimer.rs`:
- Around line 206-207: Keep FetchConnectAttempt on real time by moving its
handling out of the fake-timer path and into the real-time arm in
EventLoopTimer. Update the logic around the FetchConnectAttempt variant so it is
armed via TimespecMockMode::ForceRealTime, not through AllowMockedTime, and
verify the FetchTasklet happy-eyeballs delay still progresses correctly when
useFakeTimers() is enabled.
🪄 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: 772aba86-0a97-4e01-a862-2dba2ec3723f
📒 Files selected for processing (11)
packages/bun-usockets/src/context.cpackages/bun-usockets/src/libusockets.hsrc/event_loop/EventLoopTimer.rssrc/http/AsyncHTTP.rssrc/http/HTTPThread.rssrc/http/lib.rssrc/runtime/dispatch.rssrc/runtime/webcore/fetch/FetchTasklet.rssrc/uws_sys/ConnectingSocket.rssrc/uws_sys/socket.rstest/js/web/fetch/fetch-happy-eyeballs.test.ts
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)
src/runtime/webcore/fetch/FetchTasklet.rs (1)
461-463: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the added comments to the 3-line limit.
These comments are useful, but several new blocks exceed the repository’s comment-length rule. As per coding guidelines, “Keep code comments to 3 lines max.”
Also applies to: 825-827, 2264-2269, 2297-2300, 2324-2326
🤖 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/webcore/fetch/FetchTasklet.rs` around lines 461 - 463, Condense the new multi-line comments in FetchTasklet so each comment block stays within the repository’s 3-line limit. Update the added comment near the timer unlink/deinit logic and the other flagged comment blocks in the same file by keeping only the essential explanation while preserving context around the relevant logic in FetchTasklet and its timer handling methods. Make sure each comment is shortened rather than split into longer prose.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 `@src/runtime/webcore/fetch/FetchTasklet.rs`:
- Around line 461-463: Condense the new multi-line comments in FetchTasklet so
each comment block stays within the repository’s 3-line limit. Update the added
comment near the timer unlink/deinit logic and the other flagged comment blocks
in the same file by keeping only the essential explanation while preserving
context around the relevant logic in FetchTasklet and its timer handling
methods. Make sure each comment is shortened rather than split into longer
prose.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: e1d512a2-cb9e-430e-8631-f55808810a22
📒 Files selected for processing (2)
src/event_loop/EventLoopTimer.rssrc/runtime/webcore/fetch/FetchTasklet.rs
|
CI note for whoever looks at the red X on the rebased head (1539877, build 71636, finished: 283 of 286 jobs green). All three failing tests are endemic PR-branch flake right now, each hard-failing on unrelated branches in the same window:
My own |
There was a problem hiding this comment.
No bugs found in the current revision, but this touches the per-request fetch hot path (unconditional abort-tracker registration, a new cross-thread nudge channel, and an EventLoopTimer whose node lives inside the FetchTasklet heap box), so it's worth a human pass on the lifecycle and the every-fetch overhead before merge.
Extended reasoning...
Overview
This PR adds an RFC 8305 per-attempt connect timer to fetch() so a blackholed address in the first parallel-connect batch doesn't stall the request for ~130 s. It spans 15 files across four layers: a one-function C addition in bun-usockets (us_connecting_socket_start_next) plus a small leak fix in epoll's us_create_timer; Rust FFI shims in uws_sys; HTTP-thread plumbing (HTTPThread gains a queued_connect_nudges channel, AsyncHTTP now assigns async_http_id and registers in the abort tracker unconditionally); a new EventLoopTimer tag and an embedded timer in FetchTasklet with arm/remove/fire handlers; a test-only dnsCacheSeed host function in dns.rs with ~100 lines of unsafe (MaybeUninit slice, ares_inet_pton FFI, hand-built addrinfo linked list); and a Linux-only integration test.
The PR was substantially redesigned mid-review (the original us_timer_t-based approach was dropped in favor of an EventLoop.Timer owned by the fetch, per a reviewer's request), and an earlier revision had a real UAF that was caught and fixed. All inline review threads are now resolved.
Security risks
No auth, crypto, or permission surfaces are touched. The new dnsCacheSeed is gated behind bun:internal-for-testing and caps its input at 64 entries. The main risk class here is memory-lifetime / cross-thread correctness rather than security: the connect_attempt_timer node is held by raw pointer in the VM timer heap and must be unlinked in clear_data before the tasklet box is freed, and the nudge resolves an id on the HTTP thread through the abort tracker after the JS thread may have torn down the request.
Level of scrutiny
High. This is production-critical: the unconditional async_http_id assignment and abort-tracker put/remove now run on every fetch(), and a 300 ms repeating timer is armed for every fetch until first progress. The cross-thread nudge channel, the timer-in-struct lifecycle, and the unsafe DNS-seed code each individually warrant maintainer eyes; together with the mid-PR redesign they put this well past what should be bot-approved.
Other factors
The bug-hunting pass on the current revision found nothing. Tests pass under ASAN per the description, and the only red CI lane is a darwin artifact-download infra failure unrelated to the diff. The author has been responsive to every review comment. None of that changes the bar — this is a non-trivial change to a hot path with new lifetime invariants, so deferring to a human.
1370f45 to
7e98efe
Compare
…ess does not stall for ~130 s A hostname whose first CONCURRENT_CONNECTIONS (4) resolved addresses silently discard SYNs (filtered network, dead host) blocks fetch() and Bun.connect() for ~130 s on Linux, because usockets only advances to the next address when an in-flight connect hard-fails, and a dropped SYN does not fail until the kernel exhausts SYN retransmits. A reachable 5th address in the same DNS answer is never tried. Node, curl and browsers all handle this in under a second (RFC 8305 Happy Eyeballs; Node's autoSelectFamily). Arm a repeating 300 ms connection-attempt timer on the connecting socket after the initial parallel batch. Each tick starts one more untried address. The timer only exists for results with more than CONCURRENT_CONNECTIONS addresses and self-closes once the list is exhausted. Timer lifecycle: the timer is closed in us_internal_free_closed_sockets, after the ready-poll dispatch batch, never from a socket callback. A tick already queued in the same kevent/epoll batch when the connecting socket is retired would otherwise dispatch a freed timer (the kqueue us_timer_close does not scrub pending ready polls the way us_poll_stop does for fds). us_connecting_socket_free neutralizes addrinfo_head so such a tick cannot start new connects on the retired socket either. Also release the us_create_poll allocation that the epoll us_create_timer leaked when timerfd_create fails, the one way this new call site can see a NULL timer. Complements #32864, which fixes the address-family interleave in process_results and lists this per-attempt timer as out of scope. Adds dnsCacheSeed to bun:internal-for-testing so the test can inject a deterministic multi-address DNS answer without touching the system hosts file, plus the corresponding generate-js2native hand-export entry.
A build without the dnsCacheSeed test hook now emits a failing result directly instead of mutating /etc/hosts, so the fixture is hermetic and the no-hook case still fails the test deterministically without needing root.
…_close us_connecting_socket_close dispatches on_connecting_error into user JS before it reaches us_connecting_socket_free, and that JS can re-enter the event loop (loop.c's tick_depth guard exists for exactly this). A connect_timer tick dispatched from such an inner tick saw c->closed == 1 but addrinfo_head still set, so it could start a new connect on a closing socket: a read through a possibly-freed result buffer, and a fresh us_socket_t whose connect_state dangles once c is freed. Null addrinfo_head right after c->closed is set, before Bun__addrinfo_freeRequest (which can free the buffer it points into) and before the JS dispatch, so the timer callback's addrinfo_head == NULL guard holds on both retirement paths. Also add a test that aborts an 8-address connect while the attempt timer is still armed with untried addresses, so this teardown runs under ASAN.
…ifetime comment The happy-eyeballs test always placed the live address after the initial CONCURRENT_CONNECTIONS batch, so the attempt timer had always self-closed on its first tick before the connecting socket was retired. The deferred us_timer_close in us_internal_free_closed_sockets, the only teardown for a still-armed timer, was therefore never executed by any test; deleting it did not fail anything, even though it is what prevents a leaked repeating timer from dereferencing the freed connecting socket on the most common production shape (a >4-address hostname whose live address is in the first batch). Rework the second test into that shape: a live-address-first fetch retires the connecting socket while its timer is still armed and has never ticked, and the following all-blackholed abort fetch keeps the event loop alive past the timer's 300 ms deadline so a leak is observed. With the deferred close deleted this now fails under ASAN with heap-use-after-free in us_internal_connect_timer_cb (context.c) freed by us_internal_free_closed_sockets (loop.c) allocated by us_socket_group_connect (context.c) and passes with it present. Also assert that the first test's success took at least 250 ms, proving it arrived via the attempt timer and not another path. The connect_timer comment in internal.h stated a false invariant (never closed from a ready-poll callback) that the timer's own callback violates by design. Restate the real one: the timer's own callback may close it, because its ready_polls slot is already consumed; no other callback may, and a retirement with the timer still armed defers the close past the dispatch batch.
…, not a us_timer_t Per review: us_timer_t costs a timerfd per timer on Linux and src/uws_sys/Timer.rs documents it as deprecated, and owning a timer from inside the usockets connecting-socket lifecycle forced a deferred-close and re-entrancy dance. Replace it with the shape AbortSignal.timeout already uses end to end. - FetchTasklet embeds a 300 ms EventLoopTimer (Tag::FetchConnectAttempt), armed at queue(), re-armed by its fire handler, removed at the first progress update from the HTTP thread (the connect phase is over) and, as the backstop, in clear_data before the tasklet is freed. - Each tick posts HTTPThread::schedule_connect_nudge(async_http_id), a new cross-thread message mirroring schedule_receive_resume, drained after the shutdown drain so a same-tick abort makes it a no-op. - The drain resolves the id through the existing abort_tracker and, if the socket is still a DNS-deferred connecting socket, calls the new us_connecting_socket_start_next(), the only usockets addition (a guarded start_connections(c, 1)). Every other socket state is a no-op. - async_http_id is now assigned unconditionally and the abort-tracker registration drops its signals.aborted gate, so every fetch is addressable, not only abortable ones. All of the previous usockets timer changes (the connect_timer field, its arm and callback, the deferred us_timer_close in us_internal_free_closed_sockets, and the addrinfo_head neutralizations in close and free) are reverted. The us_create_timer leak fix in epoll_kqueue.c stays; it is independent.
FetchConnectAttempt is internal network pacing, not a user-visible timer, so exclude it from fake timers in Tag::allow_fake_timers and arm it with TimespecMockMode::ForceRealTime. Previously a test using useFakeTimers() would compute the 300 ms deadline against mocked time and never advance past a blackholed address.
Comment-only; keeps every lifetime invariant, just tighter.
The tracker now holds every in-flight request, not just abortable ones.
7e98efe to
1539877
Compare
There was a problem hiding this comment.
No bugs found, but this touches the fetch hot path (per-request timer + unconditional abort-tracker registration), cross-thread HTTP messaging, and event-loop timer lifecycle, and went through a mid-PR redesign — worth a human look.
Checked: connect_attempt_timer is unlinked in both on_progress_update and the clear_data backstop before the tasklet box is freed; the cross-thread nudge resolves by id through abort_tracker so a late tick after connect settles is a no-op; start_next_connect_attempt no-ops on every non-connecting socket state; seed_cache_for_testing fully initializes every MaybeUninit slot before assume_init and caps count at 64.
Extended reasoning...
Overview
This PR adds an RFC 8305 per-attempt connect timer to fetch() so a blackholed address in the first parallel-connect batch doesn't stall the request for ~130 s. It spans 14 files: a small usockets addition (us_connecting_socket_start_next), Rust FFI shims, a new EventLoopTimer tag and dispatch arm, a new cross-thread schedule_connect_nudge queue on HTTPThread, an embedded 300 ms timer on every FetchTasklet, unconditional async_http_id assignment and abort-tracker registration on every request (previously gated on AbortSignal), a test-only dnsCacheSeed host function with MaybeUninit result-buffer construction, and a Linux-only integration test.
Security risks
None identified. dnsCacheSeed is gated behind bun:internal-for-testing, validates address literals via ares_inet_pton, and caps the array length at 64 before allocation. The nudge path only calls start_connections(c, 1) on a still-connecting socket via the guarded us_connecting_socket_start_next (checks c->closed and addrinfo_head). No auth/crypto/permissions surface.
Level of scrutiny
High. This is production-critical networking: it changes behavior on every fetch() (a 300 ms recurring timer per in-flight request until first progress, plus one abort-tracker map put/remove per request that previously only happened for abortable ones). It threads a new cross-thread message from the JS-thread timer to the HTTP thread, and embeds an intrusive EventLoopTimer node inside a heap-allocated FetchTasklet whose lifetime is managed by refcounting — the kind of lifetime coupling that's produced UAFs in this codebase before (and did produce one in this PR's earlier us_timer_t design, per the resolved thread on socket.c). The PR was also rearchitected once mid-review (dropping the usockets-owned timer for the EventLoop.Timer approach), which is a design decision a maintainer should sign off on.
Other factors
All prior review threads (CodeRabbit and my own inline findings) are resolved. The bug-hunting system found nothing this run. I traced the timer lifecycle: armed in queue(), re-armed by its own fire handler, removed at first on_progress_update and again in clear_data before deinit frees the box — the backstop covers the abort/error paths that skip progress. The nudge drain runs after drain_queued_shutdowns, so a same-tick abort removes the tracker entry first and the nudge no-ops. start_next_connect_attempt on AnySocket no-ops for every state except a live ConnectingSocket, so a nudge landing after the socket transitions to connected is harmless. The seed_cache_for_testing MaybeUninit loop writes every field of every slot before assume_init, and the early-return on invalid address literals happens while the box is still MaybeUninit (no partial-drop issue since ResultEntry fields are POD).
Given the scope (hot path, cross-thread, timer-in-refcounted-struct, mid-PR redesign) and the per-request cost change, this should get human review even with zero findings.
…t stall bun install (#36295) Fixes #4938. Fixes #33278. Fixes #29695. Fixes #25619. Closes #33280, Closes #32864 and Closes #29696 (the per-attempt connect timer in #32949 is orthogonal and left for a separate PR). ### What does this PR do? On a dual-stack host where IPv6 is advertised but blackholed (Starlink, broken home routers, some corporate networks, Docker bridges), `bun install` stalls for ~75-130s per registry manifest fetch. `registry.npmjs.org` resolves to 12 AAAA + 12 A records; RFC 6724 sorts the AAAA records first, and `process_results()` in `src/runtime/dns_jsc/dns.rs` is supposed to interleave address families (RFC 8305 §4) before handing the list to usockets so the `CONCURRENT_CONNECTIONS = 4` parallel connect attempts cover both families. The interleave loop has never worked: ```rust let mut want = netc::AF_INET6 as usize; 'outer: for idx in 0..count { if results[idx].info.ai_family as usize == want { continue; // never flips want } for j in (idx + 1)..count { ... } break 'outer; // always breaks after first non-matching idx } ``` `want` starts at hardcoded `AF_INET6` and only flips on a swap, so any list that *starts* with IPv6 (the failing shape) passes through unchanged. With `[12×v6, 12×v4]` the first four parallel connects are all blackholed IPv6 and the kernel retries SYNs until `tcp_syn_retries` is exhausted (~75s on macOS, ~127s on Linux), matching the 105.80s one reporter measured. ### Fix Replace the post-copy swap with a closed-form interleave during the copy pass: alternate between the resolver's first family and the other, preserving resolver order within each family. The slot mapping is a bijection over `0..count`, so the existing `MaybeUninit`/`assume_init` invariant is unchanged and the broken swap loop is deleted. Starting from the resolver's first family (rather than hardcoding v6) respects the OS's RFC 6724 policy: a v4-first result stays v4-first, and a user who set `precedence ::ffff:0:0/96 100` in `gai.conf` (the workaround several reporters used) still gets their preference. With the interleave in place the first four attempts on a 12+12 result are `[v6, v4, v6, v4]`, so reachable IPv4 connects immediately even when every IPv6 address is blackholed. ### How did you verify your code works? Added `dnsCacheSeed(hostname, addresses)` to `bun:internal-for-testing`. It builds a synthetic addrinfo linked list, runs it through the real `process_results()`, and stores the packed result on a `Request` in the global DNS cache the same way `after_result()` does. Every test in `test/js/bun/dns/dns-interleave.test.ts` then does a real `fetch()` to the seeded hostname, so `us_socket_group_connect` → `Bun__addrinfo_getRequestResult` → `start_connections()` consumes the exact interleaved list. The Linux test is an end-to-end repro: 4 blackholed IPv4 listeners (backlog-0 with the accept queue filled, so SYNs are silently dropped and `connect()` sits in `EINPROGRESS`) followed by one reachable `::1`. With the interleave reverted to sequential order: ``` out: { ok: false, err: "TimeoutError", ms: 4022, order: [4, 4, 4, 4, 6] } ``` With the fix, `::1` is in slot 1 of the first batch and the fetch succeeds in ~1s: ``` out: { ok: true, body: "ok via ::1", ms: ..., order: [4, 6, 4, 4, 4] } ``` `rust:check-all` passes on all 10 targets. <!-- robobun:evidence:begin --> --- **no test proof** · iteration 2 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/dns/dns-interleave.test.ts <!-- robobun:evidence:end --> --------- Co-authored-by: Christian Rishøj <christian@rishoj.net> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
### Problem - GitHub closes only the first reference after a keyword, so "Fixes #1, #2" leaves #2 open. "Supersedes #3" links nothing, and no reference closes a pull request. - The last 1000 merged PRs name 274 such references. PR #32292 is open although merged #36135 says "Supersedes #32292". ### Fix - `.github/workflows/close-linked-issues.yml` runs on `pull_request_target` `closed` (a merge into the default branch of `oven-sh/bun`) and on `workflow_dispatch` with a PR number and `dry_run`. Everything is inline in one `actions/github-script` step, with no checkout. - Each open target is closed as `completed` with the comment "Closed as completed by #N." or "Superseded by #N.". Closed or missing targets, the PR itself and other repositories are skipped. - The parser has no regex. A closing keyword (close, fix, resolve, supersede, replace, any tense) must lead the reference, alone or in a list. A negated, hedged or noun keyword, or one whose subject is another reference, does not count ("may fix", "the rm fix #1", "#100 supersedes #1"). - Verified: `test/internal/close-linked-issues.test.ts` (333 cases) runs the YAML's script against fake `github`, `context` and `core`. Also the 1000-PR parse (Notes). ### Background - GitHub's own keywords are close, fix and resolve (-s, -ed). Each links one reference, and only a merge into the default branch closes it. - `pull_request_target` runs in the base repository with a write token, also for fork PRs. That is safe only when no PR-controlled code runs. Here the description is the only PR input, parsed as text. <details><summary>Notes</summary> A close through the API does not create the "closed this in #N" timeline link that GitHub makes for its own closes. The comment carries the PR number instead. How the parser was calibrated. I pulled the descriptions of the last 1000 merged PRs and listed every line with a keyword next to a reference. The keyword families, list shapes and reference forms in the script are the ones that appear there. A reference is `#1`, `owner/repo#1`, an issue or pull URL (bare or in `<>`), or a markdown link. Four lines would have been wrong with a plain keyword-then-reference rule, and each led to a rule: - "the open `rm` fix #37521" (#38379): "fix" as a noun. Base forms (fix, close, resolve, supersede, replace) count only at the start of a sentence or line, or after will, should, does, and, and a few similar words. "to" is not one of them ("unable to fix #1", "how to fix #1"). - "May also fix #12318 / #10046, untested" (#38242): hedged. may, might, could, would, partially and the negations disqualify the keyword, looking past adverbs such as "also". - "Supersedes the closed #26040" (#36289) and "a comment on closed #35351" (#35365): "closed" as an adjective. A determiner or preposition before the keyword disqualifies it. - "supersedes #33130's optimisation" (#35843): a number that continues into a word is not a reference. Review added: a reference before the keyword is the subject ("#100 supersedes #1"), also through "which" or "that" ("reverts #100, which fixed #1") and across a removed span ("#100 ~~also~~ fixes #1"). A hedge two words before the keyword disqualifies it ("hopefully this fixes #1", "could this fix #1?"). A clause that starts with if, when, once, until or unless is not a statement. The tokenizer keeps a line break as a token so that "Fixes #1" on one line and "Fixes #2" on the next stay two statements. Code spans, fences, indented code, blockquotes, HTML comments and strikethrough are skipped. The block stripping follows CommonMark for fences (also inside a blockquote), indented code, blockquotes with lazy continuation, setext underlines and HTML comments, and GFM for `~~` flanking. Result over the 1000 descriptions: 274 distinct references in 135 PRs. I checked the current state of all of them through GraphQL. All but one are closed (202 issues completed, 5 duplicates, 66 pull requests). The one open target is PR #32292, superseded by merged #36135. No open target is a false positive. Every review change kept this result. Patterns that are deliberately not handled: a bulleted list under "Closes:" on its own line (not seen in the sample), references separated by whitespace only ("#1 #2"), "fix for #1", and GH-1 style references. A `?` after the list is not treated as a question. The block parser tracks no list containers, so a second paragraph of a list item indented by four spaces is read as an indented code block and skipped. A removed span or inline comment reads as one word, so "Fixes <!-- n --> #1" finds nothing. The test suite covers: the phrases above, stopping at the right place in real sentences, CRLF descriptions, URLs with fragments or a `/files` suffix, case-insensitive `Owner/Repo#1`, the fake API where a lookup, an update or a comment fails, the `dry_run` input, an invalid `pr_number` input, an unmerged PR, a PR merged into a non-default branch, the merge event body against a later edit, and a description with no closing statement. The first revision of this PR checked out the repository and ran `scripts/close-linked-issues.ts`. Jarred asked for no checkout and no script file, so the script moved inline into the workflow and the test now reads it out of the YAML. </details> <!-- robobun:evidence:begin --> --- **[stamp-90s]** gate passed · iteration 9 · 2 files touched <details><summary>passes on PR (with fix)</summary> ```console Test-only change. Debug/ASAN (expected pass): $ bun bd test 'test/internal/close-linked-issues.test.ts' $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test test/internal/close-linked-issues.test.ts bun test v1.4.1 (4448a2e) test/internal/close-linked-issues.test.ts: (pass) finds "Fixes #39852" [176.21ms] (pass) finds "Closes #31772. Fixes #31771." [22.28ms] (pass) finds "- Fixes #39930" [12.28ms] (pass) finds "Fixes: #30429" [10.46ms] (pass) finds "FIXES #1" [7.86ms] (pass) finds "(Fixes #1)" [8.97ms] (pass) finds "**Fixes #1**" [10.20ms] (pass) finds "__Fixes #1__" [9.83ms] (pass) finds "_Fixes #1_" [11.25ms] (pass) finds "Fixes **#1**" [9.72ms] (pass) finds "**Fixes** #1" [7.13ms] (pass) finds "**Fixes:** #1" [8.11ms] (pass) finds "Fixes #1 and **#2**" [11.47ms] (pass) finds "Fixes **#1**, **#2**" [9.13ms] (pass) finds "## Why (fixes #13771, closes #30543)" [16.08ms] (pass) finds "Closes #11418" [19.46ms] (pass) finds "Resolves #1. Resolved #2. Resolve #3." [12.09ms] (pass) finds "Fixes #34055, #30327, #24394, #20816, #32403, #11898, #10056." [17.11ms] (pass) finds "Fixes #18192 and #31675 as a consequence" [10.45ms] (pass) finds "Fixes #1, #2, and #3" [10.96ms] (pass) finds "Fixes #1 & #2" [7.63ms] (pass) finds "Closes #33280, Closes #32864 and Closes #29696 (the timer in #32949 is orthogonal)" [20.29ms] (pass) finds "Closes #33182 and #32947 on top of current main (which already has #36304 for catalogs)." [16.12ms] (pass) finds "Fixes #1,\n#2" [7.76ms] (pass) finds "Fixes #1, #2,\nand #3" [9.27ms] (pass) finds "Fixes #1\nand #2" [8.57ms] (pass) finds "Fixes #1\n& #2" [6.80ms] (pass) finds "Fixes #1 and\n#2" [7.31ms] (pass) finds "Supersedes #39908 (same change, moved from a fork branch)" [13.21ms] (pass) finds "Supersedes #38778 and #38391. Carries the entry point arm of #35053." [14.43ms] (pass) finds "Supersedes #39193 and keeps its three tests." [11.48ms] (pass) finds "This supersedes #33306 and #32803. Their tests are kept here." [13.73ms] (pass) finds "- This replaces #33793. Its ... (truncated) Exit: 0 ``` </details> <details><summary>diff hotspot</summary> ``` .github/workflows/close-linked-issues.yml | 950 ++++++++++++++++++++++++++++++ test/internal/close-linked-issues.test.ts | 598 +++++++++++++++++++ 2 files changed, 1548 insertions(+) ``` </details> **gate history** · 29 passed · 0 rejected · iteration 9 <details><summary>evidence per changed file</summary> ``` file reads edits tests .github/workflows/close-linked-issues.yml 6 12 0 test/internal/close-linked-issues.test.ts 3 11 0 ``` </details> <!-- robobun:evidence:end -->
|
Closing this PR because it has been inactive for more than 90 days. |
Fixes a multi-minute
fetch()/Bun.connect()stall when the first few resolved addresses for a hostname silently discard SYNs but a later address in the same DNS answer is reachable.Repro
A hostname that resolves to 4 addresses whose SYNs are silently dropped (filtered network, dead host) plus 1 live address. Node connects in ~0.5 s; Bun's
fetch()to the same name blocks for ~137 s before succeeding, andstrace -e trace=connectshows exactly four parallelconnect()calls, allEINPROGRESS, with the fifth address never attempted.Cause
us_socket_group_connectopens the firstCONCURRENT_CONNECTIONS(4) resolved addresses in parallel and only advances to the next address when one of them hard fails (us_internal_socket_after_openwith an error). A silently discarded SYN never fails:connect()sits inEINPROGRESSuntil the kernel exhausts SYN retransmits, about 130 s with Linux's defaulttcp_syn_retries=6. So a reachable fifth address is never tried.A single stale or filtered AAAA record set (IPv6 published but unreachable on the client network) is enough to trigger this, and it turns every
fetch()to that host into a 2 minute stall. Node (autoSelectFamily, on by default), curl, and browsers all handle it in well under a second via RFC 8305 Happy Eyeballs.Fix
Per review, the connection-attempt delay is an
EventLoop.Timerowned by the fetch, not aus_timer_t(src/uws_sys/Timer.rsdocumentsus_timer_tas deprecated: on Linux it costs a timerfd per timer).FetchTaskletembeds a 300 msEventLoopTimer(Tag::FetchConnectAttempt), armed when the request is queued and re-armed by its own fire handler until the HTTP thread reports the first progress update, which means the connect phase is over. A backstop removal inclear_dataunlinks it before the tasklet is freed. 300 ms is a little above Node's 250 msautoSelectFamilyAttemptTimeoutdefault.HTTPThread::schedule_connect_nudge(async_http_id), a new cross-thread message that mirrors the existingschedule_receive_resume/schedule_shutdownexactly, drained indrain_eventsafter the shutdown drain so a same-tick abort makes the nudge a no-op.abort_tracker. If the socket is still a DNS-deferred connecting socket it calls the one usockets addition,us_connecting_socket_start_next(), a guardedstart_connections(c, 1). Every other socket state is a no-op, so a tick that lands after the connect settles is harmless.async_http_idis now assigned unconditionally andregister_abort_tracker/unregister_abort_trackerdrop theirsignals.abortedgates. Previously only fetches carrying anAbortSignalhad an id and a tracker entry. The cost is one relaxed atomic increment plus one small-map put and remove per request, on the path that already does DNS, connect, and TLS.The timer is only ever touched on the JS thread, and the nudge only ever acts through the same tracker lookup the abort path already relies on. The common cases never pay for any of it: an IP literal or a single-address answer short-circuits before a connecting socket exists, and a 2 to 4 address answer has every address in the initial parallel batch so there is nothing left for a nudge to start.
This complements #32864, which fixes the broken address-family interleave in
process_resultsand explicitly lists this per-attempt timer as out of scope. The two are independent: the interleave picks a good first batch, and the timer bounds the damage when every address in the first batch is unreachable regardless of family.Test
test/js/web/fetch/fetch-happy-eyeballs.test.tsbuilds the scenario hermetically on Linux: rawlisten(fd, 0)sockets whose accept queues are kept full, so the kernel silently drops further SYNs to them (the same non-failingEINPROGRESSa filtered network produces), plus one liveBun.serve. The resolved address list is injected with a newdnsCacheSeedhook onbun:internal-for-testing, so the test needs no root and never touches the system hosts file. It is all IPv4 on purpose, so it isolates the attempt timer rather than the interleave order.CONCURRENT_CONNECTIONS(4) batch, and asserts the fetch succeeds and took at least 250 ms, proving the success arrived via the attempt timer and not some other path.Also run green under the ASAN debug build:
test/js/web/fetch/client-fetch.test.ts(33),test/js/web/fetch/fetch-syscall-fault.test.ts(13),test/js/bun/net/socket-retention.test.ts, and the abort-path suites that exercise the now-unconditional abort-tracker registration:fetch-abort-queued,fetch-abort-stream-body, andfetch-tls-abortsignal-timeout.no test proof · iteration 8 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/web/fetch/fetch-happy-eyeballs.test.ts