Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Offline: detect an unreachable hub, not just dead DNS (#7591)
Michael Han3c400a67ba8f
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 974cf0ba480..8a28ae3bf29 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -532,23 +532,17 @@ _SWA_CACHE: Optional[dict] = None_SWA_CACHE_LOCK = threading.Lock()-def _probe_dns_dead(host: str = "huggingface.co", timeout: float = 2.0) -> bool:- """Quick DNS check on a daemon thread, so concurrent sockets aren't- affected by socket.setdefaulttimeout."""- result: list[Optional[bool]] = [None]+def _hf_endpoint_host() -> str:+ """Host of the configured hub endpoint (HF_ENDPOINT aware)."""+ from utils.utils import hf_endpoint_host+ return hf_endpoint_host()- def _probe() -> None:- try:- socket.gethostbyname(host)- result[0] = False- except Exception:- result[0] = True- t = threading.Thread(target = _probe, daemon = True)- t.start()- t.join(timeout)- # Thread still running -> resolver wedged -> dead.- return True if result[0] is None else result[0]+def _probe_dns_dead(host: Optional[str] = None, timeout: float = 2.0) -> bool:+ """Quick DNS check on a daemon thread, so concurrent sockets aren't+ affected by socket.setdefaulttimeout. Defaults to the configured endpoint's host."""+ from utils.utils import dns_host_dead, hf_endpoint_host+ return dns_host_dead(host or hf_endpoint_host(), timeout)def _hf_env_offline() -> bool:@@ -564,29 +558,78 @@ def _hf_env_offline() -> bool:return os.environ.get("HF_HUB_OFFLINE", "").strip().lower() in {"1", "true", "yes", "on"}+def _hf_unreachable() -> bool:+ """True when the Hub can't be reached: dead DNS, or DNS that resolves with no egress.++ DNS alone misses the common shapes (WAN down behind a live router, captive portal,+ stale cache), leaving every hub call to burn its retry backoff. The DNS shortcut stands+ down when a proxy is configured, since the proxy resolves the host.+ """+ try:+ from utils.utils import hf_dns_dead, hf_reachability_memo, hf_unreachable+ except Exception:+ return False+ # A fresh verdict already answers this. One request opens several guards, and the DNS+ # shortcut is only cheap when DNS is fast: a slow resolver costs its full timeout per+ # guard and leaves a stuck thread behind each time. Peek only, never record: a dead+ # lookup fails fast anyway, and recording it would make recovery sticky for the TTL.+ memo = hf_reachability_memo()+ if memo is not None:+ return memo+ if hf_dns_dead():+ return True+ return hf_unreachable()++@contextlib.contextmanager-def _hf_offline_if_dns_dead():- """Set HF_HUB_OFFLINE for this block only when DNS to huggingface.co fails;- restores env on exit so a transient hiccup can't quarantine the process.- No-op if the user already set it."""- if "HF_HUB_OFFLINE" in os.environ:+def _hf_offline_if_unreachable():+ """Force HF offline for this block only when the Hub is unreachable; restores on exit+ so a transient hiccup can't quarantine the process. No-op if the USER set the env var.++ Env vars alone are too late mid-process (the offline constants are read at import), so+ this holds a refcounted force_hf_offline window. Overlapping requests each take their+ own reference: no-opping would let another guard's exit restore the network+ mid-operation and drop this request back onto the retry path.+ """+ try:+ from utils.utils import force_hf_offline, force_hf_offline_state, hf_env_offline+ except Exception:yield Falsereturn- if not _probe_dns_dead():++ ours, hf_hub_env_present = force_hf_offline_state()+ # Membership preserves HF_HUB_OFFLINE=0 as an explicit stay-online override.+ # Read it with the refcount so a concurrent guard cannot look user-owned.+ if hf_hub_env_present and not ours:+ yield False+ return+ # TRANSFORMERS_OFFLINE alone still asks for offline, and the hub does not read it.+ # Honour it directly: probing would put network traffic in an explicitly offline process.+ if not ours and hf_env_offline():+ with force_hf_offline():+ yield True+ return+ # Already forced by an in-flight guard: reuse that verdict and hold a reference.+ if not ours and not _hf_unreachable():yield Falsereturn- transformers_was_set = "TRANSFORMERS_OFFLINE" in os.environ- os.environ["HF_HUB_OFFLINE"] = "1"- if not transformers_was_set:- os.environ["TRANSFORMERS_OFFLINE"] = "1"- logger.warning("huggingface.co unreachable; using local HF cache for this load.")- try:+ if not ours:+ logger.warning("Hugging Face endpoint unreachable; using local HF cache for this load.")+ with force_hf_offline():yield True- finally:- os.environ.pop("HF_HUB_OFFLINE", None)- if not transformers_was_set:- os.environ.pop("TRANSFORMERS_OFFLINE", None)+++def _hf_offline_if_unreachable_for(model_name):+ """Guard, but only for remote repo ids: a local path is served from disk and never+ reaches the hub, so probing would add seconds per request and prevent no retry."""+ try:+ from utils.paths import is_local_path+ if isinstance(model_name, str) and is_local_path(model_name):+ return contextlib.nullcontext()+ except Exception:+ pass+ return _hf_offline_if_unreachable()try:@@ -7067,7 +7110,7 @@ class LlamaCppBackend:hf_repo,)hf_repo = _resolved_repo- with _hf_offline_if_dns_dead():+ with _hf_offline_if_unreachable():_preflight_model_path = self._download_gguf(hf_repo = hf_repo,hf_variant = hf_variant,@@ -7121,7 +7164,7 @@ class LlamaCppBackend:hf_repo,)hf_repo = _resolved_repo- with _hf_offline_if_dns_dead():+ with _hf_offline_if_unreachable():model_path = _preflight_model_path or self._download_gguf(hf_repo = hf_repo,hf_variant = hf_variant,diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex f2081833007..e0d66c5f48d 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -40,6 +40,43 @@ def _ensure_backend_on_path() -> None:sys.path.insert(0, _BACKEND_PATH)+def _recorded_local_base(model_name) -> "tuple[str | None, bool]":+ """``(base, needs_hub)`` for the base this checkpoint records on disk.++ Delegates to the resolver's own disk reads so the gate cannot drift from what+ activation later resolves. Fail closed: an unavailable reader counts as needing the+ Hub, since skipping a needed probe costs the retry backoff the probe exists to avoid.+ """+ try:+ _ensure_backend_on_path()+ from utils.transformers_version import recorded_local_base+ return recorded_local_base(model_name)+ except Exception:+ return None, True+++def _hub_targets_are_local(*targets) -> bool:+ """True when every non-empty target is a local path, so nothing here needs the Hub.++ Fail closed: an unresolvable target, or an unavailable is_local_path, counts as remote,+ since skipping a needed probe costs the retry backoff it exists to avoid.+ """+ try:+ _ensure_backend_on_path()+ from utils.paths import is_local_path+ except Exception:+ return False+ for target in targets:+ if not target:+ continue+ try:+ if not (isinstance(target, str) and is_local_path(target)):+ return False+ except Exception:+ return False+ return True++def _activate_transformers_version(model_name: str, hf_token: str | None = None) -> None:"""Activate the correct transformers version BEFORE any ML imports."""_ensure_backend_on_path()@@ -783,6 +820,46 @@ def run_inference_process(os.environ["HF_HUB_DISABLE_XET"] = "1"logger.info("Xet transport disabled (HF_HUB_DISABLE_XET=1)")+ # Offline auto-detect, as the training and export workers already do. The parent's+ # guard is scoped, so child_env deliberately scrubs it rather than turning a+ # per-request flag into a lifetime one; without a probe of its own this worker would+ # then walk back into the retry paths the parent already ruled out, in+ # _remote_lora_base and in tier activation below. Runs before any HF import, so env+ # alone is enough.+ # Skip it entirely for a filesystem-only load: a local checkpoint whose recorded base+ # (an adapter's, or a full checkpoint's config.json one, both of which activation+ # resolves and reads Hub metadata for) is local too never reaches the Hub, so probing+ # would spend seconds before a load that has no Hub dependency.+ _probe_model = config["model_name"]+ _probe_base, _probe_needs_hub = _recorded_local_base(_probe_model)+ if "HF_HUB_OFFLINE" not in os.environ and (+ _probe_needs_hub or not _hub_targets_are_local(_probe_model, _probe_base)+ ):+ try:+ _ensure_backend_on_path()+ from utils.utils import hf_dns_dead, hf_env_offline, hf_probe_disabled++ _offline = hf_env_offline()+ if not _offline:+ _offline = hf_dns_dead()+ if not _offline and not hf_probe_disabled():+ from utils.transformers_version import hf_endpoint_unreachable++ # Lifetime flags, so only a definite no-egress answer counts: a momentary+ # 502 or a slow proxy must not strand the worker offline.+ _offline = hf_endpoint_unreachable(+ gateway_errors_offline = False,+ proxy_timeouts_offline = False,+ )+ if _offline:+ os.environ["HF_HUB_OFFLINE"] = "1"+ os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")+ logger.warning(+ "Hugging Face endpoint unreachable; HF_HUB_OFFLINE=1 for this worker."+ )+ except Exception:+ pass # fail open: the load decides as it does today+import warningsfrom loggers.config import LogConfigdiff --git a/studio/backend/core/training/trainer.py b/studio/backend/core/training/trainer.pyindex 661507423c7..df3b5ed65c3 100644--- a/studio/backend/core/training/trainer.py+++ b/studio/backend/core/training/trainer.py@@ -68,7 +68,6 @@ import pandas as pdfrom datasets import Datasetfrom utils.datasets.cache_safe import load_dataset_cache_safe as load_dataset-from core.inference.llama_cpp import _hf_offline_if_dns_deadfrom utils.models import is_vision_model, detect_audio_typefrom utils.models.model_config import _env_offlinefrom utils.datasets import format_and_template_datasetdiff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex 74e7d13000f..169fec81eb3 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -2330,6 +2330,46 @@ def run_mlx_training_process()+def _training_job_is_local(config) -> bool:+ """True when neither the model nor the dataset needs the Hub, so the probe is wasted.++ Fail closed: anything unresolvable counts as remote, since skipping a needed probe+ costs the retry backoff the probe exists to avoid.+ """+ try:+ from utils.paths import is_local_path+ except Exception:+ return False+ if config.get("hf_dataset"):+ return False+ model = config.get("model_name")+ try:+ if not (model and is_local_path(model)):+ return False+ # A local checkpoint can name a remote base, which activation resolves and later+ # training and security code fetches. Readable from disk, so no network needed+ # to decide. Matches the inference worker's gate.+ base, needs_hub = _recorded_local_base(model)+ if needs_hub:+ return False+ return not base or is_local_path(base)+ except Exception:+ return False+++def _recorded_local_base(model_name) -> "tuple[str | None, bool]":+ """``(base, needs_hub)`` for the base this checkpoint records on disk.++ Delegates to the resolver's own disk reads so the gate cannot drift from what+ activation later resolves. Fail closed on an unavailable reader.+ """+ try:+ from utils.transformers_version import recorded_local_base+ return recorded_local_base(model_name)+ except Exception:+ return None, True++def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) -> None:"""Subprocess entrypoint. Fresh Python — no stale module state.@@ -2358,31 +2398,44 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->flush = True,)- # Offline auto-detect: skip ~25s of HF retries per call when DNS is dead.- if "HF_HUB_OFFLINE" not in os.environ:- import socket as _socket- import threading as _threading-- # Daemon thread so we don't mutate process-wide setdefaulttimeout.- _result: list = [None]-- def _probe() -> None:- try:- _socket.gethostbyname("huggingface.co")- _result[0] = False- except Exception:- _result[0] = True-- _t = _threading.Thread(target = _probe, daemon = True)- _t.start()- _t.join(2.0)- if _result[0] is None or _result[0] is True:+ # Offline auto-detect: skip ~25s of HF retries per call when the hub is unreachable.+ # Skipped for a filesystem-only job: a local checkpoint with a local dataset never+ # reaches the Hub, and main's check here was DNS-only and returned at once, so probing+ # unconditionally would add seconds to every such startup.+ if "HF_HUB_OFFLINE" not in os.environ and not _training_job_is_local(config):+ _offline = False+ _network_offline = False+ try:+ from utils.utils import hf_dns_dead, hf_env_offline, hf_probe_disabled++ # Hub ignores TRANSFORMERS_OFFLINE, so translate it before probing.+ _offline = hf_env_offline()+ # hf_dns_dead follows HF_ENDPOINT and stands down when a proxy is configured,+ # so a reachable mirror (or proxy-only egress) is never called offline.+ if not _offline:+ _offline = _network_offline = hf_dns_dead()+ if not _offline and not hf_probe_disabled():+ # DNS answers even without egress (WAN down, captive portal). These flags+ # last the whole job, so only a connection failure counts: a momentary+ # 502/503 must not block every download for the rest of the run.+ from utils.transformers_version import hf_endpoint_unreachable+ _offline = _network_offline = hf_endpoint_unreachable(+ gateway_errors_offline = False,+ proxy_timeouts_offline = False,+ )+ except Exception:+ _offline = _network_offline = False+ if _offline:os.environ["HF_HUB_OFFLINE"] = "1"os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")- os.environ.setdefault("HF_DATASETS_OFFLINE", "1")+ # Only when the network itself is the reason. TRANSFORMERS_OFFLINE alone asks+ # for cached model files, not for a cache-only dataset: egress may be fine,+ # and an uncached hf_dataset would then fail for the whole job.+ if _network_offline:+ os.environ.setdefault("HF_DATASETS_OFFLINE", "1")# logger isn't configured yet; print to stderr instead.print(- "huggingface.co unreachable; HF_HUB_OFFLINE=1 set for this worker.",+ "Hugging Face endpoint unreachable; HF_HUB_OFFLINE=1 set for this worker.",file = sys.stderr,flush = True,)diff --git a/studio/backend/picker/routes/templates.py b/studio/backend/picker/routes/templates.pyindex 02b8bf7184d..628cc038412 100644--- a/studio/backend/picker/routes/templates.py+++ b/studio/backend/picker/routes/templates.py@@ -37,9 +37,15 @@ async def get_default_chat_template_route(hf_token: Optional[str] = Depends(get_hf_token),current_subject: str = Depends(get_current_subject),) -> ModelTemplateResponse:- template = await asyncio.to_thread(- read_default_chat_template, model_name, hf_token, gguf_variant- )+ # Cached repos resolve from disk, but a cache miss falls through to the hub and+ # offline that costs one retry backoff per candidate template file.+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for++ def _read():+ with _hf_offline_if_unreachable_for(model_name):+ return read_default_chat_template(model_name, hf_token, gguf_variant)++ template = await asyncio.to_thread(_read)if template is not None and len(template.encode("utf-8")) > MAX_CHAT_TEMPLATE_BYTES:template = Nonereturn ModelTemplateResponse(model_name = model_name, chat_template = template)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex bcfdf5624d3..836efc4e56c 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -1009,7 +1009,8 @@ try:_extra_args_draft_device_pin,_extra_args_n_ubatch,_extra_args_set_spec_type,- _hf_offline_if_dns_dead,+ _hf_offline_if_unreachable,+ _hf_offline_if_unreachable_for,_kv_bytes_per_elem,_kv_unified_from_args,_planned_main_cache_types,@@ -1058,7 +1059,8 @@ except ImportError:_extra_args_draft_device_pin,_extra_args_n_ubatch,_extra_args_set_spec_type,- _hf_offline_if_dns_dead,+ _hf_offline_if_unreachable,+ _hf_offline_if_unreachable_for,_kv_bytes_per_elem,_kv_unified_from_args,_planned_main_cache_types,@@ -3891,6 +3893,9 @@ def _target_is_vision(load_path: str) -> bool:# paths, where the token is unused, but the rule requires it regardless).from utils.models.model_config import is_vision_modeltry:+ # Deliberately unguarded: the resolver only yields local paths, so this returns+ # from the mmproj filesystem branch without touching the hub. A reachability+ # probe here would add seconds per request and prevent nothing.return bool(is_vision_model(load_path, hf_token = os.environ.get("HF_TOKEN")))except Exception as exc:# Detection failure: don't block the swap, let the load decide.@@ -5916,14 +5921,19 @@ async def _load_model_impl(cancel_pending = on_reload_confirmed is not None and bool(request.force_cancel_active)# is_lora auto-detected from adapter_config.json on disk/HF.- # DNS-probe wrap so offline loads skip 30-60s of soft-failed network- # checks before the worker starts.- with _hf_offline_if_dns_dead():- config = ModelConfig.from_identifier(- model_id = model_identifier,- hf_token = request.hf_token,- gguf_variant = request.gguf_variant,- )+ # Probe wrap so offline loads skip 30-60s of soft-failed network checks before+ # the worker starts. Off-loop: the guard can spend seconds on DNS plus a HEAD and+ # its TCP fallback, and this handler is awaited directly by the route, so running+ # it inline would stall every unrelated request. Same shape as /validate.+ def _resolve_config():+ with _hf_offline_if_unreachable_for(model_identifier):+ return ModelConfig.from_identifier(+ model_id = model_identifier,+ hf_token = request.hf_token,+ gguf_variant = request.gguf_variant,+ )++ config = await asyncio.to_thread(_resolve_config)if not config:raise HTTPException(@@ -5982,7 +5992,13 @@ async def _load_model_impl(# to match. Off-loop: tier resolution reads configs.if effective_load_in_4bit and not config.is_gguf:from utils.transformers_version import latest_tier_active_for- if await asyncio.to_thread(latest_tier_active_for, config.identifier, request.hf_token):+ if await asyncio.to_thread(+ _offline_guarded,+ (model_identifier, config.identifier, getattr(config, "base_model", None)),+ latest_tier_active_for,+ config.identifier,+ request.hf_token,+ ):effective_load_in_4bit = Falselogger.info(f"Latest-transformers sidecar active for '{model_log_label}' - "@@ -5991,8 +6007,10 @@ async def _load_model_impl()# Apply the training coexistence policy before the unload step below- # frees the resident model. Off-loop: the default-mode guard does sync work.+ # frees the resident model. Off-loop and guarded: the guard does sync HF work.await asyncio.to_thread(+ _offline_guarded,+ (model_identifier, config.identifier, getattr(config, "base_model", None)),_guard_chat_load_against_training,config,model_identifier = model_identifier,@@ -6524,6 +6542,44 @@ async def _load_model_impl(api_monitor.fail_open(_load_event, "Load did not complete")+def _any_remote(targets) -> bool:+ """True unless every target is a local path. Falsy entries are skipped (no base to+ read); anything unresolvable counts as remote, since guarding a local read costs one+ memoised verdict while missing a remote one costs the retry backoff."""+ from utils.paths import is_local_path++ for target in (targets,) if isinstance(targets, str) else targets or ():+ if not target:+ continue # no base is not an unknown base: nothing to read, nothing to guard+ try:+ if not (isinstance(target, str) and is_local_path(target)):+ return True+ except Exception:+ return True # unresolvable: guard, since missing a remote read costs the backoff+ return False+++def _offline_guarded(targets, fn, /, *args, **kwargs):+ """Run one blocking preflight inside the same forced-offline window as config+ resolution. The config is not the only remote read here: the upgrade, trust-remote-code+ and sizing preflights each fetch raw metadata, and would otherwise burn the retry+ backoff the guard exists to skip. The verdict is memoised, so this costs no extra+ probe. Call from a worker thread: the guard is process-global and blocks on a cold+ verdict.++ ``targets`` is what this call actually READS, not the outer request, because a local+ adapter can resolve to a remote base and the base is what gets fetched. Positional-only,+ so a wrapped call's own model_identifier kwarg cannot collide."""+ from contextlib import nullcontext++ # The module-level symbol, not a fresh import: route tests patch+ # routes.inference._hf_offline_if_unreachable to stay deterministic, and a local+ # re-import would bypass the patch and run a real probe.+ ctx = _hf_offline_if_unreachable() if _any_remote(targets) else nullcontext()+ with ctx:+ return fn(*args, **kwargs)++def _requires_trust_remote_code_for_model(model_identifier: str, hf_token: Optional[str] = None) -> bool:@@ -6606,7 +6662,10 @@ async def validate_model(Checks that ModelConfig.from_identifier() can resolve model_path, but doesNOT load model weights into GPU memory."""- from core.inference.llama_cpp import LlamaServerNotFoundError+ from core.inference.llama_cpp import (+ LlamaServerNotFoundError,+ _hf_offline_if_unreachable_for,+ )native_grant_backed = Falsemodel_log_label = request.model_path@@ -6614,11 +6673,18 @@ async def validate_model(model_identifier, model_log_label, native_grant_backed = (_resolve_model_identifier_for_request(request, operation = "validate-model"))- config = ModelConfig.from_identifier(- model_id = model_identifier,- hf_token = request.hf_token,- gguf_variant = request.gguf_variant,- )++ # The frontend validates before it loads, so this needs the same guard as+ # /load; otherwise the stall just moves here and /load is never reached.+ def _resolve_config():+ with _hf_offline_if_unreachable_for(model_identifier):+ return ModelConfig.from_identifier(+ model_id = model_identifier,+ hf_token = request.hf_token,+ gguf_variant = request.gguf_variant,+ )++ config = await asyncio.to_thread(_resolve_config)if not config:raise HTTPException(@@ -6658,7 +6724,13 @@ async def validate_model(from utils.models.model_config import get_base_model_from_lora_identifier# Resolve a LOCAL or REMOTE adapter's base so its code/weights are reviewed too.- _base = get_base_model_from_lora_identifier(model_identifier, request.hf_token)+ _base = await asyncio.to_thread(+ _offline_guarded,+ model_identifier,+ get_base_model_from_lora_identifier,+ model_identifier,+ request.hf_token,+ )if _base:security_targets.append(_base)except Exception:@@ -6676,7 +6748,11 @@ async def validate_model(# Cover [adapter, base]: the worker activates transformers for the base model.for _target in security_targets:_upgrade = await asyncio.to_thread(- check_upgrade_for_model, _target, request.hf_token+ _offline_guarded,+ _target,+ check_upgrade_for_model,+ _target,+ request.hf_token,)if _upgrade is not None:transformers_upgrade = TransformersUpgradeInfo(**_upgrade)@@ -6688,9 +6764,14 @@ async def validate_model(# exactly as /load does.requires_trust_remote_code = Falseif not is_gguf:- requires_trust_remote_code = any(- _requires_trust_remote_code_for_model(_t, request.hf_token)- for _t in security_targets+ # Reads raw config/tokenizer JSON, so guarded and off-loop like the rest.+ requires_trust_remote_code = await asyncio.to_thread(+ _offline_guarded,+ security_targets,+ lambda: any(+ _requires_trust_remote_code_for_model(_t, request.hf_token)+ for _t in security_targets+ ),)# Mirror /load's latest-sidecar 16-bit flip so the guard sizes it the same way. An@@ -6709,15 +6790,21 @@ async def validate_model(and not requires_trust_remote_code)if _install_only_upgrade or await asyncio.to_thread(- latest_tier_active_for, config.identifier, request.hf_token+ _offline_guarded,+ (model_identifier, config.identifier, getattr(config, "base_model", None)),+ latest_tier_active_for,+ config.identifier,+ request.hf_token,):effective_load_in_4bit = False# A metadata-only probe reads the GGUF header and allocates no VRAM, so the# training guard must not refuse it. Real loads omit include_context_length /# include_chat_template, and /load applies the guard again.if not (request.include_context_length or request.include_chat_template):- # Off-loop: guard does sync nvidia-smi / HF work.+ # Off-loop and guarded: the guard does sync nvidia-smi / HF work.await asyncio.to_thread(+ _offline_guarded,+ (model_identifier, config.identifier, getattr(config, "base_model", None)),_guard_chat_load_against_training,config,model_identifier = model_identifier,@@ -6749,8 +6836,15 @@ async def validate_model(# already resolved above for the sizing flip).requires_security_review = Falseif not is_gguf:- requires_security_review = any(- _requires_security_review_for_model(_t, request.hf_token) for _t in security_targets+ # _fetch_security_status does hf_model_info with 10s and 20s timeouts, so this+ # needs the same window and worker thread as the preflights above.+ requires_security_review = await asyncio.to_thread(+ _offline_guarded,+ security_targets,+ lambda: any(+ _requires_security_review_for_model(_t, request.hf_token)+ for _t in security_targets+ ),)# Native context length, read from the local GGUF header when present.# Lets the staged ("Load on selection" off) flow populate the contextdiff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 6e587c18e8f..f9369d566d3 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1855,75 +1855,86 @@ async def get_model_config():"""Get configuration for a specific model (wraps load_model_defaults)."""hf_token = _normalize_hf_token(header_hf_token) or _normalize_hf_token(hf_token)- try:- if not is_local_path(model_name):- resolved = resolve_cached_repo_id_case(model_name)- if resolved != model_name:- logger.info(- "Using cached repo_id casing '%s' for requested '%s'",- resolved,- model_name,- )- model_name = resolved-- logger.info(f"Getting model config for: {model_name}")- from utils.models.model_config import detect_audio_type+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for++ def _resolve(model_name: str) -> ModelDetails:+ # Each probe below can reach the hub, so the guard wraps the whole handler:+ # offline they must all resolve from the HF cache instead of retrying. Local+ # paths stay on disk, so they skip the probe entirely.+ with _hf_offline_if_unreachable_for(model_name):+ if not is_local_path(model_name):+ resolved = resolve_cached_repo_id_case(model_name)+ if resolved != model_name:+ logger.info(+ "Using cached repo_id casing '%s' for requested '%s'",+ resolved,+ model_name,+ )+ model_name = resolved- config_dict = load_model_defaults(model_name)+ logger.info(f"Getting model config for: {model_name}")+ from utils.models.model_config import detect_audio_type- # Detect capabilities (HF token for gated models).- is_vision = is_vision_model(model_name, hf_token = hf_token)- is_embedding = is_embedding_model(model_name, hf_token = hf_token)- audio_type = detect_audio_type(model_name, hf_token = hf_token)+ config_dict = load_model_defaults(model_name)- is_lora = False- base_model = None- max_position_embeddings = None- try:- model_config = ModelConfig.from_identifier(model_name)- is_lora = model_config.is_lora- base_model = model_config.base_model if is_lora else None- max_position_embeddings = _get_max_position_embeddings(model_config)- except Exception:- pass+ # Detect capabilities (HF token for gated models).+ is_vision = is_vision_model(model_name, hf_token = hf_token)+ is_embedding = is_embedding_model(model_name, hf_token = hf_token)+ audio_type = detect_audio_type(model_name, hf_token = hf_token)- # Fallback: read raw config.json (declarative fields only) -- a selection-time- # metadata probe that must never execute a repo's auto_map Python.- if max_position_embeddings is None:+ is_lora = False+ base_model = None+ max_position_embeddings = Nonetry:- from utils.transformers_version import _load_config_json- from types import SimpleNamespace+ model_config = ModelConfig.from_identifier(model_name)+ is_lora = model_config.is_lora+ base_model = model_config.base_model if is_lora else None+ max_position_embeddings = _get_max_position_embeddings(model_config)+ except Exception:+ pass- _cfg = _load_config_json(model_name, hf_token = hf_token)- if _cfg is not None:+ # Fallback: read raw config.json (declarative fields only) -- a selection-time+ # metadata probe that must never execute a repo's auto_map Python.+ if max_position_embeddings is None:+ try:+ from utils.transformers_version import _load_config_json+ from types import SimpleNamespace- def _to_ns(d):- if isinstance(d, dict):- return SimpleNamespace(**{k: _to_ns(v) for k, v in d.items()})- return d+ _cfg = _load_config_json(model_name, hf_token = hf_token)+ if _cfg is not None:- max_position_embeddings = _get_max_position_embeddings(_to_ns(_cfg))- except Exception:- pass+ def _to_ns(d):+ if isinstance(d, dict):+ return SimpleNamespace(**{k: _to_ns(v) for k, v in d.items()})+ return d- logger.info(- f"Model config result for {model_name}: is_vision={is_vision}, is_embedding={is_embedding}, audio_type={audio_type}, is_lora={is_lora}, max_position_embeddings={max_position_embeddings}"- )- return ModelDetails(- id = model_name,- model_name = model_name,- config = config_dict,- is_vision = is_vision,- is_embedding = is_embedding,- is_lora = is_lora,- is_audio = audio_type is not None,- audio_type = audio_type,- has_audio_input = is_audio_input_type(audio_type),- model_type = derive_model_type(is_vision, audio_type, is_embedding),- base_model = base_model,- max_position_embeddings = max_position_embeddings,- model_size_bytes = _get_model_size_bytes(model_name, hf_token),- )+ max_position_embeddings = _get_max_position_embeddings(_to_ns(_cfg))+ except Exception:+ pass++ logger.info(+ f"Model config result for {model_name}: is_vision={is_vision}, is_embedding={is_embedding}, audio_type={audio_type}, is_lora={is_lora}, max_position_embeddings={max_position_embeddings}"+ )+ return ModelDetails(+ id = model_name,+ model_name = model_name,+ config = config_dict,+ is_vision = is_vision,+ is_embedding = is_embedding,+ is_lora = is_lora,+ is_audio = audio_type is not None,+ audio_type = audio_type,+ has_audio_input = is_audio_input_type(audio_type),+ model_type = derive_model_type(is_vision, audio_type, is_embedding),+ base_model = base_model,+ max_position_embeddings = max_position_embeddings,+ model_size_bytes = _get_model_size_bytes(model_name, hf_token),+ )++ try:+ # Off the loop: the guard blocks on DNS + HEAD + TCP, which stalled every+ # other request for the whole handler.+ return await asyncio.to_thread(_resolve, model_name)except Exception as e:raise log_and_http_error(@@ -2585,7 +2596,16 @@ async def check_vision_model(try:logger.info(f"Checking if vision model: {model_name}")# Authenticate so a gated/private VLM classifies correctly (else 404 -> non-vision).- is_vision = is_vision_model(model_name, hf_token = hf_token)+ # Offline the guard keeps this on the HF cache instead of retrying the hub.+ # A local path resolves from disk, so it skips the probe.+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for++ # Off the loop: the guard's probes are blocking and stall unrelated requests.+ def _check():+ with _hf_offline_if_unreachable_for(model_name):+ return is_vision_model(model_name, hf_token = hf_token)++ is_vision = await asyncio.to_thread(_check)logger.info(f"Vision check result for {model_name}: is_vision={is_vision}")return VisionCheckResponse(@@ -2618,7 +2638,15 @@ async def check_embedding_model(hf_token = _normalize_hf_token(header_hf_token) or _normalize_hf_token(hf_token)try:logger.info(f"Checking if embedding model: {model_name}")- is_embedding = is_embedding_model(model_name, hf_token = hf_token)+ # Same guard as /check-vision: is_embedding_model hits the hub with a 15s+ # timeout, then answers False. Off the loop for the same reason.+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for++ def _check():+ with _hf_offline_if_unreachable_for(model_name):+ return is_embedding_model(model_name, hf_token = hf_token)++ is_embedding = await asyncio.to_thread(_check)logger.info(f"Embedding check result for {model_name}: is_embedding={is_embedding}")return EmbeddingCheckResponse(diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.pyindex aa087fe4ea2..2f86f8efdcc 100644--- a/studio/backend/tests/test_active_generations.py+++ b/studio/backend/tests/test_active_generations.py@@ -344,7 +344,7 @@ def test_a_forced_load_that_fails_preflight_leaves_the_chats_alone(monkeypatch):from models.inference import LoadRequestinf_mod = _stub_load_route(monkeypatch, active_model_name = "org/OTHER")- monkeypatch.setattr(inf_mod, "_hf_offline_if_dns_dead", contextlib.nullcontext)+ monkeypatch.setattr(inf_mod, "_hf_offline_if_unreachable", contextlib.nullcontext)# Stands in for any preflight refusal; a None here is the route's own 400.monkeypatch.setattr(inf_mod.ModelConfig, "from_identifier", staticmethod(lambda **kwargs: None))@@ -375,7 +375,7 @@ def _stub_standard_load_route(monkeypatch):_stub_load_route(monkeypatch, active_model_name = "org/OTHER")# _stub_load_route neutralises the sidecar guard; this test is about it.monkeypatch.setattr(inf_mod, "_raise_if_sidecar_swap_in_progress", real_sidecar_check)- monkeypatch.setattr(inf_mod, "_hf_offline_if_dns_dead", contextlib.nullcontext)+ monkeypatch.setattr(inf_mod, "_hf_offline_if_unreachable", contextlib.nullcontext)monkeypatch.setattr(inf_mod, "_mlx_distributed_launch_detected", lambda: False)monkeypatch.setattr(inf_mod.ModelConfig,@@ -1582,7 +1582,7 @@ def test_a_forced_load_that_loses_to_a_sidecar_install_leaves_the_chats_alone(mofrom models.inference import LoadRequestinf_mod = _stub_load_route(monkeypatch, active_model_name = "org/OTHER")- monkeypatch.setattr(inf_mod, "_hf_offline_if_dns_dead", contextlib.nullcontext)+ monkeypatch.setattr(inf_mod, "_hf_offline_if_unreachable", contextlib.nullcontext)monkeypatch.setattr(inf_mod.ModelConfig,"from_identifier",diff --git a/studio/backend/tests/test_chat_load_during_training.py b/studio/backend/tests/test_chat_load_during_training.pyindex 3ea10fd7454..31c8d0be371 100644--- a/studio/backend/tests/test_chat_load_during_training.py+++ b/studio/backend/tests/test_chat_load_during_training.py@@ -1341,7 +1341,9 @@ class TestLoadModelGuardIntegration(unittest.TestCase):patch.object(self.route, "resolve_effective_chat_template_override", return_value = None),patch.object(self.route, "get_inference_backend", return_value = inf),patch.object(self.route, "get_llama_cpp_backend", return_value = llama),- patch.object(self.route, "_hf_offline_if_dns_dead", lambda: contextlib.nullcontext()),+ patch.object(+ self.route, "_hf_offline_if_unreachable", lambda: contextlib.nullcontext()+ ),patch.object(self.route.ModelConfig, "from_identifier", return_value = cfg),_stub_guard_deps(training_active = True, decision = (False, info)),):@@ -1407,7 +1409,9 @@ class TestLoadModelGuardIntegration(unittest.TestCase):),patch.object(self.route, "get_inference_backend", return_value = inf),patch.object(self.route, "get_llama_cpp_backend", return_value = llama),- patch.object(self.route, "_hf_offline_if_dns_dead", lambda: contextlib.nullcontext()),+ patch.object(+ self.route, "_hf_offline_if_unreachable", lambda: contextlib.nullcontext()+ ),patch.object(self.route.ModelConfig, "from_identifier", return_value = cfg),_stub_guard_deps(training_active = True, decision = (True, {}), captured = captured),):diff --git a/studio/backend/tests/test_gguf_load_cache_reuse.py b/studio/backend/tests/test_gguf_load_cache_reuse.pyindex d2f3258c7a2..8c5cfedc184 100644--- a/studio/backend/tests/test_gguf_load_cache_reuse.py+++ b/studio/backend/tests/test_gguf_load_cache_reuse.py@@ -915,7 +915,7 @@ class TestLoadHubDownloadExclusion:patch.object(route, "_resolve_gguf_gpu_ids_for_request", _no_gguf_gpu_ids),patch.object(route, "_guard_chat_load_against_training", return_value = None),patch.object(route, "_effective_load_in_4bit", return_value = False),- patch.object(route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(route, "_hf_offline_if_unreachable", nullcontext),patch.object(route.asyncio, "to_thread", new = _inline_to_thread),patch.object(llama_cpp_module, "_hub_download_blocks_gguf_load", _fake_blocks),):diff --git a/studio/backend/tests/test_gpu_memory_mode.py b/studio/backend/tests/test_gpu_memory_mode.pyindex cc3a664a9ae..3757f82240b 100644--- a/studio/backend/tests/test_gpu_memory_mode.py+++ b/studio/backend/tests/test_gpu_memory_mode.py@@ -741,7 +741,7 @@ def test_remote_vulkan_diffusion_rejection_keeps_active_server(monkeypatch):)monkeypatch.setattr(llama_cpp_module,- "_hf_offline_if_dns_dead",+ "_hf_offline_if_unreachable",lambda: __import__("contextlib").nullcontext(),)@@ -790,7 +790,7 @@ def test_remote_vulkan_preflight_download_failure_keeps_active_server(monkeypatcmonkeypatch.setattr(llama_cpp_module, "_resolve_repo_id_casing", lambda repo: repo)monkeypatch.setattr(llama_cpp_module,- "_hf_offline_if_dns_dead",+ "_hf_offline_if_unreachable",lambda: __import__("contextlib").nullcontext(),)diff --git a/studio/backend/tests/test_gpu_selection.py b/studio/backend/tests/test_gpu_selection.pyindex e90767e9c19..1e5444f3cda 100644--- a/studio/backend/tests/test_gpu_selection.py+++ b/studio/backend/tests/test_gpu_selection.py@@ -1048,7 +1048,7 @@ class TestRouteErrors(unittest.TestCase):return_value = None,),patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),):with self.assertRaises(HTTPException) as exc_info:asyncio.run(@@ -1117,7 +1117,7 @@ class TestRouteErrors(unittest.TestCase):return_value = None,) as training_guard,patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),):with self.assertRaises(HTTPException) as exc_info:asyncio.run(@@ -1253,7 +1253,7 @@ class TestRouteErrors(unittest.TestCase):return_value = None,),patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),):with self.assertRaises(HTTPException) as exc_info:asyncio.run(@@ -1309,7 +1309,7 @@ class TestRouteErrors(unittest.TestCase):patch.object(inference_route, "_classify_diffusion_gguf", return_value = False),patch.object(inference_route, "_guard_chat_load_against_training", return_value = None),patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),patch.object(inference_route, "get_llama_cpp_backend", return_value = fake_backend),patch.object(hardware_pkg, "get_device", return_value = hardware_pkg.DeviceType.CUDA),):@@ -1370,7 +1370,7 @@ class TestRouteErrors(unittest.TestCase):),patch.object(inference_route, "_guard_chat_load_against_training", return_value = None),patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),patch.object(inference_route, "get_llama_cpp_backend", return_value = fake_backend),patch.object(hardware_pkg, "get_device", return_value = hardware_pkg.DeviceType.CUDA),):@@ -1512,7 +1512,7 @@ class TestRouteErrors(unittest.TestCase):return_value = None,),patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),patch("core.export.get_export_backend",return_value = SimpleNamespace(current_checkpoint = None),@@ -1583,7 +1583,7 @@ class TestRouteErrors(unittest.TestCase):return_value = None,),patch.object(inference_route.asyncio, "to_thread", new = _inline_to_thread),- patch.object(inference_route, "_hf_offline_if_dns_dead", nullcontext),+ patch.object(inference_route, "_hf_offline_if_unreachable", nullcontext),patch("core.export.get_export_backend",return_value = SimpleNamespace(current_checkpoint = None),diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.pyindex d1e61d0546e..900ae753621 100644--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py@@ -15,6 +15,8 @@ No GPU, no network, no subprocess. Linux/macOS/Windows compatible.from __future__ import annotations+import contextlib+import importlib.util as _importlib_utilimport osimport socketimport sys@@ -29,14 +31,26 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)+# Stub heavy/unavailable external deps before importing the modules under# test (same pattern as other studio backend tests).-_loggers_stub = _types.ModuleType("loggers")-_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)-sys.modules.setdefault("loggers", _loggers_stub)+def _module_available(name: str) -> bool:+ """True if the real module can be imported. Probed rather than imported: these stubs+ land in sys.modules for the whole session, so an empty one breaks anything imported+ later that actually uses the module."""+ try:+ return _importlib_util.find_spec(name) is not None+ except (ImportError, ValueError):+ return False+-_structlog_stub = _types.ModuleType("structlog")-sys.modules.setdefault("structlog", _structlog_stub)+if not _module_available("loggers"):+ _loggers_stub = _types.ModuleType("loggers")+ _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+ sys.modules.setdefault("loggers", _loggers_stub)++if not _module_available("structlog"):+ sys.modules.setdefault("structlog", _types.ModuleType("structlog"))# Prefer real httpx if installed (CI installs it). Stub only as fallback.try:@@ -81,7 +95,7 @@ from core.inference.llama_cpp import (LlamaCppBackend,_cached_colocated_split_main,_gguf_files_for_variant,- _hf_offline_if_dns_dead,+ _hf_offline_if_unreachable,_probe_dns_dead,_resolve_repo_id_casing,)@@ -144,6 +158,22 @@ def clean_offline_env(monkeypatch):monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+def clean_proxy_env(monkeypatch):+ """Keep direct-urlopen probe tests independent of the runner's proxy settings."""+ for key in (+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "ALL_PROXY",+ "NO_PROXY",+ "http_proxy",+ "https_proxy",+ "all_proxy",+ "no_proxy",+ ):+ monkeypatch.delenv(key, raising = False)++class TestGgufVariantFileResolution:def test_prefers_exact_unknown_variant_over_big_endian_sibling(self):files = [@@ -871,28 +901,49 @@ class TestDetectGgufModelRemoteOffline:# ----------------------------------------------------------------------------# _probe_dns_dead / _hf_offline_if_dns_dead+# _probe_dns_dead / _hf_offline_if_unreachable# ---------------------------------------------------------------------------class _DnsState:- """Tiny helper that toggles ``socket.gethostbyname`` failure mode."""+ """Toggles resolver failure. The probe uses ``getaddrinfo`` (IPv4 + IPv6), so patch+ both entry points."""def __init__(self, monkeypatch):self._mp = monkeypatchself._real = socket.gethostbyname+ self._real_addr = socket.getaddrinfodef fail(self):def _fail(*a, **k):raise socket.gaierror(-2, "Name or service not known")self._mp.setattr(socket, "gethostbyname", _fail)+ self._mp.setattr(socket, "getaddrinfo", _fail)def ok(self):self._mp.setattr(socket, "gethostbyname", lambda *a, **k: "127.0.0.1")+ self._mp.setattr(+ socket,+ "getaddrinfo",+ lambda *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 0))],+ )def restore(self):self._mp.setattr(socket, "gethostbyname", self._real)+ self._mp.setattr(socket, "getaddrinfo", self._real_addr)++[email protected](autouse = True)+def _drop_reachability_memo():+ """_hf_unreachable reuses a fresh verdict before re-running the DNS shortcut, so a+ verdict left by a neighbouring test would short-circuit this one's stubs. Process-global+ state, so clear it either side rather than relying on collection order."""+ from utils.utils import reset_hf_reachability_cache++ reset_hf_reachability_cache()+ yield+ reset_hf_reachability_cache()@pytest.fixture@@ -900,6 +951,18 @@ def dns(monkeypatch):return _DnsState(monkeypatch)+def reachable(monkeypatch):+ """Control the endpoint reachability probe; defaults to reachable so no test hits the network."""+ import utils.utils as _utils++ def _set(unreachable: bool):+ monkeypatch.setattr(_utils, "hf_unreachable", lambda *a, **k: unreachable)++ _set(False)+ return _set++class TestProbeDnsDead:def test_returns_false_on_success(self, dns):dns.ok()@@ -919,11 +982,17 @@ class TestProbeDnsDead:socket.setdefaulttimeout(None)-class TestHfOfflineIfDnsDead:- def test_dns_fail_sets_env_inside_block_only(self, dns, clean_offline_env):+class TestHfOfflineIfUnreachable:+ @pytest.fixture(autouse = True)+ def _no_ambient_proxy(self, clean_proxy_env):+ """hf_dns_dead stands down when a proxy is configured, so on a runner with+ HTTP_PROXY set the patched resolver is bypassed and the DNS-failure scenario these+ tests mean to exercise never happens."""++ def test_dns_fail_sets_env_inside_block_only(self, dns, reachable, clean_offline_env):dns.fail()assert "HF_HUB_OFFLINE" not in os.environ- with _hf_offline_if_dns_dead() as did_set:+ with _hf_offline_if_unreachable() as did_set:assert did_set is Trueassert os.environ.get("HF_HUB_OFFLINE") == "1"assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"@@ -931,38 +1000,58 @@ class TestHfOfflineIfDnsDead:assert "HF_HUB_OFFLINE" not in os.environassert "TRANSFORMERS_OFFLINE" not in os.environ- def test_dns_ok_is_noop(self, dns, clean_offline_env):+ def test_dns_ok_and_reachable_is_noop(self, dns, reachable, clean_offline_env):dns.ok()- with _hf_offline_if_dns_dead() as did_set:+ with _hf_offline_if_unreachable() as did_set:assert did_set is Falseassert "HF_HUB_OFFLINE" not in os.environ- def test_dns_recovers_between_calls(self, dns, clean_offline_env):+ def test_dns_ok_but_endpoint_unreachable_engages(self, dns, reachable, clean_offline_env):+ # WAN down behind a live router: DNS answers, egress does not.+ dns.ok()+ reachable(True)+ with _hf_offline_if_unreachable() as did_set:+ assert did_set is True+ assert os.environ.get("HF_HUB_OFFLINE") == "1"+ assert "HF_HUB_OFFLINE" not in os.environ++ def test_probe_opt_out_keeps_dns_only_behaviour(self, dns, clean_offline_env, monkeypatch):+ monkeypatch.setenv("UNSLOTH_OFFLINE_PROBE", "0")+ dns.ok()+ with _hf_offline_if_unreachable() as did_set:+ assert did_set is False+ assert "HF_HUB_OFFLINE" not in os.environ++ def test_dns_recovers_between_calls(self, dns, reachable, clean_offline_env):# First call: DNS dead -> env set inside, cleared on exit.dns.fail()- with _hf_offline_if_dns_dead():+ with _hf_offline_if_unreachable():passassert "HF_HUB_OFFLINE" not in os.environ# Second call: DNS healthy -> no env mutation.dns.ok()- with _hf_offline_if_dns_dead() as did_set:+ with _hf_offline_if_unreachable() as did_set:assert did_set is Falseassert "HF_HUB_OFFLINE" not in os.environ- def test_user_set_hf_hub_offline_is_preserved(self, dns, clean_offline_env, monkeypatch):+ def test_user_set_hf_hub_offline_is_preserved(+ self, dns, reachable, clean_offline_env, monkeypatch+ ):# User explicitly set offline before launching Unsloth.monkeypatch.setenv("HF_HUB_OFFLINE", "1")dns.fail()- with _hf_offline_if_dns_dead() as did_set:+ with _hf_offline_if_unreachable() as did_set:assert did_set is Falseassert os.environ.get("HF_HUB_OFFLINE") == "1"# Helper must not pop a variable it did not set.assert os.environ.get("HF_HUB_OFFLINE") == "1"- def test_user_set_transformers_offline_is_preserved(self, dns, clean_offline_env, monkeypatch):+ def test_user_set_transformers_offline_is_preserved(+ self, dns, reachable, clean_offline_env, monkeypatch+ ):monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")dns.fail()- with _hf_offline_if_dns_dead():+ with _hf_offline_if_unreachable():assert os.environ.get("HF_HUB_OFFLINE") == "1"assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"# HF_HUB_OFFLINE was set by helper -> removed.@@ -970,16 +1059,812 @@ class TestHfOfflineIfDnsDead:# TRANSFORMERS_OFFLINE pre-existed -> preserved.assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"- def test_exception_inside_block_still_restores_env(self, dns, clean_offline_env):+ def test_exception_inside_block_still_restores_env(self, dns, reachable, clean_offline_env):dns.fail()with pytest.raises(RuntimeError, match = "boom"):- with _hf_offline_if_dns_dead():+ with _hf_offline_if_unreachable():raise RuntimeError("boom")# Cleanup must happen on exception as well.assert "HF_HUB_OFFLINE" not in os.environassert "TRANSFORMERS_OFFLINE" not in os.environ+class TestEndpointAwareOfflineDetection:+ """A reachable HF_ENDPOINT mirror must not be declared offline just because+ huggingface.co does not resolve (air-gapped / corporate networks)."""++ @pytest.fixture+ def no_upstream_dns(self, monkeypatch):+ def _host(h, *a, **k):+ if "huggingface.co" in str(h):+ raise socket.gaierror(-2, "Name or service not known")+ return "127.0.0.1"++ def _addr(h, *a, **k):+ if "huggingface.co" in str(h):+ raise socket.gaierror(-2, "Name or service not known")+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 0))]++ monkeypatch.setattr(socket, "gethostbyname", _host)+ monkeypatch.setattr(socket, "getaddrinfo", _addr)++ @pytest.mark.parametrize(+ "endpoint,expected",+ [+ ("https://hf-mirror.com", "hf-mirror.com"),+ ("hf-mirror.com", "hf-mirror.com"),+ ("https://hf-mirror.com:8443", "hf-mirror.com"),+ ("https://hf-mirror.com/path", "hf-mirror.com"),+ ("", "huggingface.co"),+ ],+ )+ def test_endpoint_host_parsing(self, monkeypatch, endpoint, expected):+ from core.inference.llama_cpp import _hf_endpoint_host+ monkeypatch.setenv("HF_ENDPOINT", endpoint)+ assert _hf_endpoint_host() == expected++ def test_dns_precheck_follows_endpoint(self, monkeypatch, no_upstream_dns):+ monkeypatch.setenv("HF_ENDPOINT", "https://hf-mirror.com")+ assert _probe_dns_dead() is False++ def test_default_endpoint_still_probes_huggingface(self, monkeypatch, no_upstream_dns):+ monkeypatch.delenv("HF_ENDPOINT", raising = False)+ assert _probe_dns_dead() is True+++class TestProxyOnlyEgress:+ """With a proxy, the proxy resolves the hub host, so local DNS proves nothing and+ must not be used to declare the hub offline."""++ @pytest.fixture+ def dns_all_dead(self, monkeypatch):+ def _fail(*a, **k):+ raise socket.gaierror(-2, "Name or service not known")++ monkeypatch.setattr(socket, "gethostbyname", _fail)+ monkeypatch.setattr(socket, "getaddrinfo", _fail)++ def test_dns_shortcut_stands_down_when_proxy_configured(self, monkeypatch, dns_all_dead):+ from utils.utils import hf_dns_dead++ monkeypatch.delenv("HF_ENDPOINT", raising = False)+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("HTTP_PROXY", "http://proxy.internal:3128")+ assert hf_dns_dead() is False++ def test_dns_shortcut_applies_without_a_proxy(self, monkeypatch, dns_all_dead):+ from utils.utils import hf_dns_dead++ for key in ("HTTPS_PROXY", "HTTP_PROXY", "https_proxy", "http_proxy", "ALL_PROXY"):+ monkeypatch.delenv(key, raising = False)+ monkeypatch.setattr("utils.utils.hf_proxy_configured", lambda: False)+ assert hf_dns_dead() is True++ def test_no_proxy_bypass_restores_the_shortcut(self, monkeypatch, dns_all_dead):+ """A host listed in NO_PROXY does not go through the proxy, so DNS matters again."""+ from utils.utils import hf_proxy_configured++ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("NO_PROXY", "huggingface.co")+ assert hf_proxy_configured() is False+++class TestAllProxyIsHonoured:+ """The Hub client (requests) honours all_proxy but urllib does not, so a proxy-only+ setup would fail the probe's direct lookup and be called offline while real hub calls+ succeed. Resolution must match requests' select_proxy."""++ @pytest.fixture(autouse = True)+ def _clean_proxy_env(self, monkeypatch):+ for key in (+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "ALL_PROXY",+ "NO_PROXY",+ "http_proxy",+ "https_proxy",+ "all_proxy",+ "no_proxy",+ ):+ monkeypatch.delenv(key, raising = False)+ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")++ def test_all_proxy_alone_resolves(self, monkeypatch):+ from utils.utils import hf_proxy_configured, hf_proxy_for_endpoint++ monkeypatch.setenv("ALL_PROXY", "http://proxy.internal:3128")+ assert hf_proxy_for_endpoint() == "http://proxy.internal:3128"+ assert hf_proxy_configured() is True++ def test_scheme_specific_beats_all_proxy(self, monkeypatch):+ from utils.utils import hf_proxy_for_endpoint++ monkeypatch.setenv("ALL_PROXY", "http://catchall:3128")+ monkeypatch.setenv("HTTPS_PROXY", "http://specific:3128")+ assert hf_proxy_for_endpoint() == "http://specific:3128"++ def test_no_proxy_wins_over_all_proxy(self, monkeypatch):+ from utils.utils import hf_proxy_for_endpoint++ monkeypatch.setenv("ALL_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("NO_PROXY", "huggingface.co")+ assert hf_proxy_for_endpoint() is None++ def test_no_proxy_cidr_matches_requests(self, monkeypatch):+ """The probe and Hub client must both bypass a proxy for an IP in a CIDR."""+ from utils.utils import hf_proxy_for_endpoint++ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("NO_PROXY", "10.0.0.0/8")+ assert hf_proxy_for_endpoint("https://10.23.4.5") is None++ def test_no_proxy_host_with_port_matches_requests(self, monkeypatch):+ """requests includes an explicit endpoint port when matching NO_PROXY."""+ from utils.utils import hf_proxy_for_endpoint++ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("NO_PROXY", "huggingface.co:443")+ assert hf_proxy_for_endpoint("https://huggingface.co:443") is None++ def test_direct_egress_resolves_to_none(self):+ from utils.utils import hf_proxy_for_endpoint+ assert hf_proxy_for_endpoint() is None++ def test_connect_target_follows_all_proxy(self, monkeypatch):+ from utils.utils import hf_connect_target+ monkeypatch.setenv("ALL_PROXY", "http://proxy.internal:3128")+ assert hf_connect_target() == ("proxy.internal", 3128)++ def test_probe_opens_through_all_proxy(self, monkeypatch):+ """The HEAD probe must be issued through the proxy, not attempted directly."""+ import urllib.request++ from utils.transformers_version import hf_endpoint_unreachable++ monkeypatch.setenv("ALL_PROXY", "http://proxy.internal:3128")+ seen = {}+ real_build = urllib.request.build_opener++ def _spy(*handlers):+ for h in handlers:+ if isinstance(h, urllib.request.ProxyHandler):+ seen["proxies"] = dict(h.proxies)+ opener = real_build(*handlers)+ opener.open = lambda req, timeout = None: _Resp() # noqa: ARG005+ return opener++ class _Resp:+ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ monkeypatch.setattr(urllib.request, "build_opener", _spy)+ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: pytest.fail("probe bypassed the proxy"),+ )+ assert hf_endpoint_unreachable(timeout = 1) is False+ assert seen["proxies"] == {"https": "http://proxy.internal:3128"}++ def test_probe_forces_direct_opener_when_no_proxy_bypasses(self, monkeypatch):+ import urllib.request++ from utils.transformers_version import hf_endpoint_unreachable++ monkeypatch.setenv("HF_ENDPOINT", "https://10.23.4.5")+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("NO_PROXY", "10.0.0.0/8")+ seen = {}+ real_build = urllib.request.build_opener++ class _Resp:+ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ def _spy(*handlers):+ for handler in handlers:+ if isinstance(handler, urllib.request.ProxyHandler):+ seen["proxies"] = dict(handler.proxies)+ opener = real_build(*handlers)+ opener.open = lambda req, timeout = None: _Resp() # noqa: ARG005+ return opener++ monkeypatch.setattr(urllib.request, "build_opener", _spy)+ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: pytest.fail("default opener re-evaluated proxy settings"),+ )+ assert hf_endpoint_unreachable(timeout = 1) is False+ assert seen["proxies"] == {}+++class TestEnvOfflineSkipsTheProbe:+ """An explicitly offline process must emit no network traffic. The hub reads only+ HF_HUB_OFFLINE, so TRANSFORMERS_OFFLINE alone still has to engage the guard."""++ def test_transformers_offline_engages_without_probing(self, monkeypatch):+ llama_cpp = pytest.importorskip("core.inference.llama_cpp")++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")+ monkeypatch.setattr(+ llama_cpp,+ "_hf_unreachable",+ lambda: pytest.fail("probed the network in an explicitly offline process"),+ )+ with llama_cpp._hf_offline_if_unreachable() as engaged:+ assert engaged is True+ assert hf_constants.HF_HUB_OFFLINE is True++ def test_hub_offline_zero_still_opts_out(self, monkeypatch):+ """HF_HUB_OFFLINE=0 is an explicit "stay online" and outranks TRANSFORMERS_OFFLINE."""+ llama_cpp = pytest.importorskip("core.inference.llama_cpp")++ monkeypatch.setenv("HF_HUB_OFFLINE", "0")+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")+ monkeypatch.setattr(+ llama_cpp,+ "_hf_unreachable",+ lambda: pytest.fail("probed despite an opt-out"),+ )+ with llama_cpp._hf_offline_if_unreachable() as engaged:+ assert engaged is False++ def test_falsey_transformers_offline_still_probes(self, monkeypatch):+ llama_cpp = pytest.importorskip("core.inference.llama_cpp")++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "0")+ calls = []+ monkeypatch.setattr(+ llama_cpp,+ "_hf_unreachable",+ lambda: (calls.append(1), False)[1],+ )+ with llama_cpp._hf_offline_if_unreachable() as engaged:+ assert engaged is False+ assert calls == [1]+++class TestSlowLinkIsNotOffline:+ """A slow but reachable endpoint must not be quarantined: that would fail an uncached+ load that would otherwise merely be slow. A blackholed route must still be offline."""++ @pytest.fixture(autouse = True)+ def _direct_probe(self, clean_proxy_env):+ pass++ def _probe_raising(self, monkeypatch, exc):+ import urllib.request++ monkeypatch.setattr(urllib.request, "urlopen", lambda *a, **k: (_ for _ in ()).throw(exc))+ from utils.transformers_version import hf_endpoint_unreachable++ return hf_endpoint_unreachable++ def test_timeout_with_tcp_egress_is_reachable(self, monkeypatch):+ import urllib.error++ probe = self._probe_raising(monkeypatch, urllib.error.URLError(TimeoutError("slow")))+ monkeypatch.setattr("utils.utils.hf_tcp_reachable", lambda *a, **k: True)+ assert probe(timeout = 1) is False++ def test_timeout_without_tcp_egress_is_offline(self, monkeypatch):+ import urllib.error++ probe = self._probe_raising(monkeypatch, urllib.error.URLError(TimeoutError("dead")))+ monkeypatch.setattr("utils.utils.hf_tcp_reachable", lambda *a, **k: False)+ assert probe(timeout = 1) is True++ def test_bare_timeout_error_takes_the_same_path(self, monkeypatch):+ probe = self._probe_raising(monkeypatch, TimeoutError("slow"))+ monkeypatch.setattr("utils.utils.hf_tcp_reachable", lambda *a, **k: True)+ assert probe(timeout = 1) is False++ def test_refused_connection_counts_as_egress(self, monkeypatch):+ """Something answered, so the network works even though nothing is listening."""+ import socket as _socket++ from utils.utils import hf_tcp_reachable++ def _refuse(*a, **k):+ raise ConnectionRefusedError()++ monkeypatch.setattr(_socket, "create_connection", _refuse)+ assert hf_tcp_reachable(1, "http://127.0.0.1:9") is True+++class TestConcurrentGuardsHoldTheirOwnReference:+ """Overlapping requests must each hold a reference. If a later guard no-ops because an+ earlier one already set HF_HUB_OFFLINE, the earlier guard's exit restores the network+ while the later request is still resolving hub files."""++ def test_second_guard_engages_and_offline_survives_first_exit(+ self, monkeypatch, clean_offline_env+ ):+ import threading++ import core.inference.llama_cpp as lc++ monkeypatch.setattr(lc, "_hf_unreachable", lambda: True)++ a_in, b_in, a_done = threading.Event(), threading.Event(), threading.Event()+ seen: dict = {}++ def worker_a():+ with lc._hf_offline_if_unreachable():+ a_in.set()+ b_in.wait(5)+ a_done.set()++ def worker_b():+ a_in.wait(5)+ with lc._hf_offline_if_unreachable() as engaged:+ seen["engaged"] = engaged+ b_in.set()+ a_done.wait(5)+ seen["offline_after_a_exit"] = hf_constants.HF_HUB_OFFLINE+ seen["env_after_a_exit"] = os.environ.get("HF_HUB_OFFLINE")++ ta, tb = threading.Thread(target = worker_a), threading.Thread(target = worker_b)+ ta.start()+ tb.start()+ ta.join(20)+ tb.join(20)++ assert seen.get("engaged") is True, "second guard no-opped instead of taking a reference"+ assert seen.get("offline_after_a_exit") is True+ assert seen.get("env_after_a_exit") == "1"+ # Both windows closed -> fully restored.+ assert hf_constants.HF_HUB_OFFLINE is False+ assert "HF_HUB_OFFLINE" not in os.environ++ def test_user_set_offline_is_still_a_noop(self, monkeypatch, clean_offline_env):+ import core.inference.llama_cpp as lc++ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ monkeypatch.setattr(lc, "_hf_unreachable", lambda: True)+ with lc._hf_offline_if_unreachable() as engaged:+ assert engaged is False+ assert os.environ["HF_HUB_OFFLINE"] == "1"++ def test_guard_ownership_cannot_race_the_environment_check(+ self, monkeypatch, clean_offline_env+ ):+ """A guard that starts just before another sets the env must retain its window."""+ import threading++ import core.inference.llama_cpp as lc+ import utils.utils as uu++ monkeypatch.setattr(lc, "_hf_unreachable", lambda: True)+ original_active = uu.force_hf_offline_active+ original_state = uu.force_hf_offline_state+ owner_entered = threading.Event()+ release_owner = threading.Event()+ owner_thread = None++ def owner():+ with uu.force_hf_offline():+ owner_entered.set()+ release_owner.wait(5)++ def start_owner_after(snapshot):+ nonlocal owner_thread+ if threading.current_thread() is threading.main_thread() and owner_thread is None:+ owner_thread = threading.Thread(target = owner)+ owner_thread.start()+ assert owner_entered.wait(5)+ return snapshot++ def stale_active_read():+ # Old implementation: depth is read before the owner sets the env.+ return start_owner_after(original_active())++ def atomic_state_then_owner_enters():+ # New implementation: ownership + env are one consistent snapshot. Even if+ # another owner enters immediately after it, hf_env_offline catches that and+ # this guard takes a reference instead of treating the env as user-owned.+ return start_owner_after(original_state())++ monkeypatch.setattr(uu, "force_hf_offline_active", stale_active_read)+ monkeypatch.setattr(uu, "force_hf_offline_state", atomic_state_then_owner_enters)+ try:+ with lc._hf_offline_if_unreachable() as engaged:+ assert engaged is True+ finally:+ release_owner.set()+ if owner_thread is not None:+ owner_thread.join(10)+ assert owner_thread is not None+++class TestSpawnEnvironmentDoesNotInheritScopedOffline:+ """A scoped parent guard must not permanently quarantine a newly spawned worker."""++ def test_multiprocessing_spawn_window_uses_pre_guard_values(+ self, monkeypatch, clean_offline_env+ ):+ from utils.hf_cache_settings import child_environment_for_spawn+ from utils.utils import force_hf_offline+ with force_hf_offline():+ assert os.environ.get("HF_HUB_OFFLINE") == "1"+ with child_environment_for_spawn({}):+ assert "HF_HUB_OFFLINE" not in os.environ+ assert "TRANSFORMERS_OFFLINE" not in os.environ+ assert os.environ.get("HF_HUB_OFFLINE") == "1"+ assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"++ def test_explicit_subprocess_environment_uses_pre_guard_values(+ self, monkeypatch, clean_offline_env, tmp_path+ ):+ from utils.hf_cache_settings import HuggingFaceCachePaths+ from utils.utils import force_hf_offline++ paths = HuggingFaceCachePaths(tmp_path, tmp_path / "hub", tmp_path / "xet", "studio")+ with force_hf_offline():+ child_env = paths.child_env()+ assert "HF_HUB_OFFLINE" not in child_env+ assert "TRANSFORMERS_OFFLINE" not in child_env++ def test_nested_spawn_contexts_remain_reentrant(self, monkeypatch, clean_offline_env):+ from utils.hf_cache_settings import child_environment_for_spawn+ from utils.utils import force_hf_offline+ with force_hf_offline():+ with child_environment_for_spawn({}):+ with child_environment_for_spawn({}):+ assert "HF_HUB_OFFLINE" not in os.environ+ assert os.environ.get("HF_HUB_OFFLINE") == "1"++ def test_user_transformers_offline_keeps_child_hub_offline(+ self, monkeypatch, clean_offline_env+ ):+ from utils.hf_cache_settings import child_environment_for_spawn+ from utils.utils import force_hf_offline++ monkeypatch.setenv("TRANSFORMERS_OFFLINE", "1")+ with force_hf_offline():+ with child_environment_for_spawn({}):+ assert os.environ.get("HF_HUB_OFFLINE") == "1"+ assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"+ assert "HF_HUB_OFFLINE" not in os.environ+ assert os.environ.get("TRANSFORMERS_OFFLINE") == "1"+++class TestSpawnWindowKeepsTheParentOffline:+ """Restoring the user's env for a spawn must not un-offline the guarded parent."""++ def test_env_offline_still_true_inside_the_spawn_window(self, monkeypatch, clean_offline_env):+ from utils.hf_cache_settings import child_environment_for_spawn+ from utils.transformers_version import _env_offline+ from utils.utils import force_hf_offline, hf_env_offline++ with force_hf_offline():+ assert _env_offline() is True and hf_env_offline() is True+ with child_environment_for_spawn({}):+ # The child must inherit the user's own (online) intent ...+ assert "HF_HUB_OFFLINE" not in os.environ+ # ... while the parent's own gates stay closed.+ assert _env_offline() is True+ assert hf_env_offline() is True+ assert _env_offline() is True++ def test_guarded_metadata_fetch_stays_local_during_a_concurrent_spawn(+ self, monkeypatch, clean_offline_env+ ):+ """Guard on one thread, spawn window on a second, raw metadata read on a third.+ No request may leave the process."""+ import threading++ from utils.hf_cache_settings import child_environment_for_spawn+ from utils.utils import force_hf_offline++ from utils import transformers_version as tv++ calls: list = []+ monkeypatch.setattr(tv, "_adapter_base_from_hf_cache", lambda name: "cached/base")+ monkeypatch.setattr(+ "urllib.request.urlopen",+ lambda *a, **k: calls.append(a) or (_ for _ in ()).throw(AssertionError("network")),+ )++ guard_open = threading.Event()+ release_guard = threading.Event()+ in_window = threading.Event()+ release_window = threading.Event()++ def _guard():+ with force_hf_offline():+ guard_open.set()+ release_guard.wait(30)++ def _spawn():+ guard_open.wait(30)+ with child_environment_for_spawn({}):+ in_window.set()+ release_window.wait(30)++ threads = [+ threading.Thread(target = _guard, daemon = True),+ threading.Thread(target = _spawn, daemon = True),+ ]+ for thread in threads:+ thread.start()+ try:+ assert in_window.wait(30)+ assert tv._remote_lora_base("some-org/some-lora") == "cached/base"+ assert calls == []+ finally:+ release_window.set()+ release_guard.set()+ for thread in threads:+ thread.join(30)+++class TestProxyTimeoutIsNotExcused:+ """A live proxy proves the proxy is up, not that it can reach the hub."""++ @pytest.fixture(autouse = True)+ def _direct_probe(self, clean_proxy_env):+ pass++ def _probe_timing_out(self, monkeypatch):+ import urllib.error+ import urllib.request++ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: (_ for _ in ()).throw(urllib.error.URLError(TimeoutError("slow"))),+ )+ from utils.transformers_version import hf_endpoint_unreachable++ return hf_endpoint_unreachable++ def test_timeout_through_a_proxy_stays_unreachable(self, monkeypatch):+ probe = self._probe_timing_out(monkeypatch)+ monkeypatch.setattr("utils.utils.hf_proxy_configured", lambda: True)+ # Even if the proxy itself accepts TCP, the hub behind it may be blackholed.+ monkeypatch.setattr("utils.utils.hf_tcp_reachable", lambda *a, **k: True)+ assert probe(timeout = 1) is True++ def test_timeout_without_a_proxy_still_uses_tcp(self, monkeypatch):+ probe = self._probe_timing_out(monkeypatch)+ monkeypatch.setattr("utils.utils.hf_proxy_configured", lambda: False)+ monkeypatch.setattr("utils.utils.hf_tcp_reachable", lambda *a, **k: True)+ assert probe(timeout = 1) is False++ def test_lifetime_mode_fails_open_on_proxy_timeout(self, monkeypatch):+ probe = self._probe_timing_out(monkeypatch)+ monkeypatch.setattr("utils.utils.hf_proxy_configured", lambda: True)+ assert probe(timeout = 1, proxy_timeouts_offline = False) is False+++class TestEndpointNormalisation:+ """An empty or whitespace HF_ENDPOINT must fall back to the default hub in BOTH the+ DNS shortcut and the HTTP probe, or the two stages disagree."""++ @pytest.fixture(autouse = True)+ def _direct_probe(self, clean_proxy_env):+ pass++ @pytest.mark.parametrize("value", ["", " ", "\t"])+ def test_blank_endpoint_falls_back(self, monkeypatch, value):+ from utils.utils import hf_endpoint_host, hf_endpoint_url++ monkeypatch.setenv("HF_ENDPOINT", value)+ assert hf_endpoint_host() == "huggingface.co"+ assert hf_endpoint_url() == "https://huggingface.co"++ def test_probe_uses_the_same_normalised_url(self, monkeypatch):+ seen: list = []+ import urllib.request++ def _capture(req, *a, **k):+ seen.append(req.full_url)+ raise urllib.error.URLError("stop")++ import urllib.error++ monkeypatch.setenv("HF_ENDPOINT", " ")+ monkeypatch.setattr(urllib.request, "urlopen", _capture)+ from utils.transformers_version import hf_endpoint_unreachable++ hf_endpoint_unreachable(timeout = 1)+ assert seen and seen[0].startswith("https://huggingface.co"), seen+++class TestIpv6Endpoint:+ def test_ipv6_literal_resolves(self):+ """gethostbyname is IPv4-only and would call an AAAA-only mirror dead."""+ from utils.utils import dns_host_dead+ assert dns_host_dead("::1", timeout = 2.0) is False++ def test_unresolvable_host_still_dead(self, monkeypatch):+ # Mock the resolver rather than trusting the runner's: an ISP or captive+ # portal that hijacks NXDOMAIN resolves .invalid and would fail this test on+ # a perfectly good build. Also saves a real 2s lookup per run.+ import socket as _socket++ def _nxdomain(*a, **k):+ raise _socket.gaierror(-2, "Name or service not known")++ monkeypatch.setattr(_socket, "getaddrinfo", _nxdomain)+ from utils.utils import dns_host_dead++ assert dns_host_dead("no-such-host.invalid", timeout = 2.0) is True+++class TestGuardSkipsLocalPaths:+ """A local path never reaches the hub, so probing costs time and prevents nothing."""++ def test_local_path_is_a_noop(self, tmp_path, monkeypatch):+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for++ called: list = []+ monkeypatch.setattr("utils.utils.hf_unreachable", lambda *a, **k: called.append(1) or True)+ with _hf_offline_if_unreachable_for(str(tmp_path / "model.gguf")) as engaged:+ assert engaged is None # nullcontext yields None+ assert called == [], "probed the hub for a local path"++ def test_remote_id_still_guarded(self, monkeypatch, clean_offline_env):+ import core.inference.llama_cpp as lc+ monkeypatch.setattr(lc, "_hf_unreachable", lambda: True)+ with lc._hf_offline_if_unreachable_for("unsloth/Qwen3.5-4B-GGUF") as engaged:+ assert engaged is True+ assert os.environ.get("HF_HUB_OFFLINE") == "1"+++class TestGatewayErrorsAreNotConnectionFailures:+ """Lifetime offline flags must not be set by a momentary 502/503/504."""++ @pytest.fixture(autouse = True)+ def _direct_probe(self, clean_proxy_env):+ pass++ def _probe_with(self, monkeypatch, exc):+ import urllib.request++ def _urlopen(*a, **k):+ raise exc++ monkeypatch.setattr(urllib.request, "urlopen", _urlopen)+ from utils.transformers_version import hf_endpoint_unreachable++ return hf_endpoint_unreachable++ @pytest.mark.parametrize("code", [502, 503, 504])+ def test_strict_mode_treats_gateway_error_as_reachable(self, monkeypatch, code):+ import urllib.error++ exc = urllib.error.HTTPError("u", code, "err", {}, None)+ probe = self._probe_with(monkeypatch, exc)+ assert probe(timeout = 1, gateway_errors_offline = False) is False+ # Default (scoped callers) keeps treating a downed hub as offline.+ assert probe(timeout = 1) is True++ @pytest.mark.parametrize("code", [401, 403, 404, 429])+ def test_other_http_errors_always_reachable(self, monkeypatch, code):+ import urllib.error++ exc = urllib.error.HTTPError("u", code, "err", {}, None)+ probe = self._probe_with(monkeypatch, exc)+ assert probe(timeout = 1) is False+ assert probe(timeout = 1, gateway_errors_offline = False) is False+++class TestHfUnreachableProbe:+ """``utils.utils.hf_unreachable``: memoised, opt-outable, fails open."""++ @pytest.fixture(autouse = True)+ def _reset(self):+ from utils.utils import reset_hf_reachability_cache++ reset_hf_reachability_cache()+ yield+ reset_hf_reachability_cache()++ def _patch_probe(self, monkeypatch, result, calls):+ import utils.transformers_version as tv+ def _probe(*_a, **_k):+ calls.append(1)+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(tv, "hf_endpoint_unreachable", _probe)++ def test_probes_once_then_memoises(self, monkeypatch, clean_offline_env):+ from utils.utils import hf_unreachable++ calls: list = []+ self._patch_probe(monkeypatch, True, calls)+ assert hf_unreachable() is True+ assert hf_unreachable() is True+ assert len(calls) == 1++ def test_shared_probe_keeps_gateway_errors_online(self, monkeypatch, clean_offline_env):+ from utils.utils import hf_unreachable+ import utils.transformers_version as tv++ seen = {}++ # **_kwargs so the sibling ambiguity flag does not turn this into a TypeError+ # that the guard's fail-open would swallow. Both flags are asserted by+ # TestSlowProxyDoesNotForceOffline.+ def _probe(+ timeout,+ *,+ gateway_errors_offline = True,+ **_kwargs,+ ):+ seen["gateway_errors_offline"] = gateway_errors_offline+ return gateway_errors_offline++ monkeypatch.setattr(tv, "hf_endpoint_unreachable", _probe)+ assert hf_unreachable() is False+ assert seen["gateway_errors_offline"] is False++ def test_opt_out_skips_probe(self, monkeypatch, clean_offline_env):+ from utils.utils import hf_unreachable++ calls: list = []+ self._patch_probe(monkeypatch, True, calls)+ monkeypatch.setenv("UNSLOTH_OFFLINE_PROBE", "0")+ assert hf_unreachable() is False+ assert calls == []++ def test_probe_failure_reports_reachable(self, monkeypatch, clean_offline_env):+ from utils.utils import hf_unreachable++ calls: list = []+ self._patch_probe(monkeypatch, RuntimeError("boom"), calls)+ # Fail open: a broken probe must not strand a working install offline.+ assert hf_unreachable() is False++ def test_reset_forces_reprobe(self, monkeypatch, clean_offline_env):+ from utils.utils import hf_unreachable, reset_hf_reachability_cache++ calls: list = []+ self._patch_probe(monkeypatch, True, calls)+ assert hf_unreachable() is True+ reset_hf_reachability_cache()+ assert hf_unreachable() is True+ assert len(calls) == 2++ def test_memo_window_is_short_in_both_directions(self):+ """Stale either way is a bug: a stale 'reachable' hides the plug being pulled,+ a stale 'unreachable' fails a download after the user reconnects."""+ import utils.utils as uu+ assert uu._HF_REACHABILITY_TTL_S <= 10.0++ def test_verdict_expires_so_a_disconnect_is_noticed(self, monkeypatch, clean_offline_env):+ import time as _time++ import utils.utils as uu+ from utils.utils import hf_unreachable++ monkeypatch.setattr(uu, "_HF_REACHABILITY_TTL_S", 0.2)+ verdict = {"value": False}+ monkeypatch.setattr(+ __import__("utils.transformers_version", fromlist = ["x"]),+ "hf_endpoint_unreachable",+ lambda *a, **k: verdict["value"],+ )+ assert hf_unreachable() is False # online during the download+ verdict["value"] = True # plug pulled+ _time.sleep(0.3)+ assert hf_unreachable() is True++class TestExtractQuantLabelSubdir:"""``_extract_quant_label`` must consider parent dirs when the basename hasno quant token (subdir layouts like ``BF16/foo.gguf``)."""@@ -1322,7 +2207,14 @@ class TestProbeDnsDeadNoGlobalTimeoutMutation:original_set(value)monkeypatch.setattr(_socket, "setdefaulttimeout", tracking_set)- monkeypatch.setattr(_socket, "gethostbyname", lambda h: "127.0.0.1")+ # The probe resolves with getaddrinfo, not the IPv4-only gethostbyname, so+ # patching the latter left this test doing a real lookup and never exercising+ # the "DNS up" branch it is named for.+ monkeypatch.setattr(+ _socket,+ "getaddrinfo",+ lambda *a, **k: [(_socket.AF_INET, _socket.SOCK_STREAM, 6, "", ("127.0.0.1", 0))],+ )try:_probe_dns_dead("example.invalid", timeout = 0.5)@@ -1335,17 +2227,49 @@ class TestProbeDnsDeadNoGlobalTimeoutMutation:"must isolate timeout to the probe thread")- def test_returns_dead_when_resolver_wedges(self, monkeypatch):+ def test_wedged_resolver_is_inconclusive_not_dead(self, monkeypatch):+ """A missed deadline must not take the offline shortcut.++ Slow-but-working DNS resolves past 2s, and this shortcut skips the fail-open+ reachability probe, so calling it dead strands a working machine offline for a+ whole job. A genuinely wedged resolver is still caught downstream, by the HEAD+ probe hanging on the same lookup.+ """import socket as _socketfrom core.inference.llama_cpp import _probe_dns_dead- # Simulate a wedged resolver: thread blocks forever.- def wedged(host):+ # Patch getaddrinfo, which is what the probe calls; patching gethostbyname made+ # this pass vacuously off the real NXDOMAIN for .invalid.+ def wedged(*a, **k):import threadingthreading.Event().wait()- monkeypatch.setattr(_socket, "gethostbyname", wedged)- assert _probe_dns_dead("example.invalid", timeout = 0.1) is True+ monkeypatch.setattr(_socket, "getaddrinfo", wedged)+ assert _probe_dns_dead("example.invalid", timeout = 0.1) is False++ def test_slow_but_resolving_dns_is_not_dead(self, monkeypatch):+ """The case the deadline used to misread: an answer that arrives after it."""+ import socket as _socket+ import time as _time+ from utils.utils import dns_host_dead++ def slow(*a, **k):+ _time.sleep(0.3)+ return [(2, 1, 6, "", ("93.184.216.34", 443))]++ monkeypatch.setattr(_socket, "getaddrinfo", slow)+ assert dns_host_dead("slow.example.test", timeout = 0.1) is False++ def test_nxdomain_is_still_dead(self, monkeypatch):+ """The reported bug's shortcut must keep working: a real resolver error."""+ import socket as _socket+ from utils.utils import dns_host_dead++ def nxdomain(*a, **k):+ raise _socket.gaierror("Name or service not known")++ monkeypatch.setattr(_socket, "getaddrinfo", nxdomain)+ assert dns_host_dead("no-such-host.invalid", timeout = 2.0) is Trueclass TestWaitForHealthRetriesOnReadError:@@ -1431,3 +2355,991 @@ class TestWaitForHealthRetriesOnReadError:backend._stdout_thread = Nonebackend._stdout_lines = ["fatal: out of memory"]assert backend._wait_for_health(timeout = 5.0, interval = 0.01) is False+++class TestProxyDetectionWithoutRequests:+ """huggingface_hub 1.x moved to httpx and dropped requests. Proxy selection must+ not silently answer "no proxy" there: hf_dns_dead stands down for proxies, so+ going blind forces a working proxy-only machine offline."""++ @pytest.fixture(autouse = True)+ def _no_ambient_proxy(self, clean_proxy_env):+ pass++ def _without_requests(self, monkeypatch):+ import builtins++ real_import = builtins.__import__++ def _fail(name, *a, **k):+ if name == "requests.utils" or name.split(".")[0] == "requests":+ raise ImportError("No module named 'requests'")+ return real_import(name, *a, **k)++ monkeypatch.setattr(builtins, "__import__", _fail)++ def test_env_proxy_still_found_without_requests(self, monkeypatch):+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ self._without_requests(monkeypatch)+ from utils.utils import hf_proxy_for_endpoint++ assert hf_proxy_for_endpoint("https://huggingface.co") == "http://proxy.internal:3128"++ def test_all_proxy_still_found_without_requests(self, monkeypatch):+ monkeypatch.setenv("ALL_PROXY", "http://proxy.internal:3128")+ self._without_requests(monkeypatch)+ from utils.utils import hf_proxy_for_endpoint++ assert hf_proxy_for_endpoint("https://huggingface.co") == "http://proxy.internal:3128"++ def test_no_proxy_still_bypasses_without_requests(self, monkeypatch):+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("NO_PROXY", "huggingface.co")+ self._without_requests(monkeypatch)+ from utils.utils import hf_proxy_for_endpoint++ assert hf_proxy_for_endpoint("https://huggingface.co") is None++ def test_dns_shortcut_stands_down_without_requests(self, monkeypatch):+ monkeypatch.setenv("ALL_PROXY", "http://proxy.internal:3128")+ monkeypatch.setenv("HF_ENDPOINT", "https://does-not-resolve.invalid")+ self._without_requests(monkeypatch)+ from utils.utils import hf_dns_dead++ assert hf_dns_dead(timeout = 1.0) is False+++class TestSocksProxyIsNotEgressEvidence:+ """urllib cannot route through socks5://, so its instant failure is not proof the+ hub is unreachable -- the Hub client reaches it through that proxy fine."""++ @pytest.fixture(autouse = True)+ def _no_ambient_proxy(self, clean_proxy_env):+ pass++ def test_socks_scheme_is_not_usable_by_urllib(self):+ from utils.utils import hf_proxy_usable_by_urllib++ assert hf_proxy_usable_by_urllib("socks5://127.0.0.1:1080") is False+ assert hf_proxy_usable_by_urllib("socks5h://127.0.0.1:1080") is False+ assert hf_proxy_usable_by_urllib("http://127.0.0.1:3128") is True+ assert hf_proxy_usable_by_urllib("https://127.0.0.1:3128") is True+ assert hf_proxy_usable_by_urllib(None) is True++ def test_socks_proxy_reports_reachable(self, monkeypatch):+ import urllib.request++ monkeypatch.setenv("ALL_PROXY", "socks5://127.0.0.1:1080")+ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")++ def _boom(*a, **k):+ raise AssertionError("must not attempt urlopen through a socks proxy")++ monkeypatch.setattr(urllib.request, "urlopen", _boom)+ from utils.transformers_version import hf_endpoint_unreachable++ assert hf_endpoint_unreachable(1) is False+++class TestProbeFailsOpenOnNonNetworkErrors:+ """A malformed endpoint or a bug in the probe is not an answer about the network.+ Classifying it as offline silently quarantines every load."""++ @pytest.fixture(autouse = True)+ def _no_ambient_proxy(self, clean_proxy_env):+ pass++ @pytest.mark.parametrize("exc", [ValueError("bad url"), TypeError("bad port"), MemoryError()])+ def test_non_socket_exception_is_inconclusive(self, monkeypatch, exc):+ import urllib.request++ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")+ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: (_ for _ in ()).throw(exc),+ )+ from utils.transformers_version import hf_endpoint_unreachable++ assert hf_endpoint_unreachable(1) is False++ def test_client_side_urlerror_is_inconclusive(self, monkeypatch):+ """urllib reports client-side problems as URLError with a plain string reason+ ("no host given", "unknown url type"). That is not an answer about egress."""+ import urllib.error+ import urllib.request++ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")+ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: (_ for _ in ()).throw(urllib.error.URLError("no host given")),+ )+ from utils.transformers_version import hf_endpoint_unreachable++ assert hf_endpoint_unreachable(1) is False++ def test_socket_reason_urlerror_is_still_offline(self, monkeypatch):+ import socket+ import urllib.error+ import urllib.request++ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")+ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: (_ for _ in ()).throw(+ urllib.error.URLError(socket.gaierror(-2, "Name or service not known"))+ ),+ )+ from utils.transformers_version import hf_endpoint_unreachable++ assert hf_endpoint_unreachable(1) is True++ def test_socket_error_is_still_offline(self, monkeypatch):+ import urllib.request++ monkeypatch.setenv("HF_ENDPOINT", "https://huggingface.co")+ monkeypatch.setattr(+ urllib.request,+ "urlopen",+ lambda *a, **k: (_ for _ in ()).throw(OSError("network unreachable")),+ )+ from utils.transformers_version import hf_endpoint_unreachable++ assert hf_endpoint_unreachable(1) is True++ def test_undeterminable_connect_target_fails_open(self, monkeypatch):+ from utils.utils import hf_tcp_reachable+ monkeypatch.setenv("HF_ENDPOINT", "https://")+ assert hf_tcp_reachable(1.0, "https://") is True+++class TestExplicitBaseEnvIsAlsoScrubbed:+ """child_env(base=...) is what the vision sidecar builds, from a raw os.environ+ copy, so it has to lose the scoped offline flags too."""++ def test_explicit_base_loses_scoped_offline(self, monkeypatch, tmp_path):+ from utils.utils import force_hf_offline+ from utils.hf_cache_settings import get_hf_cache_paths+ from utils.native_path_leases import child_env_without_native_path_secret++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ paths = get_hf_cache_paths()+ with force_hf_offline():+ env = paths.child_env(child_env_without_native_path_secret())+ assert env.get("HF_HUB_OFFLINE") is None+ assert env.get("TRANSFORMERS_OFFLINE") is None+ assert paths.child_env(dict(os.environ)).get("HF_HUB_OFFLINE") is None++ def test_user_set_offline_still_reaches_the_child(self, monkeypatch):+ from utils.utils import force_hf_offline+ from utils.hf_cache_settings import get_hf_cache_paths++ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ paths = get_hf_cache_paths()+ with force_hf_offline():+ assert paths.child_env(dict(os.environ)).get("HF_HUB_OFFLINE") == "1"+++class TestHttpsProxyDefaultPort:+ """An https:// proxy with no explicit port listens on 443, not 80."""++ @pytest.fixture(autouse = True)+ def _no_ambient_proxy(self, clean_proxy_env):+ pass++ def test_https_proxy_defaults_to_443(self, monkeypatch):+ monkeypatch.setenv("HTTPS_PROXY", "https://proxy.internal")+ from utils.utils import hf_connect_target+ assert list(hf_connect_target("https://huggingface.co")) == ["proxy.internal", 443]++ def test_http_proxy_defaults_to_80(self, monkeypatch):+ monkeypatch.setenv("HTTPS_PROXY", "http://proxy.internal")+ from utils.utils import hf_connect_target+ assert list(hf_connect_target("https://huggingface.co")) == ["proxy.internal", 80]+++class TestMetadataReadsUseTheHubProxy:+ """The reachability probe and the metadata reads must agree about egress.++ urllib's default opener ignores ALL_PROXY: ``getproxies`` reports it under an ``all``+ key, but ``ProxyHandler`` only ever dispatches ``<scheme>_open``. huggingface_hub 0.36+ is built on requests, which does honour it. So on a proxy-only machine the probe+ reported "online" through the proxy while every raw config.json / tokenizer_config.json+ / adapter_config.json read went direct and silently failed, dropping the sidecar tier+ decision back to name matching. Served by a real loopback proxy, not a mock.+ """++ @pytest.fixture(autouse = True)+ def _no_ambient_proxy(self, clean_proxy_env, clean_offline_env):+ pass++ @pytest.fixture+ def stub_proxy(self, monkeypatch, tmp_path):+ """A real HTTP proxy on loopback; yields (seen_requests, payload)."""+ import json as _json+ import threading as _threading+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++ seen: list[tuple[str, str]] = []+ payload = {"architectures": ["MinistralForCausalLM"], "model_type": "ministral"}++ class _Handler(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.0"++ def do_GET(self): # noqa: N802+ seen.append((self.command, self.path))+ body = _json.dumps(payload).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ srv = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ _threading.Thread(target = srv.serve_forever, daemon = True).start()+ # Proxy-only egress: the hub name never resolves locally (.invalid, RFC 2606).+ monkeypatch.setenv("HF_ENDPOINT", "http://hub.invalid")+ monkeypatch.setenv("ALL_PROXY", f"http://127.0.0.1:{srv.server_address[1]}")+ monkeypatch.setenv("HF_HOME", str(tmp_path))+ try:+ yield seen, payload+ finally:+ srv.shutdown()++ def _clear_caches(self, monkeypatch):+ import urllib.request++ import utils.transformers_version as tv++ monkeypatch.setattr(tv, "_config_json_cache", {})+ monkeypatch.setattr(tv, "_tokenizer_class_cache", {})+ # urlopen builds its default opener once per process and caches it in _opener, so+ # an earlier test's proxy env would otherwise decide this one's routing.+ monkeypatch.setattr(urllib.request, "_opener", None)++ def test_all_proxy_is_ignored_by_the_default_opener(self, monkeypatch):+ """Guards the premise: urllib alone would never use this proxy."""+ import urllib.request++ monkeypatch.setenv("ALL_PROXY", "http://127.0.0.1:3128")+ assert urllib.request.getproxies().get("all") == "http://127.0.0.1:3128"+ handler = urllib.request.ProxyHandler(urllib.request.getproxies())+ assert not hasattr(handler, "https_open")+ assert not hasattr(handler, "http_open")++ def test_config_json_read_goes_through_the_proxy(self, stub_proxy, monkeypatch):+ seen, payload = stub_proxy+ self._clear_caches(monkeypatch)+ from utils.transformers_version import _load_config_json++ assert _load_config_json("acme/ministral-3b") == payload+ assert seen == [("GET", "http://hub.invalid/acme/ministral-3b/resolve/main/config.json")]++ def test_tokenizer_config_read_goes_through_the_proxy(self, stub_proxy, monkeypatch):+ seen, _ = stub_proxy+ self._clear_caches(monkeypatch)+ from utils.transformers_version import _check_tokenizer_config_needs_v5++ _check_tokenizer_config_needs_v5("acme/ministral-3b")+ assert seen == [+ ("GET", "http://hub.invalid/acme/ministral-3b/resolve/main/tokenizer_config.json"),+ ]++ def test_adapter_config_read_goes_through_the_proxy(self, stub_proxy, monkeypatch):+ seen, _ = stub_proxy+ self._clear_caches(monkeypatch)+ from utils.transformers_version import _remote_lora_base++ _remote_lora_base("acme/ministral-3b")+ assert seen == [+ ("GET", "http://hub.invalid/acme/ministral-3b/resolve/main/adapter_config.json"),+ ]++ def test_no_proxy_bypass_keeps_the_metadata_read_direct(self, monkeypatch, tmp_path):+ """A CIDR NO_PROXY entry requests honours and urllib does not must not be+ re-routed through the proxy by the metadata reads either."""+ import json as _json+ import threading as _threading+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++ proxy_seen: list = []+ hub_seen: list = []+ payload = {"model_type": "ministral"}++ def _make(log, body_bytes):+ class _H(BaseHTTPRequestHandler):+ protocol_version = "HTTP/1.0"++ def do_GET(self): # noqa: N802+ log.append((self.command, self.path))+ self.send_response(200)+ self.send_header("Content-Length", str(len(body_bytes)))+ self.end_headers()+ self.wfile.write(body_bytes)++ def log_message(self, *args):+ pass++ return _H++ body = _json.dumps(payload).encode()+ proxy = ThreadingHTTPServer(("127.0.0.1", 0), _make(proxy_seen, body))+ hub = ThreadingHTTPServer(("127.0.0.1", 0), _make(hub_seen, body))+ for srv in (proxy, hub):+ _threading.Thread(target = srv.serve_forever, daemon = True).start()+ try:+ monkeypatch.setenv("HF_ENDPOINT", f"http://127.0.0.1:{hub.server_address[1]}")+ monkeypatch.setenv("HTTP_PROXY", f"http://127.0.0.1:{proxy.server_address[1]}")+ monkeypatch.setenv("NO_PROXY", "127.0.0.0/8")+ monkeypatch.setenv("HF_HOME", str(tmp_path))+ self._clear_caches(monkeypatch)+ from utils.transformers_version import _load_config_json++ assert _load_config_json("acme/ministral-3b") == payload+ assert proxy_seen == []+ assert hub_seen == [("GET", "/acme/ministral-3b/resolve/main/config.json")]+ finally:+ proxy.shutdown()+ hub.shutdown()+++class TestSlowProxyDoesNotForceOffline:+ """A functional-but-slow proxy is ambiguous, so the shared guard must fail open.++ Otherwise an uncached load through a corporate proxy whose HEAD exceeds the probe+ timeout is turned cache-only, and the hub client's longer request never runs. The+ worker already passes proxy_timeouts_offline=False; the route guard must agree.+ """++ @pytest.fixture(autouse = True)+ def _fresh(self, monkeypatch):+ from utils.utils import reset_hf_reachability_cache++ reset_hf_reachability_cache()+ monkeypatch.delenv("UNSLOTH_OFFLINE_PROBE", raising = False)+ yield+ reset_hf_reachability_cache()++ def test_shared_guard_passes_both_ambiguity_flags_off(self, monkeypatch):+ seen = {}++ def _probe(timeout, **kwargs):+ seen.update(kwargs)+ return False++ import utils.transformers_version as tv++ monkeypatch.setattr(tv, "hf_endpoint_unreachable", _probe)+ from utils.utils import hf_unreachable++ assert hf_unreachable(timeout = 1) is False+ assert seen == {"gateway_errors_offline": False, "proxy_timeouts_offline": False}++ def test_slow_proxy_reads_reachable_not_offline(self, monkeypatch):+ """End to end through the real classifier: a clean timeout behind a proxy."""+ import utils.transformers_version as tv++ monkeypatch.setenv("HF_ENDPOINT", "https://hub.example.test")+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")+ monkeypatch.delenv("NO_PROXY", raising = False)++ class _SlowOpener:+ def open(+ self,+ req,+ timeout = None,+ ):+ raise TimeoutError("proxy is up, upstream is slow")++ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda _url: _SlowOpener())+ # Sanity: the same input IS offline with the flag on, so the flag is what moves it.+ assert tv.hf_endpoint_unreachable(1, proxy_timeouts_offline = True) is True++ from utils.utils import hf_unreachable++ assert hf_unreachable(timeout = 1) is False+++class TestValidateGuardCoversMetadataPreflights:+ """/validate resolves the config under the guard, then runs more remote reads.++ Those preflights (upgrade check, trust-remote-code, sizing, training guard) each+ fetch raw metadata, so leaving them outside the window just moves the stall.+ """++ def test_every_remote_preflight_on_validate_is_wrapped(self):+ """AST check: no bare await asyncio.to_thread(<remote preflight>, ...) remains."""+ import ast+ import pathlib++ # Anchored on __file__: CI runs pytest from the repo root, not studio/backend.+ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ remote = {+ "check_upgrade_for_model",+ "latest_tier_active_for",+ "get_base_model_from_lora_identifier",+ "_guard_chat_load_against_training",+ }+ bare = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ fn = node.func+ if not (isinstance(fn, ast.Attribute) and fn.attr == "to_thread"):+ continue+ if not node.args:+ continue+ first = node.args[0]+ name = getattr(first, "id", None) or getattr(first, "attr", None)+ if name in remote:+ bare.append((name, node.lineno))+ assert bare == [], f"unguarded remote preflight(s): {bare}"+++class TestGuardIsKeyedOnWhatIsRead:+ """A LOCAL adapter path can resolve to a REMOTE base, and the base is what gets+ fetched. Keying the guard on the outer request would hand back a null context while+ the preflight reads the hub."""++ def test_predicate_contract(self):+ """_any_remote: local-only is False, anything unknown or remote is True."""+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ fn = next(+ n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "_any_remote"+ )+ ns: dict = {}+ # is_local_path is imported inside the body; give it a stub module to import from.+ exec(compile(ast.Module([fn], []), "<any_remote>", "exec"), ns)+ import sys+ import types++ stub = types.ModuleType("utils.paths")+ stub.is_local_path = lambda p: p.startswith("/local")+ saved = sys.modules.get("utils.paths")+ sys.modules["utils.paths"] = stub+ try:+ any_remote = ns["_any_remote"]+ assert any_remote("/local/adapter") is False+ assert any_remote("org/model") is True+ assert any_remote(("/local/adapter", "org/base")) is True+ assert any_remote(("/local/a", "/local/b")) is False+ assert any_remote(None) is False+ assert any_remote(()) is False+ # A falsy entry means there is no base to read, not an unknown one: a local+ # model whose config carries base_model=None must not pay the probe.+ assert any_remote((None,)) is False+ assert any_remote(("/local/adapter", None)) is False+ assert any_remote(("/local/adapter", "", "org/base")) is True+ assert any_remote((123,)) is True # unresolvable: guard anyway+ finally:+ if saved is None:+ del sys.modules["utils.paths"]+ else:+ sys.modules["utils.paths"] = saved++ def test_every_guarded_call_passes_what_it_reads(self):+ """AST check: no _offline_guarded call reads config.identifier or a security+ target while keying the guard on the bare outer identifier."""+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)+ bad = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ fn = node.func+ if not (isinstance(fn, ast.Attribute) and fn.attr == "to_thread"):+ continue+ names = [getattr(a, "id", None) or getattr(a, "attr", None) for a in node.args]+ if names[:1] != ["_offline_guarded"] or len(node.args) < 3:+ continue+ targets, read = node.args[1], node.args[2]+ read_name = getattr(read, "id", None) or getattr(read, "attr", None)+ # A read of the resolved config must not be keyed on model_identifier alone.+ if read_name in ("latest_tier_active_for", "_guard_chat_load_against_training"):+ if isinstance(targets, ast.Name):+ bad.append((read_name, node.lineno))+ if read_name == "check_upgrade_for_model":+ if getattr(targets, "id", None) == "model_identifier":+ bad.append((read_name, node.lineno))+ assert bad == [], f"guard keyed on the wrong target: {bad}"+++class TestTransformersOfflineDoesNotSilenceDatasets:+ """TRANSFORMERS_OFFLINE=1 asks for cached MODEL files. Deriving HF_DATASETS_OFFLINE+ from it fails an uncached hf_dataset for the whole job on a machine with egress."""++ def _worker_block(self):+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "core" / "training" / "worker.py").read_text(encoding = "utf-8")+ start = src.index("# Offline auto-detect:")+ return src[start : start + 2200]++ def test_datasets_offline_is_gated_on_the_network_verdict(self):+ block = self._worker_block()+ assert "if _network_offline:" in block+ assert block.index("if _network_offline:") < block.index("HF_DATASETS_OFFLINE")++ def test_env_requested_offline_does_not_set_network_offline(self):+ block = self._worker_block()+ # hf_env_offline() feeds _offline only; the two probes feed _network_offline too.+ assert "_offline = hf_env_offline()" in block+ assert "_offline = _network_offline = hf_dns_dead()" in block+ assert "_offline = _network_offline = hf_endpoint_unreachable(" in block++ def test_hub_and_transformers_offline_are_still_set_either_way(self):+ block = self._worker_block()+ hub = block.index('os.environ["HF_HUB_OFFLINE"] = "1"')+ gate = block.index("if _network_offline:")+ assert hub < gate, "HF_HUB_OFFLINE must not be gated on the network verdict"+++class TestModelConfigPredicateHonoursTheWindow:+ """model_config._env_offline gates detect_audio_type's raw requests.get, which the+ patched hub constant does not cover. During hf_environment_restored_for_spawn the env+ is back to the user's values, so an env-only predicate would fire that 15s request."""++ def test_predicate_is_true_inside_the_spawn_window(self, monkeypatch):+ import threading++ from utils.models.model_config import _env_offline+ from utils.utils import force_hf_offline, hf_environment_restored_for_spawn++ for key in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):+ monkeypatch.delenv(key, raising = False)++ seen = {}+ in_window = threading.Event()+ checked = threading.Event()++ def _spawn_window():+ with hf_environment_restored_for_spawn():+ seen["env_during"] = os.environ.get("HF_HUB_OFFLINE")+ in_window.set()+ checked.wait(5)++ with force_hf_offline():+ assert _env_offline() is True+ t = threading.Thread(target = _spawn_window)+ t.start()+ assert in_window.wait(5)+ seen["predicate_during"] = _env_offline()+ checked.set()+ t.join(5)+ assert _env_offline() is True++ assert seen["env_during"] is None # the user's value really was restored+ assert seen["predicate_during"] is True # but the predicate still reads offline+ assert _env_offline() is False # and it lets go afterwards++ def test_raw_fetch_is_skipped_during_the_window(self, monkeypatch, tmp_path):+ """The stall this prevents: _detect_audio_from_tokenizer's own requests.get is the+ call the gate protects, so drive that function rather than a caller that could+ return earlier for unrelated reasons."""+ import threading++ import utils.models.model_config as mc+ from utils.utils import force_hf_offline, hf_environment_restored_for_spawn++ for key in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):+ monkeypatch.delenv(key, raising = False)+ monkeypatch.setenv("HF_HOME", str(tmp_path))++ calls = []++ class _FakeRequests:+ @staticmethod+ def get(url, **kwargs):+ calls.append(url)+ raise AssertionError("no request may leave during an offline window")++ monkeypatch.setitem(sys.modules, "requests", _FakeRequests)++ # Control: outside any window the gate is open and the fetch is attempted.+ mc._detect_audio_from_tokenizer("org/some-audio-model", None, local_files_only = False)+ assert calls, "the raw fetch is not reached at all, so the gate is untested"+ calls.clear()++ in_window = threading.Event()+ release = threading.Event()++ def _spawn_window():+ with hf_environment_restored_for_spawn():+ in_window.set()+ release.wait(5)++ with force_hf_offline():+ t = threading.Thread(target = _spawn_window)+ t.start()+ assert in_window.wait(5)+ mc._detect_audio_from_tokenizer(+ "org/some-audio-model",+ None,+ local_files_only = False,+ )+ release.set()+ t.join(5)++ assert calls == []+++class TestLocalModelWithRemoteBaseIsGuarded:+ """A local LoRA or GGUF is served from disk, so the load guard stands down for it. Its+ base can still be a hub repo, and resolving the config dereferences that base."""++ def test_helper_engages_for_a_remote_target(self, monkeypatch):+ import utils.models.model_config as mc+ import core.inference.llama_cpp as llama_cpp++ opened = []++ @contextlib.contextmanager+ def _fake_for(target):+ opened.append(target)+ yield++ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable_for", _fake_for)+ with mc._offline_while_reading("org/base"):+ pass+ assert opened == ["org/base"]++ def test_helper_is_a_noop_when_the_guard_is_unavailable(self, monkeypatch):+ """Worker contexts may not be able to import the route-side guard."""+ import builtins++ import utils.models.model_config as mc++ real_import = builtins.__import__++ def _boom(name, *a, **k):+ if name == "core.inference.llama_cpp":+ raise ImportError("not available here")+ return real_import(name, *a, **k)++ monkeypatch.setattr(builtins, "__import__", _boom)+ with mc._offline_while_reading("org/base"):+ pass # must not raise++ def test_local_lora_base_lookup_runs_inside_the_window(self):+ """AST check: the base-derived vision/audio probes sit under the guard."""+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "utils" / "models" / "model_config.py").read_text(+ encoding = "utf-8",+ )+ tree = ast.parse(src)++ guarded = set()+ for node in ast.walk(tree):+ if not isinstance(node, ast.With):+ continue+ if not any(+ isinstance(i.context_expr, ast.Call)+ and getattr(i.context_expr.func, "id", None) == "_offline_while_reading"+ for i in node.items+ ):+ continue+ for inner in ast.walk(node):+ if isinstance(inner, ast.Call):+ name = getattr(inner.func, "id", None)+ if name:+ guarded.add(name)++ for name in ("is_vision_model", "detect_audio_type"):+ assert name in guarded, f"{name} is not inside an _offline_while_reading window"++ def test_no_unguarded_base_vision_probe_remains(self):+ """Every is_vision_model call on a resolved base must be under the guard."""+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "utils" / "models" / "model_config.py").read_text(+ encoding = "utf-8",+ )+ tree = ast.parse(src)++ guarded_lines = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.With) and any(+ isinstance(i.context_expr, ast.Call)+ and getattr(i.context_expr.func, "id", None) == "_offline_while_reading"+ for i in node.items+ ):+ guarded_lines.update(range(node.lineno, (node.end_lineno or node.lineno) + 1))++ bare = []+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call) and getattr(node.func, "id", None) == "is_vision_model"+ ):+ continue+ # Only calls on a name that came from resolved metadata, not on the identifier+ # the caller already guarded.+ arg = node.args[0] if node.args else None+ if (+ getattr(arg, "id", None) in ("base", "check_model")+ and node.lineno not in guarded_lines+ ):+ bare.append(node.lineno)+ assert bare == [], f"unguarded base vision probe at line(s) {bare}"+++class TestMetadataUrlsUseTheDownloadRoute:+ """A Hub-compatible mirror implements /{repo}/resolve/{rev}/{file}, the route+ hf_hub_url builds. /raw is a huggingface.co web route a mirror need not serve, so+ reads against a mirror 404 and the tier falls back to name matching."""++ def test_url_matches_what_the_hub_client_would_build(self, monkeypatch):+ monkeypatch.setenv("HF_ENDPOINT", "https://hf.mirror.internal")+ from utils.transformers_version import _hf_raw_url++ ours = _hf_raw_url("acme/ministral-3b", "config.json")+ assert ours == "https://hf.mirror.internal/acme/ministral-3b/resolve/main/config.json"++ try:+ from huggingface_hub import hf_hub_url+ except Exception:+ return+ theirs = hf_hub_url(+ "acme/ministral-3b",+ "config.json",+ endpoint = "https://hf.mirror.internal",+ )+ assert ours == theirs, f"diverged from the hub client: {ours} vs {theirs}"++ def test_trailing_slash_endpoint_does_not_double_up(self, monkeypatch):+ monkeypatch.setenv("HF_ENDPOINT", "https://hf.mirror.internal/")+ from utils.transformers_version import _hf_raw_url+ assert "//acme" not in _hf_raw_url("acme/m", "config.json").removeprefix("https://")++ def test_no_raw_route_remains_in_the_metadata_readers(self):+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "utils" / "transformers_version.py").read_text(+ encoding = "utf-8",+ )+ assert "/raw/main" not in src+++class TestLocalGgufWithoutABaseSkipsTheProbe:+ """The exporter writes export_metadata.json with a null base_model for a non-LoRA+ checkpoint. Guarding a lookup that never happens would make a wholly local load pay+ the reachability probe."""++ def test_guard_is_not_entered_without_a_base(self):+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "utils" / "models" / "model_config.py").read_text(+ encoding = "utf-8",+ )+ tree = ast.parse(src)++ bad = []+ for node in ast.walk(tree):+ if not isinstance(node, ast.With):+ continue+ for item in node.items:+ ctx = item.context_expr+ if not (+ isinstance(ctx, ast.Call)+ and getattr(ctx.func, "id", None) == "_offline_while_reading"+ ):+ continue+ arg = ctx.args[0] if ctx.args else None+ if getattr(arg, "id", None) != "base":+ continue+ # The base variant must sit under an `if base:` truthiness check.+ guarded_by_if = any(+ isinstance(anc, ast.If)+ and getattr(anc.test, "id", None) == "base"+ and any(node is n or node in ast.walk(n) for n in anc.body)+ for anc in ast.walk(tree)+ if isinstance(anc, ast.If)+ )+ if not guarded_by_if:+ bad.append(node.lineno)+ assert bad == [], f"_offline_while_reading(base) entered unconditionally at {bad}"++ def test_none_target_would_otherwise_be_treated_as_remote(self):+ """Why the check is needed: a null target is classified remote, not local."""+ from utils.paths import is_local_path+ assert is_local_path(None or "") is False+++class TestLocalLoraRemoteBaseIsInTheGuardTargets:+ """A local LoRA's adapter_config points at a remote base. latest_tier_active_for and+ the training guard resolve that base internally, so both local paths passed alone+ would select a null context while the base's metadata is fetched."""++ def test_every_config_keyed_guard_passes_the_base(self):+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)++ checked = 0+ bad = []+ for node in ast.walk(tree):+ if not (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "to_thread"+ ):+ continue+ if not node.args or getattr(node.args[0], "id", None) != "_offline_guarded":+ continue+ targets = node.args[1]+ if not isinstance(targets, ast.Tuple):+ continue+ names = []+ for el in targets.elts:+ if isinstance(el, ast.Attribute):+ names.append(f"{getattr(el.value, 'id', '?')}.{el.attr}")+ elif isinstance(el, ast.Call):+ names.append(getattr(el.func, "id", "?"))+ else:+ names.append(getattr(el, "id", "?"))+ # A tuple keyed on the resolved config must also carry its base.+ if "config.identifier" in names:+ checked += 1+ if not any(n == "getattr" for n in names):+ bad.append((node.lineno, names))+ assert checked >= 4, f"expected the four config-keyed guards, saw {checked}"+ assert bad == [], f"guard target tuple omits the resolved base: {bad}"+++class TestHungProbeHonoursFailOpenBehindAProxy:+ """A thread still alive at the join is ambiguous behind a proxy: connect, TLS and the+ response can each stay under `timeout` while the total runs past it. Direct, a hang+ still means the real hub calls would hang too, so that verdict is unchanged."""++ class _Hang:+ def open(+ self,+ req,+ timeout = None,+ ):+ import threading as _t+ _t.Event().wait()++ def test_behind_a_proxy_the_flag_decides(self, monkeypatch):+ import utils.transformers_version as tv++ monkeypatch.setenv("HF_ENDPOINT", "https://hub.example.test")+ monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")+ monkeypatch.delenv("NO_PROXY", raising = False)+ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda _u: self._Hang())++ assert tv.hf_endpoint_unreachable(1, proxy_timeouts_offline = True) is True+ assert tv.hf_endpoint_unreachable(1, proxy_timeouts_offline = False) is False++ def test_direct_hang_still_reads_unreachable(self, monkeypatch, clean_proxy_env):+ """Unchanged: a direct hang means the load would hang the same way."""+ import utils.transformers_version as tv++ monkeypatch.setenv("HF_ENDPOINT", "https://hub.example.test")+ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda _u: self._Hang())+ assert tv.hf_endpoint_unreachable(1, proxy_timeouts_offline = False) is True++ def test_it_stays_bounded(self, monkeypatch, clean_proxy_env):+ import time as _time++ import utils.transformers_version as tv++ monkeypatch.setenv("HF_ENDPOINT", "https://hub.example.test")+ monkeypatch.setattr(tv, "_hf_proxy_opener", lambda _u: self._Hang())+ t0 = _time.monotonic()+ assert tv.hf_endpoint_unreachable(1) is True+ assert _time.monotonic() - t0 < 5.0+++class TestGuardsShareOneDnsLookup:+ """/validate opens several guards per request. The DNS shortcut is cheap only when+ DNS is fast; on a slow resolver it costs its full timeout per guard."""++ @pytest.fixture(autouse = True)+ def _fresh(self):+ from utils.utils import reset_hf_reachability_cache++ reset_hf_reachability_cache()+ yield+ reset_hf_reachability_cache()++ def test_slow_dns_costs_one_lookup_across_sibling_guards(self, monkeypatch, clean_offline_env):+ """The case that accumulates: DNS answers past its deadline, so the shortcut is+ inconclusive and the probe decides. That probe memoises, so the siblings reuse it."""+ from core.inference.llama_cpp import _hf_unreachable++ dns = []+ probe = []+ monkeypatch.setattr("utils.utils.hf_dns_dead", lambda *a, **k: (dns.append(1), False)[1])+ import utils.transformers_version as tv++ monkeypatch.setattr(+ tv, "hf_endpoint_unreachable", lambda *a, **k: (probe.append(1), True)[1]+ )++ assert _hf_unreachable() is True+ for _ in range(5):+ assert _hf_unreachable() is True+ assert dns == [1], f"DNS shortcut ran {len(dns)} times, expected once"+ assert probe == [1], f"probe ran {len(probe)} times, expected once"++ def test_a_reachable_verdict_is_reused_too(self, monkeypatch, clean_offline_env):+ from core.inference.llama_cpp import _hf_unreachable++ dns = []+ probe = []+ monkeypatch.setattr("utils.utils.hf_dns_dead", lambda *a, **k: (dns.append(1), False)[1])+ import utils.transformers_version as tv++ monkeypatch.setattr(+ tv, "hf_endpoint_unreachable", lambda *a, **k: (probe.append(1), False)[1]+ )++ assert _hf_unreachable() is False+ for _ in range(5):+ assert _hf_unreachable() is False+ assert dns == [1] and probe == [1]++ def test_a_dead_lookup_is_not_recorded_so_recovery_is_immediate(+ self, monkeypatch, clean_offline_env+ ):+ """A dead lookup fails fast, so caching it would only delay recovery by the TTL."""+ from core.inference.llama_cpp import _hf_unreachable++ state = {"dead": True}+ monkeypatch.setattr("utils.utils.hf_dns_dead", lambda *a, **k: state["dead"])+ import utils.transformers_version as tv++ monkeypatch.setattr(tv, "hf_endpoint_unreachable", lambda *a, **k: False)++ assert _hf_unreachable() is True+ state["dead"] = False+ assert _hf_unreachable() is False # no waiting out the TTLdiff --git a/studio/backend/tests/test_offline_inference_parent.py b/studio/backend/tests/test_offline_inference_parent.pyindex 3e9f09bb2fa..05aed804bea 100644--- a/studio/backend/tests/test_offline_inference_parent.py+++ b/studio/backend/tests/test_offline_inference_parent.py@@ -12,6 +12,7 @@ No GPU, no network, no subprocess. Cross-platform.from __future__ import annotations+import importlib.util as _importlib_utilimport osimport sysimport types as _types@@ -25,10 +26,23 @@ _BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)-_loggers_stub = _types.ModuleType("loggers")-_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)-sys.modules.setdefault("loggers", _loggers_stub)-sys.modules.setdefault("structlog", _types.ModuleType("structlog"))++def _module_available(name: str) -> bool:+ """True if the real module can be imported. Probed rather than imported: these stubs+ land in sys.modules for the whole session, so an empty one breaks anything imported+ later that actually uses the module."""+ try:+ return _importlib_util.find_spec(name) is not None+ except (ImportError, ValueError):+ return False+++if not _module_available("loggers"):+ _loggers_stub = _types.ModuleType("loggers")+ _loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+ sys.modules.setdefault("loggers", _loggers_stub)+if not _module_available("structlog"):+ sys.modules.setdefault("structlog", _types.ModuleType("structlog"))# Prefer real httpx if installed (CI installs it). Stub only as fallback.try:import httpx # noqa: F401@@ -207,7 +221,7 @@ class TestTrainingWorkerProbeNoGlobalTimeout:src = Path(_BACKEND_DIR, "core", "training", "worker.py").read_text(encoding = "utf-8")m = re.search(- r'if\s+"HF_HUB_OFFLINE"\s+not\s+in\s+os\.environ\s*:.*?'+ r'if\s+"HF_HUB_OFFLINE"\s+not\s+in\s+os\.environ.*?'r"print\([^)]*HF_HUB_OFFLINE=1[^)]*\)",src,flags = re.DOTALL,@@ -218,6 +232,414 @@ class TestTrainingWorkerProbeNoGlobalTimeout:"training worker still calls socket.setdefaulttimeout; ""concurrent sockets would inherit the probe timeout")+ # The probe now lives in the shared helper (endpoint- and proxy-aware), so the+ # worker must delegate to it rather than resolve a hardcoded host itself.assert (- "threading" in block and "Thread" in block- ), "training worker probe must run on a daemon thread"+ "hf_env_offline" in block+ ), "training worker must honor TRANSFORMERS_OFFLINE before probing"+ assert "hf_dns_dead" in block, "training worker must use the shared DNS helper"+ assert block.index("hf_env_offline()") < block.index(+ "hf_dns_dead()"+ ), "training worker must check explicit offline env before DNS/network probes"+ assert 'gethostbyname("huggingface.co")' not in block, (+ "training worker must not hardcode huggingface.co; a reachable HF_ENDPOINT "+ "mirror would be declared offline"+ )+ assert (+ "proxy_timeouts_offline = False" in block+ ), "training worker must fail open on an ambiguous proxy timeout"++ def test_shared_dns_helper_uses_thread_probe(self):+ """The daemon-thread property moved with the probe; pin it where it now lives."""+ import inspect++ from utils.utils import dns_host_dead++ src = inspect.getsource(dns_host_dead)+ assert ".setdefaulttimeout(" not in src, (+ "shared DNS probe calls socket.setdefaulttimeout; "+ "concurrent sockets would inherit the probe timeout"+ )+ assert "Thread" in src and "daemon" in src, "shared DNS probe must run on a daemon thread"+++class TestInferenceWorkerProbesForItself:+ """child_env deliberately scrubs the parent's scoped offline flag, so the inference+ worker needs its own probe like the training and export workers, or it walks back+ into the retry paths the parent already ruled out."""++ def _block(self):+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "core" / "inference" / "worker.py").read_text(+ encoding = "utf-8",+ )+ start = src.index("# Offline auto-detect")+ # To the end of the block, not a fixed slice: a gate added ahead of it would+ # otherwise push the tail out of the window and pass vacuously.+ return src[start : src.index("\n import warnings", start)]++ def test_the_probe_exists_and_runs_before_activation(self):+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "core" / "inference" / "worker.py").read_text(+ encoding = "utf-8",+ )+ probe = src.index("# Offline auto-detect")+ # Both HF-reading steps the parent's verdict was meant to cover.+ assert probe < src.index("_remote_lora_base(model_name")+ assert probe < src.index("_activate_transformers_version(_base")++ def test_a_user_set_flag_is_never_overridden(self):+ block = self._block()+ assert 'if "HF_HUB_OFFLINE" not in os.environ' in block++ def test_lifetime_flags_use_the_fail_open_verdict(self):+ """Same reasoning as the training worker: these last the whole process, so an+ ambiguous answer must not strand it offline."""+ block = self._block()+ assert "gateway_errors_offline = False" in block+ assert "proxy_timeouts_offline = False" in block++ def test_probe_opt_out_is_honoured(self):+ block = self._block()+ assert "hf_probe_disabled()" in block++ def test_it_fails_open(self):+ block = self._block()+ assert "except Exception:" in block++ def test_it_does_not_force_datasets_offline(self):+ """An inference worker loads no dataset; the training worker's flag is its own."""+ block = self._block()+ assert "HF_DATASETS_OFFLINE" not in block+++class TestWorkerProbesOnlyWhenTheHubIsNeeded:+ """A filesystem-only job never reaches the Hub, so the probe is pure latency: this+ was DNS-only on main for training, and absent entirely for inference."""++ def _load(self, relpath, name):+ import importlib.util+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ spec = importlib.util.spec_from_file_location(name, backend_root / relpath)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod++ def test_training_gate_classifies_each_shape(self, tmp_path):+ w = self._load("core/training/worker.py", "training_worker_gate_probe")+ local = str(tmp_path)++ assert w._training_job_is_local({"model_name": local}) is True+ assert w._training_job_is_local({"model_name": local, "hf_dataset": ""}) is True+ # A remote dataset needs the Hub even with a local model.+ assert w._training_job_is_local({"model_name": local, "hf_dataset": "org/ds"}) is False+ assert w._training_job_is_local({"model_name": "org/model"}) is False+ # Fail closed on anything unresolvable.+ assert w._training_job_is_local({}) is False+ assert w._training_job_is_local({"model_name": None}) is False++ def test_inference_gate_classifies_each_shape(self, tmp_path):+ w = self._load("core/inference/worker.py", "inference_worker_gate_probe")+ local = str(tmp_path)++ assert w._hub_targets_are_local(local) is True+ assert w._hub_targets_are_local(local, None) is True+ assert w._hub_targets_are_local(local, "org/base") is False+ assert w._hub_targets_are_local("org/model") is False+ assert w._hub_targets_are_local(None) is True+ assert w._hub_targets_are_local(123) is False++ def test_inference_gate_reads_a_local_adapter_base_from_disk(self, tmp_path):+ """A local adapter pointing at a REMOTE base still needs the probe, and the base+ is readable without touching the network."""+ import json++ w = self._load("core/inference/worker.py", "inference_worker_gate_adapter")+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"}),+ encoding = "utf-8",+ )+ base, needs_hub = w._recorded_local_base(str(tmp_path))+ assert (base, needs_hub) == ("org/base", False)+ assert w._hub_targets_are_local(str(tmp_path), base) is False++ def test_inference_gate_handles_a_missing_adapter_config(self, tmp_path):+ w = self._load("core/inference/worker.py", "inference_worker_gate_noadapter")+ assert w._recorded_local_base(str(tmp_path)) == (None, False)+ assert w._recorded_local_base("org/model") == (None, False)++ def test_both_probes_sit_behind_the_gate(self):+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ inf = (backend_root / "core" / "inference" / "worker.py").read_text(+ encoding = "utf-8",+ )+ trn = (backend_root / "core" / "training" / "worker.py").read_text(+ encoding = "utf-8",+ )+ assert "not _hub_targets_are_local(" in inf+ assert "not _training_job_is_local(config)" in trn+ # The user's own flag still wins in both.+ assert inf.count('if "HF_HUB_OFFLINE" not in os.environ and (') == 1+ assert trn.count('if "HF_HUB_OFFLINE" not in os.environ and not') == 1+++class TestLocalLoraTrainingJobStillProbes:+ """A local adapter can name a remote base, which activation resolves and later+ training and security code fetches, so the job is not filesystem-only."""++ def _worker(self):+ import importlib.util+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ spec = importlib.util.spec_from_file_location(+ "training_worker_lora_gate",+ backend_root / "core" / "training" / "worker.py",+ )+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod++ def test_local_adapter_with_a_remote_base_is_not_local(self, tmp_path):+ import json++ w = self._worker()+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"}),+ encoding = "utf-8",+ )+ assert w._training_job_is_local({"model_name": str(tmp_path)}) is False++ def test_local_adapter_with_a_local_base_is_local(self, tmp_path):+ import json++ w = self._worker()+ base = tmp_path / "base"+ base.mkdir()+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": str(base)}),+ encoding = "utf-8",+ )+ assert w._training_job_is_local({"model_name": str(tmp_path)}) is True++ def test_a_plain_local_checkpoint_is_still_local(self, tmp_path):+ w = self._worker()+ assert w._training_job_is_local({"model_name": str(tmp_path)}) is True++ def test_a_null_recorded_base_still_probes(self, tmp_path):+ """An explicit null reads the same as a missing key: no base on disk, so the+ resolver falls through to get_base_model_from_lora, which is a Hub call."""+ import json++ w = self._worker()+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": None}),+ encoding = "utf-8",+ )+ assert w._training_job_is_local({"model_name": str(tmp_path)}) is False++ def test_both_workers_agree(self, tmp_path):+ """The two gates must classify the same adapter the same way."""+ import importlib.util+ import json+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"}),+ encoding = "utf-8",+ )+ spec = importlib.util.spec_from_file_location(+ "inference_worker_lora_gate",+ backend_root / "core" / "inference" / "worker.py",+ )+ inf = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(inf)++ base, needs_hub = inf._recorded_local_base(str(tmp_path))+ assert needs_hub is False+ assert inf._hub_targets_are_local(str(tmp_path), base) is False+ assert self._worker()._training_job_is_local({"model_name": str(tmp_path)}) is False+++class TestFullCheckpointBaseKeepsTheProbe:+ """A local full checkpoint's config.json can record a REMOTE base, which+ _resolve_base_model returns and tier activation then reads Hub metadata for, so the+ job is not filesystem-only even though every path on disk is local."""++ def _module(self, relative_path, name):+ import importlib.util+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ spec = importlib.util.spec_from_file_location(name, backend_root / relative_path)+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod++ def _checkpoint(self, tmp_path, config_json):+ import json+ (tmp_path / "config.json").write_text(json.dumps(config_json), encoding = "utf-8")+ return str(tmp_path)++ def test_remote_model_name_keeps_the_probe(self, tmp_path):+ target = self._checkpoint(tmp_path, {"model_name": "org/base"})+ inf = self._module("core/inference/worker.py", "inference_worker_ckpt_gate")+ trn = self._module("core/training/worker.py", "training_worker_ckpt_gate")++ base, needs_hub = inf._recorded_local_base(target)+ assert (base, needs_hub) == ("org/base", False)+ assert inf._hub_targets_are_local(target, base) is False+ assert trn._training_job_is_local({"model_name": target}) is False++ def test_remote_name_or_path_keeps_the_probe(self, tmp_path):+ target = self._checkpoint(tmp_path, {"_name_or_path": "org/base"})+ inf = self._module("core/inference/worker.py", "inference_worker_nop_gate")+ assert inf._recorded_local_base(target) == ("org/base", False)++ def test_a_self_reference_is_not_a_base(self, tmp_path):+ """HF writes the checkpoint's own path into _name_or_path; that is not a base+ and must not cost a probe."""+ target = self._checkpoint(tmp_path, {"_name_or_path": str(tmp_path)})+ inf = self._module("core/inference/worker.py", "inference_worker_self_gate")+ trn = self._module("core/training/worker.py", "training_worker_self_gate")++ assert inf._recorded_local_base(target) == (None, False)+ assert trn._training_job_is_local({"model_name": target}) is True++ def test_an_adapter_base_still_wins_over_config_json(self, tmp_path):+ """Ordering matches the resolver: the adapter's base, not the config.json one."""+ import json++ target = self._checkpoint(tmp_path, {"model_name": "org/from-config"})+ (tmp_path / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/from-adapter"}),+ encoding = "utf-8",+ )+ inf = self._module("core/inference/worker.py", "inference_worker_order_gate")+ assert inf._recorded_local_base(target) == ("org/from-adapter", False)++ def test_a_baseless_adapter_needs_the_hub(self, tmp_path):+ """With no base on disk the resolver falls through to get_base_model_from_lora,+ which is a Hub call, so the gate must fail closed."""+ import json++ (tmp_path / "adapter_config.json").write_text(json.dumps({}), encoding = "utf-8")+ inf = self._module("core/inference/worker.py", "inference_worker_baseless_gate")+ trn = self._module("core/training/worker.py", "training_worker_baseless_gate")++ assert inf._recorded_local_base(str(tmp_path)) == (None, True)+ assert trn._training_job_is_local({"model_name": str(tmp_path)}) is False++ def test_the_gate_agrees_with_the_resolver(self, tmp_path):+ """Anti-drift: this bug was the gate reading less than _resolve_base_model does.+ For every on-disk shape the two must name the same base."""+ import json+ import sys++ backend_root = str(__import__("pathlib").Path(__file__).resolve().parent.parent)+ if backend_root not in sys.path:+ sys.path.insert(0, backend_root)+ from utils.transformers_version import _resolve_base_model, recorded_local_base++ # dir name -> (adapter_config.json, config.json, drop adapter weights in)+ shapes = {+ "adapter": ({"base_model_name_or_path": "org/a"}, None, False),+ "config": (None, {"model_name": "org/c"}, False),+ "name_or_path": (None, {"_name_or_path": "org/n"}, False),+ "both": ({"base_model_name_or_path": "org/a"}, {"model_name": "org/c"}, False),+ "bare": (None, None, False),+ # Adapter-only LoRAs: no JSON at all, so the resolver falls back to the+ # unsloth_<model>_<timestamp> dir-name convention.+ "unsloth_llama-3_1700000000": (None, None, True),+ "unsloth_a_b_1700000000": (None, None, True),+ "plain_adapter_dir": (None, None, True),+ "unsloth_nostamp": (None, None, True),+ }+ for name, (adapter, config, weights) in shapes.items():+ d = tmp_path / name+ d.mkdir()+ if adapter is not None:+ (d / "adapter_config.json").write_text(json.dumps(adapter), encoding = "utf-8")+ if config is not None:+ (d / "config.json").write_text(json.dumps(config), encoding = "utf-8")+ if weights:+ (d / "adapter_model.safetensors").write_bytes(b"")++ base, needs_hub = recorded_local_base(str(d))+ resolved = _resolve_base_model(str(d))+ # The resolver returns the input unchanged when it finds no base.+ assert needs_hub is False, name+ assert (base or str(d)) == resolved, name++ def test_an_adapter_only_lora_keeps_the_probe(self, tmp_path):+ """No JSON on disk, but the dir name resolves to a remote unsloth/... base that+ tier activation reads Hub metadata for."""+ d = tmp_path / "unsloth_llama-3_1700000000"+ d.mkdir()+ (d / "adapter_model.safetensors").write_bytes(b"")++ inf = self._module("core/inference/worker.py", "inference_worker_adapteronly_gate")+ trn = self._module("core/training/worker.py", "training_worker_adapteronly_gate")++ base, needs_hub = inf._recorded_local_base(str(d))+ assert (base, needs_hub) == ("unsloth/llama-3", False)+ assert inf._hub_targets_are_local(str(d), base) is False+ assert trn._training_job_is_local({"model_name": str(d)}) is False+++class TestLoadRouteResolvesConfigOffTheLoop:+ """_load_model_impl is awaited directly by the route, so a guard that can spend+ seconds on DNS plus a HEAD and its TCP fallback must not run inline."""++ def test_the_guard_and_config_resolution_run_in_a_thread(self):+ import ast+ import pathlib++ backend_root = pathlib.Path(__file__).resolve().parent.parent+ src = (backend_root / "routes" / "inference.py").read_text(encoding = "utf-8")+ tree = ast.parse(src)++ impl = next(+ n+ for n in ast.walk(tree)+ if isinstance(n, ast.AsyncFunctionDef) and n.name == "_load_model_impl"+ )+ threaded = set()+ for node in ast.walk(impl):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "to_thread"+ and node.args+ ):+ name = getattr(node.args[0], "id", None)+ if name:+ threaded.add(name)+ assert (+ "_resolve_config" in threaded+ ), "the load guard must be awaited off the event loop, as /validate does"++ # And nothing in that function may enter the guard inline any more.+ bad = [+ n.lineno+ for n in ast.walk(impl)+ if isinstance(n, ast.With)+ and any(+ isinstance(i.context_expr, ast.Call)+ and (getattr(i.context_expr.func, "id", "") or "").startswith(+ "_hf_offline_if_unreachable"+ )+ for i in n.items+ )+ and not any(isinstance(p, ast.FunctionDef) and n in ast.walk(p) for p in ast.walk(impl))+ ]+ assert bad == [], f"guard still entered inline on the event loop at {bad}"diff --git a/studio/backend/tests/test_transformers_version.py b/studio/backend/tests/test_transformers_version.pyindex 7926ace1d37..839380b6df5 100644--- a/studio/backend/tests/test_transformers_version.py+++ b/studio/backend/tests/test_transformers_version.py@@ -64,6 +64,27 @@ from utils.transformers_version import ()[email protected](autouse = True)+def _no_ambient_proxy(monkeypatch):+ """Module-wide: these tests patch urlopen, which a selected proxy opener bypasses.++ Every remote read here goes through ``_hf_urlopen``, which calls ``opener.open`` when+ a proxy applies. A runner with HTTPS_PROXY / ALL_PROXY set would then make a real+ request instead of hitting the patch, so results would track ambient CI connectivity.+ """+ for key in (+ "HTTP_PROXY",+ "HTTPS_PROXY",+ "ALL_PROXY",+ "NO_PROXY",+ "http_proxy",+ "https_proxy",+ "all_proxy",+ "no_proxy",+ ):+ monkeypatch.delenv(key, raising = False)++@pytest.fixture(autouse = True)def _capturable_logger(monkeypatch):"""Make the ``caplog`` assertions independent of test collection order.@@ -217,7 +238,7 @@ class TestRemoteLoraBase:with patch("urllib.request.urlopen", side_effect = fake_urlopen):assert _remote_lora_base("user/adapter") == "org/base"- assert seen["url"].startswith("https://hf.mirror.internal/user/adapter/raw/main/")+ assert seen["url"].startswith("https://hf.mirror.internal/user/adapter/resolve/main/")@staticmethoddef _seed_adapter_cache(@@ -374,6 +395,33 @@ class TestCheckTokenizerConfigNeedsV5:assert seen_auth == [None, "Bearer tok"]assert _tokenizer_class_cache[("org/gated", None)] is False # miss not poisoning+ def test_remote_fetch_respects_hf_endpoint(self, monkeypatch):+ import utils.transformers_version as tv++ monkeypatch.setattr(tv, "_env_offline", lambda: False)+ monkeypatch.setenv("HF_ENDPOINT", "https://hf.mirror.internal/")+ seen = {}++ class _Resp:+ def read(self):+ return json.dumps({"tokenizer_class": "TokenizersBackend"}).encode()++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ def fake_urlopen(req, timeout = 10):+ seen["url"] = req.full_url+ return _Resp()++ monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)+ assert _check_tokenizer_config_needs_v5("org/model") is True+ assert seen["url"] == (+ "https://hf.mirror.internal/org/model/resolve/main/tokenizer_config.json"+ )+# ---------------------------------------------------------------------------# needs_transformers_5 — integration-level@@ -718,6 +766,20 @@ class TestConfigJsonHfCacheFallback:with patch("urllib.request.urlopen", return_value = _hf_response(fresh)):assert _load_config_json("org/model") == fresh # network wins, not stale cache+ def test_remote_fetch_respects_hf_endpoint(self, monkeypatch):+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ monkeypatch.setenv("HF_ENDPOINT", "https://hf.mirror.internal/")+ seen = {}++ def fake_urlopen(req, timeout = 10):+ seen["url"] = req.full_url+ return _hf_response({"model_type": "llama"})++ with patch("urllib.request.urlopen", side_effect = fake_urlopen):+ assert _load_config_json("org/model") == {"model_type": "llama"}+ assert seen["url"] == "https://hf.mirror.internal/org/model/resolve/main/config.json"+def test_network_failure_falls_back_to_cache(self, tmp_path: Path, monkeypatch):cfg = {"model_type": "nemotron_h", "hybrid_override_pattern": "M-M*-"}self._seed_cache(tmp_path, "org/model", cfg)@@ -2527,6 +2589,8 @@ class TestOfflineCacheNotPoisoned:class TestHfEndpointUnreachable:+ # Ambient proxies are cleared module-wide by _no_ambient_proxy.+def test_reachable_returns_false(self, monkeypatch):class _Resp:def __enter__(self):@@ -2567,6 +2631,70 @@ class TestHfEndpointUnreachable:# TLS reached the server: treat as reachable so the load surfaces the cert error.assert hf_endpoint_unreachable(timeout = 2) is False+ def test_connection_refused_is_reachable(self, monkeypatch):+ import urllib.error++ def _refused(*a, **k):+ raise urllib.error.URLError(ConnectionRefusedError("refused"))++ monkeypatch.setattr("urllib.request.urlopen", _refused)+ assert hf_endpoint_unreachable(timeout = 2) is False++ def test_connection_reset_is_reachable(self, monkeypatch):+ """A reset proves the path answered, exactly like the refusal above.++ urllib wraps an OSError raised while sending, so this is the URLError form.+ """+ import urllib.error++ def _reset(*a, **k):+ raise urllib.error.URLError(ConnectionResetError(104, "Connection reset by peer"))++ monkeypatch.setattr("urllib.request.urlopen", _reset)+ assert hf_endpoint_unreachable(timeout = 2) is False++ def test_remote_disconnect_is_reachable(self, monkeypatch):+ """getresponse() is not inside urllib's OSError->URLError wrapper, so a server+ that accepts the HEAD then closes raises http.client.RemoteDisconnected raw --+ and it subclasses ConnectionResetError -> OSError."""+ import http.client++ def _disconnect(*a, **k):+ raise http.client.RemoteDisconnected("Remote end closed connection without response")++ monkeypatch.setattr("urllib.request.urlopen", _disconnect)+ assert hf_endpoint_unreachable(timeout = 2) is False++ def test_real_server_that_accepts_then_closes_is_reachable(self, monkeypatch):+ """End-to-end over a real socket: no mocking of the exception type at all."""+ import socket+ import threading++ 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(4)++ def _accept_then_close():+ try:+ conn, _ = srv.accept()+ except OSError:+ return+ try:+ conn.recv(4096)+ except OSError:+ pass+ conn.close()++ thread = threading.Thread(target = _accept_then_close, daemon = True)+ thread.start()+ monkeypatch.setenv("HF_ENDPOINT", f"http://127.0.0.1:{srv.getsockname()[1]}")+ try:+ assert hf_endpoint_unreachable(timeout = 2) is False+ finally:+ srv.close()+ thread.join(5)+def test_dns_failure_is_unreachable(self, monkeypatch):import socketimport urllib.error@@ -2721,7 +2849,9 @@ class TestLatestTierForces16Bit:"fallback so /validate does not 409 a 4-bit load /load would allow")# requires_trust_remote_code must be resolved before the flip consumes it.- assert body.index("requires_trust_remote_code = any(") < body.index(+ # Anchored on the resolving call, not its expression form: the any() now runs+ # inside _offline_guarded on a worker thread.+ assert body.index("_requires_trust_remote_code_for_model(_t") < body.index("not requires_trust_remote_code")diff --git a/studio/backend/tests/test_tunnel_safe_long_post.py b/studio/backend/tests/test_tunnel_safe_long_post.pyindex 3f8d6e0aa57..0b75a864216 100644--- a/studio/backend/tests/test_tunnel_safe_long_post.py+++ b/studio/backend/tests/test_tunnel_safe_long_post.py@@ -338,7 +338,9 @@ def _stub_unsloth_load_over_a_resident_gguf(route, monkeypatch, *, teardown):"resolve_effective_chat_template_override",lambda model_identifier = None, user_override = None: None,)- monkeypatch.setattr(route, "_hf_offline_if_dns_dead", contextlib.nullcontext)+ # Both guards: the load path resolves its config under the per-model one.+ monkeypatch.setattr(route, "_hf_offline_if_unreachable", contextlib.nullcontext)+ monkeypatch.setattr(route, "_hf_offline_if_unreachable_for", contextlib.nullcontext)monkeypatch.setattr(route, "_mlx_distributed_launch_detected", lambda: False)monkeypatch.setattr(route.ModelConfig,diff --git a/studio/backend/tests/test_validate_offline_guard.py b/studio/backend/tests/test_validate_offline_guard.pynew file mode 100644index 00000000000..48ad4f8af30--- /dev/null+++ b/studio/backend/tests/test_validate_offline_guard.py@@ -0,0 +1,106 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Runtime contract of routes.inference._offline_guarded.++Driven in a clean interpreter rather than in-process: the backend test suite installs+stubs for structlog, fastapi and others into sys.modules at collection time, so loading+the route module in-process passes or fails depending on collection order. One subprocess+keeps the check honest and order-independent. All three assertions share it so the+interpreter and torch import are paid once.+"""++import os+import subprocess+import sys+from pathlib import Path++_BACKEND_ROOT = Path(__file__).resolve().parent.parent++_DRIVER = r"""+import contextlib, importlib.util, sys+sys.path.insert(0, ".")++spec = importlib.util.spec_from_file_location("inference_route_under_test", "routes/inference.py")+route = importlib.util.module_from_spec(spec)+spec.loader.exec_module(route)++events = []++def _tracking_guard():+ events.append("open")+ try:+ yield+ finally:+ events.append("close")++# Patched on the ROUTE module: _offline_guarded deliberately uses the module-level symbol+# so route tests can intercept it, rather than re-importing from llama_cpp.+route._hf_offline_if_unreachable = _tracking_guard++# 1. the wrapped work runs INSIDE the window, not after it closes+def _work(a, b, *, kw):+ assert events == ["open"], events+ return (a, b, kw)++assert route._offline_guarded("org/model", _work, 1, 2, kw = 3) == (1, 2, 3)+assert events == ["open", "close"], events++# 2. a wrapped call may take its own model_identifier kwarg+# (_guard_chat_load_against_training does), so the helper's params are positional-only+events.clear()+seen = {}++def _guard(config, *, model_identifier, hf_token = None):+ seen.update(config = config, model_identifier = model_identifier)++route._offline_guarded("org/model", _guard, "cfg", model_identifier = "org/model")+assert seen == {"config": "cfg", "model_identifier": "org/model"}, seen+assert events == ["open", "close"], events++# 3. an exception inside the window still closes it+events.clear()+try:+ route._offline_guarded("org/model", lambda: (_ for _ in ()).throw(RuntimeError("boom")))+except RuntimeError:+ pass+assert events == ["open", "close"], events++# 4. keyed on what is READ: a local-only read skips the probe, but a local adapter whose+# base resolves remotely still opens the window+import tempfile+with tempfile.TemporaryDirectory() as local:+ events.clear()+ route._offline_guarded(local, lambda: None)+ assert events == [], events++ events.clear()+ route._offline_guarded((local, local), lambda: None)+ assert events == [], events++ events.clear()+ route._offline_guarded((local, "org/base"), lambda: None)+ assert events == ["open", "close"], events++print("OFFLINE_GUARDED_OK")+"""+++def test_offline_guarded_runtime_contract():+ # utf-8 both ways: the child prints Unsloth's non-ASCII banner, and a Windows runner+ # would otherwise decode it as cp1252 and fail on the banner rather than the contract.+ env = {**os.environ, "PYTHONIOENCODING": "utf-8"}+ proc = subprocess.run(+ [sys.executable, "-c", _DRIVER],+ cwd = _BACKEND_ROOT,+ capture_output = True,+ text = True,+ encoding = "utf-8",+ errors = "replace",+ env = env,+ timeout = 300,+ )+ assert (+ "OFFLINE_GUARDED_OK" in proc.stdout+ ), f"rc={proc.returncode}\n--- stdout ---\n{proc.stdout}\n--- stderr ---\n{proc.stderr}"diff --git a/studio/backend/utils/hf_cache_settings.py b/studio/backend/utils/hf_cache_settings.pyindex 07d901a3d2e..961d7fd5c58 100644--- a/studio/backend/utils/hf_cache_settings.py+++ b/studio/backend/utils/hf_cache_settings.py@@ -59,7 +59,11 @@ class HuggingFaceCachePaths:return self.source == "studio"def child_env(self, base: Optional[Mapping[str, str]] = None) -> dict[str, str]:- env = dict(os.environ if base is None else base)+ # Scrub either way: an explicit base is usually the caller's own os.environ+ # copy, so it carries any scoped offline flags an open guard has set.+ from utils.utils import hf_environment_for_spawn, hf_environment_scrubbed++ env = hf_environment_for_spawn() if base is None else hf_environment_scrubbed(base)# Do not rewrite HF_HOME. It also owns HF's token path, and credentials# must not be moved onto a removable cache volume.env["HF_HUB_CACHE"] = str(self.hub_cache)@@ -157,7 +161,8 @@ def child_environment_for_spawn(environment: Mapping[str, str]) -> Iterator[Nonethis short parent-process override atomic through ``Process.start()``."""- with _spawn_env_lock:+ from utils.utils import hf_environment_restored_for_spawn+ with _spawn_env_lock, hf_environment_restored_for_spawn():missing = object()saved_environment: dict[str, str | object] = {}for key, value in environment.items():diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex 7f647e01ace..c6dcb3f9724 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -24,6 +24,7 @@ from utils.models.gguf_metadata import ()import structlogfrom loggers import get_logger+import contextlib as _contextlibimport osimport reimport subprocess@@ -50,13 +51,41 @@ _OFFLINE_TRUE_VALUES = {"1", "true", "yes", "on"}def _env_offline() -> bool:- """True if an HF offline env var is truthy (canonical strip+lower parse, on/true/yes/1)."""+ """True if an HF offline env var is truthy (strip+lower, on/true/yes/1).++ An open force_hf_offline window counts even when the env momentarily disagrees: the+ spawn window restores the user's values, and this gates detect_audio_type's raw+ requests.get, which the patched hub constant does not cover. Function-local import+ avoids a cycle; the env parse is the fallback.+ """+ try:+ from utils.utils import hf_env_offline+ return hf_env_offline()+ except Exception:+ passreturn (os.environ.get("HF_HUB_OFFLINE", "").strip().lower() in _OFFLINE_TRUE_VALUESor os.environ.get("TRANSFORMERS_OFFLINE", "").strip().lower() in _OFFLINE_TRUE_VALUES)+@_contextlib.contextmanager+def _offline_while_reading(target: Optional[str]):+ """Force offline while dereferencing a REMOTE model reached from a LOCAL one.++ The load guard stands down for a local LoRA or GGUF, but its base can be a hub repo and+ the lookups below fetch that base, so a "local" load would resume the retry backoff.+ No-ops on a local target and refcounts when a window is already open.+ """+ try:+ from core.inference.llama_cpp import _hf_offline_if_unreachable_for+ except Exception:+ yield # guard unavailable (worker context): behave as before+ return+ with _hf_offline_if_unreachable_for(target):+ yield++# ── Model size extraction ────────────────────────────────────import re as _re@@ -2955,8 +2984,13 @@ class ModelConfig:try:meta = json.loads(meta_path.read_text(encoding = "utf-8-sig"))base = meta.get("base_model")- if base and is_vision_model(base, hf_token = hf_token):- base_is_vision = True+ # Only when there IS a base to read: the exporter writes null for+ # a non-LoRA checkpoint, and guarding a lookup that never happens+ # would make a wholly local load pay the reachability probe.+ if base:+ with _offline_while_reading(base):+ base_is_vision = bool(is_vision_model(base, hf_token = hf_token))+ if base_is_vision:logger.info(f"GGUF base model '{base}' is a vision model")except Exception as e:logger.debug(f"Could not read export metadata: {e}")@@ -3101,8 +3135,9 @@ class ModelConfig:else:check_model = identifier- vision = is_vision_model(check_model, hf_token = hf_token)- audio_type_val = detect_audio_type(check_model, hf_token = hf_token)+ with _offline_while_reading(check_model):+ vision = is_vision_model(check_model, hf_token = hf_token)+ audio_type_val = detect_audio_type(check_model, hf_token = hf_token)has_audio_in = is_audio_input_type(audio_type_val)display_name = Path(path).name if is_local else identifier.split("/")[-1]diff --git a/studio/backend/utils/transformers_version.py b/studio/backend/utils/transformers_version.pyindex 37744090091..59de2ccad07 100644--- a/studio/backend/utils/transformers_version.py+++ b/studio/backend/utils/transformers_version.py@@ -57,17 +57,87 @@ _OFFLINE_TRUE_VALUES = {"1", "true", "yes", "on"}def _env_offline() -> bool:- """True if an HF offline env var is truthy (canonical strip+lower parse); gates the urllib fetches below."""+ """True if an HF offline env var is truthy; gates the urllib fetches below.++ An open force_hf_offline window counts too: during a spawn the guard briefly restores+ the user's values into os.environ, and an env-only check would then send the very+ request the guard is holding back.+ """+ try:+ from utils.utils import force_hf_offline_active+ if force_hf_offline_active():+ return True+ except Exception:+ passreturn (os.environ.get("HF_HUB_OFFLINE", "").strip().lower() in _OFFLINE_TRUE_VALUESor os.environ.get("TRANSFORMERS_OFFLINE", "").strip().lower() in _OFFLINE_TRUE_VALUES)-def hf_endpoint_unreachable(timeout: int = 3) -> bool:+def _hf_raw_url(model_name: str, filename: str) -> str:+ """Raw model metadata URL for the configured Hub endpoint.++ /resolve, not /raw: that is what hf_hub_url builds, and a mirror implements the+ download route while /raw is a huggingface.co web route it need not serve. Both return+ the same bytes on huggingface.co, so this only widens where the reads work. Small JSON,+ never LFS, so no pointer-vs-content difference.+ """+ from utils.utils import hf_endpoint_url+ return f"{hf_endpoint_url().rstrip('/')}/{model_name}/resolve/main/{filename}"+++def _hf_proxy_opener(url: str):+ """Opener pinned to the Hub client's proxy choice for *url*, or None for the default.++ The default opener ignores ALL_PROXY (``getproxies`` reports an ``all`` key but+ ``ProxyHandler`` only dispatches ``<scheme>_open``) and applies urllib's NO_PROXY rules,+ which miss the CIDR / host:port entries requests honours, so the probe and the reads+ below would disagree about egress. None for a socks proxy: urllib cannot speak it.+ """+ import urllib.parse+ import urllib.request++ try:+ from utils.utils import hf_proxy_for_endpoint, hf_proxy_usable_by_urllib++ proxy = hf_proxy_for_endpoint(url)+ scheme = urllib.parse.urlparse(url).scheme or "https"+ if proxy:+ if not hf_proxy_usable_by_urllib(proxy):+ return None+ return urllib.request.build_opener(urllib.request.ProxyHandler({scheme: proxy}))+ if any(urllib.request.getproxies().get(key) for key in (scheme, "all")):+ # The Hub client bypasses the proxy for this host; force a direct opener so+ # urllib's coarser NO_PROXY parsing cannot send the request through it anyway.+ return urllib.request.build_opener(urllib.request.ProxyHandler({}))+ except Exception:+ pass+ return None+++def _hf_urlopen(req, timeout: int):+ """``urlopen`` through the same proxy huggingface_hub would use for this request."""+ import urllib.request++ opener = _hf_proxy_opener(req.full_url)+ if opener is not None:+ return opener.open(req, timeout = timeout)+ return urllib.request.urlopen(req, timeout = timeout)+++def hf_endpoint_unreachable(+ timeout: int = 3,+ *,+ gateway_errors_offline: bool = True,+ proxy_timeouts_offline: bool = True,+) -> bool:"""Bounded reachability probe to the HF endpoint. A HEAD request runs in a daemon threadjoined with a deadline, so a resolver blackhole cannot block past ~timeout+1s. True if- unreachable. urllib natively honors *_PROXY / NO_PROXY, so this verifies real egress+ unreachable. A clean socket timeout is resolved with a TCP connect, so a slow-but-live+ endpoint is not mistaken for no egress (a hang past the deadline still counts as+ unreachable, since the real hub calls would hang too).+ Egress goes through the same proxy the Hub client would use, so this verifies real egress(the proxy can reach HF), not just that the proxy is up. No ML imports, so it is safe tocall before transformers version activation. Mirrors the probe in export._hf_offline."""import ssl@@ -75,33 +145,104 @@ def hf_endpoint_unreachable(timeout: int = 3) -> bool:import urllib.errorimport urllib.request- endpoint = os.environ.get("HF_ENDPOINT", "https://huggingface.co")- if "://" not in endpoint:- endpoint = "https://" + endpoint+ # Shared normaliser, so an empty or whitespace HF_ENDPOINT falls back to the default+ # hub here exactly as it does in the DNS shortcut, instead of probing "https://".+ try:+ from utils.utils import hf_endpoint_url+ endpoint = hf_endpoint_url()+ except Exception:+ endpoint = (os.environ.get("HF_ENDPOINT") or "").strip() or "https://huggingface.co"+ if "://" not in endpoint:+ endpoint = "https://" + endpoint++ # Pin the Hub client's proxy choice. The default urllib opener ignores all_proxy and+ # can also override a requests-compatible NO_PROXY decision.+ try:+ from utils.utils import hf_proxy_for_endpoint, hf_proxy_usable_by_urllib+ proxy = hf_proxy_for_endpoint(endpoint)+ # urllib cannot speak socks5, so its instant failure is not proof of no egress.+ if proxy and not hf_proxy_usable_by_urllib(proxy):+ return False+ except Exception:+ pass+ opener = _hf_proxy_opener(endpoint)+ _open = opener.open if opener is not None else urllib.request.urlopen- result = {"online": False}+ result = {"online": False, "timed_out": False}def _probe():try:req = urllib.request.Request(endpoint, method = "HEAD")- with urllib.request.urlopen(req, timeout = timeout):+ with _open(req, timeout = timeout):result["online"] = Trueexcept urllib.error.HTTPError as exc:- # The server/proxy answered: reachable unless it is a gateway error.- result["online"] = exc.code not in (502, 503, 504)+ # The server/proxy answered, so we have egress. A gateway error usually means+ # the hub itself is down, which callers scoping offline to one operation want+ # to treat as offline; callers setting a lifetime flag pass+ # gateway_errors_offline=False so a momentary 503 can't strand the process.+ result["online"] = (+ True if not gateway_errors_offline else exc.code not in (502, 503, 504)+ )except urllib.error.URLError as exc:# A TLS/cert failure means we DID reach the server; treat as reachable so the real# load surfaces it (consistent with _is_offline_related_error not retrying TLS).- result["online"] = isinstance(exc.reason, ssl.SSLError)+ # ConnectionError is the whole "the wire answered" family (refused, reset,+ # aborted). A blackhole raises gaierror / ENETUNREACH instead, which are not.+ if isinstance(exc.reason, (ssl.SSLError, ConnectionError)):+ result["online"] = True+ elif isinstance(exc.reason, TimeoutError):+ # Resolved below, off-thread, so the extra probe cannot outrun the join.+ result["timed_out"] = True+ elif isinstance(exc.reason, OSError):+ result["online"] = False # gaierror / network unreachable: a real answer+ else:+ # A string reason ("no host given") is client-side, not an egress answer.+ result["online"] = Trueexcept ssl.SSLError:result["online"] = True- except Exception:+ except TimeoutError:+ result["timed_out"] = True+ except ConnectionError:+ # urllib only wraps OSErrors raised while sending; one from getresponse()+ # arrives raw. Accept-then-close surfaces as RemoteDisconnected, a+ # ConnectionResetError subclass, and a momentary reset must not read as no+ # egress and strand a whole job offline, same reasoning as the 502/503 case.+ result["online"] = True+ except OSError:result["online"] = False+ except Exception:+ # Bad endpoint/proxy, or a bug here. Not a network answer, so fail open.+ result["online"] = Truet = threading.Thread(target = _probe, daemon = True)t.start()t.join(timeout + 1)- return t.is_alive() or not result["online"]+ if t.is_alive():+ # Hung past the deadline. Behind a proxy that is the same ambiguous answer as a+ # clean timeout, since connect, TLS and the response can each stay under `timeout`+ # while the total runs past the join, so lifetime callers fail open here too.+ # Direct, a hang means the real hub calls would hang the same way, so cache-only+ # stays the useful answer.+ try:+ from utils.utils import hf_proxy_configured+ if hf_proxy_configured():+ return proxy_timeouts_offline+ except Exception:+ pass+ return True+ if result["timed_out"]:+ # A slow server still completes the TCP handshake; a blackholed route does not.+ # Bounded separately so the whole probe stays within a predictable deadline.+ try:+ from utils.utils import hf_proxy_configured, hf_tcp_reachable+ if hf_proxy_configured():+ # Through a proxy the handshake only proves the proxy is up, not that it+ # can reach the hub. Lifetime callers fail open on this ambiguous result.+ return proxy_timeouts_offline+ return not hf_tcp_reachable(min(timeout, 2.0), endpoint)+ except Exception:+ return True+ return not result["online"]def _safe_is_file(p: Path) -> bool:@@ -408,6 +549,42 @@ def _is_same_path(value: str, local_path: Path) -> bool:return False+def recorded_local_base(model_name) -> "tuple[str | None, bool]":+ """``(base, needs_hub)`` for what a local checkpoint records on disk.++ Mirrors every offline branch below, so a caller can tell whether a load is+ filesystem-only before paying a network probe: an adapter's+ ``base_model_name_or_path``, else a full checkpoint's ``model_name``/``_name_or_path``+ (a self-reference is not a base), else the ``unsloth_<model>_<timestamp>`` dir-name+ convention for an adapter carrying weights but no JSON. ``needs_hub`` is True when+ only the ``get_base_model_from_lora`` branch could answer, or the read failed.+ """+ root = Path(model_name)+ try:+ adapter_cfg = _safe_is_file(root / "adapter_config.json")+ if adapter_cfg:+ with open(root / "adapter_config.json", encoding = "utf-8-sig") as f:+ base = json.load(f).get("base_model_name_or_path")+ if base:+ return base, False+ if _safe_is_file(root / "config.json"):+ with open(root / "config.json", encoding = "utf-8-sig") as f:+ cfg = json.load(f)+ for _key in ("model_name", "_name_or_path"):+ base = cfg.get(_key)+ if isinstance(base, str) and base and not _is_same_path(base, root):+ return base, False+ # Only reachable without a Hub call when there is no adapter_config.json; with one,+ # the resolver tries get_base_model_from_lora first, which needs_hub already covers.+ if not adapter_cfg and root.name.startswith("unsloth_") and _has_adapter_weights(root):+ parts = root.name.split("_")+ if len(parts) >= 2:+ return "unsloth/" + "_".join(parts[1:-1]), False+ return None, adapter_cfg+ except Exception:+ return None, True++def _resolve_base_model(model_name: str) -> str:"""If *model_name* points to a LoRA adapter, return its base model.@@ -576,14 +753,13 @@ def _remote_lora_base(model_name: str, hf_token: str | None = None) -> str | Nonimport urllib.errorimport urllib.request- endpoint = (os.environ.get("HF_ENDPOINT") or "https://huggingface.co").rstrip("/")- url = f"{endpoint}/{model_name}/raw/main/adapter_config.json"+ url = _hf_raw_url(model_name, "adapter_config.json")headers = {"User-Agent": "unsloth-studio"}if hf_token:headers["Authorization"] = f"Bearer {hf_token}"try:req = urllib.request.Request(url, headers = headers)- with urllib.request.urlopen(req, timeout = 10) as resp:+ with _hf_urlopen(req, timeout = 10) as resp:cfg = json.loads(resp.read().decode())base = cfg.get("base_model_name_or_path")if base:@@ -645,13 +821,13 @@ def _check_tokenizer_config_needs_v5(model_name: str, hf_token: str | None = Non# --- Fall back to fetching from HuggingFace ----------------------------import urllib.request- url = f"https://huggingface.co/{model_name}/raw/main/tokenizer_config.json"+ url = _hf_raw_url(model_name, "tokenizer_config.json")headers = {"User-Agent": "unsloth-studio"}if hf_token:headers["Authorization"] = f"Bearer {hf_token}"try:req = urllib.request.Request(url, headers = headers)- with urllib.request.urlopen(req, timeout = 10) as resp:+ with _hf_urlopen(req, timeout = 10) as resp:data = json.loads(resp.read().decode())tokenizer_class = data.get("tokenizer_class", "")result = tokenizer_class in _TRANSFORMERS_5_TOKENIZER_CLASSES@@ -757,13 +933,13 @@ def _load_config_json(model_name: str, hf_token: str | None = None) -> dict | Noimport urllib.errorimport urllib.request- url = f"https://huggingface.co/{model_name}/raw/main/config.json"+ url = _hf_raw_url(model_name, "config.json")headers = {"User-Agent": "unsloth-studio"}if hf_token:headers["Authorization"] = f"Bearer {hf_token}"try:req = urllib.request.Request(url, headers = headers)- with urllib.request.urlopen(req, timeout = 10) as resp:+ with _hf_urlopen(req, timeout = 10) as resp:cfg = json.loads(resp.read().decode())_config_json_cache[cache_key] = cfgreturn cfgdiff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex e830ea2700b..a81d2a4456b 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.py@@ -5,6 +5,8 @@import osimport structlog+import threading+import timefrom loggers import get_loggerfrom contextlib import contextmanagerfrom pathlib import Path@@ -24,17 +26,423 @@ _HF_OFFLINE_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})def hf_env_offline() -> bool:- """True when HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE requests offline mode.+ """True when HF_HUB_OFFLINE or TRANSFORMERS_OFFLINE asks for offline mode.- Also honors TRANSFORMERS_OFFLINE (hub honors only HF_HUB_OFFLINE) since users set it- to keep transformers loads local.+ TRANSFORMERS_OFFLINE counts too (the hub reads only HF_HUB_OFFLINE), as does an open+ force_hf_offline window: hf_environment_restored_for_spawn briefly puts the user's+ values back, and an env-only check on another thread would then read "online"."""+ if force_hf_offline_active():+ return Truefor var in ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE"):if os.environ.get(var, "").strip().lower() in _HF_OFFLINE_TRUE_VALUES:return Truereturn False+def hf_endpoint_url() -> str:+ """Configured hub endpoint, scheme-normalised. Mirror users point this elsewhere."""+ endpoint = (os.environ.get("HF_ENDPOINT") or "").strip() or "https://huggingface.co"+ return endpoint if "://" in endpoint else "https://" + endpoint+++def hf_endpoint_host() -> str:+ """Host of the configured endpoint; probing huggingface.co would misjudge a mirror."""+ try:+ from urllib.parse import urlparse+ return urlparse(hf_endpoint_url()).hostname or "huggingface.co"+ except Exception:+ return "huggingface.co"+++def _stdlib_proxy_for_url(url: str) -> Optional[str]:+ """requests' proxy selection rebuilt on the stdlib, for installs without requests.++ huggingface_hub 1.x dropped requests, so importing requests.utils raises there and we+ would report "no proxy" on a machine that has one, forcing a working proxy-only setup+ offline. getproxies covers the same sources, incl. macOS sysconf and the Windows registry.+ """+ from urllib.parse import urlparse+ from urllib.request import getproxies, proxy_bypass++ parsed = urlparse(url)+ host = parsed.hostname+ if not host:+ return None+ try:+ if proxy_bypass(host):+ return None+ except Exception:+ pass # a bypass lookup that fails is not a bypass+ proxies = {k.lower(): v for k, v in getproxies().items()}+ scheme = (parsed.scheme or "https").lower()+ # select_proxy order: scheme://host, then scheme, then the all catch-all.+ for key in (f"{scheme}://{host}", scheme, "all"):+ value = proxies.get(key)+ if value:+ return value+ return None+++def hf_proxy_for_endpoint(endpoint: Optional[str] = None) -> Optional[str]:+ """Return the Hub client's proxy choice, including ALL_PROXY and NO_PROXY rules."""+ url = endpoint or hf_endpoint_url()+ try:+ from requests.utils import get_environ_proxies, select_proxy+ return select_proxy(url, get_environ_proxies(url))+ except ImportError:+ # No requests (huggingface_hub 1.x); fall back rather than go blind.+ pass+ except Exception:+ return None+ try:+ return _stdlib_proxy_for_url(url)+ except Exception:+ return None+++def hf_proxy_usable_by_urllib(proxy: Optional[str]) -> bool:+ """True when urllib can route through this proxy.++ urllib speaks only http/https, so a socks5:// proxy makes urlopen raise "unknown url+ type", which reads as no egress even though the Hub client reaches the hub through it.+ """+ if not proxy:+ return True+ from urllib.parse import urlparse++ scheme = urlparse(proxy if "://" in proxy else "http://" + proxy).scheme.lower()+ return scheme in ("http", "https")+++def hf_proxy_configured() -> bool:+ """True when egress goes through a proxy: it resolves the hub host, so local DNS+ proves nothing about reachability and must not declare the hub offline."""+ return hf_proxy_for_endpoint() is not None+++def dns_host_dead(host: str, timeout: float = 2.0) -> bool:+ """True only when host definitively does not resolve. Daemon thread, so a wedged+ resolver cannot block past the deadline and socket.setdefaulttimeout is left alone.++ getaddrinfo, not gethostbyname: the latter is IPv4-only and would call an AAAA-only+ mirror or an IPv6 literal dead.++ A missed deadline is inconclusive, not dead. Slow-but-working DNS (cold cache, DNSSEC,+ a fresh VPN) resolves past 2s, and this shortcut skips the fail-open probe, so calling+ it dead would strand a working machine for a whole job. A truly wedged resolver is+ still caught: the caller's HEAD probe hangs on the same lookup and times out.+ """+ result: list = [None]++ def _probe() -> None:+ import socket as _socket+ try:+ _socket.getaddrinfo(host, None)+ result[0] = False+ except Exception:+ result[0] = True++ t = threading.Thread(target = _probe, daemon = True)+ t.start()+ t.join(timeout)+ return False if result[0] is None else result[0]+++def hf_connect_target(endpoint: Optional[str] = None):+ """(host, port) egress actually has to reach: the proxy when one applies, else the endpoint."""+ from urllib.parse import urlparse++ url = endpoint or hf_endpoint_url()+ parsed = urlparse(url)+ default_port = 443 if parsed.scheme == "https" else 80+ try:+ proxy = hf_proxy_for_endpoint(url)+ if proxy:+ p = urlparse(proxy if "://" in proxy else "http://" + proxy)+ # An https:// proxy with no explicit port listens on 443, not 80.+ return p.hostname, p.port or (443 if p.scheme == "https" else 80)+ except Exception:+ pass+ return parsed.hostname, parsed.port or default_port+++def hf_tcp_reachable(timeout: float = 3.0, endpoint: Optional[str] = None) -> bool:+ """True when a TCP connection to the hub (or its proxy) can be established.++ Separates "no egress" from "slow to answer": a loaded server still handshakes promptly,+ a blackholed route times out. A refusal counts as reachable, since something answered.+ """+ import socket as _socket++ host, port = hf_connect_target(endpoint)+ if not host:+ return True # no target to test: a config problem, not a dead network+ try:+ with _socket.create_connection((host, port), timeout = timeout):+ return True+ except ConnectionRefusedError:+ return True+ except OSError:+ return False+ except Exception:+ return True # not a socket answer (bad port, None host): inconclusive, fail open+++def hf_dns_dead(timeout: float = 2.0) -> bool:+ """Fast offline shortcut: the endpoint's host does not resolve and no proxy applies.++ False whenever a proxy is configured, so proxy-only setups fall through to the real+ reachability probe instead of being wrongly declared offline."""+ if hf_proxy_configured():+ return False+ return dns_host_dead(hf_endpoint_host(), timeout)+++# One load makes many hub calls, so the verdict is shared briefly to avoid re-probing on+# each. Kept short in BOTH directions: a stale "reachable" misses the plug being pulled+# (the case this whole path exists for), and a stale "unreachable" sends a load to the+# cache after the user reconnected, failing it if the model is not cached.+_HF_REACHABILITY_TTL_S = 5.0+_hf_reachability: Optional[tuple] = None+_hf_reachability_lock = threading.Lock()+++def _reachability_fresh(entry) -> bool:+ """True while a cached (timestamp, unreachable) verdict may still be reused."""+ return entry is not None and (time.monotonic() - entry[0]) < _HF_REACHABILITY_TTL_S+++def hf_probe_disabled() -> bool:+ """True when UNSLOTH_OFFLINE_PROBE opts out of the reachability probe."""+ return os.environ.get("UNSLOTH_OFFLINE_PROBE", "1").strip().lower() in {+ "0",+ "false",+ "no",+ "off",+ }+++def hf_reachability_memo() -> Optional[bool]:+ """The memoised verdict while still fresh, else None.++ Lets a caller skip a cheaper-but-still-slow shortcut it has already effectively run:+ one request opens several guards, and repeating a 2s DNS lookup per guard adds up.+ Lock-free like force_hf_offline_active: the tuple read is atomic.+ """+ cached = _hf_reachability+ return cached[1] if _reachability_fresh(cached) else None+++def reset_hf_reachability_cache() -> None:+ """Drop the memoised verdict so the next call re-probes (tests, network changes)."""+ global _hf_reachability+ with _hf_reachability_lock:+ _hf_reachability = None+++def hf_unreachable(timeout: int = 3) -> bool:+ """True when the HF endpoint is unreachable, memoised for _HF_REACHABILITY_TTL_S.++ DNS resolving does not mean the Hub is reachable: a live router with the WAN down, a+ captive portal or a stale DNS cache all answer lookups while every request then burns+ huggingface_hub's retry backoff. Bounded and proxy-aware, as the export path already+ does; UNSLOTH_OFFLINE_PROBE=0 disables it. Fails open, so an unavailable probe reports+ reachable and the load decides as it does today.+ """+ if hf_probe_disabled():+ return False++ global _hf_reachability+ cached = _hf_reachability+ if _reachability_fresh(cached):+ return cached[1]++ with _hf_reachability_lock:+ cached = _hf_reachability+ if _reachability_fresh(cached):+ return cached[1]+ try:+ from utils.transformers_version import hf_endpoint_unreachable++ # Both flags off for the same reason: an ambiguous answer must not force+ # offline. Through a proxy a clean timeout only means slow, and the hub+ # client's longer request may well succeed, so an uncached load must not+ # be turned cache-only here. Matches the worker's call.+ unreachable = hf_endpoint_unreachable(+ timeout,+ gateway_errors_offline = False,+ proxy_timeouts_offline = False,+ )+ except Exception:+ unreachable = False+ _hf_reachability = (time.monotonic(), unreachable)+ return unreachable+++def _reset_hf_sessions() -> None:+ """Drop cached hub sessions so they remount with the current offline adapter."""+ try:+ from huggingface_hub.utils import _http++ for name in ("_get_session_from_cache", "get_session"):+ cache_clear = getattr(getattr(_http, name, None), "cache_clear", None)+ if cache_clear is not None:+ cache_clear()+ reset = getattr(_http, "reset_sessions", None)+ if reset is not None:+ reset()+ except Exception:+ pass+++# Process-global, so nested/concurrent loads refcount rather than restore out from under+# each other.+_force_offline_depth = 0+_force_offline_saved: list = []+_force_offline_saved_env: dict = {}+# Spawn contexts can nest while holding this lock through Process.start().+_force_offline_lock = threading.RLock()++_OFFLINE_ENV_KEYS = ("HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE")+_OFFLINE_CONSTANTS = (+ ("huggingface_hub.constants", ("HF_HUB_OFFLINE",)),+ ("transformers.utils.hub", ("_is_offline_mode", "OFFLINE")),+)+++def force_hf_offline_active() -> bool:+ """True while a force_hf_offline window is open anywhere in this process.++ Lets a concurrent caller tell our forced offline apart from one the user set, so it+ takes its own reference instead of no-opping and losing offline when the first exits.++ Lock-free: hf_environment_restored_for_spawn holds the lock across Process.start(), and+ blocking for that window would stall the operation the guard protects. The int read is+ atomic and the depth rises only after env and constants are already offline.+ """+ return _force_offline_depth > 0+++def force_hf_offline_state() -> tuple[bool, bool]:+ """Return guard ownership and env presence under one lock."""+ with _force_offline_lock:+ return _force_offline_depth > 0, "HF_HUB_OFFLINE" in os.environ+++def _restore_saved_offline_env(environment) -> None:+ """Apply the user's pre-guard offline intent to a child environment mapping."""+ for key in _OFFLINE_ENV_KEYS:+ value = _force_offline_saved_env.get(key)+ if value is None:+ environment.pop(key, None)+ else:+ environment[key] = value+ # Hub ignores TRANSFORMERS_OFFLINE, so preserve that user intent in children.+ if (+ "HF_HUB_OFFLINE" not in environment+ and str(environment.get("TRANSFORMERS_OFFLINE", "")).strip().lower()+ in _HF_OFFLINE_TRUE_VALUES+ ):+ environment["HF_HUB_OFFLINE"] = "1"+++def hf_environment_for_spawn() -> dict[str, str]:+ """Copy the environment without scoped offline values."""+ return hf_environment_scrubbed(os.environ)+++def hf_environment_scrubbed(base) -> dict[str, str]:+ """Copy an env mapping with our scoped offline values replaced by the user's intent.++ A caller that captured os.environ itself would otherwise hand a child the+ HF_HUB_OFFLINE=1 we set for one operation, and the child would stay cache-only for life.+ """+ with _force_offline_lock:+ environment = dict(base)+ if _force_offline_depth > 0:+ _restore_saved_offline_env(environment)+ return environment+++@contextmanager+def hf_environment_restored_for_spawn():+ """Restore user offline values while multiprocessing snapshots ``os.environ``."""+ with _force_offline_lock:+ if _force_offline_depth == 0:+ yield+ return++ missing = object()+ forced_environment = {key: os.environ.get(key, missing) for key in _OFFLINE_ENV_KEYS}+ _restore_saved_offline_env(os.environ)+ try:+ yield+ finally:+ for key, value in forced_environment.items():+ if value is missing:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value+++@contextmanager+def force_hf_offline():+ """Force HF offline for this block, in-process.++ Env vars alone are too late once running: huggingface_hub and transformers read their+ offline constants at import and sessions cache a non-offline adapter. Flip the constants+ and rebuild the sessions so hub calls fail fast. All restored on exit."""+ global _force_offline_depth, _force_offline_saved, _force_offline_saved_env+ import importlib++ with _force_offline_lock:+ if _force_offline_depth == 0:+ saved: list = []+ saved_env: dict = {}+ # Snapshot constants BEFORE forcing the env, else a module first imported+ # inside the window reads the "1" and we would restore it as offline.+ for mod_name, attrs in _OFFLINE_CONSTANTS:+ try:+ mod = importlib.import_module(mod_name)+ except Exception:+ continue+ for attr in attrs:+ if hasattr(mod, attr):+ saved.append((mod, attr, getattr(mod, attr)))+ for key in _OFFLINE_ENV_KEYS:+ saved_env[key] = os.environ.get(key)+ os.environ[key] = "1"+ for mod, attr, _ in saved:+ try:+ setattr(mod, attr, True)+ except Exception:+ pass+ _force_offline_saved = saved+ _force_offline_saved_env = saved_env+ _reset_hf_sessions()+ _force_offline_depth += 1+ try:+ yield+ finally:+ with _force_offline_lock:+ _force_offline_depth -= 1+ if _force_offline_depth == 0:+ for mod, attr, val in _force_offline_saved:+ try:+ setattr(mod, attr, val)+ except Exception:+ pass+ _force_offline_saved = []+ for key, val in _force_offline_saved_env.items():+ if val is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = val+ _force_offline_saved_env = {}+ _reset_hf_sessions()++def st_repo_id_candidates(model_name: str) -> list:"""Repo ids a Sentence-Transformers load may resolve model_name to; a slashless namealso resolves under the sentence-transformers/ namespace, so both are candidates."""