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 Hub download: keep refs/main on the last complete snapshot under failed updates and concurrent workers (#16422)
Daniel Han1a951a93d6b7
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.pyindex d664f30ee18..2f2edb1523a 100644--- a/studio/backend/hub/services/models/cache_inventory.py+++ b/studio/backend/hub/services/models/cache_inventory.py@@ -329,7 +329,9 @@ def _is_real_cache_blob(blob: Optional[Path], repo_dir: Optional[Path]) -> bool:if blob is None or repo_dir is None:return Falsetry:- return blob.parent.resolve(strict = False) == (repo_dir / "blobs").resolve(strict = False)+ parent = blob.parent.resolve(strict = False)+ store = (repo_dir / "blobs").resolve(strict = False)+ return parent == store or parent.samefile(store)except OSError:return Falsediff --git a/studio/backend/hub/services/models/deletion.py b/studio/backend/hub/services/models/deletion.pyindex ca622420dc8..12cd3ef5946 100644--- a/studio/backend/hub/services/models/deletion.py+++ b/studio/backend/hub/services/models/deletion.py@@ -181,7 +181,11 @@ def _has_remaining_main_gguf(target_repo) -> bool:)-def _remove_empty_variant_dirs(target_repos: list, variant: str) -> tuple[int, list[str]]:+def _remove_empty_variant_dirs(+ target_repos: list,+ variant: str,+ protected_revisions: frozenset[str] = frozenset(),+) -> tuple[int, list[str]]:"""remove empty variant folders and return their count plus non-concurrent failures."""# qualified keys own only their exact folder because token-only folders can be another build.qualified = (@@ -205,6 +209,8 @@ def _remove_empty_variant_dirs(target_repos: list, variant: str) -> tuple[int, lexcept OSError:continuefor snap in snap_dirs:+ if snap.name in protected_revisions:+ continuetry:subs = list(snap.iterdir())except OSError:@@ -577,8 +583,13 @@ def reclaim_replaced_gguf_variant(hf_token: Optional[str] = None,*,hub_cache: Optional[str | Path] = None,+ protected_revisions: frozenset[str] = frozenset(),) -> dict:- """Prune stale main-GGUF files for a variant after a replacement verified. Intentionally narrower than user-driven delete: it removes only same-variant main files whose local blob hash is not in *keep_main_hashes*, then unlinks their blobs only if no remaining snapshot references them. Shared companions and sibling variants are left intact."""+ """Prune stale main-GGUF files for a variant after a replacement verified. Intentionally narrower than user-driven delete: it removes only same-variant main files whose local blob hash is not in *keep_main_hashes*, then unlinks their blobs only if no remaining snapshot references them. Shared companions and sibling variants are left intact.++ A publication-protocol caller holds its lock throughout this call and passes+ the published and in-flight commits as ``protected_revisions``.+ """if not keep_main_hashes:logger.info("Skipping stale GGUF reclaim for %s [%s]: current main hashes unresolved",@@ -675,6 +686,14 @@ def reclaim_replaced_gguf_variant(if _main_key(match[0], main_keys) == variant_key]for snap, blob, name in matches:+ if repo_dir is None:+ continue+ try:+ commit = snap.relative_to(repo_dir / "snapshots").parts[0]+ except (ValueError, IndexError):+ continue+ if commit in protected_revisions:+ continue# prune confirmed stale blobs only; non-symlink snapshot files lack identifiable hashes.blob_hash = (_blob_hash_from_path(blob)@@ -718,8 +737,12 @@ def reclaim_replaced_gguf_variant(removed_dirs = 0dir_failures: list[str] = []if target_repos:- removed_dirs, dir_failures = _remove_empty_variant_dirs(target_repos, variant)- removed_snap_dirs, snap_dir_failures = _remove_empty_snapshot_dirs(target_repos)+ removed_dirs, dir_failures = _remove_empty_variant_dirs(+ target_repos, variant, protected_revisions+ )+ removed_snap_dirs, snap_dir_failures = _remove_empty_snapshot_dirs(+ target_repos, protected_revisions+ )removed_dirs += removed_snap_dirsdir_failures.extend(snap_dir_failures)failures.extend(dir_failures)diff --git a/studio/backend/hub/workers/hf_download.py b/studio/backend/hub/workers/hf_download.pyindex a8ece0a5bbb..a34b8952e5c 100644--- a/studio/backend/hub/workers/hf_download.py+++ b/studio/backend/hub/workers/hf_download.py@@ -8,12 +8,15 @@ by HF_HUB_DISABLE_XET=1, HF_HUB_ENABLE_HF_TRANSFER=0 (http), one writer per blobfrom __future__ import annotationsimport argparse+import jsonimport osimport reimport signalimport sysimport threadingimport time+import uuid+from dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Union@@ -265,9 +268,9 @@ def _read_ref(ref: Path):def _write_ref(ref: Path, commit: str) -> None:- """Atomic; no temp file may survive, since every file under refs/ reads as a ref (scan_cache_dir)."""+ """Atomic, with even transient files outside refs/ (scan_cache_dir reads branch names)."""ref.parent.mkdir(parents = True, exist_ok = True)- tmp = ref.with_name(f"main.{os.getpid()}.{threading.get_ident()}.tmp")+ tmp = ref.parent.parent / f".studio-{ref.name}.{uuid.uuid4().hex}.tmp"try:tmp.write_text(commit, encoding = "utf-8")os.replace(tmp, ref)@@ -280,85 +283,229 @@ def _write_ref(ref: Path, commit: str) -> None:def _pinned_revision(repo_type: RepoType, repo_id: str, commit) -> dict:- """Pin to the commit the manifest was planned from. A sha revision leaves refs/main unwritten, yet loads by- repo id (offline too) resolve through it, so it is written here as an unpinned download would."""+ """Select an immutable revision without exposing an unverified snapshot through refs/main."""if not isinstance(commit, str) or not _COMMIT_SHA.fullmatch(commit):return {}- from hub.utils.snapshot_reuse import repo_cache_dir-- ref = repo_cache_dir(repo_type, repo_id) / "refs" / "main"- if _read_ref(ref) == commit:- return {"revision": commit}- try:- _write_ref(ref, commit)- except OSError as e:- print(- f"Could not record refs/main for {repo_id} ({e}); downloading unpinned.",- file = sys.stderr,- )- return {}return {"revision": commit}-def _landed_state(repo_dir: Path, commit: str) -> frozenset:- """``commit``'s snapshot entries plus partial blob sizes: what changes once a download transfers bytes."""- state = set()- snapshot = repo_dir / "snapshots" / commit+def _model_manifest_attestation(commit) -> dict:+ """Date copied files only when metadata resolved an immutable revision."""+ if isinstance(commit, str) and _COMMIT_SHA.fullmatch(commit):+ return {"commit_hash": commit, "metadata_derived": True}+ return {}+++# Among cooperating workers, the latest-started verified success owns main.+# SHA transfers leave main unchanged; native owner locks identify abandoned attempts.+# Journal/ref writes are not a power-loss transaction and cannot coordinate external writers.+++@dataclass(frozen = True)+class _MainRefState:+ next_sequence: int = 1+ published_sequence: int = 0+ published_commit: str | None = None+ attempts: tuple[tuple[int, str], ...] = ()+ owners: tuple[tuple[int, str], ...] = ()+++def _start_main_ref(state: _MainRefState, commit: str, owner: str) -> tuple[_MainRefState, int]:+ sequence = state.next_sequence+ return _MainRefState(+ sequence + 1,+ state.published_sequence,+ state.published_commit,+ (*state.attempts, (sequence, commit)),+ (*state.owners, (sequence, owner)),+ ), sequence+++def _finish_main_ref(state: _MainRefState, sequence: int, verified: bool) -> _MainRefState:+ attempts = dict(state.attempts)+ commit = attempts.pop(sequence)+ publish = verified and sequence > state.published_sequence+ return _MainRefState(+ state.next_sequence,+ sequence if publish else state.published_sequence,+ commit if publish else state.published_commit,+ tuple(attempts.items()),+ tuple((seq, owner) for seq, owner in state.owners if seq != sequence),+ )+++def _prune_main_ref_attempts(state: _MainRefState, owner_is_alive) -> _MainRefState:+ for sequence, owner in state.owners:+ if not owner_is_alive(owner):+ state = _finish_main_ref(state, sequence, False)+ return state+++def _main_ref_owner_lock(lock_dir: Path, owner: str):+ # Soft locks survive SIGKILL and cannot prove ownership.+ from filelock import FileLock, SoftFileLock++ lock = FileLock(lock_dir / f"studio-main-owner-{owner}.lock")+ lock.acquire(timeout = 0)+ if isinstance(lock, SoftFileLock):+ lock.release()+ raise OSError("refs/main attempt ownership requires native file locks")+ return lock+++def _main_ref_owner_is_alive(lock_dir: Path, owner: str) -> bool:+ from filelock import Timeout+try:- state.update(("s", str(p.relative_to(snapshot))) for p in snapshot.rglob("*"))- except OSError:- pass+ lock = _main_ref_owner_lock(lock_dir, owner)+ except Timeout:+ return True+ lock.release()+ Path(lock.lock_file).unlink(missing_ok = True)+ return False+++def _load_main_ref_state(path: Path, previous: str | None) -> _MainRefState:try:- for p in (repo_dir / "blobs").glob("*.incomplete"):- try:- state.add(("b", p.name, p.stat().st_size))- except OSError:- pass- except OSError:- pass- return frozenset(state)+ raw = path.read_text(encoding = "utf-8")+ except FileNotFoundError:+ return _MainRefState(published_commit = previous)+ # Resetting a damaged journal could reuse a live peer's sequence.+ data = json.loads(raw)+ state = _MainRefState(+ data["next_sequence"],+ data["published_sequence"],+ data["published_commit"],+ tuple(tuple(attempt) for attempt in data["attempts"]),+ tuple(tuple(owner) for owner in data.get("owners", ())),+ )+ if (+ type(state.next_sequence) is not int+ or type(state.published_sequence) is not int+ or not 0 <= state.published_sequence < state.next_sequence+ or not (state.published_commit is None or isinstance(state.published_commit, str))+ or (state.published_sequence > 0 and state.published_commit is None)+ or len(dict(state.attempts)) != len(state.attempts)+ or any(+ type(sequence) is not int+ or not 0 < sequence < state.next_sequence+ or not isinstance(commit, str)+ or not _COMMIT_SHA.fullmatch(commit)+ for sequence, commit in state.attempts+ )+ or len(dict(state.owners)) != len(state.owners)+ or set(dict(state.owners)) != set(dict(state.attempts))+ or any(+ type(sequence) is not int+ or not isinstance(owner, str)+ or re.fullmatch(r"[0-9a-f]{32}", owner) is None+ for sequence, owner in state.owners+ )+ ):+ raise ValueError(f"Invalid refs/main publication state: {path}")+ return state-def _pinned_snapshot_download(snapshot_download, commit, **kwargs):- """``snapshot_download(**kwargs)`` at ``commit``. A failure before anything of ``commit`` lands puts refs/main- back and reruns the unpinned call, keeping its offline fallback to the older snapshot (an unpinned download- moves the ref only after the Hub answers)."""+def _update_main_ref(+ repo_dir: Path,+ *,+ commit: str | None = None,+ sequence: int | None = None,+ verified: bool = False,+ on_publish = None,+ owner: str | None = None,+) -> int | None:+ """Persist one decision under the lock; no network, transfer or verification here."""+ from huggingface_hub.utils import WeakFileLock++ lock_dir = repo_dir.parent / ".locks" / repo_dir.name+ lock_dir.mkdir(parents = True, exist_ok = True)+ state_path = lock_dir / "studio-main.json"+ ref = repo_dir / "refs" / "main"+ with WeakFileLock(lock_dir / "studio-main.lock"):+ previous = _read_ref(ref)+ before = _prune_main_ref_attempts(+ _load_main_ref_state(state_path, previous),+ lambda attempt_owner: _main_ref_owner_is_alive(lock_dir, attempt_owner),+ )+ if commit is not None:+ if owner is None:+ raise ValueError("refs/main attempt requires a live owner")+ state, sequence = _start_main_ref(before, commit, owner)+ else:+ state = _finish_main_ref(before, sequence, verified)+ try:+ _write_ref(state_path, json.dumps(asdict(state)))+ if verified and previous != state.published_commit:+ _write_ref(ref, state.published_commit)+ except BaseException:+ if verified:+ # A failed publication must not disown an older active success.+ failed = _finish_main_ref(before, sequence, False)+ _write_ref(state_path, json.dumps(asdict(failed)))+ if _read_ref(ref) != previous:+ if previous is None:+ ref.unlink(missing_ok = True)+ else:+ _write_ref(ref, previous)+ raise+ # Reclaim under this lock so no new peer loses its snapshot.+ if verified and state.published_sequence == sequence and on_publish is not None:+ on_publish(state)+ return sequence+++def _pinned_snapshot_download(+ snapshot_download,+ commit,+ *,+ expected_files = (),+ verify = None,+ on_publish = None,+ **kwargs,+):+ """Transfer and verify outside the lock; publish and reclaim under it."""from hub.utils.snapshot_reuse import repo_cache_dirrepo_type, repo_id = kwargs.get("repo_type") or "model", kwargs["repo_id"]repo_dir = repo_cache_dir(repo_type, repo_id)- ref = repo_dir / "refs" / "main"- previous = _read_ref(ref)+ if commit is None:+ commit = _read_ref(repo_dir / "refs" / "main")pin = _pinned_revision(repo_type, repo_id, commit)if not pin:- return snapshot_download(**kwargs)- before = None if previous == commit else _landed_state(repo_dir, commit)+ raise OSError(+ f"Cannot resolve an immutable revision for {repo_id}; retry when metadata is available"+ )++ lock_dir = repo_dir.parent / ".locks" / repo_dir.name+ lock_dir.mkdir(parents = True, exist_ok = True)+ owner = uuid.uuid4().hex+ owner_lock = _main_ref_owner_lock(lock_dir, owner)try:- path = snapshot_download(**kwargs, **pin)- except BaseException as e:- if before is None or _landed_state(repo_dir, commit) != before:- raise+ sequence = _update_main_ref(repo_dir, commit = commit, owner = owner)try:- # Only our own write is undone: a peer may have moved the ref since.- if _read_ref(ref) == commit:- if previous is None:- ref.unlink()- else:- _write_ref(ref, previous)- except OSError:- raise e- if not isinstance(e, Exception):+ path = snapshot_download(**kwargs, **pin)+ if Path(path).name != commit or not Path(path).is_dir():+ raise OSError(+ f"Pinned download of {repo_id} returned a snapshot other than {commit}"+ )+ # Legacy Hub can return an existing incomplete snapshot after metadata+ # fails. Check before making it visible to offline repo-ID resolution.+ if expected_files:+ from hub.utils.download_manifest import Manifest, verify_against_disk+ manifest = Manifest(repo_type, repo_id, None, "", tuple(expected_files))+ if not verify_against_disk(manifest, Path(path)).ok:+ raise OSError(f"Pinned snapshot of {repo_id} is incomplete")+ if verify is not None:+ verify(path)+ except BaseException:+ _update_main_ref(repo_dir, sequence = sequence)raise- print(- f"Pinned download of {repo_id} failed before any file landed "- f"({type(e).__name__}: {e}); retrying unpinned.",- file = sys.stderr,- )- return snapshot_download(**kwargs)- # A concurrent variant download that failed early may have put back the ref this one or a peer replaced.- if _read_ref(ref) in (previous, None) or previous == commit:- _pinned_revision(repo_type, repo_id, commit)- return path+ _update_main_ref(repo_dir, sequence = sequence, verified = True, on_publish = on_publish)+ return path+ finally:+ owner_lock.release()+ Path(owner_lock.lock_file).unlink(missing_ok = True)def _rebuild_header_only_ggufs(@@ -765,7 +912,6 @@ def _download_snapshot(from hub.utils.download_registry import prepare_cache_for_transportfrom hub.utils import download_manifest- # One metadata fetch powers both the ignore-pattern decision and the manifest's expected_files; a failure is non-fatal and falls back to the legacy ignore set, losing verification only.try:info = _model_info_with_retry(repo_id, hf_token)except Exception as e:@@ -776,14 +922,25 @@ def _download_snapshot()info = None+ commit = getattr(info, "sha", None)download_manifest.clear_cancel_marker("model", repo_id, None)if info is not None:ignore_patterns, expected_files = _snapshot_download_plan(info)# The manifest verifies the finalized files under snapshots/, which both transports produce identically; XET's block-level dedup lives only in the chunk cache.- download_manifest.write_manifest("model", repo_id, None, expected_files, mode)+ download_manifest.write_manifest(+ "model",+ repo_id,+ None,+ expected_files,+ mode,+ **_model_manifest_attestation(getattr(info, "sha", None)),+ )else:ignore_patterns = list(SNAPSHOT_IGNORE_PATTERNS)- expected_files = []+ manifest = download_manifest.read_manifest("model", repo_id, None)+ expected_files = list(manifest.expected_files) if manifest is not None else []+ if manifest is not None and manifest.metadata_derived:+ commit = download_manifest.normalized_commit_hash(manifest.commit_hash)purged = prepare_cache_for_transport("model", repo_id, mode)if purged:@@ -796,31 +953,36 @@ def _download_snapshot("model", repo_id, getattr(info, "sha", None), expected_files, hf_token)_preflight_disk_space("model", repo_id, to_download)- snapshot_path = _pinned_snapshot_download(++ def verify(snapshot_path: str) -> None:+ if info is None:+ _recover_manifest_after_download(+ "model",+ repo_id,+ snapshot_path,+ mode,+ fetch_info = lambda: _model_info_with_retry(repo_id, hf_token),+ expected_files_from_info = lambda recovered: _snapshot_download_plan(recovered)[1],+ )+ _verify_completed_download(+ "model",+ repo_id,+ None,+ snapshot_path,+ metadata_unavailable = info is None,+ )++ _pinned_snapshot_download(snapshot_download,- getattr(info, "sha", None),+ commit,+ expected_files = expected_files,+ verify = verify,repo_id = repo_id,token = _hf_token_arg(hf_token),ignore_patterns = ignore_patterns,max_workers = _file_workers(mode),tqdm_class = tqdm_class,)- if info is None:- _recover_manifest_after_download(- "model",- repo_id,- snapshot_path,- mode,- fetch_info = lambda: _model_info_with_retry(repo_id, hf_token),- expected_files_from_info = lambda recovered: _snapshot_download_plan(recovered)[1],- )- _verify_completed_download(- "model",- repo_id,- None,- snapshot_path,- metadata_unavailable = info is None,- )def _gguf_variant_target_plan(@@ -860,6 +1022,7 @@ def _download_gguf_variant(plan = Nonemetadata_unavailable = True+ commit = None if metadata_unavailable else _RESOLVED_COMMITS.get(repo_id)if not metadata_unavailable:if plan is None:print(@@ -877,6 +1040,7 @@ def _download_gguf_variant(variant,expected_files,mode,+ **_model_manifest_attestation(commit),)else:# Metadata unreachable: resume the exact shards the original attempt recorded so snapshot_download can range over the surviving .incomplete blobs.@@ -889,6 +1053,8 @@ def _download_gguf_variant()sys.exit(1)plan = plan_from_expected_files(variant, manifest.expected_files)+ if manifest.metadata_derived:+ commit = download_manifest.normalized_commit_hash(manifest.commit_hash)targets = list(plan.target_filenames)expected_files = list(plan.expected_files)download_manifest.write_manifest(@@ -897,6 +1063,7 @@ def _download_gguf_variant(variant,expected_files,mode,+ **_model_manifest_attestation(commit),)main_blob_hashes = plan.main_hashescompanion_blob_hashes = plan.companion_hashes@@ -942,14 +1109,36 @@ def _download_gguf_variant(to_download = (expected_filesif metadata_unavailable- else _reuse_unchanged_files(- "model", repo_id, _RESOLVED_COMMITS.get(repo_id), expected_files, hf_token- )+ else _reuse_unchanged_files("model", repo_id, commit, expected_files, hf_token))_preflight_disk_space("model", repo_id, to_download)++ def reclaim(state: _MainRefState) -> None:+ try:+ from hub.services.models.deletion import reclaim_replaced_gguf_variant+ from hub.utils.snapshot_reuse import repo_cache_dir+ reclaim_replaced_gguf_variant(+ repo_id,+ variant,+ plan.main_hashes,+ hf_token,+ hub_cache = repo_cache_dir("model", repo_id).parent,+ protected_revisions = frozenset(+ [state.published_commit, *(sha for _, sha in state.attempts)]+ ),+ )+ except Exception as e:+ print(+ f"Verified GGUF update for {repo_id} [{variant}], but stale-cache "+ f"reclaim failed ({type(e).__name__}: {e})",+ file = sys.stderr,+ )+snapshot_path = _pinned_snapshot_download(snapshot_download,- None if metadata_unavailable else _RESOLVED_COMMITS.get(repo_id),+ commit,+ expected_files = expected_files,+ on_publish = reclaim,repo_id = repo_id,token = _hf_token_arg(hf_token),allow_patterns = targets,@@ -963,22 +1152,6 @@ def _download_gguf_variant(snapshot_path,metadata_unavailable = metadata_unavailable,)- if plan is not None:- try:- from hub.services.models.deletion import reclaim_replaced_gguf_variant- reclaim_replaced_gguf_variant(- repo_id,- variant,- plan.main_hashes,- hf_token,- hub_cache = Path(snapshot_path).parents[2],- )- except Exception as e:- print(- f"Verified GGUF update for {repo_id} [{variant}], but stale-cache "- f"reclaim failed ({type(e).__name__}: {e})",- file = sys.stderr,- )def _download_scoped_snapshot(@@ -1005,6 +1178,7 @@ def _download_scoped_snapshot()info = None+ commit = getattr(info, "sha", None)expected_files: list[ExpectedFile] = []blob_hashes: frozenset[str] = frozenset()if info is not None:@@ -1029,7 +1203,20 @@ def _download_scoped_snapshot(from hub.utils.snapshot_filters import blob_hashes_for_siblingsblob_hashes = blob_hashes_for_siblings(siblings)- download_manifest.write_manifest("model", repo_id, scope, expected_files, mode)+ download_manifest.write_manifest(+ "model",+ repo_id,+ scope,+ expected_files,+ mode,+ **_model_manifest_attestation(getattr(info, "sha", None)),+ )+ else:+ manifest = download_manifest.read_manifest("model", repo_id, scope)+ if manifest is not None:+ expected_files = list(manifest.expected_files)+ if manifest.metadata_derived:+ commit = download_manifest.normalized_commit_hash(manifest.commit_hash)download_manifest.clear_cancel_marker("model", repo_id, scope)purged = prepare_cache_for_transport(@@ -1050,34 +1237,39 @@ def _download_scoped_snapshot("model", repo_id, getattr(info, "sha", None), expected_files, hf_token)_preflight_disk_space("model", repo_id, to_download)- snapshot_path = _pinned_snapshot_download(++ def verify(snapshot_path: str) -> None:+ if info is None:+ # A saved manifest may omit files in the current request.+ root = Path(snapshot_path)+ absent = tuple(f for f in files if not (root / f).exists())+ if absent:+ print(+ f"Could not reach Hugging Face for {repo_id} [{scope}] and the copy on disk "+ f"is incomplete ({len(absent)} file(s) missing): {_format_path_list(absent)}. "+ "Reconnect (or set a valid HF token) and resume the download.",+ file = sys.stderr,+ )+ sys.exit(1)+ _verify_completed_download(+ "model",+ repo_id,+ scope,+ snapshot_path,+ metadata_unavailable = info is None,+ )++ _pinned_snapshot_download(snapshot_download,- getattr(info, "sha", None),+ commit,+ expected_files = expected_files,+ verify = verify,repo_id = repo_id,token = _hf_token_arg(hf_token),allow_patterns = files,max_workers = _file_workers(mode),tqdm_class = tqdm_class,)- if info is None:- # With no metadata there is no manifest, and snapshot_download RETURNS AN EXISTING SNAPSHOT FOLDER when repo_info also fails, flipping the job to complete with no weights.- root = Path(snapshot_path)- absent = tuple(f for f in files if not (root / f).exists())- if absent:- print(- f"Could not reach Hugging Face for {repo_id} [{scope}] and the copy on disk "- f"is incomplete ({len(absent)} file(s) missing): {_format_path_list(absent)}. "- "Reconnect (or set a valid HF token) and resume the download.",- file = sys.stderr,- )- sys.exit(1)- _verify_completed_download(- "model",- repo_id,- scope,- snapshot_path,- metadata_unavailable = info is None,- )def _download_dataset(diff --git a/studio/backend/tests/test_hf_download_fallback_and_kill.py b/studio/backend/tests/test_hf_download_fallback_and_kill.pynew file mode 100644index 00000000000..787a57b44e6--- /dev/null+++ b/studio/backend/tests/test_hf_download_fallback_and_kill.py@@ -0,0 +1,233 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Metadata fallback and hard cancellation must use the publication protocol."""++import hashlib+import json+import os+import signal+import subprocess+import sys+import time++import pytest++from .test_hf_download_pinned_revision import (+ _BACKEND,+ _FakeHub,+ _NEW,+ _OLD,+ _WORKER,+ _repo_dir,+ _run,+)+from .test_hf_download_reclaim_race import _PAUSED_WORKER, _worker_env+++def _wait_for_transfer(child, tmp_path):+ deadline = time.monotonic() + 20+ while not (tmp_path / "ready").exists():+ assert child.poll() is None, child.communicate()+ assert time.monotonic() < deadline, "worker did not reach the transfer barrier"+ time.sleep(0.01)+++_FALLBACK_WORKER = r"""+import hashlib, sys+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from hub.workers import hf_download as w+from hub.utils import download_manifest as dm+repo, commit, name = 'fake/repo', 'b' * 40, 'model-Q8_0.gguf'+data = b'GGUF' + b'q8' * 1024+assert dm.write_manifest('model', repo, 'Q8_0',+ [dm.ExpectedFile(name, len(data), hashlib.sha256(data).hexdigest())],+ 'http', commit_hash=commit, metadata_derived=True)+original = w._model_info_with_retry+calls = 0+def fail_once(*args, **kwargs):+ global calls+ calls += 1+ if calls == 1:+ raise OSError('transient metadata failure')+ return original(*args, **kwargs)+w._model_info_with_retry = fail_once+w._download_gguf_variant(repo, 'Q8_0', None, 'http')+from huggingface_hub import hf_hub_download+path = hf_hub_download(repo, name, local_files_only=True)+assert Path(path).read_bytes() == data+"""+++def test_metadata_fallback_completion_survives_older_pinned_worker(tmp_path):+ """Real GGUF workers: A starts, fallback B completes, then A completes."""+ hub = _FakeHub()+ child = None+ try:+ hub.commits[_NEW]["model-Q8_0.gguf"] = b"GGUF" + b"q8" * 1024+ child = subprocess.Popen(+ [sys.executable, "-c", _PAUSED_WORKER, str(_WORKER), "before_transfer", str(tmp_path)],+ env = _worker_env(hub, tmp_path),+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ text = True,+ )+ _wait_for_transfer(child, tmp_path)+ hub.head = _NEW+ resumed = subprocess.run(+ [sys.executable, "-c", _FALLBACK_WORKER, str(_BACKEND)],+ env = _worker_env(hub, tmp_path),+ capture_output = True,+ text = True,+ timeout = 40,+ )+ assert resumed.returncode == 0, resumed.stdout + resumed.stderr+ repo = _repo_dir(tmp_path)+ assert (repo / "refs" / "main").read_text() == _NEW+ (tmp_path / "release").touch()+ out, err = child.communicate(timeout = 40)+ assert child.returncode == 0, out + err+ offline = subprocess.run(+ [+ sys.executable,+ "-c",+ "from huggingface_hub import hf_hub_download; from pathlib import Path; "+ "p = hf_hub_download('fake/repo', 'model-Q8_0.gguf', local_files_only=True); "+ "assert Path(p).read_bytes() == b'GGUF' + b'q8' * 1024",+ ],+ env = _worker_env(hub, tmp_path),+ capture_output = True,+ text = True,+ timeout = 20,+ )+ assert offline.returncode == 0, offline.stdout + offline.stderr+ assert (repo / "refs" / "main").read_text() == _NEW+ finally:+ (tmp_path / "release").touch()+ if child is not None and child.poll() is None:+ child.kill()+ child.communicate(timeout = 20)+ hub.close()++[email protected]("commit", [None, "main", "A" * 40])+def test_unresolved_revision_fails_before_transfer(monkeypatch, tmp_path, commit):+ from huggingface_hub import constants+ from hub.workers import hf_download as w++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))++ def transfer(**kwargs):+ pytest.fail("unresolved revision must not run an unpinned transfer")++ with pytest.raises(OSError, match = "Cannot resolve an immutable revision"):+ w._pinned_snapshot_download(transfer, commit, repo_id = "fake/repo")+ assert not (tmp_path / "models--fake--repo" / "refs").exists()++[email protected]("active", [False, True])+def test_legacy_journal_requires_owners_only_for_active_attempts(tmp_path, active):+ from hub.workers import hf_download as w++ journal = tmp_path / "studio-main.json"+ journal.write_text(+ json.dumps(+ {+ "next_sequence": 2,+ "published_sequence": 0,+ "published_commit": _OLD,+ "attempts": [[1, _NEW]] if active else [],+ }+ )+ )+ if active:+ # Old workers have no provable lifetime; do not guess they are dead.+ with pytest.raises(ValueError, match = "Invalid refs/main publication state"):+ w._load_main_ref_state(journal, _OLD)+ else:+ state = w._load_main_ref_state(journal, _OLD)+ assert state.published_commit == _OLD+ assert not state.attempts and not state.owners+++def test_soft_owner_lock_fails_before_transfer(monkeypatch, tmp_path):+ import filelock+ from huggingface_hub import constants+ from hub.workers import hf_download as w++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ monkeypatch.setattr(filelock, "FileLock", filelock.SoftFileLock)++ def transfer(**kwargs):+ pytest.fail("a soft lock cannot prove owner death")++ with pytest.raises(OSError, match = "requires native file locks"):+ w._pinned_snapshot_download(transfer, _NEW, repo_id = "fake/repo")+++def test_owner_dying_during_transfer_is_pruned_before_publish(monkeypatch, tmp_path):+ from huggingface_hub import constants+ from hub.workers import hf_download as w++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ repo = tmp_path / "models--fake--repo"+ lock_dir = tmp_path / ".locks" / repo.name+ published = []++ def transfer(**kwargs):+ # Simulate another attempt's death after this transfer has started.+ owner = "c" * 32+ lock = w._main_ref_owner_lock(lock_dir, owner)+ try:+ w._update_main_ref(repo, commit = _OLD, owner = owner)+ finally:+ lock.release()+ target = repo / "snapshots" / _NEW+ target.mkdir(parents = True)+ return str(target)++ w._pinned_snapshot_download(transfer, _NEW, repo_id = "fake/repo", on_publish = published.append)+ assert len(published) == 1+ assert published[0].published_commit == _NEW+ assert not published[0].attempts and not published[0].owners++[email protected](os.name == "nt", reason = "requires POSIX SIGKILL")+def test_sigkill_attempt_is_pruned_by_a_fresh_worker_before_reclaim(tmp_path):+ """No parent cleanup: the new process recovers solely from the on-disk ledger."""+ hub = _FakeHub()+ child = None+ name = "model-Q4_K_M.gguf"+ try:+ child = subprocess.Popen(+ [sys.executable, "-c", _PAUSED_WORKER, str(_WORKER), "after_transfer", str(tmp_path)],+ env = _worker_env(hub, tmp_path),+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ text = True,+ )+ _wait_for_transfer(child, tmp_path)+ repo = _repo_dir(tmp_path)+ stale = repo / "snapshots" / _OLD / name+ blob = repo / "blobs" / hashlib.sha256(hub.commits[_OLD][name]).hexdigest()+ assert stale.is_file() and blob.is_file()+ journal = repo.parent / ".locks" / repo.name / "studio-main.json"+ assert json.loads(journal.read_text())["attempts"]+ os.kill(child.pid, signal.SIGKILL)+ child.communicate(timeout = 20)+ assert child.returncode == -signal.SIGKILL+ assert json.loads(journal.read_text())["attempts"] # SIGKILL bypassed finish+ hub.head = _NEW+ newer = _run(hub, tmp_path, "--variant", "Q4_K_M")+ assert newer.returncode == 0, newer.stderr+ assert (repo / "refs" / "main").read_text() == _NEW+ assert not stale.exists(), "dead attempt still protects obsolete snapshot"+ assert not blob.exists(), "dead attempt still protects obsolete blob"+ assert not json.loads(journal.read_text())["attempts"]+ assert (repo / "snapshots" / _NEW / name).read_bytes() == hub.commits[_NEW][name]+ finally:+ if child is not None and child.poll() is None:+ child.kill()+ child.communicate(timeout = 20)+ hub.close()diff --git a/studio/backend/tests/test_hf_download_partial_fallback.py b/studio/backend/tests/test_hf_download_partial_fallback.pynew file mode 100644index 00000000000..e2ef6fdec90--- /dev/null+++ b/studio/backend/tests/test_hf_download_partial_fallback.py@@ -0,0 +1,70 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A cache hit after a network error must not publish an incomplete snapshot."""++import json+import subprocess+import sys++import pytest++from .test_hf_download_pinned_revision import _FakeHub, _FULL, _NEW, _OLD, _repo_dir, _run++[email protected]("kind", ["full", "scoped", "gguf"])[email protected]("same_size", [False, True])+def test_reused_file_and_failed_update_keep_old_weights_loadable(tmp_path, kind, same_size):+ hub = _FakeHub()+ try:+ hub.commits[_NEW]["config.json"] = hub.commits[_OLD]["config.json"]+ for commit in (_OLD, _NEW):+ hub.commits[commit]["mmproj-F16.gguf"] = b"GGUF" + b"shared" * 16+ if same_size:+ # Presence and size verification cannot distinguish these old and new weights.+ for name in ("model.safetensors", "model-Q4_K_M.gguf"):+ size = len(hub.commits[_OLD][name])+ hub.commits[_NEW][name] = hub.commits[_NEW][name][:size]+ assert hub.commits[_NEW][name] != hub.commits[_OLD][name]+ hub.head, hub.down = _NEW, True+ repo = _repo_dir(tmp_path)+ old = repo / "snapshots" / _OLD+ old.mkdir(parents = True)+ for name in hub.commits[_OLD]:+ (old / name).write_bytes(hub.commits[_OLD][name])+ ref = repo / "refs" / "main"+ ref.parent.mkdir()+ ref.write_text(_OLD)+ extra = []+ if kind == "scoped":+ files = tmp_path / "files.json"+ files.write_text(json.dumps(list(_FULL)))+ extra = ["--variant", "test-scope", "--files-json", str(files)]+ elif kind == "gguf":+ extra = ["--variant", "Q4_K_M"]+ reused = "mmproj-F16.gguf" if kind == "gguf" else "config.json"+ weights = "model-Q4_K_M.gguf" if kind == "gguf" else "model.safetensors"+ result = _run(hub, tmp_path, *extra)+ assert result.returncode != 0, result.stderr+ assert (repo / "snapshots" / _NEW / reused).is_file(), result.stderr+ assert not (repo / "snapshots" / _NEW / weights).exists()+ assert ref.read_text() == _OLD, result.stderr+ # Exercise the real offline repo-ID resolver, not just the ref's contents.+ offline = subprocess.run(+ [+ sys.executable,+ "-c",+ "from huggingface_hub import hf_hub_download; import sys; "+ "print(hf_hub_download('fake/repo', sys.argv[2], "+ "cache_dir=sys.argv[1], local_files_only=True))",+ str(repo.parent),+ weights,+ ],+ text = True,+ capture_output = True,+ timeout = 20,+ )+ assert offline.returncode == 0, offline.stderr+ assert _OLD in offline.stdout+ finally:+ hub.close()diff --git a/studio/backend/tests/test_hf_download_pinned_revision.py b/studio/backend/tests/test_hf_download_pinned_revision.pyindex 0583c37999e..b07f446083c 100644--- a/studio/backend/tests/test_hf_download_pinned_revision.py+++ b/studio/backend/tests/test_hf_download_pinned_revision.py@@ -360,7 +360,8 @@ def test_resume_after_a_dropped_transfer_and_offline_rerun(tmp_path, hub_factoryhub = hub_factory(fail_get = "model.safetensors")first = _run(hub, tmp_path)assert first.returncode != 0- assert (_repo_dir(tmp_path) / "refs" / "main").read_text(encoding = "utf-8") == _OLD+ # An interrupted first download has no successful publication yet.+ assert not (_repo_dir(tmp_path) / "refs" / "main").exists()hub.fail_get = Nonehub.move = True # the branch moves before the resume's metadata read is answeredsecond = _run(hub, tmp_path)@@ -387,7 +388,7 @@ def test_network_drop_after_the_metadata_read_keeps_the_older_snapshot_loadable(repo = _repo_dir(tmp_path)assert (repo / "refs" / "main").read_text(encoding = "utf-8") == _OLDassert [p.name for p in (repo / "refs").iterdir()] == ["main"]- assert "retrying unpinned" in second.stderr+ assert "retrying unpinned" not in second.stderrenv = dict(os.environ, HF_HUB_CACHE = str(tmp_path / "hf" / "hub"), HF_HUB_OFFLINE = "1")loaded = subprocess.run([@@ -417,10 +418,10 @@ def test_no_pin_without_a_full_sha(monkeypatch, tmp_path):assert hf_download._pinned_revision("model", _REPO, "A" * 40) == {}assert not (tmp_path / "models--fake--repo").exists()assert hf_download._pinned_revision("model", _REPO, _OLD) == {"revision": _OLD}- assert (tmp_path / "models--fake--repo" / "refs" / "main").read_text(encoding = "utf-8") == _OLD+ assert not (tmp_path / "models--fake--repo").exists()-def test_pinned_call_rolls_the_ref_back_only_when_nothing_landed(monkeypatch, tmp_path):+def test_failed_pinned_call_preserves_publication_even_when_files_landed(monkeypatch, tmp_path):from hub.workers import hf_downloadfrom huggingface_hub import constants@@ -428,61 +429,56 @@ def test_pinned_call_rolls_the_ref_back_only_when_nothing_landed(monkeypatch, tmrepo = tmp_path / "models--fake--repo"ref = repo / "refs" / "main"ref.parent.mkdir(parents = True)+ ref.write_text(_OLD)calls = []def fake(behaviour):def snapshot_download(**kw):calls.append(kw.get("revision"))- if kw.get("revision") is None:- return "unpinned"+ assert kw["revision"] # No fallback may silently load an older snapshot.+ target = repo / "snapshots" / kw["revision"]if behaviour == "land":- (repo / "snapshots" / _NEW).mkdir(parents = True, exist_ok = True)- (repo / "snapshots" / _NEW / "config.json").write_text("{}")+ target.mkdir(parents = True, exist_ok = True)+ (target / "config.json").write_text("{}")if behaviour == "peer_rollback":ref.write_text(_OLD)- return "pinned"+ target.mkdir(parents = True, exist_ok = True)+ return str(target)if behaviour == "interrupt":raise KeyboardInterruptraise OSError("network down")return snapshot_download- # Nothing landed: the ref goes back and the unpinned call runs (main's offline fallback).- ref.write_text(_OLD)- assert hf_download._pinned_snapshot_download(fake("drop"), _NEW, repo_id = _REPO) == "unpinned"- assert calls == [_NEW, None] and ref.read_text() == _OLD- # A file landed: the ref stays on the new commit and the error stands, as an unpinned download leaves it.- calls.clear()- with pytest.raises(OSError):- hf_download._pinned_snapshot_download(fake("land"), _NEW, repo_id = _REPO)- assert calls == [_NEW] and ref.read_text() == _NEW- # A cancel before anything landed restores the ref and is not retried.- ref.write_text(_OLD)+ # Neither a failed transfer with no bytes nor one with partial bytes may+ # replace a successful publication. Both propagate the original failure.+ for behaviour in ("drop", "land"):+ calls.clear()+ with pytest.raises(OSError, match = "network down"):+ hf_download._pinned_snapshot_download(fake(behaviour), _NEW, repo_id = _REPO)+ assert calls == [_NEW] and ref.read_text() == _OLDcalls.clear()with pytest.raises(KeyboardInterrupt):hf_download._pinned_snapshot_download(fake("interrupt"), "c" * 40, repo_id = _REPO)assert calls == ["c" * 40] and ref.read_text() == _OLD- # A peer's rollback during a successful download is undone: the fetched commit is named.- assert (- hf_download._pinned_snapshot_download(fake("peer_rollback"), "d" * 40, repo_id = _REPO)- == "pinned"- )- assert ref.read_text() == "d" * 40- # Same when a peer had already published the commit before this download started.- assert (- hf_download._pinned_snapshot_download(fake("peer_rollback"), "d" * 40, repo_id = _REPO)- == "pinned"- )- assert ref.read_text() == "d" * 40- # No ref before and nothing landed: no ref after.+ # A successful publication repairs the ref, including a repeated no-op SHA.+ for _ in range(2):+ result = hf_download._pinned_snapshot_download(+ fake("peer_rollback"),+ "d" * 40,+ repo_id = _REPO,+ )+ assert Path(result).name == "d" * 40+ assert ref.read_text() == "d" * 40+ # No ref before and no successful download: no ref afterward.ref.unlink()- assert (- hf_download._pinned_snapshot_download(fake("drop"), "e" * 40, repo_id = _REPO) == "unpinned"- )+ with pytest.raises(OSError):+ hf_download._pinned_snapshot_download(fake("drop"), "e" * 40, repo_id = _REPO)assert not ref.exists()- # A failed ref write leaves no temp file under refs/ (every file there reads as a ref).+ # A failed atomic replacement leaves no temporary branch names behind.monkeypatch.setattr(hf_download.os, "replace", lambda *a: (_ for _ in ()).throw(PermissionError("locked")))- assert hf_download._pinned_revision("model", _REPO, "f" * 40) == {}- assert [p.name for p in ref.parent.iterdir()] == []+ with pytest.raises(PermissionError):+ hf_download._write_ref(ref, "f" * 40)+ assert list(ref.parent.iterdir()) == []diff --git a/studio/backend/tests/test_hf_download_publication_protocol.py b/studio/backend/tests/test_hf_download_publication_protocol.pynew file mode 100644index 00000000000..784747d2524--- /dev/null+++ b/studio/backend/tests/test_hf_download_publication_protocol.py@@ -0,0 +1,333 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exhaustive schedules use the production decisions, with transfers as explicit fake steps."""++import hashlib+import itertools+import json+import os+import subprocess+import sys+from pathlib import Path++import pytest++from .test_hf_download_pinned_revision import _BACKEND, _FakeHub, _NEW, _OLD, _REPO+++_RACE_CHILD = r"""+import hashlib, os, sys, threading+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from huggingface_hub import snapshot_download, hf_hub_download+from hub.workers import hf_download as w+from hub.utils.download_manifest import ExpectedFile+repo_id, old, new = 'fake/repo', 'a' * 40, 'b' * 40+cache = Path(os.environ['HF_HUB_CACHE'])+weights = 'model.safetensors'+kwargs = dict(repo_id=repo_id, token=False, allow_patterns=[weights])+old_path = Path(snapshot_download(revision=old, **kwargs))+ref = old_path.parent.parent / 'refs' / 'main'+ref.parent.mkdir(parents=True, exist_ok=True)+ref.write_text(old)+old_ready, new_ready, old_done = (threading.Event() for _ in range(3))+results, errors = {}, []+def old_transfer(**kw):+ old_ready.set()+ assert new_ready.wait(10)+ return snapshot_download(**kw)+def new_transfer(**kw):+ new_ready.set()+ assert old_done.wait(10)+ return snapshot_download(**kw)+def run(name, transfer, commit, size):+ try:+ results[name] = w._pinned_snapshot_download(+ transfer, commit, expected_files=[ExpectedFile(weights, size)], **kwargs)+ except BaseException as exc:+ errors.append(repr(exc))+ finally:+ if name == 'old':+ old_done.set()+a = threading.Thread(target=run, args=('old', old_transfer, old, old_path.joinpath(weights).stat().st_size))+b = threading.Thread(target=run, args=('new', new_transfer, new, int(sys.argv[2])))+a.start()+assert old_ready.wait(10)+b.start()+a.join(20)+b.join(20)+assert not a.is_alive() and not b.is_alive()+assert not errors, errors+assert set(results) == {'old', 'new'}, results+assert Path(results['new']).joinpath(weights).is_file()+loaded = hf_hub_download(repo_id, weights, cache_dir=str(cache), local_files_only=True)+assert new in loaded, (ref.read_text(), loaded)+assert hashlib.sha256(Path(loaded).read_bytes()).hexdigest() == sys.argv[3]+print('Both workers succeeded; offline hf_hub_download resolved verified B.')+"""+++def test_cached_a_finishes_before_later_b_does_not_disown_b(tmp_path):+ """A's no-op completion must not revoke the later-started B's publication."""+ hub = _FakeHub()+ try:+ weights = hub.commits[_NEW]["model.safetensors"]+ env = dict(os.environ)+ env.pop("HF_TOKEN", None)+ env.update(+ HF_ENDPOINT = hub.endpoint,+ HF_HOME = str(tmp_path / "hf"),+ HF_HUB_CACHE = str(tmp_path / "hf" / "hub"),+ HF_HUB_DISABLE_XET = "1",+ HF_HUB_ENABLE_HF_TRANSFER = "0",+ HF_HUB_DISABLE_TELEMETRY = "1",+ HF_HUB_DISABLE_IMPLICIT_TOKEN = "1",+ HF_HUB_OFFLINE = "0",+ CUDA_VISIBLE_DEVICES = "",+ )+ result = subprocess.run(+ [+ sys.executable,+ "-c",+ _RACE_CHILD,+ str(_BACKEND),+ str(len(weights)),+ hashlib.sha256(weights).hexdigest(),+ ],+ env = env,+ text = True,+ capture_output = True,+ timeout = 60,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ finally:+ hub.close()+++def _schedules(workers, canonical_starts):+ """All linear extensions of start < transfer-done < verify-result < finish.++ For three workers, remove only label symmetry: first starter is worker 0,+ second worker 1, third worker 2. All target/outcome assignments still run.+ Every labelled schedule maps to exactly one of these via worker renaming.+ """++ def visit(phases, history):+ if all(phase == 4 for phase in phases):+ yield history+ return+ first_unstarted = next((i for i, phase in enumerate(phases) if not phase), None)+ for worker, phase in enumerate(phases):+ if phase == 4 or (canonical_starts and phase == 0 and worker != first_unstarted):+ continue+ updated = list(phases)+ updated[worker] += 1+ yield from visit(updated, (*history, (worker, phase)))++ return tuple(visit([0] * workers, ()))++[email protected]("workers,orderings", [(2, 70), (3, 5775)])[email protected]("previous", [None, _OLD, _NEW])+def test_every_publication_interleaving(workers, orderings, previous):+ from hub.workers import hf_download as w++ schedules = _schedules(workers, canonical_starts = workers == 3)+ assert len(schedules) == orderings+ checked = 0+ # The fake transfer records completion; verification independently returns+ # success, failure, cancellation, or a killed owner. Only the final step may+ # change a ref; killed attempts leave via the production pruning reducer.+ for assignments in itertools.product(+ itertools.product((_OLD, _NEW), ("ok", "fail", "cancel", "killed")), repeat = workers+ ):+ for schedule in schedules:+ state = w._MainRefState(published_commit = previous)+ started, succeeded, sequences, transferred, verified, finished = (+ [],+ set(),+ {},+ set(),+ {},+ set(),+ )+ ref = previous+ for worker, phase in schedule:+ commit, outcome = assignments[worker]+ if phase == 0:+ started.append(worker)+ state, sequences[worker] = w._start_main_ref(state, commit, str(worker))+ elif phase == 1:+ transferred.add(worker) # fake transfer: no ref side effects+ elif phase == 2:+ assert worker in transferred+ verified[worker] = outcome == "ok"+ else:+ finished.add(worker)+ ok = verified[worker]+ before = ref+ if outcome == "killed":+ state = w._prune_main_ref_attempts(+ state, lambda owner: owner != str(worker)+ )+ else:+ state = w._finish_main_ref(state, sequences[worker], ok)+ if ok:+ succeeded.add(worker)+ ref = state.published_commit+ else:+ assert ref == before # failure/cancel cannot hide a peer+ # Independent oracle: scan chronological starts backwards for a+ # terminal verified success, without using the reducer's sequence.+ winner = next((i for i in reversed(started) if i in succeeded), None)+ expected = previous if winner is None else assignments[winner][0]+ assert ref == expected, (assignments, schedule, worker, phase)+ assert state.published_commit == expected+ assert dict(state.attempts) == {+ sequences[i]: assignments[i][0] for i in started if i not in finished+ }+ assert dict(state.owners) == {+ sequences[i]: str(i) for i in started if i not in finished+ }+ assert not state.attempts+ assert not state.owners+ checked += 1+ assert checked == orderings * 8**workers+ print(f"{workers} workers, initial={previous}: {checked:,} schedules checked")+++ "outcome", ["fail", "cancel", "verify_fail", "verify_cancel", "wrong_commit"]+)[email protected]("previous", [None, _OLD])+def test_failed_attempt_never_exposes_landed_partial(monkeypatch, tmp_path, outcome, previous):+ from huggingface_hub import constants+ from hub.workers import hf_download as w+ from hub.utils import download_manifest as dm++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ repo = tmp_path / "models--fake--repo"+ ref = repo / "refs" / "main"+ if previous is not None:+ ref.parent.mkdir(parents = True)+ ref.write_text(previous)+ calls = []++ def transfer(**kwargs):+ calls.append(kwargs["revision"])+ assert w._read_ref(ref) == previous+ target = repo / "snapshots" / (_OLD if outcome == "wrong_commit" else _NEW)+ target.mkdir(parents = True)+ (target / "weights").write_bytes(b"partial")+ if outcome == "fail":+ raise OSError("transfer failed after bytes landed")+ if outcome == "cancel":+ raise KeyboardInterrupt+ return str(target)++ if outcome == "verify_cancel":++ def cancel(*args):+ raise KeyboardInterrupt++ monkeypatch.setattr(dm, "verify_against_disk", cancel)+ with pytest.raises(KeyboardInterrupt if "cancel" in outcome else OSError):+ w._pinned_snapshot_download(+ transfer,+ _NEW,+ repo_id = _REPO,+ expected_files = [dm.ExpectedFile("weights", 100)],+ )+ assert calls == [_NEW] # failure never retries an older branch snapshot+ assert w._read_ref(ref) == previous+ state_file = tmp_path / ".locks" / repo.name / "studio-main.json"+ state = w._load_main_ref_state(state_file, previous)+ assert not state.attempts+ assert state.published_sequence == 0+++def test_coordination_failure_does_not_transfer_unpinned(monkeypatch, tmp_path):+ from huggingface_hub import constants+ from hub.workers import hf_download as w++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ state_file = tmp_path / ".locks" / "models--fake--repo" / "studio-main.json"+ state_file.parent.mkdir(parents = True)+ state_file.write_text("{broken journal")++ def transfer(**kwargs):+ pytest.fail("coordination failure must not run an unpinned transfer")++ with pytest.raises(json.JSONDecodeError):+ w._pinned_snapshot_download(transfer, _NEW, repo_id = _REPO)+++def test_temporary_ref_files_stay_outside_refs(monkeypatch, tmp_path):+ from hub.workers import hf_download as w++ ref = tmp_path / "repo" / "refs" / "main"+ replace = os.replace++ def checked_replace(source, target):+ assert Path(source).parent == ref.parent.parent+ assert list(ref.parent.iterdir()) == []+ replace(source, target)++ monkeypatch.setattr(w.os, "replace", checked_replace)+ w._write_ref(ref, _OLD)+ assert list(ref.parent.iterdir()) == [ref]+ assert ref.read_text() == _OLD++[email protected]("failure", ["state", "ref", "cancel_after_replace"])+def test_failed_publication_does_not_disown_older_success(monkeypatch, tmp_path, failure):+ from huggingface_hub import constants+ from hub.workers import hf_download as w++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ repo = tmp_path / "models--fake--repo"+ ref = repo / "refs" / "main"+ ref.parent.mkdir(parents = True)+ baseline = "c" * 40+ ref.write_text(baseline)+ original_write = w._write_ref+ injected = False++ def write(path, value):+ nonlocal injected+ is_publication = (+ path.name == "studio-main.json" and json.loads(value)["published_sequence"] == 2+ if failure == "state"+ else path == ref and value == _NEW+ )+ if is_publication and not injected:+ injected = True+ if failure == "cancel_after_replace":+ original_write(path, value)+ raise KeyboardInterrupt+ raise OSError("publication write failed")+ original_write(path, value)++ monkeypatch.setattr(w, "_write_ref", write)++ def new_transfer(**kwargs):+ target = repo / "snapshots" / _NEW+ target.mkdir(parents = True)+ return str(target)++ def old_transfer(**kwargs):+ with pytest.raises(KeyboardInterrupt if failure == "cancel_after_replace" else OSError):+ w._pinned_snapshot_download(new_transfer, _NEW, repo_id = _REPO)+ assert injected+ assert ref.read_text() == baseline+ target = repo / "snapshots" / _OLD+ target.mkdir(parents = True)+ return str(target)++ w._pinned_snapshot_download(old_transfer, _OLD, repo_id = _REPO)+ assert ref.read_text() == _OLD+ state_file = tmp_path / ".locks" / repo.name / "studio-main.json"+ state = w._load_main_ref_state(state_file, baseline)+ assert state.published_sequence == 1+ assert not state.attemptsdiff --git a/studio/backend/tests/test_hf_download_reclaim_race.py b/studio/backend/tests/test_hf_download_reclaim_race.pynew file mode 100644index 00000000000..1b69e9801d3--- /dev/null+++ b/studio/backend/tests/test_hf_download_reclaim_race.py@@ -0,0 +1,150 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Exercise reclamation with real workers and a local HTTP Hub, including offline resolution."""++import hashlib+import os+import subprocess+import sys+import time+from pathlib import Path++import pytest++from .test_hf_download_pinned_revision import _FakeHub, _NEW, _OLD, _REPO, _WORKER, _repo_dir, _run+++def test_cache_blob_directory_identity_accepts_windows_extended_paths(tmp_path):+ from hub.services.models.cache_inventory import _is_real_cache_blob++ repo = _repo_dir(tmp_path)+ store = repo / "blobs"+ store.mkdir(parents = True)+ blob = store / ("d" * 64)+ blob.write_bytes(b"payload")+ alias = Path("\\\\?\\" + str(store.resolve())) if os.name == "nt" else store+ assert _is_real_cache_blob(alias / blob.name, repo)+ assert _is_real_cache_blob(blob, repo)+ outside = tmp_path / "other-blobs"+ outside.mkdir()+ (outside / blob.name).hardlink_to(blob)+ assert not _is_real_cache_blob(outside / blob.name, repo)+ assert not _is_real_cache_blob(repo / "snapshots" / "blobs" / blob.name, repo)+++def _worker_env(hub, tmp_path):+ env = dict(os.environ)+ env.pop("HF_TOKEN", None)+ env.update(+ HF_ENDPOINT = hub.endpoint,+ HF_HOME = str(tmp_path / "hf"),+ HF_HUB_CACHE = str(tmp_path / "hf" / "hub"),+ UNSLOTH_STUDIO_HOME = str(tmp_path / "studio"),+ HF_HUB_DISABLE_XET = "1",+ HF_HUB_ENABLE_HF_TRANSFER = "0",+ HF_HUB_DISABLE_TELEMETRY = "1",+ HF_HUB_DISABLE_IMPLICIT_TOKEN = "1",+ HF_HUB_OFFLINE = "0",+ CUDA_VISIBLE_DEVICES = "",+ )+ return env+++_PAUSED_WORKER = """+import runpy, sys, time+from pathlib import Path+import huggingface_hub as hf+worker, phase, root = sys.argv[1:]+root = Path(root)+original = hf.snapshot_download+def pause():+ (root / 'ready').touch()+ deadline = time.monotonic() + 30+ while not (root / 'release').exists():+ if time.monotonic() > deadline:+ raise RuntimeError('test did not release transfer')+ time.sleep(0.01)+def transfer(**kwargs):+ if phase == 'before_transfer':+ pause()+ result = original(**kwargs)+ if phase == 'after_transfer':+ pause()+ return result+hf.snapshot_download = transfer+sys.argv = [worker, '--repo-id', 'fake/repo', '--variant', 'Q4_K_M', '--transport', 'http']+runpy.run_path(worker, run_name='__main__')+"""++[email protected]("phase", ["before_transfer", "after_transfer"])+def test_gguf_reclaim_preserves_publication_and_active_peer(tmp_path, phase):+ hub = _FakeHub()+ child = None+ name = "model-Q4_K_M.gguf"+ try:+ # Same filename and size, different hashes: size verification cannot detect a mix-up.+ for commit, byte in ((_OLD, b"a"), (_NEW, b"b")):+ hub.commits[commit][name] = b"GGUF" + byte * 1024+ repo = _repo_dir(tmp_path)+ stale_commit = "c" * 40+ stale_data = b"GGUF" + b"c" * 1024+ stale_blob = repo / "blobs" / hashlib.sha256(stale_data).hexdigest()+ stale_blob.parent.mkdir(parents = True)+ stale_blob.write_bytes(stale_data)+ stale = repo / "snapshots" / stale_commit / name+ stale.parent.mkdir(parents = True)+ stale.symlink_to(stale_blob)+ ref = repo / "refs" / "main"+ ref.parent.mkdir()+ ref.write_text(stale_commit)++ child = subprocess.Popen(+ [sys.executable, "-c", _PAUSED_WORKER, str(_WORKER), phase, str(tmp_path)],+ env = _worker_env(hub, tmp_path),+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ text = True,+ )+ deadline = time.monotonic() + 20+ while not (tmp_path / "ready").exists():+ assert child.poll() is None, child.communicate()+ assert time.monotonic() < deadline, "older worker did not reach the transfer barrier"+ time.sleep(0.01)+ assert ref.read_text() == stale_commit+ hub.head = _NEW+ newer = _run(hub, tmp_path, "--variant", "Q4_K_M")+ assert newer.returncode == 0, newer.stderr+ assert ref.read_text() == _NEW+ assert not stale.exists() and not stale_blob.exists(), newer.stderr+ if phase == "after_transfer":+ assert (repo / "snapshots" / _OLD / name).read_bytes() == hub.commits[_OLD][name]+ (tmp_path / "release").touch()+ out, err = child.communicate(timeout = 30)+ assert child.returncode == 0, out + err+ assert ref.read_text() == _NEW++ offline = subprocess.run(+ [+ sys.executable,+ "-c",+ "from huggingface_hub import hf_hub_download; from pathlib import Path; "+ "import sys; p = hf_hub_download('fake/repo', sys.argv[2], "+ "cache_dir=sys.argv[1], local_files_only=True); "+ "assert Path(p).read_bytes() == b'GGUF' + b'b' * 1024",+ str(repo.parent),+ name,+ ],+ env = _worker_env(hub, tmp_path),+ capture_output = True,+ text = True,+ timeout = 20,+ )+ assert offline.returncode == 0, offline.stderr+ finally:+ (tmp_path / "release").touch()+ if child is not None and child.poll() is None:+ child.kill()+ child.communicate()+ hub.close()diff --git a/studio/backend/tests/test_hf_download_ref_concurrency.py b/studio/backend/tests/test_hf_download_ref_concurrency.pynew file mode 100644index 00000000000..155d90e5556--- /dev/null+++ b/studio/backend/tests/test_hf_download_ref_concurrency.py@@ -0,0 +1,224 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A later publication or completion wins over an older worker's ref changes."""++import os+import subprocess+import sys+import threading+import time+from pathlib import Path++import pytest++from .test_hf_download_pinned_revision import _NEW, _OLD, _REPO, _BACKEND+++_CHILD = """+import sys, time+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from hub.workers import hf_download as w+root, mode = Path(sys.argv[2]), sys.argv[3]+repo = root / 'models--fake--repo'+def transfer(**kwargs):+ (root / 'ready').touch()+ deadline = time.monotonic() + 15+ while not (root / 'release').exists():+ if time.monotonic() > deadline:+ raise RuntimeError('peer did not release child')+ time.sleep(0.01)+ if mode == 'cancel':+ raise KeyboardInterrupt+ target = repo / 'snapshots' / ('a' * 40)+ target.mkdir(parents=True, exist_ok=True)+ (target / 'model-Q4_K_M.gguf').write_bytes(b'GGUF-old')+ return str(target)+try:+ w._pinned_snapshot_download(transfer, ('b' if mode == 'cancel' else 'a') * 40,+ repo_id='fake/repo')+except KeyboardInterrupt:+ pass+"""++[email protected]("mode", ["older_success", "cancel"])+def test_peer_completion_survives_an_older_process(monkeypatch, tmp_path, mode):+ from hub.workers import hf_download as w+ from huggingface_hub import constants, snapshot_download++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ repo = tmp_path / "models--fake--repo"+ ref = repo / "refs" / "main"+ ref.parent.mkdir(parents = True)+ ref.write_text(_OLD)+ target = repo / "snapshots" / _NEW+ target.mkdir(parents = True)+ # A no-op successful peer is still a completion. Snapshot state alone cannot detect it.+ (target / "model-Q8_0.gguf").write_bytes(b"GGUF-new")+ env = dict(os.environ, HF_HUB_CACHE = str(tmp_path), CUDA_VISIBLE_DEVICES = "")+ child = subprocess.Popen(+ [sys.executable, "-c", _CHILD, str(_BACKEND), str(tmp_path), mode],+ env = env,+ stdout = subprocess.PIPE,+ stderr = subprocess.PIPE,+ text = True,+ )+ try:+ deadline = time.monotonic() + 10+ while not (tmp_path / "ready").exists():+ assert child.poll() is None, child.communicate()+ assert time.monotonic() < deadline, "child did not start its transfer"+ time.sleep(0.01)+ w._pinned_snapshot_download(lambda **kw: str(target), _NEW, repo_id = _REPO)+ assert ref.read_text() == _NEW+ (tmp_path / "release").touch()+ out, err = child.communicate(timeout = 20)+ assert child.returncode == 0, out + err+ resolved = Path(snapshot_download(_REPO, cache_dir = str(tmp_path), local_files_only = True))+ assert resolved.name == _NEW+ assert (resolved / "model-Q8_0.gguf").read_bytes() == b"GGUF-new"+ finally:+ if child.poll() is None:+ child.kill()+ child.communicate()+++def test_cancel_final_read_cannot_race_a_successful_peer(monkeypatch, tmp_path):+ from hub.workers import hf_download as w+ from huggingface_hub import constants++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ repo = tmp_path / "models--fake--repo"+ ref = repo / "refs" / "main"+ ref.parent.mkdir(parents = True)+ ref.write_text(_OLD)+ at_read, peer_started, peer_done = (threading.Event() for _ in range(3))+ original_read = w._read_ref+ cancelling = False+ paused = False+ failures = []++ def read(path):+ nonlocal paused+ captured = original_read(path)+ if (+ path == ref+ and threading.current_thread().name == "cancel"+ and cancelling+ and not paused+ ):+ paused = True+ at_read.set()+ assert peer_started.wait(5)+ peer_done.wait(0.5) # A locked peer must wait until this critical section ends.+ return captured++ monkeypatch.setattr(w, "_read_ref", read)++ def transfer(**kw):+ nonlocal cancelling+ cancelling = True+ raise KeyboardInterrupt++ def cancel():+ try:+ w._pinned_snapshot_download(transfer, _NEW, repo_id = _REPO)+ except KeyboardInterrupt:+ pass+ except BaseException as exc:+ failures.append(exc)++ def peer_transfer(**kw):+ target = repo / "snapshots" / _NEW+ target.mkdir(parents = True)+ (target / "model-Q8_0.gguf").write_bytes(b"GGUF-new")+ return str(target)++ def peer():+ peer_started.set()+ try:+ w._pinned_snapshot_download(peer_transfer, _NEW, repo_id = _REPO)+ except BaseException as exc:+ failures.append(exc)+ finally:+ peer_done.set()++ a = threading.Thread(target = cancel, name = "cancel")+ b = threading.Thread(target = peer, name = "peer")+ a.start()+ try:+ assert at_read.wait(5)+ b.start()+ finally:+ peer_started.set()+ a.join(10)+ if b.ident is not None:+ b.join(10)+ assert not a.is_alive() and not b.is_alive()+ assert not failures, failures+ assert ref.read_text() == _NEW++[email protected]("restart_commit", [_NEW, "c" * 40])+def test_cancelled_restart_cannot_hide_a_surviving_peers_snapshot(+ monkeypatch, tmp_path, restart_commit+):+ from hub.workers import hf_download as w+ from huggingface_hub import constants, hf_hub_download++ monkeypatch.setattr(constants, "HF_HUB_CACHE", str(tmp_path))+ repo = tmp_path / "models--fake--repo"+ ref = repo / "refs" / "main"+ ref.parent.mkdir(parents = True)+ ref.write_text(_OLD)+ (repo / "snapshots" / _OLD).mkdir(parents = True)+ ready, release = threading.Event(), threading.Event()+ results, failures = [], []+ target = repo / "snapshots" / _NEW+ weights = "model-Q8_0.gguf"++ def peer_transfer(**kw):+ assert kw["revision"] == _NEW+ ready.set()+ assert release.wait(10), "peer was not released"+ target.mkdir(parents = True)+ (target / weights).write_bytes(b"GGUF-new")+ return str(target)++ def peer():+ try:+ results.append(w._pinned_snapshot_download(peer_transfer, _NEW, repo_id = _REPO))+ except BaseException as exc:+ failures.append(exc)++ b = threading.Thread(target = peer, name = "surviving-peer")++ def first_transfer(**kw):+ b.start() # B joins A's generation before A rolls the ref back.+ assert ready.wait(5), "peer did not start"+ raise KeyboardInterrupt++ def restart_transfer(**kw):+ assert kw["revision"] == restart_commit+ raise KeyboardInterrupt++ try:+ with pytest.raises(KeyboardInterrupt):+ w._pinned_snapshot_download(first_transfer, _NEW, repo_id = _REPO)+ assert ref.read_text() == _OLD+ with pytest.raises(KeyboardInterrupt):+ w._pinned_snapshot_download(restart_transfer, restart_commit, repo_id = _REPO)+ assert ref.read_text() == _OLD+ finally:+ release.set()+ if b.ident is not None:+ b.join(10)+ assert not b.is_alive()+ assert not failures, failures+ assert results == [str(target)]+ # A successful peer must publish its files through the actual offline repo-ID resolver.+ loaded = hf_hub_download(_REPO, weights, cache_dir = str(tmp_path), local_files_only = True)+ assert Path(loaded).read_bytes() == b"GGUF-new"+ assert ref.read_text() == _NEWdiff --git a/studio/backend/tests/test_hf_download_saved_manifest_fallback.py b/studio/backend/tests/test_hf_download_saved_manifest_fallback.pynew file mode 100644index 00000000000..ea33bf215c4--- /dev/null+++ b/studio/backend/tests/test_hf_download_saved_manifest_fallback.py@@ -0,0 +1,200 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Offline full/scoped retries must verify before becoming publication winners."""++import subprocess+import sys++import pytest++from .test_hf_download_pinned_revision import _BACKEND, _FakeHub, _NEW+from .test_hf_download_reclaim_race import _worker_env+++_CHILD = r"""+import hashlib, json, os, sys+from pathlib import Path+sys.path.insert(0, sys.argv[1])+import huggingface_hub as hf+from hub.workers import hf_download as w+from hub.utils import download_manifest as dm+from hub.utils.snapshot_reuse import repo_cache_dir++kind, scenario = sys.argv[2:]+repo_id, old, new = 'fake/repo', 'a' * 40, 'b' * 40+files = ['config.json', 'model.safetensors']+scope = 'test-scope' if kind == 'scoped' else None+repo = repo_cache_dir('model', repo_id)+ref = repo / 'refs' / 'main'+journal = repo.parent / '.locks' / repo.name / 'studio-main.json'+original = hf.snapshot_download++def download():+ if scope is None:+ w._download_snapshot(repo_id, None, 'http')+ else:+ w._download_scoped_snapshot(repo_id, scope, files, None, 'http')++def unavailable(*args, **kwargs):+ raise OSError('test metadata unavailable')++def cancel_after_transfer(**kwargs):+ original(**kwargs)+ raise KeyboardInterrupt('cancelled after requested files landed')++def offline_transfer(**kwargs):+ transfers.append(kwargs['revision'])+ return original(**kwargs, local_files_only=True)++if scenario in ('resume', 'peer'):+ if scenario == 'peer':+ # Publish A, then leave an attested manifest for a cancelled B download.+ original(repo_id=repo_id, revision=old, allow_patterns=files, token=False)+ ref.parent.mkdir(parents=True, exist_ok=True)+ ref.write_text(old)+ hf.snapshot_download = cancel_after_transfer+ try:+ download()+ except KeyboardInterrupt:+ pass+ else:+ raise AssertionError('first worker was not cancelled')+ assert w._read_ref(ref) == (old if scenario == 'peer' else None)+ saved = dm.read_manifest('model', repo_id, scope)+ assert saved.metadata_derived and saved.commit_hash == new, saved+ assert {item.path for item in saved.expected_files} == set(files)+ # A real immutable local-only Hub lookup succeeds despite refs/main being absent/A.+ cached = original(repo_id=repo_id, revision=new, allow_patterns=files,+ token=False, local_files_only=True)+ assert dm.verify_against_disk(saved, Path(cached)).ok+ assert dm.write_cancel_marker('model', repo_id, scope, 'http')+ w._model_info_with_retry = unavailable+ transfers = []+ hf.snapshot_download = offline_transfer+ if scenario == 'resume':+ download()+ assert transfers == [new], transfers+ assert ref.read_text() == new+ assert dm.verify_against_disk(saved, repo / 'snapshots' / new).ok+ else:+ # B is now incomplete. A later fallback must fail without outranking an+ # earlier B peer whose actual transfer completes after that failure.+ (repo / 'snapshots' / new / files[1]).unlink()+ failed = []+ def peer_transfer(**kwargs):+ try:+ download()+ except (OSError, SystemExit) as exc:+ failed.append(type(exc).__name__)+ else:+ raise AssertionError('incomplete metadata fallback succeeded')+ return original(**kwargs)+ w._pinned_snapshot_download(peer_transfer, new, repo_id=repo_id,+ token=False, allow_patterns=files, expected_files=saved.expected_files)+ assert failed, 'the fallback was not exercised'+ loaded = hf.hf_hub_download(repo_id, files[1], local_files_only=True)+ assert new in loaded, ('failed fallback suppressed verified peer', loaded,+ json.loads(journal.read_text()))+ assert transfers == [new], transfers+ assert ref.read_text() == new+ state = w._load_main_ref_state(journal, old)+ assert state.published_sequence == 2, state # cancelled first=1, peer=2, fallback=3+ assert not state.attempts and not state.owners+elif scenario in ('no_manifest', 'unattested'):+ # Legacy fallbacks still use the published ref. A manifest without metadata+ # attestation may supply expected files, but must not supply a revision.+ original(repo_id=repo_id, revision=old, allow_patterns=files, token=False)+ ref.parent.mkdir(parents=True, exist_ok=True)+ ref.write_text(old)+ if scenario == 'unattested':+ expected = [dm.ExpectedFile(name, (repo / 'snapshots' / old / name).stat().st_size)+ for name in files]+ assert dm.write_manifest('model', repo_id, scope, expected, 'http',+ commit_hash=new, metadata_derived=False)+ else:+ assert dm.read_manifest('model', repo_id, scope) is None+ w._model_info_with_retry = unavailable+ transfers = []+ hf.snapshot_download = offline_transfer+ download()+ assert transfers == [old], transfers+ loaded = hf.hf_hub_download(repo_id, files[1], local_files_only=True)+ assert old in loaded, loaded+ assert Path(loaded).read_bytes() == hashlib.sha256(b'old').digest() * 2048+else:+ # The saved scope may describe fewer files than the current request. Even+ # without a manifest, its existing requested-file check must precede publish.+ assert scenario in ('requested_saved', 'requested_no_manifest')+ original(repo_id=repo_id, revision=new, allow_patterns=[files[0]], token=False)+ ref.parent.mkdir(parents=True, exist_ok=True)+ ref.write_text(old)+ if scenario == 'requested_saved':+ original(repo_id=repo_id, revision=old, allow_patterns=[files[0]], token=False)+ data = (repo / 'snapshots' / new / files[0]).read_bytes()+ assert dm.write_manifest('model', repo_id, scope,+ [dm.ExpectedFile(files[0], len(data))], 'http',+ commit_hash=new, metadata_derived=True)+ else:+ # refs/main is the only available pin when no manifest exists.+ ref.write_text(new)+ w._model_info_with_retry = unavailable+ transfers = []+ hf.snapshot_download = offline_transfer+ try:+ download()+ except (OSError, SystemExit):+ pass+ else:+ raise AssertionError('missing requested file was accepted')+ state = w._load_main_ref_state(journal, w._read_ref(ref))+ assert state.published_sequence == 0, ('failed scoped request was published', state)+ assert w._read_ref(ref) == (old if scenario == 'requested_saved' else new)+ assert not state.attempts and not state.owners++# Resolve by repo ID through the real Hub API and check the exact fake B bytes.+if scenario in ('resume', 'peer'):+ loaded = hf.hf_hub_download(repo_id, files[1], local_files_only=True)+ assert new in loaded, loaded+ assert Path(loaded).read_bytes() == hashlib.sha256(b'new').digest() * 4096+print('verified', kind, scenario, 'on Hub', hf.__version__)+"""+++def _run_case(tmp_path, kind, scenario):+ hub = _FakeHub()+ try:+ hub.head = _NEW+ result = subprocess.run(+ [sys.executable, "-c", _CHILD, str(_BACKEND), kind, scenario],+ env = _worker_env(hub, tmp_path),+ capture_output = True,+ text = True,+ timeout = 40,+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert hub.requests+ print(result.stdout.strip())+ finally:+ hub.close()++[email protected]("kind", ["full", "scoped"])+def test_cancelled_first_download_resumes_from_saved_manifest_without_metadata(tmp_path, kind):+ _run_case(tmp_path, kind, "resume")++[email protected]("kind", ["full", "scoped"])+def test_failed_metadata_fallback_cannot_suppress_verified_peer(tmp_path, kind):+ _run_case(tmp_path, kind, "peer")++[email protected]("scenario", ["requested_saved", "requested_no_manifest"])+def test_scoped_requested_files_checked_before_publication(tmp_path, scenario):+ _run_case(tmp_path, "scoped", scenario)++[email protected]("kind", ["full", "scoped"])[email protected]("scenario", ["no_manifest", "unattested"])+def test_legacy_metadata_fallback_uses_published_revision(tmp_path, kind, scenario):+ _run_case(tmp_path, kind, scenario)diff --git a/studio/backend/tests/test_snapshot_progress_copy_layout.py b/studio/backend/tests/test_snapshot_progress_copy_layout.pynew file mode 100644index 00000000000..8f78ead2115--- /dev/null+++ b/studio/backend/tests/test_snapshot_progress_copy_layout.py@@ -0,0 +1,124 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A manifest dates copied snapshot files while refs/main still names the last verified success."""++import json+import subprocess+import sys++import pytest++from .test_hf_download_pinned_revision import _FakeHub, _FULL, _NEW, _OLD, _WORKER, _repo_dir+from .test_hf_download_reclaim_race import _worker_env+++_COPY_WORKER = """+import json, runpy, sys+from pathlib import Path+from types import SimpleNamespace+import huggingface_hub as hf+from huggingface_hub import file_download+worker, kind, root = sys.argv[1:]+root = Path(root)+sys.path.insert(0, str(Path(worker).parents[2]))+from hub.services import snapshot_progress as sp+from hub.utils import download_manifest as dm+repo = root / 'hf' / 'hub' / 'models--fake--repo'+variant = {'full': None, 'scoped': 'test-scope', 'gguf': 'Q4_K_M'}[kind]+file_download.are_symlinks_supported = lambda *a, **k: False+sp.preferred_repo_cache_dirs = lambda *a, **k: [repo]+original = hf.snapshot_download+observations = []+def poll():+ manifest = dm.read_manifest('model', 'fake/repo', variant, hub_cache=repo.parent)+ assert manifest is not None+ hashes = frozenset(f.sha256 for f in manifest.expected_files if f.sha256)+ total = sum(f.size for f in manifest.expected_files)+ reading = sp.compute_snapshot_progress(+ repo_type='model', repo_id='fake/repo', job_key='fake/repo',+ expected_bytes=total, hf_token=None, variant=variant,+ variant_file_matcher=lambda name, **kw: name in {f.path for f in manifest.expected_files},+ registry=SimpleNamespace(get_job=lambda key: SimpleNamespace(state='running')),+ metadata_resolver=lambda *args: (total, hashes),+ )+ observations.append(dict(+ reading=reading, commit=manifest.commit_hash, attested=manifest.metadata_derived,+ ref=(repo / 'refs' / 'main').read_text(),+ old_is_stale=sp._snapshot_is_stale_copy(repo / 'snapshots' / ('a' * 40), manifest),+ new_exists=any((repo / 'snapshots' / ('b' * 40) / f.path).exists()+ for f in manifest.expected_files),+ ))+def transfer(**kwargs):+ poll() # Metadata and manifest exist; no B bytes have been transferred.+ result = original(**kwargs)+ poll() # B now exists as regular files, but publication must still be deferred.+ return result+hf.snapshot_download = transfer+extra = []+if kind == 'gguf':+ extra = ['--variant', 'Q4_K_M']+elif kind == 'scoped':+ files = root / 'files.json'+ files.write_text(json.dumps(['config.json', 'model.safetensors']))+ extra = ['--variant', 'test-scope', '--files-json', str(files)]+sys.argv = [worker, '--repo-id', 'fake/repo', '--transport', 'http', *extra]+try:+ runpy.run_path(worker, run_name='__main__')+except SystemExit as exc:+ if exc.code:+ raise+(root / 'progress.json').write_text(json.dumps(observations))+"""++[email protected]("kind", ["full", "scoped", "gguf"])+def test_copy_layout_progress_uses_attested_download_commit(tmp_path, kind):+ hub = _FakeHub()+ try:+ # Every old file has the expected new size and different content/hash.+ for name, data in hub.commits[_OLD].items():+ hub.commits[_NEW][name] = hub.commits[_NEW][name][: len(data)]+ assert len(hub.commits[_NEW][name]) == len(data)+ assert hub.commits[_NEW][name] != data+ repo = _repo_dir(tmp_path)+ old = repo / "snapshots" / _OLD+ old.mkdir(parents = True)+ for name, data in hub.commits[_OLD].items():+ (old / name).write_bytes(data)+ ref = repo / "refs" / "main"+ ref.parent.mkdir()+ ref.write_text(_OLD)+ hub.head = _NEW+ result = subprocess.run(+ [sys.executable, "-c", _COPY_WORKER, str(_WORKER), kind, str(tmp_path)],+ env = _worker_env(hub, tmp_path),+ capture_output = True,+ text = True,+ timeout = 60,+ )+ assert result.returncode == 0, result.stderr+ before, transferred = json.loads((tmp_path / "progress.json").read_text())+ assert before["ref"] == transferred["ref"] == _OLD+ assert before["new_exists"] is False+ assert transferred["new_exists"] is True+ # Full copy-layout progress already has no snapshot-byte fallback. All+ # three workers must nevertheless attest the revision that dates copies.+ assert before["reading"]["complete_on_disk"] is False, before+ assert before["reading"]["completed_bytes"] == 0, before+ assert before["reading"]["downloaded_bytes"] == 0, before+ assert before["reading"]["progress"] == 0, before+ assert before["commit"] == transferred["commit"] == _NEW, before+ assert before["attested"] and transferred["attested"], before+ assert before["old_is_stale"] and transferred["old_is_stale"], before+ if kind != "full":+ assert transferred["reading"]["complete_on_disk"] is True, transferred+ assert transferred["reading"]["progress"] == 1.0, transferred+ assert ref.read_text() == _NEW+ names = ["model-Q4_K_M.gguf"] if kind == "gguf" else _FULL+ for name in names:+ target = repo / "snapshots" / _NEW / name+ assert not target.is_symlink()+ assert target.read_bytes() == hub.commits[_NEW][name]+ finally:+ hub.close()