Skip to content

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.

Studio: Use saved Hugging Face login for model downloads (#10758)

Nilay5c04ec19305e
diff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.py
index a2088a637da..e0c50578155 100644
--- a/studio/backend/hub/services/datasets/downloads.py
+++ b/studio/backend/hub/services/datasets/downloads.py
@@ -249,74 +249,79 @@ async def download_dataset_response(
cache_paths = get_hf_cache_paths()
cache_env = cache_paths.child_env({})
- registry = _account_registry()
- claimed, claim_state = _claim_dataset_download(
- registry,
- key,
- transport,
- repo_type = "dataset",
- repo_id = repo_id,
- hub_cache = str(cache_paths.hub_cache),
- xet_cache = str(cache_paths.xet_cache),
- )
- generation = registry.current_generation(key)
- if not claimed:
- # Both come from adoptable: an in-progress delete leaves no job, and only an in-flight job of this
- # repo attached to anything.
- adoptable = registry.adoptable(key)
+ def claim_and_launch():
+ # Claim and launch as one operation, off the loop: a cancel while queued must not
+ # leave a claimed job with no worker, and token resolution can do network I/O.
+ registry = _account_registry()
+ claimed, claim_state = _claim_dataset_download(
+ registry,
+ key,
+ transport,
+ repo_type = "dataset",
+ repo_id = repo_id,
+ hub_cache = str(cache_paths.hub_cache),
+ xet_cache = str(cache_paths.xet_cache),
+ )
+ generation = registry.current_generation(key)
+ if not claimed:
+ # Both come from adoptable: an in-progress delete leaves no job, and only an in-flight job of this
+ # repo attached to anything.
+ adoptable = registry.adoptable(key)
+ return {
+ "repo_id": repo_id,
+ "state": claim_state,
+ "accepted": adoptable,
+ "attached": adoptable,
+ "generation": generation,
+ # An adopted job keeps the transport it started on, so report it rather than let the caller assume
+ # the one it asked for.
+ "transport": registry.job_transport(key),
+ # And its cancel marker: a run that fell back from Xet to HTTP still cancels into a restart-only
+ # partial.
+ "cancel_transport": registry.job_cancel_transport(key),
+ }
+ # Record ownership with the claim, not at launch: retirement scans this registry, and an
+ # unattributed job makes its cancel raise "Download not found" and abort the deletion.
+ download_lifecycle.record_download_account(registry, key)
+ download_manifest.clear_cancel_marker(
+ "dataset",
+ repo_id,
+ None,
+ hub_cache = cache_paths.hub_cache,
+ )
+
+ state = download_lifecycle.launch_worker(
+ registry,
+ key,
+ spawn = lambda: download_lifecycle.spawn_worker(
+ ["--repo-id", repo_id, "--dataset"],
+ hf_token,
+ use_xet = use_xet,
+ cache_env = cache_env,
+ allow_ambient_token = allow_ambient_token,
+ ),
+ hf_token = hf_token,
+ allow_ambient_token = allow_ambient_token,
+ label = repo_id,
+ log_prefix = "Dataset download",
+ logger = logger,
+ repo_type = "dataset",
+ repo_id = repo_id,
+ transport = transport,
+ watch_name = f"hf-dataset-download-watch-{repo_id}",
+ )
+
return {
"repo_id": repo_id,
- "state": claim_state,
- "accepted": adoptable,
- "attached": adoptable,
+ "state": state,
+ "accepted": True,
+ "attached": False,
"generation": generation,
- # An adopted job keeps the transport it started on, so report it rather than let the caller assume
- # the one it asked for.
- "transport": registry.job_transport(key),
- # And its cancel marker: a run that fell back from Xet to HTTP still cancels into a restart-only
- # partial.
- "cancel_transport": registry.job_cancel_transport(key),
+ # See models: the resolved transport, which a downgrade can make different from the one requested.
+ "transport": transport,
}
- # Record ownership with the claim, not at launch: retirement scans this registry, and an
- # unattributed job makes its cancel raise "Download not found" and abort the deletion.
- download_lifecycle.record_download_account(registry, key)
- download_manifest.clear_cancel_marker(
- "dataset",
- repo_id,
- None,
- hub_cache = cache_paths.hub_cache,
- )
-
- state = download_lifecycle.launch_worker(
- registry,
- key,
- spawn = lambda: download_lifecycle.spawn_worker(
- ["--repo-id", repo_id, "--dataset"],
- hf_token,
- use_xet = use_xet,
- cache_env = cache_env,
- allow_ambient_token = allow_ambient_token,
- ),
- hf_token = hf_token,
- allow_ambient_token = allow_ambient_token,
- label = repo_id,
- log_prefix = "Dataset download",
- logger = logger,
- repo_type = "dataset",
- repo_id = repo_id,
- transport = transport,
- watch_name = f"hf-dataset-download-watch-{repo_id}",
- )
- return {
- "repo_id": repo_id,
- "state": state,
- "accepted": True,
- "attached": False,
- "generation": generation,
- # See models: the resolved transport, which a downgrade can make different from the one requested.
- "transport": transport,
- }
+ return await asyncio.to_thread(claim_and_launch)
async def cancel_dataset_download_response(body: CancelDatasetDownloadRequest) -> dict:
diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.py
index 55ac2f737ad..597fc64aab1 100644
--- a/studio/backend/hub/services/download_lifecycle.py
+++ b/studio/backend/hub/services/download_lifecycle.py
@@ -164,8 +164,15 @@ def write_files_manifest(files: Sequence[str]) -> str:
handle = tempfile.NamedTemporaryFile(
mode = "w", suffix = ".json", prefix = "unsloth-dl-files-", delete = False, encoding = "utf-8"
)
- with handle:
- json.dump(list(files), handle)
+ try:
+ with handle:
+ json.dump(list(files), handle)
+ except BaseException:
+ try:
+ Path(handle.name).unlink(missing_ok = True)
+ except OSError:
+ pass
+ raise
return handle.name
@@ -177,6 +184,7 @@ def spawn_worker(
protected_blob_hashes: Optional[frozenset[str]] = None,
cache_env: Optional[Mapping[str, str]] = None,
allow_ambient_token: bool = True,
+ files: Optional[Sequence[str]] = None,
) -> subprocess.Popen:
"""Spawn the download worker.
@@ -211,9 +219,18 @@ def spawn_worker(
# No tuning module: that unsloth_zoo is also the one setting HF_XET_HIGH_PERFORMANCE=1 at import, and the inherited "1" would hand the worker a 64GB ceiling, since xet-core applies the preset AFTER reading the environment.
for key in ("HF_XET_HIGH_PERFORMANCE", "HF_XET_HP"):
env[key] = "0"
- # Fall back to the backend's own HF_TOKEN so private repos stay downloadable, but never for a repo an API caller named: that would lend them the owner's identity.
if not hf_token and allow_ambient_token:
- hf_token = os.environ.get("HF_TOKEN") or None
+ from huggingface_hub.utils import get_token_to_send
+ try:
+ hf_token = get_token_to_send(None)
+ except Exception as e: # noqa: BLE001
+ # Best effort, like the env lookup this replaced: do not narrow this catch. An OIDCError
+ # or httpx error from hub's OIDC rung would 500 a public download and strand a reservation.
+ detail = download_registry.scrub_secrets(f"{type(e).__name__}: {e}")
+ logger.warning(
+ f"Could not resolve a saved Hugging Face login ({detail}); downloading anonymously"
+ )
+ hf_token = None
env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] = "0" if hf_token else "1"
# hf_transfer's parallel Range chunks can leave sparse partials even in "http" mode, so disable it and keep the worker's writer sequential.
env["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
@@ -230,7 +247,11 @@ def spawn_worker(
existing_path = env.get("PYTHONPATH", "")
env["PYTHONPATH"] = f"{cwd}{os.pathsep}{existing_path}" if existing_path else str(cwd)
proc = None
+ files_manifest = None
try:
+ if files:
+ files_manifest = write_files_manifest(files)
+ args = [*args, "--files-json", files_manifest]
proc = subprocess.Popen(
[
sys.executable,
@@ -250,6 +271,11 @@ def spawn_worker(
)
return proc
finally:
+ if proc is None and files_manifest is not None:
+ try:
+ Path(files_manifest).unlink(missing_ok = True)
+ except OSError:
+ logger.warning("Could not remove the unconsumed download files manifest")
if use_xet:
# Tie the sizing's RAM reservation to the worker so it frees when the worker exits and a sibling sizes against the remainder; a spawn that raised passes None, dropping the reservation.
from utils import hf_xet_fallback
@@ -323,6 +349,19 @@ def classify_exit(rc: int, *, cancel_requested: bool = False) -> str:
return "error"
+def _cleanup_worker_files_manifest(proc: subprocess.Popen) -> None:
+ args = getattr(proc, "args", None)
+ if not isinstance(args, (list, tuple)) or "--files-json" not in args:
+ return
+ index = args.index("--files-json") + 1
+ if index >= len(args) or proc.poll() is None:
+ return
+ try:
+ Path(args[index]).unlink(missing_ok = True)
+ except OSError:
+ logger.warning("Could not remove the exited worker's download files manifest")
+
+
def finalize_worker_exit(
registry: download_registry.DownloadRegistry,
key: str,
@@ -341,6 +380,7 @@ def finalize_worker_exit(
"""Block until *proc* exits, then record the job's terminal state in *registry*. Drains and scrubs stderr first, then classifies the exit code. A no-op when the process was already dropped (e.g. superseded). No stall watchdog: huggingface_hub already times out chunk reads and raises a resumable error on a dead connection, so the worker's exit code is the single source of truth."""
stderr_data = drain_stderr_excerpt(proc.stderr)
rc = proc.wait()
+ _cleanup_worker_files_manifest(proc)
cancel_requested = registry.cancel_requested(key)
if not registry.drop_process(key, proc):
return "idle"
@@ -608,10 +648,6 @@ def _try_transport_retry(
args.append("--dataset")
elif variant:
args.extend(["--variant", variant])
- # A scoped job must retry as the SAME scoped download; without its file list the recovery worker would fall through to a full snapshot.
- if original_metadata.scoped_files:
- args.extend(["--files-json", write_files_manifest(original_metadata.scoped_files)])
-
peer_hashes = registry.peer_blob_hashes(key) if variant else frozenset()
if retry_over_xet:
@@ -644,6 +680,8 @@ def _try_transport_retry(
}
if cache_env is not None:
spawn_kwargs["cache_env"] = cache_env
+ if original_metadata.scoped_files:
+ spawn_kwargs["files"] = original_metadata.scoped_files
proc = spawn_worker(
args,
hf_token,
@@ -741,6 +779,7 @@ def kill_and_reap_process(
logger.warning(f"Cancelled worker for {label} did not exit after SIGKILL")
except Exception:
pass
+ _cleanup_worker_files_manifest(proc)
def _record_xet_failure(reason: str, logger) -> None:
@@ -1118,11 +1157,22 @@ def launch_worker(
proc = spawn()
except Exception as e:
scrubbed = download_registry.scrub_secrets(str(e), hf_token = hf_token)
+ state = _set_retry_failure_state(
+ registry,
+ key,
+ scrubbed,
+ repo_type = repo_type,
+ repo_id = repo_id,
+ fallback_variant = download_registry.variant_from_key(key),
+ fallback_transport = transport,
+ logger = logger,
+ )
+ if state == "cancelled":
+ return state
logger.error(
f"Failed to spawn {log_prefix.lower()} worker for {label}: {scrubbed}",
exc_info = True,
)
- registry.set_job(key, "error", scrubbed)
raise HTTPException(
status_code = 500,
detail = f"Failed to start {log_prefix.lower()}: {scrubbed}",
@@ -1157,9 +1207,13 @@ def cancel_worker(
proc = registry.get_process(key)
# No worker process yet: arm a pending cancel so register_process kills it on arrival during the claim-to-register window.
if proc is None:
- if registry.mark_pending_cancel(key, generation):
+ if not registry.mark_pending_cancel(key, generation):
+ return registry.get_job(key).state
+ # Registration can race the first lookup now that launch runs in a thread: if it got
+ # past the pending-cancel check, kill that process below.
+ proc = registry.get_process(key)
+ if proc is None:
return "cancelling"
- return registry.get_job(key).state
# Worker already exited; let its watcher classify the real return code.
if proc.poll() is not None:
get_metadata = getattr(registry, "get_job_metadata", None)
diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.py
index 3ae7767daf2..da2ea7df478 100644
--- a/studio/backend/hub/services/models/downloads.py
+++ b/studio/backend/hub/services/models/downloads.py
@@ -151,9 +151,6 @@ def _spawn_download_worker(
args = ["--repo-id", repo_id]
if variant:
args.extend(["--variant", variant])
- if files:
- # Via a temp file, not argv: a pipeline repo's list runs to hundreds of names.
- args.extend(["--files-json", download_lifecycle.write_files_manifest(files)])
return download_lifecycle.spawn_worker(
args,
hf_token,
@@ -161,6 +158,7 @@ def _spawn_download_worker(
protected_blob_hashes = protected_blob_hashes,
cache_env = cache_env,
allow_ambient_token = allow_ambient_token,
+ files = files,
)
@@ -275,94 +273,99 @@ async def download_model_response(
variant_progress_blob_hashes,
)
- claimed, claim_state = _registry.claim(
- key,
- transport,
- repo_type = "model",
- repo_id = repo_id,
- variant = variant,
- blob_hashes = variant_blob_hashes,
- progress_blob_hashes = variant_progress_blob_hashes,
- completed_baseline_bytes = completed_baseline_bytes,
- admission_check = lambda: not _load_in_flight(repo_id),
- hub_cache = str(cache_paths.hub_cache),
- xet_cache = str(cache_paths.xet_cache),
- scoped_files = scoped_files if scope_variant is not None else None,
- )
- generation = _registry.current_generation(key)
- if not claimed:
- download_lifecycle.require_download_account(_registry, key)
- if claim_state == "admission_blocked":
- raise _load_in_flight_error(repo_id)
- if claim_state == "scope_file_mismatch":
- raise HTTPException(
- status_code = 409,
- detail = (
- f"Another download for '{repo_id}' is already fetching a different "
- "set of files. Wait for it to finish (or cancel it), then start "
- "this one."
- ),
- )
- # claim_state is the blocking job's state. Attaching and accepting are one verdict: only this key's own in-flight job can be joined, and a cross-variant conflict or in-progress delete joined nothing.
- adoptable = _registry.adoptable(key)
+ def claim_and_launch():
+ # Claim and launch as one operation, off the loop: a cancel while queued must not
+ # leave a claimed job with no worker, and token resolution can do network I/O.
+ claimed, claim_state = _registry.claim(
+ key,
+ transport,
+ repo_type = "model",
+ repo_id = repo_id,
+ variant = variant,
+ blob_hashes = variant_blob_hashes,
+ progress_blob_hashes = variant_progress_blob_hashes,
+ completed_baseline_bytes = completed_baseline_bytes,
+ admission_check = lambda: not _load_in_flight(repo_id),
+ hub_cache = str(cache_paths.hub_cache),
+ xet_cache = str(cache_paths.xet_cache),
+ scoped_files = scoped_files if scope_variant is not None else None,
+ )
+ generation = _registry.current_generation(key)
+ if not claimed:
+ download_lifecycle.require_download_account(_registry, key)
+ if claim_state == "admission_blocked":
+ raise _load_in_flight_error(repo_id)
+ if claim_state == "scope_file_mismatch":
+ raise HTTPException(
+ status_code = 409,
+ detail = (
+ f"Another download for '{repo_id}' is already fetching a different "
+ "set of files. Wait for it to finish (or cancel it), then start "
+ "this one."
+ ),
+ )
+ # claim_state is the blocking job's state. Attaching and accepting are one verdict: only this key's own in-flight job can be joined, and a cross-variant conflict or in-progress delete joined nothing.
+ adoptable = _registry.adoptable(key)
+ return {
+ "job_key": key,
+ "state": claim_state,
+ "accepted": adoptable,
+ "attached": adoptable,
+ "generation": generation,
+ # An adopted job keeps the transport it started on, so report it rather than let the caller assume the one it asked for.
+ "transport": _registry.job_transport(key),
+ # And its cancel marker: a run that fell back from Xet to HTTP still cancels into a restart-only partial.
+ "cancel_transport": _registry.job_cancel_transport(key),
+ }
+ # Record ownership with the claim, not at launch, or the last downloader keeps the key.
+ download_lifecycle.record_download_account(_registry, key)
+ # Only then read the tombstone: an account retired during the awaits must not spawn.
+ download_lifecycle.require_live_account(_registry, key)
+ download_manifest.clear_cancel_marker(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = cache_paths.hub_cache,
+ )
+ # Blobs a concurrent same-repo variant is already writing, such as a shared mmproj: the worker must not purge these during cache preparation.
+ protected_blob_hashes = _registry.peer_blob_hashes(key) if variant else frozenset()
+
+ label = f"{repo_id}{f' [{variant}]' if variant else ''}"
+ state = download_lifecycle.launch_worker(
+ _registry,
+ key,
+ spawn = lambda: _spawn_download_worker(
+ repo_id,
+ variant,
+ hf_token,
+ use_xet = use_xet,
+ protected_blob_hashes = protected_blob_hashes,
+ cache_env = cache_env,
+ files = scoped_files if scope_variant is not None else None,
+ allow_ambient_token = allow_ambient_token,
+ ),
+ hf_token = hf_token,
+ allow_ambient_token = allow_ambient_token,
+ label = label,
+ log_prefix = "Download",
+ logger = logger,
+ repo_type = "model",
+ repo_id = repo_id,
+ transport = transport,
+ watch_name = f"hf-download-watch-{repo_id}",
+ )
+
return {
"job_key": key,
- "state": claim_state,
- "accepted": adoptable,
- "attached": adoptable,
+ "state": state,
+ "accepted": True,
+ "attached": False,
"generation": generation,
- # An adopted job keeps the transport it started on, so report it rather than let the caller assume the one it asked for.
- "transport": _registry.job_transport(key),
- # And its cancel marker: a run that fell back from Xet to HTTP still cancels into a restart-only partial.
- "cancel_transport": _registry.job_cancel_transport(key),
+ # The transport actually resolved: an explicit "xet" is downgraded to HTTP where hf_xet is unavailable, and a client that assumed its request stood would offer the wrong stop control.
+ "transport": transport,
}
- # Record ownership with the claim, not at launch, or the last downloader keeps the key.
- download_lifecycle.record_download_account(_registry, key)
- # Only then read the tombstone: an account retired during the awaits must not spawn.
- download_lifecycle.require_live_account(_registry, key)
- download_manifest.clear_cancel_marker(
- "model",
- repo_id,
- variant,
- hub_cache = cache_paths.hub_cache,
- )
- # Blobs a concurrent same-repo variant is already writing, such as a shared mmproj: the worker must not purge these during cache preparation.
- protected_blob_hashes = _registry.peer_blob_hashes(key) if variant else frozenset()
-
- label = f"{repo_id}{f' [{variant}]' if variant else ''}"
- state = download_lifecycle.launch_worker(
- _registry,
- key,
- spawn = lambda: _spawn_download_worker(
- repo_id,
- variant,
- hf_token,
- use_xet = use_xet,
- protected_blob_hashes = protected_blob_hashes,
- cache_env = cache_env,
- files = scoped_files if scope_variant is not None else None,
- allow_ambient_token = allow_ambient_token,
- ),
- hf_token = hf_token,
- allow_ambient_token = allow_ambient_token,
- label = label,
- log_prefix = "Download",
- logger = logger,
- repo_type = "model",
- repo_id = repo_id,
- transport = transport,
- watch_name = f"hf-download-watch-{repo_id}",
- )
- return {
- "job_key": key,
- "state": state,
- "accepted": True,
- "attached": False,
- "generation": generation,
- # The transport actually resolved: an explicit "xet" is downgraded to HTTP where hf_xet is unavailable, and a client that assumed its request stood would offer the wrong stop control.
- "transport": transport,
- }
+ return await asyncio.to_thread(claim_and_launch)
def retire_account_downloads() -> None:
diff --git a/studio/backend/tests/test_hub_download_ambient_token.py b/studio/backend/tests/test_hub_download_ambient_token.py
index 5ab93a455e4..3aa9d079ac2 100644
--- a/studio/backend/tests/test_hub_download_ambient_token.py
+++ b/studio/backend/tests/test_hub_download_ambient_token.py
@@ -235,17 +235,17 @@ def _spawn_env(monkeypatch, hf_token, **kwargs):
captured = {}
class _Fake:
- pass
+ pid = 4242
def _fake_popen(*_args, **popen_kwargs):
captured.update(popen_kwargs["env"])
return _Fake()
monkeypatch.setattr(download_lifecycle.subprocess, "Popen", _fake_popen)
+ kwargs.setdefault("use_xet", False)
download_lifecycle.spawn_worker(
["--repo-id", "attacker/private-model"],
hf_token,
- use_xet = False,
**kwargs,
)
return captured
@@ -281,7 +281,10 @@ def test_an_explicit_request_token_wins_over_the_backend_one(monkeypatch):
assert env["HF_TOKEN"] == "request-token"
-def test_an_anonymous_job_stays_anonymous_on_the_http_retry(monkeypatch, tmp_path):
[email protected]("allow_ambient", [False, True])
+def test_http_retry_preserves_ambient_token_policy(
+ monkeypatch, tmp_path, cached_hf_login, allow_ambient
+):
"""The recovery ladder must carry the token policy: a job started without the ambient token
must not pick it up when the Xet worker fails and the HTTP one takes over."""
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
@@ -300,6 +303,14 @@ def test_an_anonymous_job_stays_anonymous_on_the_http_retry(monkeypatch, tmp_pat
blob_hashes = frozenset({"blob"}),
)[0]
retried = []
+ environments = []
+ original_spawn = download_lifecycle.spawn_worker
+
+ def fake_popen(*args, **kwargs):
+ environments.append(kwargs["env"])
+ return _Proc(0)
+
+ monkeypatch.setattr(download_lifecycle.subprocess, "Popen", fake_popen)
def fake_spawn(
_args,
@@ -310,7 +321,13 @@ def test_an_anonymous_job_stays_anonymous_on_the_http_retry(monkeypatch, tmp_pat
**_kwargs,
):
retried.append(allow_ambient_token)
- return _Proc(0)
+ return original_spawn(
+ _args,
+ _token,
+ use_xet = use_xet,
+ allow_ambient_token = allow_ambient_token,
+ **_kwargs,
+ )
monkeypatch.setattr(download_lifecycle, "spawn_worker", fake_spawn)
monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)
@@ -326,7 +343,195 @@ def test_an_anonymous_job_stays_anonymous_on_the_http_retry(monkeypatch, tmp_pat
repo_id = "Org/Model",
transport = download_registry.TRANSPORT_XET,
watch_name = "model-watch",
+ allow_ambient_token = allow_ambient,
+ )
+
+ assert retried == [allow_ambient]
+ assert len(environments) == 1
+ assert environments[0].get("HF_TOKEN") == (cached_hf_login if allow_ambient else None)
+
+
+def cached_hf_login(monkeypatch, tmp_path):
+ from huggingface_hub import constants
+
+ token_path = tmp_path / "token"
+ token_path.write_text("hf_test_cached_login\n")
+ monkeypatch.setattr(constants, "HF_TOKEN_PATH", str(token_path))
+ monkeypatch.setattr(constants, "HF_HUB_DISABLE_IMPLICIT_TOKEN", False)
+ for key in (
+ "HF_TOKEN",
+ "HF_HUB_TOKEN",
+ "HUGGING_FACE_HUB_TOKEN",
+ "HUGGINGFACE_HUB_TOKEN",
+ "HUGGINGFACEHUB_API_TOKEN",
+ ):
+ monkeypatch.delenv(key, raising = False)
+ return "hf_test_cached_login"
+
+
[email protected]("allow_ambient", [False, True])
[email protected]("explicit", [None, "hf_test_request"])
[email protected]("implicit_disabled", [False, True])
+def test_cached_login_obeys_caller_and_implicit_auth_policy(
+ monkeypatch, cached_hf_login, allow_ambient, explicit, implicit_disabled
+):
+ from huggingface_hub import constants
+
+ monkeypatch.setattr(constants, "HF_HUB_DISABLE_IMPLICIT_TOKEN", implicit_disabled)
+ env = _spawn_env(monkeypatch, explicit, allow_ambient_token = allow_ambient)
+
+ expected = explicit or (cached_hf_login if allow_ambient and not implicit_disabled else None)
+ assert env.get("HF_TOKEN") == expected
+ assert env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == ("0" if expected else "1")
+
+
+def test_environment_token_takes_precedence_over_cached_login(monkeypatch, cached_hf_login):
+ monkeypatch.setenv("HF_TOKEN", "hf_test_environment")
+
+ env = _spawn_env(monkeypatch, None, allow_ambient_token = True)
+
+ assert env["HF_TOKEN"] == "hf_test_environment"
+
+
+def test_forbidden_ambient_token_is_not_resolved(monkeypatch, cached_hf_login):
+ import huggingface_hub.utils
+
+ def unexpected_resolution(*args):
+ pytest.fail("A restricted caller must not resolve the owner's credentials")
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", unexpected_resolution)
+ env = _spawn_env(
+ monkeypatch,
+ None,
allow_ambient_token = False,
+ cache_env = {
+ "HF_TOKEN": "hf_test_environment",
+ "HF_HUB_TOKEN": "hf_test_alias",
+ "HUGGING_FACE_HUB_TOKEN": "hf_test_alias",
+ "HUGGINGFACE_HUB_TOKEN": "hf_test_alias",
+ "HUGGINGFACEHUB_API_TOKEN": "hf_test_alias",
+ },
)
- assert retried == [False], "the HTTP retry regained the backend's token"
+ assert not any(
+ key in env
+ for key in (
+ "HF_TOKEN",
+ "HF_HUB_TOKEN",
+ "HUGGING_FACE_HUB_TOKEN",
+ "HUGGINGFACE_HUB_TOKEN",
+ "HUGGINGFACEHUB_API_TOKEN",
+ )
+ )
+ assert env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == "1"
+
+
[email protected]("failure", ["unreadable", "invalid_encoding"])
+def test_unusable_cached_login_does_not_block_an_anonymous_worker(
+ monkeypatch, cached_hf_login, failure
+):
+ from pathlib import Path
+ from huggingface_hub import constants
+
+ token_path = Path(constants.HF_TOKEN_PATH)
+ if failure == "invalid_encoding":
+ token_path.write_bytes(b"\x81")
+ else:
+ original_read_text = Path.read_text
+
+ def read_text(path, *args, **kwargs):
+ if path == token_path:
+ raise PermissionError("cached token is unreadable")
+ return original_read_text(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", read_text)
+
+ env = _spawn_env(monkeypatch, None, allow_ambient_token = True)
+
+ assert "HF_TOKEN" not in env
+ assert env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == "1"
+
+
+class _OIDCLike(Exception):
+ """Stands in for huggingface_hub's OIDCError, which is a plain Exception."""
+
+
+class _HttpxLike(Exception):
+ """Stands in for httpx.ConnectError, which is not an OSError either."""
+
+
+# Everything hub's resolver can raise that is NOT an unreadable-file OSError/UnicodeError. The OIDC
+# rungs reach all of these whenever HF_OIDC_RESOURCE is set in the backend's environment.
+_RESOLVER_FAILURES = [
+ _OIDCLike("no OIDC id token is available"),
+ _HttpxLike("all connection attempts failed"),
+ NotImplementedError("unsupported OIDC provider"),
+ ValueError("malformed stored token"),
+ RuntimeError("unexpected hub failure"),
+]
+
+
[email protected]("failure", _RESOLVER_FAILURES, ids = lambda e: type(e).__name__)
+def test_a_failed_ambient_lookup_still_starts_an_anonymous_worker(
+ monkeypatch, cached_hf_login, failure
+):
+ """The ambient lookup is best effort. Before it existed this branch was an os.environ read and
+ could not raise, so letting one escape would take a public download down with a 500."""
+ import huggingface_hub.utils
+
+ def raiser(*args):
+ raise failure
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", raiser)
+ env = _spawn_env(monkeypatch, None, allow_ambient_token = True)
+
+ assert "HF_TOKEN" not in env
+ assert env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == "1"
+
+
+def test_a_failed_ambient_lookup_does_not_strand_the_xet_reservation(monkeypatch, cached_hf_login):
+ """apply_xet_env books RAM against the imminent spawn and only bind_worker_budget settles it, so
+ a resolver that escaped in between would leave the promise counted against every sibling."""
+ import huggingface_hub.utils
+ from utils import hf_xet_fallback
+
+ def sized(env, cache_dir = None):
+ hf_xet_fallback._reserve_worker_budget(1 << 30)
+ return dict(env)
+
+ monkeypatch.setattr(hf_xet_fallback, "apply_xet_env", sized)
+ monkeypatch.setattr(hf_xet_fallback._pending_reservation, "token", None, raising = False)
+ with hf_xet_fallback._budget_lock:
+ hf_xet_fallback._budget_reservations.clear()
+
+ def raiser(*args):
+ raise _OIDCLike("no OIDC id token is available")
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", raiser)
+ _spawn_env(monkeypatch, None, use_xet = True, allow_ambient_token = True)
+
+ with hf_xet_fallback._budget_lock:
+ unbound = [e for e in hf_xet_fallback._budget_reservations.values() if e[1] is None]
+ assert unbound == []
+
+
+def test_a_failed_ambient_lookup_reports_the_cause_without_the_credential(
+ monkeypatch, caplog, cached_hf_login
+):
+ """The warning has to name the failure to be diagnosable, and a resolver that quoted a token back
+ is exactly the case the existing scrubber exists for."""
+ import huggingface_hub.utils
+
+ leaked = "hf_" + "A" * 34
+
+ def raiser(*args):
+ raise RuntimeError(f"hub rejected {leaked}")
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", raiser)
+ with caplog.at_level(logging.WARNING):
+ _spawn_env(monkeypatch, None, allow_ambient_token = True)
+
+ assert leaked not in caplog.text
+ assert "RuntimeError" in caplog.text
+ assert "downloading anonymously" in caplog.text
diff --git a/studio/backend/tests/test_hub_download_token_off_event_loop.py b/studio/backend/tests/test_hub_download_token_off_event_loop.py
new file mode 100644
index 00000000000..9fa3912328a
--- /dev/null
+++ b/studio/backend/tests/test_hub_download_token_off_event_loop.py
@@ -0,0 +1,408 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Slow saved-token refresh must not stall requests or orphan claimed downloads."""
+
+import asyncio
+from concurrent.futures import ThreadPoolExecutor
+import threading
+from types import SimpleNamespace
+
+import pytest
+import huggingface_hub.utils
+
+from hub.schemas.downloads import DownloadModelRequest, DownloadDatasetRequest
+from hub.services import download_lifecycle
+from hub.services.models import downloads as models
+from hub.services.datasets import downloads as datasets
+from hub.utils import download_manifest, download_registry
+from utils import hf_cache_settings
+
+
[email protected](params = ["model", "dataset"])
+def download(monkeypatch, tmp_path, request):
+ model = request.param == "model"
+ service = models if model else datasets
+ request_cls = DownloadModelRequest if model else DownloadDatasetRequest
+ handler = service.download_model_response if model else service.download_dataset_response
+ registry = download_registry.DownloadRegistry()
+ monkeypatch.setattr(service, "_registry", registry)
+ monkeypatch.setattr(service, "resolve_cached_repo_id_case", lambda repo, **kw: repo)
+ monkeypatch.setattr(models, "_reject_if_load_in_flight", lambda repo: None)
+ monkeypatch.setattr(models, "_load_in_flight", lambda repo: False)
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *a, **kw: None)
+ paths = SimpleNamespace(
+ hub_cache = tmp_path / "hub",
+ xet_cache = tmp_path / "xet",
+ child_env = lambda *a: {},
+ )
+ monkeypatch.setattr(hf_cache_settings, "get_hf_cache_paths", lambda: paths)
+ spawned = []
+ registered = threading.Event()
+ proc = SimpleNamespace(pid = 4242, poll = lambda: None)
+
+ def popen(*args, **kwargs):
+ spawned.append(kwargs["env"].get("HF_TOKEN"))
+ return proc
+
+ def register(registry, key, proc, **kwargs):
+ accepted = registry.register_process(key, proc)
+ registered.set()
+ return accepted
+
+ monkeypatch.setattr(download_lifecycle.subprocess, "Popen", popen)
+ monkeypatch.setattr(download_lifecycle, "register_worker", register)
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", lambda token: "hf_fixture")
+ return SimpleNamespace(
+ handler = handler,
+ body = request_cls(repo_id = "fixture/public", use_xet = False),
+ registry = registry,
+ key = models._download_job_key("fixture/public", None)
+ if model
+ else datasets._download_job_key("fixture/public"),
+ repo_type = request.param,
+ proc = proc,
+ spawned = spawned,
+ registered = registered,
+ )
+
+
[email protected]("cancel_request", [False, True])
+def test_slow_token_resolution_keeps_loop_responsive(monkeypatch, download, cancel_request):
+ entered = threading.Event()
+ release = threading.Event()
+ responsive = threading.Event()
+ observations = []
+
+ def resolve(token):
+ entered.set()
+ assert release.wait(15), "observer failed to release token resolution"
+ return "hf_fixture"
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", resolve)
+
+ async def run():
+ loop = asyncio.get_running_loop()
+ task = asyncio.create_task(download.handler(download.body, None))
+
+ def probe():
+ if cancel_request:
+ task.cancel()
+ responsive.set()
+
+ def observer():
+ try:
+ if not entered.wait(10):
+ observations.append(False)
+ return
+ loop.call_soon_threadsafe(probe)
+ observations.append(responsive.wait(5))
+ finally:
+ release.set()
+
+ thread = threading.Thread(target = observer, daemon = True)
+ thread.start()
+ try:
+ if cancel_request:
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ else:
+ assert (await task)["accepted"] is True
+ assert await asyncio.to_thread(download.registered.wait, 10)
+ finally:
+ release.set()
+ await asyncio.to_thread(thread.join, 15)
+
+ asyncio.run(run())
+ assert observations == [True], "token resolution blocked the event loop"
+ assert download.spawned == ["hf_fixture"]
+ assert download.registry.get_process(download.key) is download.proc
+
+
+def test_cancellation_while_executor_busy_leaves_no_claim(monkeypatch, download):
+ release = threading.Event()
+ original_transport = download_lifecycle.resolve_transport
+
+ async def run():
+ loop = asyncio.get_running_loop()
+ loop.set_default_executor(ThreadPoolExecutor(max_workers = 1))
+ task = asyncio.current_task()
+ blocker = None
+
+ def transport(use_xet):
+ nonlocal blocker
+ # Earlier preparation awaits have finished. Occupy the only thread so
+ # the next offloaded operation is queued when the request is cancelled.
+ blocker = loop.run_in_executor(None, release.wait, 15)
+ loop.call_soon(task.cancel)
+ return original_transport(use_xet)
+
+ monkeypatch.setattr(download_lifecycle, "resolve_transport", transport)
+ try:
+ with pytest.raises(asyncio.CancelledError):
+ await download.handler(download.body, None)
+ finally:
+ release.set()
+ if blocker is not None:
+ await blocker
+ await asyncio.to_thread(lambda: None)
+
+ asyncio.run(run())
+ assert download.registry.get_job(download.key).state == "idle"
+ assert download.registry.get_process(download.key) is None
+ assert download.spawned == []
+
+
+def test_cancel_stops_worker_registered_after_initial_lookup(monkeypatch, download):
+ import logging
+
+ registry = download.registry
+ assert registry.claim(
+ download.key,
+ download_registry.TRANSPORT_HTTP,
+ repo_type = download.repo_type,
+ repo_id = "fixture/public",
+ )[0]
+ killed = []
+ download.proc.kill = lambda: killed.append(True)
+ get_process = registry.get_process
+ first = True
+
+ def lookup(key):
+ nonlocal first
+ proc = get_process(key)
+ if first:
+ first = False
+ assert proc is None
+ # The launch thread registers after cancel reads None but before it
+ # arms pending cancellation. Registration cannot see the future flag.
+ assert registry.register_process(key, download.proc)
+ return proc
+
+ monkeypatch.setattr(registry, "get_process", lookup)
+ assert (
+ download_lifecycle.cancel_worker(
+ registry,
+ download.key,
+ generation = registry.current_generation(download.key),
+ label = "fixture/public",
+ logger = logging.getLogger(__name__),
+ )
+ == "cancelling"
+ )
+ assert killed == [True]
+
+
+def test_a_failed_token_resolution_downloads_anonymously(monkeypatch, download):
+ """The ambient lookup is a fallback, so losing it must not fail a download that needed no
+ credential. Before it existed this branch was an os.environ read and could not raise."""
+
+ def resolve(token):
+ raise RuntimeError("fixture token exchange failed")
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", resolve)
+
+ result = asyncio.run(download.handler(download.body, None))
+
+ assert result["accepted"] is True
+ assert download.spawned == [None]
+ assert download.registry.get_process(download.key) is download.proc
+
+
[email protected]("cancel_download", [False, True])
+def test_launch_failure_preserves_download_cancellation(monkeypatch, download, cancel_download):
+ """The launch still runs in a thread, so a failure there has to settle the claim either way.
+
+ The failure is injected at the spawn rather than at token resolution: resolution is the ambient
+ fallback and no longer raises, so a launch failure is what reaches this path now.
+ """
+ from fastapi import HTTPException
+ from hub.schemas.downloads import CancelDownloadRequest, CancelDatasetDownloadRequest
+
+ entered = threading.Event()
+ release = threading.Event()
+
+ def resolve(token):
+ entered.set()
+ assert release.wait(10), "test did not release token resolution"
+ return None
+
+ def failing_popen(*args, **kwargs):
+ raise RuntimeError("fixture launch failure")
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", resolve)
+ monkeypatch.setattr(download_lifecycle.subprocess, "Popen", failing_popen)
+
+ async def run():
+ task = asyncio.create_task(download.handler(download.body, None))
+ try:
+ assert await asyncio.to_thread(entered.wait, 5)
+ if cancel_download:
+ model = download.repo_type == "model"
+ handler = (
+ models.cancel_download_model_response
+ if model
+ else datasets.cancel_dataset_download_response
+ )
+ request_cls = CancelDownloadRequest if model else CancelDatasetDownloadRequest
+ result = await handler(
+ request_cls(
+ repo_id = "fixture/public",
+ generation = download.registry.current_generation(download.key),
+ )
+ )
+ assert result["state"] == "cancelling"
+ release.set()
+ if cancel_download:
+ assert (await task)["state"] == "cancelled"
+ else:
+ with pytest.raises(HTTPException) as exc:
+ await task
+ assert exc.value.status_code == 500
+ assert "fixture launch failure" in exc.value.detail
+ finally:
+ release.set()
+ if not task.done():
+ await asyncio.gather(task, return_exceptions = True)
+
+ asyncio.run(run())
+ state = download.registry.get_job(download.key)
+ assert state.state == ("cancelled" if cancel_download else "error")
+ assert state.error == (None if cancel_download else "fixture launch failure")
+ assert download.spawned == []
+ assert download.registry.get_process(download.key) is None
+
+
[email protected]("failure_at", ["token", "manifest", "popen", None])
+def test_scoped_manifest_ownership_on_spawn_failure(monkeypatch, tmp_path, failure_at):
+ import json
+ from pathlib import Path
+ import tempfile
+
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path))
+ monkeypatch.setattr(
+ hf_cache_settings, "get_hf_cache_paths", lambda: SimpleNamespace(child_env = lambda: {})
+ )
+ error = (
+ RuntimeError("fixture token exchange failed")
+ if failure_at == "token"
+ else OSError("fixture spawn failure")
+ )
+ created = []
+ write = download_lifecycle.write_files_manifest
+ proc = object()
+ files = ["model_index.json", "weights.safetensors"]
+ commands = []
+
+ def resolve(token):
+ if failure_at == "token":
+ raise error
+ return None
+
+ def manifest(names):
+ path = write(names)
+ created.append(Path(path))
+ return path
+
+ def dump(*args, **kwargs):
+ raise error
+
+ def popen(args, **kwargs):
+ commands.append(args)
+ path = Path(args[args.index("--files-json") + 1])
+ assert json.loads(path.read_text(encoding = "utf-8")) == files
+ if failure_at == "popen":
+ raise error
+ return proc
+
+ monkeypatch.setattr(huggingface_hub.utils, "get_token_to_send", resolve)
+ monkeypatch.setattr(download_lifecycle, "write_files_manifest", manifest)
+ monkeypatch.setattr(download_lifecycle.subprocess, "Popen", popen)
+ if failure_at == "manifest":
+ monkeypatch.setattr(json, "dump", dump)
+
+ def spawn():
+ return models._spawn_download_worker(
+ "fixture/public", "@diffusion", None, use_xet = False, files = files
+ )
+
+ if failure_at in (None, "token"):
+ # A failed ambient lookup is not a spawn failure: the worker starts anonymously and, having
+ # started, owns its manifest.
+ assert spawn() is proc
+ assert len(created) == 1
+ assert created[0].exists(), "a started worker must retain its manifest"
+ else:
+ with pytest.raises(type(error)) as exc:
+ spawn()
+ assert exc.value is error
+ assert list(tmp_path.glob("unsloth-dl-files-*.json")) == []
+ assert len(commands) == (0 if failure_at == "manifest" else 1)
+
+
+ "phase", ["registration_rejected", "cancelled_after_registration", "kill_failed"]
+)
+def test_exited_worker_releases_unread_scoped_manifest(monkeypatch, tmp_path, phase):
+ import io
+ import logging
+ import subprocess
+ from pathlib import Path
+ import tempfile
+
+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path))
+ path = Path(download_lifecycle.write_files_manifest(["weights.safetensors"]))
+ registry = download_registry.DownloadRegistry()
+ key = models._download_job_key("fixture/public", "@diffusion")
+ assert registry.claim(
+ key,
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "fixture/public",
+ variant = "@diffusion",
+ hub_cache = str(tmp_path / "hub"),
+ )[0]
+ exited = False
+
+ def kill():
+ nonlocal exited
+ if phase == "kill_failed":
+ raise PermissionError("fixture kill failed")
+ exited = True
+
+ def wait(timeout = None):
+ if not exited:
+ raise subprocess.TimeoutExpired("fixture-worker", timeout or 0)
+ return -9
+
+ proc = SimpleNamespace(
+ pid = 4242,
+ args = ["python", "worker", "--files-json", str(path)],
+ stderr = io.BytesIO(),
+ kill = kill,
+ wait = wait,
+ poll = lambda: -9 if exited else None,
+ )
+ kwargs = dict(
+ hf_token = None,
+ label = "fixture/public",
+ log_prefix = "Download",
+ logger = logging.getLogger(__name__),
+ repo_type = "model",
+ repo_id = "fixture/public",
+ transport = download_registry.TRANSPORT_HTTP,
+ )
+ if phase == "cancelled_after_registration":
+ assert registry.register_process(key, proc)
+ assert registry.request_cancel(key, proc, registry.current_generation(key))
+ proc.kill()
+ assert download_lifecycle.finalize_worker_exit(registry, key, proc, **kwargs) == "cancelled"
+ else:
+ assert registry.mark_pending_cancel(key, registry.current_generation(key))
+ assert (
+ download_lifecycle.register_worker(
+ registry, key, proc, watch_name = "fixture-watch", **kwargs
+ )
+ is False
+ )
+ assert path.exists() is (phase == "kill_failed")
diff --git a/studio/backend/tests/test_scoped_download_job.py b/studio/backend/tests/test_scoped_download_job.py
index fa93b1262b9..06db072d2da 100644
--- a/studio/backend/tests/test_scoped_download_job.py
+++ b/studio/backend/tests/test_scoped_download_job.py
@@ -80,7 +80,7 @@ def test_scope_requires_files_and_rejects_a_variant(monkeypatch):
assert "mutually exclusive" in str(both.value)
-def test_scoped_start_spawns_a_file_scoped_worker(monkeypatch):
+def test_scoped_start_spawns_a_file_scoped_worker(monkeypatch, tmp_path):
spawned: dict = {}
monkeypatch.setattr(dl, "_reject_if_load_in_flight", lambda repo_id: None)
@@ -91,12 +91,14 @@ def test_scoped_start_spawns_a_file_scoped_worker(monkeypatch):
spawn()
return "running"
- def _fake_spawn(args, hf_token, **kwargs):
+ def _fake_spawn(args, **kwargs):
spawned["args"] = args
return object()
monkeypatch.setattr(download_lifecycle, "launch_worker", _fake_launch)
- monkeypatch.setattr(download_lifecycle, "spawn_worker", _fake_spawn)
+ monkeypatch.setattr(download_lifecycle.subprocess, "Popen", _fake_spawn)
+ monkeypatch.setattr("huggingface_hub.utils.get_token_to_send", lambda token: None)
+ monkeypatch.setattr("tempfile.tempdir", str(tmp_path))
result = asyncio.run(dl.download_model_response(_request()))
assert result["accepted"] is True
@@ -105,7 +107,6 @@ def test_scoped_start_spawns_a_file_scoped_worker(monkeypatch):
args = spawned["args"]
assert "--variant" in args and args[args.index("--variant") + 1] == scope_variant
- # The file list travels in a temp JSON file, not argv: a pipeline repo lists hundreds.
manifest_path = args[args.index("--files-json") + 1]
assert json.loads(Path(manifest_path).read_text(encoding = "utf-8")) == FILES
Path(manifest_path).unlink(missing_ok = True)