Skip to content

fix(dns): preserve OS order in internal DNS cache - #29696

Closed
robobun wants to merge 7 commits into
mainfrom
farm/04be0174/preserve-os-dns-order
Closed

robobun wants to merge 7 commits into
mainfrom
farm/04be0174/preserve-os-dns-order

Conversation

@robobun

@robobun robobun commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator

What

process_results() in src/runtime/dns_jsc/dns.rs — the internal DNS cache that feeds fetch, Bun.serve outbound, Bun.connect and every other uws connect — was always reordering getaddrinfo() results so the first entry was IPv6:

// sort (interleave ipv4 and ipv6)
let mut want = netc::AF_INET6 as usize;
'outer: for idx in 0..count {
    if results[idx].info.ai_family as usize == want {
        continue;
    }
    for j in (idx + 1)..count {
        if results[j].info.ai_family as usize == want {
            results.swap(idx, j);
            want = if want == netc::AF_INET6 as usize {
                netc::AF_INET as usize
            } else {
                netc::AF_INET6 as usize
            };
        }
    }
    break 'outer;
}

On hosts where IPv6 is configured but a specific destination is unreachable (the VPN case in #29695 against www.python.org), this picks a dead AAAA before a reachable A and returns ECONNRESET. It also disagrees with dns.lookup() (which reports verbatim by default) and with what the OS already decided via RFC 6724 destination selection and /etc/gai.conf.

(This originally modified the Zig processResults() in src/bun.js/api/bun/dns.zig; the DNS module was ported Zig→Rust on main, so the fix was re-applied to the Rust process_results().)

Fix

Drop the IPv6-first interleave. The packing into a single allocation stays (the linked list still needs to outlive freeaddrinfo); the sort goes. AI_ADDRCONFIG, gai.conf, and libinfo on mac have already told glibc which family should come first for this destination — we should just honor that.

Verification

test/regression/issue/29695.test.ts compiles a small LD_PRELOAD shim that makes getaddrinfo("mock29695") return [127.0.0.1, ::1] in that exact order, then spawns a Bun subprocess with the shim preloaded running Bun.serve({ hostname: "::" }) and fetch("http://mock29695:PORT/"). The dual-stack listener reports ::ffff:127.0.0.1 when the connection came in over IPv4 and ::1 when it was native IPv6, giving a one-bit signal for which family the internal DNS cache picked.

  • Before: subprocess hits the server as ::1 (the cache forced AAAA to the front).
  • After: subprocess hits the server as ::ffff:127.0.0.1 (OS order preserved).

Guarded to glibc Linux with cc available and an IPv6 loopback — macOS uses libinfo so LD_PRELOAD doesn't intercept the same code path, musl ignores LD_PRELOAD for setuid binaries and has its own getaddrinfo, and we need ::1 for the dual-stack listener to bind. The shim lives in a disposable tempDir() scoped to the one Bun.spawn that needs it, so nothing host-global is touched.

Fixes #29695

@robobun

robobun commented Apr 24, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 3:14 AM PT - Jun 25th, 2026

❌ @robobun, your commit 02127fe has 4 failures in Build #64599 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 29696

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

bun-29696 --bun

Comment thread test/regression/issue/29695.test.ts Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Found 4 issues this PR may fix:

  1. DNS resolution prefers Global IPv6 on Link-Local only interface (VPN/Cisco AnyConnect) causes timeout #25619 - DNS resolution forces IPv6 on VPN interfaces with only link-local IPv6, causing timeouts because the OS address ordering is ignored
  2. Inconsistent IP version preference in Bun node:dns.lookup #29227 - node:dns.lookup returns ::1 (IPv6) instead of 127.0.0.1 (IPv4) for hostnames resolving to both, because the internal DNS cache sorts IPv6 first regardless of OS preference
  3. bun install/create fails with error: ConnectionRefused downloading package manifest #4988 - bun install fails with ConnectionRefused downloading package manifests; disabling IPv6 fixes it, indicating forced IPv6-first ordering causes connections to unreachable IPv6 addresses
  4. bun install resolve step *extremely* slow #4938 - bun install resolve step extremely slow; disabling IPv6 fixed the issue, confirming IPv6 preference was the root cause

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

Fixes #25619
Fixes #29227
Fixes #4988
Fixes #4938

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Preserve the OS-provided getaddrinfo() ordering when producing DNS results in dns.zig; add a Linux/glibc-only regression test that LD_PRELOADs a shimmed getaddrinfo()/freeaddrinfo() to validate address-family/order observed by a Bun subprocess running a dual-stack server.

Changes

Cohort / File(s) Summary
DNS result processing
src/bun.js/api/bun/dns.zig
processResults no longer reorders getaddrinfo() linked-list results by address family. Entries are copied into a packed ResultEntry array preserving OS order; addrinfo.next and ai_addr are relinked/repointed to packed storage so the returned list outlives the original freeaddrinfo buffer.
Regression test (Linux/glibc-only)
test/regression/issue/29695.test.ts
Adds a test that builds an LD_PRELOAD shim overriding getaddrinfo()/freeaddrinfo() to return IPv4 then IPv6 for mock29695, spawns a Bun subprocess with the shim and DNS flags, runs a dual-stack Bun.serve, fetches /, and asserts the observed client address/family matches the expected IPv6-mapped result. Test is Linux glibc-specific and compiles a temporary shared object.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: preserving OS order in the internal DNS cache by removing the IPv6-first interleaving logic.
Linked Issues check ✅ Passed The PR directly addresses all coding objectives from #29695: removes IPv6-first reordering in processResults(), adds regression test confirming OS order is preserved, and fixes the inconsistency between dns.lookup() verbatim mode and outbound connection behavior.
Out of Scope Changes check ✅ Passed All changes are in scope: dns.zig modification removes the problematic reordering, and the regression test file validates the fix on glibc Linux. No unrelated modifications are present.
Description check ✅ Passed The PR description is substantive and covers the change and verification, though its headings differ from the repository template.

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


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

@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 the current code and only fix it if needed.

Inline comments:
In `@test/regression/issue/29695.test.ts`:
- Around line 126-136: The current test asserts exitCode and stderr together
before inspecting stdout, which hides useful failure context; update the
assertions so you first parse stdout (the Promise.all that assigns stdout,
stderr, exitCode and the JSON.parse into body) and then call
expect(body).toMatchObject(...) to verify the regression signal, and only after
that assert expect(exitCode).toBe(0) (you can still assert stderr as needed
separately) so test failures show the stdout content before the process
exit-code assertion.
- Around line 20-21: The test is mutating the machine-wide resolver at
GAI_CONF_PATH and using a fixed backup GAI_CONF_BACKUP which can affect parallel
tests; change the test to avoid touching /etc/gai.conf by running the scenario
in an isolated hermetic environment or by using a per-run temporary file (e.g.,
create a temp copy in os.tmpdir or use mkdtemp/tmpfile with a unique name) and
point the code under test to that temp config, and ensure cleanup restores only
that temp file (not the real /etc/gai.conf); update references to GAI_CONF_PATH
and GAI_CONF_BACKUP in the test to use the temp path or mock the resolver
behavior instead so the shard-wide resolver is never modified.
🪄 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: 2b0e5ea3-fe0a-4b49-b623-a0664af55725

📥 Commits

Reviewing files that changed from the base of the PR and between 259f16f and 267136e.

📒 Files selected for processing (2)
  • src/bun.js/api/bun/dns.zig
  • test/regression/issue/29695.test.ts

Comment thread test/regression/issue/29695.test.ts Resolved
Comment thread test/regression/issue/29695.test.ts 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.

♻️ Duplicate comments (2)
test/regression/issue/29695.test.ts (2)

126-130: ⚠️ Potential issue | 🟡 Minor

Assert stdout-derived regression signal before exit code; remove tautological stderr check.

Line 127 currently checks stderr: expect.any(String) (no signal) and asserts exit status before validating stdout content. Parse/assert body first, then assert exitCode.

💡 Suggested change
-  const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
-  expect({ stderr, exitCode }).toEqual({ stderr: expect.any(String), exitCode: 0 });
+  const [stdout, , exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

   // Parse the only JSON object the child printed.
   const body = JSON.parse(stdout.trim().split("\n").at(-1)!);

   // With the gai.conf override, OS order is [127.0.0.1, ::1]. After the
   // fix, the internal DNS cache preserves that order and the dual-stack
   // server sees the IPv4-mapped address. Before the fix, the cache
   // forced AAAA to the front and the server saw pure ::1.
   expect(body).toMatchObject({ address: "::ffff:127.0.0.1", family: "IPv6" });
+  expect(exitCode).toBe(0);
As per coding guidelines, "When spawning processes in tests, use `expect(stdout).toBe(...)` BEFORE `expect(exitCode).toBe(0)` to get more useful error messages."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/regression/issue/29695.test.ts` around lines 126 - 130, The current test
asserts a tautological stderr value and checks exitCode before validating the
stdout-derived signal; update the test to first parse and assert the JSON body
from stdout (use stdout.trim().split("\n").at(-1)! to produce `body` and add the
appropriate assertions about its contents), then assert the exitCode equals 0,
and remove the redundant `stderr: expect.any(String)` check from the object
equality assertion so that `proc`, `stdout`, `stderr`, `exitCode`, and `body`
are validated in the correct order.

20-21: ⚠️ Potential issue | 🟠 Major

Avoid host-global /etc/gai.conf mutation in shared CI.

This still mutates machine-wide resolver policy and uses a fixed backup filename, so concurrent tests/jobs can interfere or clobber restore state. Please isolate this test to a dedicated hermetic shard/container (or add an explicit CI gate so it only runs where isolation is guaranteed).

Also applies to: 57-67, 69-82

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/regression/issue/29695.test.ts` around lines 20 - 21, The test currently
mutates the global /etc/gai.conf via the constants GAI_CONF_PATH and
GAI_CONF_BACKUP which can corrupt shared CI; change the test to avoid
host-global mutation by either running only under an isolation gate (check an
env var like RUN_HERMETIC_GAI_TEST and skip otherwise) or operate on a per-test
temporary file using secure temp names (use mkstemp-style temp file creation and
a unique backup name instead of GAI_CONF_BACKUP), update code that references
GAI_CONF_PATH to accept an injected path (e.g., pass a temp path into the
functions under test) and ensure cleanup restores state only for that temp file
so no /etc files are touched.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@test/regression/issue/29695.test.ts`:
- Around line 126-130: The current test asserts a tautological stderr value and
checks exitCode before validating the stdout-derived signal; update the test to
first parse and assert the JSON body from stdout (use
stdout.trim().split("\n").at(-1)! to produce `body` and add the appropriate
assertions about its contents), then assert the exitCode equals 0, and remove
the redundant `stderr: expect.any(String)` check from the object equality
assertion so that `proc`, `stdout`, `stderr`, `exitCode`, and `body` are
validated in the correct order.
- Around line 20-21: The test currently mutates the global /etc/gai.conf via the
constants GAI_CONF_PATH and GAI_CONF_BACKUP which can corrupt shared CI; change
the test to avoid host-global mutation by either running only under an isolation
gate (check an env var like RUN_HERMETIC_GAI_TEST and skip otherwise) or operate
on a per-test temporary file using secure temp names (use mkstemp-style temp
file creation and a unique backup name instead of GAI_CONF_BACKUP), update code
that references GAI_CONF_PATH to accept an injected path (e.g., pass a temp path
into the functions under test) and ensure cleanup restores state only for that
temp file so no /etc files are touched.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 5db8811a-c0d2-440b-b57c-044d0dd1569d

📥 Commits

Reviewing files that changed from the base of the PR and between 267136e and 65146e2.

📒 Files selected for processing (1)
  • test/regression/issue/29695.test.ts

Comment thread test/regression/issue/29695.test.ts Resolved
@robobun
robobun force-pushed the farm/04be0174/preserve-os-dns-order branch from 65146e2 to e5d5d7a Compare April 24, 2026 19:10
Comment thread test/regression/issue/29695.test.ts Resolved
Comment thread test/regression/issue/29695.test.ts Resolved
Comment thread test/regression/issue/29695.test.ts 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.

Test-side feedback is all addressed (registry-based freeaddrinfo, stderr surfaced before JSON.parse, happy-eyeballs caveat documented). The remaining piece — dropping the IPv6-first interleave from the DNS cache that feeds every fetch/Bun.connect/install — is a small diff but a runtime-wide connection-ordering policy change, so I'd like a maintainer to sign off on that rather than auto-approve.

Extended reasoning...

Overview

Two files: src/bun.js/api/bun/dns.zig removes the ~14-line sort that forced IPv6 to the front of the packed getaddrinfo() result list (keeping the single-allocation packing and re-linking intact), and test/regression/issue/29695.test.ts adds a glibc-Linux-only regression test that compiles an LD_PRELOAD shim returning [127.0.0.1, ::1] for a sentinel hostname and asserts the dual-stack server sees the IPv4-mapped client.

Security risks

None identified. No auth/crypto/permissions surface; the test writes only to a per-run tempDir and scopes LD_PRELOAD to a single child process. The earlier revision's /etc/gai.conf mutation (and its destructive double-restore) was removed in e5d5d7a.

Level of scrutiny

The Zig change is mechanically simple but sits on the hot path for every outbound connection (fetch, Bun.connect, bun install, uws connect). The original interleave was presumably an intentional happy-eyeballs-ish heuristic; replacing it with "trust OS order verbatim" is well-reasoned (matches Node's verbatim default, respects RFC 6724 / gai.conf, and uws still opens CONCURRENT_CONNECTIONS=4 in parallel so resilience isn't lost) and likely fixes #25619/#29227/#4988/#4938 — but it's a runtime-wide behavioral policy decision that a maintainer should ratify.

Other factors

All prior review feedback has been addressed in d44f2d0: the shim's freeaddrinfo now uses an in-bounds mutex-protected pointer registry (no more OOB magic read), stderr is asserted before JSON.parse so CI failures surface the real diagnostic, and the happy-eyeballs-race caveat is documented inline with a remediation note. The one remaining open nit (loopback-race determinism) is explicitly non-blocking. No CODEOWNER signal checked, but dns.zig is core runtime.

@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

♻️ Duplicate comments (1)
test/regression/issue/29695.test.ts (1)

212-221: ⚠️ Potential issue | 🟡 Minor

Keep the body assertion ahead of the exit-code guard.

This reintroduces the same failure-ordering issue that was fixed earlier: the subprocess exit check now runs before the actual regression signal in stdout. Assert the parsed body first, then keep expect(exitCode).toBe(0) last.

As per coding guidelines, "When spawning processes in tests, use expect(stdout).toBe(...) BEFORE expect(exitCode).toBe(0) to get more useful error messages."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/regression/issue/29695.test.ts` around lines 212 - 221, The test
currently checks exitCode before asserting on the child's JSON output which
masks useful stderr/stdout failures; change the order in the block using stdout,
stderr, exitCode so you parse stdout into body first (const body =
JSON.parse(stdout.trim().split("\n").at(-1)!)) and assert the expected contents
of body with expect(body)... before asserting the exit code; keep
expect(exitCode).toBe(0) as the final assertion so process output failures are
surfaced first.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/regression/issue/29695.test.ts`:
- Around line 100-145: The mock getaddrinfo currently always builds both IPv4
and IPv6 entries and returns &b->a4 regardless of hints->ai_family, which breaks
the libc contract and mismatches registry_take in freeaddrinfo; update
getaddrinfo to inspect hints->ai_family and: build both entries but choose the
returned head as (1) &b->a4 for AF_INET, (2) &b->a6 for AF_INET6, (3) &b->a4
with a4.ai_next = &b->a6 for AF_UNSPEC; ensure when returning a single-family
head you set ai_next = NULL so the chain is correct; finally make
registry_add/register behavior record the exact head pointer you return (so
registry_take(res) can find the corresponding mock_bundle) — adjust
registry_add/registry_take usage accordingly to map the returned head to its
bundle.

---

Duplicate comments:
In `@test/regression/issue/29695.test.ts`:
- Around line 212-221: The test currently checks exitCode before asserting on
the child's JSON output which masks useful stderr/stdout failures; change the
order in the block using stdout, stderr, exitCode so you parse stdout into body
first (const body = JSON.parse(stdout.trim().split("\n").at(-1)!)) and assert
the expected contents of body with expect(body)... before asserting the exit
code; keep expect(exitCode).toBe(0) as the final assertion so process output
failures are surfaced first.
🪄 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: aefe1b93-5a1c-480a-b9c8-98b1cfe155df

📥 Commits

Reviewing files that changed from the base of the PR and between 0a3da6a and d44f2d0.

📒 Files selected for processing (1)
  • test/regression/issue/29695.test.ts

Comment thread test/regression/issue/29695.test.ts Resolved
Comment thread test/regression/issue/29695.test.ts Resolved

@liufang88789-ui liufang88789-ui left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is a solid fix. The IPv6-first interleave was silently overriding the OS's RFC 6724 destination selection, which is why it worked fine on some hosts but caused ECONNRESET on VPNs where IPv6 is configured but specific routes are unreachable.

One minor thing to double-check: the re-linking logic in the for (results, 0..) loop at the end - it resets canonname to null and rewires the next pointers. Since results is a fresh allocation from bun.default_allocator (not the original linked list), the relink is necessary to keep the list valid for freeaddrinfo. That part looks correct to me.

The test shim is thorough - compiling a disposable LD_PRELOAD library in tempDir is a nice approach to avoid polluting the host-global /etc/gai.conf. The mutex-protected registry for tracking live allocations is also clean.

The isGlibc && isLinux && hasIPv6Loopback guard is appropriately narrow. On macOS with libinfo the test wouldn't exercise the same code path anyway, and musl's loader ignoring LD_PRELOAD for setuid is the right reason to skip it there.

LGTM overall. The reasoning in the PR description is clear and matches what I'd expect from Node.js's verbatim behavior for dns.lookup().

@Jarred-Sumner
Jarred-Sumner force-pushed the farm/04be0174/preserve-os-dns-order branch from 7e41437 to 7fa84a0 Compare May 4, 2026 10:34

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

I didn't find any remaining issues, but removing the IPv6-first interleave changes address-selection behavior for every outbound connection (fetch, Bun.connect, bun install) — that's a networking policy decision worth a human sign-off rather than a bot approval.

Extended reasoning...

Overview

The PR touches two files: src/runtime/dns_jsc/dns.zig (deletes the ~15-line IPv6-first interleave sort in processResults(), keeping only the pack-into-single-allocation and re-link logic) and a new 253-line regression test test/regression/issue/29695.test.ts that compiles an LD_PRELOAD shim to verify the OS getaddrinfo() order is preserved end-to-end through fetch.

All prior review feedback (mine and CodeRabbit's) has been addressed across several revisions: the test no longer mutates /etc/gai.conf, the shim's freeaddrinfo uses an in-bounds registry instead of an OOB magic-byte read, it honors hints->ai_family, stderr is surfaced before JSON.parse, and the PR body was updated to match the final approach. The current bug-hunting pass found nothing new.

Security risks

None identified. The Zig change is a pure deletion of a sort loop on already-validated addrinfo entries; no new parsing, allocation, or trust-boundary crossing. The test's LD_PRELOAD shim is scoped to a single subprocess in a disposable tempDir and gated to glibc Linux.

Level of scrutiny

High. processResults() feeds the internal DNS cache used by fetch, Bun.serve outbound, Bun.connect, and bun install — effectively every outbound TCP connection Bun makes. The diff is small, but it is a behavioral policy reversal: the original interleave was a deliberate Happy-Eyeballs-style choice, and dropping it in favor of trusting OS RFC 6724 ordering is a design decision with a wide blast radius (the issue-finder bot links four separate user-facing reports). The rationale is sound and matches Node's verbatim default, but a maintainer should confirm this is the direction they want rather than e.g. keeping interleave behind a flag.

Other factors

The two CI failures reported by robobun (webview-chrome.test.ts timeout on macOS, prefetch.test.ts on x64-asan) appear unrelated to DNS. The new regression test is well-gated and hermetic. Given the production-critical path and the policy nature of the change, deferring to a human reviewer.

@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 issues found and all prior review feedback is resolved — deferring only because this removes the IPv6-first interleave from the DNS path that backs every outbound connect (fetch, Bun.connect, bun install), which is a deliberate behavioral change worth a human maintainer's sign-off.

Extended reasoning...

Overview

Two files: src/runtime/dns_jsc/dns.zig deletes ~14 lines of sort logic from processResults() so the packed getaddrinfo() results retain OS order instead of being interleaved IPv6-first; test/regression/issue/29695.test.ts (new, ~250 lines) compiles an LD_PRELOAD shim that forces a deterministic [127.0.0.1, ::1] order for a mock hostname and asserts the dual-stack server sees the IPv4-mapped client. The Zig change is a pure deletion plus comment update — the allocation/copy/relink logic is untouched. The test went through several review rounds (gai.conf mutation → LD_PRELOAD shim, OOB magic-byte read → bundle registry, ai_family honoring, stderr surfacing) and every thread is resolved.

Security risks

None identified. No new parsing, no untrusted input handling, no auth/crypto/permissions surface. The change narrows Bun's deviation from the OS resolver rather than adding logic. The test's LD_PRELOAD shim is scoped to a single subprocess in a disposable tempDir and only intercepts one synthetic hostname.

Level of scrutiny

High. processResults() sits in the internal DNS cache that feeds every uws-backed outbound connection — fetch, Bun.connect, Bun.serve outbound, bun install. The diff is mechanically trivial, but it reverses an intentional design choice (the interleave was presumably added for Happy-Eyeballs-style fallback). Dropping it in favor of verbatim OS order is well-argued (matches Node's default, respects RFC 6724 / gai.conf, fixes #29695 and likely #25619/#29227/#4988/#4938), but whether to remove the interleave entirely vs. keep it and seed it with the OS's first family is a product/design call a maintainer should make, not a bot.

Other factors

The bug-hunting system found nothing on the current revision. All eight prior inline threads (mine and CodeRabbit's) are marked resolved with corresponding commits. CI build #51088 was retriggered after an infra timeout (commit 5927456), so the latest run hasn't been confirmed green in the timeline yet. Given the blast radius (every outbound connection across all platforms) I'm not comfortable shadow-approving without a human glance, even though I believe the change is correct.

robobun and others added 6 commits June 25, 2026 09:06
processResults() in the internal DNS cache (used by fetch, Bun.serve
outbound, Bun.connect, etc.) always reordered getaddrinfo() results so
the first entry was IPv6. On hosts where IPv6 is configured but a
specific destination is unreachable this picks a dead AAAA before a
reachable A, producing ECONNRESET; it also disagrees with the OS's own
RFC 6724 destination selection and with node:dns.lookup()'s verbatim
default.

Drop the IPv6-first interleave. The packing into a single allocation
stays; the sort goes. Node reports verbatim order by default, and
AI_ADDRCONFIG / gai.conf have already told glibc (or libinfo on mac)
which family should be preferred for this destination.

Fixes #29695
CodeRabbit noted the first version of this test rewrote the host-global
/etc/gai.conf for the whole test shard, so any other parallel test doing
dual-stack getaddrinfo during that window would observe the IPv4
preference and potentially flake.

Replace the gai.conf dance with a tiny LD_PRELOAD shim that intercepts
only one hostname (mock29695) and returns [127.0.0.1, ::1] in that
exact order. The .so lives in tempDirWithFiles() and is scoped to the
single Bun.spawn subprocess that runs the fetch — nothing leaks to the
rest of the test run.

Assertion order also updated to match the coding guideline: parse the
stdout payload and assert the regression signal before the process
exit code, so a failure message shows the JSON body we actually
received before the unrelated 'exitCode 0' line.
…e child stderr

Review feedback from claude[bot]:

1. The shim's freeaddrinfo recovered the bundle head by subtracting
   offsetof(mock_bundle, a4) from the caller-supplied addrinfo and
   reading a magic word there. When the subprocess's Bun.serve(::)
   also goes through the shim and eventually calls freeaddrinfo on a
   real glibc-owned allocation, that read lands 8 bytes before the
   glibc allocation — undefined behavior, and if the bytes happened to
   match MOCK_MAGIC we'd free() a pointer we don't own.

   Replaced the magic with a tiny mutex-protected registry of live
   bundle pointers. freeaddrinfo checks whether the caller's addrinfo
   equals &bundle->a4 for any registered bundle; if yes free it, else
   fall through to real freeaddrinfo. No out-of-bounds reads.

2. The subprocess's stderr was piped, awaited, then discarded via
   array-element elision. A failure in the child (LD_PRELOAD rejected,
   :: bind failed, fetch threw) left stdout empty, so JSON.parse('')
   masked the real error with 'Unexpected end of JSON input'. Assert
   exitCode and stderr together before JSON.parse so the diff prints
   the child's actual error message.

3. Documented that strictly this test is observing which loopback
   connect won the happy-eyeballs race, not which entry
   processResults() placed first, since uws' start_connections() opens
   CONCURRENT_CONNECTIONS=4 sockets in the same tick. Empirically
   stable on glibc Linux loopback (10/10 pass with fix, 10/10 fail
   without) but worth flagging if this ever flakes.
…ned head

Follow-up to d44f2d0 and coderabbit feedback: previously the shim always
built both IPv4 and IPv6 entries and returned &b->a4, ignoring
hints->ai_family. That violates the libc contract, and freeaddrinfo()
only recognized &b->a4 as a valid head — if any caller ever asked for
AF_INET6 explicitly and got handed &b->a6, freeaddrinfo would fall
through to the real glibc implementation with an offset pointer and
crash.

Now:
- AF_INET  → return &b->a4 (ai_next = NULL)
- AF_INET6 → return &b->a6 (ai_next = NULL)
- AF_UNSPEC → return &b->a4 with ai_next = &b->a6 (the order under test)
- anything else → EAI_FAMILY

Registry tracks the exact head pointer we returned alongside the bundle
so freeaddrinfo can pair them back up regardless of which family was
asked for.

Does not change the regression signal (Bun fetch uses AF_UNSPEC); just
makes the shim faithful to libc.
@robobun
robobun force-pushed the farm/04be0174/preserve-os-dns-order branch from 5927456 to 5b41f1a Compare June 25, 2026 09:11
@robobun

robobun commented Jun 25, 2026

Copy link
Copy Markdown
Collaborator Author

Rebased onto main to resolve the merge conflict. The conflict was non-trivial: the internal DNS module was ported from Zig to Rust on main (#32621 et al.), deleting src/runtime/dns_jsc/dns.zig that this PR originally modified.

Resolution: re-applied the identical fix to the Rust port src/runtime/dns_jsc/dns.rs — removed the IPv6-first interleave sort from process_results (the direct translation of the old processResults), keeping the single-allocation packing and pointer re-linking intact. The regression test is unchanged.

Verified on a fresh debug build:

  • unfixed dns.rs → dual-stack server sees ::1 (test fails)
  • fixed dns.rs → sees ::ffff:127.0.0.1 (test passes)

Also dropped the stale empty ci: retrigger commit that had accumulated from an earlier Azure VM infra outage.

Comment thread test/regression/issue/29695.test.ts Resolved
Comment thread test/regression/issue/29695.test.ts Resolved
The happy-eyeballs caveat comment pointed at context.c:596 (now :632
after the rebase) and the Zig name processResults(). Drop the hard
line number (the file path + function name are greppable) and use the
Rust name process_results().

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

Thanks for addressing the stale-breadcrumb nits — the test and PR body now line up with the Rust port. I'm deferring to a human on the runtime change itself: dropping the IPv6-first interleave in process_results() is a deliberate policy shift that affects address selection for every outbound connection (fetch, bun install, Bun.connect), and it was re-applied across a non-trivial Zig→Rust rebase, so it's worth a maintainer sign-off on the behavioral change rather than just the test mechanics.

Extended reasoning...

Overview

This PR makes two changes:

  1. src/runtime/dns_jsc/dns.rs — removes the IPv6-first interleave sort from process_results(), the function that packs getaddrinfo() results into the internal DNS cache used by fetch, Bun.connect, Bun.serve outbound, bun install, and every other uws-backed connect. After the change, the OS's RFC 6724 / gai.conf / AI_ADDRCONFIG ordering is preserved verbatim instead of being reordered to lead with AAAA.
  2. test/regression/issue/29695.test.ts — a new ~250-line glibc-Linux-only regression test that compiles an LD_PRELOAD shim overriding getaddrinfo/freeaddrinfo for a synthetic hostname, spawns a Bun subprocess, and asserts the dual-stack server observed the IPv4-mapped client address (proving the cache didn't reorder v6 to the front).

The PR went through several review rounds (gai.conf mutation → LD_PRELOAD shim → registry-based freeaddrinfo → ai_family honoring → tempDir disposal), and was rebased two months later across a Zig→Rust port of the DNS module. All inline comments — including my two most recent nits about stale Zig/line-number breadcrumbs after the rebase — have been addressed (commit 02127fe0 and the updated PR body).

Security risks

None identified. The change does not introduce new attack surface; it removes logic and defers to libc's existing ordering. The LD_PRELOAD shim in the test is scoped to a single child process via env var and lives in a disposable tempDir, so there is no host-global mutation (the earlier /etc/gai.conf approach that did have that risk was removed in e5d5d7a).

Level of scrutiny

High. The runtime diff is small (~25 lines net removed) but the blast radius is large: it changes which address family is tried first for every outbound connection in Bun. The rationale (match Node.js verbatim default, honor RFC 6724, fix #29695/#25619/#29227/#4988/#4938) is sound and well-argued, but this is a behavioral policy change — not a bug fix in the narrow sense — and the original interleave was presumably added deliberately. A maintainer should confirm they want OS-order-verbatim as the new policy, especially since hosts exist where the old behavior may have been helping (e.g. OS returns v4 first but v6 is the faster path).

Additionally, the fix was re-applied by hand across a Zig→Rust port during rebase. The author verified before/after on a debug build, but the surrounding process_results() packing/relinking code (raw pointer manipulation, assume_init, split_at_mut) is unsafe Rust that wasn't reviewed in its post-rebase form by a human.

Other factors

  • The test is thorough, hermetic, and well-gated, but only exercises glibc Linux; macOS/Windows/musl get no regression coverage for this change.
  • CI shows unrelated failures (musl build, Windows napi.test.ts) on the latest commit; the new test itself isn't implicated.
  • All bot review threads (mine and CodeRabbit's) are resolved; no human reviewer has weighed in at any point.
  • The bug-hunting system found no issues in the current revision.

@robobun

robobun commented Jun 27, 2026

Copy link
Copy Markdown
Collaborator Author

Opened #32864 with a different take on the same broken loop: rather than removing the interleave, it fixes it so families actually alternate while keeping the resolver's first entry in slot 0. The difference shows up when the resolver returns [AAAA, AAAA, AAAA, AAAA, A] (routable IPv6, destination's v6 addresses blackholed): preserving resolver order still puts four AAAA in usockets' first connect batch, interleaving gets the A record into it. Cross-linking so whoever picks this up can see both.

@robobun

robobun commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #36295, which keeps the resolver's first address first (same intent as this PR) but interleaves the rest so a blackholed first family can't fill all four parallel connect slots.

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

dns.lookup(..., { hints: dns.ADDRCONFIG }) returns IPv6 inside Bun.serve but IPv4 in a plain Bun process

2 participants