bao_uloop 0.2.1

Raw epoll + eventfd implementation of the uSockets loop ABI for Bao
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
//! `Bun__addrinfo_*` — the usockets DNS seam, backed by the shared per-host
//! cache (`bun_dns::cache`) plus a blocking `getaddrinfo` worker.
//!
//! # Contract (mirrors upstream Bun's `dns_jsc::internal`, Linux path)
//!
//! The C side (packages/bun-usockets/src/context.c, quic.c) drives this ABI:
//!
//! * `Bun__addrinfo_get(loop, host, port, &req)` — consults the shared cache.
//!   Returns **0** when a completed result is ready (`req` valid, result
//!   readable via `getRequestResult`), **1** when a fresh/inflight request
//!   was started (`req` valid; completion arrives via callbacks). It never
//!   returns -1 — context.c stores `req` unconditionally, so a miss here must
//!   still hand back a live request. (The previous stub returned -1 and left
//!   `ai_req` uninitialized in C, which made every hostname connect through
//!   usockets undefined behavior.)
//! * `Bun__addrinfo_set(req, socket)` — registers a `us_connecting_socket_t`.
//!   If the result is already complete the socket is notified immediately
//!   (same-thread `us_internal_dns_callback`).
//! * `Bun__addrinfo_cancel(req, socket)` — 1 if the socket was removed before
//!   completion (caller then owns teardown + `freeRequest`), 0 if the result
//!   is already set (callback fired or queued; socket.c keeps the socket
//!   alive until `us_internal_socket_after_resolve` finishes it).
//! * `Bun__addrinfo_freeRequest(req, err)` — releases one reference.
//! * `Bun__addrinfo_getRequestResult(req)` — `*addrinfo_result` (stable
//!   address inside the request; entries form an `ai_next` chain).
//! * `Bun__addrinfo_registerQuic2(req, pc, notify)` — QUIC variant of `set`
//!   with an explicit completion callback (see `bun_dns::internal`).
//!
//! # Resolution backend + TTL honesty
//!
//! POSIX `getaddrinfo` exposes no TTL, so worker-produced entries enter the
//! shared cache with the engine's cap (`BUN_CONFIG_DNS_TIME_TO_LIVE_SECONDS`,
//! default 30 s) — the same lifetime upstream Bun applies to its Linux
//! `getaddrinfo` WorkPool cache. Upstream also retries once without
//! `AI_ADDRCONFIG` on `EAI_NONAME`; both behaviors are mirrored here.
//!
//! Upstream keeps completed `Request`s in its own GlobalCache and invalidates
//! them when a connect fails (`freeRequest(err=1)`). Here the completed-result
//! cache is the shared `bun_dns` layer and a failed *connect* does not evict:
//! a refused/RST connection says nothing about DNS correctness, entries are
//! bounded by the TTL cap either way, and cross-stack invalidation on routine
//! connect failures would thrash the shared cache the other paths rely on.
//!
//! # Reference counting
//!
//! A new request starts with refs = 3: one per `Bun__addrinfo_get` handout
//! (released by `freeRequest`), one for the resolver worker, one for the
//! inflight map. Cache-hit-completed requests start with refs = 1. Inflight
//! dedupe bumps refs per extra handout. When refs reaches 0 the request box
//! is freed — this happens either in `freeRequest` or in `complete`,
//! whichever releases the last reference.
//!
//! # Windows arm (GetAddrInfoW pipeline) — ABI 对照
//!
//! The seam contract is byte-identical on both platforms; only the resolution
//! backend and the C-layout namespace differ. Per-item map:
//!
//! | item | POSIX | Windows | parity note |
//! |---|---|---|---|
//! | `Bun__addrinfo_get/set/cancel/freeRequest/getRequestResult/registerQuic(2)` | shared cache + worker + refcount machinery | **identical machinery** (all platform-independent in this file) | return values / callback timing / refcount rules unchanged |
//! | resolver backend | `getaddrinfo` (blocking, on the worker thread) | `GetAddrInfoW` (blocking, same worker thread) | sync call on our own worker both sides — no async-cancel surface exists at this layer, so there is no cancellation-semantics divergence |
//! | name encoding | UTF-8 bytes | UTF-16 = widening of the same UTF-8 bytes | ws2_32's ANSI `getaddrinfo` export would decode non-ASCII via the codepage; the W API keeps byte-faithful behavior for IDN names |
//! | `hints` | `AF_UNSPEC` + `SOCK_STREAM` + `AI_ADDRCONFIG` | same flags (winsock values; `AI_ADDRCONFIG` is 0x400 on windows vs glibc's 0x20 — each namespace is self-consistent) | semantic parity: only families with a configured adapter |
//! | ADDRCONFIG retry | once without `AI_ADDRCONFIG` on `EAI_NONAME` | once without `AI_ADDRCONFIG` on `WSANO_DATA` (11004) — ws2tcpip.h `#define EAI_NONAME WSANO_DATA` | same trigger, per-platform error namespace (`EAI_*` vs WSA codes; `GetAddrInfoW` returns the WSA code directly) |
//! | error channel to C | `EAI_*` code in `addrinfo_result.error` | WSA code in the same field | C interprets the code per its own platform's namespace (same split as upstream bun's posix/windows backends) |
//! | result layout | glibc/musl `struct addrinfo` (`socklen_t ai_addrlen`, `ai_addr` before `ai_canonname`) | winsock `ADDRINFOA` (`size_t ai_addrlen`, `ai_canonname` before `ai_addr`) | **layouts differ** — `addrinfo` is cfg-aliased per platform so `addrinfo_result_entry` always matches the C TU's definition (C gets the type from winsock headers on windows) |
//! | `ai_canonname` | nulled by `link_chain` | nulled identically | no `ADDRINFOW`-wide canonname ever escapes (freeing-side safe: we copy addresses into our own entries and `FreeAddrInfoW` the chain immediately) |
//! | chain release | `freeaddrinfo` | `FreeAddrInfoW` | 1:1 |
//! | cache (bun_dns) + TTL cap | shared | shared, byte-identical path (`resolve_worker` → `dns_cache::insert`) | `IpAddr` values are platform-neutral |
//!
//! Upstream reference: bun's windows DNS face (`src/runtime/dns_jsc/dns.rs`
//! `lib_uv_backend`) also resolves via the winsock wide pipeline (through
//! libuv's `uv_getaddrinfo`); here the same wide API is called directly on
//! this module's own worker, which is what keeps the seam's threaded
//! get/handout/cancel contract unchanged.

use std::collections::HashMap;
use std::ffi::CStr;
use std::ffi::CString;
use std::sync::Mutex;
use std::sync::OnceLock;
use std::thread;

use bun_dns::cache::{self as dns_cache, IpAddr};

use core::ffi::c_char;
use core::ffi::c_int;
use core::ffi::c_void;

// ───────── platform socket-type namespace ────────────────────────────────
//
// POSIX: libc (glibc/musl `struct addrinfo`, socklen_t addrlen). Windows: the
// ADDRINFOA mirror in `bun_windows_sys::ws2_32` — there C's `struct addrinfo`
// comes from winsock (winsock2.h/ws2tcpip.h), whose ADDRINFOA puts
// `ai_addrlen: size_t` before `ai_canonname`/`ai_addr`, so the C-facing
// `addrinfo_result_entry` layout must be the winsock shape on that target.
// The mirror's field names deliberately match the POSIX names, which keeps
// every producer/consumer below cfg-blind. See the ABI 对照 table in the
// module docs for the per-platform semantic map.
#[cfg(not(windows))]
use libc::{
    addrinfo, sockaddr_in, sockaddr_in6, sockaddr_storage, AI_ADDRCONFIG, AF_INET, AF_INET6,
    AF_UNSPEC, EAI_NONAME, IPPROTO_TCP, SOCK_STREAM,
};
#[cfg(not(windows))]
use libc::{sa_family_t, socklen_t};
#[cfg(windows)]
use bun_windows_sys::ws2_32::{
    addrinfo, sockaddr_in, sockaddr_in6, sockaddr_storage, AF_INET, AF_INET6, AF_UNSPEC,
    IPPROTO_TCP, SOCK_STREAM,
};

/// `ai_addrlen` field type: `socklen_t` (u32) in the POSIX addrinfo, `size_t`
/// in winsock's ADDRINFOA.
#[cfg(windows)]
#[allow(non_camel_case_types)] // mirrors the C type name
type socklen_t = usize;
/// `sa_family` field type: u16 on both (libc's `sa_family_t` does not exist
/// for windows targets; winsock's ADDRESS_FAMILY is u16).
#[cfg(windows)]
#[allow(non_camel_case_types)] // mirrors the C type name
type sa_family_t = u16;

/// Windows resolution backend: `GetAddrInfoW`/`FreeAddrInfoW` (ws2_32).
///
/// The W variants are the byte-faithful windows counterparts of POSIX
/// `getaddrinfo`/`freeaddrinfo`: ws2_32 also exports an ANSI `getaddrinfo`,
/// but that one decodes non-ASCII hostnames through the ANSI codepage, while
/// our C callers hand over UTF-8 bytes (URL host) — the wide API fed the
/// UTF-16 widening of those bytes keeps POSIX-facing semantics for IDN names.
#[cfg(windows)]
mod win_dns {
    use core::ffi::c_int;

    /// `ADDRINFOW` (`ws2tcpip.h`): `GetAddrInfoW`'s node type. Layout is
    /// identical to the ADDRINFOA mirror (`addrinfo` in this file's scope);
    /// only `ai_canonname` differs (`PWSTR` there). We never read canonname —
    /// the POSIX arm nulls it in `link_chain` too — so the returned chain is
    /// traversed through the A-layout alias.
    pub type ADDRINFOW = super::addrinfo;

    /// `AI_ADDRCONFIG` (`ws2tcpip.h`). Same semantic as POSIX's (resolve only
    /// families the local configuration can use); a different numeric value
    /// than glibc's — each platform uses its own constant namespace.
    pub const AI_ADDRCONFIG: c_int = 0x400;
    /// windows' `EAI_NONAME`: ws2tcpip.h does `#define EAI_NONAME WSANO_DATA`
    /// (11004). `GetAddrInfoW` returns the WSA code directly (not via
    /// WSAGetLastError), so this is the retry trigger's window counterpart.
    pub const EAI_NONAME: c_int = 11004;

    #[link(name = "ws2_32")]
    unsafe extern "system" {
        /// 0 on success; otherwise the WSA error code. Node/service are
        /// NUL-terminated UTF-16; service NULL mirrors the POSIX arm.
        pub unsafe fn GetAddrInfoW(
            pwNodeName: *const u16,
            pwServiceName: *const u16,
            pHints: *const ADDRINFOW,
            ppResult: *mut *mut ADDRINFOW,
        ) -> c_int;
        /// Frees a chain returned by `GetAddrInfoW`.
        pub unsafe fn FreeAddrInfoW(pAddrInfo: *mut ADDRINFOW);
    }
}

#[cfg(windows)]
use win_dns::{AI_ADDRCONFIG, EAI_NONAME};

/// Numeric-literal fast path for the connect seam (absorbed oven-sh/bun
/// 4af1842c8c, C `try_parse_ip`): fills `out` with `host`:`port` when `host`
/// is an IP literal and returns 1; returns 0 when it is a name (or a scoped
/// literal with a non-numeric zone), sending it to `getaddrinfo` instead —
/// the one parse behind usockets' connect paths, so a literal never reaches
/// the resolver.
///
/// # Safety
/// `host` must be a NUL-terminated C string (or null); `out` must be
/// writable `sockaddr_storage` storage (or null).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__parseIpAddress(
    host: *const c_char,
    port: u16,
    out: *mut sockaddr_storage,
) -> c_int {
    if host.is_null() || out.is_null() {
        return 0;
    }
    // SAFETY: caller contract — `host` is a NUL-terminated C string.
    let bytes = unsafe { CStr::from_ptr(host) }.to_bytes();
    // RFC 6874 `%zone` suffix: keep it only when it is a numeric interface
    // index we can put in `sin6_scope_id`; a name-form zone goes to
    // `getaddrinfo`, which knows how to resolve it.
    let (addr_bytes, zone) = match bytes.iter().position(|&b| b == b'%') {
        Some(at) => (&bytes[..at], Some(&bytes[at + 1..])),
        None => (bytes, None),
    };
    let ip = match core::str::from_utf8(addr_bytes).ok().and_then(|s| s.parse::<std::net::IpAddr>().ok()) {
        Some(ip) => ip,
        None => return 0,
    };
    let scope_id = match (ip, zone) {
        (std::net::IpAddr::V6(_), Some(zone)) => match core::str::from_utf8(zone).unwrap_or("").parse::<u32>() {
            Ok(idx) => idx,
            Err(_) => return 0,
        },
        _ => 0,
    };
    // SAFETY: `out` is writable `sockaddr_storage` storage; zero it first so
    // the unused tail of the chosen sockaddr is fully defined.
    unsafe { core::ptr::write_bytes(out, 0, 1) };
    match ip {
        std::net::IpAddr::V4(octets) => {
            // SAFETY: sockaddr_storage is at least sockaddr_in-sized and aligned.
            let sin = unsafe { &mut *out.cast::<sockaddr_in>() };
            sin.sin_family = AF_INET as sa_family_t;
            sin.sin_port = port.to_be();
            sin.sin_addr.s_addr = u32::from_ne_bytes(octets.octets());
        }
        std::net::IpAddr::V6(octets) => {
            // SAFETY: sockaddr_storage is at least sockaddr_in6-sized and aligned.
            let sin6 = unsafe { &mut *out.cast::<sockaddr_in6>() };
            sin6.sin6_family = AF_INET6 as sa_family_t;
            sin6.sin6_port = port.to_be();
            sin6.sin6_addr.s6_addr = octets.octets();
            sin6.sin6_scope_id = scope_id;
        }
    }
    1
}

// ─────────────── C-layout result types (internal/internal.h) ───────────────
//
// `struct addrinfo_result_entry { struct addrinfo info; struct sockaddr_storage _storage; }`
// `struct addrinfo_result { struct addrinfo_result_entry* entries; int error; }`

#[repr(C)]
struct AddrInfoResultEntry {
    info: addrinfo,
    storage: sockaddr_storage,
}

#[repr(C)]
struct AddrInfoResult {
    entries: *mut AddrInfoResultEntry,
    error: c_int,
}

/// Who to tell when the request completes.
enum Notify {
    /// `*mut us_connecting_socket_t` (context.c async path).
    Socket(*mut c_void),
    /// QUIC pending-connect handle + its threadsafe completion callback.
    Quic {
        pc: *mut c_void,
        notify: unsafe extern "C" fn(*mut c_void),
    },
}

struct ReqState {
    /// Manual refcount: 1 per `Bun__addrinfo_get` handout (balanced by
    /// `freeRequest`), +1 for the resolver worker, +1 while the request sits
    /// in the inflight map. Zero → the Box is freed.
    refs: usize,
    /// Set (under `state`'s lock) once resolution finishes. `set`/`cancel`
    /// consult this to pick between immediate-notify and queue.
    completed: bool,
    host: CString,
    port: u16,
    notify: Vec<Notify>,
    /// getaddrinfo error code (0 = success).
    error: c_int,
    /// Completed entries; `result_c.entries` points at this Vec's buffer.
    entries_buf: Vec<AddrInfoResultEntry>,
}

/// Opaque `struct addrinfo_request`. `result_c` must stay at a fixed offset:
/// C reads it through the pointer returned by `getRequestResult`.
struct Request {
    result_c: AddrInfoResult,
    state: Mutex<ReqState>,
}

// SAFETY: the raw pointers inside are usockets handles; Notify::Socket is
// only touched on the loop thread and only through the C notify entry points
// (which are the same call the upstream Zig code makes cross-thread). The
// request's shared mutable state is behind `state`'s mutex.
unsafe impl Send for Request {}
unsafe impl Sync for Request {}

/// Raw request handle wrapped for cross-thread storage/transfer. Sound
/// because requests are hand-refcounted: whoever holds a `RequestPtr` owns
/// one reference (map membership / worker transfer), so the pointee outlives
/// every wrapper.
#[derive(Clone, Copy, PartialEq, Eq)]
struct RequestPtr(*mut Request);
// SAFETY: see type docs.
unsafe impl Send for RequestPtr {}
// SAFETY: see type docs.
unsafe impl Sync for RequestPtr {}

/// Inflight (worker-outstanding) requests, keyed by the shared-cache key.
/// Map membership is one refs count.
static INFLIGHT: OnceLock<Mutex<HashMap<Box<str>, RequestPtr>>> = OnceLock::new();

fn inflight() -> &'static Mutex<HashMap<Box<str>, RequestPtr>> {
    INFLIGHT.get_or_init(|| Mutex::new(HashMap::new()))
}

unsafe extern "C" {
    /// Same-thread DNS completion: queues `c` on the loop's dns_ready_head.
    /// Provided by libusockets.a (loop.c).
    unsafe fn us_internal_dns_callback(c: *mut c_void, req: *mut c_void);
    /// Cross-thread DNS completion: queues + wakes the loop.
    /// Provided by libusockets.a (loop.c).
    unsafe fn us_internal_dns_callback_threadsafe(c: *mut c_void, req: *mut c_void);
}

// ───────────────────────────── entry points ─────────────────────────────

/// Query the shared cache / start resolution. See module docs for the
/// return-value contract.
///
/// SAFETY: `host` must be NUL-terminated and live for the call; `ptr` must be
/// a valid out-pointer. The returned request must eventually reach
/// `Bun__addrinfo_freeRequest` exactly once per handout.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_get(
    _loop: *mut c_void,
    host: *const c_char,
    port: u16,
    ptr: *mut *mut c_void,
) -> c_int {
    // SAFETY: caller contract (context.c/quic.c pass NUL-terminated hosts).
    let host = unsafe { CStr::from_ptr(host) };
    let mut completed_hit = false;
    let req = get_or_start(host, port, &mut completed_hit);
    // SAFETY: `ptr` is a valid out-pointer per the caller contract.
    unsafe { *ptr = req.cast::<c_void>() };
    if completed_hit { 0 } else { 1 }
}

/// Shared-cache lookup → completed request; miss → inflight dedupe or spawn.
fn get_or_start(host: &CStr, port: u16, completed_hit: &mut bool) -> *mut Request {
    if let Some(addrs) = dns_cache::lookup(host.to_bytes()) {
        *completed_hit = true;
        return Request::completed(addrs, port);
    }
    let key = dns_cache_key(host);
    {
        let inflight = inflight().lock().unwrap();
        if let Some(&RequestPtr(req)) = inflight.get(&key) {
            // The inflight map holds a reference, so the request is alive;
            // refs is bumped under its lock (worker completion cannot free
            // it while the map entry exists).
            let mut st = unsafe { (*req).state.lock().unwrap() };
            st.refs += 1;
            return req;
        }
    }
    let req = new_inflight(host, port);
    inflight()
        .lock()
        .unwrap()
        .insert(key.clone(), RequestPtr(req));

    // RequestPtr (not the bare pointer) so the closure captures a Send
    // wrapper; passed whole into resolve_worker to force whole-struct capture.
    let worker_req = RequestPtr(req);
    let spawned = thread::Builder::new()
        .name("bao-dns-resolve".into())
        .spawn(move || resolve_worker(worker_req, key));
    if spawned.is_err() {
        // No thread available: fail the request now. complete() releases the
        // worker+map refs and notifies any waiters.
        inflight().lock().unwrap().remove(&dns_cache_key(host));
        let notify = complete(req, Vec::new(), libc::EAGAIN as c_int);
        notify_all(notify);
    }
    req
}

/// Fresh unresolved request (refs = 3: C handout + worker + inflight map).
/// Callers must add it to the inflight map themselves; tests use this to
/// exercise the lifecycle without spawning a real resolver thread.
fn new_inflight(host: &CStr, port: u16) -> *mut Request {
    Box::into_raw(Box::new(Request {
        result_c: AddrInfoResult {
            entries: core::ptr::null_mut(),
            error: 0,
        },
        state: Mutex::new(ReqState {
            refs: 3,
            completed: false,
            host: host.to_owned(),
            port,
            notify: Vec::new(),
            error: 0,
            entries_buf: Vec::new(),
        }),
    }))
}

/// SAFETY: `req` must be a live request handed out by `Bun__addrinfo_get`,
/// and `socket` a live `us_connecting_socket_t` on this thread's loop.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_set(req: *mut c_void, socket: *mut c_void) -> c_int {
    // SAFETY: live request per caller contract.
    let Some(r) = (unsafe { (req as *const Request).as_ref() }) else {
        return 0;
    };
    let notify_now = {
        let mut st = r.state.lock().unwrap();
        if st.completed {
            Some(Notify::Socket(socket))
        } else {
            st.notify.push(Notify::Socket(socket));
            None
        }
    };
    if notify_now.is_some() {
        // Same thread as the connecting socket (set is called from
        // us_socket_group_connect) — no wakeup needed.
        // SAFETY: `socket` is a live us_connecting_socket_t per the caller.
        unsafe { us_internal_dns_callback(socket, req) };
    }
    0
}

/// SAFETY: `req` must be a live request; `socket` a live connecting socket.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_cancel(req: *mut c_void, socket: *mut c_void) -> c_int {
    // SAFETY: live request per caller contract.
    let Some(r) = (unsafe { (req as *const Request).as_ref() }) else {
        return 0;
    };
    let mut st = r.state.lock().unwrap();
    // Once completed, the callback has fired or is queued; the socket stays
    // alive until after_resolve drains it (socket.c relies on exactly this
    // two-outcome contract).
    if st.completed {
        return 0;
    }
    let before = st.notify.len();
    st.notify
        .retain(|n| !matches!(n, Notify::Socket(s) if *s == socket));
    (st.notify.len() != before) as c_int
}

/// SAFETY: `req` must be a live request with exactly one outstanding handout
/// being released by this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_freeRequest(req: *mut c_void, _error: c_int) {
    // SAFETY: live request per caller contract.
    let Some(r) = (unsafe { (req as *const Request).as_ref() }) else {
        return;
    };
    let mut st = r.state.lock().unwrap();
    st.refs -= 1;
    if st.refs == 0 {
        drop(st);
        // SAFETY: refs hit zero — no handouts, no worker, no map entry.
        drop(unsafe { Box::from_raw(r as *const Request as *mut Request) });
    }
}

/// SAFETY: `req` must be a live, completed request.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_getRequestResult(req: *mut c_void) -> *mut c_void {
    // SAFETY: live request per caller contract.
    let Some(r) = (unsafe { (req as *const Request).as_ref() }) else {
        return core::ptr::null_mut();
    };
    (&raw const r.result_c) as *const AddrInfoResult as *mut AddrInfoResult as *mut c_void
}

/// QUIC registration with explicit threadsafe completion callback.
///
/// SAFETY: `req` must be a live request; `pc` a live h3 PendingConnect that
/// stays valid until `notify` fires.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_registerQuic2(
    req: *mut c_void,
    pc: *mut c_void,
    notify: Option<unsafe extern "C" fn(*mut c_void)>,
) {
    let Some(cb) = notify else {
        return;
    };
    // SAFETY: live request per caller contract.
    let Some(r) = (unsafe { (req as *const Request).as_ref() }) else {
        return;
    };
    let notify_now = {
        let mut st = r.state.lock().unwrap();
        if st.completed {
            Some(Notify::Quic { pc, notify: cb })
        } else {
            st.notify.push(Notify::Quic { pc, notify: cb });
            None
        }
    };
    if let Some(Notify::Quic { pc, notify }) = notify_now {
        // registerQuic2 runs on the HTTP thread; the h3 callback is the
        // threadsafe variant, which is also correct same-thread.
        // SAFETY: `pc` is live per the caller contract.
        unsafe { notify(pc) };
    }
}

/// Legacy C-ABI registration kept for the internal.h declaration; no live C
/// caller (the Rust h3 client uses `Bun__addrinfo_registerQuic2` via
/// `bun_dns::internal::register_quic`). Without a callback there is no way
/// to deliver completion, so this is a no-op.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn Bun__addrinfo_registerQuic(_req: *mut c_void, _pc: *mut c_void) {}

// ───────────────────────────── resolution ─────────────────────────────

fn dns_cache_key(host: &CStr) -> Box<str> {
    // Mirrors bun_dns::cache's key normalization (ASCII-lowercase).
    String::from_utf8_lossy(&host.to_bytes().to_ascii_lowercase()).into()
}

fn resolve_worker(worker_req: RequestPtr, key: Box<str>) {
    let RequestPtr(req) = worker_req;
    let (host, port) = {
        let st = unsafe { (*req).state.lock().unwrap() };
        (st.host.clone(), st.port)
    };
    let (entries, addrs, error) = resolve_getaddrinfo(&host, port);
    if error == 0 && !addrs.is_empty() {
        dns_cache::insert(host.to_bytes(), addrs, None);
    }
    inflight().lock().unwrap().remove(&key);
    let notify = complete(req, entries, error);
    notify_all(notify);
}

/// Blocking resolution on this worker thread. Returns the C entries (built as
/// an interleaved `ai_next` chain, matching upstream `processResults`), the
/// raw address list (for the shared cache), and a getaddrinfo error code
/// (0 = success; EAI_* otherwise).
fn resolve_getaddrinfo(host: &CStr, port: u16) -> (Vec<AddrInfoResultEntry>, Vec<IpAddr>, c_int) {
    let mut hints: addrinfo = unsafe { core::mem::zeroed() };
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_ADDRCONFIG;

    // POSIX: `getaddrinfo(host, service=NULL)` over the NUL-terminated UTF-8
    // bytes. Windows: `GetAddrInfoW` over the UTF-16 widening of those bytes
    // (see win_dns docs for why the W entry point, not ws2_32's ANSI export).
    #[cfg(windows)]
    let host_w: Vec<u16> = {
        let mut w: Vec<u16> = String::from_utf8_lossy(host.to_bytes()).encode_utf16().collect();
        w.push(0);
        w
    };
    #[cfg(windows)]
    let host_arg = host_w.as_ptr();
    #[cfg(not(windows))]
    let host_arg = host.as_ptr();

    let mut result: *mut addrinfo = core::ptr::null_mut();
    // SAFETY: host is NUL-terminated; hints/result are valid pointers.
    let mut rc =
        unsafe { getaddrinfo(host_arg, core::ptr::null(), &hints, &mut result) };

    // Upstream retries once without AI_ADDRCONFIG on EAI_NONAME (an
    // IPv6-only box can make ADDRCONFIG suppress the only usable family).
    // Windows: the same trigger — GetAddrInfoW reports the WSA code directly,
    // and `EAI_NONAME` is `WSANO_DATA` (11004) there.
    if rc == EAI_NONAME {
        hints.ai_flags &= !AI_ADDRCONFIG;
        // SAFETY: same as above.
        rc = unsafe { getaddrinfo(host_arg, core::ptr::null(), &hints, &mut result) };
    }

    if rc != 0 || result.is_null() {
        if !result.is_null() {
            // SAFETY: result was allocated by getaddrinfo/GetAddrInfoW.
            unsafe { freeaddrinfo(result) };
        }
        return (Vec::new(), Vec::new(), rc);
    }

    // SAFETY: result is a live chain allocated by getaddrinfo/GetAddrInfoW.
    let (mut entries, mut addrs) = unsafe { collect_entries(result, port) };
    // SAFETY: done with the chain.
    unsafe { freeaddrinfo(result) };
    interleave_families(&mut entries, &mut addrs);
    link_chain(&mut entries);
    (entries, addrs, 0)
}

/// `freeaddrinfo`/`FreeAddrInfoW` — release a chain returned by the
/// platform's resolve call.
#[cfg(not(windows))]
unsafe fn freeaddrinfo(res: *mut addrinfo) {
    // SAFETY: `res` is a live getaddrinfo chain per the caller.
    unsafe { libc::freeaddrinfo(res) };
}
#[cfg(windows)]
unsafe fn freeaddrinfo(res: *mut addrinfo) {
    // SAFETY: `res` is a live GetAddrInfoW chain per the caller.
    unsafe { win_dns::FreeAddrInfoW(res) };
}

/// The platform resolve call: POSIX `getaddrinfo` / windows `GetAddrInfoW`.
///
/// SAFETY: `host_arg` is the platform-native NUL-terminated name
/// (`*const c_char` / `*const u16`); hints/result are valid pointers.
#[cfg(not(windows))]
unsafe fn getaddrinfo(
    host_arg: *const c_char,
    service: *const c_char,
    hints: &addrinfo,
    result: &mut *mut addrinfo,
) -> c_int {
    // SAFETY: host_arg/service NUL-terminated, hints/result valid per caller.
    unsafe { libc::getaddrinfo(host_arg, service, hints, result) }
}
#[cfg(windows)]
unsafe fn getaddrinfo(
    host_arg: *const u16,
    service: *const u16,
    hints: &addrinfo,
    result: &mut *mut addrinfo,
) -> c_int {
    // SAFETY: host_arg/service are NUL-terminated UTF-16; hints/result valid.
    unsafe { win_dns::GetAddrInfoW(host_arg, service, hints, result) }
}

/// Copy a getaddrinfo chain into C-layout entries + raw cache addrs.
///
/// SAFETY: `head` must be a live getaddrinfo result chain.
unsafe fn collect_entries(
    head: *mut addrinfo,
    port: u16,
) -> (Vec<AddrInfoResultEntry>, Vec<IpAddr>) {
    let mut entries: Vec<AddrInfoResultEntry> = Vec::new();
    let mut addrs: Vec<IpAddr> = Vec::new();
    let mut cur = head;
    while !cur.is_null() {
        // SAFETY: cur is non-null and points into the result chain.
        let ai = unsafe { &*cur };
        if !ai.ai_addr.is_null() {
            let mut entry = AddrInfoResultEntry {
                // SAFETY: plain-old-data copy of the chain node; the
                // ai_next/ai_addr/ai_canonname pointers it carries are
                // overwritten below / in link_chain before use.
                info: unsafe { core::ptr::read(ai) },
                storage: unsafe { core::mem::zeroed() },
            };
            // SAFETY: ai_addr is non-null and valid for ai_addrlen.
            if let Some(ip) = unsafe { copy_sockaddr(ai, &mut entry, port) } {
                addrs.push(ip);
                entries.push(entry);
            }
        }
        cur = ai.ai_next;
    }
    (entries, addrs)
}

/// Copy `ai.ai_addr` into `entry.storage`, point `entry.info.ai_addr` at it,
/// apply `port`, and return the raw address.
///
/// SAFETY: `ai.ai_addr` must be non-null and valid for `ai.ai_addrlen`, and
/// `ai.ai_family` must accurately describe it.
unsafe fn copy_sockaddr(
    ai: &addrinfo,
    entry: &mut AddrInfoResultEntry,
    port: u16,
) -> Option<IpAddr> {
    match ai.ai_family {
        AF_INET => {
            // SAFETY: family-checked; sockaddr_in fits sockaddr_storage.
            let src = unsafe { &*(ai.ai_addr as *const sockaddr_in) };
            // SAFETY: storage is zeroed and at least sockaddr_in-sized.
            let dst = unsafe { &mut *((&raw mut entry.storage).cast::<sockaddr_in>()) };
            dst.sin_family = AF_INET as sa_family_t;
            dst.sin_port = port.to_be();
            dst.sin_addr = src.sin_addr;
            entry.info.ai_family = AF_INET;
            entry.info.ai_addrlen = core::mem::size_of::<sockaddr_in>() as socklen_t;
            // ai_addr is NOT set here: this entry is a stack local that gets
            // moved into the Vec by value — a self-pointer assigned now would
            // dangle with the frame. link_chain re-points it at the entry's
            // own storage inside the final Vec (see its BCE note).
            Some(IpAddr::V4(src.sin_addr.s_addr.to_ne_bytes()))
        }
        AF_INET6 => {
            // SAFETY: family-checked; sockaddr_in6 fits sockaddr_storage.
            let src = unsafe { &*(ai.ai_addr as *const sockaddr_in6) };
            // SAFETY: storage is zeroed and at least sockaddr_in6-sized.
            let dst = unsafe { &mut *((&raw mut entry.storage).cast::<sockaddr_in6>()) };
            dst.sin6_family = AF_INET6 as sa_family_t;
            dst.sin6_port = port.to_be();
            dst.sin6_addr = src.sin6_addr;
            entry.info.ai_family = AF_INET6;
            entry.info.ai_addrlen = core::mem::size_of::<sockaddr_in6>() as socklen_t;
            // ai_addr intentionally not set — see the AF_INET arm's note.
            Some(IpAddr::V6(src.sin6_addr.s6_addr))
        }
        _ => None,
    }
}

/// Interleave v6/v4 starting with IPv6, in lockstep across both parallel
/// vectors (upstream `processResults` ordering — `start_connections` then
/// opens family-balanced candidate sockets).
fn interleave_families(entries: &mut [AddrInfoResultEntry], addrs: &mut [IpAddr]) {
    debug_assert_eq!(entries.len(), addrs.len());
    let mut want = AF_INET6;
    for idx in 0..entries.len() {
        if entries[idx].info.ai_family == want {
            want = other_family(want);
            continue;
        }
        for j in idx + 1..entries.len() {
            if entries[j].info.ai_family == want {
                entries.swap(idx, j);
                addrs.swap(idx, j);
                want = other_family(want);
                break;
            }
        }
    }
}

fn other_family(f: c_int) -> c_int {
    if f == AF_INET6 {
        AF_INET
    } else {
        AF_INET6
    }
}

/// Point each entry's `ai_next` at the following entry and drop the stale
/// canonname pointer copied from the source chain.
///
/// BCE (hostname-connect hang): every producer (`collect_entries`,
/// `entry_from_ip`) builds an entry as a stack local and only then moves it
/// (by value) into the Vec. The `ai_addr` stored there points at the
/// *stack-frame* storage — dangling once the frame dies — so C's
/// `init_addr_with_port` memcpy'd 16 bytes of stack residue into the connect
/// address (`0.0.0.0`, `AF_UNSPEC`, …) and every hostname connect through
/// usockets hung or misdialed. IP literals never see this seam (C
/// `try_parse_ip` short-circuits before `Bun__addrinfo_get`), which is why
/// only hostname URLs hung. Re-point `ai_addr` at each entry's *own* storage
/// in the final Vec, here, the single mandatory tail of both producer paths —
/// the authoritative redirect, exactly like the `ai_next` fixups below.
fn link_chain(entries: &mut [AddrInfoResultEntry]) {
    let len = entries.len();
    let base = entries.as_mut_ptr();
    for idx in 0..len {
        // SAFETY: idx < len; single mutable access per iteration, and the
        // pointers stored into ai_next/ai_addr are raw (no borrow carried
        // across).
        let entry = unsafe { &mut *base.add(idx) };
        entry.info.ai_canonname = core::ptr::null_mut();
        entry.info.ai_addr = core::ptr::addr_of_mut!(entry.storage).cast();
        if idx + 1 < len {
            entry.info.ai_next = core::ptr::addr_of_mut!(entry.info);
            // SAFETY: idx + 1 < len.
            entry.info.ai_next = unsafe { core::ptr::addr_of_mut!((*base.add(idx + 1)).info) };
        } else {
            entry.info.ai_next = core::ptr::null_mut();
        }
    }
}

/// Mark the request completed and release the worker+map references.
/// Returns the notify list (moved out under the same lock — once `completed`
/// is visible, cancel can no longer remove anyone) and frees the request if
/// that released the last reference.
fn complete(req: *mut Request, entries: Vec<AddrInfoResultEntry>, error: c_int) -> Vec<Notify> {
    let mut st = unsafe { (*req).state.lock().unwrap() };
    st.completed = true;
    st.error = error;
    st.entries_buf = entries;
    // Single writer (the resolver side) publishes the C-facing result before
    // completion is delivered; the loop thread reads it only after the
    // callback/wakeup handshake, which orders the writes in practice (same
    // discipline as upstream's afterResult under the global cache lock).
    let entries_ptr = if st.entries_buf.is_empty() {
        core::ptr::null_mut()
    } else {
        st.entries_buf.as_mut_ptr()
    };
    unsafe {
        (*req).result_c.entries = entries_ptr;
        (*req).result_c.error = error;
    }
    let notify = core::mem::take(&mut st.notify);
    st.refs -= 2;
    if st.refs == 0 {
        drop(st);
        // SAFETY: refs hit zero — no handouts remain, worker+map released.
        drop(unsafe { Box::from_raw(req) });
    }
    notify
}

impl Request {
    /// Build an already-completed request from a shared-cache hit (refs = 1:
    /// the C handout). Not placed in the inflight map — there is no work.
    fn completed(addrs: Vec<IpAddr>, port: u16) -> *mut Request {
        let mut entries: Vec<AddrInfoResultEntry> =
            addrs.iter().map(|ip| entry_from_ip(ip, port)).collect();
        link_chain(&mut entries);
        let entries_ptr = if entries.is_empty() {
            core::ptr::null_mut()
        } else {
            entries.as_mut_ptr()
        };
        Box::into_raw(Box::new(Request {
            result_c: AddrInfoResult {
                entries: entries_ptr,
                error: 0,
            },
            state: Mutex::new(ReqState {
                refs: 1,
                completed: true,
                host: CString::default(),
                port,
                notify: Vec::new(),
                error: 0,
                entries_buf: entries,
            }),
        }))
    }
}

/// Deliver completions. Called from the resolver worker (threadsafe Cb) or,
/// for already-completed registrations, from the registering thread.
fn notify_all(notify: Vec<Notify>) {
    for owner in notify {
        match owner {
            Notify::Socket(socket) => {
                // SAFETY: the usockets invariant — a registered connecting
                // socket stays alive until its callback drains (cancel either
                // removed it before we took the list, or socket.c left it
                // alive for after_resolve). The req argument is unused by
                // loop.c.
                unsafe { us_internal_dns_callback_threadsafe(socket, core::ptr::null_mut()) };
            }
            Notify::Quic { pc, notify } => {
                // SAFETY: h3's PendingConnect stays alive until this fires.
                unsafe { notify(pc) };
            }
        }
    }
}

/// Build one C entry from a raw cache address (port applied; authoritative
/// for display only — context.c re-applies the real port via
/// `init_addr_with_port` before connecting).
fn entry_from_ip(ip: &IpAddr, port: u16) -> AddrInfoResultEntry {
    let mut entry = AddrInfoResultEntry {
        info: unsafe { core::mem::zeroed() },
        storage: unsafe { core::mem::zeroed() },
    };
    match ip {
        IpAddr::V4(octets) => {
            // SAFETY: storage is zeroed and at least sockaddr_in-sized.
            let dst = unsafe { &mut *((&raw mut entry.storage).cast::<sockaddr_in>()) };
            dst.sin_family = AF_INET as sa_family_t;
            dst.sin_port = port.to_be();
            dst.sin_addr.s_addr = u32::from_ne_bytes(*octets);
            entry.info.ai_family = AF_INET;
            entry.info.ai_socktype = SOCK_STREAM;
            entry.info.ai_protocol = IPPROTO_TCP;
            entry.info.ai_addrlen = core::mem::size_of::<sockaddr_in>() as socklen_t;
        }
        IpAddr::V6(octets) => {
            // SAFETY: storage is zeroed and at least sockaddr_in6-sized.
            let dst = unsafe { &mut *((&raw mut entry.storage).cast::<sockaddr_in6>()) };
            dst.sin6_family = AF_INET6 as sa_family_t;
            dst.sin6_port = port.to_be();
            dst.sin6_addr.s6_addr = *octets;
            entry.info.ai_family = AF_INET6;
            entry.info.ai_socktype = SOCK_STREAM;
            entry.info.ai_protocol = IPPROTO_TCP;
            entry.info.ai_addrlen = core::mem::size_of::<sockaddr_in6>() as socklen_t;
        }
    }
    // ai_addr intentionally not set here (stack-local entry moved by value):
    // link_chain re-points it at the entry's own storage inside the Vec.
    entry
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Cache-flood isolation: the shared bun_dns cache is process-global.
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    /// completed-from-cache requests must expose a readable C result with a
    /// correct single-entry chain (context.c's immediate-connect fast path).
    #[test]
    fn completed_request_result_layout() {
        let _guard = TEST_LOCK.lock().unwrap();
        dns_cache::insert(b"layout.test", vec![IpAddr::V4([127, 0, 0, 1])], Some(60));
        let mut hit = false;
        let req = get_or_start(
            CString::new("layout.test").unwrap().as_c_str(),
            8080,
            &mut hit,
        );
        assert!(hit);
        // SAFETY: req is a live handout.
        let result = unsafe { Bun__addrinfo_getRequestResult(req as *mut c_void) };
        assert!(!result.is_null());
        // SAFETY: result points at the request's result_c.
        let result = unsafe { &*(result as *const AddrInfoResult) };
        assert_eq!(result.error, 0);
        assert!(!result.entries.is_null());
        // SAFETY: entries points at entries_buf[0] (chain of one).
        let entry = unsafe { &*result.entries };
        assert!(entry.info.ai_next.is_null());
        assert_eq!(entry.info.ai_family, AF_INET);
        // BCE (hostname-connect hang) regression lock: ai_addr must point at
        // THIS entry's storage inside the request-owned Vec — not at a dead
        // producer stack frame. Pointer identity, plus the content it yields.
        assert!(core::ptr::eq(
            entry.info.ai_addr.cast::<u8>(),
            (&raw const entry.storage).cast::<u8>()
        ));
        // SAFETY: ai_addr points at entry.storage (identity-checked above).
        let sa = unsafe { &*(entry.info.ai_addr as *const sockaddr_in) };
        assert_eq!(sa.sin_addr.s_addr, u32::from_ne_bytes([127, 0, 0, 1]));
        assert_eq!(sa.sin_port, 8080u16.to_be());
        // SAFETY: release the handout (single ref → freed).
        unsafe { Bun__addrinfo_freeRequest(req as *mut c_void, 0) };
    }

    /// BCE (hostname-connect hang) regression lock, multi-entry worker path:
    /// after collect→interleave→link_chain every entry's ai_addr must point
    /// at its own storage in the final Vec and dereference to the matching
    /// address — the invariant C's `init_addr_with_port` memcpy relies on.
    #[test]
    fn link_chain_points_ai_addr_at_own_storage() {
        let mut entries = vec![
            entry_from_ip(&IpAddr::V4([10, 0, 0, 1]), 80),
            entry_from_ip(&IpAddr::V6([0x20; 16]), 443),
        ];
        link_chain(&mut entries);
        for entry in &mut entries {
            assert!(
                core::ptr::eq(
                    entry.info.ai_addr.cast::<u8>(),
                    (&raw const entry.storage).cast::<u8>()
                ),
                "ai_addr must point at the entry's own Vec storage, not a producer stack frame"
            );
        }
        // Content survives through the published pointers: v4 first.
        // SAFETY: identity-checked above; family-checked here.
        let sa4 = unsafe { &*(entries[0].info.ai_addr as *const sockaddr_in) };
        assert_eq!(sa4.sin_addr.s_addr, u32::from_ne_bytes([10, 0, 0, 1]));
        assert_eq!(sa4.sin_port, 80u16.to_be());
        // SAFETY: same for the v6 entry.
        let sa6 = unsafe { &*(entries[1].info.ai_addr as *const sockaddr_in6) };
        assert_eq!(sa6.sin6_addr.s6_addr, [0x20; 16]);
        assert_eq!(sa6.sin6_port, 443u16.to_be());
    }

    /// A miss must hand back a live request (never null / never leave the C
    /// out-pointer untouched) and register it inflight so a concurrent get
    /// dedupes onto the same request. Uses `new_inflight` directly so no real
    /// resolver thread spawns; the dedupe branch of `get_or_start` is then
    /// exercised through the map entry.
    #[test]
    fn miss_creates_inflight_request() {
        let _guard = TEST_LOCK.lock().unwrap();
        let host = CString::new("definitely-miss-1.test").unwrap();
        let req = new_inflight(host.as_c_str(), 443);
        assert!(!req.is_null());
        let key = dns_cache_key(&host);
        inflight()
            .lock()
            .unwrap()
            .insert(key.clone(), RequestPtr(req));
        {
            let inflight = inflight().lock().unwrap();
            assert!(inflight.contains_key(&key));
        }
        // get while inflight → same request via the dedupe branch, refs
        // bumped, no worker spawned (map entry exists). Callers initialize
        // `completed_hit` to false (Bun__addrinfo_get does); the dedupe
        // branch leaves it untouched.
        let mut hit = false;
        let req2 = get_or_start(host.as_c_str(), 443, &mut hit);
        assert!(!hit);
        assert_eq!(req, req2);
        // Simulate worker completion (releases worker+map refs) and drop the
        // map entry just like resolve_worker does.
        let notify = complete(req, Vec::new(), EAI_NONAME);
        assert!(notify.is_empty());
        inflight().lock().unwrap().remove(&key);
        // SAFETY: two handouts out → two frees (refs 3 + 1 dedupe - 2
        // complete - 1 - 1 = 0 → freed by the second one).
        unsafe {
            Bun__addrinfo_freeRequest(req as *mut c_void, 0);
            Bun__addrinfo_freeRequest(req2 as *mut c_void, 0);
        }
    }

    /// set() on an uncompleted request registers the socket; cancel removes
    /// it and reports 1; a second cancel reports 0.
    #[test]
    fn set_and_cancel_lifecycle() {
        let _guard = TEST_LOCK.lock().unwrap();
        let host = CString::new("definitely-miss-2.test").unwrap();
        let req = new_inflight(host.as_c_str(), 443);
        let key = dns_cache_key(&host);
        inflight()
            .lock()
            .unwrap()
            .insert(key.clone(), RequestPtr(req));
        let fake_socket = 0x1000usize as *mut c_void;
        // SAFETY: req is live; the fake socket is only stored/compared, never
        // dereferenced while the request is uncompleted.
        assert_eq!(
            unsafe { Bun__addrinfo_set(req as *mut c_void, fake_socket) },
            0
        );
        assert_eq!(
            unsafe { Bun__addrinfo_cancel(req as *mut c_void, fake_socket) },
            1
        );
        assert_eq!(
            unsafe { Bun__addrinfo_cancel(req as *mut c_void, fake_socket) },
            0
        );
        // SAFETY: release handout; then simulate worker completion (frees:
        // 3 refs - 1 handout free - 2 worker/map = 0).
        unsafe { Bun__addrinfo_freeRequest(req as *mut c_void, 0) };
        let notify = complete(req, Vec::new(), EAI_NONAME);
        assert!(notify.is_empty());
        inflight().lock().unwrap().remove(&key);
    }

    /// End-to-end: a real worker resolves `localhost`, the result lands in
    /// the shared cache, and a second `get` returns a completed hit without
    /// spawning another worker — the usockets path's fusion guarantee.
    #[test]
    fn end_to_end_resolve_then_cache_hit() {
        let _guard = TEST_LOCK.lock().unwrap();
        let host = CString::new("localhost").unwrap();
        // First get: miss → inflight request + real worker thread.
        let mut hit = false;
        let req = get_or_start(host.as_c_str(), 80, &mut hit);
        assert!(!hit);
        // The worker holds its refs, so `req` stays alive; wait for it.
        let mut completed = false;
        for _ in 0..1000 {
            {
                let st = unsafe { (*req).state.lock().unwrap() };
                if st.completed {
                    completed = true;
                    break;
                }
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        assert!(completed, "resolver worker did not complete in time");
        {
            // SAFETY: completed — result_c published before completion.
            let st = unsafe { (*req).state.lock().unwrap() };
            assert_eq!(st.error, 0);
            assert!(!st.entries_buf.is_empty());
        }
        // SAFETY: release the first handout.
        unsafe { Bun__addrinfo_freeRequest(req as *mut c_void, 0) };
        // The lookup path must now hit the shared cache the worker filled.
        assert!(dns_cache::lookup(b"localhost").is_some());
        // Second get: completed hit (return code 0 contract), no new worker.
        let req2 = get_or_start(host.as_c_str(), 80, &mut hit);
        assert!(hit);
        // SAFETY: release the second handout.
        unsafe { Bun__addrinfo_freeRequest(req2 as *mut c_void, 0) };
    }

    /// interleave_families must alternate v6-first across both parallel
    /// vectors so the cache sees the same order the entries chain gets.
    #[test]
    fn interleave_starts_v6() {
        let mut entries = vec![
            entry_from_ip(&IpAddr::V4([1, 1, 1, 1]), 0),
            entry_from_ip(&IpAddr::V4([2, 2, 2, 2]), 0),
            entry_from_ip(&IpAddr::V6([0x20; 16]), 0),
        ];
        let mut addrs = vec![
            IpAddr::V4([1, 1, 1, 1]),
            IpAddr::V4([2, 2, 2, 2]),
            IpAddr::V6([0x20; 16]),
        ];
        interleave_families(&mut entries, &mut addrs);
        assert_eq!(entries[0].info.ai_family, AF_INET6);
        assert_eq!(entries[1].info.ai_family, AF_INET);
        assert_eq!(entries[2].info.ai_family, AF_INET);
        assert!(matches!(addrs[0], IpAddr::V6(_)));
        link_chain(&mut entries);
        // SAFETY: chain links point inside the vec.
        unsafe {
            let next1 = (&raw mut entries[1].info) as *mut addrinfo;
            assert_eq!(entries[0].info.ai_next, next1);
            assert!(entries[2].info.ai_next.is_null());
        }
    }
}