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
Studio: Auto download transport, Xet memory caps, and stall detection on the hub path (#7742)
Daniel Hanf17e04f64a29
diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.pyindex 0a66b33048f..15c11c443ae 100644--- a/studio/backend/hub/schemas/downloads.py+++ b/studio/backend/hub/schemas/downloads.py@@ -26,7 +26,14 @@ class DownloadModelRequest(BaseModel):)use_xet: bool = Field(True,- description = "Use Xet parallel chunked transport. Default True; set False for HTTP Range-resume.",+ description = "Legacy transport flag, superseded by transport_mode. Kept so an older "+ "frontend or a scripted caller keeps working.",+ )+ transport_mode: Optional[Literal["auto", "xet", "http"]] = Field(+ None,+ description = "Transport preference. 'auto' (the default in the UI) lets the backend pick "+ "per machine: it knows this host's RAM, its hf_xet build, and whether Xet has "+ "been failing here. 'xet'/'http' force one. Omitted -> use_xet decides.",)@@ -93,6 +100,8 @@ class TransportCapability(BaseModel):class TransportCapabilities(BaseModel):http: TransportCapabilityxet: TransportCapability+ auto_resolves_to: Literal["xet", "http"] = "xet"+ auto_reason: Optional[str] = Noneclass TransportStatusResponse(BaseModel):@@ -126,7 +135,14 @@ class DownloadDatasetRequest(BaseModel):repo_id: str = Field(..., description = "HuggingFace dataset repo ID")use_xet: bool = Field(True,- description = "Use Xet parallel chunked transport. Default True; set False for HTTP Range-resume.",+ description = "Legacy transport flag, superseded by transport_mode. Kept so an older "+ "frontend or a scripted caller keeps working.",+ )+ transport_mode: Optional[Literal["auto", "xet", "http"]] = Field(+ None,+ description = "Transport preference. 'auto' (the default in the UI) lets the backend pick "+ "per machine: it knows this host's RAM, its hf_xet build, and whether Xet has "+ "been failing here. 'xet'/'http' force one. Omitted -> use_xet decides.",)diff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.pyindex b412a339e9a..9ca78698106 100644--- a/studio/backend/hub/services/datasets/downloads.py+++ b/studio/backend/hub/services/datasets/downloads.py@@ -157,8 +157,15 @@ async def download_dataset_response(repo_id = await asyncio.to_thread(resolve_cached_repo_id_case, repo_id, repo_type = "dataset")key = _download_job_key(repo_id)- use_xet = download_lifecycle.resolve_effective_use_xet(body.use_xet)+ # Off the event loop: resolving "auto" can run the Xet reachability probe, and a blackholed DNS+ # makes that outlast its 3s budget while every other Studio request waits behind it.+ use_xet, transport_reason = await asyncio.to_thread(+ download_lifecycle.resolve_requested_use_xet,+ getattr(body, "transport_mode", None),+ body.use_xet,+ )transport = download_lifecycle.resolve_transport(use_xet)+ logger.info("Download transport for %s: %s (%s)", repo_id, transport, transport_reason)from utils.hf_cache_settings import get_hf_cache_pathscache_paths = get_hf_cache_paths()diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex f431f4497ea..e15e0e55417 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -43,6 +43,45 @@ def resolve_effective_use_xet(use_xet: bool) -> bool:return False+def resolve_requested_use_xet(transport_mode: Optional[str], use_xet: bool) -> tuple[bool, str]:+ """Turn a download request's transport preference into ``(use_xet, reason)``.++ ``transport_mode`` is the current field; ``use_xet`` is the older boolean, still honoured so an+ older frontend or scripted caller keeps working. An explicit "xet" is respected even on a+ machine the health check dislikes, but still gets the memory caps and the stall fallback.+ """+ mode = (transport_mode or "").strip().lower()+ if mode == download_registry.TRANSPORT_HTTP:+ return (False, "HTTP (requested)")+ if mode == download_registry.TRANSPORT_XET:+ return (resolve_effective_use_xet(True), "Xet (requested)")+ if mode == download_registry.TRANSPORT_AUTO:+ return resolve_auto_use_xet()+ resolved = resolve_effective_use_xet(use_xet)+ return (resolved, "Xet" if resolved else "HTTP")+++def resolve_auto_use_xet() -> tuple[bool, str]:+ """Pick a transport for a download the user left on "Auto". Returns ``(use_xet, reason)``.++ Server-side on purpose: only the backend can see this machine's RAM, its hf_xet build, and+ whether Xet has been failing here. Probing IS allowed here, unlike in the capabilities endpoint+ the UI polls on render, because this runs once per download request and the verdict is memoized.+ """+ if not resolve_effective_use_xet(True):+ return (False, "hf_xet is not installed")+ try:+ from utils.hf_xet_fallback import xet_health+ health = xet_health()+ except Exception as exc: # noqa: BLE001 - never let a health probe block a download+ logger.debug("Xet health probe failed, defaulting to Xet: %s", exc)+ return (True, "Xet (health check unavailable)")+ if health is None:+ # Older unsloth_zoo without the health module: no opinion, keep the existing default.+ return (True, "Xet")+ return (bool(health.use_xet), str(health.reason))++def resolve_transport(use_xet: bool) -> str:transport = download_registry.TRANSPORT_XET if use_xet else download_registry.TRANSPORT_HTTPunavailable_reason = download_registry.download_transport_unavailable_reason(transport)@@ -82,6 +121,34 @@ def spawn_worker(env["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"env["HF_HUB_DISABLE_TELEMETRY"] = "1"env["HF_HUB_DISABLE_XET"] = "0" if use_xet else "1"+ if use_xet:+ # hf_xet sizes its reconstruction buffers from constants (up to 8GB stock, 64GB under+ # high-performance mode), not from the machine. Cap them from this host's RAM and cores+ # BEFORE the worker starts: hf_xet reads its config natively at import, so setting them+ # inside the worker is too late. Anything already in `env` was set by the caller, so leave.+ from utils.hf_xet_fallback import xet_env_overrides++ allow_high_perf = os.environ.get(+ "UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE", ""+ ).strip().lower() in (+ "1",+ "true",+ "yes",+ "on",+ )+ if not allow_high_perf:+ # Unconditional, and deliberately not routed through xet_env_overrides(): an older+ # unsloth_zoo has no tuning module (overrides come back empty) and is also the one that+ # sets HF_XET_HIGH_PERFORMANCE=1 at import. `env` is seeded from the parent environment,+ # so that inherited "1" would raise the buffer ceiling to 64GB and void every cap below+ # (xet-core applies the preset AFTER reading the environment). Overwrite, not setdefault.+ for key in ("HF_XET_HIGH_PERFORMANCE", "HF_XET_HP"):+ env[key] = "0"+ for key, value in xet_env_overrides().items():+ if key in ("HF_XET_HIGH_PERFORMANCE", "HF_XET_HP") and not allow_high_perf:+ env[key] = value+ else:+ env.setdefault(key, value)# No token in Unsloth settings: fall back to the backend's own HF_TOKEN so# private repos stay downloadable (needed while inkling repos are private).# Not for a repo an API caller named: that would lend them the owner's identity.@@ -554,6 +621,135 @@ def kill_and_reap_process(pass+def _record_xet_failure(reason: str, logger) -> None:+ """Tell the health tracker a Xet transfer failed here; best-effort, never fatal to a download."""+ try:+ from utils.hf_xet_fallback import record_xet_outcome+ record_xet_outcome(False, reason)+ except Exception as exc: # noqa: BLE001+ logger.debug("could not record Xet outcome: %s", exc)+++def _repo_bytes_on_disk(repo_type, repo_id: str, cache_dir) -> "Optional[int]":+ """Bytes present for this repo, or None when unmeasurable.++ Tells an actual Xet transfer from a job that found everything cached: the worker reports only an+ exit code, and the .transport marker is written before the transfer, so there is no other signal.+ """+ try:+ from utils.hf_xet_fallback import get_hf_download_state+ state = get_hf_download_state([repo_id], repo_type = repo_type, cache_dir = cache_dir)+ except Exception: # noqa: BLE001 - a missing measurement must never fail a download+ return None+ return None if state is None else int(state[0])+++_UNSAMPLED = object()+++def _job_bytes_on_disk(repo_type, repo_id: str, cache_dir, blob_hashes) -> "Optional[int]":+ """Bytes THIS job owns, or None when unmeasurable.++ Scoped to the variant's own blobs when the claim resolved them: the registry lets two+ same-transport GGUF variants of one repo run concurrently over one blobs/ dir, so a repo-wide+ measure would credit a cached no-op worker with its sibling's bytes, clearing a legitimate stall+ streak and flipping an already demoted verdict back to Xet. Non-variant model jobs and dataset+ jobs cannot have a concurrent same-repo sibling (claim() rejects those), so they stay repo-wide.+ """+ if blob_hashes is None:+ return _repo_bytes_on_disk(repo_type, repo_id, cache_dir)+ if not blob_hashes:+ return None # variant job with no resolved hashes: unmeasurable, so never clear the streak+ try:+ return download_registry.completed_blob_bytes(+ repo_type,+ repo_id,+ blob_hashes,+ root = Path(cache_dir) if cache_dir else None,+ )+ except Exception: # noqa: BLE001 - a missing measurement must never fail a download+ return None+++def _record_xet_success(logger) -> None:+ """Tell the health tracker a Xet transfer completed here, which resets the failure streak."""+ try:+ from utils.hf_xet_fallback import record_xet_outcome+ record_xet_outcome(True, "Xet download completed")+ except Exception as exc: # noqa: BLE001+ logger.debug("could not record Xet outcome: %s", exc)+++def _start_stall_watchdog(+ registry: download_registry.DownloadRegistry,+ key: str,+ proc: subprocess.Popen,+ *,+ repo_type: RepoType,+ repo_id: str,+ label: str,+ log_prefix: str,+ logger,+ on_stall: Callable[[str], None],+):+ """Kill *proc* if its download stops making byte-level progress. Returns a stop event, or+ ``None`` when no watchdog could be started.++ SIGKILL rather than a polite signal: the worker traps SIGTERM and exits 130 ("cancelled"), which+ would record a user cancel and skip the HTTP retry. An untrapped kill lands as "error", which is+ what triggers the retry, and the worker's writer is sequential and resumable so the partial+ survives.+ """+ try:+ from utils.hf_xet_fallback import start_watchdog+ except Exception as exc: # noqa: BLE001 - degraded unsloth_zoo: keep the old behaviour+ logger.debug("%s stall watchdog unavailable for %s: %s", log_prefix, label, exc)+ return None++ metadata = registry.get_job_metadata(key)+ cache_dir = getattr(metadata, "hub_cache", None) if metadata is not None else None++ def _on_stall(message: str) -> None:+ logger.warning(+ "%s %s for %s; killing the worker to retry over HTTP", log_prefix, message, label+ )+ on_stall(message)+ try:+ # Kill only: the _watch thread is already reaping this process, so a wait() here would+ # race it for the exit status.+ proc.kill()+ except ProcessLookupError:+ pass # already exited between the stall verdict and the kill+ except Exception:+ logger.exception("%s failed to kill stalled worker for %s", log_prefix, label)++ try:+ return start_watchdog(+ repo_ids = [repo_id],+ repo_type = repo_type,+ cache_dir = cache_dir,+ on_stall = _on_stall,+ child_pid = proc.pid,+ # Scope the measurement to partials this worker holds open; otherwise the shared helper+ # stays repo-wide, child_pid does nothing, and two concurrent same-transport GGUF+ # variants of one repo reset each other's stall timer. This scopes the DATA clock only:+ # before its first byte a variant is still covered by the shared peer-progress check,+ # repo-wide by design so a lock wait behind a live sibling is not read as a hang.+ watch_new_partials_only = True,+ # The shared 90s zero-byte default assumes a single-file download whose pre-byte phase+ # is one HEAD. This worker calls snapshot_download(max_workers=1), so its pre-byte phase+ # is a model_info lookup with retries plus one sequential HEAD per file, which for an+ # already-cached repo is the ENTIRE job with no byte written. A few hundred files on a+ # slow link legitimately exceeds 90s, so a healthy worker would be killed before it+ # started.+ connect_timeout = 600.0,+ xet_disabled = False,+ )+ except Exception as exc: # noqa: BLE001+ logger.debug("%s could not start stall watchdog for %s: %s", log_prefix, label, exc)+ return None++def register_worker(registry: download_registry.DownloadRegistry,key: str,@@ -568,14 +764,36 @@ def register_worker(transport: str,cancel_marker_transport: Optional[str] = None,watch_name: str,+ bytes_before: "Optional[int]" = _UNSAMPLED,) -> bool:if not registry.register_process(key, proc):kill_and_reap_process(proc, label = label, logger = logger)return Falseworker_token = hf_token+ # getattr, not a direct call: test doubles and older registries do not all implement this.+ _get_metadata = getattr(registry, "get_job_metadata", None)+ _metadata = _get_metadata(key) if callable(_get_metadata) else None+ _cache_dir = getattr(_metadata, "hub_cache", None) if _metadata is not None else None+ # The variant's own blobs, so a sibling variant writing into the same repo is not counted as+ # this job's progress. None for job shapes that cannot have a concurrent same-repo sibling.+ _own_blob_hashes = (+ getattr(_metadata, "blob_hashes", frozenset())+ if getattr(_metadata, "variant", None)+ else None+ )+ # Sampled before the worker can write, so "did this job move bytes over Xet" is answerable on+ # exit. launch_worker samples BEFORE spawn(); sampling here would race a fast child that already+ # finalized its blobs, making a real transfer look like a no-op and leaving the streak uncleared.+ _bytes_before = (+ _job_bytes_on_disk(repo_type, repo_id, _cache_dir, _own_blob_hashes)+ if bytes_before is _UNSAMPLED+ else bytes_before+ )def _watch() -> None:+ stalled: list[str] = []+ watchdog_stop = Nonetry:can_retry_http = (transport == download_registry.TRANSPORT_XET@@ -584,6 +802,22 @@ def register_worker()is None)+ # This path had NO stall detection: it relied on the worker's exit code, and a Xet+ # transfer that hangs with no progress and no error never produces one (the frozen+ # progress bar on the model-hub page). Watch the cache for byte-level progress and kill+ # a hung worker; the SIGKILL surfaces as "error", which triggers the HTTP retry below.+ if can_retry_http:+ watchdog_stop = _start_stall_watchdog(+ registry,+ key,+ proc,+ repo_type = repo_type,+ repo_id = repo_id,+ label = label,+ log_prefix = log_prefix,+ logger = logger,+ on_stall = stalled.append,+ )state = finalize_worker_exit(registry,key,@@ -598,6 +832,48 @@ def register_worker(cancel_marker_transport = cancel_marker_transport,defer_error = can_retry_http,)+ if watchdog_stop is not None:+ # Stop measuring once the worker is reaped: post-download work (symlinking,+ # verification) makes no byte-level progress and must not read as a stall.+ watchdog_stop.set()+ if stalled:+ # Exclude only the PRE-BYTE trip: "did not start" means no byte ever arrived, as+ # likely slow metadata, a queue of HEADs or a cache lock as a broken Xet, and two+ # recorded failures pin this machine to HTTP for 24h. Everything else is evidence.+ # "did not resume" fires only after bytes HAVE flowed and is the shape this worker+ # hangs in most often (snapshot_download owns no partial between files); an earlier+ # allow-list keyed on "no progress" silently dropped it. Excluding one wording+ # rather than allowing one also fails cheaply if the shared wording changes.+ #+ # `state == "error"` is the other half: the watchdog appends its verdict before the+ # kill lands, so a worker that completed or was cancelled in that instant would be+ # charged a failure it did not earn -- and on the completed path that also skips the+ # success-clearing below, costing two streak steps the wrong way.+ if state == "error" and "did not start" not in stalled[0]:+ _record_xet_failure(stalled[0], logger)+ else:+ logger.debug(+ "%s not recording a Xet health failure (state=%s): %s",+ log_prefix,+ state,+ stalled[0],+ )+ elif transport == download_registry.TRANSPORT_XET and state == "complete":+ # Clear the streak so "two failures in a row" means in a row: otherwise a stall+ # today and another next week count as consecutive despite every download between+ # them succeeding, pinning Auto to HTTP for no reason. Only a job that actually+ # moved bytes says anything about Xet's health though: a fully cached repo (the UI's+ # re-download on an up-to-date model) exits 0 without touching the network, and+ # clearing an earned demotion on that puts a bad machine back on Xet. Unmeasurable+ # means do not clear: a missed clear costs one streak entry, a wrong clear undoes+ # the demotion.+ bytes_after = _job_bytes_on_disk(repo_type, repo_id, _cache_dir, _own_blob_hashes)+ if (+ _bytes_before is not None+ and bytes_after is not None+ and bytes_after > _bytes_before+ ):+ _record_xet_success(logger)# XET-to-HTTP recovery: when a non-cancelled XET worker fails and# HTTP is available, attempt one automatic retry over HTTP. The# transport check is the recursion guard: an HTTP worker that errors@@ -615,6 +891,8 @@ def register_worker(watch_name = watch_name,)except Exception:+ if watchdog_stop is not None:+ watchdog_stop.set()# finalize_worker_exit is the only thing that clears running/cancelling;# if it raises, force a terminal state so claim() isn't blocked until restart.logger.exception("download watcher crashed for %s", key)@@ -664,6 +942,25 @@ def launch_worker(transport: str,watch_name: str,) -> str:+ # Only the Xet success-recording consumes this, and sampling lazy-loads unsloth_zoo (so torch+ # and transformers) on the request path. An HTTP start skips it entirely.+ _baseline: Optional[int] = None+ if transport == download_registry.TRANSPORT_XET:+ # Before spawn(), deliberately: a small download can finalize its blobs while we are still+ # registering the process, and a later baseline would show no growth for a transfer that+ # really happened, leaving the streak uncleared.+ _get_metadata = getattr(registry, "get_job_metadata", None)+ _metadata = _get_metadata(key) if callable(_get_metadata) else None+ _baseline = _job_bytes_on_disk(+ repo_type,+ repo_id,+ getattr(_metadata, "hub_cache", None) if _metadata is not None else None,+ (+ getattr(_metadata, "blob_hashes", frozenset())+ if getattr(_metadata, "variant", None)+ else None+ ),+ )try:proc = spawn()except Exception as e:@@ -689,6 +986,7 @@ def launch_worker(repo_id = repo_id,transport = transport,watch_name = watch_name,+ bytes_before = _baseline,)return registry.get_job(key).statediff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex 5dc4ebef373..b717e119c6f 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -136,8 +136,15 @@ async def download_model_response(detail = f"Invalid gguf_variant: {variant!r}",)key = _download_job_key(repo_id, variant)- use_xet = download_lifecycle.resolve_effective_use_xet(body.use_xet)+ # Off the event loop: resolving "auto" can run the Xet reachability probe, and a blackholed DNS+ # makes that outlast its 3s budget while every other Studio request waits behind it.+ use_xet, transport_reason = await asyncio.to_thread(+ download_lifecycle.resolve_requested_use_xet,+ getattr(body, "transport_mode", None),+ body.use_xet,+ )transport = download_lifecycle.resolve_transport(use_xet)+ logger.info("Download transport for %s: %s (%s)", repo_id, transport, transport_reason)from utils.hf_cache_settings import get_hf_cache_pathscache_paths = get_hf_cache_paths()diff --git a/studio/backend/hub/tests/conftest.py b/studio/backend/hub/tests/conftest.pyindex 38b6bed9384..254045c8d7a 100644--- a/studio/backend/hub/tests/conftest.py+++ b/studio/backend/hub/tests/conftest.py@@ -104,3 +104,23 @@ sys.modules.setdefault(get_logger = lambda *args, **kwargs: _DummyLogger(),),)+++import pytest++[email protected](autouse = True)+def _reset_optional_module_memo():+ """Forget the shim's memoised optional-module results between tests.++ ``_load_optional`` caches per module name including failures, so without this one test's fake+ module would answer the next test's question.+ """+ try:+ import utils.hf_xet_fallback as _shim+ except Exception: # noqa: BLE001 - hub tests run against stubbed modules+ yield+ return+ _shim._reset_optional_module_cache()+ yield+ _shim._reset_optional_module_cache()diff --git a/studio/backend/hub/tests/test_download_lifecycle.py b/studio/backend/hub/tests/test_download_lifecycle.pyindex 87346573b03..89bb7c381e0 100644--- a/studio/backend/hub/tests/test_download_lifecycle.py+++ b/studio/backend/hub/tests/test_download_lifecycle.py@@ -4,6 +4,8 @@import ioimport logging+import pytest+from hub.services import download_lifecyclefrom hub.utils import download_registry, state_dir@@ -56,6 +58,10 @@ def test_resolve_effective_use_xet(monkeypatch):def test_xet_failure_retries_over_http_for_model_and_dataset(monkeypatch, tmp_path):monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)+ # _ImmediateThread mutates the stdlib threading module, which the shared Zoo watchdog also+ # imports, so it would run INLINE and block in Event.wait() before finalize_worker_exit could+ # set its stop flag. Stub the seam instead.+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", lambda *a, **k: None)register_worker = download_lifecycle.register_workerfor repo_type, repo_id, variant, expected_args in (@@ -115,6 +121,10 @@ def test_xet_failure_retries_over_http_for_model_and_dataset(monkeypatch, tmp_padef test_http_failure_remains_terminal(monkeypatch, tmp_path):monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)+ # _ImmediateThread mutates the stdlib threading module, which the shared Zoo watchdog also+ # imports, so it would run INLINE and block in Event.wait() before finalize_worker_exit could+ # set its stop flag. Stub the seam instead.+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", lambda *a, **k: None)register_worker = download_lifecycle.register_workerregistry = download_registry.DownloadRegistry()key = download_registry.normalize_repo_key("Org/Data")@@ -145,3 +155,284 @@ def test_http_failure_remains_terminal(monkeypatch, tmp_path):watch_name = "dataset-watch",)assert registry.get_job(key).state == "error"+++def _run_completed_xet_worker(monkeypatch, tmp_path, *, bytes_before, bytes_after):+ """Drive one successful Xet worker to completion and report whether success was recorded."""+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", lambda *a, **k: None)++ sizes = iter([bytes_before, bytes_after])+ monkeypatch.setattr(+ download_lifecycle, "_repo_bytes_on_disk", lambda *a, **k: next(sizes, bytes_after)+ )+ recorded = []+ monkeypatch.setattr(+ download_lifecycle, "_record_xet_success", lambda _logger: recorded.append(True)+ )++ registry = download_registry.DownloadRegistry()+ key = download_registry.normalize_job_key("Org/Model")+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ variant = None,+ blob_hashes = frozenset({"blob"}),+ )[0]++ download_lifecycle.register_worker(+ registry,+ key,+ _Proc(0),+ hf_token = None,+ label = "Org/Model",+ log_prefix = "Download",+ logger = logging.getLogger("test"),+ repo_type = "model",+ repo_id = "Org/Model",+ transport = download_registry.TRANSPORT_XET,+ watch_name = "model-watch",+ )+ return recorded+++def test_a_cached_xet_job_does_not_clear_the_failure_streak(monkeypatch, tmp_path):+ """A fully cached repo exits 0 without touching the network (the UI's re-download on an+ up-to-date model), and recording that as a Xet success wipes a correctly earned demotion."""+ recorded = _run_completed_xet_worker(+ monkeypatch, tmp_path, bytes_before = 5_000, bytes_after = 5_000+ )+ assert recorded == []+++def test_a_real_xet_transfer_does_clear_the_failure_streak(monkeypatch, tmp_path):+ """The streak must still reset on a job that actually moved bytes, or "two in a row" is wrong."""+ recorded = _run_completed_xet_worker(monkeypatch, tmp_path, bytes_before = 0, bytes_after = 5_000)+ assert recorded == [True]+++def test_a_sibling_variants_bytes_do_not_count_as_this_jobs_progress(monkeypatch, tmp_path):+ """Two same-transport GGUF variants of one repo may run concurrently over one blobs/ dir, and a+ repo-wide measure credited a cached no-op worker with its sibling's bytes, clearing a legitimate+ stall streak and flipping an already demoted verdict back to Xet."""+ seen = []++ def _fake_completed(+ repo_type,+ repo_id,+ blob_hashes,+ *,+ root = None,+ ):+ seen.append(frozenset(blob_hashes))+ return 1_000 # this variant's own blobs never grow: it was already cached++ monkeypatch.setattr(download_registry, "completed_blob_bytes", _fake_completed)+ monkeypatch.setattr(+ download_lifecycle,+ "_repo_bytes_on_disk",+ lambda *a, **k: pytest.fail("a variant job must not use the repo-wide measure"),+ )+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", lambda *a, **k: None)++ recorded = []+ monkeypatch.setattr(+ download_lifecycle, "_record_xet_success", lambda _logger: recorded.append(True)+ )++ registry = download_registry.DownloadRegistry()+ key = download_registry.normalize_job_key("Org/Model::Q4_K_M")+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ variant = "Q4_K_M",+ blob_hashes = frozenset({"mine"}),+ )[0]++ download_lifecycle.register_worker(+ registry,+ key,+ _Proc(0),+ hf_token = None,+ label = "Org/Model",+ log_prefix = "Download",+ logger = logging.getLogger("test"),+ repo_type = "model",+ repo_id = "Org/Model",+ transport = download_registry.TRANSPORT_XET,+ watch_name = "model-watch",+ )++ assert recorded == [], "a cached variant was credited with a sibling's bytes"+ assert seen and all(h == frozenset({"mine"}) for h in seen), seen+++def _trip_xet_worker(+ monkeypatch,+ tmp_path,+ message,+ rc = 1,+):+ """Run a Xet worker whose watchdog trips with *message*; return the health failures recorded."""+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)++ def _start(registry, key, proc, *, on_stall, **kwargs):+ on_stall(message) # the watchdog tripped+ return None++ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", _start)+ monkeypatch.setattr(download_lifecycle, "spawn_worker", lambda *a, **k: _Proc(0))+ monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)++ recorded = []+ monkeypatch.setattr(download_lifecycle, "_record_xet_failure", lambda m, _l: recorded.append(m))++ registry = download_registry.DownloadRegistry()+ key = download_registry.normalize_job_key("Org/Model")+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ variant = None,+ blob_hashes = frozenset({"blob"}),+ )[0]++ _register = download_lifecycle.__dict__["register_worker"]+ _real = getattr(download_lifecycle, "_REAL_REGISTER", None)+ (_real or _register)(+ registry,+ key,+ _Proc(rc, b"killed" if rc else b""),+ hf_token = None,+ label = "Org/Model",+ log_prefix = "Download",+ logger = logging.getLogger("test"),+ repo_type = "model",+ repo_id = "Org/Model",+ transport = download_registry.TRANSPORT_XET,+ watch_name = "model-watch",+ )+ return recorded+++def test_a_data_phase_stall_is_recorded_against_the_machine(monkeypatch, tmp_path):+ """A frozen partial with bytes already flowing is genuinely Xet misbehaving."""+ monkeypatch.setattr(+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False+ )++ assert _trip_xet_worker(+ monkeypatch,+ tmp_path,+ "Download appears stalled (xet transport) -- no progress for 30s",+ ), "a real data-phase stall must still be recorded"+++def test_a_pre_byte_trip_does_not_poison_the_machines_health_record(monkeypatch, tmp_path):+ """Two recorded failures pin this machine to HTTP for 24h, and "did not start" means not one+ byte arrived, as likely slow metadata, a queue of HEADs or a cache lock as a broken Xet. The+ HTTP retry still happens either way."""+ monkeypatch.setattr(+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False+ )+ assert (+ _trip_xet_worker(+ monkeypatch,+ tmp_path,+ "Download did not start (xet transport) -- no data after 600s",+ )+ == []+ )+++def test_a_post_byte_hang_between_files_is_recorded(monkeypatch, tmp_path):+ """ "did not resume" fires only after bytes HAVE flowed, so it is real Xet evidence, and it is+ the shape this worker hangs in most often since snapshot_download owns no partial between+ files. An earlier allow-list keyed on "no progress" silently dropped it."""+ monkeypatch.setattr(+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False+ )+ assert _trip_xet_worker(+ monkeypatch,+ tmp_path,+ "Download did not resume (xet transport) -- no data for 600s",+ ), "a post-byte Xet hang was not recorded against the machine"+++def test_the_xet_baseline_is_sampled_before_the_worker_spawns(monkeypatch, tmp_path):+ """A fast child can finalize its blobs while we are still registering the process, so a later+ baseline shows no growth for a real transfer: the streak is never cleared and two stalls either+ side of it read as consecutive, demoting Auto for 24h."""+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", lambda *a, **k: None)++ order = []+ sizes = iter([0, 5_000]) # nothing before the spawn, bytes present after it++ monkeypatch.setattr(+ download_lifecycle,+ "_job_bytes_on_disk",+ lambda *a, **k: (order.append("sample"), next(sizes, 5_000))[1],+ )+ recorded = []+ monkeypatch.setattr(download_lifecycle, "_record_xet_success", lambda _l: recorded.append(True))++ registry = download_registry.DownloadRegistry()+ key = download_registry.normalize_job_key("Org/Model")+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ variant = None,+ blob_hashes = frozenset({"blob"}),+ )[0]++ def _spawn():+ order.append("spawn")+ return _Proc(0)++ download_lifecycle.launch_worker(+ registry,+ key,+ spawn = _spawn,+ hf_token = None,+ label = "Org/Model",+ log_prefix = "Download",+ logger = logging.getLogger("test"),+ repo_type = "model",+ repo_id = "Org/Model",+ transport = download_registry.TRANSPORT_XET,+ watch_name = "model-watch",+ )++ assert order[0] == "sample" and order[1] == "spawn", order+ assert recorded == [True], "a real transfer did not clear the failure streak"+++def test_a_stall_verdict_racing_a_completed_worker_is_not_recorded(monkeypatch, tmp_path):+ """The watchdog appends its verdict BEFORE the kill lands, so a worker that completed in that+ instant would be charged a failure it did not earn, and on the completed path that also skips+ the success-clearing: two streak steps the wrong way from one race."""+ monkeypatch.setattr(+ download_lifecycle, "_REAL_REGISTER", download_lifecycle.register_worker, raising = False+ )+ assert (+ _trip_xet_worker(+ monkeypatch,+ tmp_path,+ "Download appears stalled (xet transport) -- no progress for 30s",+ rc = 0, # the worker actually finished+ )+ == []+ ), "a completed worker was charged a stall it raced"diff --git a/studio/backend/hub/utils/download_registry.py b/studio/backend/hub/utils/download_registry.pyindex 760ef6b01c0..367aa3e1448 100644--- a/studio/backend/hub/utils/download_registry.py+++ b/studio/backend/hub/utils/download_registry.py@@ -58,10 +58,12 @@ logger = get_logger(__name__)from hub.utils.hf_cache_state import (INCOMPLETE_SUFFIX,+ TRANSPORT_AUTO,TRANSPORT_HTTP,TRANSPORT_XET,TRANSPORT_MARKER_NAME,VALID_TRANSPORTS,+ VALID_TRANSPORT_MODES,has_active_incomplete_blobs,iter_repo_cache_dirs,iter_active_repo_cache_dirs,@@ -81,10 +83,30 @@ class DownloadTransportCapability:class DownloadTransportCapabilities:http: DownloadTransportCapabilityxet: DownloadTransportCapability+ # What "auto" would pick right now, and why, so the picker can say+ # "Auto (HTTP -- Xet stalled twice on this machine)" instead of just "Auto".+ auto_resolves_to: str = TRANSPORT_XET+ auto_reason: Optional[str] = None-def get_download_transport_capabilities() -> DownloadTransportCapabilities:+def get_download_transport_capabilities(*, probe: bool = False) -> DownloadTransportCapabilities:xet_available = importlib.util.find_spec("hf_xet") is not None+ auto_transport = TRANSPORT_XET if xet_available else TRANSPORT_HTTP+ auto_reason: Optional[str] = None+ if xet_available:+ try:+ from utils.hf_xet_fallback import xet_health++ # Default probe = False: the UI polls this endpoint, so it answers from the cached+ # verdict and local signals. The download-start path opts in, since otherwise a host+ # with an unreachable CAS and no recorded failures yet would learn only by stalling.+ health = xet_health(probe = probe)+ if health is not None:+ auto_transport = TRANSPORT_XET if health.use_xet else TRANSPORT_HTTP+ auto_reason = str(health.reason)+ except Exception:+ # No opinion: keep the optimistic default; the download-time ladder still recovers.+ passreturn DownloadTransportCapabilities(http = DownloadTransportCapability(available = True),xet = DownloadTransportCapability(@@ -93,6 +115,8 @@ def get_download_transport_capabilities() -> DownloadTransportCapabilities:if xet_availableelse "Xet transport is unavailable because hf_xet is not installed.",),+ auto_resolves_to = auto_transport,+ auto_reason = auto_reason,)@@ -543,7 +567,17 @@ def prepare_cache_for_transport(the environment. Markers are written for the new mode before returning."""if mode not in VALID_TRANSPORTS:- raise ValueError(f"Invalid transport mode: {mode!r}")+ if mode == TRANSPORT_AUTO:+ # "auto" is a request preference, not a cache writer: it must be resolved to xet/http+ # before reaching this layer. Naming it turns "invalid transport" into the actual bug.+ raise ValueError(+ f"{TRANSPORT_AUTO!r} must be resolved to a concrete transport before preparing the "+ f"cache; expected one of {sorted(VALID_TRANSPORTS)}"+ )+ raise ValueError(+ f"Invalid transport mode: {mode!r} (transports: {sorted(VALID_TRANSPORTS)}, "+ f"request modes: {sorted(VALID_TRANSPORT_MODES)})"+ )root = hf_cache_root(create = True) if root is None else hf_cache_root(create = True, root = root)if root is None:return 0diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.pyindex c5d47d27091..09c015780bd 100644--- a/studio/backend/hub/utils/hf_cache_state.py+++ b/studio/backend/hub/utils/hf_cache_state.py@@ -15,6 +15,11 @@ EXIT_CANCELLED = 130TRANSPORT_HTTP = "http"TRANSPORT_XET = "xet"VALID_TRANSPORTS = frozenset({TRANSPORT_HTTP, TRANSPORT_XET})+# A *request* preference, deliberately NOT in VALID_TRANSPORTS: "auto" is resolved to a real+# transport before anything is spawned, and the on-disk .transport marker must keep naming the+# writer that produced a partial, or a resume picks the wrong strategy.+TRANSPORT_AUTO = "auto"+VALID_TRANSPORT_MODES = frozenset({TRANSPORT_HTTP, TRANSPORT_XET, TRANSPORT_AUTO})TRANSPORT_MARKER_NAME = ".transport"INCOMPLETE_SUFFIX = ".incomplete"diff --git a/studio/backend/hub/workers/hf_download.py b/studio/backend/hub/workers/hf_download.pyindex 9ff394b0094..ca37b2605b8 100644--- a/studio/backend/hub/workers/hf_download.py+++ b/studio/backend/hub/workers/hf_download.py@@ -732,6 +732,31 @@ def _download_dataset(repo_id: str, hf_token: str | None, mode: str) -> None:)+def _force_stall_for_tests(repo_id: str, repo_type: str) -> None:+ """Test-only fault injection: hang the Xet attempt so the stall watchdog can be exercised.++ Never set in production. ``unsloth_zoo.hf_xet_fallback`` has the same hook for its own spawns,+ but the hub worker is a different process launched a different way, so without this there is no+ way to hang a *real* hub download on demand. A partial has to exist and stay open: the watchdog+ counts only ``.incomplete`` files held open by the child it is watching.+ """+ from huggingface_hub.constants import HF_HUB_CACHE++ blobs = os.path.join(HF_HUB_CACHE, f"{repo_type}s--" + repo_id.replace("/", "--"), "blobs")+ handle = None+ try:+ os.makedirs(blobs, exist_ok = True)+ handle = open(os.path.join(blobs, "xet-force-stall.incomplete"), "wb")+ handle.write(b"\0" * 4096)+ handle.flush()+ except OSError:+ pass+ print("UNSLOTH_HF_XET_FORCE_STALL: hanging the xet attempt", file = sys.stderr, flush = True)+ while True:+ # `handle` stays referenced by this frame, which never returns, so the partial stays open.+ time.sleep(3600)++def main() -> None:parser = argparse.ArgumentParser(description = "HuggingFace Hub download worker")parser.add_argument("--repo-id", required = True)@@ -746,6 +771,9 @@ def main() -> None:hf_token = os.environ.get("HF_TOKEN") or None+ if args.transport == "xet" and os.environ.get("UNSLOTH_HF_XET_FORCE_STALL") == "1":+ _force_stall_for_tests(args.repo_id, "dataset" if args.dataset else "model")+try:if args.dataset:_download_dataset(args.repo_id, hf_token, args.transport)diff --git a/studio/backend/main.py b/studio/backend/main.pyindex 3541704c6ed..f31b00f1f1c 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1397,8 +1397,11 @@ def studio_release_notes("/api/studio/download-transport-capabilities",response_model = TransportCapabilities,)-def studio_download_transport_capabilities(_current_subject: str = Depends(get_current_subject)):- return asdict(get_download_transport_capabilities())+def studio_download_transport_capabilities(+ probe: bool = False, _current_subject: str = Depends(get_current_subject)+):+ # Sync def, so FastAPI runs this in the threadpool and an opted-in probe cannot block the loop.+ return asdict(get_download_transport_capabilities(probe = probe))@app.post("/api/shutdown")diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex f4431afbdf5..842ac9a30df 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -58,6 +58,56 @@ def pytest_addoption(parser):# E2E server fixtures[email protected](scope = "session", autouse = True)+def _isolate_xet_health_home(tmp_path_factory):+ """Point HF_HOME at a temp dir for the whole session, before any server is spawned.++ Session scope is load-bearing: pytest builds higher-scoped fixtures first, so setting HF_HOME+ function-scoped landed AFTER ``studio_server`` snapshotted os.environ, leaving that server+ rewriting the developer's real unsloth_xet_health.json.+ """+ from _pytest.monkeypatch import MonkeyPatch++ from huggingface_hub import constants as hf_constants++ mp = MonkeyPatch()+ # Pin these to what the hub resolved from the REAL environment before moving HF_HOME, which+ # also defaults HF_HUB_CACHE, HF_XET_CACHE and HF_TOKEN_PATH: moving it alone would send the+ # E2E server to an empty cache and token store, so a ~1.1GB GGUF redownload inside the 120s+ # startup deadline and no credentials for a private --unsloth-model.+ mp.setenv("HF_HUB_CACHE", hf_constants.HF_HUB_CACHE)+ mp.setenv("HF_TOKEN_PATH", hf_constants.HF_TOKEN_PATH)+ xet_cache = getattr(hf_constants, "HF_XET_CACHE", None)+ if xet_cache:+ mp.setenv("HF_XET_CACHE", xet_cache)+ mp.setenv("HF_HOME", str(tmp_path_factory.mktemp("xet_health_home")))+ yield+ mp.undo()++[email protected](autouse = True)+def _isolate_xet_health_state():+ """Keep the persisted Xet health verdict out of the developer's real HF home.++ The verdict is sticky across sessions (two consecutive failures pin a machine to HTTP for 24h),+ so a machine that has genuinely stalled starts the ladder on HTTP inside a test expecting Xet.+ That reproduced: `test_shim_injects_studio_prepare_on_http_retry` saw the fallback without the+ Xet attempt it asserts. Clean CI runners hide it, developer machines do not.+ """+ # Load it the way the shim does: a bare `from unsloth_zoo import ...` raises NotImplementedError+ # on a CPU-only host (its __init__ runs accelerator detection), so a plain import would skip+ # this isolation on exactly the hosts the shim's GPU-init retry exists to support.+ from utils.hf_xet_fallback import _load_optional++ hf_xet_health = _load_optional("unsloth_zoo.hf_xet_health")+ if hf_xet_health is None:+ yield+ return+ hf_xet_health.clear_xet_health()+ yield+ hf_xet_health.clear_xet_health()++@pytest.fixture(autouse = True)def _no_background_model_scan(monkeypatch):"""Keep the /v1 admission hook from scanning the real HF cache during tests.@@ -220,3 +270,17 @@ def stub_embeddings(monkeypatch):)monkeypatch.setattr(embeddings, "warm", lambda model_name = None: None)return dim++[email protected](autouse = True)+def _reset_optional_module_memo():+ """Forget the shim's memoised optional-module results between tests.++ ``_load_optional`` caches per module name including failures, so without this one test's fake+ module would answer the next test's question.+ """+ import utils.hf_xet_fallback as _shim++ _shim._reset_optional_module_cache()+ yield+ _shim._reset_optional_module_cache()diff --git a/studio/backend/tests/test_hf_xet_fallback.py b/studio/backend/tests/test_hf_xet_fallback.pyindex a037ea25794..23c4624aea3 100644--- a/studio/backend/tests/test_hf_xet_fallback.py+++ b/studio/backend/tests/test_hf_xet_fallback.py@@ -363,6 +363,131 @@ def test_retries_under_light_gpu_init_when_import_fails(monkeypatch):sys.modules["utils.hf_xet_fallback"] = saved_shim+def test_a_worker_spawned_during_the_gpu_init_retry_does_not_inherit_the_override(monkeypatch):+ """The shim sets UNSLOTH_ZOO_DISABLE_GPU_INIT=1 process-wide while it retries an optional+ import, and unsloth_zoo answers that flag with STUB triton and bitsandbytes, so a child that+ inherited it would run for life against no-ops and never clear it."""+ import importlib+ import os++ from utils.child_stdio import utf8_child_env++ monkeypatch.delenv("UNSLOTH_ZOO_DISABLE_GPU_INIT", raising = False)+ child_envs = []++ class _SpawnsAWorkerMidImport:+ def find_spec(+ self,+ name,+ path = None,+ target = None,+ ):+ if name == "unsloth_zoo":+ # A concurrent request lands mid-retry and spawns its worker right here.+ child_envs.append(utf8_child_env())+ raise NotImplementedError("Unsloth cannot find any torch accelerator")+ return None++ finder = _SpawnsAWorkerMidImport()+ saved = {+ k: v+ for k, v in list(sys.modules.items())+ if k == "unsloth_zoo" or k.startswith("unsloth_zoo.")+ }+ for k in saved:+ del sys.modules[k]+ saved_shim = sys.modules.pop("utils.hf_xet_fallback", None)+ sys.meta_path.insert(0, finder)+ try:+ shim = importlib.import_module("utils.hf_xet_fallback")+ shim.DownloadStallError # drives the load: plain attempt, then the retry+ assert len(child_envs) == 2, child_envs+ # The retry is the attempt that sets it; neither child may see it.+ assert os.environ.get("UNSLOTH_ZOO_DISABLE_GPU_INIT") is None+ for env in child_envs:+ assert "UNSLOTH_ZOO_DISABLE_GPU_INIT" not in env, env+ assert env["PYTHONIOENCODING"] == "utf-8"+ finally:+ sys.meta_path.remove(finder)+ sys.modules.pop("utils.hf_xet_fallback", None)+ sys.modules.update(saved)+ if saved_shim is not None:+ sys.modules["utils.hf_xet_fallback"] = saved_shim+++def test_a_spawn_cannot_overlap_the_loader_env_override_window():+ """multiprocessing spawn copies the parent's LIVE os.environ and takes no env argument, so the+ only way to keep the shim's transient UNSLOTH_ZOO_DISABLE_GPU_INIT out of a worker is that a+ spawn cannot start while a loader holds it; a child that inherits it silently trains against+ unsloth_zoo's stub triton and bitsandbytes. Structural on purpose: it asserts the two share one+ lock rather than trying to hit a microsecond window by timing."""+ import threading++ from utils.hf_cache_settings import child_environment_for_spawn++ loader_holds = threading.Event()+ release_loader = threading.Event()+ spawn_started = threading.Event()+ spawn_entered = threading.Event()++ def _loader():+ with xf.env_override_barrier():+ loader_holds.set()+ release_loader.wait(5.0)++ def _spawner():+ spawn_started.set()+ with child_environment_for_spawn({}):+ spawn_entered.set()++ t_loader = threading.Thread(target = _loader, daemon = True)+ t_loader.start()+ assert loader_holds.wait(5.0), "loader never took the barrier"++ t_spawn = threading.Thread(target = _spawner, daemon = True)+ t_spawn.start()+ assert spawn_started.wait(5.0)+ try:+ assert not spawn_entered.wait(0.5), "a spawn started inside the loader override window"+ finally:+ release_loader.set()+ assert spawn_entered.wait(5.0), "the spawn never proceeded after the loader let go"+ t_loader.join(5.0)+ t_spawn.join(5.0)+++def test_the_spawn_barrier_is_reentrant():+ """child_environment_for_spawn nests (an inference respawn inside a training start), which its+ RLock _spawn_env_lock allows, so the barrier it now takes alongside must be reentrant too or the+ inner enter deadlocks. Bounded on purpose: a plain Lock hangs the suite rather than failing."""+ import threading++ from utils.hf_cache_settings import child_environment_for_spawn++ done = threading.Event()++ def _nest():+ with child_environment_for_spawn({"HF_HUB_CACHE": "outer"}):+ with child_environment_for_spawn({"HF_HUB_CACHE": "inner"}):+ pass+ done.set()++ worker = threading.Thread(target = _nest, daemon = True)+ worker.start()+ assert done.wait(10.0), "a nested spawn deadlocked on the loader barrier"+ worker.join(5.0)+++def test_an_operator_set_gpu_init_override_still_reaches_the_child(monkeypatch):+ """Only the loader's own transient value is dropped. Someone who exported the flag themselves+ on a GPU-less box meant it, and their children must keep it."""+ from utils.child_stdio import utf8_child_env++ monkeypatch.setenv("UNSLOTH_ZOO_DISABLE_GPU_INIT", "1")+ monkeypatch.setattr(xf, "_gpu_init_override_depth", 0, raising = False)+ assert utf8_child_env()["UNSLOTH_ZOO_DISABLE_GPU_INIT"] == "1"++def test_importing_child_should_disable_xet_stays_light(monkeypatch):"""Regression guard for the stale-transformers-sidecar bug: importing the shim (and``child_should_disable_xet``) must NOT pull in ``transformers``/``unsloth_zoo``. The worker calls@@ -389,3 +514,71 @@ def test_importing_child_should_disable_xet_stays_light(monkeypatch):# And nothing heavy was imported as a side effect.assert "transformers" not in sys.modules, "importing the shim must not import transformers"assert "unsloth_zoo" not in sys.modules, "importing the shim must not import unsloth_zoo"+++def test_start_watchdog_drops_kwargs_the_installed_zoo_cannot_take(monkeypatch):+ """Version-skew adapter, and load-bearing: the floor's start_watchdog is keyword-only with no+ **kwargs and no connect_timeout, so passing one raises TypeError into the caller's+ `except Exception` and the watchdog silently never starts. That is the feature entirely off.+ """+ import threading++ import utils.hf_xet_fallback as shim++ seen = {}++ def _old_signature_watchdog(+ *,+ repo_ids,+ on_stall,+ repo_type = "model",+ cache_dir = None,+ interval = 30.0,+ stall_timeout = 180.0,+ xet_disabled = False,+ on_heartbeat = None,+ watch_new_partials_only = False,+ baseline_incomplete_blobs = None,+ child_pid = None,+ ):+ seen.update(locals())+ return threading.Event()++ class _FakeShared:+ start_watchdog = staticmethod(_old_signature_watchdog)++ monkeypatch.setattr(shim, "_shared", _FakeShared, raising = False)+ monkeypatch.setattr(shim, "_shared_available", True, raising = False)++ stop = shim.start_watchdog(+ repo_ids = ["a/b"],+ on_stall = lambda _m: None,+ watch_new_partials_only = True,+ child_pid = 1234,+ connect_timeout = 600.0, # only on the unreleased zoo+ )+ assert stop is not None, "the watchdog did not start"+ assert seen["watch_new_partials_only"] is True, "a SUPPORTED kwarg was dropped"+ assert seen["child_pid"] == 1234+++def test_start_watchdog_passes_everything_to_a_zoo_that_accepts_it(monkeypatch):+ """A newer zoo must still receive the newer knobs."""+ import threading++ import utils.hf_xet_fallback as shim++ seen = {}++ def _new_signature_watchdog(**kwargs):+ seen.update(kwargs)+ return threading.Event()++ class _FakeShared:+ start_watchdog = staticmethod(_new_signature_watchdog)++ monkeypatch.setattr(shim, "_shared", _FakeShared, raising = False)+ monkeypatch.setattr(shim, "_shared_available", True, raising = False)++ shim.start_watchdog(repo_ids = ["a/b"], on_stall = lambda _m: None, connect_timeout = 600.0)+ assert seen["connect_timeout"] == 600.0, "a newer zoo lost the kwarg it supports"diff --git a/studio/backend/tests/test_hub_download_transport_auto.py b/studio/backend/tests/test_hub_download_transport_auto.pynew file mode 100644index 00000000000..4b0e8ae2244--- /dev/null+++ b/studio/backend/tests/test_hub_download_transport_auto.py@@ -0,0 +1,488 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Tests for the hub download path's transport selection, RAM caps, and stall -> HTTP recovery.++The model-hub page is how most users download, and it was the ONE download path with no stall+detection: it relied on the worker's exit code, and a Xet transfer that hangs with no progress and+no error never produces one. These tests pin the three pieces that close that gap.++CPU-only, no network, no real worker subprocess.+"""++from __future__ import annotations++import subprocess+import sys+import threading+import time+import types as _types+from pathlib import Path++import pytest++_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)+try:+ import structlog # noqa: F401+except ImportError:+ sys.modules["structlog"] = _types.ModuleType("structlog")++from hub.services import download_lifecycle as dl+from hub.utils import download_registry+++# --------------------------------------------------------------------------------------------+# Transport selection+# --------------------------------------------------------------------------------------------+++def test_explicit_modes_are_honoured(monkeypatch):+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ assert dl.resolve_requested_use_xet("http", True)[0] is False+ assert dl.resolve_requested_use_xet("xet", False)[0] is True+++def test_explicit_xet_beats_an_unhealthy_verdict(monkeypatch):+ """An explicit choice is not overruled by the health verdict; it still gets the memory caps and+ the stall fallback."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ monkeypatch.setattr(dl, "resolve_auto_use_xet", lambda: (False, "demoted"))+ assert dl.resolve_requested_use_xet("xet", True)[0] is True+++def test_auto_defers_to_the_health_verdict(monkeypatch):+ monkeypatch.setattr(dl, "resolve_auto_use_xet", lambda: (False, "Xet stalled twice"))+ use_xet, reason = dl.resolve_requested_use_xet("auto", True)+ assert use_xet is False+ assert reason == "Xet stalled twice"+++def test_legacy_use_xet_still_works(monkeypatch):+ """An older frontend, or a scripted API caller, sends no transport_mode at all."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ assert dl.resolve_requested_use_xet(None, True)[0] is True+ assert dl.resolve_requested_use_xet(None, False)[0] is False+++def test_auto_falls_back_to_xet_when_health_is_unavailable(monkeypatch):+ """A missing or broken health module means "no opinion", never "downgrade"."""+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: requested)+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: None+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ assert dl.resolve_auto_use_xet()[0] is True+++def test_auto_reports_http_when_hf_xet_is_missing(monkeypatch):+ monkeypatch.setattr(dl, "resolve_effective_use_xet", lambda requested: False)+ use_xet, reason = dl.resolve_auto_use_xet()+ assert use_xet is False+ assert "hf_xet" in reason+++def test_auto_is_not_a_real_transport():+ """ "auto" is a request preference: the .transport marker must keep naming the writer that+ produced a partial, or a resume picks the wrong strategy."""+ assert download_registry.TRANSPORT_AUTO not in download_registry.VALID_TRANSPORTS+ assert download_registry.TRANSPORT_AUTO in download_registry.VALID_TRANSPORT_MODES+++# --------------------------------------------------------------------------------------------+# RAM caps reach the worker environment+# --------------------------------------------------------------------------------------------+++class _FakePopen:+ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs+ self.pid = 4242+ self.stderr = None+ self.returncode = 0+++def _spawn_env(+ monkeypatch,+ *,+ use_xet: bool,+ parent_env: dict | None = None,+) -> dict:+ captured = {}++ def _fake_popen(+ cmd,+ env = None,+ **kwargs,+ ):+ captured.update(env or {})+ return _FakePopen()++ paths = _types.SimpleNamespace(child_env = lambda *a, **k: dict(parent_env or {}))+ fake_settings = _types.ModuleType("utils.hf_cache_settings")+ fake_settings.get_hf_cache_paths = lambda: paths+ monkeypatch.setitem(sys.modules, "utils.hf_cache_settings", fake_settings)+ monkeypatch.setattr(dl.subprocess, "Popen", _fake_popen)+ dl.spawn_worker(["--repo-id", "a/b"], None, use_xet = use_xet)+ return captured+++def _tuning_available() -> bool:+ try:+ from utils.hf_xet_fallback import xet_env_overrides+ return bool(xet_env_overrides())+ except Exception: # noqa: BLE001+ return False+++ not _tuning_available(),+ reason = "the installed unsloth_zoo predates hf_xet_tuning, so there are no caps to apply",+)+def test_xet_worker_gets_ram_caps(monkeypatch):+ env = _spawn_env(monkeypatch, use_xet = True)+ limit = int(env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"])+ # Stock hf_xet allows 8GB here (64GB under high-performance mode).+ assert 0 < limit <= 4_000_000_000+ assert env["HF_HUB_DISABLE_XET"] == "0"+++def test_high_performance_is_cleared_not_merely_defaulted(monkeypatch):+ """xet-core applies the high-performance preset AFTER reading the environment, so an inherited+ "1" would discard every cap above rather than compete with it. setdefault is not enough."""+ env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})+ assert env["HF_XET_HIGH_PERFORMANCE"] == "0"+++def test_high_performance_is_cleared_even_without_the_tuning_module(monkeypatch):+ """An unsloth_zoo with no `hf_xet_tuning` is exactly the version that sets+ HF_XET_HIGH_PERFORMANCE=1 at import, so routing the clear through the (then empty) overrides+ would hand the worker a 64GB buffer ceiling on the installs Studio alone cannot fix."""+ import utils.hf_xet_fallback as shim++ monkeypatch.setattr(shim, "xet_env_overrides", lambda *a, **k: {})+ env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})+ assert env["HF_XET_HIGH_PERFORMANCE"] == "0"+ assert env["HF_XET_HP"] == "0"+++def test_user_can_opt_back_into_high_performance(monkeypatch):+ monkeypatch.setenv("UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE", "1")+ env = _spawn_env(monkeypatch, use_xet = True, parent_env = {"HF_XET_HIGH_PERFORMANCE": "1"})+ assert env["HF_XET_HIGH_PERFORMANCE"] == "1"+++ not _tuning_available(),+ reason = "the installed unsloth_zoo predates hf_xet_tuning, so there are no caps to preserve",+)+def test_explicit_cap_from_the_operator_is_preserved(monkeypatch):+ env = _spawn_env(+ monkeypatch,+ use_xet = True,+ parent_env = {+ "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT": "7777777",+ },+ )+ assert env["HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT"] == "7777777"+++def test_http_worker_gets_no_xet_caps(monkeypatch):+ env = _spawn_env(monkeypatch, use_xet = False)+ assert env["HF_HUB_DISABLE_XET"] == "1"+ assert "HF_XET_RECONSTRUCTION_DOWNLOAD_BUFFER_LIMIT" not in env+++# --------------------------------------------------------------------------------------------+# Stall -> kill -> HTTP retry+# --------------------------------------------------------------------------------------------+++class _KillablePopen:+ def __init__(self):+ self.pid = 999+ self.killed = threading.Event()++ def kill(self):+ self.killed.set()+++def _registry_stub():+ return _types.SimpleNamespace(get_job_metadata = lambda key: None)+++def test_stall_watchdog_kills_the_worker(monkeypatch):+ """The kill converts an invisible hang into an "error" exit, the state the HTTP-retry keys on."""+ proc = _KillablePopen()+ seen: list[str] = []+ started = {}++ fake = _types.ModuleType("utils.hf_xet_fallback")++ def _start_watchdog(*, on_stall, **kwargs):+ started.update(kwargs)+ on_stall("Download appears stalled (xet transport) -- no progress for 30s")+ return threading.Event()++ fake.start_watchdog = _start_watchdog+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ stop = dl._start_stall_watchdog(+ _registry_stub(),+ "models--a--b",+ proc,+ repo_type = "model",+ repo_id = "a/b",+ label = "a/b",+ log_prefix = "[hub]",+ logger = dl.logger,+ on_stall = seen.append,+ )+ assert stop is not None+ assert proc.killed.is_set(), "a stalled worker was not killed"+ assert seen and "stalled" in seen[0]+ assert started["repo_ids"] == ["a/b"]+ assert started["child_pid"] == 999+++def test_stall_watchdog_survives_an_already_exited_worker(monkeypatch):+ """The worker can exit between the stall verdict and the kill; that is a race, not an error."""++ class _Gone:+ pid = 1++ def kill(self):+ raise ProcessLookupError++ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.start_watchdog = lambda *, on_stall, **kw: (on_stall("stalled"), threading.Event())[1]+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)++ stop = dl._start_stall_watchdog(+ _registry_stub(),+ "k",+ _Gone(),+ repo_type = "model",+ repo_id = "a/b",+ label = "a/b",+ log_prefix = "[hub]",+ logger = dl.logger,+ on_stall = lambda _m: None,+ )+ assert stop is not None+++def test_missing_watchdog_degrades_quietly(monkeypatch):+ """An older unsloth_zoo without start_watchdog must not break downloads, only stall detection."""+ fake = _types.ModuleType("utils.hf_xet_fallback")+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ assert (+ dl._start_stall_watchdog(+ _registry_stub(),+ "k",+ _KillablePopen(),+ repo_type = "model",+ repo_id = "a/b",+ label = "a/b",+ log_prefix = "[hub]",+ logger = dl.logger,+ on_stall = lambda _m: None,+ )+ is None+ )+++def test_stall_is_recorded_against_the_machine(monkeypatch):+ recorded: list = []+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.record_xet_outcome = lambda ok, reason: recorded.append((ok, reason))+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ dl._record_xet_failure("Xet stalled", dl.logger)+ assert recorded == [(False, "Xet stalled")]+++def test_recording_a_failure_never_raises(monkeypatch):+ fake = _types.ModuleType("utils.hf_xet_fallback")++ def _boom(ok, reason):+ raise RuntimeError("state file is read-only")++ fake.record_xet_outcome = _boom+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ dl._record_xet_failure("Xet stalled", dl.logger) # must not propagate+++# --------------------------------------------------------------------------------------------+# Capabilities endpoint+# --------------------------------------------------------------------------------------------+++def test_capabilities_report_what_auto_resolves_to(monkeypatch):+ fake = _types.ModuleType("utils.hf_xet_fallback")+ fake.xet_health = lambda **kw: _types.SimpleNamespace(+ use_xet = False,+ reason = "Xet failed 2 times in a row on this machine",+ )+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ caps = download_registry.get_download_transport_capabilities()+ if not caps.xet.available:+ pytest.skip("hf_xet is not installed in this environment")+ assert caps.auto_resolves_to == download_registry.TRANSPORT_HTTP+ assert "2 times" in caps.auto_reason+++def test_capabilities_stay_optimistic_when_health_raises(monkeypatch):+ fake = _types.ModuleType("utils.hf_xet_fallback")++ def _boom(**kw):+ raise RuntimeError("no")++ fake.xet_health = _boom+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", fake)+ caps = download_registry.get_download_transport_capabilities()+ if not caps.xet.available:+ pytest.skip("hf_xet is not installed in this environment")+ # The download-time ladder still recovers, so an unknown verdict should not cost the fast path.+ assert caps.auto_resolves_to == download_registry.TRANSPORT_XET+++# --------------------------------------------------------------------------------------------+# CPU-only hosts+# --------------------------------------------------------------------------------------------+++def test_optional_loader_retries_with_gpu_init_disabled(monkeypatch):+ """unsloth_zoo.__init__ runs torch accelerator detection and raises on a CPU-only host, which is+ exactly the small machine these caps protect, so without the retry they switch off where they+ are needed."""+ import importlib++ import utils.hf_xet_fallback as shim++ attempts: list[str | None] = []+ sentinel = _types.ModuleType("fake_zoo_module")++ def _fake_import(name):+ import os++ seen = os.environ.get("UNSLOTH_ZOO_DISABLE_GPU_INIT")+ attempts.append(seen)+ if seen != "1":+ raise NotImplementedError("Unsloth cannot find any torch accelerator? You need a GPU.")+ return sentinel++ monkeypatch.setattr(importlib, "import_module", _fake_import)+ monkeypatch.delenv("UNSLOTH_ZOO_DISABLE_GPU_INIT", raising = False)++ assert shim._load_optional("unsloth_zoo.hf_xet_tuning") is sentinel+ assert attempts == [None, "1"]+ # The flag is scoped to the retry: it must not leak into unrelated later imports.+ import os++ assert "UNSLOTH_ZOO_DISABLE_GPU_INIT" not in os.environ+++def test_optional_loader_returns_none_when_truly_absent(monkeypatch):+ import importlib++ import utils.hf_xet_fallback as shim++ def _always_fail(name):+ raise ModuleNotFoundError(name)++ monkeypatch.setattr(importlib, "import_module", _always_fail)+ assert shim._load_optional("unsloth_zoo.hf_xet_tuning") is None+ # A missing module means "no opinion", never a hard failure.+ assert shim.xet_env_overrides() == {}+ assert shim.xet_health() is None+ shim.record_xet_outcome(False, "x")+++def test_capabilities_probe_is_opt_in(monkeypatch):+ """The UI polls this endpoint on render, so it must stay cheap by default. The download-start+ path opts in: a host with an unreachable CAS and no recorded failure yet would otherwise learn+ by stalling."""+ from hub.utils import download_registry++ seen: list[bool] = []++ class _Health:+ use_xet = False+ reason = "probed: CAS unreachable"++ def _fake_health(*, probe = True):+ seen.append(probe)+ return _Health()++ # Patch the sys.modules entry, not an imported alias: the endpoint does a local+ # `from utils.hf_xet_fallback import xet_health`, and test_hf_xet_fallback.py swaps that+ # sys.modules entry in and out, so an alias captured here can be a different module object.+ import sys+ import types++ stub = types.ModuleType("utils.hf_xet_fallback")+ stub.xet_health = _fake_health+ monkeypatch.setitem(sys.modules, "utils.hf_xet_fallback", stub)++ caps = download_registry.get_download_transport_capabilities()+ if not caps.xet.available:+ # The health lookup sits behind an hf_xet availability check, so with no hf_xet installed+ # neither call reaches it.+ pytest.skip("hf_xet is not installed in this environment")+ download_registry.get_download_transport_capabilities(probe = True)++ assert seen == [False, True]+++def test_gpu_init_override_is_serialized(monkeypatch):+ """The optional-module retry must not leak the process-wide GPU-init override: a leaked+ UNSLOTH_ZOO_DISABLE_GPU_INIT=1 is inherited by every spawned worker for the life of the process.++ Scope: this races the loader against itself. The cross-loader interleave with _load_shared is+ not reproducible by thread timing, and is established by construction instead (both take the+ same `_load_lock` around their save/set/restore) -- see the test below.+ """+ import importlib+ import os+ import threading++ import utils.hf_xet_fallback as shim++ monkeypatch.delenv("UNSLOTH_ZOO_DISABLE_GPU_INIT", raising = False)++ def _always_fail(name):+ time.sleep(0.005) # widen the window the lock has to close+ raise ModuleNotFoundError(name)++ monkeypatch.setattr(importlib, "import_module", _always_fail)++ threads = [+ threading.Thread(target = shim._load_optional, args = ("unsloth_zoo.hf_xet_tuning",))+ for _ in range(8)+ ]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()++ assert "UNSLOTH_ZOO_DISABLE_GPU_INIT" not in os.environ+++def test_both_loaders_share_one_env_lock():+ """The cross-loader guarantee, checked structurally. Two separate locks would each be correct in+ isolation and still allow the interleave that leaves the override set permanently."""+ import inspect++ import utils.hf_xet_fallback as shim++ for fn in (shim._load_shared, shim._load_optional):+ source = inspect.getsource(fn)+ assert "UNSLOTH_ZOO_DISABLE_GPU_INIT" in source+ assert (+ "with _load_lock:" in source+ ), f"{fn.__name__} mutates the GPU-init override outside the shared _load_lock"diff --git a/studio/backend/utils/child_stdio.py b/studio/backend/utils/child_stdio.pyindex 4709d650dfc..67f2b139ec3 100644--- a/studio/backend/utils/child_stdio.py+++ b/studio/backend/utils/child_stdio.py@@ -19,4 +19,15 @@ def utf8_child_env(env: Optional[Mapping[str, str]] = None) -> dict[str, str]:"""Copy *env* (or the current environment) with UTF-8 stdio forced."""child = dict(os.environ if env is None else env)child["PYTHONIOENCODING"] = "utf-8"+ if env is None and child.get("UNSLOTH_ZOO_DISABLE_GPU_INIT") == "1":+ # The Xet shim sets this process-wide for one optional import; a child spawned in that+ # window inherits it for life, and unsloth_zoo injects triton and bitsandbytes STUBS when it+ # is set, so a training child would run against no-ops. Only the loader's own transient+ # value is dropped, so an operator who set it deliberately is unaffected.+ try:+ from utils.hf_xet_fallback import gpu_init_override_active+ if gpu_init_override_active():+ child.pop("UNSLOTH_ZOO_DISABLE_GPU_INIT", None)+ except Exception: # noqa: BLE001 - never fail a spawn over this+ passreturn childdiff --git a/studio/backend/utils/hf_cache_settings.py b/studio/backend/utils/hf_cache_settings.pyindex 961d7fd5c58..cc01f0b97ad 100644--- a/studio/backend/utils/hf_cache_settings.py+++ b/studio/backend/utils/hf_cache_settings.py@@ -152,6 +152,19 @@ def active_hf_hub_cache() -> str:return str(get_hf_cache_paths().hub_cache)+@contextmanager+def _xet_loader_barrier() -> Iterator[None]:+ """Block while a Xet shim loader holds its process-wide env override. Never fails a spawn."""+ try:+ from utils.hf_xet_fallback import env_override_barrier+ barrier = env_override_barrier()+ except Exception: # noqa: BLE001 - the shim is optional; a spawn must never depend on it+ yield+ return+ with barrier:+ yield++@contextmanagerdef child_environment_for_spawn(environment: Mapping[str, str]) -> Iterator[None]:"""Apply captured env before spawn imports the child entrypoint.@@ -162,7 +175,12 @@ def child_environment_for_spawn(environment: Mapping[str, str]) -> Iterator[None"""from utils.utils import hf_environment_restored_for_spawn- with _spawn_env_lock, hf_environment_restored_for_spawn():++ # Also exclude the Xet shim's GPU-init override window: a child spawned inside it inherits the+ # flag for life, whereupon unsloth_zoo hands it STUB triton and bitsandbytes and the run+ # silently produces nothing. Filtering a child env dict cannot help here, since spawn copies the+ # live environment and takes no env argument.+ with _spawn_env_lock, _xet_loader_barrier(), 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/hf_xet_fallback.py b/studio/backend/utils/hf_xet_fallback.pyindex 49872f371e5..863185f60e3 100644--- a/studio/backend/utils/hf_xet_fallback.py+++ b/studio/backend/utils/hf_xet_fallback.py@@ -29,13 +29,23 @@ from typing import Any, Callable, Optional# default args below) without importing unsloth_zoo/transformers.DEFAULT_GRACE_PERIOD = 10.0DEFAULT_HEARTBEAT_INTERVAL = 30.0-DEFAULT_STALL_TIMEOUT = 180.0+# Xet gets 30s of zero progress before the HTTP retry; HTTP, the last resort, keeps 180s. The+# wrappers pass None so the shared layer picks per transport; these literals are for callers that+# want an explicit value without the heavy import.+DEFAULT_STALL_TIMEOUT = 30.0+DEFAULT_CONNECT_TIMEOUT = 90.0+DEFAULT_HTTP_STALL_TIMEOUT = 180.0# --- lazy shared-backend loader ----------------------------------------------------------------_shared: Any = None_shared_available: Optional[bool] = None # None = not yet attempted_shared_import_error: Optional[BaseException] = None-_load_lock = threading.Lock()+# Guards _shared_available AND every UNSLOTH_ZOO_DISABLE_GPU_INIT save/set/restore here. Both+# loaders mutate that one process-wide variable, so they must serialize against each other: two+# locks would still allow A-saves-unset / B-saves-"1" / A-restores-unset / B-restores-"1", leaving+# it set for the life of the process. RLock because child_environment_for_spawn holds it across a+# spawn and legitimately nests (its own _spawn_env_lock is an RLock for the same reason).+_load_lock = threading.RLock()def _load_shared() -> bool:@@ -61,7 +71,10 @@ def _load_shared() -> bool:_shared_import_error = excimport os as _os+ global _gpu_init_override_depth_prev_gpu_init = _os.environ.get("UNSLOTH_ZOO_DISABLE_GPU_INIT")+ _ours = _prev_gpu_init != "1"+ _gpu_init_override_depth += _ours # claimed before the write, released after_os.environ["UNSLOTH_ZOO_DISABLE_GPU_INIT"] = "1"try:import unsloth_zoo.hf_xet_fallback as shared@@ -87,6 +100,119 @@ def _load_shared() -> bool:_os.environ.pop("UNSLOTH_ZOO_DISABLE_GPU_INIT", None)else:_os.environ["UNSLOTH_ZOO_DISABLE_GPU_INIT"] = _prev_gpu_init+ _gpu_init_override_depth -= _ours+++# _load_optional results by module name. Memoising the FAILURE is the point: on a zoo that predates+# these modules the import can never start succeeding, so without this every xet_health /+# record_xet_outcome / xet_env_overrides call re-ran the GPU-init retry, re-opening the+# process-wide env window on every download. With it the window opens once per module per process.+_UNTRIED = object()+_optional_modules: "dict[str, Any]" = {}+++def _reset_optional_module_cache() -> None:+ """Forget memoised optional-module results (tests that install or remove a zoo module)."""+ with _load_lock:+ _optional_modules.clear()+++def _load_optional(module_name: str) -> Any:+ """Import an optional shared Xet helper module (health / tuning), or return ``None``.++ Separate from ``_load_shared``: these modules exist only in newer unsloth_zoo, and a Studio+ pinned to an older one must keep downloading without the preflight verdict or buffer caps.+ The GPU-init retry matters most here: ``unsloth_zoo.__init__`` runs torch accelerator detection+ and raises ``NotImplementedError`` on a CPU-only host, which is precisely the small machine+ whose RAM these caps protect, so without the retry they switch off where they are needed.+ """+ import importlib+ import os as _os++ cached = _optional_modules.get(module_name, _UNTRIED)+ if cached is not _UNTRIED:+ return cached++ try:+ module = importlib.import_module(module_name)+ _optional_modules[module_name] = module+ return module+ except Exception as exc: # noqa: BLE001 - an older/absent unsloth_zoo must degrade, not crash+ first_error = exc++ # Deliberately the SAME lock _load_shared uses: interleaved save/set/restore would leave+ # UNSLOTH_ZOO_DISABLE_GPU_INIT set for the life of the process (see _load_lock).+ with _load_lock:+ cached = _optional_modules.get(module_name, _UNTRIED)+ if cached is not _UNTRIED:+ return cached+ global _gpu_init_override_depth+ previous = _os.environ.get("UNSLOTH_ZOO_DISABLE_GPU_INIT")+ ours = previous != "1"+ # Claim BEFORE the write, release AFTER the restore, so the set window sits strictly inside+ # the window where a spawning thread can see the flag is ours. The other order leaves a gap+ # at each end where a child inherits an unclaimed flag and never clears it.+ _gpu_init_override_depth += ours+ try:+ _os.environ["UNSLOTH_ZOO_DISABLE_GPU_INIT"] = "1"+ try:+ module = importlib.import_module(module_name)+ except Exception as exc: # noqa: BLE001+ import logging as _logging+ _logging.getLogger(__name__).debug(+ "%s unavailable (%s; with GPU init disabled: %s)", module_name, first_error, exc+ )+ module = None+ finally:+ if previous is None:+ _os.environ.pop("UNSLOTH_ZOO_DISABLE_GPU_INIT", None)+ else:+ _os.environ["UNSLOTH_ZOO_DISABLE_GPU_INIT"] = previous+ finally:+ _gpu_init_override_depth -= ours+ _optional_modules[module_name] = module+ return module+++def xet_health(**kwargs: Any) -> Any:+ """The machine's Xet verdict, or ``None`` when unsloth_zoo cannot answer.++ ``None`` means "no opinion": callers keep their default (Xet), they do not downgrade.+ """+ module = _load_optional("unsloth_zoo.hf_xet_health")+ if module is None:+ return None+ try:+ return module.xet_health(**kwargs)+ except Exception as exc: # noqa: BLE001+ import logging as _logging+ _logging.getLogger(__name__).debug("xet_health failed: %s", exc)+ return None+++def record_xet_outcome(ok: bool, reason: str = "") -> None:+ """Record a finished Xet attempt so a repeatedly-failing machine stops starting on Xet."""+ module = _load_optional("unsloth_zoo.hf_xet_health")+ if module is None:+ return+ try:+ module.record_xet_outcome(ok, reason)+ except Exception as exc: # noqa: BLE001+ import logging as _logging+ _logging.getLogger(__name__).debug("record_xet_outcome failed: %s", exc)+++def xet_env_overrides() -> "dict[str, str]":+ """RAM/CPU-derived ``HF_XET_*`` caps for a download worker's environment; ``{}`` if unavailable."""+ module = _load_optional("unsloth_zoo.hf_xet_tuning")+ if module is None:+ return {}+ try:+ return dict(module.xet_env_overrides())+ except Exception as exc: # noqa: BLE001+ import logging as _logging+ _logging.getLogger(__name__).debug("xet_env_overrides failed: %s", exc)+ return {}def child_should_disable_xet(config: dict) -> bool:@@ -211,15 +337,76 @@ def _degraded_snapshot_download_with_xet_fallback(# only for these heavy names, not for ``child_should_disable_xet`` / ``DEFAULT_*``._DEGRADED_ATTRS = {"DownloadStallError": _DegradedDownloadStallError,- "start_watchdog": _degraded_start_watchdog,"get_hf_download_state": _degraded_get_hf_download_state,}++# Nonzero while a loader has UNSLOTH_ZOO_DISABLE_GPU_INIT set process-wide for its retry. Read by+# utf8_child_env so a child spawned in that window does not inherit it: unsloth_zoo injects triton+# and bitsandbytes STUBS when it is set, so a training child would silently run against no-ops.+# Only counted when the loader introduced the value; an operator who exported it keeps it.+_gpu_init_override_depth = 0+++def gpu_init_override_active() -> bool:+ """Is a loader currently holding UNSLOTH_ZOO_DISABLE_GPU_INIT set for its own import?"""+ return _gpu_init_override_depth > 0+++def env_override_barrier() -> Any:+ """Context manager a caller holds across a spawn so no loader can be mid-override.++ Spawn children inherit the parent's live ``os.environ`` and there is no env dict to filter, so+ the only way to keep UNSLOTH_ZOO_DISABLE_GPU_INIT out of a worker is that no loader has it set+ when the child is created. Loaders never spawn, so holding this with the spawn lock cannot+ deadlock, and ``_load_optional`` memoises so the window opens at most once per module per+ process.+ """+ return _load_lock+++def _supported_kwargs(fn: Any, kwargs: "dict[str, Any]") -> "dict[str, Any]":+ """Drop kwargs *fn* does not accept; pass everything through if it takes ``**kwargs``.++ Uninspectable callables (C functions, some test doubles) also pass through unchanged.+ """+ import inspect++ try:+ params = inspect.signature(fn).parameters+ except (TypeError, ValueError):+ return kwargs+ if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()):+ return kwargs+ return {k: v for k, v in kwargs.items() if k in params}+++def start_watchdog(**kwargs: Any) -> Any:+ """Shared stall watchdog, minus any kwarg the INSTALLED unsloth_zoo does not accept.++ Load-bearing version-skew adapter: the supported floor (2026.8.1) has no ``connect_timeout`` or+ ``heartbeat_interval`` and no ``**kwargs``, so passing one raises TypeError into the caller's+ ``except Exception`` -- the watchdog then never starts and a stalled Xet worker is never killed+ or retried over HTTP. That is the feature entirely off, not degraded. Filtering keeps newer+ knobs live on a newer zoo and makes the NEXT new kwarg a no-op instead of a repeat of this bug.++ Dropping the pre-byte budget on 2026.8.1 costs little: huggingface_hub opens the ``.incomplete``+ BEFORE calling ``xet_get`` (``file_download.py`` opens ``incomplete_path`` and calls ``xet_get``+ inside that ``with``) and the floor counts a partial by presence, not size, so a hf_xet hang+ still trips the floor's 180s data clock. Verified against the released wheel: wedged inside+ ``xet_get`` trips, wedged before the open does not. The uncovered window is the metadata phase,+ where ``snapshot_download`` calls ``repo_info`` with no timeout. That gap predates this shim;+ the connect clock closes it only once a zoo carrying it ships, and passing the kwarg early would+ not close it, it would disable the watchdog outright.+ """+ impl = _shared.start_watchdog if _load_shared() else _degraded_start_watchdog+ return impl(**_supported_kwargs(impl, kwargs))++# Annotation-only declarations for the three names above: they bind NO value, so lookup still misses# and PEP 562 ``__getattr__`` resolves them lazily -- but ruff/pyflakes see them as defined, so listing# them in ``__all__`` does not trip F822 (while F822 still catches a real typo elsewhere in the list).DownloadStallError: type-start_watchdog: Anyget_hf_download_state: Any@@ -252,13 +439,18 @@ def _shared_snapshot_download_with_xet_fallback(*args: Any, **kwargs: Any) -> st__all__ = [+ "DEFAULT_CONNECT_TIMEOUT","DEFAULT_GRACE_PERIOD","DEFAULT_HEARTBEAT_INTERVAL",+ "DEFAULT_HTTP_STALL_TIMEOUT","DEFAULT_STALL_TIMEOUT","DownloadStallError","child_should_disable_xet","get_hf_download_state",+ "record_xet_outcome","start_watchdog",+ "xet_env_overrides",+ "xet_health","hf_hub_download_with_xet_fallback","snapshot_download_with_xet_fallback",]@@ -300,8 +492,8 @@ def hf_hub_download_with_xet_fallback(cancel_event: Optional[threading.Event] = None,repo_type: str = "model",revision: Optional[str] = None,- stall_timeout: float = DEFAULT_STALL_TIMEOUT,- interval: float = DEFAULT_HEARTBEAT_INTERVAL,+ stall_timeout: Optional[float] = None,+ interval: Optional[float] = None,grace_period: float = DEFAULT_GRACE_PERIOD,on_status: Optional[Callable[[str], None]] = None,force_download: bool = False,@@ -312,6 +504,14 @@ def hf_hub_download_with_xet_fallback(if cache_dir is None:from utils.hf_cache_settings import get_hf_cache_pathscache_dir = str(get_hf_cache_paths().hub_cache)+ # Omit rather than forward None: an older unsloth_zoo hands `interval` straight to Event.wait(),+ # where None blocks forever and a hung Xet download never falls back. Omitting also lets the+ # shared layer pick its per-transport defaults.+ optional: dict[str, Any] = {}+ if stall_timeout is not None:+ optional["stall_timeout"] = stall_timeout+ if interval is not None:+ optional["interval"] = intervalreturn _shared_hf_hub_download_with_xet_fallback(repo_id,filename,@@ -319,8 +519,7 @@ def hf_hub_download_with_xet_fallback(cancel_event = cancel_event,repo_type = repo_type,revision = revision,- stall_timeout = stall_timeout,- interval = interval,+ **optional,grace_period = grace_period,on_status = on_status,force_download = force_download,diff --git a/studio/frontend/src/features/hub/catalog/transport-toggle.tsx b/studio/frontend/src/features/hub/catalog/transport-toggle.tsxindex bd6222094aa..1bb5dc0a7cd 100644--- a/studio/frontend/src/features/hub/catalog/transport-toggle.tsx+++ b/studio/frontend/src/features/hub/catalog/transport-toggle.tsx@@ -13,23 +13,31 @@ import {import { cn } from "@/lib/utils";import { useEffect } from "react";-const OPTIONS: { value: "http" | "xet"; label: string; hint: string }[] = [- {- value: "http",- label: "HTTP",- hint: "Resumes from where it stopped if you cancel.",- },- {- value: "xet",- label: "Xet",- hint: "Usually faster on a fresh download, but starts over if you cancel.",- },-];+const OPTIONS: { value: "auto" | "http" | "xet"; label: string; hint: string }[] =+ [+ {+ value: "auto",+ label: "Auto",+ hint: "Picks the transport for this machine and switches to HTTP if Xet stalls or fails.",+ },+ {+ value: "http",+ label: "HTTP",+ hint: "Resumes from where it stopped if you cancel.",+ },+ {+ value: "xet",+ label: "Xet",+ hint: "Usually faster on a fresh download, but starts over if you cancel.",+ },+ ];export function TransportToggle() {const [mode, setMode] = useTransportMode();const { capabilities } = useDownloadTransportCapabilities();const xetUnavailable = capabilities?.xet.available === false;+ const autoResolvesTo = capabilities?.auto_resolves_to ?? "xet";+ const autoReason = capabilities?.auto_reason;useEffect(() => {if (mode === "xet" && xetUnavailable) {@@ -45,10 +53,16 @@ export function TransportToggle() {{OPTIONS.map((opt) => {const active = mode === opt.value;const disabled = opt.value === "xet" && xetUnavailable;- const hint =- disabled && capabilities?.xet.reason- ? capabilities.xet.reason- : opt.hint;+ let hint = opt.hint;+ if (disabled && capabilities?.xet.reason) {+ hint = capabilities.xet.reason;+ } else if (opt.value === "auto") {+ // Say what Auto is doing right now and why, so "Auto" is never an opaque choice.+ const label = autoResolvesTo === "http" ? "HTTP" : "Xet";+ hint = autoReason+ ? `${opt.hint} Currently: ${label} (${autoReason}).`+ : `${opt.hint} Currently: ${label}.`;+ }return (<Tooltip key={opt.value}><TooltipTrigger asChild={true}>diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.tsindex 2c55b90edd0..b8d487ba190 100644--- a/studio/frontend/src/features/hub/download-manager/api.ts+++ b/studio/frontend/src/features/hub/download-manager/api.ts@@ -104,16 +104,6 @@ export interface TransportStatus {resumable: boolean;}-export interface DownloadTransportCapability {- available: boolean | null;- reason: string | null;-}--export interface DownloadTransportCapabilities {- http: DownloadTransportCapability;- xet: DownloadTransportCapability;-}-export interface DownloadProgressResponse {downloaded_bytes: number;completed_bytes: number;@@ -133,73 +123,57 @@ export type GgufDownloadProgressOptions = DownloadProgressOptions & {variant: string;};-const DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK: DownloadTransportCapabilities = {- http: { available: true, reason: null },- xet: {- available: null,- reason: "Couldn't verify Xet support with the Unsloth backend.",- },-};-let downloadTransportCapabilitiesCache: DownloadTransportCapabilities | null =- null;+export type {+ DownloadTransportCapability,+ DownloadTransportCapabilities,+} from "./transport-capabilities";+import {+ DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK,+ normalizeDownloadTransportCapabilities,+} from "./transport-capabilities";+import type { DownloadTransportCapabilities } from "./transport-capabilities";++// The Auto verdict is dynamic: a stalled transfer demotes this machine mid-session, so an+// indefinite cache would keep serving the pre-stall answer until the page reloads. Refreshing is+// cheap because the endpoint answers from cached health without a network probe.+const DOWNLOAD_TRANSPORT_CAPABILITIES_TTL_MS = 30_000;+let downloadTransportCapabilitiesCache: {+ expiresAt: number;+ probed: boolean;+ capabilities: DownloadTransportCapabilities;+} | null = null;let downloadTransportCapabilitiesInFlight: Promise<DownloadTransportCapabilities> | null =null;-function normalizeDownloadTransportCapability(- value: unknown,- fallback: DownloadTransportCapability,-): DownloadTransportCapability {- if (!value || typeof value !== "object") {- return fallback;- }- const candidate = value as { available?: unknown; reason?: unknown };- return {- available:- typeof candidate.available === "boolean"- ? candidate.available- : fallback.available,- reason:- typeof candidate.reason === "string"- ? candidate.reason- : candidate.reason === null- ? null- : fallback.reason,- };-}--function normalizeDownloadTransportCapabilities(- value: unknown,-): DownloadTransportCapabilities {- if (!value || typeof value !== "object") {- return DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK;- }- const candidate = value as { http?: unknown; xet?: unknown };- return {- http: normalizeDownloadTransportCapability(candidate.http, {- available: true,- reason: null,- }),- xet: normalizeDownloadTransportCapability(- candidate.xet,- DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK.xet,- ),- };-}-export async function getDownloadTransportCapabilities(options: {force?: boolean;+ // Reach for the Xet endpoint instead of answering from the cached verdict. Only the+ // download-start path sets this; the UI polls on render and must not connect per poll.+ probe?: boolean;} = {}): Promise<DownloadTransportCapabilities> {- if (!options.force && downloadTransportCapabilitiesCache) {- return downloadTransportCapabilitiesCache;+ const cached = downloadTransportCapabilitiesCache;+ // A cheap cached answer cannot satisfy a probe request, but a probed one satisfies everybody.+ const cacheUsable =+ cached !== null &&+ cached.expiresAt > Date.now() &&+ (!options.probe || cached.probed);+ if (!options.force && cacheUsable) {+ return cached.capabilities;}- if (!options.force && downloadTransportCapabilitiesInFlight) {+ if (!options.force && !options.probe && downloadTransportCapabilitiesInFlight) {return downloadTransportCapabilitiesInFlight;}- const request = authFetch("/api/studio/download-transport-capabilities")+ const request = authFetch(+ `/api/studio/download-transport-capabilities${options.probe ? "?probe=1" : ""}`,+ ).then(parseJsonOrThrow<unknown>).then(normalizeDownloadTransportCapabilities).then((capabilities) => {- downloadTransportCapabilitiesCache = capabilities;+ downloadTransportCapabilitiesCache = {+ expiresAt: Date.now() + DOWNLOAD_TRANSPORT_CAPABILITIES_TTL_MS,+ probed: options.probe === true,+ capabilities,+ };return capabilities;}).catch(() => DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK)@@ -222,6 +196,7 @@ export async function startModelDownload(payload: {gguf_variant?: string | null;hf_token?: string | null;use_xet?: boolean;+ transport_mode?: "auto" | "xet" | "http";}): Promise<DownloadStartResult & { job_key: string }> {const { hf_token, ...body } = payload;const headers = {@@ -343,6 +318,7 @@ export async function startDatasetDownload(payload: {repo_id: string;hf_token?: string | null;use_xet?: boolean;+ transport_mode?: "auto" | "xet" | "http";}): Promise<DownloadStartResult & { repo_id: string }> {const { hf_token, ...body } = payload;const headers = {diff --git a/studio/frontend/src/features/hub/download-manager/constants.ts b/studio/frontend/src/features/hub/download-manager/constants.tsindex 784173a4bfe..340cf54d8c2 100644--- a/studio/frontend/src/features/hub/download-manager/constants.ts+++ b/studio/frontend/src/features/hub/download-manager/constants.ts@@ -4,12 +4,24 @@export const TRANSPORT = {HTTP: "http",XET: "xet",+ AUTO: "auto",} as const;-export const TRANSPORT_MODES = [TRANSPORT.HTTP, TRANSPORT.XET] as const;+// The two transports a download can run on. "auto" is a preference, resolved to one of these+// before a download starts; only these reach a `.transport` marker on disk, which records the+// writer so a resume picks the right strategy.+export const RESOLVED_TRANSPORTS = [TRANSPORT.HTTP, TRANSPORT.XET] as const;+export type ResolvedTransport = (typeof RESOLVED_TRANSPORTS)[number];++export const TRANSPORT_MODES = [+ TRANSPORT.AUTO,+ TRANSPORT.HTTP,+ TRANSPORT.XET,+] as const;export type TransportMode = (typeof TRANSPORT_MODES)[number];-// Xet by default; effectiveTransportMode() downgrades to HTTP if hf_xet is missing.-export const DEFAULT_TRANSPORT_MODE: TransportMode = TRANSPORT.XET;+// Auto by default: the backend picks per machine (RAM, hf_xet build, recent Xet failures), and+// effectiveTransportMode() resolves that to a concrete transport before any download starts.+export const DEFAULT_TRANSPORT_MODE: TransportMode = TRANSPORT.AUTO;export function isTransportMode(value: unknown): value is TransportMode {return (@@ -18,6 +30,15 @@ export function isTransportMode(value: unknown): value is TransportMode {);}+export function isResolvedTransport(+ value: unknown,+): value is ResolvedTransport {+ return (+ typeof value === "string" &&+ (RESOLVED_TRANSPORTS as readonly string[]).includes(value)+ );+}+export const DOWNLOAD_KIND = {MODEL: "model",DATASET: "dataset",diff --git a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts b/studio/frontend/src/features/hub/download-manager/download-api-adapter.tsindex a6518ec6564..dc03e6edd05 100644--- a/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts+++ b/studio/frontend/src/features/hub/download-manager/download-api-adapter.ts@@ -24,7 +24,12 @@ import {TRANSPORT_STATUS_RETRY_DELAY_MS,TRANSPORT_STATUS_TIMEOUT_MS,} from "./download-manager-config";-import { DOWNLOAD_KIND, TRANSPORT, type TransportMode } from "./constants";+import {+ DOWNLOAD_KIND,+ TRANSPORT,+ type ResolvedTransport,+ type TransportMode,+} from "./constants";import type {DownloadRequest,ManagedDownload,@@ -90,17 +95,22 @@ export function apiStart(useXet: boolean,hfToken: string | null,): Promise<DownloadStartResult> {+ // Already RESOLVED ("xet"/"http"), never "auto": effectiveTransportMode() asked the backend what+ // auto means here, and that answer must reach both the worker and the on-disk transport marker.+ const transport_mode = useXet ? TRANSPORT.XET : TRANSPORT.HTTP;return req.kind === DOWNLOAD_KIND.DATASET? startDatasetDownload({repo_id: req.repoId,hf_token: hfToken,use_xet: useXet,+ transport_mode,}): startModelDownload({repo_id: req.repoId,gguf_variant: req.variant,hf_token: hfToken,use_xet: useXet,+ transport_mode,});}@@ -171,11 +181,22 @@ export async function apiTransportStatusWithRetry(export async function effectiveTransportMode(preferred: TransportMode,-): Promise<TransportMode> {- if (preferred !== TRANSPORT.XET) {- return preferred;+): Promise<ResolvedTransport> {+ if (preferred === TRANSPORT.HTTP) {+ return TRANSPORT.HTTP;+ }+ // Probe only for Auto, and only at download start: a host whose CAS is unreachable but which has+ // recorded no failure yet would otherwise discover that by stalling for 30s.+ const capabilities = await getDownloadTransportCapabilities(+ preferred === TRANSPORT.AUTO ? { probe: true } : {},+ );+ if (preferred === TRANSPORT.AUTO) {+ // Resolve "auto" from the backend's own verdict, not independently: the resolved transport is+ // compared against an existing partial's `.transport` marker, so the two must agree.+ return capabilities.auto_resolves_to === TRANSPORT.HTTP+ ? TRANSPORT.HTTP+ : TRANSPORT.XET;}- const capabilities = await getDownloadTransportCapabilities();if (capabilities.xet.available === true) {lastXetUnavailableWarningReason = null;return preferred;diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.tsindex e10b9a53701..1566bc4d132 100644--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts@@ -36,6 +36,7 @@ import {DOWNLOAD_KIND,TRANSPORT,type DownloadKind,+ type ResolvedTransport,type TransportMode,} from "./constants";import {@@ -625,11 +626,16 @@ export async function startJob(const expected = Math.max(existing?.expectedBytes ?? 0, req.expectedBytes);const hfToken = getHfToken() || null;- const requestedUseXet = opts.useXet ?? (getTransportMode() === TRANSPORT.XET);- const requestedMode: TransportMode = requestedUseXet- ? TRANSPORT.XET- : TRANSPORT.HTTP;- let mode: TransportMode;+ // An explicit opts.useXet (a retry pinning a transport) wins; otherwise carry the stored+ // preference UNRESOLVED so "auto" survives to effectiveTransportMode(). Collapsing it to a+ // boolean here would read "auto" as "not xet" and send every download over HTTP.+ const requestedMode: TransportMode =+ opts.useXet === undefined+ ? getTransportMode()+ : opts.useXet+ ? TRANSPORT.XET+ : TRANSPORT.HTTP;+ let mode: ResolvedTransport;try {mode = opts.adopt? TRANSPORT.HTTPdiff --git a/studio/frontend/src/features/hub/download-manager/transport-capabilities.ts b/studio/frontend/src/features/hub/download-manager/transport-capabilities.tsnew file mode 100644index 00000000000..1d484fcf2be--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/transport-capabilities.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Kept OUT of api.ts on purpose: api.ts imports the auth barrel, which the test runner cannot+// load, so anything defined there is untestable. That is how a normalizer silently dropping the+// backend's Auto verdict shipped green.++export interface DownloadTransportCapability {+ available: boolean | null;+ reason: string | null;+}++export interface DownloadTransportCapabilities {+ http: DownloadTransportCapability;+ xet: DownloadTransportCapability;+ // What "auto" resolves to right now, and why. Server-side because only the backend can see this+ // machine's RAM, hf_xet build, and recent Xet failures.+ auto_resolves_to?: "xet" | "http";+ auto_reason?: string | null;+}++export const DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK: DownloadTransportCapabilities = {+ http: { available: true, reason: null },+ xet: {+ available: null,+ reason: "Couldn't verify Xet support with the Unsloth backend.",+ },+ // Unknown backend state: stay on Xet, the download-time ladder still falls back to HTTP.+ auto_resolves_to: "xet",+ auto_reason: null,+};+export function normalizeDownloadTransportCapability(+ value: unknown,+ fallback: DownloadTransportCapability,+): DownloadTransportCapability {+ if (!value || typeof value !== "object") {+ return fallback;+ }+ const candidate = value as { available?: unknown; reason?: unknown };+ return {+ available:+ typeof candidate.available === "boolean"+ ? candidate.available+ : fallback.available,+ reason:+ typeof candidate.reason === "string"+ ? candidate.reason+ : candidate.reason === null+ ? null+ : fallback.reason,+ };+}++export function normalizeDownloadTransportCapabilities(+ value: unknown,+): DownloadTransportCapabilities {+ if (!value || typeof value !== "object") {+ return DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK;+ }+ const candidate = value as {+ http?: unknown;+ xet?: unknown;+ auto_resolves_to?: unknown;+ auto_reason?: unknown;+ };+ return {+ http: normalizeDownloadTransportCapability(candidate.http, {+ available: true,+ reason: null,+ }),+ xet: normalizeDownloadTransportCapability(+ candidate.xet,+ DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK.xet,+ ),+ // Carry the backend's verdict through. Dropping these left effectiveTransportMode("auto")+ // reading undefined, so Auto always resolved to Xet whatever the machine's health was.+ auto_resolves_to:+ candidate.auto_resolves_to === "http" || candidate.auto_resolves_to === "xet"+ ? candidate.auto_resolves_to+ : DOWNLOAD_TRANSPORT_CAPABILITIES_FALLBACK.auto_resolves_to,+ auto_reason:+ typeof candidate.auto_reason === "string" ? candidate.auto_reason : null,+ };+}diff --git a/studio/frontend/tests/transport-capabilities.test.ts b/studio/frontend/tests/transport-capabilities.test.tsnew file mode 100644index 00000000000..c6f9fb9d65b--- /dev/null+++ b/studio/frontend/tests/transport-capabilities.test.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++const { normalizeDownloadTransportCapabilities } = await import(+ "../src/features/hub/download-manager/transport-capabilities.ts"+);++test("the backend's auto verdict survives normalization", () => {+ // Rebuilding the object from http/xet alone discarded the verdict, so Auto resolved to Xet on+ // every machine, including ones the backend had just demoted to HTTP.+ const caps = normalizeDownloadTransportCapabilities({+ http: { available: true, reason: null },+ xet: { available: true, reason: null },+ auto_resolves_to: "http",+ auto_reason: "Xet stalled twice on this machine",+ });++ assert.equal(caps.auto_resolves_to, "http");+ assert.equal(caps.auto_reason, "Xet stalled twice on this machine");+});++test("a backend with no auto fields still resolves to xet", () => {+ // Older backend, predating Auto: the download-time ladder still falls back to HTTP, so Xet is+ // the safe assumption.+ const caps = normalizeDownloadTransportCapabilities({+ http: { available: true, reason: null },+ xet: { available: true, reason: null },+ });++ assert.equal(caps.auto_resolves_to, "xet");+ assert.equal(caps.auto_reason, null);+});++test("a junk auto verdict is not trusted", () => {+ const caps = normalizeDownloadTransportCapabilities({+ http: { available: true, reason: null },+ xet: { available: true, reason: null },+ auto_resolves_to: "carrier-pigeon",+ auto_reason: 42,+ });++ assert.equal(caps.auto_resolves_to, "xet");+ assert.equal(caps.auto_reason, null);+});diff --git a/studio/frontend/tests/transport-mode-auto.test.ts b/studio/frontend/tests/transport-mode-auto.test.tsnew file mode 100644index 00000000000..52d4b5eb263--- /dev/null+++ b/studio/frontend/tests/transport-mode-auto.test.ts@@ -0,0 +1,50 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();++// constants.ts only: transport-preference.ts reaches lib/toast -> a .tsx barrel node's type+// stripping cannot load. It adds no decision logic (readStored() is exactly+// `isTransportMode(raw) ? raw : DEFAULT_TRANSPORT_MODE`), so these two exports pin the contract.+const {+ DEFAULT_TRANSPORT_MODE,+ RESOLVED_TRANSPORTS,+ TRANSPORT,+ TRANSPORT_MODES,+ isResolvedTransport,+ isTransportMode,+} = await import("../src/features/hub/download-manager/constants.ts");++test("auto is the default transport preference", () => {+ // The backend picks per machine (RAM, hf_xet build, recent Xet failures), and a user who never+ // touches this control is the one who most needs that.+ assert.equal(DEFAULT_TRANSPORT_MODE, TRANSPORT.AUTO);+});++test("auto is a preference, not a transport a download can run on", () => {+ // Only "xet"/"http" reach a .transport marker: it records which writer produced a partial, and+ // a resume picks its strategy from it.+ assert.ok(TRANSPORT_MODES.includes(TRANSPORT.AUTO));+ assert.ok(!RESOLVED_TRANSPORTS.includes(TRANSPORT.AUTO as never));+ assert.ok(isResolvedTransport("xet"));+ assert.ok(isResolvedTransport("http"));+ assert.ok(!isResolvedTransport("auto"));+});++test("a previously stored explicit preference is still valid", () => {+ // Someone who pinned HTTP (or Xet) before this change must not be moved onto Auto:+ // isTransportMode() accepting the old values is what keeps readStored() returning them.+ assert.ok(isTransportMode("http"));+ assert.ok(isTransportMode("xet"));+});++test("an unrecognised stored value is rejected, so readStored falls back to auto", () => {+ for (const junk of ["ftp", "", "AUTO", null, undefined, 3]) {+ assert.ok(!isTransportMode(junk), `${String(junk)} should not be a transport mode`);+ }+});