Skip to content

Studio: stop an IPv6 blackhole from killing the backend - #10803

Merged
danielhanchen merged 18 commits into
unslothai:mainfrom
Lwrless:studio/ipv6-blackhole-connect-stall
Oct 5, 2026
Merged

danielhanchen merged 18 commits into
unslothai:mainfrom
Lwrless:studio/ipv6-blackhole-connect-stall

Conversation

@Lwrless

@Lwrless Lwrless commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Unsloth Studio would not come up for me today. The backend bound 127.0.0.1:8888 and then went quiet: HF token setting status stuck on "Checking token...", and about 80 seconds later the desktop app reported "Server stopped unexpectedly" with terminal_reason=unresponsive_health_check. The process was alive and healthy the whole time. The watchdog had missed /api/liveness three times, 15 seconds apart, and sent SIGTERM.

I was on a VPN that carries no IPv6 while the host still has an IPv6 address, so every AAAA answer is a blackhole: the SYN leaves, nothing comes back, and connect() sits there until the timeout. That turned out to be two bugs stacked on each other, and this PR is one commit for each.

What the network was doing

huggingface.co answers with eight AAAA and four A. socket.create_connection walks the getaddrinfo() results in order and applies the caller's timeout to each address, with no overall deadline:

for res in getaddrinfo(host, port, 0, SOCK_STREAM):
    sock = socket(af, socktype, proto)
    sock.settimeout(timeout)      # per address, inside the loop
    sock.connect(sa)

So a 10s client pays 80s and a 15s client pays 120s before it touches the first A record, on a link where IPv4 answers in ~300ms. Every sync HTTP stack in the process bottoms out there: httpx (so huggingface_hub 1.x, whose get_session() is an httpx.Client) through httpcore's sync backend, requests through urllib3, and urllib.request through http.client. The async side was fine, because anyio already implements Happy Eyeballs for AsyncClient.

Upstream was a dead end

I went looking for this to already be solved somewhere below us. CPython has python/cpython#88810 open for exactly this, sync Happy Eyeballs in socket.create_connection, filed in 2021 and still open. Even if it landed tomorrow it would ship in a future minor and never be backported, and Studio supports 3.9 through 3.14. httpcore's sync backend hands straight to socket.create_connection, so there is nothing to switch on there, and huggingface_hub sits on top of that. If we want this, it has to be ours.

The kill was a separate bug

A slow connect on its own should not kill anything. Sync Hub work runs in threads, and /api/liveness should keep answering while a thread waits on a socket. Adding Happy Eyeballs made the kill disappear along with the stall, which was suspicious rather than reassuring, so I went after it with a real stack instead of a guess.

GET /api/inference/status, which the frontend polls continuously, is async def and called _resolve_loaded_trust_remote_code inline on the event loop. Its auto_map fallback goes _config_has_auto_map → _load_remote_code_configs → hf_hub_download on a cache miss, despite the docstring saying "reads the loaded model's cached config; no network". One status poll parked the loop for the full address walk, /api/liveness went down with it, and the watchdog did what it is supposed to do.

validate_model and the transformers upgrade check already wrap this same read in asyncio.to_thread(_offline_guarded, ...). get_status was the one caller of the three that did not.

The two commits

1. Studio: resolve trust_remote_code off the event loop in /api/inference/status

Same pattern as the sibling call sites: asyncio.to_thread plus _offline_guarded. The guard matters as much as the offload; it bounds the read to the memoised reachability verdict instead of the per-address connect budget, which takes the route from ~80s to ~4s against an unreachable Hub on top of no longer blocking anything else. The read is also skipped when no model is loaded, where it previously walked the fallback with an empty identifier. The wrong docstring is corrected.

2. Studio: race address families on sync connects (RFC 8305 Happy Eyeballs)

utils/happy_eyeballs.py is a drop-in socket.create_connection. It interleaves the resolved families, staggers attempts 250ms apart per RFC 8305, and makes timeout the budget for the whole connect, which is what every caller already believed it had. A host that resolves to a single address delegates to the stdlib so its semantics and error types are untouched, and a refused port still fails immediately rather than waiting out the deadline.

It is installed process-wide beside activate_native_tls(), which has the same spawn-does-not-inherit property, so the same five entry points activate both. http.client reads socket.create_connection in HTTPConnection.__init__ rather than at class definition, so patching the module attribute before the first request reaches urllib and requests as well as httpx. UNSLOTH_STUDIO_HAPPY_EYEBALLS=0 turns it off; UNSLOTH_STUDIO_HAPPY_EYEBALLS_DELAY tunes the stagger.

Measurements

The black hole is real rather than mocked: 100::/64 is the RFC 6666 discard prefix, so a connect to it hangs exactly as it does behind the VPN, with no sudo and no VPN needed. Eight black-holed AAAA throughout, matching what huggingface.co returns.

before after
POST /api/hub/token/validate, no address reachable 80,485 ms 10,013 ms
connector alone, IPv4 reachable 80 s 0.25 s
GET /api/inference/status (three black-holed records) 30 s, loop parked 6 ms
/api/liveness during that poll timed out past 12 s 0.01 s
sweep of all 123 no-arg GET routes 1 parked the loop none

The token/validate number after the fix is the stated 10s timeout paid once instead of eight times; that is the correct cost when no address is reachable at all.

Update

…e/status

The frontend polls this route continuously, and its auto_map fallback reads raw
config JSON from the Hub. Run inline on the loop, one unreachable address family
parked the whole server -- /api/liveness with it -- and the desktop watchdog
SIGTERMs a backend that misses three 15s probes, surfaced to the user as "Server
stopped unexpectedly" with terminal_reason=unresponsive_health_check. The process
was alive and healthy the entire time.

socket.create_connection applies its timeout to EACH getaddrinfo result rather
than to the connect as a whole, so a host whose network black-holes AAAA pays it
once per record before the first A is tried. huggingface.co answers with eight
AAAA, so a status poll parked the loop for ~80s on a VPN carrying no IPv6.
Measured against the real app with the RFC 6666 discard prefix standing in for
the VPN: 30s of dead loop on only three black-holed records, with /api/liveness
failing outright rather than merely slowing.

validate_model and the transformers upgrade check already wrap this same read in
asyncio.to_thread + _offline_guarded; get_status was the only one of the three
callers that did not. Use the same pattern here. Also skip the read entirely when
no model is loaded: it previously walked the auto_map fallback with an empty
identifier and paid for it.

The offline guard matters as much as the offload. It bounds the read to the
memoised reachability verdict instead of the per-address connect budget, taking
the route from ~80s to ~4s against an unreachable Hub, on top of no longer
blocking anything else.

The docstring on _resolve_loaded_trust_remote_code claimed this fallback "reads
the loaded model's cached config; no network". It does not -- on a cache miss
_load_remote_code_configs calls hf_hub_download -- and that assumption is why the
call was left on the loop. Corrected here.

Tests: three new, asserting which thread the read runs on and that it goes
through the guard, in the style of the sibling off-event-loop guards. All three
fail on the pre-fix tree.
socket.create_connection loops over getaddrinfo() results and applies the
caller's timeout to EACH address, with no overall deadline:

    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        sock = socket(af, socktype, proto)
        sock.settimeout(timeout)      # per address, inside the loop
        sock.connect(sa)

On a host with IPv6 whose network black-holes AAAA -- a VPN carrying no IPv6, a
hotel or airline network, a partial dual-stack rollout -- every AAAA connect
burns the full timeout before the first A record is tried. huggingface.co answers
with eight AAAA and four A, so a 10s client pays 80s and a 15s client pays 120s
on a link where IPv4 answers in ~300ms.

Every sync HTTP stack in the process bottoms out there: httpx (so
huggingface_hub 1.x, whose get_session() is an httpx.Client) via httpcore's sync
backend, requests via urllib3, and urllib.request via http.client. Async httpx
already races through anyio, so this closes the gap on the sync side rather than
introducing a new policy.

Interleave the resolved families, stagger attempts 250ms apart per RFC 8305, and
make timeout the budget for the whole connect -- the behaviour every caller
already believed it had. A single-address host delegates to the stdlib so its
semantics and error types are untouched, and a refused port still fails
immediately instead of waiting out the deadline.

Installed process-wide beside activate_native_tls(), which has the same
spawn-does-not-inherit property, so every network-touching entry point activates
both. http.client reads socket.create_connection in HTTPConnection.__init__
rather than at class definition, so patching the module attribute before the
first request reaches urllib and requests as well as httpx. Opt out with
UNSLOTH_STUDIO_HAPPY_EYEBALLS=0.

Measured with eight black-holed AAAA (RFC 6666 discard prefix): POST
/api/hub/token/validate drops from 80.5s to 10.0s where no address is reachable
at all, which is the stated timeout paid once instead of eight times, and the
connector returns in 0.25s where IPv4 answers. Across a sweep of all 123 no-arg
GET routes, nothing parks the event loop.

CPython has an open issue for this (python/cpython#88810, filed 2021). Waiting is
not a plan: it would land in a future version, stdlib features are not
backported, and Studio supports 3.9 through 3.14.

Tests: nine new, including a cross-entry-point guard so a worker that activates
native TLS without this one is caught, mirroring test_native_tls_entrypoints.py.
chatgpt-codex-connector[bot]

This comment was marked as outdated.

scripts/lint_backend_python_floor.py failed the pull request: vermin reports that
utils/happy_eyeballs.py needs 3.11 for ExceptionGroup and for
create_connection's all_errors keyword, while studio-backend-ci declares
PYTHON_FLOOR 3.10.

Both are already behind `_HAS_EXCEPTION_GROUP = sys.version_info >= (3, 11)`, but
vermin reads names rather than control flow and cannot see a runtime guard, which
is exactly the case the lint's own docstring describes. So suppress at the site
with `# novermin`, as locale.getencoding() in the data-designer state_store
already does, rather than dropping the file from the scan or raising the floor.

Placement is not obvious and is worth recording: vermin attributes a keyword
argument to the line the CALL starts on, not to the line the keyword is written
on. The repo formatter explodes this call across lines, so a marker on the
closing paren or beside the keyword itself does nothing. Confirmed against vermin
directly on a two-line reduction of each form before settling on this one.
The racing connector accumulated every address's failure and raised the first.
socket.create_connection raises the LAST one when all_errors is false -- it calls
exceptions.clear() before appending each new error, so the single element it
raises is the most recent, and the docstring says so.

That difference is not cosmetic, because a caller reads which error it got.
utils.utils.hf_tcp_reachable treats ConnectionRefusedError as proof the endpoint
answered and any other OSError as unreachable:

    except ConnectionRefusedError:
        return True
    except OSError:
        return False

It dials through socket.create_connection, so it dials through this. On a host
where IPv6 fails fast with ENETUNREACH and IPv4 answers with ECONNREFUSED, the
old order handed it the ENETUNREACH, and the endpoint that had just answered was
recorded as unreachable. That switches the offline guard on -- the same guard the
status-route fix in this branch relies on to bound its reads.

Attempts already append in completion order, so the fix is to raise the last
rather than the first. A deadline that expires with attempts still in flight now
raises a timeout too, instead of whatever an address that failed earlier happened
to report; before, a refused address dialled at the start could be raised for a
connect that had actually run out of time on a black-holed one.

Tests: two new. The last-error one is scripted through a stub socket rather than
dialled, because whether a discard-prefix address hangs or is refused outright
depends on whether the host has an IPv6 route at all -- on the development
machine here it is refused, so a dialled version of this test would assert
nothing.

Reported by Codex on unslothai#10803.
hub/workers/hf_download.py is the Hub downloader. It spawns a fresh interpreter,
activates native TLS, and did not activate this -- so on the black-holed link
this whole change exists for, model downloads kept paying one timeout per
resolved address while the parent process no longer did. The STT download worker
and the export worker were missing for the same reason.

The guard that was supposed to catch this said it mirrored
test_native_tls_entrypoints.py, and then restated that file's list by hand and
dropped three of its seven entries. A copied list is not a mirror. Import
_ENTRYPOINTS from it instead, so a future entry point added there is covered here
without anyone remembering to, and keep only the one genuine addition --
diffusion_training_service.py, which activates inside the spawned child function
rather than at import, so the native TLS guard's module-level AST check does not
list it.

Verified by deleting the activation from hf_download.py and watching the guard
fail, rather than trusting that it would.

Reported by Codex on unslothai#10803.
…nector

The module docstring claimed every sync HTTP stack in the process bottoms out at
socket.create_connection, naming "requests via urllib3". That is wrong. urllib3
2.x implements urllib3.util.connection.create_connection itself, with its own
getaddrinfo loop and its own socket.connect, and never calls the stdlib's -- so
patching the socket module does nothing for anything built on requests.

Checked against the installed 2.7.0 rather than from memory. The httpx half of
the claim does hold: httpcore 1.0.9 calls socket.create_connection directly, so
huggingface_hub 1.x is covered.

What stays uncovered is therefore worth naming rather than leaving implied: the
raw Hub API fallback at utils/models/model_config.py, which calls
requests.get(..., timeout = 15) deliberately to bypass the hub constant, and all
of huggingface_hub on Python 3.9, where requirements/studio.txt pins the
requests-based huggingface-hub==0.36.2. Both keep the one-timeout-per-address
walk on a black-holed link.

Closing that gap means patching a third-party library's connector process-wide,
which is a larger ask than patching the stdlib's and deserves its own decision
rather than riding along here. Left as a follow-up, and now documented where
someone will find it instead of a claim that says it is already handled.

Reported by Codex on unslothai#10803.
Moving the trust_remote_code read off the event loop put a suspension point
between reading the active model and building the response, where there had not
been one: get_status had exactly one await before this branch, and it ran before
model_info was read.

model_info, inference_config, the safetensors capability flags and the resolved
trust requirement are all derived from backend.active_model_name before that
await. The response then read backend.active_model_name and
backend.models.keys() again. A load or unload completing while the read was off
on its worker thread therefore published the new model's identity carrying the
previous model's capabilities and trust requirement, and the frontend hydrates
its runtime state from exactly those fields. requires_trust_remote_code being
the wrong one of the two is the part worth avoiding.

The window is as long as the Hub read takes, which on the black-holed link this
branch is about is seconds rather than microseconds, and status is polled
continuously, so this is a race with a real chance of being lost.

Snapshot the identifier once, before the await, and build the response from the
snapshot. `loaded` stays live: it answers "what is resident", not "what is this
response about".

Tests: one new, swapping the backend's active model from inside the resolve and
asserting the response does not mix the two. It fails on the unfixed route.

Reported by Codex on unslothai#10803.
@Lwrless

This comment has been minimized.

@danielhanchen

This comment has been minimized.

…on does

The racing connector shared one budget of `timeout` across the entire connect.
The stdlib does not. socket.create_connection hands the caller's timeout to each
resolved address in turn, so an address late in the list still gets a full budget
of its own, and a host with n addresses can cost n x timeout.

Sharing one budget took that away twice over:

  - an attempt opened k staggers in had timeout - k*0.25 left, not timeout;
  - once timeout/0.25 attempts had opened, the deadline had already passed and
    every address behind them was never dialled at all.

So a host whose only reachable address sits late in the list failed here where
the stdlib connected. Measured against real black holes -- 192.0.2.0/24 is
TEST-NET-1, which drops SYNs on this network -- with a real acceptor on
127.0.0.1 as the last address:

    9 A records, only the last one reachable, timeout = 1s
        stdlib      8.01s  connected
        before      1.00s  TimeoutError
        after       2.01s  connected

The deadline now carries one stagger per extra address, so attempt k has
timeout + (n-k)*delay -- never less than the timeout the stdlib gave it. The
whole walk still ends within timeout + (n-1)*delay against the stdlib's
n x timeout, which is where the black-hole fix came from in the first place, so
nothing is given back.

Interleaving already covers the common form of this: a host with one dead family
and one live one gets the live family second, not ninth. The case that needed
fixing is a single family with several dead records, where there is no other
family to cut in.

Tests: one new, scripted, because what it asserts is which attempts open and
when. The budget test is renamed to state the bound it now holds to.

Raised in review on unslothai#10803.
Reverts the two commits that fix /api/inference/status, so this branch carries
only the process-wide socket.create_connection replacement. Requested in review:
the connector changes the connect budget for every sync caller in the backend and
deserves its own review, separate from a route fix that was already accepted.

The offload and its snapshot follow-up move to unslothai#10830 unchanged. This is a
revert rather than a rewrite so the commits under review here keep their IDs, and
the review threads on them stay anchored.

Reverted:

  4da15d5  Studio: resolve trust_remote_code off the event loop in
             /api/inference/status
  04c9302  Studio: snapshot the active model across the trust_remote_code await

and the hunk of 18cef76 that formatted the test file those two added.
@Lwrless

This comment has been minimized.

@danielhanchen

This comment has been minimized.

…te_connection does

Checking error-type parity against the stdlib for the reachable-Hub question on
unslothai#10803 turned up one divergence. With a black-holed address followed by a
refused one, the stdlib raises ConnectionRefusedError and the connector raised
TimeoutError.

The stdlib's rule is simple: it walks every address, each with the full
timeout, and raises whatever the last one did. The connector had a different
rule from 68d0ab2: a deadline reached with an attempt still in flight is a
timeout, whatever an address that failed earlier reported. The two agree when
the black hole is last, and disagree when it is not.

That difference lands on utils.utils.hf_tcp_reachable, which reads
ConnectionRefusedError as "the endpoint answered" and any other OSError as
unreachable. In the [black hole, refused] order the stdlib says answered and
the connector said unreachable, and the offline guard switched on.

Now the last address in resolver order decides: its own failure if it had one,
else a timeout, since at the deadline it was still in flight and the stdlib's
attempt on it would have timed out too. Failures are recorded per address to
make that lookup; the completion-ordered list stays for the ExceptionGroup.

Parity means the same answer, not the more informative one: in the mirror order
[refused, black hole] both raise TimeoutError, and a test pins each order.

Measured with the same inputs on both connectors, all four cases now match:
refused on every address, an unresolvable host, black holes on every address,
and the mixed order above.

Raised in review on unslothai#10803.
@Lwrless

This comment has been minimized.

@danielhanchen danielhanchen self-assigned this Oct 5, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 5, 2026
@danielhanchen

danielhanchen commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Review record for #10803, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#442.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror b0d471060 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/happy_eyeballs.py (on the mirror)

@@ -0,0 +1,218 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""RFC 8305 Happy Eyeballs for sync connects.
+
+``socket.create_connection`` applies ``timeout`` per resolved address, so a black-holed
+family (VPN without IPv6) costs one timeout per address (python/cpython#88810). httpx's
+sync backend and ``http.client`` call it; ``requests`` does not (urllib3 2.x has its own
+loop). Spawned children must re-activate, like :mod:`utils.native_tls`.
+"""
+
+from __future__ import annotations
+
+import errno
+import logging
+import os
+import selectors
+import socket
+import sys
+import time
+
+_ENV = "UNSLOTH_STUDIO_HAPPY_EYEBALLS"
+_DELAY_ENV = "UNSLOTH_STUDIO_HAPPY_EYEBALLS_DELAY"
+_FALSEY = ("0", "false", "no", "off")
+
+# Connection Attempt Delay, RFC 8305 section 5.
+_DEFAULT_DELAY = 0.25
+
+_IN_FLIGHT = frozenset({errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY})
+_HAS_EXCEPTION_GROUP = sys.version_info >= (3, 11)
+
+_logger = logging.getLogger(__name__)
+_original_create_connection = socket.create_connection
+_activated = False
+
+
+def happy_eyeballs_enabled() -> bool:
+    return os.environ.get(_ENV, "").strip().lower() not in _FALSEY
+
+
+def attempt_delay() -> float:
+    try:
+        value = float(os.environ.get(_DELAY_ENV, "").strip() or _DEFAULT_DELAY)
+    except ValueError:
+        return _DEFAULT_DELAY
+    return max(0.0, value)
+
+
+def _interleave(infos: list) -> list:
+    """Round-robin across families, resolver order kept within each."""
+    by_family: dict = {}
+    for info in infos:
+        by_family.setdefault(info[0], []).append(info)
+    queues = list(by_family.values())
+    ordered = []
+    for i in range(max((len(q) for q in queues), default = 0)):
+        for q in queues:
+            if i < len(q):
+                ordered.append(q[i])
+    return ordered
+
+
+def happy_eyeballs_connection(
+    address,
+    timeout = socket._GLOBAL_DEFAULT_TIMEOUT,
+    source_address = None,
+    *,
+    all_errors = False,
+):
+    """Drop-in ``socket.create_connection``: attempts overlap, each with the whole ``timeout``."""
+    host, port = address
+    if timeout is socket._GLOBAL_DEFAULT_TIMEOUT:
+        resolved_timeout = socket.getdefaulttimeout()
+    else:
+        resolved_timeout = timeout
+
+    infos = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
+    if len(infos) <= 1:
+        if _HAS_EXCEPTION_GROUP:
+            return _original_create_connection(  # novermin
+                address,
+                timeout,
+                source_address,
+                all_errors = all_errors,
+            )
+        return _original_create_connection(address, timeout, source_address)
+
+    ordered = _interleave(infos)
+    delay = attempt_delay()
+    exceptions: list = []
+    failed: dict = {}  # sockaddr -> its failure
+    pending: dict = {}  # socket -> (sockaddr, expiry); every attempt gets the whole timeout
+    winner = None
+
+    def _fail(sa, exc):
+        exceptions.append(exc)
+        failed[sa] = exc
+
+    sel = selectors.DefaultSelector()
+    try:
+        index = 0
+        next_due = 0.0
+        kick = True  # a failed attempt lets the next one start at once (RFC 8305)
+        while True:
+            now = time.monotonic()
+            for sock, (sa, expiry) in list(pending.items()):
+                if expiry is not None and expiry <= now:
+                    sel.unregister(sock)
+                    del pending[sock]
+                    sock.close()
+                    _fail(sa, socket.timeout("timed out"))
+                    kick = True
+            if index < len(ordered) and (kick or not pending or now >= next_due):
+                kick = False
+                af, socktype, proto, _canon, sa = ordered[index]
+                index += 1
+                next_due = now + delay
+                sock = None
+                try:
+                    sock = socket.socket(af, socktype, proto)
+                    sock.setblocking(False)
+                    if source_address:
+                        sock.bind(source_address)
+                    err = sock.connect_ex(sa)

P2 Badge Preserve fixed source ports across raced attempts

When a caller supplies a nonzero source_address port, the first in-flight socket keeps that local endpoint bound, so subsequent candidates generally fail here with EADDRINUSE instead of being tried. This differs from socket.create_connection, which closes each failed attempt before binding the next one, and can make a reachable later address fail whenever an earlier address is black-holed. Either avoid overlapping attempts for fixed source ports or otherwise preserve the documented source_address behavior.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in d772ba3: a nonzero source_address port now delegates to the stdlib's sequential walk, since only one socket can hold that local port; covered by test_a_fixed_source_port_walks_like_the_stdlib.

Round 2: reviewed mirror 136d5ed19 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/utils/happy_eyeballs.py (on the mirror)

@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""RFC 8305 Happy Eyeballs for sync connects.
+
+``socket.create_connection`` applies ``timeout`` per resolved address, so a black-holed
+family (VPN without IPv6) costs one timeout per address (python/cpython#88810). httpx's
+sync backend and ``http.client`` call it; ``requests`` does not (urllib3 2.x has its own
+loop). Spawned children must re-activate, like :mod:`utils.native_tls`.
+"""
+
+from __future__ import annotations
+
+import errno
+import logging
+import os
+import selectors
+import socket
+import sys
+import time
+
+_ENV = "UNSLOTH_STUDIO_HAPPY_EYEBALLS"
+_DELAY_ENV = "UNSLOTH_STUDIO_HAPPY_EYEBALLS_DELAY"
+_FALSEY = ("0", "false", "no", "off")
+
+# Connection Attempt Delay, RFC 8305 section 5.
+_DEFAULT_DELAY = 0.25
+
+_IN_FLIGHT = frozenset({errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY})
+_HAS_EXCEPTION_GROUP = sys.version_info >= (3, 11)
+
+_logger = logging.getLogger(__name__)
+_original_create_connection = socket.create_connection
+_activated = False
+
+
+def happy_eyeballs_enabled() -> bool:
+    return os.environ.get(_ENV, "").strip().lower() not in _FALSEY
+
+
+def attempt_delay() -> float:
+    try:
+        value = float(os.environ.get(_DELAY_ENV, "").strip() or _DEFAULT_DELAY)
+    except ValueError:
+        return _DEFAULT_DELAY
+    return max(0.0, value)
+
+
+def _interleave(infos: list) -> list:
+    """Round-robin across families, resolver order kept within each."""
+    by_family: dict = {}
+    for info in infos:
+        by_family.setdefault(info[0], []).append(info)
+    queues = list(by_family.values())
+    ordered = []
+    for i in range(max((len(q) for q in queues), default = 0)):
+        for q in queues:
+            if i < len(q):
+                ordered.append(q[i])
+    return ordered
+
+
+def happy_eyeballs_connection(
+    address,
+    timeout = socket._GLOBAL_DEFAULT_TIMEOUT,
+    source_address = None,
+    *,
+    all_errors = False,
+):
+    """Drop-in ``socket.create_connection``: attempts overlap, each with the whole ``timeout``."""
+    host, port = address
+    if timeout is socket._GLOBAL_DEFAULT_TIMEOUT:
+        resolved_timeout = socket.getdefaulttimeout()
+    else:
+        resolved_timeout = timeout
+
+    infos = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
+    # A fixed source port can only be bound by one socket at a time, so it cannot race.
+    if len(infos) <= 1 or (source_address and source_address[1]):
+        if _HAS_EXCEPTION_GROUP:
+            return _original_create_connection(  # novermin
+                address,
+                timeout,
+                source_address,
+                all_errors = all_errors,
+            )
+        return _original_create_connection(address, timeout, source_address)
+
+    ordered = _interleave(infos)
+    delay = attempt_delay()
+    exceptions: list = []
+    failed: dict = {}  # sockaddr -> its failure
+    pending: dict = {}  # socket -> (sockaddr, expiry); every attempt gets the whole timeout
+    winner = None
+
+    def _fail(sa, exc):
+        exceptions.append(exc)
+        failed[sa] = exc
+
+    sel = selectors.DefaultSelector()
+    try:
+        index = 0
+        next_due = 0.0
+        kick = True  # a failed attempt lets the next one start at once (RFC 8305)
+        while True:
+            now = time.monotonic()
+            for sock, (sa, expiry) in list(pending.items()):
+                if expiry is not None and expiry <= now:
+                    sel.unregister(sock)
+                    del pending[sock]
+                    sock.close()
+                    _fail(sa, socket.timeout("timed out"))
+                    kick = True
+            if index < len(ordered) and (kick or not pending or now >= next_due):
+                kick = False
+                af, socktype, proto, _canon, sa = ordered[index]
+                index += 1
+                next_due = now + delay
+                sock = None
+                try:
+                    sock = socket.socket(af, socktype, proto)
+                    sock.setblocking(False)
+                    if source_address:
+                        sock.bind(source_address)
+                    err = sock.connect_ex(sa)
+                    if err == 0:
+                        winner = sock
+                        break
+                    if err not in _IN_FLIGHT:
+                        raise OSError(err, os.strerror(err))
+                    sel.register(sock, selectors.EVENT_WRITE)
+                    pending[sock] = (
+                        sa,
+                        None if resolved_timeout is None else now + resolved_timeout,
+                    )
+                except OSError as exc:
+                    _fail(sa, exc)
+                    kick = True
+                    if sock is not None:
+                        sock.close()
+                    continue
+            if not pending:
+                if index >= len(ordered):
+                    break
+                continue
+
+            wakes = [e for _sa, e in pending.values() if e is not None]
+            if index < len(ordered):
+                wakes.append(next_due)
+            wait = max(0.0, min(wakes) - time.monotonic()) if wakes else None
+            for key, _mask in sel.select(wait):
+                sock = key.fileobj
+                err = sock.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
+                sel.unregister(sock)
+                sa, _expiry = pending.pop(sock)
+                if err == 0:
+                    winner = sock
+                    break
+                sock.close()
+                _fail(sa, OSError(err, os.strerror(err)))
+                kick = True
+            if winner is not None:
+                break
+    finally:
+        for sock in list(pending):
+            try:
+                sel.unregister(sock)
+            except Exception:  # noqa: BLE001
+                pass
+            if sock is not winner:
+                sock.close()
+        sel.close()
+
+    if winner is not None:
+        winner.setblocking(True)
+        winner.settimeout(resolved_timeout)
+        return winner
+
+    if not exceptions:
+        exceptions.append(socket.timeout("timed out"))
+    if all_errors and _HAS_EXCEPTION_GROUP:
+        raise ExceptionGroup("create_connection failed", exceptions)  # novermin
+    # Like the stdlib, the last address in resolver order decides the error:
+    # hf_tcp_reachable reads ECONNREFUSED as "the endpoint answered".
+    raise failed.get(infos[-1][4]) or socket.timeout("timed out")
+
+
+def activate_happy_eyeballs() -> bool:
+    """Idempotently install the connector process-wide; True when active."""
+    global _activated
+    if _activated:
+        return True
+    if not happy_eyeballs_enabled():
+        return False
+    try:
+        socket.create_connection = happy_eyeballs_connection

P1 Badge Cover the Python 3.9 Hub transport

On supported Python 3.9 installations, pyproject.toml pins huggingface-hub==0.36.2, whose synchronous Hub calls use requests/urllib3; as the new module's own docstring notes, urllib3 performs its own address walk and never calls this patched function. Consequently token validation and Hub downloads on Python 3.9 still serialize across black-holed IPv6 addresses and can retain the startup stall this change is intended to prevent, so this needs an urllib3-compatible hook or another fallback for that supported runtime.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Studio never runs on 3.9: the backend floor is 3.10 (studio-backend-ci.yml PYTHON_FLOOR, 'because 3.9 is not true today') and install.sh provisions 3.12/3.13, so the 0.36.2 requests-based hub pin is not on a Studio runtime. urllib3's own connect loop stays out of scope by design, as the module docstring states.

chatgpt-codex-connector[bot] on studio/backend/utils/happy_eyeballs.py (on the mirror)

@@ -0,0 +1,219 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""RFC 8305 Happy Eyeballs for sync connects.
+
+``socket.create_connection`` applies ``timeout`` per resolved address, so a black-holed
+family (VPN without IPv6) costs one timeout per address (python/cpython#88810). httpx's
+sync backend and ``http.client`` call it; ``requests`` does not (urllib3 2.x has its own
+loop). Spawned children must re-activate, like :mod:`utils.native_tls`.
+"""
+
+from __future__ import annotations
+
+import errno
+import logging
+import os
+import selectors
+import socket
+import sys
+import time
+
+_ENV = "UNSLOTH_STUDIO_HAPPY_EYEBALLS"
+_DELAY_ENV = "UNSLOTH_STUDIO_HAPPY_EYEBALLS_DELAY"
+_FALSEY = ("0", "false", "no", "off")
+
+# Connection Attempt Delay, RFC 8305 section 5.
+_DEFAULT_DELAY = 0.25
+
+_IN_FLIGHT = frozenset({errno.EINPROGRESS, errno.EWOULDBLOCK, errno.EALREADY})
+_HAS_EXCEPTION_GROUP = sys.version_info >= (3, 11)
+
+_logger = logging.getLogger(__name__)
+_original_create_connection = socket.create_connection
+_activated = False
+
+
+def happy_eyeballs_enabled() -> bool:
+    return os.environ.get(_ENV, "").strip().lower() not in _FALSEY
+
+
+def attempt_delay() -> float:
+    try:
+        value = float(os.environ.get(_DELAY_ENV, "").strip() or _DEFAULT_DELAY)
+    except ValueError:
+        return _DEFAULT_DELAY
+    return max(0.0, value)
+
+
+def _interleave(infos: list) -> list:
+    """Round-robin across families, resolver order kept within each."""
+    by_family: dict = {}
+    for info in infos:
+        by_family.setdefault(info[0], []).append(info)
+    queues = list(by_family.values())
+    ordered = []
+    for i in range(max((len(q) for q in queues), default = 0)):
+        for q in queues:
+            if i < len(q):
+                ordered.append(q[i])
+    return ordered
+
+
+def happy_eyeballs_connection(
+    address,
+    timeout = socket._GLOBAL_DEFAULT_TIMEOUT,
+    source_address = None,
+    *,
+    all_errors = False,
+):
+    """Drop-in ``socket.create_connection``: attempts overlap, each with the whole ``timeout``."""
+    host, port = address
+    if timeout is socket._GLOBAL_DEFAULT_TIMEOUT:
+        resolved_timeout = socket.getdefaulttimeout()
+    else:
+        resolved_timeout = timeout
+
+    infos = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
+    # A fixed source port can only be bound by one socket at a time, so it cannot race.
+    if len(infos) <= 1 or (source_address and source_address[1]):
+        if _HAS_EXCEPTION_GROUP:
+            return _original_create_connection(  # novermin

P2 Badge Reuse the first single-address resolution

When the first getaddrinfo() call returns one address, this branch delegates to _original_create_connection, which resolves the hostname a second time. For an IPv4-only host with transient or rotating DNS, the second lookup can fail or return a black-holed set even though the first lookup produced a usable endpoint; it also doubles uncached DNS latency for every such connection. Connect using the already-resolved entry instead of invoking the resolver again.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Fixed in ab1fa86: the single-address and fixed-source-port paths now walk the already-resolved entries with the stdlib's loop instead of calling create_connection again; one lookup per connect, covered by test_a_single_address_resolves_once_and_keeps_the_callers_timeout.

Round 3: reviewed mirror 2c82d27fd (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/tests/test_happy_eyeballs.py (on the mirror)

@@ -0,0 +1,448 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""A black-holed address family must cost one stagger, not one timeout per address.
+
+100::/64 is the RFC 6666 discard prefix; on a host with no IPv6 route it is refused
+outright, so ordering cases script the socket instead.
+"""
+
+from __future__ import annotations
+
+import ast
+import errno
+import selectors
+import socket
+import sys
+import threading
+import time
+from pathlib import Path
+
+import pytest
+
+from utils import happy_eyeballs as he
+
+_TESTS_DIR = str(Path(__file__).resolve().parent)
+if _TESTS_DIR not in sys.path:
+    sys.path.insert(0, _TESTS_DIR)
+
+from test_native_tls_entrypoints import _ENTRYPOINTS as _NATIVE_TLS_ENTRYPOINTS  # noqa: E402
+
+# Activate inside a spawned child function or inline script, so the native TLS guard does not list them.
+_EXTRA_ENTRYPOINTS = (
+    "core/training/diffusion_training_service.py",
+    "utils/models/model_config.py",
+)
+
+
+DISCARD = [f"100::{i + 1}" for i in range(8)]
+
+
+@pytest.fixture
+def listener():
+    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+    srv.bind(("127.0.0.1", 0))
+    srv.listen(32)
+    accepted = []
+
+    def _accept():
+        while True:
+            try:
+                accepted.append(srv.accept()[0])
+            except OSError:
+                return
+
+    threading.Thread(target = _accept, daemon = True).start()
+    yield srv.getsockname()[1]
+    srv.close()
+    for sock in accepted:
+        sock.close()
+
+
+def _resolver(
+    port,
+    *,
+    aaaa = 8,
+    with_a = True,
+):
+    def _getaddrinfo(
+        host,
+        _port,
+        family = 0,
+        type = 0,
+        proto = 0,
+        flags = 0,
+    ):
+        infos = [
+            (socket.AF_INET6, socket.SOCK_STREAM, 6, "", (addr, port, 0, 0))
+            for addr in DISCARD[:aaaa]
+        ]
+        if with_a:
+            infos.append((socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port)))
+        return infos
+
+    return _getaddrinfo
+
+
+def test_families_are_interleaved_not_walked_in_resolver_order():
+    infos = [
+        (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("100::1", 443, 0, 0)),
+        (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("100::2", 443, 0, 0)),
+        (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("100::3", 443, 0, 0)),
+        (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("1.2.3.4", 443)),
+        (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("5.6.7.8", 443)),
+    ]
+    assert [i[4][0] for i in he._interleave(infos)] == [
+        "100::1",
+        "1.2.3.4",
+        "100::2",
+        "5.6.7.8",
+        "100::3",
+    ], "the second family must get a turn before the first family is exhausted"
+
+
+def test_eight_black_holed_aaaa_cost_one_stagger(listener, monkeypatch):
+    monkeypatch.setattr(socket, "getaddrinfo", _resolver(listener))
+
+    start = time.monotonic()
+    sock = he.happy_eyeballs_connection(("hub.invalid", listener), 10)
+    elapsed = time.monotonic() - start
+    try:
+        assert sock.getpeername()[0] == "127.0.0.1"
+    finally:
+        sock.close()
+
+    # The stdlib pays 8 x 10s.
+    assert elapsed < 3.0, f"took {elapsed:.1f}s; the AAAA records were walked in order"
+
+
+def test_the_whole_walk_costs_one_timeout_plus_staggers_not_one_timeout_each(monkeypatch):
+    monkeypatch.setattr(socket, "getaddrinfo", _resolver(443, aaaa = 6, with_a = False))
+
+    start = time.monotonic()
+    with pytest.raises(OSError):
+        he.happy_eyeballs_connection(("hub.invalid", 443), 3)
+    elapsed = time.monotonic() - start
+
+    # 3s + five staggers = 4.25s; the stdlib pays 18s.
+    assert (
+        elapsed < 6.0
+    ), f"took {elapsed:.1f}s for a 3s budget; the timeout is still applied per address"
+
+
+def test_a_reachable_address_late_in_the_list_is_still_dialled(monkeypatch):
+    """Every attempt keeps the whole timeout, so a live address opened past
+    ``timeout / delay`` staggers is still dialled, as the stdlib would."""
+    monkeypatch.setenv(he._DELAY_ENV, "0.05")
+    good = "127.0.0.1"
+    dialled = []
+
+    class _Stub:
+        def __init__(self, family, *_args, **_kwargs):
+            self.family = family
+            self.peer = None
+
+        def setblocking(self, _flag):
+            pass
+
+        def settimeout(self, _value):
+            pass
+
+        def connect_ex(self, sa):
+            dialled.append(sa[0])
+            self.peer = sa[0]
+            return 0 if sa[0] == good else errno.EINPROGRESS
+
+        def close(self):
+            pass
+
+    class _NeverReady:
+        def register(self, *_args, **_kwargs):
+            pass
+
+        def unregister(self, *_args, **_kwargs):
+            pass
+
+        def select(self, timeout):
+            if timeout:
+                time.sleep(timeout + 0.03)  # a loaded runner oversleeps every stagger
+            return []
+
+        def close(self):
+            pass
+
+    # TEST-NET-1 black holes; the live address is ninth, due 0.4s in.
+    monkeypatch.setattr(
+        socket,
+        "getaddrinfo",
+        lambda *a, **k: [
+            (socket.AF_INET, socket.SOCK_STREAM, 6, "", (f"192.0.2.{i + 1}", 443)) for i in range(8)
+        ]
+        + [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (good, 443))],
+    )
+    monkeypatch.setattr(socket, "socket", _Stub)
+    monkeypatch.setattr(selectors, "DefaultSelector", _NeverReady)
+
+    sock = he.happy_eyeballs_connection(("hub.invalid", 443), 0.2)
+
+    assert good in dialled, (
+        "the only live address was never dialled; the stdlib would have reached it with "
+        "a whole timeout of its own"
+    )
+    assert sock.peer == good, "the race returned a black hole instead of the winner"
+
+
+def test_a_single_address_resolves_once_and_keeps_the_callers_timeout(listener, monkeypatch):
+    lookups = []
+
+    def _one(*a, **k):
+        lookups.append(a[0])
+        return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", listener))]
+
+    monkeypatch.setattr(socket, "getaddrinfo", _one)
+    sock = he.happy_eyeballs_connection(("one.invalid", listener), 5)
+    try:
+        assert sock.gettimeout() == 5
+    finally:
+        sock.close()
+    assert lookups == ["one.invalid"], "the host was resolved more than once"
+
+
+def test_a_refused_port_still_raises_immediately(monkeypatch):
+    """Racing must not turn a fast, definite failure into a wait for the deadline."""
+    monkeypatch.setattr(
+        socket,
+        "getaddrinfo",
+        lambda *a, **k: [
+            (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 1)),
+            (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::1", 1, 0, 0)),
+        ],
+    )
+
+    start = time.monotonic()
+    with pytest.raises(OSError) as excinfo:
+        he.happy_eyeballs_connection(("refused.invalid", 1), 30)
+    elapsed = time.monotonic() - start
+
+    # Windows retries a reset SYN for ~2s; the stdlib pays that per address too.
+    assert elapsed < 10.0, f"a refused connect waited {elapsed:.1f}s instead of failing"
+    assert excinfo.value.errno in (errno.ECONNREFUSED, errno.EADDRNOTAVAIL)
+
+
+def test_the_last_failure_is_raised_not_the_first(monkeypatch):
+    """hf_tcp_reachable reads ECONNREFUSED as "the Hub answered"."""
+    scripted = {"100::1": errno.ENETUNREACH, "127.0.0.1": errno.ECONNREFUSED}
+
+    class _Stub:
+        def __init__(self, family, *_args, **_kwargs):
+            self.family = family
+
+        def setblocking(self, _flag):
+            pass
+
+        def connect_ex(self, sa):
+            return scripted[sa[0]]
+
+        def close(self):
+            pass
+
+    monkeypatch.setattr(
+        socket,
+        "getaddrinfo",
+        lambda *a, **k: [
+            (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("100::1", 443, 0, 0)),
+            (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443)),
+        ],
+    )
+    monkeypatch.setattr(socket, "socket", _Stub)
+
+    with pytest.raises(OSError) as excinfo:
+        he.happy_eyeballs_connection(("hub.invalid", 443), 5)
+
+    assert excinfo.value.errno == errno.ECONNREFUSED, (
+        "raised the first family's failure instead of the last; hf_tcp_reachable reads "
+        "that as an unreachable Hub"
+    )
+
+
+def test_a_deadline_reached_with_attempts_in_flight_raises_a_timeout(monkeypatch):
+    class _Stub:
+        def __init__(self, family, *_args, **_kwargs):
+            self.family = family
+
+        def setblocking(self, _flag):
+            pass
+
+        def connect_ex(self, sa):
+            return errno.ECONNREFUSED if sa[0] == "127.0.0.1" else errno.EINPROGRESS
+
+        def close(self):
+            pass
+
+    class _NeverReady:
+        def register(self, *_args, **_kwargs):
+            pass
+
+        def unregister(self, *_args, **_kwargs):
+            pass
+
+        def select(self, timeout):
+            if timeout:
+                time.sleep(min(timeout, 0.05))
+            return []
+
+        def close(self):
+            pass
+
+    monkeypatch.setattr(
+        socket,
+        "getaddrinfo",
+        lambda *a, **k: [
+            (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 443)),
+            (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("100::1", 443, 0, 0)),
+        ],
+    )
+    monkeypatch.setattr(socket, "socket", _Stub)
+    monkeypatch.setattr(selectors, "DefaultSelector", _NeverReady)
+
+    with pytest.raises(socket.timeout):
+        he.happy_eyeballs_connection(("hub.invalid", 443), 0.3)
+
+
+def _mixed_list_connector(monkeypatch, order):
+    """What the connector raises for "hole" (never answers) and "refused" in *order*."""
+    monkeypatch.setenv(he._DELAY_ENV, "0.05")
+    addr = {"hole": ("192.0.2.1", 443), "refused": ("127.0.0.1", 1)}
+
+    class _Stub:
+        def __init__(self, family, *_args, **_kwargs):
+            self.family = family
+
+        def setblocking(self, _flag):
+            pass
+
+        def connect_ex(self, sa):
+            return errno.ECONNREFUSED if sa == addr["refused"] else errno.EINPROGRESS
+
+        def close(self):
+            pass
+
+    class _NeverReady:
+        def register(self, *_args, **_kwargs):
+            pass
+
+        def unregister(self, *_args, **_kwargs):
+            pass
+
+        def select(self, timeout):
+            if timeout:
+                time.sleep(timeout)
+            return []
+
+        def close(self):
+            pass
+
+    monkeypatch.setattr(
+        socket,
+        "getaddrinfo",
+        lambda *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", addr[k]) for k in order],
+    )
+    monkeypatch.setattr(socket, "socket", _Stub)
+    monkeypatch.setattr(selectors, "DefaultSelector", _NeverReady)
+
+    with pytest.raises(OSError) as excinfo:
+        he.happy_eyeballs_connection(("hub.invalid", 443), 0.2)
+    return excinfo.value
+
+
+def test_a_black_hole_then_a_refused_address_raises_refused_as_the_stdlib_does(monkeypatch):
+    exc = _mixed_list_connector(monkeypatch, ("hole", "refused"))
+    assert isinstance(
+        exc, ConnectionRefusedError
+    ), f"raised {type(exc).__name__}; the stdlib raises the last address's refusal"
+
+
+def test_a_refused_address_then_a_black_hole_raises_a_timeout_as_the_stdlib_does(monkeypatch):
+    exc = _mixed_list_connector(monkeypatch, ("refused", "hole"))
+    assert isinstance(
+        exc, socket.timeout
+    ), f"raised {type(exc).__name__}; the stdlib raises the last address's timeout"
+
+
+def test_the_winning_socket_is_blocking_with_the_callers_timeout(listener, monkeypatch):
+    monkeypatch.setattr(socket, "getaddrinfo", _resolver(listener, aaaa = 2))
+
+    sock = he.happy_eyeballs_connection(("hub.invalid", listener), 7)
+    try:
+        assert sock.gettimeout() == 7
+    finally:
+        sock.close()
+
+
+def test_the_env_switch_turns_it_off(monkeypatch):
+    monkeypatch.setenv(he._ENV, "0")
+    assert he.happy_eyeballs_enabled() is False
+    monkeypatch.setenv(he._ENV, "1")
+    assert he.happy_eyeballs_enabled() is True
+    monkeypatch.delenv(he._ENV, raising = False)
+    assert he.happy_eyeballs_enabled() is True, "it must be on by default"
+
+
+def test_activation_installs_the_connector_and_is_idempotent(monkeypatch):
+    monkeypatch.setattr(he, "_activated", False)
+    monkeypatch.setattr(socket, "create_connection", he._original_create_connection)
+
+    assert he.activate_happy_eyeballs() is True
+    assert socket.create_connection is he.happy_eyeballs_connection
+    assert he.activate_happy_eyeballs() is True
+
+
+def test_every_network_entry_point_activates_it():
+    import pathlib
+    backend = pathlib.Path(he.__file__).resolve().parent.parent
+    for rel in tuple(_NATIVE_TLS_ENTRYPOINTS) + _EXTRA_ENTRYPOINTS:

P2 Badge Activate Happy Eyeballs in standalone prebuilt installers

This coverage list omits studio/prebuilt_core.py, although utils/prebuilt/update_flow.py launches its installer consumers in fresh Python processes and prebuilt_core.download_bytes() performs urllib.request downloads with timeouts as large as 120 seconds. Those children do not inherit the parent's socket.create_connection assignment, so on the black-holed-IPv6 setup addressed by this change, native-engine resolution, installation, and updates still walk each AAAA record sequentially and can stall for many minutes. Add activation to the standalone installer path and include it in this entry-point guard.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Same scope call as before: prebuilt_core.py is the vendored standalone installer/updater bootstrap shared with install.sh and install.ps1, so a socket patch there is an installer change with its own release-safety review. This PR stays on the backend's sync HTTP clients.

Round 4: reviewed mirror 2c82d27fd (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 2c82d27fd7

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 2c82d27fd (no equivalent commit found on this PR).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 5, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Oct 5, 2026
danielhanchen added a commit that referenced this pull request Oct 5, 2026
…e/status (#10830)

* Studio: resolve trust_remote_code off the event loop in /api/inference/status

The frontend polls this route continuously, and its auto_map fallback reads raw
config JSON from the Hub. Run inline on the loop, one unreachable address family
parked the whole server -- /api/liveness with it -- and the desktop watchdog
SIGTERMs a backend that misses three 15s probes, surfaced to the user as "Server
stopped unexpectedly" with terminal_reason=unresponsive_health_check. The process
was alive and healthy the entire time.

socket.create_connection applies its timeout to EACH getaddrinfo result rather
than to the connect as a whole, so a host whose network black-holes AAAA pays it
once per record before the first A is tried. huggingface.co answers with eight
AAAA, so a status poll parked the loop for ~80s on a VPN carrying no IPv6.
Measured against the real app with the RFC 6666 discard prefix standing in for
the VPN: 30s of dead loop on only three black-holed records, with /api/liveness
failing outright rather than merely slowing.

validate_model and the transformers upgrade check already wrap this same read in
asyncio.to_thread + _offline_guarded; get_status was the only one of the three
callers that did not. Use the same pattern here. Also skip the read entirely when
no model is loaded: it previously walked the auto_map fallback with an empty
identifier and paid for it.

The offline guard matters as much as the offload. It bounds the read to the
memoised reachability verdict instead of the per-address connect budget, taking
the route from ~80s to ~4s against an unreachable Hub, on top of no longer
blocking anything else.

The docstring on _resolve_loaded_trust_remote_code claimed this fallback "reads
the loaded model's cached config; no network". It does not -- on a cache miss
_load_remote_code_configs calls hf_hub_download -- and that assumption is why the
call was left on the loop. Corrected here.

Tests: three new, asserting which thread the read runs on and that it goes
through the guard, in the style of the sibling off-event-loop guards. All three
fail on the pre-fix tree.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

* Studio: snapshot the active model across the trust_remote_code await

Moving the trust_remote_code read off the event loop put a suspension point
between reading the active model and building the response, where there had not
been one: get_status had exactly one await before this branch, and it ran before
model_info was read.

model_info, inference_config, the safetensors capability flags and the resolved
trust requirement are all derived from backend.active_model_name before that
await. The response then read backend.active_model_name and
backend.models.keys() again. A load or unload completing while the read was off
on its worker thread therefore published the new model's identity carrying the
previous model's capabilities and trust requirement, and the frontend hydrates
its runtime state from exactly those fields. requires_trust_remote_code being
the wrong one of the two is the part worth avoiding.

The window is as long as the Hub read takes, which on the black-holed link this
branch is about is seconds rather than microseconds, and status is polled
continuously, so this is a race with a real chance of being lost.

Snapshot the identifier once, before the await, and build the response from the
snapshot. `loaded` stays live: it answers "what is resident", not "what is this
response about".

Tests: one new, swapping the backend's active model from inside the resolve and
asserting the response does not mix the two. It fails on the unfixed route.

Reported by Codex on #10803.

* Studio: answer /api/inference/status trust_remote_code from the stored value inline

Three problems with the offload, all in the polled status route.

The whole resolver went through _offline_guarded, and the guard probes Hub
reachability on entry, before the wrapped function runs. The normal load path
stores requires_trust_remote_code on the model, so reporting it back is a dict
read. That read was paying a reachability probe every time the 5s memo expired,
up to 3s on a cold verdict, and a default-executor thread each time, for a
value already in memory.

The fallback ran through asyncio.to_thread, on the default executor. That pool
drives local token streaming, and this route already keeps its llama.cpp probe
on _STATUS_PROBE_EXECUTOR for exactly that reason. Enough overlapping polls on a
slow Hub could starve generation while the loop itself stayed responsive.

The snapshot covered active_model but not loaded, which was still read after
the await. The race test's own mutation produced active_model="Qwen3-8B" with
loaded=["Llama-3.1-8B"]: a response whose active model is missing from its own
resident list.

The resolver is split so the route can use the halves separately.
_stored_trust_remote_code is the no-network part of the order (stored at load,
the value the load used, the YAML default) and returns None when only the raw
auto_map check can answer. _auto_map_trust_remote_code is that check.
_resolve_loaded_trust_remote_code composes the two and is unchanged for its
other callers. get_status reads the stored part inline, and only on None goes
to _STATUS_PROBE_EXECUTOR, under the guard, for the auto_map fallback. loaded
joins the snapshot.

Tests: one new, and the race test now asserts loaded. The off-loop test asserts
the executor by thread name. Each of the three was reverted alone against the
suite, and each failed its own test.

Reported by Codex on #10830.

* Update is_local_model contract test to the status snapshot spelling

---------

Co-authored-by: Daniel Han <[email protected]>
@danielhanchen
danielhanchen merged commit 954bf81 into unslothai:main Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants