Repository navigation
Studio: resolve trust_remote_code off the event loop in /api/inference/status - #10830
danielhanchen merged 6 commits into
Conversation
…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.
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.
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.
…d 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 unslothai#10830.
|
Confirmed the inline resolve is still there in studio/backend/routes/inference.py, and the auto_map fallback can reach the Hub from the event loop, and the follow-ups on the snapshot and the guard fast path look addressed in 54c747c. Will get this reviewed. |
|
Review record for #10830, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#441. 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
|
…ls) (#10803) * 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. * Studio: race address families on sync connects (RFC 8305 Happy Eyeballs) 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. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Studio: keep the happy eyeballs connector under the 3.10 backend floor 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. * Studio: raise the last connect failure, the way create_connection does 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 #10803. * Studio: activate happy eyeballs in the download and export workers too 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 #10803. * Studio: say plainly that requests does not go through the patched connector 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 #10803. * 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: give every attempt the whole timeout, the way create_connection 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 #10803. * Studio: move the trust_remote_code offload out of this branch 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 #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. * Studio: raise for the last address in resolver order, exactly as create_connection does Checking error-type parity against the stdlib for the reachable-Hub question on #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 #10803. * Studio: trim happy eyeballs comments * Studio: activate happy eyeballs in the transformers 5 config probe subprocess * Studio: activate happy eyeballs in the AutoConfig tier probe child * Studio: give each happy eyeballs attempt its own deadline * Studio: do not race attempts that bind a fixed source port * Studio: walk already-resolved addresses instead of resolving twice --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Daniel Han <[email protected]>
Split out of #10803.
GET /api/inference/statusisasync defand called_resolve_loaded_trust_remote_codeinline. Itsauto_mapfallback can reach the Hub (_config_has_auto_map→_load_remote_code_configs→hf_hub_downloadon a cache miss), although its docstring says it does no network. On a link that black-holes IPv6, one status poll parked the event loop for the full address walk./api/livenessstopped with it, and the watchdog sent SIGTERM after three misses.validate_modeland the transformers upgrade check already wrap the same read inasyncio.to_thread(_offline_guarded, ...). This does the same forget_status, skips the read when no model is loaded, and fixes the docstring.The second commit reads
backend.active_model_nameonce, before the await. The offload added a suspension point, and a load or unload that finished inside it paired one model's name with another model's capabilities.GET /api/inference/status, three black-holed records/api/livenessduring that poll