Skip to content

fetch: add an RFC 8305 per-attempt connect timer so a blackholed address does not stall for ~130 s - #32949

Closed
robobun wants to merge 10 commits into
mainfrom
claude/farm/1a33836f/happy-eyeballs-connect-timer
Closed

robobun wants to merge 10 commits into
mainfrom
claude/farm/1a33836f/happy-eyeballs-connect-timer

Conversation

@robobun

@robobun robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator

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, and strace -e trace=connect shows exactly four parallel connect() calls, all EINPROGRESS, with the fifth address never attempted.

Cause

us_socket_group_connect opens the first CONCURRENT_CONNECTIONS (4) resolved addresses in parallel and only advances to the next address when one of them hard fails (us_internal_socket_after_open with an error). A silently discarded SYN never fails: connect() sits in EINPROGRESS until the kernel exhausts SYN retransmits, about 130 s with Linux's default tcp_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.Timer owned by the fetch, not a us_timer_t (src/uws_sys/Timer.rs documents us_timer_t as deprecated: on Linux it costs a timerfd per timer).

  • FetchTasklet embeds a 300 ms EventLoopTimer (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 in clear_data unlinks it before the tasklet is freed. 300 ms is a little above Node's 250 ms autoSelectFamilyAttemptTimeout default.
  • Each tick calls HTTPThread::schedule_connect_nudge(async_http_id), a new cross-thread message that mirrors the existing schedule_receive_resume / schedule_shutdown exactly, drained in drain_events after the shutdown drain so a same-tick abort makes the nudge a no-op.
  • The drain resolves the id through the existing abort_tracker. If the socket is still a DNS-deferred connecting socket it calls the one usockets addition, us_connecting_socket_start_next(), a guarded start_connections(c, 1). Every other socket state is a no-op, so a tick that lands after the connect settles is harmless.
  • To make every fetch addressable, async_http_id is now assigned unconditionally and register_abort_tracker / unregister_abort_tracker drop their signals.aborted gates. Previously only fetches carrying an AbortSignal had 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_results and 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.ts builds the scenario hermetically on Linux: raw listen(fd, 0) sockets whose accept queues are kept full, so the kernel silently drops further SYNs to them (the same non-failing EINPROGRESS a filtered network produces), plus one live Bun.serve. The resolved address list is injected with a new dnsCacheSeed hook on bun: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.

  • The first test puts the live address fifth, one past the 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.
  • The second test covers the other two shapes under the ASAN build: a live-address-first fetch (the most common production shape for a more-than-4 address hostname, which settles with attempts still pending), followed by an all-blackholed fetch aborted at 700 ms, which must reject promptly and exit cleanly.
# bun 1.4.0 (unfixed): the 5th address is never tried
{"ok":false,"ms":4001,"err":"TimeoutError"}

# with this change (bun bd, ASAN)
(pass) fetch() advances to the next resolved address before a blackholed connect hard-fails [1992ms]
(pass) a live first address succeeds from the initial batch and an abort with attempts still pending tears down cleanly [2388ms]

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, and fetch-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

@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Implements RFC 8305 Happy Eyeballs connect staggering for fetch(), adds the socket and HTTP-thread plumbing that advances attempts, exposes a DNS cache seeding hook, and adds a Linux integration test for fallback and abort timing.

Changes

Happy Eyeballs RFC 8305 Implementation

Layer / File(s) Summary
bun-usockets start-next API
packages/bun-usockets/src/libusockets.h, packages/bun-usockets/src/context.c, packages/bun-usockets/src/eventing/epoll_kqueue.c
Declares and implements us_connecting_socket_start_next for deferred-DNS connect advancement, and frees the allocated poll object on timerfd_create failure.
Rust socket forwarding
src/uws_sys/ConnectingSocket.rs, src/uws_sys/socket.rs
Adds the FFI shim and Rust methods that forward connect-attempt advancement through ConnectingSocket and AnySocket.
AsyncHTTP ids and abort tracker
src/http/AsyncHTTP.rs, src/http/lib.rs
Always assigns a monotonic async_http_id and always inserts/removes abort-tracker entries using that id.
HTTP thread connect nudges
src/http/HTTPThread.rs
Adds the queued connect-nudge state, enqueue API, drain logic, and wakeup path for advancing pending connect attempts.
FetchTasklet connect-attempt timer
src/event_loop/EventLoopTimer.rs, src/runtime/webcore/fetch/FetchTasklet.rs, src/runtime/dispatch.rs
Adds the fetch connect-attempt timer tag, timer lifecycle, nudge scheduling, re-arming, and dispatch handling for the RFC 8305 delay loop.
DNS cache seed binding
src/runtime/dns_jsc/dns.rs, src/codegen/generate-js2native.ts, src/js/internal-for-testing.ts
Adds the test-only DNS cache seed host function, exports it to JS, suppresses the duplicate thunk, and exposes dnsCacheSeed().
Fetch Happy Eyeballs integration test
test/js/web/fetch/fetch-happy-eyeballs.test.ts
Adds the Linux-only test fixture and assertions for reachable-fallback success and abort behavior with pending connect attempts.

Possibly related PRs

  • oven-sh/bun#31325: Shares src/runtime/webcore/fetch/FetchTasklet.rs progress-handling logic around timer-driven fetch phase transitions.
  • oven-sh/bun#32862: Also changes HTTP abort-tracker lifecycle handling in src/http/lib.rs.

Suggested reviewers

  • alii
  • Jarred-Sumner
🚥 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 summarizes the main change: adding an RFC 8305 per-attempt connect timer to avoid long stalls.
Description check ✅ Passed The description covers what the PR does and how it was verified, with repro, cause, fix, and test details.

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

@robobun
robobun force-pushed the claude/farm/1a33836f/happy-eyeballs-connect-timer branch from be7dec3 to 962c023 Compare June 28, 2026 00:15
@robobun

robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:42 PM PT - Jul 10th, 2026

❌ @robobun, your commit 1539877 has 3 failures in Build #71636 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32949

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

bun-32949 --bun

@robobun
robobun force-pushed the claude/farm/1a33836f/happy-eyeballs-connect-timer branch from 54fa87b to 2306c37 Compare June 28, 2026 00:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f9331d and 962c023.

📒 Files selected for processing (8)
  • packages/bun-usockets/src/context.c
  • packages/bun-usockets/src/internal/internal.h
  • packages/bun-usockets/src/loop.c
  • packages/bun-usockets/src/socket.c
  • src/codegen/generate-js2native.ts
  • src/js/internal-for-testing.ts
  • src/runtime/dns_jsc/dns.rs
  • test/js/web/fetch/fetch-happy-eyeballs.test.ts

Comment thread src/runtime/dns_jsc/dns.rs Resolved
Comment thread packages/bun-usockets/src/context.c Resolved
@robobun
robobun force-pushed the claude/farm/1a33836f/happy-eyeballs-connect-timer branch from 2306c37 to d454dde Compare June 28, 2026 00:27

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 962c023 and 97a2d8a.

📒 Files selected for processing (9)
  • packages/bun-usockets/src/context.c
  • packages/bun-usockets/src/eventing/epoll_kqueue.c
  • packages/bun-usockets/src/internal/internal.h
  • packages/bun-usockets/src/loop.c
  • packages/bun-usockets/src/socket.c
  • src/codegen/generate-js2native.ts
  • src/js/internal-for-testing.ts
  • src/runtime/dns_jsc/dns.rs
  • test/js/web/fetch/fetch-happy-eyeballs.test.ts

Comment thread packages/bun-usockets/src/socket.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.

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.

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

@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 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 Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

You're right, and thanks. Moving it.

On "I thought this already existed": it exists for node:net (autoSelectFamily with its own per-attempt timer, in src/js/node/net.ts) but not for fetch(). The native client's only multi-address handling today is the CONCURRENT_CONNECTIONS (4) parallel attempts in us_socket_group_connect, which only advance to the next address when one of them hard-fails, so a silently dropped SYN blocks the rest for the full kernel SYN-retry window (~130 s). There is no per-attempt timer anywhere in src/http/, and the two open DNS PRs (#32864, #29696) only change address ordering, which does not help when every address in the first batch is unreachable regardless of order.

I'll drop the us_timer_t and all the us_connecting_socket_t lifecycle changes that came with it, and drive the 300 ms attempt delay from AsyncHTTP with an EventLoop.Timer instead, with a minimal entry point for the tick to tell the connecting socket to start its next address. The test is at the fetch() level so it carries over unchanged as the proof.

@robobun

robobun commented Jun 28, 2026

Copy link
Copy Markdown
Collaborator Author

Done in 2234350.

The attempt delay is now an EventLoop.Timer on the fetch. FetchTasklet embeds a 300 ms EventLoopTimer (Tag::FetchConnectAttempt), armed at queue(), re-armed by its fire handler, and removed at the first progress update from the HTTP thread, with a backstop in clear_data. Each tick posts a new HTTPThread::schedule_connect_nudge(async_http_id) that mirrors schedule_receive_resume, and the HTTP-thread drain resolves the id through the existing abort_tracker and, if the socket is still a DNS-deferred connecting socket, calls us_connecting_socket_start_next(), a guarded start_connections(c, 1) and the only usockets addition.

To make every fetch addressable (not just abortable ones), async_http_id is now assigned unconditionally and the abort-tracker registration drops its signals.aborted gate.

All of the earlier us_timer_t code and the us_connecting_socket_t lifecycle changes that came with it are reverted. The tests are unchanged since they are at the fetch() level; they still fail on the unfixed build and pass on this one.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 97a2d8a and 2234350.

📒 Files selected for processing (11)
  • packages/bun-usockets/src/context.c
  • packages/bun-usockets/src/libusockets.h
  • src/event_loop/EventLoopTimer.rs
  • src/http/AsyncHTTP.rs
  • src/http/HTTPThread.rs
  • src/http/lib.rs
  • src/runtime/dispatch.rs
  • src/runtime/webcore/fetch/FetchTasklet.rs
  • src/uws_sys/ConnectingSocket.rs
  • src/uws_sys/socket.rs
  • test/js/web/fetch/fetch-happy-eyeballs.test.ts

Comment thread src/event_loop/EventLoopTimer.rs Resolved

@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)
src/runtime/webcore/fetch/FetchTasklet.rs (1)

461-463: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Condense 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2234350 and 6b77bce.

📒 Files selected for processing (2)
  • src/event_loop/EventLoopTimer.rs
  • src/runtime/webcore/fetch/FetchTasklet.rs

@robobun

robobun commented Jun 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

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:

  • test/napi/napi.test.ts on Windows x64 (No finalizers were called - test did not properly trigger GC): a GC-timing test that never calls fetch(), which is the only entry point to any code in this diff. Appears on 15 of the last 60 non-main builds across unrelated branches, and build 71618 on farm/16993ee9/custom-error-stack hard-failed it the same way.
  • test/js/bun/http/proxy-stress-concurrent.test.ts on darwin 14 x64 (1 of 1200 requests failed in the https-proxy to https-origin 35 s stress run): hard-fails on 71644 spawnsync-timeout-stale-clock, 71638 fix-html-import-etag-quotes, 71632 node-sqlite-v26 and flakes on 5 more; an open branch ciro/proxy-stress-macos-portrange is actively working on it. The test connects to Bun.serve({port:0}) and a 127.0.0.1 proxy, which take the IP-literal fast path and never create a ConnectingSocket, so this diff's nudge is a structural no-op for it.
  • test/js/third_party/grpc-js/test-tonic.test.ts on darwin 14 aarch64 (150 s timeout in the gRPC test tonic server subtest): hard-fails on 71622 import-meta-hot-for-bun-hot and 71617 ebadf-investigation. The test's one fetch() is a beforeAll download of the tonic server binary from a GitHub release; the timeout is in the gRPC (node:http2) client/server interaction after that.

My own fetch-happy-eyeballs tests pass on this build. I have already used my one empty retrigger earlier in this PR, so I am leaving these for a maintainer to retry rather than push more no-op commits.

Comment thread src/http/lib.rs 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.

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.

@robobun
robobun force-pushed the claude/farm/1a33836f/happy-eyeballs-connect-timer branch from 1370f45 to 7e98efe Compare July 7, 2026 09:07
robobun and others added 7 commits July 10, 2026 21:51
…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.
robobun added 3 commits July 10, 2026 21:51
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.
@robobun
robobun force-pushed the claude/farm/1a33836f/happy-eyeballs-connect-timer branch from 7e98efe to 1539877 Compare July 10, 2026 21:55

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

Jarred-Sumner pushed a commit that referenced this pull request Jul 29, 2026
…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>
Jarred-Sumner pushed a commit that referenced this pull request Aug 22, 2026
### 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 -->
@github-actions

github-actions Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

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