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.

Stop a finished download reporting 0 B and offering Retry (#8160)

Daniel Han68408d06e0cf
diff --git a/studio/backend/hub/schemas/downloads.py b/studio/backend/hub/schemas/downloads.py
index 05fc735c0fd..904e5bcd951 100644
--- a/studio/backend/hub/schemas/downloads.py
+++ b/studio/backend/hub/schemas/downloads.py
@@ -154,6 +154,21 @@ class DownloadProgressResponse(BaseModel):
expected_bytes: int
progress: float
cache_path: Optional[str] = None
+ cache_measured: bool = Field(
+ True,
+ description = (
+ "False when the cache could not be scanned at all (an unreadable root). The "
+ "reading is then unknown, not empty: cache_path is null either way, and "
+ "hydration must not retire a persisted job on a scan that never happened."
+ ),
+ )
+ target_present: Optional[bool] = Field(
+ None,
+ description = (
+ "Whether this TARGET (variant) has anything in the cache, as opposed to the "
+ "shared repo directory existing. Null where it cannot be established."
+ ),
+ )
class DownloadDatasetRequest(BaseModel):
diff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.py
index 32b85cb0be6..6ed216389c6 100644
--- a/studio/backend/hub/services/models/downloads.py
+++ b/studio/backend/hub/services/models/downloads.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import asyncio
+from pathlib import Path
from typing import Optional, Sequence, TYPE_CHECKING
from fastapi import HTTPException
@@ -19,8 +20,9 @@ from hub.schemas.downloads import (
)
from hub.utils import download_registry
from hub.utils import download_manifest
+from hub.utils import gguf_plan
from hub.utils import inventory_scan as hf_cache_scan
-from hub.utils.hf_cache_state import has_active_incomplete_blobs
+from hub.utils.hf_cache_state import has_active_incomplete_blobs, preferred_repo_cache_dirs
from hub.utils.snapshot_filters import blob_hashes_for_siblings
from hub.utils.paths import (
is_valid_gguf_variant as _is_valid_gguf_variant,
@@ -490,6 +492,108 @@ async def get_model_transport_status_response(
}
+def _variant_manifest_in_any_cache(
+ repo_id: str,
+ variant: str,
+ *,
+ force_active: bool = False,
+ active_root: Optional[Path] = None,
+) -> Optional[download_manifest.Manifest]:
+ """The manifest half of :func:`_variant_manifest_decision`."""
+ return _variant_manifest_decision(
+ repo_id, variant, force_active = force_active, active_root = active_root
+ )[1]
+
+
+def _variant_manifest_decision(
+ repo_id: str,
+ variant: str,
+ *,
+ force_active: bool = False,
+ active_root: Optional[Path] = None,
+) -> "tuple[str, Optional[download_manifest.Manifest]]":
+ """The variant's manifest from whichever cache dir on disk holds it, and why.
+
+ The verdict is ``"found"``, ``"absent"`` (no cache on disk has one) or ``"refused"`` (one
+ exists but applying it across the scanned caches would be wrong). Callers have to tell those
+ last two apart: a refusal is a decision that NO manifest may speak here, so re-reading one by
+ another route walks straight back into the answer this function just rejected.
+
+ snapshot_progress reads manifests per scanned cache entry (``entry.parent``)
+ while this resolver only ever asked the active cache, so the two could
+ disagree about whether a manifest exists at all. When it lost, the expected
+ file set came back empty and the hash filter then dropped every blob in the
+ shared ``blobs/`` dir -- a finished variant reporting 0 bytes against the
+ caller's catalog-hinted total. Active cache first, so the common case is one
+ lookup; every candidate found has to agree before one is returned.
+ """
+ # The active cache's manifest is a candidate like any other, NOT an early return. Its repo
+ # dir can be gone while its scoped state still holds an old manifest, and idle progress goes
+ # on scanning the remembered caches -- so returning it unexamined applies a stale revision's
+ # hashes to a remembered cache that has the complete variant, and filters every blob of it
+ # out. That is the same wrong answer as two remembered caches disagreeing.
+ found: list[download_manifest.Manifest] = []
+ # ``active_root`` is the root the job records, which is the one snapshot_progress scans; it
+ # is not necessarily the configured default (a cache moved mid-download), and reading the
+ # default there would be another cache's answer again.
+ active_manifest = download_manifest.read_manifest(
+ "model", repo_id, variant, hub_cache = active_root
+ )
+ if active_manifest is not None:
+ found.append(active_manifest)
+ # The active cache was just probed by the call above and a state-dir miss is not free, so
+ # skip the entry that repeats it. In the common case preferred_repo_cache_dirs returns only
+ # that entry and this loop does no work at all.
+ active = download_manifest._canonical_hub_cache(active_root)
+ # The SAME cache dirs snapshot_progress will scan. A running or cancelling job writes into
+ # the active root and is read only from there, so a remembered cache's manifest for the same
+ # variant is not merely a second opinion -- its hashes would be applied to the active root's
+ # blobs and filter out every byte the live download has written, leaving the card at 0 B
+ # until Hub metadata comes back.
+ for entry in preferred_repo_cache_dirs(
+ "model", repo_id, force_active = force_active, active_root = active_root
+ ):
+ if active is not None and download_manifest._canonical_hub_cache(entry.parent) == active:
+ if active_manifest is None:
+ # The cache snapshot_progress will scan, with no manifest of its own. Anything
+ # returned here would be another cache's answer applied to its blobs.
+ return ("refused", None)
+ continue
+ manifest = download_manifest.read_manifest(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = entry.parent,
+ )
+ if manifest is None:
+ # A scanned cache that contributed NOTHING. Its snapshot may be the complete one --
+ # a manifest can be deleted, or never written by an older build -- and returning
+ # some other cache's hashes filters every blob of it out AND disables the per-entry
+ # name-based fallback that would still have counted them. Refuse instead.
+ return ("refused", None)
+ found.append(manifest)
+ if not found:
+ return ("absent", None)
+ # One answer, or several that agree: safe to apply to every scanned entry, which is what
+ # snapshot_progress does with the hash set this produces.
+ #
+ # Several that DISAGREE is the case worth refusing. snapshot_progress picks its reading by
+ # bytes, across all the preferred cache dirs, but the hashes come from this single lookup --
+ # so handing it the first cache's older revision filters out every blob of a LATER cache that
+ # holds the complete variant, and reports 0 or partial for a finished download. That is the
+ # exact failure this fallback exists to prevent, just sourced from the wrong cache. Returning
+ # None instead degrades to the name-based fallback, which stays attributable per entry.
+ first = _manifest_hashes(found[0])
+ if any(_manifest_hashes(m) != first for m in found[1:]):
+ return ("refused", None)
+ return ("found", found[0])
+
+
+def _manifest_hashes(manifest: download_manifest.Manifest) -> frozenset[str]:
+ """The manifest's expected-file identity, for comparing two caches' answers."""
+ return frozenset(f"{f.sha256 or ''}:{f.path}:{f.size}" for f in (manifest.expected_files or ()))
+
+
async def get_gguf_download_progress_response(
repo_id: str,
variant: str = "",
@@ -521,16 +625,33 @@ async def get_gguf_download_progress_response(
)
if requirement is not None:
return requirement.download_size_bytes, requirement.required_hashes
- manifest = download_manifest.read_manifest(
- "model",
+ job_key = _download_job_key(resolved_repo_id, progress_variant)
+ job = _registry.get_job(job_key)
+ # getattr, the same way snapshot_progress reads it: a registry without the accessor
+ # simply has no recorded root, which is the "use the configured one" case.
+ get_job_metadata = getattr(_registry, "get_job_metadata", None)
+ job_metadata = get_job_metadata(job_key) if callable(get_job_metadata) else None
+ hub_cache = getattr(job_metadata, "hub_cache", None)
+ verdict, manifest = _variant_manifest_decision(
resolved_repo_id,
progress_variant,
+ # Same scoping rule snapshot_progress applies to its own scan.
+ force_active = job.state in {"running", "cancelling"},
+ active_root = Path(hub_cache) if hub_cache else None,
)
if manifest is not None:
return (
sum(max(0, int(file.size or 0)) for file in manifest.expected_files),
frozenset(file.sha256 for file in manifest.expected_files if file.sha256),
)
+ if verdict == "refused":
+ # A refusal is not a miss. The lookup above found manifests and ruled that none of
+ # them may be applied across the caches snapshot_progress scans; the blob-hash
+ # helper reads the DEFAULT cache's manifest with none of that scoping, so falling
+ # through here reinstates the very hashes just rejected and filters out every blob
+ # of whichever cache actually holds the variant. An empty set degrades to the
+ # per-entry name-based fallback, which stays attributable to the entry it counted.
+ return (expected_total, frozenset())
return (
expected_total,
gguf_variants.gguf_variant_blob_hashes(
@@ -541,6 +662,43 @@ async def get_gguf_download_progress_response(
),
)
+ def _expected_files_resolver(
+ resolved_repo_id: str, token: Optional[str]
+ ) -> Sequence[download_manifest.ExpectedFile]:
+ """What HF says this variant should contain, paths and declared sizes.
+
+ The only thing that lets a finished variant whose manifest is missing
+ settle terminal instead of staying partial forever, so it has to be the
+ metadata's own file list: a byte tally taken from the shared blobs/ dir
+ cannot tell this quant's bytes from a sibling's. The requirement lookup
+ is cached, and snapshot_progress only calls this once a reading has
+ otherwise passed for complete.
+ """
+ if progress_variant is None:
+ return ()
+ requirement = gguf_variants.gguf_variant_requirements(
+ resolved_repo_id,
+ progress_variant,
+ token,
+ )
+ return requirement.expected_files if requirement is not None else ()
+
+ def _variant_file_matcher(path: str, *, companions: bool = True) -> bool:
+ # Which snapshot files a quant owns, for the reading snapshot_progress
+ # falls back to when the blob hashes cannot be resolved. Main shards are
+ # matched by quant label; mmproj and the MTP drafter are downloaded with
+ # every variant, so they belong to whichever one is being polled.
+ #
+ # ``companions`` False asks the narrower question -- does this path prove the quant
+ # ITSELF is here -- which the caller uses first: shared companions belong to every
+ # quant in the repo, so counting them for a variant whose main shard was deleted
+ # reported bytes for a file that is gone.
+ if progress_variant is None:
+ return False
+ if gguf_plan.is_main_gguf_variant_path(path, progress_variant):
+ return True
+ return companions and gguf_plan.is_companion_gguf_path(path)
+
return await snapshot_progress.snapshot_progress_response(
repo_type = "model",
repo_id = repo_id,
@@ -550,6 +708,8 @@ async def get_gguf_download_progress_response(
registry = _registry,
metadata_resolver = _metadata_resolver,
variant = progress_variant,
+ variant_file_matcher = _variant_file_matcher,
+ expected_files_resolver = _expected_files_resolver,
)
diff --git a/studio/backend/hub/services/snapshot_progress.py b/studio/backend/hub/services/snapshot_progress.py
index c3db6fed7a7..f8a925cd155 100644
--- a/studio/backend/hub/services/snapshot_progress.py
+++ b/studio/backend/hub/services/snapshot_progress.py
@@ -12,9 +12,11 @@ summing stale blobs against the wrong total)."""
from __future__ import annotations
import asyncio
+import os
+import stat as stat_module
import threading
from pathlib import Path
-from typing import Callable, Optional
+from typing import Callable, Generic, Optional, Sequence, TypeVar
from loggers import get_logger
@@ -25,8 +27,8 @@ from hub.utils.state_dir import RepoType
from hub.utils.hf_cache_state import (
INCOMPLETE_SUFFIX,
blob_bytes_present,
- latest_snapshot_dir,
preferred_repo_cache_dirs,
+ snapshot_selection_key,
)
from hub.utils.paths import is_valid_repo_id as _is_valid_repo_id
@@ -34,6 +36,14 @@ logger = get_logger(__name__)
# (repo_id, hf_token) -> (expected_total_bytes, expected_blob_hashes)
SnapshotMetadataResolver = Callable[[str, Optional[str]], "tuple[int, frozenset[str]]"]
+# (repo_id, hf_token) -> the files HF says this target should contain. Optional,
+# and the only thing that lets a materialized snapshot with no manifest settle.
+SnapshotExpectedFilesResolver = Callable[
+ [str, Optional[str]], Sequence["download_manifest.ExpectedFile"]
+]
+# repo-relative snapshot path -> whether it belongs to the variant being polled.
+# Supplied per repo kind, so this module keeps knowing nothing about quant labels.
+VariantFileMatcher = Callable[[str], bool]
# One progress log per 10% step per job, so an active download reports progress
# without emitting a line on every poll.
@@ -58,15 +68,236 @@ def _log_progress_step(job_key: str, repo_id: str, variant: Optional[str], progr
)
-def _empty_progress(expected_bytes: int) -> dict:
- return {
+def _empty_progress(expected_bytes: int, *, measured: bool = True) -> dict:
+ """An all-zero reading.
+
+ ``measured`` is the difference between "there is no cache dir for this repo" and "the scan
+ itself failed". Hydration retires a persisted job on the first and must not on the second: a
+ transient failure is not evidence that a partial cache was wiped.
+
+ Carried as its own flag, not by omitting ``cache_path``: these dicts are serialized through
+ DownloadProgressResponse, whose ``cache_path`` defaults to None, so the omission was
+ reinstated as an explicit null before the frontend ever saw it and the distinction was lost
+ on every route. An older backend sends neither field, which the frontend reads as unknown,
+ so the rule still covers it."""
+ reading = {
"downloaded_bytes": 0,
"completed_bytes": 0,
"complete_on_disk": False,
"expected_bytes": max(expected_bytes, 0),
"progress": 0,
- "cache_path": None,
+ "cache_measured": measured,
}
+ if measured:
+ reading["cache_path"] = None
+ return reading
+
+
+_T = TypeVar("_T")
+
+
+class _Lazy(Generic[_T]):
+ """A value computed at most once, and only once something asks for it.
+
+ The entry's manifest, its newest snapshot dir and the metadata file list are
+ each wanted by two callers -- the unknown-file-set byte reading and the
+ completion check -- and the completion check only wants them once its cheap
+ byte guards have passed. Taking them up front would put a state-dir lookup,
+ a ``snapshots/`` listing and a metadata call on every poll of every repo
+ that is still mid-download.
+ """
+
+ __slots__ = ("_compute", "_value", "_loaded")
+
+ def __init__(self, compute: Callable[[], _T]) -> None:
+ self._compute = compute
+ self._value: Optional[_T] = None
+ self._loaded = False
+
+ def get(self) -> _T:
+ if not self._loaded:
+ self._value = self._compute()
+ self._loaded = True
+ return self._value # type: ignore[return-value]
+
+
+def _variant_bytes_on_disk(
+ manifest: Optional[download_manifest.Manifest],
+ snapshot_dir: Optional[Path],
+ variant_file_matcher: Optional["VariantFileMatcher"],
+) -> int:
+ """Bytes a variant owns, read from the snapshot dir instead of ``blobs/``.
+
+ Only used when the expected blob hashes could not be resolved. The snapshot
+ dir is the one variant-scoped view of the cache: its entries are named per
+ file, so a sibling quant is excluded by name, whereas in the shared
+ ``blobs/`` dir a sibling's bytes are indistinguishable from this variant's
+ and counting them wholesale is the "instant ~900 MB" bug. ``stat`` follows
+ HF's symlink layout and reads the Windows copy layout directly.
+ """
+ if snapshot_dir is None:
+ return 0
+ total = 0
+ if manifest is not None:
+ for expected in manifest.expected_files:
+ if not download_manifest.expected_path_is_safe(expected.path):
+ continue
+ try:
+ total += (snapshot_dir / expected.path).stat().st_size
+ except OSError:
+ continue
+ return total
+ if variant_file_matcher is None:
+ return 0
+ return _materialized_bytes(snapshot_dir, variant_file_matcher)
+
+
+def _walk_files(root: Path) -> "tuple[list[Path], bool]":
+ """Every file under ``root``, and whether the traversal saw all of it.
+
+ Not ``rglob``: it suppresses every OSError raised while scanning (documented behaviour
+ since 3.13), so an unreadable subtree comes back as a SHORT list that is indistinguishable
+ from an empty one -- and a caller asking "is the variant here?" then answers a confident
+ no about a directory it could not read. ``os.scandir`` reports the failure, and a subtree
+ that is genuinely missing is not one.
+ """
+ files: list[Path] = []
+ complete = True
+ stack = [root]
+ while stack:
+ current = stack.pop()
+ try:
+ with os.scandir(current) as scan:
+ entries = list(scan)
+ except (FileNotFoundError, NotADirectoryError):
+ continue # nothing there IS the answer, not a gap in the reading
+ except OSError:
+ complete = False
+ continue
+ for entry in entries:
+ try:
+ if entry.is_dir(follow_symlinks = False):
+ stack.append(Path(entry.path))
+ elif entry.is_file():
+ files.append(Path(entry.path))
+ except OSError:
+ # DirEntry.is_dir/is_file raise rather than suppress, so this one is visible.
+ complete = False
+ return files, complete
+
+
+def _variant_main_shard_present(
+ snapshot_dir: Optional[Path], variant_file_matcher: Optional["VariantFileMatcher"]
+) -> Optional[bool]:
+ """Whether the variant's OWN files are in the snapshot dir. None when unanswerable.
+
+ The narrower question ``companions = False`` asks: shared companions belong to every quant
+ in the repo, so their presence says nothing about this one. Used on the path where the blob
+ hashes could not be resolved -- the snapshot dir is still named per file, so it can settle
+ absence even when the hash filter cannot, and an unreadable or absent dir stays unknown.
+ """
+ if snapshot_dir is None or variant_file_matcher is None:
+ return None
+ # An entry we could not read may BE the main shard -- a transient network-filesystem hiccup
+ # or a Windows ACL denial on one directory is not evidence the variant is gone. A positive
+ # match elsewhere still settles it; otherwise the reading stays unknown.
+ entries, complete = _walk_files(snapshot_dir)
+ for path in entries:
+ relative = path.relative_to(snapshot_dir).as_posix()
+ if variant_file_matcher(relative, companions = False):
+ return True
+ return None if not complete else False
+
+
+def _retained_snapshot_dirs(entry: Path) -> list[Path]:
+ """Every snapshot the repo cache dir keeps, newest first.
+
+ A cache can hold several revisions, and the requested variant is not always in the newest:
+ reading only that one reported a complete cached quant as 0 bytes and never verified its
+ manifest, so it stayed at 99% and adoptable.
+ """
+ try:
+ snapshots = [child for child in (entry / "snapshots").iterdir() if child.is_dir()]
+ except OSError:
+ return []
+ return sorted(snapshots, key = snapshot_selection_key, reverse = True)
+
+
+def _variant_present_in_any_snapshot(
+ entry: Path, variant_file_matcher: Optional["VariantFileMatcher"]
+) -> Optional[bool]:
+ """``_variant_main_shard_present`` over every snapshot the repo dir retains.
+
+ True as soon as one holds the variant's own file; False only when every snapshot was read
+ and none did; None when there was nothing to read or a read failed, which is unknown.
+ """
+ snapshots = _retained_snapshot_dirs(entry)
+ if not snapshots:
+ return None
+ verdicts = [
+ _variant_main_shard_present(snapshot, variant_file_matcher) for snapshot in snapshots
+ ]
+ if any(verdict is True for verdict in verdicts):
+ return True
+ if any(verdict is None for verdict in verdicts):
+ return None
+ return False
+
+
+def _materialized_bytes(snapshot_dir: Path, variant_file_matcher: "VariantFileMatcher") -> int:
+ """Bytes the variant's files present in the snapshot dir.
+
+ A predicate, not a file list, because this is the path where the file list
+ is precisely what could not be determined. That makes it a lower bound on
+ the wrong side for shared companions -- the matcher accepts every mmproj and
+ drafter in the repo, while a plan fetches one of each -- so it is fit for a
+ byte reading the caller clamps and displays, and not for deciding whether a
+ download finished. ``stat`` follows the link, so a blob that was written but
+ never linked contributes nothing, and the Windows copy layout is read as is.
+ """
+ try:
+ entries = list(snapshot_dir.rglob("*")) # unordered: the result is a sum
+ except OSError:
+ return 0
+
+ def _accepts(relative: str, *, companions: bool) -> bool:
+ # A matcher that understands the distinction gets asked for it; an older one is
+ # answered as before. Only the GGUF matcher takes the keyword today.
+ try:
+ return bool(variant_file_matcher(relative, companions = companions))
+ except TypeError:
+ return bool(variant_file_matcher(relative))
+
+ # Companions (mmproj, the MTP drafter) are shared by every quant in the repo, so on their
+ # own they are not evidence that THIS one is here. Deleting a quant while a sibling keeps
+ # its companion left a positive reading for the deleted variant, which hydration reads as
+ # active: it re-adopts the stale job and blocks a fresh download of the same quant.
+ owns_a_main = False
+ for path in entries:
+ try:
+ relative = path.relative_to(snapshot_dir).as_posix()
+ except ValueError:
+ continue
+ if _accepts(relative, companions = False):
+ try:
+ if path.is_file():
+ owns_a_main = True
+ break
+ except OSError:
+ continue
+ if not owns_a_main:
+ return 0
+
+ total = 0
+ for path in entries:
+ try:
+ relative = path.relative_to(snapshot_dir).as_posix()
+ if not _accepts(relative, companions = True) or not path.is_file():
+ continue
+ total += path.stat().st_size
+ except (OSError, ValueError):
+ continue
+ return total
def _snapshot_complete_on_disk(
@@ -75,34 +306,96 @@ def _snapshot_complete_on_disk(
repo_id: str,
variant: Optional[str],
entry: Path,
+ snapshot_dirs: "_Lazy[list[Path]]",
+ entry_manifest: "_Lazy[Optional[download_manifest.Manifest]]",
+ metadata_files: "_Lazy[tuple[download_manifest.ExpectedFile, ...]]",
expected_total: int,
completed_bytes: int,
in_progress_bytes: int,
+ expected_hashes: "frozenset[str]" = frozenset(),
) -> bool:
if expected_total <= 0 or completed_bytes < expected_total or in_progress_bytes > 0:
return False
- snapshot_dir = latest_snapshot_dir(entry)
- if snapshot_dir is None:
+ snapshots = snapshot_dirs.get()
+ if not snapshots:
return False
if variant is None and hf_cache_scan.repo_cache_dir_has_incomplete_blobs(entry):
return False
- hub_cache = entry.parent
if download_manifest.has_cancel_marker(
repo_type,
repo_id,
variant,
- hub_cache = hub_cache,
+ hub_cache = entry.parent,
):
return False
- manifest = download_manifest.read_manifest(
- repo_type,
- repo_id,
- variant,
- hub_cache = hub_cache,
- )
+ manifest = entry_manifest.get()
if manifest is None:
- return False
- return download_manifest.verify_against_disk(manifest, snapshot_dir).ok
+ # No manifest, but HF metadata describes the same thing a manifest does:
+ # the exact files this download was supposed to fetch, at their declared
+ # sizes. Verify against that rather than refusing outright, because a
+ # manifest that was never written (metadata was unreachable when the run
+ # ended), was deleted, or sits under a cache scope this reader cannot
+ # name is not evidence of an unfinished download -- and refusing left a
+ # materialized snapshot partial forever.
+ #
+ # Nothing weaker will do here. The caller's expected_bytes is a catalog
+ # hint, and a byte total assembled from the shared blobs/ dir cannot
+ # tell this variant's bytes from a sibling's or a stray companion's, so
+ # neither is grounds for calling a download complete. Checking the named
+ # files against the snapshot dir also catches the case a blob-level
+ # tally structurally cannot: HF writes a blob and then links it, so a
+ # run killed in between leaves bytes that nothing points at.
+ metadata_expected = metadata_files.get()
+ if not metadata_expected:
+ return False
+ manifest = download_manifest.Manifest(
+ repo_type = repo_type,
+ repo_id = repo_id,
+ variant = variant,
+ started_at = "",
+ expected_files = metadata_expected,
+ )
+ # ANY retained snapshot: the variant can be complete in an older revision while the newest
+ # holds only a sibling, and checking the newest alone left that download at 99% forever.
+ #
+ # But an older revision can carry the same FILENAMES at the same sizes and different
+ # content, and verify_against_disk does not read sha256 -- so with the resolved hashes in
+ # hand, require the snapshot's entries to actually resolve to them. Without that, a blob
+ # finalized but not yet linked (a crash between the two) let a stale revision satisfy the
+ # check and the job settled on files the app would not load. No resolved hashes means no
+ # such claim is possible, and the filename check stands alone as before.
+ for snap in snapshots:
+ if not download_manifest.verify_against_disk(manifest, snap).ok:
+ continue
+ if not expected_hashes or _snapshot_resolves_to(manifest, snap, expected_hashes):
+ return True
+ return False
+
+
+def _snapshot_resolves_to(
+ manifest: download_manifest.Manifest, snapshot: Path, expected_hashes: "frozenset[str]"
+) -> bool:
+ """Whether every expected file in ``snapshot`` points at one of ``expected_hashes``.
+
+ HF names a blob by its hash and the snapshot entry links to it, so the link target settles
+ which revision is materialized here. A copy-layout cache (Windows without symlinks) has no
+ target to read: unanswerable is not a mismatch, so it passes -- and it does not have to be
+ answered, because the byte tally that gates completion only ever counts blobs whose name IS
+ an expected hash, so the expected revision is already proven present in this cache dir.
+ """
+ for expected in getattr(manifest, "expected_files", ()) or ():
+ if not download_manifest.expected_path_is_safe(expected.path):
+ continue
+ entry = snapshot / expected.path
+ try:
+ if not entry.is_symlink():
+ continue # copy layout: nothing to compare against
+ target = os.path.basename(os.readlink(entry))
+ except OSError:
+ continue
+ if target and target not in expected_hashes:
+ return False
+ return True
def compute_snapshot_progress(
@@ -115,6 +408,8 @@ def compute_snapshot_progress(
registry,
metadata_resolver: SnapshotMetadataResolver,
variant: Optional[str] = None,
+ variant_file_matcher: Optional[VariantFileMatcher] = None,
+ expected_files_resolver: Optional[SnapshotExpectedFilesResolver] = None,
) -> dict:
"""Synchronous progress reading. Safe to run under ``asyncio.to_thread``."""
empty = _empty_progress(expected_bytes)
@@ -138,34 +433,75 @@ def compute_snapshot_progress(
# when metadata is unavailable (e.g. offline). Take the larger total so a low
# caller hint can't cap the bar below the revision's real size.
meta_total, expected_hashes = metadata_resolver(repo_id, hf_token)
+ meta_total = max(0, meta_total)
expected_total = max(expected_total, meta_total)
# Without resolved hashes, a variant must not count unscoped blobs: sibling
# quants share one blobs/ dir, so a sibling's bytes (or .incomplete) would be
# misattributed and make the bar jump backward. A no-variant snapshot owns
# the whole dir, so it counts unscoped.
- count_finalized_unscoped = variant is None
+ count_unscoped = variant is None
+ # An empty hash set is "the expected file set could not be determined", not
+ # "this variant has no bytes" -- model_info failing (offline, or a 401 on a
+ # gated repo) is negatively cached, so one failed lookup keeps the set empty
+ # for the whole TTL. Filtering every blob out then reports a finished 33 GB
+ # variant as "0 B of 33 GB" and, because completion is never observed, leaves
+ # Retry/Resume on the card. Fall back to the variant's own files in the
+ # snapshot dir, which stay attributable when the blob hashes do not.
+ variant_file_set_unknown = variant is not None and not expected_hashes
+ # Resolved at most once, and only if a reading gets far enough to need it.
+ metadata_files: "_Lazy[tuple[download_manifest.ExpectedFile, ...]]" = _Lazy(
+ lambda: tuple(expected_files_resolver(repo_id, hf_token))
+ if expected_files_resolver is not None
+ else ()
+ )
- readings: list[tuple[int, int, Optional[str], bool]] = []
+ readings: list[tuple[int, int, Optional[str], bool, Optional[bool]]] = []
+ # The enumeration suppresses OSError per root, so an unreadable cache root came back as
+ # "no dirs" -- indistinguishable from a wiped cache, and hydration retires the job on
+ # that. Collected so the empty answer below can say unknown instead of absent.
+ scan_errors: list = []
cache_dirs = (
preferred_repo_cache_dirs(
repo_type,
repo_id,
force_active = force_active,
active_root = active_root,
+ scan_errors = scan_errors,
)
if active_root is not None
- else preferred_repo_cache_dirs(repo_type, repo_id, force_active = force_active)
+ else preferred_repo_cache_dirs(
+ repo_type, repo_id, force_active = force_active, scan_errors = scan_errors
+ )
)
for entry in cache_dirs:
completed_bytes = 0
in_progress_bytes = 0
+ # A partial this reading could not attribute to any target. It is not evidence FOR this
+ # variant -- it may be a sibling quant's -- but with the hashes unresolved it is not
+ # evidence against it either, and the by-name scan cannot see it because a partial is
+ # not linked into a snapshot yet.
+ unattributable_partial = False
cache_path = hf_cache_scan.resolve_hf_cache_realpath(entry)
blobs_dir = entry / "blobs"
- if blobs_dir.is_dir():
+ try:
+ # os.stat, not Path.is_dir(): is_dir() swallows the OSError and answers False, so a
+ # Windows ACL or network-filesystem failure on the directory ITSELF read as "no
+ # blobs here" -- a MEASURED absence, which hydration retires the job on.
+ blobs_present = stat_module.S_ISDIR(os.stat(blobs_dir).st_mode)
+ except FileNotFoundError:
+ blobs_present = False
+ except OSError as exc:
+ scan_errors.append(exc)
+ blobs_present = False
+ if blobs_present:
try:
blob_entries = list(blobs_dir.iterdir())
- except OSError:
+ except OSError as exc:
+ # An unreadable blobs dir is not an empty one. Swallowing it produced a
+ # measured zero -- target_present false, cache_measured true -- and hydration
+ # retires a job whose cache was never actually read.
+ scan_errors.append(exc)
blob_entries = []
for f in blob_entries:
# Skip a blob that vanished mid-poll rather than zeroing the reading.
@@ -177,18 +513,92 @@ def compute_snapshot_progress(
if expected_hashes:
if blob_hash not in expected_hashes:
continue
- elif not count_finalized_unscoped:
+ elif not count_unscoped:
+ unattributable_partial = True
continue
in_progress_bytes += blob_bytes_present(f)
else:
if expected_hashes:
if f.name not in expected_hashes:
continue
- elif not count_finalized_unscoped:
+ elif not count_unscoped:
continue
completed_bytes += f.stat().st_size
- except OSError:
+ except OSError as exc:
+ # A blob we could not inspect is not a blob that is not there. Swallowing it
+ # produced a MEASURED absence, which hydration reads as "gone" and retires a
+ # persisted download whose target may be intact behind the error.
+ scan_errors.append(exc)
continue
+ snapshot_dirs: "_Lazy[list[Path]]" = _Lazy(
+ lambda entry = entry: _retained_snapshot_dirs(entry)
+ )
+ entry_manifest: "_Lazy[Optional[download_manifest.Manifest]]" = _Lazy(
+ lambda entry = entry: download_manifest.read_manifest(
+ repo_type,
+ repo_id,
+ variant,
+ hub_cache = entry.parent,
+ )
+ )
+ if variant_file_set_unknown:
+ # The best reading across every retained snapshot, for the same reason presence is
+ # established across all of them: the variant can live in an older revision while
+ # the newest holds a sibling, and reading only the newest reported 0 bytes for a
+ # complete cached quant.
+ on_disk = max(
+ (
+ _variant_bytes_on_disk(entry_manifest.get(), snap, variant_file_matcher)
+ for snap in snapshot_dirs.get()
+ ),
+ default = 0,
+ )
+ # Clamped, because the matcher behind the no-manifest half of that
+ # reading accepts every companion in the repo and so can overshoot.
+ # A bar reading "44 GB of 33 GB" is a worse answer than a pinned one.
+ if expected_total > 0:
+ on_disk = min(on_disk, expected_total)
+ completed_bytes = max(completed_bytes, on_disk)
+ # Does THIS target have anything here, as opposed to the repo dir existing at all?
+ # Sibling quants share one repo cache dir, so deleting a variant's files leaves the
+ # dir standing and the reading came back "zero bytes, cache_path names a directory"
+ # -- which hydration reads as resumable and adopts as a phantom, blocking a fresh
+ # download of that same variant until the idle grace expires. False only on positive
+ # evidence of absence: a named variant, a file set we could resolve, no manifest of
+ # its own and nothing counted. Anything less certain stays None.
+ target_present: Optional[bool] = None
+ if variant is not None and not variant_file_set_unknown:
+ # The MATERIALIZED file, not the blob tally. These counters come from the shared
+ # blobs/ dir: deleting a variant's snapshot symlink leaves its finalized blob
+ # behind, and a companion blob shared with a sibling keeps the count positive on its
+ # own -- so a quant that is gone read as present and hydration re-adopted the
+ # phantom. The by-name scan the unknown-hash branch already uses answers this
+ # properly; bytes only stand in when it cannot (nothing readable to look at), where
+ # in-progress bytes are still real evidence that this download is live.
+ scanned = _variant_present_in_any_snapshot(entry, variant_file_matcher)
+ if scanned is not None:
+ target_present = scanned or bool(in_progress_bytes)
+ else:
+ target_present = bool(completed_bytes or in_progress_bytes)
+ elif variant is not None:
+ # An unresolvable file set does not have to mean unknown. The byte reading above
+ # already walked the snapshot dir, whose entries are named per file, so it can
+ # answer the narrower question the hash filter could not: is a main shard of THIS
+ # quant here? Without this, a repo dir kept alive by a sibling read as "zero bytes,
+ # cache_path names a directory", which hydration adopts as a resumable phantom and
+ # which then blocks a fresh download of the deleted quant until the idle grace runs
+ # out -- the same trap as above, on the metadata-unavailable path.
+ # ...across EVERY snapshot the entry retains, not only the newest by mtime. A cache
+ # can hold several revisions, and the requested quant living in an older one while
+ # the newest holds a sibling read as absent -- and hydration retires a job whose
+ # target is still usable.
+ scanned = _variant_present_in_any_snapshot(entry, variant_file_matcher)
+ if scanned is not None:
+ # ...unless the shared blobs/ dir holds a partial nothing here can attribute.
+ # An idle or restarted download whose hashes were refused has its bytes in an
+ # .incomplete blob that is not linked into any snapshot yet, so the by-name scan
+ # answers a confident "absent" -- and hydration retires a job that is resumable.
+ target_present = None if (not scanned and unattributable_partial) else scanned
readings.append(
(
completed_bytes,
@@ -199,29 +609,73 @@ def compute_snapshot_progress(
repo_id = repo_id,
variant = variant,
entry = entry,
+ snapshot_dirs = snapshot_dirs,
+ entry_manifest = entry_manifest,
+ metadata_files = metadata_files,
expected_total = expected_total,
completed_bytes = completed_bytes,
in_progress_bytes = in_progress_bytes,
+ expected_hashes = expected_hashes,
),
+ target_present,
)
)
selected = max(
readings,
- key = lambda item: (item[0] + item[1], item[0]),
+ # complete_on_disk last-but-one: two remembered caches can clamp to the SAME byte total
+ # while only one has a manifest that verifies against disk, and root order then carried
+ # the unverified reading -- the response stayed capped at 99% and kept offering Retry.
+ key = lambda item: (item[0] + item[1], bool(item[3]), item[0]),
default = None,
)
if selected is None:
+ # Nothing measured AND a root that could not be listed: the cache may be entirely
+ # intact behind that error, so this is unknown, not gone.
+ if scan_errors:
+ return _empty_progress(expected_bytes, measured = False)
return empty
- completed_bytes, in_progress_bytes, cache_path, complete_on_disk = selected
+ completed_bytes, in_progress_bytes, cache_path, complete_on_disk, target_present = selected
+ # Presence is a property of the SET of caches, not of the one that happened to hold the most
+ # bytes. A sibling-only repo dir and a cache that still holds this variant's manifest both
+ # read as zero bytes, so root order alone could pick the False and retire a job whose target
+ # another scanned cache proves is there. A positive reading anywhere wins.
+ presence = [reading[4] for reading in readings]
+ if any(verdict is True for verdict in presence):
+ target_present = True
+ elif any(verdict is None for verdict in presence):
+ # And absence needs EVERY scanned cache to say so. One unknown reading -- a cache with
+ # no readable snapshot to identify the variant from, whose shared blobs dir may still
+ # hold an unattributable partial -- is not evidence the target is gone.
+ target_present = None
downloaded_bytes = completed_bytes + in_progress_bytes
+ # A reading taken while some root could not be listed is only ever a LOWER bound. The
+ # active root raising EACCES/EIO while a remembered cache still holds the repo dir (with a
+ # sibling quant in it) gives a non-null selection carrying target_present False and zero
+ # bytes -- and hydration reads that as "the variant was deleted" and retires the job,
+ # though the inaccessible root may hold every byte of it. Absence claims need a complete
+ # scan behind them, so downgrade them to unknown; a positive reading is unaffected,
+ # because bytes we did see are bytes that are there.
+ scan_incomplete = bool(scan_errors)
+ if scan_incomplete:
+ if not target_present:
+ target_present = None
# Subtract the companion baseline only while still counted in completed_bytes
# and the variant is not yet verified complete, else genuine progress reads as
- # 0-byte.
+ # 0-byte. A baseline that covers the whole expected total is never subtracted
+ # either: a variant that was already on disk when the job was claimed carries
+ # exactly that, and netting it out leaves "0 B of 0 B" -- nothing for the bar
+ # to draw and, to the frontend, a job to evict. complete_on_disk covered that
+ # only while completion could be verified, which is the one thing an
+ # unresolvable file set takes away.
effective_baseline_bytes = (
completed_baseline_bytes
- if not complete_on_disk and completed_baseline_bytes <= completed_bytes
+ if (
+ not complete_on_disk
+ and completed_baseline_bytes <= completed_bytes
+ and completed_baseline_bytes < expected_total
+ )
else 0
)
display_completed_bytes = max(0, completed_bytes - effective_baseline_bytes)
@@ -236,6 +690,8 @@ def compute_snapshot_progress(
"expected_bytes": 0,
"progress": 0,
"cache_path": cache_path,
+ "target_present": target_present,
+ "cache_measured": not scan_incomplete,
}
display_expected_total = max(0, expected_total - effective_baseline_bytes)
@@ -244,6 +700,9 @@ def compute_snapshot_progress(
**empty,
"expected_bytes": display_expected_total,
"cache_path": cache_path,
+ "target_present": target_present,
+ # Zero bytes read out of an incomplete scan is not evidence of zero bytes on disk.
+ "cache_measured": not scan_incomplete,
}
# Cap at 0.99 until the manifest-backed disk check verifies completion: on
@@ -266,6 +725,8 @@ def compute_snapshot_progress(
"expected_bytes": display_expected_total,
"progress": round(progress, 3),
"cache_path": cache_path,
+ "target_present": target_present,
+ "cache_measured": not scan_incomplete,
}
@@ -279,6 +740,8 @@ async def snapshot_progress_response(
registry,
metadata_resolver: SnapshotMetadataResolver,
variant: Optional[str] = None,
+ variant_file_matcher: Optional[VariantFileMatcher] = None,
+ expected_files_resolver: Optional[SnapshotExpectedFilesResolver] = None,
) -> dict:
"""Async wrapper: offloads the blocking cache walk and never raises."""
try:
@@ -292,6 +755,8 @@ async def snapshot_progress_response(
registry = registry,
metadata_resolver = metadata_resolver,
variant = variant,
+ variant_file_matcher = variant_file_matcher,
+ expected_files_resolver = expected_files_resolver,
)
except Exception as e:
logger.warning(
@@ -301,4 +766,4 @@ async def snapshot_progress_response(
type(e).__name__,
download_registry.scrub_secrets(str(e), hf_token = hf_token),
)
- return _empty_progress(expected_bytes)
+ return _empty_progress(expected_bytes, measured = False)
diff --git a/studio/backend/hub/tests/test_dataset_services.py b/studio/backend/hub/tests/test_dataset_services.py
index af33d14ba6a..38dd96d93a6 100644
--- a/studio/backend/hub/tests/test_dataset_services.py
+++ b/studio/backend/hub/tests/test_dataset_services.py
@@ -280,7 +280,7 @@ def _app_cache_entry(monkeypatch, hub_cache: Path, repo_id: str, commit_hash: st
roots = getattr(monkeypatch, "_dataset_hub_roots", [])
roots.append(hub_cache)
monkeypatch._dataset_hub_roots = roots
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: roots)
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: roots)
entry = dataset_processed_cache.prepare_app_processed_dataset_cache(
repo_id,
snapshot,
diff --git a/studio/backend/hub/tests/test_download_manifest_scoping.py b/studio/backend/hub/tests/test_download_manifest_scoping.py
index a7cc5a0bed8..7cbd137fdda 100644
--- a/studio/backend/hub/tests/test_download_manifest_scoping.py
+++ b/studio/backend/hub/tests/test_download_manifest_scoping.py
@@ -1,9 +1,14 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import errno
import json
+import os
+from pathlib import Path
from types import SimpleNamespace
+import pytest
+
from hub.utils import download_manifest, state_dir
@@ -12,6 +17,42 @@ def _write_manifest(path, payload):
path.write_text(json.dumps(payload), encoding = "utf-8")
+def _manifest_payload(
+ repo_id,
+ variant,
+ hub_cache,
+ *,
+ size = 4,
+):
+ return {
+ "version": 1,
+ "repo_type": "model",
+ "repo_id": repo_id,
+ "variant": variant,
+ "started_at": "2026-01-01T00:00:00+00:00",
+ "expected_files": [{"path": "model.gguf", "size": size}],
+ "transport": "http",
+ "hub_cache": hub_cache,
+ }
+
+
+def _redirected_hub_cache(tmp_path):
+ """A cache path whose resolved and unresolved spellings differ.
+
+ A POSIX symlink stands in for the Windows shapes that make ``resolve``
+ change a path: a directory junction, a OneDrive redirect, a mapped drive,
+ an 8.3 short name. Returns (as the caller spells it, what it resolves to).
+ """
+ target = tmp_path / "resolved" / "hub"
+ target.mkdir(parents = True)
+ link = tmp_path / "redirected"
+ try:
+ link.symlink_to(tmp_path / "resolved", target_is_directory = True)
+ except (NotImplementedError, OSError): # pragma: no cover - unprivileged Windows
+ pytest.skip("symlinks unavailable on this host")
+ return link / "hub", target
+
+
def test_purge_state_preserves_active_legacy_when_deleting_inactive_cache(monkeypatch, tmp_path):
"""A scoped delete of an inactive cache must not erase the unscoped legacy
state, which _legacy_state_applies attributes to the active cache."""
@@ -62,6 +103,656 @@ def test_purge_state_removes_legacy_owned_by_the_deleted_cache(monkeypatch, tmp_
assert not legacy.is_file() # owned by the deleted cache -> purged
+def test_scope_digest_is_shared_with_the_ownership_canonicalization(monkeypatch, tmp_path):
+ """cache_scope_name and _canonical_hub_cache must normalize identically.
+
+ They did not: the digest skipped ``resolve``, so a caller that reached
+ state_dir with its own spelling of a redirected cache filed state under one
+ digest while every reader that had gone through _canonical_hub_cache looked
+ under another. On Windows, where junctions, OneDrive redirects and 8.3 short
+ names make the two spellings diverge routinely, that is a finished download
+ whose manifest can never be found again.
+ """
+ spelled, resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+
+ assert spelled != resolved
+ assert state_dir.cache_scope_name(spelled) == state_dir.cache_scope_name(resolved)
+ assert state_dir.cache_scope_name(spelled) == state_dir._cache_scope_digest(
+ download_manifest._canonical_hub_cache(spelled)
+ )
+ assert state_dir.manifest_path(
+ "model", "Org/Model", hub_cache = spelled
+ ) == state_dir.manifest_path("model", "Org/Model", hub_cache = resolved)
+
+
+def test_manifest_under_the_pre_resolve_digest_is_still_found(monkeypatch, tmp_path):
+ """A digest change must not orphan state an earlier build already wrote.
+
+ State written when the digest hashed the unresolved spelling -- or when
+ ``resolve`` failed for a OneDrive placeholder and normalize_hub_cache
+ degraded to it -- sits under legacy_cache_scope_name. Readers probe it after
+ the canonical one, so the manifest survives the migration.
+ """
+ spelled, _resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(tmp_path / "other")),
+ )
+
+ legacy_scope = state_dir.legacy_cache_scope_name(spelled)
+ assert legacy_scope != state_dir.cache_scope_name(spelled)
+ orphan = state_dir.manifest_path(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ hub_cache = spelled,
+ cache_scope = legacy_scope,
+ )
+ _write_manifest(orphan, _manifest_payload("Org/Model", "Q4_K_M", str(spelled)))
+
+ manifest = download_manifest.read_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ hub_cache = spelled,
+ )
+
+ assert manifest is not None
+ assert manifest.expected_files[0].path == "model.gguf"
+
+
+def _legacy_scoped_variant_manifest(
+ tmp_path,
+ spelled,
+ variant = "Q4_K_M",
+):
+ """Plant a variant manifest under the pre-resolve digest, as an old build would."""
+ path = state_dir.manifest_path(
+ "model",
+ "Org/Model",
+ variant,
+ hub_cache = spelled,
+ cache_scope = state_dir.legacy_cache_scope_name(spelled),
+ )
+ assert path.parent.name != state_dir.cache_scope_name(spelled)
+ _write_manifest(path, _manifest_payload("Org/Model", variant, str(spelled)))
+ return path
+
+
+def test_every_enumerator_agrees_about_the_pre_resolve_digest(monkeypatch, tmp_path):
+ """One reader finding state that another cannot is worse than neither finding it.
+
+ Four code paths answer "what state does this repo have": the per-triple
+ read, the per-repo variant enumeration, the one-pass index the inventory
+ scan is built on, and the delete. They all derive their scope directories
+ from cache_scope_names, so a manifest under the pre-resolve digest is either
+ visible to all of them or to none. A reader that saw it while the delete did
+ not would resurrect a purged variant on the next scan, and an index that
+ missed it while the per-variant endpoint saw it would have the list view and
+ the detail view disagree about the same quant.
+ """
+ spelled, _resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(tmp_path / "other")),
+ )
+ orphan = _legacy_scoped_variant_manifest(tmp_path, spelled)
+
+ assert (
+ download_manifest.read_manifest("model", "Org/Model", "Q4_K_M", hub_cache = spelled)
+ is not None
+ )
+ assert [
+ variant
+ for variant, _path in download_manifest.iter_variant_manifests(
+ "model", "Org/Model", hub_cache = spelled
+ )
+ ] == ["Q4_K_M"]
+ index = download_manifest.build_variant_state_index(
+ [("model", "Org/Model", spelled)],
+ active_hub_cache = spelled,
+ )
+ state = index.for_repo("model", "Org/Model", hub_cache = spelled)
+ assert state.manifest_for("Q4_K_M") is not None
+ assert download_manifest.purge_all_state_for_repo("model", "Org/Model", hub_cache = spelled)
+ assert not orphan.is_file()
+
+
+def test_pre_resolve_digest_cancel_marker_is_cleared_by_a_new_attempt(monkeypatch, tmp_path):
+ """A marker the read side can find has to be one the clear side can remove.
+
+ has_cancel_marker suppresses a completed download, so a marker discoverable
+ under the pre-resolve digest but not clearable there would pin a finished
+ variant to partial for good.
+ """
+ spelled, _resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(tmp_path / "other")),
+ )
+ marker = state_dir.marker_path(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ hub_cache = spelled,
+ cache_scope = state_dir.legacy_cache_scope_name(spelled),
+ )
+ _write_manifest(
+ marker,
+ {
+ "version": 2,
+ "repo_type": "model",
+ "repo_id": "Org/Model",
+ "variant": "Q4_K_M",
+ "transport": "http",
+ "cancelled_at": "2026-01-01T00:00:00+00:00",
+ "hub_cache": str(spelled),
+ },
+ )
+
+ assert download_manifest.has_cancel_marker("model", "Org/Model", "Q4_K_M", hub_cache = spelled)
+ download_manifest.clear_cancel_marker("model", "Org/Model", "Q4_K_M", hub_cache = spelled)
+ assert not marker.is_file()
+ assert not download_manifest.has_cancel_marker(
+ "model", "Org/Model", "Q4_K_M", hub_cache = spelled
+ )
+
+
+def test_repo_delete_clears_variant_state_under_a_redirected_cache(monkeypatch, tmp_path):
+ """purge_all_state_for_repo reaches state_dir with the caller's own spelling.
+
+ The delete routes pass the scanned cache root straight through, so before
+ the digest shared one canonicalization this globbed a scope directory that
+ never existed and every variant manifest survived the delete.
+ """
+ spelled, _resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(tmp_path / "other")),
+ )
+
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model.gguf", size = 4)],
+ "http",
+ hub_cache = spelled,
+ )
+ written = state_dir.manifest_path("model", "Org/Model", "Q4_K_M", hub_cache = spelled)
+ assert written.is_file()
+
+ assert download_manifest.purge_all_state_for_repo("model", "Org/Model", hub_cache = spelled)
+ assert not written.is_file()
+
+
+def test_windows_shaped_copy_cache_scope_survives_a_restart(monkeypatch, tmp_path):
+ """Restart-after-completion on the Windows copy layout still reads its manifest.
+
+ No symlinks anywhere (blobs are copied into the snapshot dir, as HF does
+ when the filesystem denies symlink creation), a case-skewed spelling of the
+ cache on the second run, and the state root rebuilt from scratch: the
+ manifest written by the first run has to be the one the second run finds.
+ """
+ hub_cache = tmp_path / "Hub"
+ snapshot = hub_cache / "models--Org--Model" / "snapshots" / "rev0"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model.gguf").write_bytes(b"x" * 16) # a copy, not a symlink
+ assert not (snapshot / "model.gguf").is_symlink()
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(hub_cache)),
+ )
+
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model.gguf", size = 16)],
+ "http",
+ hub_cache = hub_cache,
+ )
+
+ # Second run: the same directory reached as the parent of a scanned entry.
+ entry = next(path for path in hub_cache.iterdir() if path.name.startswith("models--"))
+ manifest = download_manifest.read_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ hub_cache = entry.parent,
+ )
+ assert manifest is not None
+ assert download_manifest.verify_against_disk(manifest, snapshot).ok
+
+
+def test_normalize_hub_cache_degrades_when_resolve_refuses(monkeypatch, tmp_path):
+ """A path Windows can open but not resolve keeps a scope instead of losing one."""
+
+ def _refuse(self, strict = False):
+ raise OSError(5, "Access is denied")
+
+ monkeypatch.setattr(Path, "resolve", _refuse)
+ expected = os.path.normcase(str(tmp_path / "hub"))
+ assert state_dir.normalize_hub_cache(tmp_path / "hub") == expected
+
+
+def test_degraded_normalization_matches_its_own_recovery_probe(monkeypatch, tmp_path):
+ """The two halves of the resolve-failed pair have to agree on one spelling.
+
+ normalize_hub_cache degrades to the expanded spelling when ``resolve``
+ refuses, and legacy_cache_scope_name is what recovers state written in that
+ state. If the degraded branch skipped expanduser while the probe applied it,
+ a "~"-spelled cache would file state under a digest no reader could rebuild
+ -- and its recorded ownership is not absolute, so nothing else could
+ attribute it either.
+ """
+ spellings = ["~/hf-hub", str(tmp_path / "hub") + "/", str(tmp_path / "hub" / "." / "x")]
+
+ def _refuse(self, strict = False):
+ raise OSError(5, "Access is denied")
+
+ monkeypatch.setattr(Path, "resolve", _refuse)
+ for spelling in spellings:
+ assert state_dir.cache_scope_name(spelling) == state_dir.legacy_cache_scope_name(spelling)
+
+
+def test_expanduser_failure_does_not_escape_a_plain_read(monkeypatch, tmp_path):
+ """A homeless "~" must not turn read_manifest into a RuntimeError.
+
+ legacy_cache_scope_name is fed the caller's raw spelling now, so it sees
+ values the canonical path had already expanded away.
+ """
+
+ def _refuse(self):
+ raise RuntimeError("Could not determine home directory")
+
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(Path, "expanduser", _refuse)
+
+ assert state_dir.cache_scope_names("~/hf-hub")
+ assert download_manifest.read_manifest("model", "Org/Model", hub_cache = "~/hf-hub") is None
+
+
+def _legacy_scoped_manifest(tmp_path, spelled, resolved, repo_id, variant):
+ """Plant a manifest under the PRE-resolve digest of ``spelled``.
+
+ That is where state lands when ``resolve`` is unavailable at write time (a
+ OneDrive placeholder, a locked junction), and where an 8.3 path's state
+ lands until the directory it names exists. The reader recovers it; the
+ point of these tests is that the delete and the index do too.
+ """
+ legacy = state_dir.manifest_path(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = str(resolved),
+ cache_scope = state_dir.legacy_cache_scope_name(str(spelled)),
+ )
+ _write_manifest(legacy, _manifest_payload(repo_id, variant, str(resolved)))
+ assert state_dir.legacy_cache_scope_name(str(spelled)) != state_dir.cache_scope_name(
+ str(spelled)
+ ), "fixture is not exercising a split digest"
+ return legacy
+
+
+def test_repo_delete_clears_legacy_scope_when_handed_a_RESOLVED_root(monkeypatch, tmp_path):
+ """The delete reaches purge_all_state_for_repo with an ALREADY-resolved root.
+
+ Every production caller does: hub/services/models/deletion.py and
+ hub/services/datasets/cache_inventory.py all pass
+ resolve_delete_target_root(...), whose every branch calls .resolve(). So the
+ raw-spelling probe inside cache_scope_names finds nothing here, while the
+ read path -- fed the raw configured setting -- still has it. Left that way,
+ a purged variant survives under the legacy digest and the next read brings
+ it back, which is exactly the resurrection the scope fan-out exists to stop.
+ """
+ spelled, resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(spelled)),
+ )
+ legacy = _legacy_scoped_manifest(tmp_path, spelled, resolved, "Org/Model", "Q4_K_M")
+
+ # The resolved spelling, as resolve_delete_target_root would hand it over.
+ removed = download_manifest.purge_all_state_for_repo(
+ "model", "Org/Model", hub_cache = str(resolved)
+ )
+
+ assert removed > 0
+ assert not legacy.is_file()
+ # ...and the read path agrees it is gone, rather than resurrecting it.
+ assert download_manifest.read_manifest("model", "Org/Model", "Q4_K_M") is None
+
+
+def test_variant_delete_clears_legacy_scope_when_handed_a_RESOLVED_root(monkeypatch, tmp_path):
+ """Same asymmetry, one variant at a time.
+
+ The single-variant delete route reaches purge_state with the root
+ resolve_delete_target_root already resolved, so the raw spelling reproduced the canonical
+ digest and only that scope was probed. The read path still probed both, so the exact
+ variant the user deleted came back as partial (or cancelled) on the next poll, its files
+ gone but its state file sitting under the pre-resolve digest.
+ """
+ spelled, resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(spelled)),
+ )
+ legacy = _legacy_scoped_manifest(tmp_path, spelled, resolved, "Org/Model", "Q4_K_M")
+
+ removed = download_manifest.purge_state("model", "Org/Model", "Q4_K_M", hub_cache = str(resolved))
+
+ assert removed is True
+ assert not legacy.is_file()
+ assert download_manifest.read_manifest("model", "Org/Model", "Q4_K_M") is None
+
+
+def test_variant_index_sees_legacy_scope_when_handed_a_RESOLVED_root(monkeypatch, tmp_path):
+ """Same asymmetry on the inventory side.
+
+ cache_inventory feeds build_variant_state_index a directory derived from
+ huggingface_hub.scan_cache_dir, which resolves. Without the configured
+ spelling the cached-model views would report no state for a variant the
+ progress endpoint can see.
+ """
+ spelled, resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(spelled)),
+ )
+ _legacy_scoped_manifest(tmp_path, spelled, resolved, "Org/Model", "Q4_K_M")
+
+ index = download_manifest.build_variant_state_index(
+ [("model", "Org/Model", str(resolved))],
+ active_hub_cache = str(resolved),
+ )
+ state = index.for_repo("model", "Org/Model", hub_cache = str(resolved))
+
+ assert state.manifest_for("Q4_K_M") is not None
+
+
+def test_the_configured_spelling_is_only_borrowed_for_the_SAME_directory(monkeypatch, tmp_path):
+ """The guard on the fan-out, which matters more than the fan-out.
+
+ Borrowing the configured cache's spellings unconditionally would make a
+ delete aimed at an INACTIVE cache sweep the active cache's state for the
+ same repo -- silently losing state for a cache the user never touched,
+ which is a far worse failure than the resurrection above.
+ """
+ spelled, resolved = _redirected_hub_cache(tmp_path)
+ other = tmp_path / "other" / "hub"
+ other.mkdir(parents = True)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(spelled)),
+ )
+ active_legacy = _legacy_scoped_manifest(tmp_path, spelled, resolved, "Org/Model", "Q4_K_M")
+ victim = state_dir.manifest_path("model", "Org/Model", "Q8_0", hub_cache = str(other))
+ _write_manifest(victim, _manifest_payload("Org/Model", "Q8_0", str(other)))
+
+ # Deleting the repo out of the OTHER cache must not touch the active one.
+ download_manifest.purge_all_state_for_repo("model", "Org/Model", hub_cache = str(other))
+
+ assert not victim.is_file()
+ assert active_legacy.is_file()
+
+
+def test_disagreeing_manifests_across_caches_are_refused(monkeypatch, tmp_path):
+ """snapshot_progress picks its READING by bytes across every preferred cache dir, but the
+ expected-file hashes come from one manifest lookup. Handing it the first cache's older
+ revision filters out every blob of a later cache that holds the complete variant, so a
+ finished download reports 0 or partial -- the exact failure this fallback exists to prevent,
+ just sourced from the wrong cache. Two caches that disagree therefore yield no manifest, and
+ the name-based fallback (which stays attributable per entry) takes over.
+ """
+ from hub.services.models import downloads
+ from hub.utils import download_manifest
+
+ old = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ variant = "Q4_K_M",
+ started_at = "2026-01-01T00:00:00Z",
+ expected_files = (download_manifest.ExpectedFile("old.gguf", 10, "aaa"),),
+ )
+ new = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ variant = "Q4_K_M",
+ started_at = "2026-02-01T00:00:00Z",
+ expected_files = (download_manifest.ExpectedFile("new.gguf", 20, "bbb"),),
+ )
+ first, second = tmp_path / "a" / "repo", tmp_path / "b" / "repo"
+ served = {first.parent: old, second.parent: new}
+
+ monkeypatch.setattr(downloads, "preferred_repo_cache_dirs", lambda *a, **k: [first, second])
+ monkeypatch.setattr(download_manifest, "_canonical_hub_cache", lambda *a, **k: None)
+ monkeypatch.setattr(
+ download_manifest,
+ "read_manifest",
+ lambda repo_type, repo_id, variant = None, *, hub_cache = None: (
+ served.get(Path(hub_cache)) if hub_cache is not None else None
+ ),
+ )
+
+ assert downloads._variant_manifest_in_any_cache("unsloth/Model-GGUF", "Q4_K_M") is None
+
+ # Agreement is still answered: the point is the ambiguity, not the multiplicity.
+ served[second.parent] = old
+ assert downloads._variant_manifest_in_any_cache("unsloth/Model-GGUF", "Q4_K_M") is old
+
+
+def test_a_stale_active_manifest_is_compared_rather_than_returned(monkeypatch, tmp_path):
+ """The configured cache's repo dir can be gone while its scoped state still holds an old
+ manifest, and idle progress keeps scanning the remembered caches. Returning the active one
+ unexamined applies a stale revision's hashes to a remembered cache that has the complete
+ variant and filters every blob of it out -- the same wrong answer, one cache earlier."""
+ from hub.services.models import downloads
+ from hub.utils import download_manifest
+
+ stale = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ variant = "Q4_K_M",
+ started_at = "2026-01-01T00:00:00Z",
+ expected_files = (download_manifest.ExpectedFile("old.gguf", 10, "aaa"),),
+ )
+ current = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ variant = "Q4_K_M",
+ started_at = "2026-02-01T00:00:00Z",
+ expected_files = (download_manifest.ExpectedFile("new.gguf", 20, "bbb"),),
+ )
+ remembered = tmp_path / "remembered" / "repo"
+
+ monkeypatch.setattr(downloads, "preferred_repo_cache_dirs", lambda *a, **k: [remembered])
+ monkeypatch.setattr(download_manifest, "_canonical_hub_cache", lambda *a, **k: None)
+ monkeypatch.setattr(
+ download_manifest,
+ "read_manifest",
+ # hub_cache omitted is the ACTIVE cache lookup.
+ lambda repo_type, repo_id, variant = None, *, hub_cache = None: (
+ stale if hub_cache is None else current
+ ),
+ )
+
+ assert downloads._variant_manifest_in_any_cache("unsloth/Model-GGUF", "Q4_K_M") is None
+
+
+def test_variant_enumeration_sees_legacy_scope_when_handed_a_RESOLVED_root(monkeypatch, tmp_path):
+ """The third caller with the same asymmetry, and the one that was left out.
+
+ A variant request carrying ``local_path`` is resolved by ``_repo_cache_dir_for_request``
+ before the enumerator ever sees the cache root, so ``cache_scope_names`` -- which recovers
+ the pre-resolve digest only from an unresolved path -- returned the canonical digest alone.
+ On a cache reached through a symlink or junction the offline variant listing then lost the
+ partial download entirely, along with its resume control, while the progress endpoint could
+ still see it.
+ """
+ spelled, resolved = _redirected_hub_cache(tmp_path)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(spelled)),
+ )
+ _legacy_scoped_manifest(tmp_path, spelled, resolved, "Org/Model", "Q4_K_M")
+
+ listed = dict(
+ download_manifest.iter_variant_manifests("model", "Org/Model", hub_cache = str(resolved))
+ )
+
+ assert "Q4_K_M" in listed, (
+ "the resolved spelling lost the legacy scope, so an offline listing cannot see the "
+ "partial download it is meant to offer a resume for"
+ )
+
+
+def test_a_scanned_cache_with_no_manifest_refuses_the_others(monkeypatch, tmp_path):
+ """A cache that contributes nothing is not a cache that agrees.
+
+ Manifests get deleted, and older builds never wrote one, so a cache holding the COMPLETE
+ snapshot can have no manifest at all. Returning another cache's manifest then applies its
+ hashes to that snapshot's blobs -- filtering every one of them out -- and, worse, disables
+ the per-entry name-based fallback that would still have counted them. The finished variant
+ reports zero.
+ """
+ from pathlib import Path
+
+ from hub.services.models import downloads
+ from hub.utils import download_manifest
+
+ only = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ variant = "Q4_K_M",
+ started_at = "2026-01-01T00:00:00Z",
+ expected_files = (download_manifest.ExpectedFile("old.gguf", 10, "aaa"),),
+ )
+ first, second = tmp_path / "a" / "repo", tmp_path / "b" / "repo"
+ served: dict = {first.parent: only, second.parent: None}
+
+ monkeypatch.setattr(downloads, "preferred_repo_cache_dirs", lambda *a, **k: [first, second])
+ monkeypatch.setattr(download_manifest, "_canonical_hub_cache", lambda *a, **k: None)
+ monkeypatch.setattr(
+ download_manifest,
+ "read_manifest",
+ lambda repo_type, repo_id, variant = None, *, hub_cache = None: (
+ served.get(Path(hub_cache)) if hub_cache is not None else None
+ ),
+ )
+
+ assert downloads._variant_manifest_in_any_cache("unsloth/Model-GGUF", "Q4_K_M") is None
+
+ # ...and once that cache has its own agreeing manifest, the answer comes back.
+ served[second.parent] = only
+ assert downloads._variant_manifest_in_any_cache("unsloth/Model-GGUF", "Q4_K_M") is only
+
+
+def test_the_active_cache_must_have_a_manifest_when_it_is_scanned(monkeypatch, tmp_path):
+ """Same rule for the active cache: snapshot_progress scans it like any other."""
+ from pathlib import Path
+
+ from hub.services.models import downloads
+ from hub.utils import download_manifest
+
+ other = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ variant = "Q4_K_M",
+ started_at = "2026-01-01T00:00:00Z",
+ expected_files = (download_manifest.ExpectedFile("old.gguf", 10, "aaa"),),
+ )
+ active_repo, remembered = tmp_path / "active" / "repo", tmp_path / "b" / "repo"
+
+ monkeypatch.setattr(
+ downloads, "preferred_repo_cache_dirs", lambda *a, **k: [active_repo, remembered]
+ )
+ monkeypatch.setattr(
+ download_manifest,
+ "_canonical_hub_cache",
+ lambda path = None: str(active_repo.parent)
+ if path in (None, active_repo.parent)
+ else str(path),
+ )
+ monkeypatch.setattr(
+ download_manifest,
+ "read_manifest",
+ # The active cache (hub_cache=None) has none; the remembered one does.
+ lambda repo_type, repo_id, variant = None, *, hub_cache = None: (
+ None if hub_cache is None else other
+ ),
+ )
+
+ assert downloads._variant_manifest_in_any_cache("unsloth/Model-GGUF", "Q4_K_M") is None
+
+
+def test_an_unreadable_cache_root_is_unknown_rather_than_absent(monkeypatch, tmp_path):
+ """A root that cannot be listed is not evidence that the cache was wiped.
+
+ ``iter_repo_cache_dirs`` and ``iter_active_repo_cache_dirs`` swallow OSError per root, so
+ an EACCES or EIO came back as "no cache dirs" -- and the all-zero reading that produces
+ carried ``cache_path: null``, which hydration reads as gone and removes a persisted job
+ whose partial cache is sitting on the disk behind that error. These errors never reached
+ the exception fallback that already knew the difference, because nothing raised."""
+ from hub.services import snapshot_progress
+ from hub.utils import hf_cache_state
+
+ unreadable = tmp_path / "hub"
+ unreadable.mkdir()
+
+ def _explode(self):
+ raise PermissionError(13, "Permission denied")
+
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda scan_errors = None: [unreadable])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_root", lambda root = None, **kw: None)
+ monkeypatch.setattr(type(unreadable), "iterdir", _explode)
+
+ # The enumeration reports the skip rather than only swallowing it...
+ errors: list = []
+ assert (
+ hf_cache_state.preferred_repo_cache_dirs("model", "unsloth/Model-GGUF", scan_errors = errors)
+ == []
+ )
+ assert errors and isinstance(errors[0], OSError)
+
+ # ...and the reading built on it says unknown by omitting cache_path entirely.
+ class _Registry:
+ def get_job(self, key):
+ return SimpleNamespace(state = "idle")
+
+ reading = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ job_key = "model:unsloth/Model-GGUF",
+ expected_bytes = 33_000_000_000,
+ hf_token = None,
+ registry = _Registry(),
+ metadata_resolver = lambda *a, **k: (33_000_000_000, frozenset()),
+ )
+ assert "cache_path" not in reading
+ # And it survives DownloadProgressResponse, which defaults cache_path to None and would
+ # otherwise reinstate the omission as an explicit "absent" before the frontend saw it.
+ assert reading["cache_measured"] is False
+ from hub.schemas.downloads import DownloadProgressResponse
+
+ # DECLARED on the response model, or FastAPI drops it before the frontend sees it: these
+ # readings are serialized through DownloadProgressResponse, whose cache_path defaults to
+ # None, so the omission alone was reinstated as an explicit "absent" on the wire.
+ assert "cache_measured" in DownloadProgressResponse.__annotations__
+ assert reading["downloaded_bytes"] == 0
+
+
def test_a_scope_whose_payload_is_lost_reads_back_as_a_digest(monkeypatch, tmp_path):
"""A scope is unspellable in a filename, so it is stored hashed. Lose the payload
and the reader falls back to that filename, handing back the digest instead of
@@ -102,3 +793,90 @@ def test_a_scope_whose_payload_is_lost_reads_back_as_a_digest(monkeypatch, tmp_p
# A real quant label is never mistaken for one.
for quant in ("Q4_K_M", "UD-Q4_K_XL", "sha256-short"):
assert not state_dir.variant_is_hashed_fragment(quant)
+
+
+def test_a_variant_with_nothing_of_its_own_says_so(monkeypatch, tmp_path):
+ """Sibling quants share one repo cache directory, so "the directory exists" is the wrong
+ granularity for a variant. With Q4_K_M's files deleted and Q8_0 keeping the dir alive, the
+ reading was zero bytes with a non-null cache_path -- which hydration adopts as resumable,
+ leaving a phantom card that blocks a fresh download of that same variant."""
+ from hub.services import snapshot_progress
+
+ entry = tmp_path / "hub" / "models--unsloth--Model-GGUF"
+ (entry / "blobs").mkdir(parents = True)
+ (entry / "blobs" / "sibling").write_bytes(b"x" * 32) # Q8_0's, not ours
+
+ monkeypatch.setattr(snapshot_progress, "preferred_repo_cache_dirs", lambda *a, **k: [entry])
+
+ class _Registry:
+ def get_job(self, key):
+ return SimpleNamespace(state = "idle")
+
+ def _reading(variant, expected_hashes):
+ return snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "unsloth/Model-GGUF",
+ job_key = "model:unsloth/Model-GGUF",
+ expected_bytes = 33_000_000_000,
+ hf_token = None,
+ registry = _Registry(),
+ metadata_resolver = lambda *a, **k: (33_000_000_000, expected_hashes),
+ variant = variant,
+ )
+
+ ours = _reading("Q4_K_M", frozenset({"ours"}))
+ assert ours["downloaded_bytes"] == 0
+ assert ours["cache_path"] is not None, "the sibling keeps the directory alive"
+ assert ours["target_present"] is False
+ # Through the response model, or FastAPI drops the field and the frontend never sees it.
+ from hub.schemas.downloads import DownloadProgressResponse
+
+ # Declared on the response model too, else FastAPI drops it on the way out.
+ assert "target_present" in DownloadProgressResponse.__annotations__
+
+ # Unresolvable file set: nothing was established, so nothing is claimed either.
+ unknown = _reading("Q4_K_M", frozenset())
+ assert unknown["target_present"] is None
+
+ # And a whole-repo job owns the directory, so the repo-level answer already covers it.
+ assert _reading(None, frozenset())["target_present"] is None
+
+
+def test_a_root_that_cannot_even_be_stat_ed_is_unknown(monkeypatch, tmp_path):
+ """The failure can happen one step earlier than the listing.
+
+ ``hf_cache_root`` calls ``_safe_is_dir``, which swallows the OSError from probing a
+ restricted configured cache and answers None -- so an inaccessible active root produced a
+ measured "no cache dir" answer with an empty scan_errors, and hydration retired the job as
+ deleted. Statting is part of the scan.
+
+ Driven through os.stat rather than Path.is_dir, because is_dir() suppresses the failure
+ itself: it swallows several errnos on 3.13 and, as of 3.14, every OSError there is. A
+ handler wrapped around it can never run."""
+ import os as _os
+
+ from hub.utils import hf_cache_state
+
+ root = tmp_path / "hub"
+ root.mkdir()
+ real_stat = _os.stat
+
+ def _explode(path, *args, **kwargs):
+ # ELOOP, which is one of the errnos Path.is_dir() answers False for rather than raising.
+ if str(path) == str(root):
+ raise OSError(errno.ELOOP, "Too many levels of symbolic links")
+ return real_stat(path, *args, **kwargs)
+
+ monkeypatch.setattr(_os, "stat", _explode)
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda scan_errors = None: [])
+
+ errors: list = []
+ assert (
+ hf_cache_state.preferred_repo_cache_dirs(
+ "model", "unsloth/Model-GGUF", active_root = root, scan_errors = errors
+ )
+ == []
+ )
+ assert errors and isinstance(
+ errors[0], OSError
+ ), "a root we could not stat is not evidence that the cache was deleted"
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 0050333f37a..3db699f4a70 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -2,6 +2,8 @@
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import asyncio
+import errno
+import time
import json
import os
import sys
@@ -2703,7 +2705,7 @@ def test_purge_repo_cache_dirs_skips_top_level_symlink(monkeypatch, tmp_path):
target.mkdir()
link = root / "models--Org--Repo"
link.symlink_to(target, target_is_directory = True)
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [root])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda scan_errors = None: [root])
removed = hf_cache_state.purge_repo_cache_dirs("model", "Org/Repo")
@@ -2754,14 +2756,20 @@ def test_gguf_download_progress_fallback_logs_warning(monkeypatch):
)
)
+ # cache_path is ABSENT, not null. Null means "no cache dir for this repo exists", which
+ # hydration acts on by retiring the persisted job; a scan that threw is not evidence of
+ # that, and dropping a job whose partial cache is still on disk costs the user the resume.
+ # cache_measured carries the same distinction through DownloadProgressResponse, which
+ # defaults cache_path to None and would otherwise turn the omission back into an "absent".
assert result == {
"downloaded_bytes": 0,
"completed_bytes": 0,
"complete_on_disk": False,
"expected_bytes": 0,
"progress": 0,
- "cache_path": None,
+ "cache_measured": False,
}
+ assert "cache_path" not in result
assert logger.warnings
args, kwargs = logger.warnings[0]
assert args[:4] == (
@@ -3353,2270 +3361,3550 @@ def test_gguf_progress_unknown_hashes_no_backward_dip_when_variant_finalizes(mon
assert result["progress"] == 0 # no ~0.78 backward dip
-def test_hf_cache_model_file_probe_is_bounded(monkeypatch, tmp_path):
- snapshot = tmp_path / "snapshot"
- snapshot.mkdir()
- first = tmp_path / "README.md"
- second = tmp_path / "notes.txt"
- model = tmp_path / "model.safetensors"
- first.write_text("readme", encoding = "utf-8")
- second.write_text("notes", encoding = "utf-8")
- model.write_bytes(b"weights")
- entries = [first, second, model]
-
- monkeypatch.setattr(model_common.Path, "rglob", lambda _self, _pattern: iter(entries))
- monkeypatch.setattr(model_common, "_HF_CACHE_MODEL_FILE_PROBE_LIMIT", 2)
-
- bounded = model_common._iter_hf_cache_model_files(snapshot)
+def _unresolvable_variant_metadata(
+ monkeypatch,
+ entry,
+ *,
+ state = "running",
+):
+ """A repo whose model_info is failing: no requirement, no blob hashes.
- assert bounded == [first, second]
+ Reproduces the negatively-cached lookup -- a 401 on a gated repo whose token
+ was removed, or an offline poll -- that leaves the expected file set empty
+ for the whole TTL after a single failure.
+ """
- monkeypatch.setattr(model_common, "_HF_CACHE_MODEL_FILE_PROBE_LIMIT", 3)
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
- unbounded = model_common._iter_hf_cache_model_files(snapshot)
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: None,
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_args, **_kwargs: frozenset(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = state)),
+ )
- assert unbounded == [first, second, model]
+def test_gguf_progress_unknown_hashes_reports_the_variant_files_on_disk(monkeypatch, tmp_path):
+ """A finished variant must not read as "0 B of 33 GB" when metadata flakes.
-def test_download_state_lookup_is_repo_case_insensitive(monkeypatch, tmp_path):
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+ model_info failing is negatively cached, so a 401 that lands after the last
+ byte keeps the expected hash set empty for the whole TTL. Every blob was
+ then filtered out of the count and the reading collapsed to zero against the
+ caller's catalog hint, which is the stale "downloaded 0 B" card. The
+ variant's own snapshot files are still attributable by name, so they are
+ what the reading falls back to -- the sibling quant beside them is not.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (snap / "mmproj-F16.gguf").write_bytes(b"y" * 30)
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900) # sibling quant
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ (blobs / "siblinghash").write_bytes(b"z" * 900)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry)
- assert download_manifest.write_manifest(
- "model",
- "Owner/Repo",
- "Q4_K_M",
- [download_manifest.ExpectedFile(path = "config.json", size = 12)],
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
)
- assert download_manifest.write_cancel_marker("model", "Owner/Repo", "q4_k_m", "http")
- manifest = download_manifest.read_manifest("model", "owner/repo", "q4_k_m")
+ assert result["completed_bytes"] == 130 # main quant + shared companion
+ assert result["downloaded_bytes"] == 130
+ assert result["progress"] > 0 # not the "0 B of 130" card
- assert manifest is not None
- assert manifest.repo_id == "Owner/Repo"
- assert manifest.expected_files[0].path == "config.json"
- assert download_manifest.has_cancel_marker("model", "owner/repo", "Q4_K_M")
- assert (
- download_manifest.read_cancel_marker_transport(
- "model",
- "owner/repo",
- "Q4_K_M",
- )
- == "http"
- )
- assert [
- variant
- for variant, _path in download_manifest.iter_variant_markers(
- "model",
- "owner/repo",
- )
- ] == ["q4_k_m"]
- assert download_manifest.purge_all_state_for_repo("model", "owner/repo") == 1
- assert download_manifest.read_manifest("model", "owner/repo", "Q4_K_M") is None
+def test_gguf_progress_unknown_hashes_keeps_a_total_under_a_full_baseline(monkeypatch, tmp_path):
+ """A variant already on disk at claim time must not net out to "0 B of 0 B".
-def test_hf_cache_scan_fallback_row_uses_local_model_info_alias(monkeypatch, tmp_path):
- cache_dir = tmp_path / "hub"
- repo_dir = cache_dir / "models--Org--Broken"
- blobs_dir = repo_dir / "blobs"
- blobs_dir.mkdir(parents = True)
- (blobs_dir / "blob").write_bytes(b"content")
- monkeypatch.setattr(local_inventory, "_classify_local_path", lambda *_args, **_kwargs: [])
- monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "is_snapshot_partial",
- lambda *_args, **_kwargs: False,
- )
+ Its completed_baseline_bytes covers the whole variant, and the subtraction
+ was previously held off by complete_on_disk -- which is exactly what an
+ unresolvable file set takes away. Without the guard the fallback reading
+ cancels against the baseline and the response carries no total at all, so
+ the bar has nothing to draw and the frontend reads the job as evictable.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ snap.mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 130)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry)
monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "is_gguf_repo_partial",
- lambda *_args, **_kwargs: False,
+ downloads,
+ "_registry",
+ SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ get_job_metadata = lambda _key: SimpleNamespace(completed_baseline_bytes = 130),
+ ),
)
- monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "resolve_hf_cache_realpath",
- lambda *_args, **_kwargs: None,
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
)
- rows = local_inventory._scan_hf_cache(cache_dir)
+ assert result["expected_bytes"] == 130
+ assert result["downloaded_bytes"] == 130
- assert len(rows) == 1
- assert rows[0].model_id == "Org/Broken"
- assert rows[0].source == "hf_cache"
- assert rows[0].model_format == "unknown"
+def test_gguf_progress_unknown_hashes_prefers_the_manifest_file_set(monkeypatch, tmp_path):
+ """With a manifest but no hashes in it, its declared paths scope the reading.
-def test_hf_cache_scan_uses_gguf_partial_row_for_variant_state(monkeypatch, tmp_path):
+ The metadata-fallback manifest the worker writes from the finished snapshot
+ carries paths and sizes but no sha256, so the hash filter still resolves to
+ nothing. Its file list is exact, so it is used ahead of matching by name.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ snap.mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900)
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- cache_dir = tmp_path / "hub"
- repo_dir = cache_dir / "models--Org--PartialGguf"
- blobs_dir = repo_dir / "blobs"
- blobs_dir.mkdir(parents = True)
- (blobs_dir / "partial").write_bytes(b"content")
assert download_manifest.write_manifest(
"model",
- "Org/PartialGguf",
- "Q4_K_M",
- [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 8192)],
- "http",
- hub_cache = cache_dir,
- )
- assert download_manifest.write_cancel_marker(
- "model",
- "Org/PartialGguf",
+ "Org/Model-GGUF",
"Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100)],
"http",
- hub_cache = cache_dir,
- )
- monkeypatch.setattr(local_inventory, "_classify_local_path", lambda *_args, **_kwargs: [])
- monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "is_snapshot_partial",
- lambda *_args, **_kwargs: False,
- )
- monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "is_gguf_repo_partial",
- lambda *_args, **_kwargs: True,
- )
- monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "resolve_hf_cache_realpath",
- lambda *_args, **_kwargs: None,
+ hub_cache = entry.parent,
)
+ _unresolvable_variant_metadata(monkeypatch, entry)
- rows = local_inventory._scan_hf_cache(cache_dir)
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 0,
+ )
+ )
- assert len(rows) == 1
- assert rows[0].model_id == "Org/PartialGguf"
- assert rows[0].source == "hf_cache"
- assert rows[0].model_format == "gguf"
- assert rows[0].partial is True
- assert rows[0].size_bytes == 8192
- assert rows[0].capabilities.requires_variant is True
+ assert result["completed_bytes"] == 100
+ assert result["complete_on_disk"] is True # manifest verifies against disk
+ assert result["progress"] == 1.0
-def test_local_inventory_filters_custom_embedder_hf_cache_row(monkeypatch, tmp_path):
- from core.rag import config as rag_config
+def test_gguf_progress_unknown_hashes_stays_zero_without_variant_files(monkeypatch, tmp_path):
+ """The fallback reads the variant's files, not the shared blobs/ dir.
- monkeypatch.setattr(rag_config, "effective_embedding_model", lambda: "org/embedder")
- monkeypatch.setattr(rag_config, "effective_gguf_repo", lambda: "org/embedder-GGUF")
+ Guards the "instant ~900 MB" regression from the other direction: a cached
+ sibling quant with no snapshot file of this variant's own still reads zero.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ (blobs / "siblinghash").write_bytes(b"z" * 900)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry)
- def _row(repo_id: str):
- repo_path = tmp_path / f"models--{repo_id.replace('/', '--')}"
- return model_common._local_model_info(
- scan_path = repo_path,
- load_path = repo_path,
- source = "hf_cache",
- model_format = "safetensors",
- model_id = repo_id,
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 900,
)
+ )
- rows = local_inventory._filter_hidden_models([_row("org/embedder"), _row("org/chat-model")])
+ assert result["completed_bytes"] == 0
+ assert result["downloaded_bytes"] == 0
- assert [row.model_id for row in rows] == ["org/chat-model"]
+def test_gguf_progress_settles_complete_from_disk_without_a_manifest(monkeypatch, tmp_path):
+ """A materialized snapshot whose manifest is gone must not stay partial forever.
-def test_local_inventory_filters_embedder_configured_by_snapshot_path(monkeypatch, tmp_path):
- from core.rag import config as rag_config
+ Metadata named every blob the revision expects and all of them are on disk
+ finalized at their declared sizes, which is the evidence a manifest verify
+ collects. Refusing it because no manifest file happens to exist -- it was
+ never written, was deleted, or was filed under a cache scope this reader can
+ no longer name -- left the job in an active state with Retry/Resume showing
+ on a download that had finished.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert (
+ download_manifest.read_manifest("model", "Org/Model-GGUF", "Q4_K_M", hub_cache = entry.parent)
+ is None
+ )
- embedder_path = tmp_path / "hub" / "models--org--embedder"
- embedder_snapshot = embedder_path / "snapshots" / "revision"
- embedder_snapshot.mkdir(parents = True)
- chat_path = tmp_path / "hub" / "models--org--chat-model"
- chat_path.mkdir(parents = True)
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
monkeypatch.setattr(
- rag_config,
- "effective_embedding_model",
- lambda: str(embedder_snapshot),
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ download_size_bytes = 100,
+ required_hashes = frozenset({"mainhash"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ ),
+ ),
)
- monkeypatch.setattr(rag_config, "effective_gguf_repo", lambda: "org/embedder-GGUF")
monkeypatch.setattr(
- local_inventory.hf_cache_scan,
- "resolve_hf_cache_realpath",
- lambda path: str(embedder_snapshot) if Path(path) == embedder_path else str(path),
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
)
- def _row(repo_id: str, repo_path: Path):
- return model_common._local_model_info(
- scan_path = repo_path,
- load_path = repo_path,
- source = "hf_cache",
- model_format = "safetensors",
- model_id = repo_id,
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
)
+ )
- rows = local_inventory._filter_hidden_models(
- [_row("org/embedder", embedder_path), _row("org/chat-model", chat_path)]
+ assert result["complete_on_disk"] is True
+ assert result["progress"] == 1.0
+
+
+def test_a_refused_manifest_is_not_reread_through_the_blob_hash_fallback(monkeypatch, tmp_path):
+ """Refusing a manifest has to stick.
+
+ Two caches disagreeing about the variant means no manifest may be applied across the
+ scan. The generic blob-hash helper reads the DEFAULT cache's manifest with none of that
+ scoping, so falling through to it reinstated the rejected hashes -- and they then filter
+ out every blob of the cache that actually holds the finished variant.
+ """
+ active = tmp_path / "active" / "models--Org--Model-GGUF"
+ remembered = tmp_path / "remembered" / "models--Org--Model-GGUF"
+ active.mkdir(parents = True)
+ remembered.mkdir(parents = True)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(
+ download_manifest, "_canonical_hub_cache", lambda root = None: str(root or "")
+ )
+ for root, digest in ((active.parent, "new"), (remembered.parent, "old")):
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100, sha256 = digest)],
+ "http",
+ hub_cache = root,
+ )
+ monkeypatch.setattr(
+ downloads,
+ "preferred_repo_cache_dirs",
+ lambda *_a, **_kw: [active, remembered],
)
- assert [row.model_id for row in rows] == ["org/chat-model"]
+ called: list[str] = []
+ def _blob_hashes(*_args, **_kwargs):
+ called.append("fallback")
+ return frozenset({"new"})
-def test_model_download_job_helpers_preserve_idle_shape():
- key = downloads._download_job_key("Org/Model", None)
- status = downloads._job_status(key)
+ monkeypatch.setattr(downloads.gguf_variants, "gguf_variant_blob_hashes", _blob_hashes)
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ )
+ captured: dict = {}
+
+ async def _progress(*_args, **kwargs):
+ captured["resolver"] = kwargs.get("metadata_resolver")
+ return {
+ "downloaded_bytes": 0,
+ "completed_bytes": 0,
+ "complete_on_disk": False,
+ "expected_bytes": 0,
+ "progress": 0,
+ "cache_path": None,
+ }
- assert key == "org/model::"
- assert status.state == "idle"
- assert status.error is None
+ monkeypatch.setattr(downloads.snapshot_progress, "snapshot_progress_response", _progress)
+
+ asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+ resolver = captured["resolver"]
+ assert resolver is not None
+ assert resolver("Org/Model-GGUF", None) == (100, frozenset())
+ assert called == []
-def test_gguf_repo_partial_treats_completed_disk_variant_as_clean(monkeypatch, tmp_path):
+def test_gguf_progress_without_a_manifest_needs_every_expected_blob(monkeypatch, tmp_path):
+ """The no-manifest completion is evidence-gated, not size-gated.
+
+ One expected blob missing while an oversized sibling makes the byte total
+ look satisfied must stay partial: the caller's expected_bytes is a catalog
+ hint and can never be what completion is judged against.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (snap / "model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"x" * 400)
+ (blobs / "shard1").write_bytes(b"x" * 400) # shard2 never arrived
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- snapshot = tmp_path / "cache" / "models--Org--Repo" / "snapshots" / "abc"
- snapshot.mkdir(parents = True)
- (snapshot / "model-Q8_0.gguf").write_bytes(b"complete")
- assert download_manifest.write_cancel_marker("model", "Org/Repo", "Q4_K_M", "xet")
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
monkeypatch.setattr(
- inventory_scan,
- "resolve_snapshot_dir_for_scan",
- lambda *_args: snapshot,
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ download_size_bytes = 300,
+ required_hashes = frozenset({"shard1", "shard2"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M-00001-of-00002.gguf",
+ size = 150,
+ sha256 = "shard1",
+ ),
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M-00002-of-00002.gguf",
+ size = 150,
+ sha256 = "shard2",
+ ),
+ ),
+ ),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
)
- assert inventory_scan.is_gguf_repo_partial("Org/Repo", snapshot.parents[1]) is False
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 300,
+ )
+ )
+
+ assert result["complete_on_disk"] is False
+ assert result["progress"] == 0.99 # capped, not settled
-def test_gguf_repo_partial_flags_vision_variant_missing_mmproj(monkeypatch, tmp_path):
+def test_gguf_progress_recovers_the_windows_shaped_stale_download_card(monkeypatch, tmp_path):
+ """The reported symptom end to end: finished download, "0 B of 33 GB", Retry showing.
+
+ Every Windows-shaped condition at once, none of which reproduce on Linux on
+ their own. The cache is reached through a redirect so its resolved and
+ unresolved spellings differ; the snapshot holds copies rather than symlinks,
+ as HF falls back to when the filesystem refuses them; the manifest sits
+ under the pre-resolve scope digest an earlier build wrote it to; and
+ model_info is failing, so the expected blob hashes come back empty and stay
+ that way for the negative-cache TTL. Each one alone was enough to zero the
+ reading and keep the job out of a terminal state.
+ """
+ resolved_root = tmp_path / "resolved"
+ resolved_root.mkdir()
+ link = tmp_path / "redirected"
+ try:
+ link.symlink_to(resolved_root, target_is_directory = True)
+ except (NotImplementedError, OSError): # pragma: no cover - unprivileged Windows
+ pytest.skip("symlinks unavailable on this host")
+ hub_cache = link / "hub"
+ entry = hub_cache / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ # Copy layout: the snapshot holds real files, and blobs/ was never populated
+ # with anything this reading could have matched by hash.
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 33_000)
+ assert not (snap / "model-Q4_K_M.gguf").is_symlink()
+
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- snapshot = tmp_path / "cache" / "models--Org--Vision" / "snapshots" / "abc"
- snapshot.mkdir(parents = True)
- (snapshot / "model-Q4_K_M.gguf").write_bytes(b"complete-weight")
- assert download_manifest.write_manifest(
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = str(hub_cache)),
+ )
+ # A manifest as an older build filed it: hashed from the unresolved spelling,
+ # and with no sha256 because HF metadata was already unreachable when the
+ # worker recorded it from the finished snapshot.
+ legacy = state_dir.manifest_path(
"model",
- "Org/Vision",
+ "Org/Model-GGUF",
"Q4_K_M",
- [
- download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 15),
- download_manifest.ExpectedFile(path = "mmproj-F16.gguf", size = 8),
- ],
- "http",
+ hub_cache = hub_cache,
+ cache_scope = state_dir.legacy_cache_scope_name(hub_cache),
)
- monkeypatch.setattr(
- inventory_scan,
- "resolve_snapshot_dir_for_scan",
- lambda *_args: snapshot,
+ assert legacy.parent.name != state_dir.cache_scope_name(hub_cache)
+ legacy.parent.mkdir(parents = True, exist_ok = True)
+ legacy.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo_type": "model",
+ "repo_id": "Org/Model-GGUF",
+ "variant": "Q4_K_M",
+ "started_at": "2026-01-01T00:00:00+00:00",
+ "expected_files": [{"path": "model-Q4_K_M.gguf", "size": 33_000}],
+ "transport": "http",
+ "hub_cache": str(hub_cache),
+ }
+ ),
+ encoding = "utf-8",
)
+ _unresolvable_variant_metadata(monkeypatch, entry, state = "idle")
- assert inventory_scan.is_gguf_repo_partial("Org/Vision") is True
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 33_000,
+ )
+ )
+ assert result["downloaded_bytes"] == 33_000 # not "0 B"
+ assert result["completed_bytes"] == 33_000 # what settles the job terminal
+ assert result["expected_bytes"] == 33_000
+ assert result["complete_on_disk"] is True # so Retry/Resume goes away
+ assert result["progress"] == 1.0
-def test_cancel_worker_leaves_exited_process_to_watcher():
- calls: list = []
- class _Registry:
- def get_process(self, _key):
- return SimpleNamespace(poll = lambda: 1)
+def test_gguf_progress_without_a_manifest_needs_the_snapshot_materialized(monkeypatch, tmp_path):
+ """A finalized blob no one linked to is not a finished download.
- def get_job(self, _key):
- return SimpleNamespace(state = "running")
+ HF writes the blob and then links it into the snapshot dir, so a run killed
+ between the two leaves bytes that nothing points at. With a manifest,
+ verify_against_disk catches it; without one, blob-level evidence alone would
+ have called an unloadable snapshot complete.
- def mark_pending_cancel(self, key, generation):
- calls.append(("pending", key, generation))
- return True
+ The stray companion is the reason completion is judged against the metadata
+ file list rather than a byte total taken over the snapshot dir. Every mmproj
+ and drafter in a repo looks like it belongs to whichever variant is being
+ polled -- a plan fetches one of each -- so a leftover one, or an opt-in
+ ``dspark/`` drafter, would cover for the shard that never landed.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (blobs / "mainhash").write_bytes(b"x" * 100) # never linked into rev0
+ (snap / "mmproj-F32.gguf").write_bytes(b"y" * 5_000) # not in this plan
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- def request_cancel(self, key, proc, generation):
- calls.append(("request", key, generation))
- return True
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
- def cancel_requested(self, _key):
- return False
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_requirements",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ download_size_bytes = 100,
+ required_hashes = frozenset({"mainhash"}),
+ expected_files = (
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ ),
+ ),
+ ),
+ )
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ )
- state = download_lifecycle.cancel_worker(
- _Registry(),
- "org/model::",
- generation = 3,
- label = "Org/Model",
- logger = SimpleNamespace(warning = lambda *_a, **_k: None),
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
)
- assert state == "running"
- assert calls == []
+ assert result["complete_on_disk"] is False
-def test_completed_gguf_split_variant_requires_all_shards(tmp_path):
- snapshot = tmp_path / "snapshot"
- snapshot.mkdir()
- first = snapshot / "model-Q8_0-00001-of-00002.gguf"
- second = snapshot / "model-Q8_0-00002-of-00002.gguf"
- first.write_bytes(b"first")
+def test_running_job_never_reads_progress_from_a_remembered_cache(monkeypatch, tmp_path):
+ """force_active means the active root and nothing else, even before it exists.
- assert "Q8_0" not in inventory_scan._completed_gguf_variants(snapshot)
+ The first download into a freshly configured cache creates the root, so
+ hf_cache_root declines it and the lookup used to fall through to every
+ remembered cache. A previous cache's completed copy then read as this run's
+ progress, finalizing a job that had not written a byte.
+ """
+ previous = tmp_path / "previous"
+ complete = previous / "models--Org--Model" / "blobs"
+ complete.mkdir(parents = True)
+ (complete / "mainhash").write_bytes(b"x" * 100)
+ active = tmp_path / "active" # not created yet
+ monkeypatch.setattr(
+ hf_cache_state,
+ "hf_cache_roots",
+ lambda scan_errors = None: [previous],
+ )
- second.write_bytes(b"second")
- assert "Q8_0" in inventory_scan._completed_gguf_variants(snapshot)
+ dirs = hf_cache_state.preferred_repo_cache_dirs(
+ "model",
+ "Org/Model",
+ force_active = True,
+ active_root = active,
+ )
+ assert dirs == [active / "models--Org--Model"]
+ assert not dirs[0].exists()
+ # Without force_active the remembered copy is still the best reading there is.
+ assert hf_cache_state.preferred_repo_cache_dirs("model", "Org/Model") == [
+ previous / "models--Org--Model"
+ ]
-def test_completed_gguf_variants_ignores_big_endian_by_the_loader_label(tmp_path):
- # The scan reads Q4_K_M here, the loader reads F16 and refuses the file as big-endian. By
- # the scan's label it would vouch for Q4_K_M, and _complete_with_servable skips complete
- # quants, so the torn split below would be reported downloaded.
+
+def test_hf_cache_model_file_probe_is_bounded(monkeypatch, tmp_path):
snapshot = tmp_path / "snapshot"
snapshot.mkdir()
- (snapshot / "0-F16-be-checkpoint-Q4_K_M.gguf").write_bytes(b"GGUF")
- (snapshot / "z-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")
+ first = tmp_path / "README.md"
+ second = tmp_path / "notes.txt"
+ model = tmp_path / "model.safetensors"
+ first.write_text("readme", encoding = "utf-8")
+ second.write_text("notes", encoding = "utf-8")
+ model.write_bytes(b"weights")
+ entries = [first, second, model]
- assert "Q4_K_M" not in inventory_scan._completed_gguf_variants(snapshot)
+ monkeypatch.setattr(model_common.Path, "rglob", lambda _self, _pattern: iter(entries))
+ monkeypatch.setattr(model_common, "_HF_CACHE_MODEL_FILE_PROBE_LIMIT", 2)
- (snapshot / "z-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")
- assert "Q4_K_M" in inventory_scan._completed_gguf_variants(snapshot)
+ bounded = model_common._iter_hf_cache_model_files(snapshot)
+ assert bounded == [first, second]
-def test_variant_partial_accepts_variant_filtered_legacy_hashes(monkeypatch, tmp_path):
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+ monkeypatch.setattr(model_common, "_HF_CACHE_MODEL_FILE_PROBE_LIMIT", 3)
- assert inventory_scan.is_variant_partial(
- "Org/Repo",
- "Q4_K_M",
- incomplete_blob_hashes = {"main-q4", "main-q8"},
- variant_blob_hashes = frozenset({"main-q4"}),
- )
- assert not inventory_scan.is_variant_partial(
- "Org/Repo",
- "Q5_K_M",
- incomplete_blob_hashes = {"main-q4"},
- variant_blob_hashes = frozenset({"main-q5"}),
- )
+ unbounded = model_common._iter_hf_cache_model_files(snapshot)
+ assert unbounded == [first, second, model]
+
+
+def test_download_state_lookup_is_repo_case_insensitive(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
-def test_variant_partial_accepts_completed_variant_in_non_latest_snapshot(monkeypatch, tmp_path):
- """A verified GGUF update can prune an older snapshot and make that old
- directory the newest by mtime. The variant is still complete when another
- snapshot satisfies its manifest."""
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- repo_dir = tmp_path / "cache" / "models--Org--Repo"
- old_snapshot = repo_dir / "snapshots" / "old"
- new_snapshot = repo_dir / "snapshots" / "new"
- old_snapshot.mkdir(parents = True)
- new_snapshot.mkdir(parents = True)
- (old_snapshot / "model-Q8_0.gguf").write_bytes(b"sibling")
- (new_snapshot / "model-Q4_K_M.gguf").write_bytes(b"new")
assert download_manifest.write_manifest(
"model",
- "Org/Repo",
- "Q4_K_M",
- [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 3)],
- "http",
- )
-
- assert not inventory_scan.is_variant_partial(
- "Org/Repo",
+ "Owner/Repo",
"Q4_K_M",
- snapshot_dir = old_snapshot,
- repo_cache_dir = repo_dir,
+ [download_manifest.ExpectedFile(path = "config.json", size = 12)],
)
+ assert download_manifest.write_cancel_marker("model", "Owner/Repo", "q4_k_m", "http")
+ manifest = download_manifest.read_manifest("model", "owner/repo", "q4_k_m")
-def test_gguf_variants_partial_marker_overrides_size_only_downloaded(monkeypatch, tmp_path):
- async def _run_inline(fn, *args, **kwargs):
- return fn(*args, **kwargs)
+ assert manifest is not None
+ assert manifest.repo_id == "Owner/Repo"
+ assert manifest.expected_files[0].path == "config.json"
+ assert download_manifest.has_cancel_marker("model", "owner/repo", "Q4_K_M")
+ assert (
+ download_manifest.read_cancel_marker_transport(
+ "model",
+ "owner/repo",
+ "Q4_K_M",
+ )
+ == "http"
+ )
+ assert [
+ variant
+ for variant, _path in download_manifest.iter_variant_markers(
+ "model",
+ "owner/repo",
+ )
+ ] == ["q4_k_m"]
+ assert download_manifest.purge_all_state_for_repo("model", "owner/repo") == 1
+ assert download_manifest.read_manifest("model", "owner/repo", "Q4_K_M") is None
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- monkeypatch.setattr(gguf_variants.asyncio, "to_thread", _run_inline)
- assert download_manifest.write_cancel_marker("model", "Org/PartialRepo", "Q4_K_M", "http")
- snapshot = tmp_path / "cache" / "models--Org--PartialRepo" / "snapshots" / "rev0"
- snapshot.mkdir(parents = True)
- (snapshot / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+def test_hf_cache_scan_fallback_row_uses_local_model_info_alias(monkeypatch, tmp_path):
+ cache_dir = tmp_path / "hub"
+ repo_dir = cache_dir / "models--Org--Broken"
+ blobs_dir = repo_dir / "blobs"
+ blobs_dir.mkdir(parents = True)
+ (blobs_dir / "blob").write_bytes(b"content")
+ monkeypatch.setattr(local_inventory, "_classify_local_path", lambda *_args, **_kwargs: [])
monkeypatch.setattr(
- gguf_variants,
- "list_gguf_variants",
- lambda *_args, **_kwargs: (
- [
- SimpleNamespace(
- filename = "model-Q4_K_M.gguf",
- quant = "Q4_K_M",
- display_label = None,
- size_bytes = 100,
- )
- ],
- False,
- None,
- ),
- )
- monkeypatch.setattr(
- gguf_variants,
- "iter_hf_cache_snapshots",
- lambda _repo_id, root = None: [snapshot],
+ local_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
)
monkeypatch.setattr(
- gguf_variants,
- "_gguf_all_variant_requirements",
- lambda *_args, **_kwargs: {},
+ local_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda *_args, **_kwargs: False,
)
monkeypatch.setattr(
- gguf_variants.download_registry,
- "incomplete_blob_hashes",
- lambda *_args, **_kwargs: set(),
+ local_inventory.hf_cache_scan,
+ "resolve_hf_cache_realpath",
+ lambda *_args, **_kwargs: None,
)
- result = asyncio.run(gguf_variants.get_gguf_variants_response("Org/PartialRepo"))
-
- assert result.variants[0].downloaded is False
- assert result.variants[0].partial is True
-
+ rows = local_inventory._scan_hf_cache(cache_dir)
-def test_gguf_variants_scopes_partial_state_to_requested_cache(monkeypatch, tmp_path):
- async def _run_inline(fn, *args, **kwargs):
- return fn(*args, **kwargs)
+ assert len(rows) == 1
+ assert rows[0].model_id == "Org/Broken"
+ assert rows[0].source == "hf_cache"
+ assert rows[0].model_format == "unknown"
- repo_id = "Org/SharedRepo"
- repo_name = "models--Org--SharedRepo"
- cache_a = tmp_path / "cache-a"
- cache_b = tmp_path / "cache-b"
- repo_a = cache_a / repo_name
- snapshot_a = repo_a / "snapshots" / "revision"
- snapshot_a.mkdir(parents = True)
- (snapshot_a / "model-Q8_0.gguf").write_bytes(b"complete")
- blobs_b = cache_b / repo_name / "blobs"
- blobs_b.mkdir(parents = True)
- (blobs_b / "q8-hash.incomplete").write_bytes(b"partial")
+def test_hf_cache_scan_uses_gguf_partial_row_for_variant_state(monkeypatch, tmp_path):
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- monkeypatch.setattr(gguf_variants.asyncio, "to_thread", _run_inline)
- monkeypatch.setattr(
- "utils.hf_cache_settings.get_hf_cache_paths",
- lambda: SimpleNamespace(hub_cache = cache_b),
+ cache_dir = tmp_path / "hub"
+ repo_dir = cache_dir / "models--Org--PartialGguf"
+ blobs_dir = repo_dir / "blobs"
+ blobs_dir.mkdir(parents = True)
+ (blobs_dir / "partial").write_bytes(b"content")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/PartialGguf",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 8192)],
+ "http",
+ hub_cache = cache_dir,
)
assert download_manifest.write_cancel_marker(
"model",
- repo_id,
- "Q8_0",
+ "Org/PartialGguf",
+ "Q4_K_M",
"http",
- hub_cache = cache_b,
+ hub_cache = cache_dir,
)
+ monkeypatch.setattr(local_inventory, "_classify_local_path", lambda *_args, **_kwargs: [])
monkeypatch.setattr(
- gguf_variants,
- "list_gguf_variants",
- lambda *_args, **_kwargs: (
- [
- SimpleNamespace(
- filename = "model-Q8_0.gguf",
- quant = "Q8_0",
- display_label = None,
- size_bytes = 8,
- )
- ],
- False,
- [
- SimpleNamespace(
- rfilename = "model-Q8_0.gguf",
- size = 8,
- lfs = SimpleNamespace(sha256 = "q8-hash"),
- )
- ],
- ),
+ local_inventory.hf_cache_scan,
+ "is_snapshot_partial",
+ lambda *_args, **_kwargs: False,
)
- monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: [])
-
- result = asyncio.run(
- gguf_variants.get_gguf_variants_response(
- repo_id,
- local_path = str(repo_a),
- )
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda *_args, **_kwargs: True,
+ )
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "resolve_hf_cache_realpath",
+ lambda *_args, **_kwargs: None,
)
- assert result.variants[0].downloaded is True
- assert result.variants[0].partial is False
+ rows = local_inventory._scan_hf_cache(cache_dir)
+ assert len(rows) == 1
+ assert rows[0].model_id == "Org/PartialGguf"
+ assert rows[0].source == "hf_cache"
+ assert rows[0].model_format == "gguf"
+ assert rows[0].partial is True
+ assert rows[0].size_bytes == 8192
+ assert rows[0].capabilities.requires_variant is True
-def test_download_registry_repo_keys_are_case_insensitive():
- registry = download_registry.DownloadRegistry()
- claimed, state = registry.claim(
- "Org/Repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q8_0",
- )
- # The same variant under a different-cased repo id resolves to the same
- # job, so the second claim attaches to the running one instead of starting
- # a duplicate.
- duplicate_claimed, duplicate_state = registry.claim(
- "org/repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "org/repo",
- variant = "Q8_0",
- )
+def test_local_inventory_filters_custom_embedder_hf_cache_row(monkeypatch, tmp_path):
+ from core.rag import config as rag_config
- assert claimed is True
- assert state == "running"
- assert duplicate_claimed is False
- assert duplicate_state == "running"
- assert registry.active_jobs("ORG/REPO") == {"org/repo::Q8_0": "running"}
+ monkeypatch.setattr(rag_config, "effective_embedding_model", lambda: "org/embedder")
+ monkeypatch.setattr(rag_config, "effective_gguf_repo", lambda: "org/embedder-GGUF")
+ def _row(repo_id: str):
+ repo_path = tmp_path / f"models--{repo_id.replace('/', '--')}"
+ return model_common._local_model_info(
+ scan_path = repo_path,
+ load_path = repo_path,
+ source = "hf_cache",
+ model_format = "safetensors",
+ model_id = repo_id,
+ )
-def test_download_registry_allows_disjoint_gguf_variant_downloads():
- registry = download_registry.DownloadRegistry()
+ rows = local_inventory._filter_hidden_models([_row("org/embedder"), _row("org/chat-model")])
- claimed, state = registry.claim(
- "Org/Repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q8_0",
- blob_hashes = frozenset({"q8-main"}),
- progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
- )
- second_claimed, second_state = registry.claim(
- "Org/Repo::Q4_K_M",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q4_K_M",
- blob_hashes = frozenset({"q4-main"}),
- progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
- )
-
- assert claimed is True
- assert state == "running"
- assert second_claimed is True
- assert second_state == "running"
- assert registry.active_jobs("org/repo") == {
- "org/repo::Q8_0": "running",
- "org/repo::Q4_K_M": "running",
- }
+ assert [row.model_id for row in rows] == ["org/chat-model"]
-def test_download_registry_allows_overlapping_same_transport_variant_downloads():
- # Two variants sharing one mmproj blob still download together on one
- # transport: huggingface_hub's per-blob lock serializes the shared write and
- # prepare_cache_for_transport never purges a blob a peer is writing.
- registry = download_registry.DownloadRegistry()
+def test_local_inventory_filters_embedder_configured_by_snapshot_path(monkeypatch, tmp_path):
+ from core.rag import config as rag_config
- claimed, state = registry.claim(
- "Org/Repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q8_0",
- blob_hashes = frozenset({"q8-main"}),
- progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ embedder_path = tmp_path / "hub" / "models--org--embedder"
+ embedder_snapshot = embedder_path / "snapshots" / "revision"
+ embedder_snapshot.mkdir(parents = True)
+ chat_path = tmp_path / "hub" / "models--org--chat-model"
+ chat_path.mkdir(parents = True)
+ monkeypatch.setattr(
+ rag_config,
+ "effective_embedding_model",
+ lambda: str(embedder_snapshot),
)
- second_claimed, second_state = registry.claim(
- "Org/Repo::Q4_K_M",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q4_K_M",
- blob_hashes = frozenset({"q4-main"}),
- progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ monkeypatch.setattr(rag_config, "effective_gguf_repo", lambda: "org/embedder-GGUF")
+ monkeypatch.setattr(
+ local_inventory.hf_cache_scan,
+ "resolve_hf_cache_realpath",
+ lambda path: str(embedder_snapshot) if Path(path) == embedder_path else str(path),
)
- assert claimed is True
- assert state == "running"
- assert second_claimed is True
- assert second_state == "running"
-
+ def _row(repo_id: str, repo_path: Path):
+ return model_common._local_model_info(
+ scan_path = repo_path,
+ load_path = repo_path,
+ source = "hf_cache",
+ model_format = "safetensors",
+ model_id = repo_id,
+ )
-def test_download_registry_variant_delete_does_not_block_sibling_download():
- # Deleting one quant's partial must be allowed while a different quant of the
- # same repo is downloading, and must protect every blob the live sibling is
- # writing (including a shared mmproj companion).
- registry = download_registry.DownloadRegistry()
- registry.claim(
- "Org/Repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q8_0",
- blob_hashes = frozenset({"q8-main"}),
- progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ rows = local_inventory._filter_hidden_models(
+ [_row("org/embedder", embedder_path), _row("org/chat-model", chat_path)]
)
- # A sibling variant delete is allowed; deleting the in-flight variant is not.
- assert registry.begin_delete("Org/Repo", "Q4_K_M") is True
- assert registry.begin_delete("Org/Repo", "Q8_0") is False
- # A whole-repo delete still waits for every active download.
- assert registry.begin_delete("Org/Repo") is False
+ assert [row.model_id for row in rows] == ["org/chat-model"]
- # The live sibling is detected so the delete keeps the shared companion.
- assert registry.has_active_peer_variant("Org/Repo", "Q4_K_M") is True
- assert registry.has_active_peer_variant("Org/Repo", "Q8_0") is False
- # While Q4_K_M is being deleted, re-downloading it is blocked but an
- # untouched third variant may still start.
- blocked, blocked_state = registry.claim(
- "Org/Repo::Q4_K_M",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q4_K_M",
- )
- assert blocked is False
- assert blocked_state == "deleting"
- started, started_state = registry.claim(
- "Org/Repo::Q5_K_M",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q5_K_M",
- )
- assert started is True
- assert started_state == "running"
+def test_model_download_job_helpers_preserve_idle_shape():
+ key = downloads._download_job_key("Org/Model", None)
+ status = downloads._job_status(key)
- registry.end_delete("Org/Repo", "Q4_K_M")
- assert registry.begin_delete("Org/Repo", "Q4_K_M") is True
+ assert key == "org/model::"
+ assert status.state == "idle"
+ assert status.error is None
-def test_partial_gguf_reconstruction_dedupes_variant_casing(monkeypatch):
- # The manifest keeps original casing while the marker is lowercased; offline
- # reconstruction must collapse them to ONE entry (manifest's casing), not two.
+def test_gguf_repo_partial_treats_completed_disk_variant_as_clean(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ snapshot = tmp_path / "cache" / "models--Org--Repo" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model-Q8_0.gguf").write_bytes(b"complete")
+ assert download_manifest.write_cancel_marker("model", "Org/Repo", "Q4_K_M", "xet")
monkeypatch.setattr(
- download_manifest,
- "iter_variant_manifests",
- lambda _repo_type, _repo_id: iter([("Q4_K_M", Path("manifest.json"))]),
+ inventory_scan,
+ "resolve_snapshot_dir_for_scan",
+ lambda *_args: snapshot,
+ )
+
+ assert inventory_scan.is_gguf_repo_partial("Org/Repo", snapshot.parents[1]) is False
+
+
+def test_gguf_repo_partial_flags_vision_variant_missing_mmproj(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ snapshot = tmp_path / "cache" / "models--Org--Vision" / "snapshots" / "abc"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model-Q4_K_M.gguf").write_bytes(b"complete-weight")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Vision",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 15),
+ download_manifest.ExpectedFile(path = "mmproj-F16.gguf", size = 8),
+ ],
+ "http",
)
monkeypatch.setattr(
- download_manifest,
- "iter_variant_markers",
- lambda _repo_type, _repo_id: iter([("q4_k_m", Path("marker.json"))]),
+ inventory_scan,
+ "resolve_snapshot_dir_for_scan",
+ lambda *_args: snapshot,
)
- monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: None)
- result = gguf.list_partial_gguf_variants_from_state("Org/Repo")
+ assert inventory_scan.is_gguf_repo_partial("Org/Vision") is True
- assert result is not None
- variants, _has_vision = result
- assert [variant.quant for variant in variants] == ["Q4_K_M"]
+def test_cancel_worker_leaves_exited_process_to_watcher():
+ calls: list = []
-def test_partial_gguf_reconstruction_drops_a_variant_read_off_the_filename(monkeypatch):
- # An unreadable payload leaves the reader the filename, whose digest fragment
- # names nothing and would re-key to a further hash on resume. A variant genuinely
- # called sha256-<32 hex> reads the same but is stored under the hash of itself, so
- # the file it came from tells them apart where the spelling cannot.
- digest = "sha256-" + "0" * 32
- entries = [
- # variant, the file it was recovered from
- (f"@{digest}", Path(f"repo--variant--@{digest}.json")), # scope, payload lost
- (digest, Path(f"repo--variant--{digest}.json")), # ditto, older tag
- (digest, Path("repo--variant--@sha256-" + "c" * 32 + ".json")), # real, payload intact
- ("Q4_K_M", Path("repo--variant--q4_k_m.json")),
- ]
- monkeypatch.setattr(
- download_manifest, "iter_variant_manifests", lambda *_a, **_k: iter(entries)
- )
- monkeypatch.setattr(download_manifest, "iter_variant_markers", lambda *_a, **_k: iter(()))
- monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: None)
+ class _Registry:
+ def get_process(self, _key):
+ return SimpleNamespace(poll = lambda: 1)
- result = gguf.list_partial_gguf_variants_from_state("Org/Repo")
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
- assert result is not None
- variants, _has_vision = result
- assert sorted(variant.quant for variant in variants) == ["Q4_K_M", digest]
+ def mark_pending_cancel(self, key, generation):
+ calls.append(("pending", key, generation))
+ return True
+ def request_cancel(self, key, proc, generation):
+ calls.append(("request", key, generation))
+ return True
-def test_download_registry_serializes_cross_transport_variant_downloads():
- # An HTTP append-resume and an XET rewrite of the same shared blob would
- # corrupt each other, so different-transport variants are serialized.
- registry = download_registry.DownloadRegistry()
+ def cancel_requested(self, _key):
+ return False
- claimed, state = registry.claim(
- "Org/Repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q8_0",
- blob_hashes = frozenset({"q8-main"}),
- progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
- )
- second_claimed, second_state = registry.claim(
- "Org/Repo::Q4_K_M",
- download_registry.TRANSPORT_XET,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q4_K_M",
- blob_hashes = frozenset({"q4-main"}),
- progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ state = download_lifecycle.cancel_worker(
+ _Registry(),
+ "org/model::",
+ generation = 3,
+ label = "Org/Model",
+ logger = SimpleNamespace(warning = lambda *_a, **_k: None),
)
- assert claimed is True
assert state == "running"
- assert second_claimed is False
- assert second_state == "running"
+ assert calls == []
-def test_download_registry_allows_unknown_hash_gguf_variant_downloads():
- # Resolved blob hashes are NOT required to run two same-transport variants
- # concurrently: on-disk safety comes from each worker purging only its own
- # main-quant blobs plus huggingface_hub's per-etag lock. Requiring them here
- # used to reject the second variant whenever a metadata fetch flaked.
- registry = download_registry.DownloadRegistry()
+def test_completed_gguf_split_variant_requires_all_shards(tmp_path):
+ snapshot = tmp_path / "snapshot"
+ snapshot.mkdir()
+ first = snapshot / "model-Q8_0-00001-of-00002.gguf"
+ second = snapshot / "model-Q8_0-00002-of-00002.gguf"
+ first.write_bytes(b"first")
- claimed, state = registry.claim(
- "Org/Repo::Q8_0",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q8_0",
- )
- second_claimed, second_state = registry.claim(
- "Org/Repo::Q4_K_M",
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q4_K_M",
- blob_hashes = frozenset({"q4-main"}),
- progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
- )
-
- assert claimed is True
- assert state == "running"
- assert second_claimed is True
- assert second_state == "running"
- assert registry.active_jobs("org/repo") == {
- "org/repo::Q8_0": "running",
- "org/repo::Q4_K_M": "running",
- }
-
-
-def test_finalize_worker_exit_never_kills_a_healthy_worker(monkeypatch, tmp_path):
- # finalize_worker_exit relies solely on the worker's exit code and never kills
- # a live process: huggingface_hub already bounds reads with timeouts, so a
- # liveness kill could only false-cancel a healthy download.
- import inspect
- import io
- import logging
+ assert "Q8_0" not in inventory_scan._completed_gguf_variants(snapshot)
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ second.write_bytes(b"second")
+ assert "Q8_0" in inventory_scan._completed_gguf_variants(snapshot)
- class _Proc:
- pid = 4242
- def __init__(self):
- self.killed = False
- self.stderr = io.BytesIO(b"")
+def test_completed_gguf_variants_ignores_big_endian_by_the_loader_label(tmp_path):
+ # The scan reads Q4_K_M here, the loader reads F16 and refuses the file as big-endian. By
+ # the scan's label it would vouch for Q4_K_M, and _complete_with_servable skips complete
+ # quants, so the torn split below would be reported downloaded.
+ snapshot = tmp_path / "snapshot"
+ snapshot.mkdir()
+ (snapshot / "0-F16-be-checkpoint-Q4_K_M.gguf").write_bytes(b"GGUF")
+ (snapshot / "z-Q4_K_M-00001-of-00002.gguf").write_bytes(b"GGUF")
- def poll(self):
- return 0
+ assert "Q4_K_M" not in inventory_scan._completed_gguf_variants(snapshot)
- def wait(self, timeout = None):
- return 0
+ (snapshot / "z-Q4_K_M-00002-of-00002.gguf").write_bytes(b"GGUF")
+ assert "Q4_K_M" in inventory_scan._completed_gguf_variants(snapshot)
- def kill(self):
- self.killed = True
- registry = download_registry.DownloadRegistry()
- proc = _Proc()
- key = "Org/Repo::Q4_K_M"
- registry.claim(
- key,
- download_registry.TRANSPORT_HTTP,
- repo_type = "model",
- repo_id = "Org/Repo",
- variant = "Q4_K_M",
- )
- registry.register_process(key, proc)
+def test_variant_partial_accepts_variant_filtered_legacy_hashes(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
- download_lifecycle.finalize_worker_exit(
- registry,
- key,
- proc,
- hf_token = None,
- label = "Org/Repo [Q4_K_M]",
- log_prefix = "Download",
- logger = logging.getLogger("test"),
- repo_type = "model",
- repo_id = "Org/Repo",
- transport = "http",
+ assert inventory_scan.is_variant_partial(
+ "Org/Repo",
+ "Q4_K_M",
+ incomplete_blob_hashes = {"main-q4", "main-q8"},
+ variant_blob_hashes = frozenset({"main-q4"}),
)
-
- assert proc.killed is False
- assert registry.get_job(key).state == "complete"
- # The stall-watchdog knob is gone entirely; no caller may re-enable it.
- assert (
- "enable_stall_watchdog"
- not in inspect.signature(download_lifecycle.finalize_worker_exit).parameters
+ assert not inventory_scan.is_variant_partial(
+ "Org/Repo",
+ "Q5_K_M",
+ incomplete_blob_hashes = {"main-q4"},
+ variant_blob_hashes = frozenset({"main-q5"}),
)
-def test_prepare_cache_for_transport_purges_only_requested_hashes(monkeypatch, tmp_path):
- root = tmp_path / "hub"
- blobs = root / "models--Org--Repo" / "blobs"
- blobs.mkdir(parents = True)
- (blobs / "variant-main.incomplete").write_bytes(b"x")
- (blobs / "shared-mmproj.incomplete").write_bytes(b"y")
- monkeypatch.setattr(download_registry, "hf_cache_root", lambda create = False: root)
-
- purged = download_registry.prepare_cache_for_transport(
+def test_variant_partial_accepts_completed_variant_in_non_latest_snapshot(monkeypatch, tmp_path):
+ """A verified GGUF update can prune an older snapshot and make that old
+ directory the newest by mtime. The variant is still complete when another
+ snapshot satisfies its manifest."""
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ repo_dir = tmp_path / "cache" / "models--Org--Repo"
+ old_snapshot = repo_dir / "snapshots" / "old"
+ new_snapshot = repo_dir / "snapshots" / "new"
+ old_snapshot.mkdir(parents = True)
+ new_snapshot.mkdir(parents = True)
+ (old_snapshot / "model-Q8_0.gguf").write_bytes(b"sibling")
+ (new_snapshot / "model-Q4_K_M.gguf").write_bytes(b"new")
+ assert download_manifest.write_manifest(
"model",
"Org/Repo",
- download_registry.TRANSPORT_XET,
"Q4_K_M",
- frozenset({"variant-main"}),
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 3)],
+ "http",
)
- assert purged == 1
- assert not (blobs / "variant-main.incomplete").exists()
- assert (blobs / "shared-mmproj.incomplete").exists()
+ assert not inventory_scan.is_variant_partial(
+ "Org/Repo",
+ "Q4_K_M",
+ snapshot_dir = old_snapshot,
+ repo_cache_dir = repo_dir,
+ )
-def test_prepare_cache_for_transport_uses_captured_root(monkeypatch, tmp_path):
- cache_a = tmp_path / "cache-a"
- cache_b = tmp_path / "cache-b"
- repo_name = "models--Org--Repo"
- partial_a = cache_a / repo_name / "blobs" / "blob.incomplete"
- partial_b = cache_b / repo_name / "blobs" / "blob.incomplete"
- partial_a.parent.mkdir(parents = True)
- partial_b.parent.mkdir(parents = True)
- partial_a.write_bytes(b"a")
- partial_b.write_bytes(b"b")
+def test_gguf_variants_partial_marker_overrides_size_only_downloaded(monkeypatch, tmp_path):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(gguf_variants.asyncio, "to_thread", _run_inline)
+ assert download_manifest.write_cancel_marker("model", "Org/PartialRepo", "Q4_K_M", "http")
+ snapshot = tmp_path / "cache" / "models--Org--PartialRepo" / "snapshots" / "rev0"
+ snapshot.mkdir(parents = True)
+ (snapshot / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+
monkeypatch.setattr(
- download_registry,
- "hf_cache_root",
- lambda create = False, root = None: root or cache_b,
+ gguf_variants,
+ "list_gguf_variants",
+ lambda *_args, **_kwargs: (
+ [
+ SimpleNamespace(
+ filename = "model-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ display_label = None,
+ size_bytes = 100,
+ )
+ ],
+ False,
+ None,
+ ),
)
-
- purged = download_registry.prepare_cache_for_transport(
- "model",
- "Org/Repo",
- download_registry.TRANSPORT_HTTP,
- root = cache_a,
+ monkeypatch.setattr(
+ gguf_variants,
+ "iter_hf_cache_snapshots",
+ lambda _repo_id, root = None: [snapshot],
+ )
+ monkeypatch.setattr(
+ gguf_variants,
+ "_gguf_all_variant_requirements",
+ lambda *_args, **_kwargs: {},
+ )
+ monkeypatch.setattr(
+ gguf_variants.download_registry,
+ "incomplete_blob_hashes",
+ lambda *_args, **_kwargs: set(),
)
- assert purged == 1
- assert not partial_a.exists()
- assert partial_b.exists()
+ result = asyncio.run(gguf_variants.get_gguf_variants_response("Org/PartialRepo"))
+ assert result.variants[0].downloaded is False
+ assert result.variants[0].partial is True
-def _vision_cache_root(monkeypatch, tmp_path):
- root = tmp_path / "hub"
- blobs = root / "models--Org--Vision" / "blobs"
- blobs.mkdir(parents = True)
- monkeypatch.setattr(download_registry, "hf_cache_root", lambda create = False: root)
- return blobs
+def test_gguf_variants_scopes_partial_state_to_requested_cache(monkeypatch, tmp_path):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
-def test_prepare_cache_for_transport_purges_cross_transport_companion(monkeypatch, tmp_path):
- blobs = _vision_cache_root(monkeypatch, tmp_path)
- companion = frozenset({"shared-mmproj"})
+ repo_id = "Org/SharedRepo"
+ repo_name = "models--Org--SharedRepo"
+ cache_a = tmp_path / "cache-a"
+ cache_b = tmp_path / "cache-b"
+ repo_a = cache_a / repo_name
+ snapshot_a = repo_a / "snapshots" / "revision"
+ snapshot_a.mkdir(parents = True)
+ (snapshot_a / "model-Q8_0.gguf").write_bytes(b"complete")
+ blobs_b = cache_b / repo_name / "blobs"
+ blobs_b.mkdir(parents = True)
+ (blobs_b / "q8-hash.incomplete").write_bytes(b"partial")
- # An interrupted XET download stamps the companion marker "xet" and leaves a
- # sparse partial. A later HTTP download of a different variant must purge it,
- # else the HTTP resumer appends to the sparse bytes and corrupts the blob.
- download_registry.prepare_cache_for_transport(
- "model",
- "Org/Vision",
- download_registry.TRANSPORT_XET,
- "Q4_K_M",
- only_blob_hashes = frozenset({"q4-main"}),
- companion_blob_hashes = companion,
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ monkeypatch.setattr(gguf_variants.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = cache_b),
)
- (blobs / "shared-mmproj.incomplete").write_bytes(b"sparse")
-
- purged = download_registry.prepare_cache_for_transport(
+ assert download_manifest.write_cancel_marker(
"model",
- "Org/Vision",
- download_registry.TRANSPORT_HTTP,
+ repo_id,
"Q8_0",
- only_blob_hashes = frozenset({"q8-main"}),
- companion_blob_hashes = companion,
+ "http",
+ hub_cache = cache_b,
)
-
- assert purged == 1
- assert not (blobs / "shared-mmproj.incomplete").exists()
-
-
-def test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypatch, tmp_path):
- blobs = _vision_cache_root(monkeypatch, tmp_path)
- companion = frozenset({"shared-mmproj"})
-
- download_registry.prepare_cache_for_transport(
- "model",
- "Org/Vision",
- download_registry.TRANSPORT_HTTP,
- "Q4_K_M",
- only_blob_hashes = frozenset({"q4-main"}),
- companion_blob_hashes = companion,
+ monkeypatch.setattr(
+ gguf_variants,
+ "list_gguf_variants",
+ lambda *_args, **_kwargs: (
+ [
+ SimpleNamespace(
+ filename = "model-Q8_0.gguf",
+ quant = "Q8_0",
+ display_label = None,
+ size_bytes = 8,
+ )
+ ],
+ False,
+ [
+ SimpleNamespace(
+ rfilename = "model-Q8_0.gguf",
+ size = 8,
+ lfs = SimpleNamespace(sha256 = "q8-hash"),
+ )
+ ],
+ ),
)
- (blobs / "shared-mmproj.incomplete").write_bytes(b"resumable")
+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: [])
- purged = download_registry.prepare_cache_for_transport(
- "model",
- "Org/Vision",
- download_registry.TRANSPORT_HTTP,
- "Q4_K_M",
- only_blob_hashes = frozenset({"q4-main"}),
- companion_blob_hashes = companion,
+ result = asyncio.run(
+ gguf_variants.get_gguf_variants_response(
+ repo_id,
+ local_path = str(repo_a),
+ )
)
- assert purged == 0
- assert (blobs / "shared-mmproj.incomplete").exists()
+ assert result.variants[0].downloaded is True
+ assert result.variants[0].partial is False
-def test_prepare_cache_for_transport_protects_peer_companion(monkeypatch, tmp_path):
- blobs = _vision_cache_root(monkeypatch, tmp_path)
- companion = frozenset({"shared-mmproj"})
+def test_download_registry_repo_keys_are_case_insensitive():
+ registry = download_registry.DownloadRegistry()
- download_registry.prepare_cache_for_transport(
- "model",
- "Org/Vision",
- download_registry.TRANSPORT_XET,
- "Q4_K_M",
- only_blob_hashes = frozenset({"q4-main"}),
- companion_blob_hashes = companion,
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
)
- (blobs / "shared-mmproj.incomplete").write_bytes(b"sparse")
-
- purged = download_registry.prepare_cache_for_transport(
- "model",
- "Org/Vision",
+ # The same variant under a different-cased repo id resolves to the same
+ # job, so the second claim attaches to the running one instead of starting
+ # a duplicate.
+ duplicate_claimed, duplicate_state = registry.claim(
+ "org/repo::Q8_0",
download_registry.TRANSPORT_HTTP,
- "Q8_0",
- only_blob_hashes = frozenset({"q8-main"}),
- companion_blob_hashes = companion,
- protected_blob_hashes = companion,
+ repo_type = "model",
+ repo_id = "org/repo",
+ variant = "Q8_0",
)
- assert purged == 0
- assert (blobs / "shared-mmproj.incomplete").exists()
+ assert claimed is True
+ assert state == "running"
+ assert duplicate_claimed is False
+ assert duplicate_state == "running"
+ assert registry.active_jobs("ORG/REPO") == {"org/repo::Q8_0": "running"}
-def test_model_download_records_completed_baseline_for_new_gguf_variant(monkeypatch, tmp_path):
- async def _run_inline(fn, *args, **kwargs):
- return fn(*args, **kwargs)
+def test_download_registry_allows_disjoint_gguf_variant_downloads():
+ registry = download_registry.DownloadRegistry()
- monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- monkeypatch.setattr(
- downloads,
- "resolve_cached_repo_id_case",
- lambda repo_id, repo_type = "model": repo_id,
- )
- monkeypatch.setattr(
- downloads.gguf_variants,
- "gguf_variant_blob_hashes",
- lambda _repo, _variant, _token = None, include_companions = True, **_kwargs: (
- frozenset({"mainhash", "mmprojhash"}) if include_companions else frozenset({"mainhash"})
- ),
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
)
- monkeypatch.setattr(
- downloads.download_registry,
- "completed_blob_bytes",
- lambda *_args, **_kwargs: 30,
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
)
- class _Registry:
- claim_kwargs = None
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is True
+ assert second_state == "running"
+ assert registry.active_jobs("org/repo") == {
+ "org/repo::Q8_0": "running",
+ "org/repo::Q4_K_M": "running",
+ }
- def claim(self, _key, _transport, **kwargs):
- self.claim_kwargs = kwargs
- return True, "running"
- def current_generation(self, _key):
- return 1
+def test_download_registry_allows_overlapping_same_transport_variant_downloads():
+ # Two variants sharing one mmproj blob still download together on one
+ # transport: huggingface_hub's per-blob lock serializes the shared write and
+ # prepare_cache_for_transport never purges a blob a peer is writing.
+ registry = download_registry.DownloadRegistry()
- def get_job(self, _key):
- return SimpleNamespace(state = "running")
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
- def register_process(self, _key, _proc):
- return False
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is True
+ assert second_state == "running"
- def peer_blob_hashes(self, _key):
- return frozenset()
- class _Proc:
- pid = 123
- stderr = None
+def test_download_registry_variant_delete_does_not_block_sibling_download():
+ # Deleting one quant's partial must be allowed while a different quant of the
+ # same repo is downloading, and must protect every blob the live sibling is
+ # writing (including a shared mmproj companion).
+ registry = download_registry.DownloadRegistry()
+ registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
- def poll(self):
- return None
+ # A sibling variant delete is allowed; deleting the in-flight variant is not.
+ assert registry.begin_delete("Org/Repo", "Q4_K_M") is True
+ assert registry.begin_delete("Org/Repo", "Q8_0") is False
+ # A whole-repo delete still waits for every active download.
+ assert registry.begin_delete("Org/Repo") is False
- def kill(self):
- return None
+ # The live sibling is detected so the delete keeps the shared companion.
+ assert registry.has_active_peer_variant("Org/Repo", "Q4_K_M") is True
+ assert registry.has_active_peer_variant("Org/Repo", "Q8_0") is False
- def wait(self, timeout = None):
- return 0
+ # While Q4_K_M is being deleted, re-downloading it is blocked but an
+ # untouched third variant may still start.
+ blocked, blocked_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ )
+ assert blocked is False
+ assert blocked_state == "deleting"
+ started, started_state = registry.claim(
+ "Org/Repo::Q5_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q5_K_M",
+ )
+ assert started is True
+ assert started_state == "running"
- registry = _Registry()
- monkeypatch.setattr(downloads, "_registry", registry)
- monkeypatch.setattr(downloads, "_spawn_download_worker", lambda *_args, **_kwargs: _Proc())
+ registry.end_delete("Org/Repo", "Q4_K_M")
+ assert registry.begin_delete("Org/Repo", "Q4_K_M") is True
- asyncio.run(downloads.download_model_response(_download_body(gguf_variant = "Q4_K_M")))
- assert registry.claim_kwargs["blob_hashes"] == frozenset({"mainhash"})
- assert registry.claim_kwargs["progress_blob_hashes"] == frozenset({"mainhash", "mmprojhash"})
- assert registry.claim_kwargs["completed_baseline_bytes"] == 30
+def test_partial_gguf_reconstruction_dedupes_variant_casing(monkeypatch):
+ # The manifest keeps original casing while the marker is lowercased; offline
+ # reconstruction must collapse them to ONE entry (manifest's casing), not two.
+ monkeypatch.setattr(
+ download_manifest,
+ "iter_variant_manifests",
+ lambda _repo_type, _repo_id: iter([("Q4_K_M", Path("manifest.json"))]),
+ )
+ monkeypatch.setattr(
+ download_manifest,
+ "iter_variant_markers",
+ lambda _repo_type, _repo_id: iter([("q4_k_m", Path("marker.json"))]),
+ )
+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: None)
+ result = gguf.list_partial_gguf_variants_from_state("Org/Repo")
-def test_gguf_model_download_skips_completed_baseline_for_variant_resume_state(
- monkeypatch, tmp_path
-):
- async def _run_inline(fn, *args, **kwargs):
- return fn(*args, **kwargs)
+ assert result is not None
+ variants, _has_vision = result
+ assert [variant.quant for variant in variants] == ["Q4_K_M"]
- monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- assert download_manifest.write_manifest(
- "model",
- "Org/Model",
- "Q4_K_M",
- [
- download_manifest.ExpectedFile(
- path = "model-Q4_K_M.gguf",
- size = 100,
- sha256 = "mainhash",
- )
- ],
- "http",
- )
- monkeypatch.setattr(
- downloads,
- "resolve_cached_repo_id_case",
- lambda repo_id, repo_type = "model": repo_id,
- )
- monkeypatch.setattr(
- downloads.gguf_variants,
- "gguf_variant_blob_hashes",
- lambda _repo, _variant, _token = None, include_companions = True, **_kwargs: (
- frozenset({"mainhash", "mmprojhash"}) if include_companions else frozenset({"mainhash"})
- ),
- )
+
+def test_partial_gguf_reconstruction_drops_a_variant_read_off_the_filename(monkeypatch):
+ # An unreadable payload leaves the reader the filename, whose digest fragment
+ # names nothing and would re-key to a further hash on resume. A variant genuinely
+ # called sha256-<32 hex> reads the same but is stored under the hash of itself, so
+ # the file it came from tells them apart where the spelling cannot.
+ digest = "sha256-" + "0" * 32
+ entries = [
+ # variant, the file it was recovered from
+ (f"@{digest}", Path(f"repo--variant--@{digest}.json")), # scope, payload lost
+ (digest, Path(f"repo--variant--{digest}.json")), # ditto, older tag
+ (digest, Path("repo--variant--@sha256-" + "c" * 32 + ".json")), # real, payload intact
+ ("Q4_K_M", Path("repo--variant--q4_k_m.json")),
+ ]
monkeypatch.setattr(
- downloads.download_registry,
- "completed_blob_bytes",
- lambda *_args, **_kwargs: 30,
+ download_manifest, "iter_variant_manifests", lambda *_a, **_k: iter(entries)
)
+ monkeypatch.setattr(download_manifest, "iter_variant_markers", lambda *_a, **_k: iter(()))
+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *_a, **_k: None)
- class _Registry:
- claim_kwargs = None
-
- def claim(self, _key, _transport, **kwargs):
- self.claim_kwargs = kwargs
- return True, "running"
-
- def current_generation(self, _key):
- return 1
-
- def get_job(self, _key):
- return SimpleNamespace(state = "running")
-
- def register_process(self, _key, _proc):
- return False
-
- def peer_blob_hashes(self, _key):
- return frozenset()
-
- class _Proc:
- pid = 123
- stderr = None
+ result = gguf.list_partial_gguf_variants_from_state("Org/Repo")
- def poll(self):
- return None
+ assert result is not None
+ variants, _has_vision = result
+ assert sorted(variant.quant for variant in variants) == ["Q4_K_M", digest]
- def kill(self):
- return None
- def wait(self, timeout = None):
- return 0
+def test_download_registry_serializes_cross_transport_variant_downloads():
+ # An HTTP append-resume and an XET rewrite of the same shared blob would
+ # corrupt each other, so different-transport variants are serialized.
+ registry = download_registry.DownloadRegistry()
- registry = _Registry()
- monkeypatch.setattr(downloads, "_registry", registry)
- monkeypatch.setattr(downloads, "_spawn_download_worker", lambda *_args, **_kwargs: _Proc())
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ blob_hashes = frozenset({"q8-main"}),
+ progress_blob_hashes = frozenset({"q8-main", "shared-mmproj"}),
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_XET,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
- asyncio.run(downloads.download_model_response(_download_body(gguf_variant = "Q4_K_M")))
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is False
+ assert second_state == "running"
- assert registry.claim_kwargs["completed_baseline_bytes"] == 0
+def test_download_registry_allows_unknown_hash_gguf_variant_downloads():
+ # Resolved blob hashes are NOT required to run two same-transport variants
+ # concurrently: on-disk safety comes from each worker purging only its own
+ # main-quant blobs plus huggingface_hub's per-etag lock. Requiring them here
+ # used to reject the second variant whenever a metadata fetch flaked.
+ registry = download_registry.DownloadRegistry()
-def test_model_idle_status_uses_cancel_marker_after_restart(monkeypatch, tmp_path):
- monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
- monkeypatch.setattr(downloads, "_registry", download_registry.DownloadRegistry())
- assert download_manifest.write_cancel_marker("model", "Owner/Repo", "Q4_K_M", "http")
+ claimed, state = registry.claim(
+ "Org/Repo::Q8_0",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q8_0",
+ )
+ second_claimed, second_state = registry.claim(
+ "Org/Repo::Q4_K_M",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
+ blob_hashes = frozenset({"q4-main"}),
+ progress_blob_hashes = frozenset({"q4-main", "shared-mmproj"}),
+ )
- status = asyncio.run(downloads.get_download_status_response("owner/repo", "Q4_K_M"))
+ assert claimed is True
+ assert state == "running"
+ assert second_claimed is True
+ assert second_state == "running"
+ assert registry.active_jobs("org/repo") == {
+ "org/repo::Q8_0": "running",
+ "org/repo::Q4_K_M": "running",
+ }
- assert status.state == "cancelled"
- assert status.error is None
+def test_finalize_worker_exit_never_kills_a_healthy_worker(monkeypatch, tmp_path):
+ # finalize_worker_exit relies solely on the worker's exit code and never kills
+ # a live process: huggingface_hub already bounds reads with timeouts, so a
+ # liveness kill could only false-cancel a healthy download.
+ import inspect
+ import io
+ import logging
-def test_shutdown_kills_all_workers_before_shared_deadline_reap(monkeypatch):
- events = []
- now = [100.0]
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
class _Proc:
- def __init__(self, name):
- self.name = name
+ pid = 4242
+
+ def __init__(self):
+ self.killed = False
+ self.stderr = io.BytesIO(b"")
def poll(self):
- return None
+ return 0
- def kill(self):
- events.append(("kill", self.name))
+ def wait(self, timeout = None):
+ return 0
- def wait(self, timeout):
- events.append(("wait", self.name, timeout))
- now[0] += 7.0
+ def kill(self):
+ self.killed = True
registry = download_registry.DownloadRegistry()
- proc_a = _Proc("a")
- proc_b = _Proc("b")
- registry.claim(
- "Org/A",
- download_registry.TRANSPORT_HTTP,
- repo_type = "dataset",
- repo_id = "Org/A",
- )
+ proc = _Proc()
+ key = "Org/Repo::Q4_K_M"
registry.claim(
- "Org/B",
+ key,
download_registry.TRANSPORT_HTTP,
- repo_type = "dataset",
- repo_id = "Org/B",
- )
- assert registry.register_process("org/a", proc_a)
- assert registry.register_process("org/b", proc_b)
- monkeypatch.setattr(
- download_registry,
- "persist_cancel_marker",
- lambda *args, **kwargs: events.append(("marker", args[1])),
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ variant = "Q4_K_M",
)
- monkeypatch.setattr(download_registry.time, "monotonic", lambda: now[0])
-
- registry.terminate_all("dataset download")
+ registry.register_process(key, proc)
- assert events == [
- ("kill", "a"),
- ("kill", "b"),
- ("wait", "a", 10.0),
- ("marker", "Org/A"),
- ("wait", "b", 3.0),
- ("marker", "Org/B"),
- ]
+ download_lifecycle.finalize_worker_exit(
+ registry,
+ key,
+ proc,
+ hf_token = None,
+ label = "Org/Repo [Q4_K_M]",
+ log_prefix = "Download",
+ logger = logging.getLogger("test"),
+ repo_type = "model",
+ repo_id = "Org/Repo",
+ transport = "http",
+ )
+ assert proc.killed is False
+ assert registry.get_job(key).state == "complete"
+ # The stall-watchdog knob is gone entirely; no caller may re-enable it.
+ assert (
+ "enable_stall_watchdog"
+ not in inspect.signature(download_lifecycle.finalize_worker_exit).parameters
+ )
-def test_shutdown_skips_marker_for_worker_that_exits_cleanly(monkeypatch):
- markers = []
- class _Proc:
- def __init__(self, final_rc):
- self._final_rc = final_rc
- self._exited = False
+def test_prepare_cache_for_transport_purges_only_requested_hashes(monkeypatch, tmp_path):
+ root = tmp_path / "hub"
+ blobs = root / "models--Org--Repo" / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "variant-main.incomplete").write_bytes(b"x")
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"y")
+ monkeypatch.setattr(download_registry, "hf_cache_root", lambda create = False, **kw: root)
- def poll(self):
- return self._final_rc if self._exited else None
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Repo",
+ download_registry.TRANSPORT_XET,
+ "Q4_K_M",
+ frozenset({"variant-main"}),
+ )
- def kill(self):
- pass
+ assert purged == 1
+ assert not (blobs / "variant-main.incomplete").exists()
+ assert (blobs / "shared-mmproj.incomplete").exists()
- def wait(self, timeout):
- self._exited = True
- registry = download_registry.DownloadRegistry()
- clean = _Proc(0)
- interrupted = _Proc(-9)
- registry.claim(
- "Org/Clean",
- download_registry.TRANSPORT_HTTP,
- repo_type = "dataset",
- repo_id = "Org/Clean",
- )
- registry.claim(
- "Org/Cut",
- download_registry.TRANSPORT_HTTP,
- repo_type = "dataset",
- repo_id = "Org/Cut",
- )
- assert registry.register_process("org/clean", clean)
- assert registry.register_process("org/cut", interrupted)
+def test_prepare_cache_for_transport_uses_captured_root(monkeypatch, tmp_path):
+ cache_a = tmp_path / "cache-a"
+ cache_b = tmp_path / "cache-b"
+ repo_name = "models--Org--Repo"
+ partial_a = cache_a / repo_name / "blobs" / "blob.incomplete"
+ partial_b = cache_b / repo_name / "blobs" / "blob.incomplete"
+ partial_a.parent.mkdir(parents = True)
+ partial_b.parent.mkdir(parents = True)
+ partial_a.write_bytes(b"a")
+ partial_b.write_bytes(b"b")
monkeypatch.setattr(
download_registry,
- "persist_cancel_marker",
- lambda *args, **kwargs: markers.append(args[1]),
+ "hf_cache_root",
+ lambda create = False, root = None: root or cache_b,
)
- registry.terminate_all("dataset download")
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Repo",
+ download_registry.TRANSPORT_HTTP,
+ root = cache_a,
+ )
- assert markers == ["Org/Cut"]
+ assert purged == 1
+ assert not partial_a.exists()
+ assert partial_b.exists()
-def test_orphan_reaper_uses_worker_cache_root_after_setting_changes(monkeypatch, tmp_path):
- workers = tmp_path / "workers"
- workers.mkdir()
- cache_a = tmp_path / "cache-a" / "hub"
- cache_b = tmp_path / "cache-b" / "hub"
- partial = cache_a / "models--Org--Model" / "blobs" / "abc.incomplete"
- partial.parent.mkdir(parents = True)
- partial.write_bytes(b"partial")
- cache_b.mkdir(parents = True)
- monkeypatch.setattr(state_dir, "workers_dir", lambda: workers)
- monkeypatch.setattr(download_registry, "_process_alive", lambda _pid: False)
- monkeypatch.setattr(
- "utils.hf_cache_settings.get_hf_cache_paths",
- lambda: SimpleNamespace(hub_cache = cache_b),
+def _vision_cache_root(monkeypatch, tmp_path):
+ root = tmp_path / "hub"
+ blobs = root / "models--Org--Vision" / "blobs"
+ blobs.mkdir(parents = True)
+ monkeypatch.setattr(download_registry, "hf_cache_root", lambda create = False, **kw: root)
+ return blobs
+
+
+def test_prepare_cache_for_transport_purges_cross_transport_companion(monkeypatch, tmp_path):
+ blobs = _vision_cache_root(monkeypatch, tmp_path)
+ companion = frozenset({"shared-mmproj"})
+
+ # An interrupted XET download stamps the companion marker "xet" and leaves a
+ # sparse partial. A later HTTP download of a different variant must purge it,
+ # else the HTTP resumer appends to the sparse bytes and corrupts the blob.
+ download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_XET,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
)
- markers = []
- monkeypatch.setattr(
- download_registry,
- "persist_cancel_marker",
- lambda *args, **kwargs: markers.append(args),
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"sparse")
+
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q8_0",
+ only_blob_hashes = frozenset({"q8-main"}),
+ companion_blob_hashes = companion,
)
- metadata = download_registry.DownloadMetadata(
- repo_type = "model",
- repo_id = "Org/Model",
- variant = None,
- transport = download_registry.TRANSPORT_HTTP,
- hub_cache = str(cache_a),
- xet_cache = str(tmp_path / "cache-a" / "xet"),
+
+ assert purged == 1
+ assert not (blobs / "shared-mmproj.incomplete").exists()
+
+
+def test_prepare_cache_for_transport_preserves_same_transport_companion(monkeypatch, tmp_path):
+ blobs = _vision_cache_root(monkeypatch, tmp_path)
+ companion = frozenset({"shared-mmproj"})
+
+ download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
)
- download_registry.write_worker_breadcrumb("org/model", 1234, metadata)
- [breadcrumb] = list(workers.iterdir())
- payload = json.loads(breadcrumb.read_text(encoding = "utf-8"))
- assert payload["hub_cache"] == str(cache_a)
- assert payload["xet_cache"] == str(tmp_path / "cache-a" / "xet")
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"resumable")
- download_registry.reap_orphan_workers()
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
+ )
- assert markers == [("model", "Org/Model", None, "http")]
- assert list(workers.iterdir()) == []
+ assert purged == 0
+ assert (blobs / "shared-mmproj.incomplete").exists()
-def test_model_claim_register_cancel_uses_registry_marker_owner(monkeypatch):
- killed = []
+def test_prepare_cache_for_transport_protects_peer_companion(monkeypatch, tmp_path):
+ blobs = _vision_cache_root(monkeypatch, tmp_path)
+ companion = frozenset({"shared-mmproj"})
- class _Registry:
- def claim(self, *_args, **_kwargs):
- return True, "running"
+ download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_XET,
+ "Q4_K_M",
+ only_blob_hashes = frozenset({"q4-main"}),
+ companion_blob_hashes = companion,
+ )
+ (blobs / "shared-mmproj.incomplete").write_bytes(b"sparse")
- def current_generation(self, _key):
- return 1
+ purged = download_registry.prepare_cache_for_transport(
+ "model",
+ "Org/Vision",
+ download_registry.TRANSPORT_HTTP,
+ "Q8_0",
+ only_blob_hashes = frozenset({"q8-main"}),
+ companion_blob_hashes = companion,
+ protected_blob_hashes = companion,
+ )
- def register_process(self, _key, _proc):
- return False
+ assert purged == 0
+ assert (blobs / "shared-mmproj.incomplete").exists()
- def persist_cancel_for_key(self, *_args, **_kwargs):
- raise AssertionError("register_process owns pending-cancel markers")
- def get_job(self, _key):
- return SimpleNamespace(state = "cancelled", error = None)
+def test_model_download_records_completed_baseline_for_new_gguf_variant(monkeypatch, tmp_path):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
- monkeypatch.setattr(downloads, "_registry", _Registry())
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
monkeypatch.setattr(
downloads,
"resolve_cached_repo_id_case",
- lambda repo_id, **_kwargs: repo_id,
- )
- monkeypatch.setattr(
- downloads.download_registry,
- "download_transport_unavailable_reason",
- lambda _transport: None,
+ lambda repo_id, repo_type = "model": repo_id,
)
monkeypatch.setattr(
- downloads,
- "_spawn_download_worker",
- lambda *_args, **_kwargs: object(),
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda _repo, _variant, _token = None, include_companions = True, **_kwargs: (
+ frozenset({"mainhash", "mmprojhash"}) if include_companions else frozenset({"mainhash"})
+ ),
)
monkeypatch.setattr(
- downloads.download_lifecycle,
- "kill_and_reap_process",
- lambda proc, **_kwargs: killed.append(proc),
+ downloads.download_registry,
+ "completed_blob_bytes",
+ lambda *_args, **_kwargs: 30,
)
- result = asyncio.run(downloads.download_model_response(_download_body()))
+ class _Registry:
+ claim_kwargs = None
- assert result["state"] == "cancelled"
- assert killed
+ def claim(self, _key, _transport, **kwargs):
+ self.claim_kwargs = kwargs
+ return True, "running"
+ def current_generation(self, _key):
+ return 1
-def test_model_cancel_registered_worker_requests_and_kills(monkeypatch):
- events = []
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
+
+ def register_process(self, _key, _proc):
+ return False
+
+ def peer_blob_hashes(self, _key):
+ return frozenset()
class _Proc:
+ pid = 123
+ stderr = None
+
def poll(self):
return None
def kill(self):
- events.append(("kill",))
+ return None
- class _Registry:
- def get_process(self, _key):
- return _Proc()
+ def wait(self, timeout = None):
+ return 0
- def request_cancel(self, key, _proc, generation):
- events.append(("request", key, generation))
- return True
+ registry = _Registry()
+ monkeypatch.setattr(downloads, "_registry", registry)
+ monkeypatch.setattr(downloads, "_spawn_download_worker", lambda *_args, **_kwargs: _Proc())
- def persist_cancel_for_key(self, *_args, **_kwargs):
- raise AssertionError(
- "cancel_worker must leave marker persistence to the exit watcher; "
- "an eager persist races a clean completion and strands a stale marker"
- )
+ asyncio.run(downloads.download_model_response(_download_body(gguf_variant = "Q4_K_M")))
- def get_job(self, _key):
- return SimpleNamespace(state = "running")
+ assert registry.claim_kwargs["blob_hashes"] == frozenset({"mainhash"})
+ assert registry.claim_kwargs["progress_blob_hashes"] == frozenset({"mainhash", "mmprojhash"})
+ assert registry.claim_kwargs["completed_baseline_bytes"] == 30
- monkeypatch.setattr(downloads, "_registry", _Registry())
- monkeypatch.setattr(
- downloads,
- "resolve_cached_repo_id_case",
- lambda repo_id, **_kwargs: repo_id,
- )
- result = asyncio.run(
- downloads.cancel_download_model_response(
- SimpleNamespace(repo_id = "Org/Model", gguf_variant = "Q4_K_M", generation = 7)
- )
- )
-
- assert result == {
- "job_key": downloads._download_job_key("Org/Model", "Q4_K_M"),
- "state": "cancelling",
- }
- assert events == [
- ("request", downloads._download_job_key("Org/Model", "Q4_K_M"), 7),
- ("kill",),
- ]
-
-
-def test_model_download_watcher_invalidates_hf_cache_scan(monkeypatch):
- invalidated = []
-
- class _Registry:
- def claim(self, *_args, **_kwargs):
- return True, "running"
-
- def current_generation(self, _key):
- return 1
-
- def register_process(self, _key, _proc):
- return True
-
- def get_job(self, _key):
- return SimpleNamespace(state = "complete", error = None)
-
- class _ImmediateThread:
- def __init__(self, *, target, **_kwargs):
- self._target = target
-
- def start(self):
- self._target()
-
- monkeypatch.setattr(downloads, "_registry", _Registry())
- monkeypatch.setattr(
- downloads,
- "resolve_cached_repo_id_case",
- lambda repo_id, **_kwargs: repo_id,
- )
- monkeypatch.setattr(
- downloads.download_registry,
- "download_transport_unavailable_reason",
- lambda _transport: None,
- )
- monkeypatch.setattr(
- downloads.download_lifecycle,
- "finalize_worker_exit",
- lambda *_args, **_kwargs: None,
- )
- monkeypatch.setattr(
- downloads,
- "_spawn_download_worker",
- lambda *_args, **_kwargs: object(),
- )
- monkeypatch.setattr(downloads.download_lifecycle.threading, "Thread", _ImmediateThread)
- monkeypatch.setattr(
- downloads.hf_cache_scan,
- "invalidate_hf_cache_scans",
- lambda: invalidated.append(True),
- )
-
- async def _inline_to_thread(func, *args, **kwargs):
- return func(*args, **kwargs)
-
- monkeypatch.setattr(downloads.asyncio, "to_thread", _inline_to_thread)
-
- result = asyncio.run(downloads.download_model_response(_download_body()))
-
- assert result["accepted"] is True
- assert invalidated == [True]
-
-
-def test_two_concurrent_same_repo_variants_both_complete(monkeypatch, tmp_path):
- # End-to-end proof that two GGUF variants of ONE repo download concurrently
- # without cancelling each other, with real registry/finalize/subprocess/watch
- # threads exercising the claim gate, register, finalize funnel, and
- # classify_exit under true concurrency.
- import subprocess
- import time
+def test_gguf_model_download_skips_completed_baseline_for_variant_resume_state(
+ monkeypatch, tmp_path
+):
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- monkeypatch.setattr(
- downloads,
- "_registry",
- download_registry.DownloadRegistry(),
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ [
+ download_manifest.ExpectedFile(
+ path = "model-Q4_K_M.gguf",
+ size = 100,
+ sha256 = "mainhash",
+ )
+ ],
+ "http",
)
monkeypatch.setattr(
downloads,
"resolve_cached_repo_id_case",
- lambda repo_id, **_k: repo_id,
- )
- monkeypatch.setattr(
- downloads.download_registry,
- "download_transport_unavailable_reason",
- lambda _transport: None,
+ lambda repo_id, repo_type = "model": repo_id,
)
- # Per-variant blob hashes (distinct main shard, shared mmproj companion).
monkeypatch.setattr(
downloads.gguf_variants,
"gguf_variant_blob_hashes",
- lambda _repo, variant, _token = None, include_companions = True, **_k: (
- frozenset({f"{variant.lower()}-main", "shared-mmproj"})
- if include_companions
- else frozenset({f"{variant.lower()}-main"})
+ lambda _repo, _variant, _token = None, include_companions = True, **_kwargs: (
+ frozenset({"mainhash", "mmprojhash"}) if include_companions else frozenset({"mainhash"})
),
)
monkeypatch.setattr(
downloads.download_registry,
"completed_blob_bytes",
- lambda *_a, **_k: 0,
- )
- monkeypatch.setattr(
- downloads.hf_cache_scan,
- "invalidate_hf_cache_scans",
- lambda: None,
+ lambda *_args, **_kwargs: 30,
)
- # Real subprocess that exits 0 immediately, with a stderr pipe to drain.
- spawned: list[subprocess.Popen] = []
- def _fake_spawn(*_args, **_kwargs):
- proc = subprocess.Popen(
- [sys.executable, "-c", "import sys; sys.exit(0)"],
- stderr = subprocess.PIPE,
- )
- spawned.append(proc)
- return proc
+ class _Registry:
+ claim_kwargs = None
- monkeypatch.setattr(downloads, "_spawn_download_worker", _fake_spawn)
+ def claim(self, _key, _transport, **kwargs):
+ self.claim_kwargs = kwargs
+ return True, "running"
- async def _run_both():
- return await asyncio.gather(
- downloads.download_model_response(_download_body(gguf_variant = "Q4_K_M")),
- downloads.download_model_response(_download_body(gguf_variant = "Q8_0")),
- )
+ def current_generation(self, _key):
+ return 1
- results = asyncio.run(_run_both())
- assert all(r["accepted"] is True for r in results), results
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
- registry = downloads._registry
- key_q4 = downloads._download_job_key("Org/Model", "Q4_K_M")
- key_q8 = downloads._download_job_key("Org/Model", "Q8_0")
- deadline = time.monotonic() + 10.0
- while time.monotonic() < deadline:
- s4 = registry.get_job(key_q4).state
- s8 = registry.get_job(key_q8).state
- if s4 in download_registry.TERMINAL_STATES and s8 in download_registry.TERMINAL_STATES:
- break
- time.sleep(0.02)
+ def register_process(self, _key, _proc):
+ return False
- for p in spawned:
- try:
- p.wait(timeout = 5)
- except Exception:
- pass
+ def peer_blob_hashes(self, _key):
+ return frozenset()
- assert registry.get_job(key_q4).state == "complete"
- assert registry.get_job(key_q8).state == "complete"
+ class _Proc:
+ pid = 123
+ stderr = None
+ def poll(self):
+ return None
-def test_download_registry_factories_reuse_service_singletons():
- registry_module = downloads.download_registry
- before_count = len(registry_module._REGISTRIES)
+ def kill(self):
+ return None
- assert registry_module.get_models_registry() is downloads.registry
- assert registry_module.get_models_registry() is downloads.registry
- assert registry_module.get_datasets_registry() is dataset_downloads.registry
- assert registry_module.get_datasets_registry() is dataset_downloads.registry
- assert len(registry_module._REGISTRIES) == before_count
+ def wait(self, timeout = None):
+ return 0
+ registry = _Registry()
+ monkeypatch.setattr(downloads, "_registry", registry)
+ monkeypatch.setattr(downloads, "_spawn_download_worker", lambda *_args, **_kwargs: _Proc())
-def test_hub_hf_token_header_uses_namespaced_header_only():
- assert get_hf_token("new-token") == "new-token"
- assert get_hf_token(None) is None
+ asyncio.run(downloads.download_model_response(_download_body(gguf_variant = "Q4_K_M")))
+ assert registry.claim_kwargs["completed_baseline_bytes"] == 0
-def test_scan_folder_rejects_credential_directories(tmp_path):
- sensitive_dir = tmp_path / ".ssh" / "models"
- sensitive_dir.mkdir(parents = True)
- with pytest.raises(ValueError, match = "Credential or configuration"):
- scan_folders.add_scan_folder(str(sensitive_dir))
+def test_model_idle_status_uses_cancel_marker_after_restart(monkeypatch, tmp_path):
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+ monkeypatch.setattr(downloads, "_registry", download_registry.DownloadRegistry())
+ assert download_manifest.write_cancel_marker("model", "Owner/Repo", "Q4_K_M", "http")
+ status = asyncio.run(downloads.get_download_status_response("owner/repo", "Q4_K_M"))
-def _build_variant_cache_repo(repo_dir, blob_specs, snapshot_links):
- """Build a HF cache repo dir with blobs + snapshot symlinks for the
- per-variant deletion path. blob_specs: {blob_name: bytes_payload};
- snapshot_links: list of (revision, filename, blob_name)."""
- blobs_dir = repo_dir / "blobs"
- blobs_dir.mkdir(parents = True)
- for blob_name, payload in blob_specs.items():
- (blobs_dir / blob_name).write_bytes(payload)
+ assert status.state == "cancelled"
+ assert status.error is None
- files = []
- for revision, filename, blob_name in snapshot_links:
- snap_dir = repo_dir / "snapshots" / revision
- snap_dir.mkdir(parents = True, exist_ok = True)
- blob = blobs_dir / blob_name
- link = snap_dir / filename
- link.symlink_to(blob)
- files.append(
- SimpleNamespace(
- file_name = filename,
- file_path = str(link),
- blob_path = str(blob),
- size_on_disk = blob.stat().st_size,
- )
- )
- repo = SimpleNamespace(
- repo_id = "Org/Repo-GGUF",
- repo_type = "model",
- repo_path = repo_dir,
- revisions = [SimpleNamespace(commit_hash = "rev1", files = files)],
- )
- return repo
+def test_shutdown_kills_all_workers_before_shared_deadline_reap(monkeypatch):
+ events = []
+ now = [100.0]
-def _patch_variant_delete_side_effects(monkeypatch, hub_cache = None):
- monkeypatch.setattr(
- deletion.download_manifest,
- "purge_state",
- lambda *_args, **_kwargs: False,
- )
- # The repo under test lives in this cache; make it the active one so the
- # delete scopes to it (default target root is the active hub cache).
- if hub_cache is not None:
- monkeypatch.setattr(
- "utils.hf_cache_settings.get_hf_cache_paths",
- lambda: SimpleNamespace(hub_cache = hub_cache),
- )
+ class _Proc:
+ def __init__(self, name):
+ self.name = name
+ def poll(self):
+ return None
-def test_snapshot_progress_filters_stale_blobs(monkeypatch, tmp_path):
- """Exclude superseded-revision blobs; count an in-progress blob only when its
- hash belongs to the target."""
- entry = tmp_path / "datasets--Org--Data"
- blobs = entry / "blobs"
- blobs.mkdir(parents = True)
- (blobs / "keep1").write_bytes(b"a" * 100)
- (blobs / "stale").write_bytes(b"b" * 500)
- (blobs / "keep2.incomplete").write_bytes(b"c" * 40)
+ def kill(self):
+ events.append(("kill", self.name))
- monkeypatch.setattr(
- snapshot_progress,
- "preferred_repo_cache_dirs",
- lambda _repo_type, _repo_id, force_active = False: [entry],
- )
+ def wait(self, timeout):
+ events.append(("wait", self.name, timeout))
+ now[0] += 7.0
- result = snapshot_progress.compute_snapshot_progress(
+ registry = download_registry.DownloadRegistry()
+ proc_a = _Proc("a")
+ proc_b = _Proc("b")
+ registry.claim(
+ "Org/A",
+ download_registry.TRANSPORT_HTTP,
repo_type = "dataset",
- repo_id = "Org/Data",
- job_key = "org/data",
- expected_bytes = 0,
- hf_token = None,
- registry = SimpleNamespace(
- get_job = lambda _key: SimpleNamespace(state = "running"),
- ),
- metadata_resolver = lambda _repo_id, _hf_token: (
- 140,
- frozenset({"keep1", "keep2"}),
- ),
+ repo_id = "Org/A",
+ )
+ registry.claim(
+ "Org/B",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/B",
)
+ assert registry.register_process("org/a", proc_a)
+ assert registry.register_process("org/b", proc_b)
+ monkeypatch.setattr(
+ download_registry,
+ "persist_cancel_marker",
+ lambda *args, **kwargs: events.append(("marker", args[1])),
+ )
+ monkeypatch.setattr(download_registry.time, "monotonic", lambda: now[0])
- assert result["completed_bytes"] == 100
- assert result["downloaded_bytes"] == 140
- assert result["complete_on_disk"] is False
- assert result["expected_bytes"] == 140
+ registry.terminate_all("dataset download")
+ assert events == [
+ ("kill", "a"),
+ ("kill", "b"),
+ ("wait", "a", 10.0),
+ ("marker", "Org/A"),
+ ("wait", "b", 3.0),
+ ("marker", "Org/B"),
+ ]
-def test_snapshot_progress_confirms_complete_only_with_verified_snapshot(monkeypatch, tmp_path):
- entry = tmp_path / "models--Org--Model"
- blobs = entry / "blobs"
- snap = entry / "snapshots" / "rev0"
- blobs.mkdir(parents = True)
- snap.mkdir(parents = True)
- (blobs / "keep1").write_bytes(b"a" * 100)
- (snap / "model.safetensors").write_bytes(b"a" * 100)
- monkeypatch.setattr(
- snapshot_progress,
- "preferred_repo_cache_dirs",
- lambda _repo_type, _repo_id, force_active = False: [entry],
+def test_shutdown_skips_marker_for_worker_that_exits_cleanly(monkeypatch):
+ markers = []
+
+ class _Proc:
+ def __init__(self, final_rc):
+ self._final_rc = final_rc
+ self._exited = False
+
+ def poll(self):
+ return self._final_rc if self._exited else None
+
+ def kill(self):
+ pass
+
+ def wait(self, timeout):
+ self._exited = True
+
+ registry = download_registry.DownloadRegistry()
+ clean = _Proc(0)
+ interrupted = _Proc(-9)
+ registry.claim(
+ "Org/Clean",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/Clean",
+ )
+ registry.claim(
+ "Org/Cut",
+ download_registry.TRANSPORT_HTTP,
+ repo_type = "dataset",
+ repo_id = "Org/Cut",
)
+ assert registry.register_process("org/clean", clean)
+ assert registry.register_process("org/cut", interrupted)
monkeypatch.setattr(
- snapshot_progress.download_manifest,
- "has_cancel_marker",
- lambda *_args, **_kwargs: False,
+ download_registry,
+ "persist_cancel_marker",
+ lambda *args, **kwargs: markers.append(args[1]),
)
+
+ registry.terminate_all("dataset download")
+
+ assert markers == ["Org/Cut"]
+
+
+def test_orphan_reaper_uses_worker_cache_root_after_setting_changes(monkeypatch, tmp_path):
+ workers = tmp_path / "workers"
+ workers.mkdir()
+ cache_a = tmp_path / "cache-a" / "hub"
+ cache_b = tmp_path / "cache-b" / "hub"
+ partial = cache_a / "models--Org--Model" / "blobs" / "abc.incomplete"
+ partial.parent.mkdir(parents = True)
+ partial.write_bytes(b"partial")
+ cache_b.mkdir(parents = True)
+ monkeypatch.setattr(state_dir, "workers_dir", lambda: workers)
+ monkeypatch.setattr(download_registry, "_process_alive", lambda _pid: False)
monkeypatch.setattr(
- snapshot_progress.download_manifest,
- "read_manifest",
- lambda *_args, **_kwargs: SimpleNamespace(),
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = cache_b),
)
+ markers = []
monkeypatch.setattr(
- snapshot_progress.download_manifest,
- "verify_against_disk",
- lambda *_args, **_kwargs: SimpleNamespace(ok = True),
+ download_registry,
+ "persist_cancel_marker",
+ lambda *args, **kwargs: markers.append(args),
)
-
- result = snapshot_progress.compute_snapshot_progress(
+ metadata = download_registry.DownloadMetadata(
repo_type = "model",
repo_id = "Org/Model",
- job_key = "org/model::",
- expected_bytes = 100,
- hf_token = None,
- registry = SimpleNamespace(
- get_job = lambda _key: SimpleNamespace(state = "idle"),
- ),
- metadata_resolver = lambda _repo_id, _hf_token: (
- 100,
- frozenset({"keep1"}),
- ),
+ variant = None,
+ transport = download_registry.TRANSPORT_HTTP,
+ hub_cache = str(cache_a),
+ xet_cache = str(tmp_path / "cache-a" / "xet"),
)
+ download_registry.write_worker_breadcrumb("org/model", 1234, metadata)
+ [breadcrumb] = list(workers.iterdir())
+ payload = json.loads(breadcrumb.read_text(encoding = "utf-8"))
+ assert payload["hub_cache"] == str(cache_a)
+ assert payload["xet_cache"] == str(tmp_path / "cache-a" / "xet")
- assert result["completed_bytes"] == 100
- assert result["complete_on_disk"] is True
+ download_registry.reap_orphan_workers()
+ assert markers == [("model", "Org/Model", None, "http")]
+ assert list(workers.iterdir()) == []
-def test_expected_files_from_snapshot_dir_records_relative_paths_and_sizes(tmp_path):
- snap = tmp_path / "snapshots" / "rev0"
- (snap / "nested").mkdir(parents = True)
- (snap / "model.safetensors").write_bytes(b"a" * 12)
- (snap / "nested" / "config.json").write_bytes(b"b" * 3)
- files = download_manifest.expected_files_from_snapshot_dir(snap)
+def test_model_claim_register_cancel_uses_registry_marker_owner(monkeypatch):
+ killed = []
- by_path = {f.path: f for f in files}
- assert by_path["model.safetensors"].size == 12
- assert by_path["nested/config.json"].size == 3
- assert all(f.sha256 is None for f in files)
+ class _Registry:
+ def claim(self, *_args, **_kwargs):
+ return True, "running"
+ def current_generation(self, _key):
+ return 1
-def test_snapshot_progress_complete_with_manifest_synthesized_from_disk(monkeypatch, tmp_path):
- """A finished snapshot whose only manifest was synthesized from on-disk files
- still verifies as complete, so a refresh finalizes it instead of capping at
- 99% and evicting it as gone."""
- entry = tmp_path / "models--Org--Model"
- blobs = entry / "blobs"
- snap = entry / "snapshots" / "rev0"
- blobs.mkdir(parents = True)
- snap.mkdir(parents = True)
- (blobs / "keep1").write_bytes(b"a" * 100)
- (snap / "model.safetensors").write_bytes(b"a" * 100)
+ def register_process(self, _key, _proc):
+ return False
- synthesized = download_manifest.expected_files_from_snapshot_dir(snap)
- manifest = download_manifest.Manifest(
- repo_type = "model",
- repo_id = "Org/Model",
- variant = None,
- started_at = "",
- expected_files = tuple(synthesized),
- )
+ def persist_cancel_for_key(self, *_args, **_kwargs):
+ raise AssertionError("register_process owns pending-cancel markers")
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "cancelled", error = None)
+ monkeypatch.setattr(downloads, "_registry", _Registry())
monkeypatch.setattr(
- snapshot_progress,
- "preferred_repo_cache_dirs",
- lambda _repo_type, _repo_id, force_active = False: [entry],
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
)
monkeypatch.setattr(
- snapshot_progress.download_manifest,
- "has_cancel_marker",
- lambda *_args, **_kwargs: False,
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
)
monkeypatch.setattr(
- snapshot_progress.download_manifest,
- "read_manifest",
- lambda *_args, **_kwargs: manifest,
+ downloads,
+ "_spawn_download_worker",
+ lambda *_args, **_kwargs: object(),
)
-
- result = snapshot_progress.compute_snapshot_progress(
- repo_type = "model",
- repo_id = "Org/Model",
- job_key = "org/model::",
- expected_bytes = 100,
- hf_token = None,
- registry = SimpleNamespace(
- get_job = lambda _key: SimpleNamespace(state = "idle"),
- ),
- metadata_resolver = lambda _repo_id, _hf_token: (
- 100,
- frozenset({"keep1"}),
- ),
+ monkeypatch.setattr(
+ downloads.download_lifecycle,
+ "kill_and_reap_process",
+ lambda proc, **_kwargs: killed.append(proc),
)
- assert result["complete_on_disk"] is True
- assert result["progress"] == 1.0
+ result = asyncio.run(downloads.download_model_response(_download_body()))
+ assert result["state"] == "cancelled"
+ assert killed
-def test_delete_variant_keeps_blob_shared_with_other_snapshot(monkeypatch, tmp_path):
- """A blob still referenced by a non-target snapshot symlink survives so that
- symlink doesn't dangle (which the scanner reports as partial)."""
- repo_dir = tmp_path / "models--Org--Repo-GGUF"
- repo = _build_variant_cache_repo(
- repo_dir,
- blob_specs = {"sharedblob": b"x" * 200, "q8blob": b"y" * 300},
- snapshot_links = [
- ("rev1", "model-Q4_K_M.gguf", "sharedblob"),
- ("rev1", "model-Q8_0.gguf", "q8blob"),
- # An unrelated file that happens to share Q4's blob content.
- ("rev1", "extra-copy.gguf", "sharedblob"),
- ],
- )
- monkeypatch.setattr(
- deletion.cache_inventory,
- "all_hf_cache_scans",
- lambda: [SimpleNamespace(repos = [repo])],
- )
- _patch_variant_delete_side_effects(monkeypatch, tmp_path)
- result = deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+def test_model_cancel_registered_worker_requests_and_kills(monkeypatch):
+ events = []
- assert result["status"] == "deleted"
- # Q4 snapshot link gone, but its blob survives (extra-copy still links it).
- assert not (repo_dir / "snapshots" / "rev1" / "model-Q4_K_M.gguf").exists()
- assert (repo_dir / "blobs" / "sharedblob").exists()
- extra = repo_dir / "snapshots" / "rev1" / "extra-copy.gguf"
- assert extra.is_symlink() and extra.exists() # not dangling
+ class _Proc:
+ def poll(self):
+ return None
+ def kill(self):
+ events.append(("kill",))
-def test_delete_variant_unlinks_unshared_blob(monkeypatch, tmp_path):
- repo_dir = tmp_path / "models--Org--Repo-GGUF"
- repo = _build_variant_cache_repo(
- repo_dir,
- blob_specs = {"q4blob": b"x" * 200, "q8blob": b"y" * 300},
- snapshot_links = [
- ("rev1", "model-Q4_K_M.gguf", "q4blob"),
- ("rev1", "model-Q8_0.gguf", "q8blob"),
- ],
- )
- monkeypatch.setattr(
- deletion.cache_inventory,
- "all_hf_cache_scans",
- lambda: [SimpleNamespace(repos = [repo])],
- )
- _patch_variant_delete_side_effects(monkeypatch, tmp_path)
+ class _Registry:
+ def get_process(self, _key):
+ return _Proc()
- result = deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+ def request_cancel(self, key, _proc, generation):
+ events.append(("request", key, generation))
+ return True
- assert result["status"] == "deleted"
- assert not (repo_dir / "blobs" / "q4blob").exists()
- # Untouched sibling variant remains fully intact.
- assert (repo_dir / "blobs" / "q8blob").exists()
- q8 = repo_dir / "snapshots" / "rev1" / "model-Q8_0.gguf"
- assert q8.is_symlink() and q8.exists()
+ def persist_cancel_for_key(self, *_args, **_kwargs):
+ raise AssertionError(
+ "cancel_worker must leave marker persistence to the exit watcher; "
+ "an eager persist races a clean completion and strands a stale marker"
+ )
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running")
-def test_delete_variant_surfaces_locked_file_as_conflict(monkeypatch, tmp_path):
- """A blob unlink that fails (e.g. a Windows file lock on a loaded model)
- must raise a clear 409, not report a misleading success."""
- repo_dir = tmp_path / "models--Org--Repo-GGUF"
- repo = _build_variant_cache_repo(
- repo_dir,
- blob_specs = {"lockedblob": b"x" * 200},
- snapshot_links = [("rev1", "model-Q4_K_M.gguf", "lockedblob")],
- )
+ monkeypatch.setattr(downloads, "_registry", _Registry())
monkeypatch.setattr(
- deletion.cache_inventory,
- "all_hf_cache_scans",
- lambda: [SimpleNamespace(repos = [repo])],
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
)
- _patch_variant_delete_side_effects(monkeypatch, tmp_path)
- real_unlink = Path.unlink
+ result = asyncio.run(
+ downloads.cancel_download_model_response(
+ SimpleNamespace(repo_id = "Org/Model", gguf_variant = "Q4_K_M", generation = 7)
+ )
+ )
- def fake_unlink(self, *args, **kwargs):
- if self.name == "lockedblob":
- raise PermissionError("file in use")
- return real_unlink(self, *args, **kwargs)
+ assert result == {
+ "job_key": downloads._download_job_key("Org/Model", "Q4_K_M"),
+ "state": "cancelling",
+ }
+ assert events == [
+ ("request", downloads._download_job_key("Org/Model", "Q4_K_M"), 7),
+ ("kill",),
+ ]
- monkeypatch.setattr(Path, "unlink", fake_unlink)
- with pytest.raises(HTTPException) as exc_info:
- deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+def test_model_download_watcher_invalidates_hf_cache_scan(monkeypatch):
+ invalidated = []
- assert exc_info.value.status_code == 409
+ class _Registry:
+ def claim(self, *_args, **_kwargs):
+ return True, "running"
+ def current_generation(self, _key):
+ return 1
-def test_download_snapshot_writes_manifest_for_xet(monkeypatch, tmp_path):
- written = []
- verified = []
+ def register_process(self, _key, _proc):
+ return True
+
+ def get_job(self, _key):
+ return SimpleNamespace(state = "complete", error = None)
+
+ class _ImmediateThread:
+ def __init__(self, *, target, **_kwargs):
+ self._target = target
+
+ def start(self):
+ self._target()
+ monkeypatch.setattr(downloads, "_registry", _Registry())
monkeypatch.setattr(
- hf_download,
- "_model_info_with_retry",
- lambda *_args, **_kwargs: SimpleNamespace(
- siblings = [SimpleNamespace(rfilename = "config.json", size = 12)]
- ),
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
)
monkeypatch.setattr(
- hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
)
monkeypatch.setattr(
- download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ downloads.download_lifecycle,
+ "finalize_worker_exit",
+ lambda *_args, **_kwargs: None,
)
- monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
monkeypatch.setattr(
- download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ downloads,
+ "_spawn_download_worker",
+ lambda *_args, **_kwargs: object(),
)
- monkeypatch.setitem(
- sys.modules,
- "huggingface_hub",
- SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ monkeypatch.setattr(downloads.download_lifecycle.threading, "Thread", _ImmediateThread)
+ monkeypatch.setattr(
+ downloads.hf_cache_scan,
+ "invalidate_hf_cache_scans",
+ lambda: invalidated.append(True),
)
- hf_download._download_snapshot("Org/Model", None, "xet")
+ async def _inline_to_thread(func, *args, **kwargs):
+ return func(*args, **kwargs)
- assert written, "XET snapshot download must still record a manifest"
- assert written[0][0:3] == ("model", "Org/Model", None)
- assert written[0][3][0].path == "config.json"
- assert verified == [("model", "Org/Model", None, str(tmp_path))]
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _inline_to_thread)
+ result = asyncio.run(downloads.download_model_response(_download_body()))
-def test_download_gguf_variant_writes_manifest_for_xet(monkeypatch, tmp_path):
- written = []
- verified = []
+ assert result["accepted"] is True
+ assert invalidated == [True]
+
+def test_two_concurrent_same_repo_variants_both_complete(monkeypatch, tmp_path):
+ # End-to-end proof that two GGUF variants of ONE repo download concurrently
+ # without cancelling each other, with real registry/finalize/subprocess/watch
+ # threads exercising the claim gate, register, finalize funnel, and
+ # classify_exit under true concurrency.
+ import subprocess
+ import time
+
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
monkeypatch.setattr(
- hf_download,
- "_model_info_with_retry",
- lambda *_args, **_kwargs: SimpleNamespace(
- siblings = [_sibling("model-Q4_K_M.gguf", 10, "main")]
- ),
- )
- monkeypatch.setattr(
- hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ downloads,
+ "_registry",
+ download_registry.DownloadRegistry(),
)
monkeypatch.setattr(
- download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_k: repo_id,
)
- monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
monkeypatch.setattr(
- download_manifest, "write_manifest", lambda *args: written.append(args) or True
- )
- monkeypatch.setitem(
- sys.modules,
- "huggingface_hub",
- SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ downloads.download_registry,
+ "download_transport_unavailable_reason",
+ lambda _transport: None,
)
-
- hf_download._download_gguf_variant("Org/Model", "Q4_K_M", None, "xet")
-
- assert written, "XET GGUF variant download must still record a manifest"
- assert written[0][0:3] == ("model", "Org/Model", "Q4_K_M")
- assert written[0][3][0].path == "model-Q4_K_M.gguf"
- assert verified == [("model", "Org/Model", "Q4_K_M", str(tmp_path))]
-
-
-def test_download_dataset_writes_manifest_for_xet(monkeypatch, tmp_path):
- written = []
- verified = []
- snapshot_calls = []
-
+ # Per-variant blob hashes (distinct main shard, shared mmproj companion).
monkeypatch.setattr(
- hf_download,
- "_dataset_info_with_retry",
- lambda *_args, **_kwargs: SimpleNamespace(
- sha = "dataset-commit",
- siblings = [SimpleNamespace(rfilename = "data.parquet", size = 30)],
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda _repo, variant, _token = None, include_companions = True, **_k: (
+ frozenset({f"{variant.lower()}-main", "shared-mmproj"})
+ if include_companions
+ else frozenset({f"{variant.lower()}-main"})
),
)
monkeypatch.setattr(
- hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
- )
- monkeypatch.setattr(
- download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ downloads.download_registry,
+ "completed_blob_bytes",
+ lambda *_a, **_k: 0,
)
- monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
monkeypatch.setattr(
- download_manifest,
- "write_manifest",
- lambda *args, **kwargs: written.append((args, kwargs)) or True,
- )
- monkeypatch.setitem(
- sys.modules,
- "huggingface_hub",
- SimpleNamespace(
- snapshot_download = (lambda **kwargs: snapshot_calls.append(kwargs) or str(tmp_path))
- ),
+ downloads.hf_cache_scan,
+ "invalidate_hf_cache_scans",
+ lambda: None,
)
+ # Real subprocess that exits 0 immediately, with a stderr pipe to drain.
+ spawned: list[subprocess.Popen] = []
+
+ def _fake_spawn(*_args, **_kwargs):
+ proc = subprocess.Popen(
+ [sys.executable, "-c", "import sys; sys.exit(0)"],
+ stderr = subprocess.PIPE,
+ )
+ spawned.append(proc)
+ return proc
+
+ monkeypatch.setattr(downloads, "_spawn_download_worker", _fake_spawn)
+
+ async def _run_both():
+ return await asyncio.gather(
+ downloads.download_model_response(_download_body(gguf_variant = "Q4_K_M")),
+ downloads.download_model_response(_download_body(gguf_variant = "Q8_0")),
+ )
+
+ results = asyncio.run(_run_both())
+ assert all(r["accepted"] is True for r in results), results
+
+ registry = downloads._registry
+ key_q4 = downloads._download_job_key("Org/Model", "Q4_K_M")
+ key_q8 = downloads._download_job_key("Org/Model", "Q8_0")
+ deadline = time.monotonic() + 10.0
+ while time.monotonic() < deadline:
+ s4 = registry.get_job(key_q4).state
+ s8 = registry.get_job(key_q8).state
+ if s4 in download_registry.TERMINAL_STATES and s8 in download_registry.TERMINAL_STATES:
+ break
+ time.sleep(0.02)
+
+ for p in spawned:
+ try:
+ p.wait(timeout = 5)
+ except Exception:
+ pass
+
+ assert registry.get_job(key_q4).state == "complete"
+ assert registry.get_job(key_q8).state == "complete"
+
+
+def test_download_registry_factories_reuse_service_singletons():
+ registry_module = downloads.download_registry
+ before_count = len(registry_module._REGISTRIES)
+
+ assert registry_module.get_models_registry() is downloads.registry
+ assert registry_module.get_models_registry() is downloads.registry
+ assert registry_module.get_datasets_registry() is dataset_downloads.registry
+ assert registry_module.get_datasets_registry() is dataset_downloads.registry
+ assert len(registry_module._REGISTRIES) == before_count
+
+
+def test_hub_hf_token_header_uses_namespaced_header_only():
+ assert get_hf_token("new-token") == "new-token"
+ assert get_hf_token(None) is None
+
+
+def test_scan_folder_rejects_credential_directories(tmp_path):
+ sensitive_dir = tmp_path / ".ssh" / "models"
+ sensitive_dir.mkdir(parents = True)
+
+ with pytest.raises(ValueError, match = "Credential or configuration"):
+ scan_folders.add_scan_folder(str(sensitive_dir))
+
+
+def _build_variant_cache_repo(repo_dir, blob_specs, snapshot_links):
+ """Build a HF cache repo dir with blobs + snapshot symlinks for the
+ per-variant deletion path. blob_specs: {blob_name: bytes_payload};
+ snapshot_links: list of (revision, filename, blob_name)."""
+ blobs_dir = repo_dir / "blobs"
+ blobs_dir.mkdir(parents = True)
+ for blob_name, payload in blob_specs.items():
+ (blobs_dir / blob_name).write_bytes(payload)
+
+ files = []
+ for revision, filename, blob_name in snapshot_links:
+ snap_dir = repo_dir / "snapshots" / revision
+ snap_dir.mkdir(parents = True, exist_ok = True)
+ blob = blobs_dir / blob_name
+ link = snap_dir / filename
+ link.symlink_to(blob)
+ files.append(
+ SimpleNamespace(
+ file_name = filename,
+ file_path = str(link),
+ blob_path = str(blob),
+ size_on_disk = blob.stat().st_size,
+ )
+ )
+ repo = SimpleNamespace(
+ repo_id = "Org/Repo-GGUF",
+ repo_type = "model",
+ repo_path = repo_dir,
+ revisions = [SimpleNamespace(commit_hash = "rev1", files = files)],
+ )
+ return repo
+
+
+def _patch_variant_delete_side_effects(monkeypatch, hub_cache = None):
+ monkeypatch.setattr(
+ deletion.download_manifest,
+ "purge_state",
+ lambda *_args, **_kwargs: False,
+ )
+ # The repo under test lives in this cache; make it the active one so the
+ # delete scopes to it (default target root is the active hub cache).
+ if hub_cache is not None:
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = hub_cache),
+ )
+
+
+def test_snapshot_progress_filters_stale_blobs(monkeypatch, tmp_path):
+ """Exclude superseded-revision blobs; count an in-progress blob only when its
+ hash belongs to the target."""
+ entry = tmp_path / "datasets--Org--Data"
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "keep1").write_bytes(b"a" * 100)
+ (blobs / "stale").write_bytes(b"b" * 500)
+ (blobs / "keep2.incomplete").write_bytes(b"c" * 40)
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False, **kw: [entry],
+ )
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "dataset",
+ repo_id = "Org/Data",
+ job_key = "org/data",
+ expected_bytes = 0,
+ hf_token = None,
+ registry = SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "running"),
+ ),
+ metadata_resolver = lambda _repo_id, _hf_token: (
+ 140,
+ frozenset({"keep1", "keep2"}),
+ ),
+ )
+
+ assert result["completed_bytes"] == 100
+ assert result["downloaded_bytes"] == 140
+ assert result["complete_on_disk"] is False
+ assert result["expected_bytes"] == 140
+
+
+def test_snapshot_progress_confirms_complete_only_with_verified_snapshot(monkeypatch, tmp_path):
+ entry = tmp_path / "models--Org--Model"
+ blobs = entry / "blobs"
+ snap = entry / "snapshots" / "rev0"
+ blobs.mkdir(parents = True)
+ snap.mkdir(parents = True)
+ (blobs / "keep1").write_bytes(b"a" * 100)
+ (snap / "model.safetensors").write_bytes(b"a" * 100)
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False, **kw: [entry],
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "has_cancel_marker",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "read_manifest",
+ lambda *_args, **_kwargs: SimpleNamespace(),
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "verify_against_disk",
+ lambda *_args, **_kwargs: SimpleNamespace(ok = True),
+ )
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "Org/Model",
+ job_key = "org/model::",
+ expected_bytes = 100,
+ hf_token = None,
+ registry = SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "idle"),
+ ),
+ metadata_resolver = lambda _repo_id, _hf_token: (
+ 100,
+ frozenset({"keep1"}),
+ ),
+ )
+
+ assert result["completed_bytes"] == 100
+ assert result["complete_on_disk"] is True
+
+
+def test_expected_files_from_snapshot_dir_records_relative_paths_and_sizes(tmp_path):
+ snap = tmp_path / "snapshots" / "rev0"
+ (snap / "nested").mkdir(parents = True)
+ (snap / "model.safetensors").write_bytes(b"a" * 12)
+ (snap / "nested" / "config.json").write_bytes(b"b" * 3)
+
+ files = download_manifest.expected_files_from_snapshot_dir(snap)
+
+ by_path = {f.path: f for f in files}
+ assert by_path["model.safetensors"].size == 12
+ assert by_path["nested/config.json"].size == 3
+ assert all(f.sha256 is None for f in files)
+
+
+def test_snapshot_progress_complete_with_manifest_synthesized_from_disk(monkeypatch, tmp_path):
+ """A finished snapshot whose only manifest was synthesized from on-disk files
+ still verifies as complete, so a refresh finalizes it instead of capping at
+ 99% and evicting it as gone."""
+ entry = tmp_path / "models--Org--Model"
+ blobs = entry / "blobs"
+ snap = entry / "snapshots" / "rev0"
+ blobs.mkdir(parents = True)
+ snap.mkdir(parents = True)
+ (blobs / "keep1").write_bytes(b"a" * 100)
+ (snap / "model.safetensors").write_bytes(b"a" * 100)
+
+ synthesized = download_manifest.expected_files_from_snapshot_dir(snap)
+ manifest = download_manifest.Manifest(
+ repo_type = "model",
+ repo_id = "Org/Model",
+ variant = None,
+ started_at = "",
+ expected_files = tuple(synthesized),
+ )
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False, **kw: [entry],
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "has_cancel_marker",
+ lambda *_args, **_kwargs: False,
+ )
+ monkeypatch.setattr(
+ snapshot_progress.download_manifest,
+ "read_manifest",
+ lambda *_args, **_kwargs: manifest,
+ )
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "Org/Model",
+ job_key = "org/model::",
+ expected_bytes = 100,
+ hf_token = None,
+ registry = SimpleNamespace(
+ get_job = lambda _key: SimpleNamespace(state = "idle"),
+ ),
+ metadata_resolver = lambda _repo_id, _hf_token: (
+ 100,
+ frozenset({"keep1"}),
+ ),
+ )
+
+ assert result["complete_on_disk"] is True
+ assert result["progress"] == 1.0
+
+
+def test_a_shared_companion_alone_is_not_evidence_the_quant_is_here(tmp_path):
+ """mmproj and the MTP drafter are downloaded with every quant in a repo, so on their own
+ they say nothing about THIS one. Deleting a quant while a sibling kept its companion left
+ a positive byte reading for the deleted variant, and hydration reads any positive reading
+ as active: it re-adopts the stale job and blocks a fresh download of the same quant."""
+ snap = tmp_path / "snapshots" / "rev0"
+ snap.mkdir(parents = True)
+ (snap / "mmproj-F16.gguf").write_bytes(b"m" * 64)
+
+ def matcher(path, *, companions = True):
+ if path.endswith("Q4_K_M.gguf"):
+ return True
+ return companions and path.startswith("mmproj")
+
+ assert snapshot_progress._materialized_bytes(snap, matcher) == 0
+
+ # With the quant's own shard present, the companion counts again.
+ (snap / "model-Q4_K_M.gguf").write_bytes(b"q" * 32)
+ assert snapshot_progress._materialized_bytes(snap, matcher) == 96
+
+ # A matcher that does not take the keyword keeps the old behaviour.
+ assert snapshot_progress._materialized_bytes(snap, lambda path: path.startswith("mmproj")) == 64
+
+
+def test_a_root_that_will_not_resolve_is_a_scan_error(monkeypatch, tmp_path):
+ """A root that stats but will not resolve -- an intermittent network mount, a Windows
+ reparse point -- was dropped silently, so the scan answered "measured, no cache" and
+ hydration retired a download whose files may be entirely intact."""
+ from hub.utils import hf_cache_state as state
+
+ root = tmp_path / "hub"
+ root.mkdir()
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.known_hf_hub_caches", lambda: [root], raising = False
+ )
+ monkeypatch.setattr(state, "_safe_is_dir", lambda path, scan_errors = None: path == root)
+
+ real_resolve = Path.resolve
+
+ def _boom(self, *args, **kwargs):
+ if self == root:
+ raise OSError("network mount unavailable")
+ return real_resolve(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "resolve", _boom)
+ errors: list = []
+ assert state.hf_cache_roots(errors) == []
+ assert any(
+ "network mount unavailable" in str(e) for e in errors
+ ), "the unreadable root has to be reported, not silently dropped"
+
+
+def test_a_partial_scan_cannot_report_the_target_as_gone(monkeypatch, tmp_path):
+ """One unreadable root plus one readable one is a LOWER bound, not an absence.
+
+ The active root raising EACCES while a remembered cache still holds the repo dir (with a
+ sibling quant in it and nothing of ours) produced a non-null reading carrying
+ target_present False -- and hydration retires the job on that, though every byte of the
+ variant may sit in the root that could not be listed.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ (entry / "blobs").mkdir(parents = True)
+ (entry / "snapshots" / "rev0").mkdir(parents = True)
+
+ def _one_root_failed(
+ _repo_type,
+ _repo_id,
+ force_active = False,
+ scan_errors = None,
+ **kw,
+ ):
+ if scan_errors is not None:
+ scan_errors.append(PermissionError("denied"))
+ return [entry]
+
+ monkeypatch.setattr(snapshot_progress, "preferred_repo_cache_dirs", _one_root_failed)
+ monkeypatch.setattr(snapshot_progress.download_manifest, "read_manifest", lambda *a, **k: None)
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "Org/Model-GGUF",
+ job_key = "org/model-gguf::Q4_K_M",
+ expected_bytes = 100,
+ hf_token = None,
+ variant = "Q4_K_M",
+ variant_file_matcher = lambda name: name.endswith("Q4_K_M.gguf"),
+ registry = SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ metadata_resolver = lambda _repo_id, _hf_token: (100, frozenset({"blob-a"})),
+ expected_files_resolver = lambda _repo_id, _hf_token: (),
+ )
+
+ assert result["target_present"] is None, "absence needs a complete scan behind it"
+ assert result["cache_measured"] is False
+
+
+def test_a_complete_scan_still_reports_the_target_as_gone(monkeypatch, tmp_path):
+ # The same reading with no scan error keeps the positive-evidence verdict, or the fix
+ # above would simply disable the phantom-adoption guard it is protecting.
+ entry = tmp_path / "models--Org--Model-GGUF"
+ (entry / "blobs").mkdir(parents = True)
+ (entry / "snapshots" / "rev0").mkdir(parents = True)
+
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda _repo_type, _repo_id, force_active = False, **kw: [entry],
+ )
+ monkeypatch.setattr(snapshot_progress.download_manifest, "read_manifest", lambda *a, **k: None)
+
+ result = snapshot_progress.compute_snapshot_progress(
+ repo_type = "model",
+ repo_id = "Org/Model-GGUF",
+ job_key = "org/model-gguf::Q4_K_M",
+ expected_bytes = 100,
+ hf_token = None,
+ variant = "Q4_K_M",
+ variant_file_matcher = lambda name: name.endswith("Q4_K_M.gguf"),
+ registry = SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ metadata_resolver = lambda _repo_id, _hf_token: (100, frozenset({"blob-a"})),
+ expected_files_resolver = lambda _repo_id, _hf_token: (),
+ )
+
+ assert result["target_present"] is False
+ assert result["cache_measured"] is True
+
+
+def test_delete_variant_keeps_blob_shared_with_other_snapshot(monkeypatch, tmp_path):
+ """A blob still referenced by a non-target snapshot symlink survives so that
+ symlink doesn't dangle (which the scanner reports as partial)."""
+ repo_dir = tmp_path / "models--Org--Repo-GGUF"
+ repo = _build_variant_cache_repo(
+ repo_dir,
+ blob_specs = {"sharedblob": b"x" * 200, "q8blob": b"y" * 300},
+ snapshot_links = [
+ ("rev1", "model-Q4_K_M.gguf", "sharedblob"),
+ ("rev1", "model-Q8_0.gguf", "q8blob"),
+ # An unrelated file that happens to share Q4's blob content.
+ ("rev1", "extra-copy.gguf", "sharedblob"),
+ ],
+ )
+ monkeypatch.setattr(
+ deletion.cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ _patch_variant_delete_side_effects(monkeypatch, tmp_path)
+
+ result = deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+
+ assert result["status"] == "deleted"
+ # Q4 snapshot link gone, but its blob survives (extra-copy still links it).
+ assert not (repo_dir / "snapshots" / "rev1" / "model-Q4_K_M.gguf").exists()
+ assert (repo_dir / "blobs" / "sharedblob").exists()
+ extra = repo_dir / "snapshots" / "rev1" / "extra-copy.gguf"
+ assert extra.is_symlink() and extra.exists() # not dangling
+
+
+def test_delete_variant_unlinks_unshared_blob(monkeypatch, tmp_path):
+ repo_dir = tmp_path / "models--Org--Repo-GGUF"
+ repo = _build_variant_cache_repo(
+ repo_dir,
+ blob_specs = {"q4blob": b"x" * 200, "q8blob": b"y" * 300},
+ snapshot_links = [
+ ("rev1", "model-Q4_K_M.gguf", "q4blob"),
+ ("rev1", "model-Q8_0.gguf", "q8blob"),
+ ],
+ )
+ monkeypatch.setattr(
+ deletion.cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ _patch_variant_delete_side_effects(monkeypatch, tmp_path)
+
+ result = deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+
+ assert result["status"] == "deleted"
+ assert not (repo_dir / "blobs" / "q4blob").exists()
+ # Untouched sibling variant remains fully intact.
+ assert (repo_dir / "blobs" / "q8blob").exists()
+ q8 = repo_dir / "snapshots" / "rev1" / "model-Q8_0.gguf"
+ assert q8.is_symlink() and q8.exists()
+
+
+def test_delete_variant_surfaces_locked_file_as_conflict(monkeypatch, tmp_path):
+ """A blob unlink that fails (e.g. a Windows file lock on a loaded model)
+ must raise a clear 409, not report a misleading success."""
+ repo_dir = tmp_path / "models--Org--Repo-GGUF"
+ repo = _build_variant_cache_repo(
+ repo_dir,
+ blob_specs = {"lockedblob": b"x" * 200},
+ snapshot_links = [("rev1", "model-Q4_K_M.gguf", "lockedblob")],
+ )
+ monkeypatch.setattr(
+ deletion.cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = [repo])],
+ )
+ _patch_variant_delete_side_effects(monkeypatch, tmp_path)
+
+ real_unlink = Path.unlink
+
+ def fake_unlink(self, *args, **kwargs):
+ if self.name == "lockedblob":
+ raise PermissionError("file in use")
+ return real_unlink(self, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", fake_unlink)
+
+ with pytest.raises(HTTPException) as exc_info:
+ deletion._delete_cached_model_blocking("Org/Repo-GGUF", "Q4_K_M", None)
+
+ assert exc_info.value.status_code == 409
+
+
+def test_download_snapshot_writes_manifest_for_xet(monkeypatch, tmp_path):
+ written = []
+ verified = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [SimpleNamespace(rfilename = "config.json", size = 12)]
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ hf_download._download_snapshot("Org/Model", None, "xet")
+
+ assert written, "XET snapshot download must still record a manifest"
+ assert written[0][0:3] == ("model", "Org/Model", None)
+ assert written[0][3][0].path == "config.json"
+ assert verified == [("model", "Org/Model", None, str(tmp_path))]
+
+
+def test_download_gguf_variant_writes_manifest_for_xet(monkeypatch, tmp_path):
+ written = []
+ verified = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_model_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ siblings = [_sibling("model-Q4_K_M.gguf", 10, "main")]
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest, "write_manifest", lambda *args: written.append(args) or True
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(snapshot_download = lambda **_kwargs: str(tmp_path)),
+ )
+
+ hf_download._download_gguf_variant("Org/Model", "Q4_K_M", None, "xet")
+
+ assert written, "XET GGUF variant download must still record a manifest"
+ assert written[0][0:3] == ("model", "Org/Model", "Q4_K_M")
+ assert written[0][3][0].path == "model-Q4_K_M.gguf"
+ assert verified == [("model", "Org/Model", "Q4_K_M", str(tmp_path))]
+
+
+def test_download_dataset_writes_manifest_for_xet(monkeypatch, tmp_path):
+ written = []
+ verified = []
+ snapshot_calls = []
+
+ monkeypatch.setattr(
+ hf_download,
+ "_dataset_info_with_retry",
+ lambda *_args, **_kwargs: SimpleNamespace(
+ sha = "dataset-commit",
+ siblings = [SimpleNamespace(rfilename = "data.parquet", size = 30)],
+ ),
+ )
+ monkeypatch.setattr(
+ hf_download, "_verify_completed_download", lambda *args, **kwargs: verified.append(args)
+ )
+ monkeypatch.setattr(
+ download_registry, "prepare_cache_for_transport", lambda *_args, **_kwargs: 0
+ )
+ monkeypatch.setattr(download_manifest, "clear_cancel_marker", lambda *_args: None)
+ monkeypatch.setattr(
+ download_manifest,
+ "write_manifest",
+ lambda *args, **kwargs: written.append((args, kwargs)) or True,
+ )
+ monkeypatch.setitem(
+ sys.modules,
+ "huggingface_hub",
+ SimpleNamespace(
+ snapshot_download = (lambda **kwargs: snapshot_calls.append(kwargs) or str(tmp_path))
+ ),
+ )
+
+ hf_download._download_dataset("Org/Data", None, "xet")
+
+ assert written, "XET dataset download must still record a manifest"
+ assert written[0][0][0:3] == ("dataset", "Org/Data", None)
+ assert written[0][0][3][0].path == "data.parquet"
+ assert written[0][1] == {"commit_hash": "dataset-commit", "metadata_derived": True}
+ assert snapshot_calls == [
+ {
+ "repo_id": "Org/Data",
+ "token": False,
+ "repo_type": "dataset",
+ "max_workers": 1,
+ "revision": "dataset-commit",
+ }
+ ]
+ assert verified == [("dataset", "Org/Data", None, str(tmp_path))]
+
+
+def test_dataset_status_includes_generation(monkeypatch):
+ class _Registry:
+ def get_job(self, _key):
+ return SimpleNamespace(state = "running", error = None)
+
+ def current_generation(self, _key):
+ return 4
+
+ monkeypatch.setattr(dataset_downloads, "_registry", _Registry())
+ monkeypatch.setattr(
+ dataset_downloads,
+ "resolve_cached_repo_id_case",
+ lambda repo_id, **_kwargs: repo_id,
+ )
+
+ result = asyncio.run(dataset_downloads.get_dataset_download_status_response("Org/Data"))
+
+ assert result.state == "running"
+ assert result.generation == 4
+
+
+def _write_local_model(
+ root: Path,
+ name: str,
+ config: dict,
+ *,
+ modules: bool = False,
+) -> Path:
+ path = root / name
+ path.mkdir(parents = True)
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+ (path / "model.safetensors").write_bytes(b"\0" * 16)
+ if modules:
+ (path / "modules.json").write_text("[]", encoding = "utf-8")
+ return path
+
+
+ "config, modules, expected",
+ [
+ ({"architectures": ["LlamaForCausalLM"], "model_type": "llama"}, False, True),
+ ({"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"}, False, True),
+ ({"auto_map": {"AutoModelForCausalLM": "m.C"}, "model_type": "bert"}, False, True),
+ ({"architectures": ["BertModel"], "model_type": "bert"}, False, False),
+ ({"architectures": ["BertModel"], "model_type": "bert"}, True, False),
+ ({"architectures": ["RobertaForMaskedLM"], "model_type": "roberta"}, False, False),
+ ({"architectures": ["CLIPModel"], "model_type": "clip"}, False, False),
+ # Unknown architectures must fail OPEN: never hide a real chat model.
+ ({"architectures": ["SomeCustomNet"], "model_type": "custom"}, False, None),
+ ({}, False, None),
+ ],
+)
+def test_local_transformers_chat_classification(tmp_path, config, modules, expected):
+ """A safetensors dir is chat-capable on file format alone, so an embedding
+ export looked like a chat model, and auto-load tries the smallest first."""
+ path = _write_local_model(tmp_path, "row", config, modules = modules)
+ assert model_common._local_transformers_can_chat(path) is expected
+
+
+def test_local_embedding_model_is_not_chat_capable(tmp_path):
+ """End to end through the scanner: the row is still listed, since that is
+ how the user deletes it, but can_chat is false so auto-load skips it."""
+ _write_local_model(
+ tmp_path,
+ "all-MiniLM-L6-v2",
+ {"architectures": ["BertModel"], "model_type": "bert"},
+ modules = True,
+ )
+ _write_local_model(
+ tmp_path,
+ "tiny-llama",
+ {"architectures": ["LlamaForCausalLM"], "model_type": "llama"},
+ )
+ rows = {
+ row.display_name: row
+ for path in sorted(tmp_path.iterdir())
+ for row in model_common._classify_local_path(path, "models_dir")
+ }
+ assert rows["all-MiniLM-L6-v2"].capabilities.can_chat is False
+ assert rows["tiny-llama"].capabilities.can_chat is True
+ # Training and LoRA support are unchanged: this only gates chat.
+ assert rows["all-MiniLM-L6-v2"].capabilities.can_train is True
+
+
+def test_cached_encoder_repo_is_not_chat_capable(tmp_path):
+ """Cached rows build capabilities from file format too, so a cached BERT
+ looked like a chat model to auto-load."""
+ snapshot = _write_local_model(
+ tmp_path, "snap", {"architectures": ["BertModel"], "model_type": "bert"}
+ )
+ fields = cache_inventory._cache_inventory_fields(
+ "sentence-transformers/all-MiniLM-L6-v2",
+ "safetensors",
+ identity = cache_inventory._LoadIdentity(
+ load_id = str(snapshot), active_cache = False, load_snapshot = snapshot
+ ),
+ )
+ assert fields["capabilities"]["can_chat"] is False
+
+
+def test_cached_generative_repo_stays_chat_capable(tmp_path):
+ """Control for the gate above."""
+ snapshot = _write_local_model(
+ tmp_path, "snap", {"architectures": ["LlamaForCausalLM"], "model_type": "llama"}
+ )
+ fields = cache_inventory._cache_inventory_fields(
+ "unsloth/Llama-3.2-1B-Instruct",
+ "safetensors",
+ identity = cache_inventory._LoadIdentity(
+ load_id = str(snapshot), active_cache = False, load_snapshot = snapshot
+ ),
+ )
+ assert fields["capabilities"]["can_chat"] is True
+
+
+def test_cached_row_without_a_snapshot_keeps_its_format_capability(tmp_path):
+ """Fails open: no snapshot to inspect must not hide the row."""
+ fields = cache_inventory._cache_inventory_fields(
+ "unsloth/Llama-3.2-1B-Instruct",
+ "safetensors",
+ identity = cache_inventory._LoadIdentity(
+ load_id = "unsloth/Llama-3.2-1B-Instruct",
+ active_cache = True,
+ load_snapshot = None,
+ ),
+ )
+ assert fields["capabilities"]["can_chat"] is True
+
+
+ "config",
+ [
+ {"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"},
+ {"architectures": ["SomeCustomHead"], "model_type": "whisper"},
+ {"architectures": ["VisionEncoderDecoderModel"], "model_type": "vision-encoder-decoder"},
+ {"architectures": ["MusicgenForConditionalGeneration"], "model_type": "musicgen"},
+ ],
+)
+def test_non_chat_conditional_generation_is_not_chat_capable(tmp_path, config):
+ """These end in ForConditionalGeneration but cannot answer a text turn, and
+ are small enough that the cascade would stop there. The managed cache
+ already hides Whisper; scan folders did not."""
+ path = _write_local_model(tmp_path, "row", config)
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+ "config",
+ [
+ {"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"},
+ {"architectures": ["Gemma3ForConditionalGeneration"], "model_type": "gemma3"},
+ {"architectures": ["BartForConditionalGeneration"], "model_type": "bart"},
+ ],
+)
+def test_real_conditional_generation_chat_models_are_unaffected(tmp_path, config):
+ """Guard on the list above: multimodal and seq2seq chat models must stay."""
+ path = _write_local_model(tmp_path, "row", config)
+ assert model_common._local_transformers_can_chat(path) is True
+
+
+ "config",
+ [
+ {"architectures": ["ViTModel"], "model_type": "vit"},
+ {"architectures": ["Dinov2Model"], "model_type": "dinov2"},
+ {"architectures": ["SwinModel"], "model_type": "swin"},
+ {"architectures": ["Wav2Vec2Model"], "model_type": "wav2vec2"},
+ ],
+)
+def test_bare_vision_and_audio_backbones_are_not_chat_capable(tmp_path, config):
+ """Their class names carry no task suffix, so only the model type gives them
+ away."""
+ path = _write_local_model(tmp_path, "row", config)
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+def test_unreadable_config_never_fails_the_scan(tmp_path):
+ """One bad config.json must classify as unknown, not take the inventory
+ request down. Deep nesting raises RecursionError, which is neither
+ JSONDecodeError nor OSError."""
+ cases = {
+ "deep": "[" * 60000 + "]" * 60000,
+ "truncated": '{"architectures": ["Llam',
+ "not_an_object": '["a", "b"]',
+ "empty": "",
+ }
+ for name, body in cases.items():
+ path = tmp_path / name
+ path.mkdir()
+ (path / "config.json").write_text(body, encoding = "utf-8")
+ assert model_common._local_transformers_can_chat(path) is None, name
- hf_download._download_dataset("Org/Data", None, "xet")
- assert written, "XET dataset download must still record a manifest"
- assert written[0][0][0:3] == ("dataset", "Org/Data", None)
- assert written[0][0][3][0].path == "data.parquet"
- assert written[0][1] == {"commit_hash": "dataset-commit", "metadata_derived": True}
- assert snapshot_calls == [
- {
- "repo_id": "Org/Data",
- "token": False,
- "repo_type": "dataset",
- "max_workers": 1,
- "revision": "dataset-commit",
- }
- ]
- assert verified == [("dataset", "Org/Data", None, str(tmp_path))]
+def test_oversized_config_is_skipped_rather_than_read(tmp_path):
+ path = tmp_path / "huge"
+ path.mkdir()
+ (path / "config.json").write_text(
+ '{"architectures": ["LlamaForCausalLM"], "pad": "'
+ + "a" * (model_common._MAX_LOCAL_JSON_BYTES + 1)
+ + '"}',
+ encoding = "utf-8",
+ )
+ assert model_common._local_transformers_can_chat(path) is None
-def test_dataset_status_includes_generation(monkeypatch):
- class _Registry:
- def get_job(self, _key):
- return SimpleNamespace(state = "running", error = None)
+def test_a_fifo_named_config_json_does_not_block_the_scan(tmp_path):
+ """read_text() on a FIFO with no writer blocks forever, hanging the scan."""
+ os = pytest.importorskip("os")
+ if not hasattr(os, "mkfifo"):
+ pytest.skip("no mkfifo on this platform")
+ path = tmp_path / "fifo"
+ path.mkdir()
+ os.mkfifo(path / "config.json")
+ assert model_common._local_transformers_can_chat(path) is None
- def current_generation(self, _key):
- return 4
- monkeypatch.setattr(dataset_downloads, "_registry", _Registry())
+ "model_type",
+ ["siglip", "clip", "bert", "vit", "wav2vec2"],
+)
+def test_an_encoder_without_architectures_is_still_not_chat_capable(tmp_path, model_type):
+ """google/siglip2-* ships config.json with no architectures key, and the
+ encoder-only branch used to require one, so those rows stayed chat-capable
+ and sorted ahead of a real chat model."""
+ path = tmp_path / model_type
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps({"model_type": model_type}), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+def test_a_causal_lm_without_architectures_still_fails_open(tmp_path):
+ """Control: keyed on the encoder-only type list, so an unknown type with no
+ architectures stays inconclusive."""
+ path = tmp_path / "custom"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps({"model_type": "some_new_llm"}), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is None
+
+
+ "config",
+ [
+ {"model_type": "blip", "architectures": ["BlipForConditionalGeneration"]},
+ {"model_type": "blip-2", "architectures": ["Blip2ForConditionalGeneration"]},
+ {"model_type": "instructblip", "architectures": ["InstructBlipForConditionalGeneration"]},
+ {"model_type": "git", "architectures": ["GitForCausalLM"]},
+ ],
+)
+def test_an_image_captioner_is_not_chat_capable(tmp_path, config):
+ """These generate text, but only about an image, so a plain text turn fails,
+ and the smallest-first cascade would load one and stop looking."""
+ path = tmp_path / "captioner"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+ "architecture",
+ ["CLIPTextModelWithProjection", "CLIPVisionModelWithProjection", "CLIPTextModel"],
+)
+def test_a_projection_head_encoder_is_not_chat_capable(tmp_path, architecture):
+ """The encoder-only branch also required the name to end in Model, so a
+ projection variant fell through and kept its format capability."""
+ path = tmp_path / "proj"
+ path.mkdir()
+ (path / "config.json").write_text(
+ json.dumps({"model_type": "clip", "architectures": [architecture]}), encoding = "utf-8"
+ )
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+ "config",
+ [
+ {"model_type": "bert", "architectures": ["BertLMHeadModel"]},
+ {"model_type": "t5", "architectures": ["T5ForConditionalGeneration"]},
+ {"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]},
+ ],
+)
+def test_a_generative_head_still_wins_over_the_encoder_type(tmp_path, config):
+ """Control for both gates above: a generative architecture is accepted
+ before the type list is consulted."""
+ path = tmp_path / "gen"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is True
+
+
+ "config",
+ [
+ {"model_type": "llama", "architectures": ["LlamaModel"]},
+ {"model_type": "gpt2", "architectures": ["GPT2Model"]},
+ {"model_type": "t5", "architectures": ["T5Model"]},
+ {"model_type": "mistral", "architectures": ["MistralModel"]},
+ ],
+)
+def test_a_bare_text_backbone_is_not_chat_capable(tmp_path, config):
+ """AutoModel.save_pretrained writes the backbone name, and a backbone has no
+ LM head, so the cascade would stop on one before a usable chat model."""
+ path = tmp_path / "backbone"
+ path.mkdir()
+ (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+
+ assert model_common._local_transformers_can_chat(path) is False
+
+
+def test_an_unfamiliar_backbone_still_fails_open(tmp_path):
+ """The list is explicit, not shape-matched, so a custom FooModel keeps its
+ format capability."""
+ path = tmp_path / "custom"
+ path.mkdir()
+ (path / "config.json").write_text(
+ json.dumps({"model_type": "brand_new_arch", "architectures": ["FooModel"]}),
+ encoding = "utf-8",
+ )
+
+ assert model_common._local_transformers_can_chat(path) is None
+
+
[email protected]("layout", ["flat", "publisher_child"])
+def test_lmstudio_scan_matches_gguf_suffix_case_insensitively(tmp_path, layout):
+ """The custom and models-dir scans lower() the suffix; these two did not, so a
+ .GGUF was invisible only here. Windows and macOS treat the two spellings as one
+ name, so the file is reachable but unlisted."""
+ lm_dir = tmp_path / "models"
+ holder = lm_dir if layout == "flat" else lm_dir / "publisher"
+ holder.mkdir(parents = True)
+ for name in ("lower.gguf", "UPPER.GGUF", "Mixed.GguF"):
+ (holder / name).write_bytes(b"x")
+
+ found = {Path(row.path).name for row in local_inventory._scan_lmstudio_dir(lm_dir)}
+
+ assert found == {"lower.gguf", "UPPER.GGUF", "Mixed.GguF"}
+
+
+ ("config", "expected"),
+ [
+ ({"model_type": "bert", "architectures": ["BertModel"]}, False),
+ ({"model_type": "clip", "architectures": ["CLIPModel"]}, False),
+ ({"model_type": "llama", "architectures": ["LlamaForCausalLM"]}, True),
+ ],
+)
+def test_custom_promotion_keeps_the_classifier_verdict(tmp_path, config, expected):
+ """Promotion rebuilt capabilities from the format alone, which restored
+ can_chat on rows the classifier had ruled out."""
+ model_dir = tmp_path / "scan" / "model"
+ model_dir.mkdir(parents = True)
+ (model_dir / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+ (model_dir / "model.safetensors").write_bytes(b"x" * 1024)
+
+ rows = local_inventory._scan_custom_folder(tmp_path / "scan")
+ assert rows, "the scan produced no row"
+ for row in rows:
+ promoted = local_inventory._promote_to_custom_source(row)
+ assert promoted.source == "custom"
+ assert promoted.capabilities.can_chat is expected
+
+
+def test_gguf_progress_unknown_hashes_calls_a_sibling_only_dir_absent(monkeypatch, tmp_path):
+ """A repo dir kept alive by a sibling quant is not evidence that THIS one is here.
+
+ With the hash set unresolvable, target_present used to stay null, and the frontend's idle
+ probe reads zero bytes with a non-null cache_path as an active job unless presence is
+ explicitly false -- so the deleted quant's stale card was re-adopted and blocked a fresh
+ download until the idle grace ran out. The snapshot dir is named per file, so absence is
+ answerable here even when the hashes are not.
+ """
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ snap.mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900) # the sibling that keeps the dir alive
+ (snap / "mmproj-F16.gguf").write_bytes(b"y" * 30) # shared by every quant in the repo
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry)
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+
+ assert result["completed_bytes"] == 0
+ assert result["target_present"] is False, result
+
+
+def test_gguf_progress_target_presence_is_aggregated_across_caches(monkeypatch, tmp_path):
+ """Presence is a property of the set of caches, not of the one with the most bytes.
+
+ A sibling-only repo dir and a remembered cache that still holds this variant both read as
+ zero bytes, so the byte ordering alone could select the sibling-only reading and report the
+ target gone -- retiring a job whose files another scanned cache proves are there.
+ """
+ sibling = tmp_path / "a" / "models--Org--Model-GGUF"
+ (sibling / "snapshots" / "rev0").mkdir(parents = True)
+ (sibling / "blobs").mkdir(parents = True)
+ (sibling / "snapshots" / "rev0" / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ holder = tmp_path / "b" / "models--Org--Model-GGUF"
+ (holder / "snapshots" / "rev0").mkdir(parents = True)
+ (holder / "blobs").mkdir(parents = True)
+ # The variant's own file, named but empty: zero bytes keeps the tie with the sibling-only
+ # reading, and the name is what proves the target is in this cache.
+ (holder / "snapshots" / "rev0" / "model-Q4_K_M.gguf").write_bytes(b"")
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100)],
+ "http",
+ hub_cache = holder.parent,
+ )
+ _unresolvable_variant_metadata(monkeypatch, sibling, state = "idle")
monkeypatch.setattr(
- dataset_downloads,
- "resolve_cached_repo_id_case",
- lambda repo_id, **_kwargs: repo_id,
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [sibling, holder],
+ )
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+
+ assert result["target_present"] is True, result
+
+
+def test_a_running_job_does_not_borrow_another_caches_manifest(monkeypatch, tmp_path):
+ """A live download is read from the active root only, so its hashes must come from there.
+
+ An older cache holding a DIFFERENT revision's manifest for the same variant made the two
+ disagree, and a disagreement is refused -- so a live download whose own manifest is right
+ there lost its hash set and every blob it had written was filtered out by the name-based
+ fallback's clamp. Scoped to the roots the scan will actually read, the active manifest
+ stands on its own.
+ """
+ active = tmp_path / "active" / "models--Org--Model-GGUF"
+ (active / "blobs").mkdir(parents = True)
+ remembered = tmp_path / "old" / "models--Org--Model-GGUF"
+ (remembered / "blobs").mkdir(parents = True)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100, sha256 = "old")],
+ "http",
+ hub_cache = remembered.parent,
+ )
+ monkeypatch.setattr(
+ downloads,
+ "preferred_repo_cache_dirs",
+ lambda *_a, force_active = False, active_root = None, **_kw: (
+ [active] if force_active else [active, remembered]
+ ),
+ )
+
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100, sha256 = "new")],
+ "http",
+ hub_cache = active.parent,
+ )
+ monkeypatch.setattr(
+ download_manifest, "_canonical_hub_cache", lambda root = None: str(root or "")
)
- result = asyncio.run(dataset_downloads.get_dataset_download_status_response("Org/Data"))
+ scoped = downloads._variant_manifest_in_any_cache(
+ "Org/Model-GGUF", "Q4_K_M", force_active = True, active_root = active.parent
+ )
+ assert scoped is not None and scoped.expected_files[0].sha256 == "new"
+ # Unscoped, the superseded cache is consulted too and the disagreement refuses both.
+ assert (
+ downloads._variant_manifest_in_any_cache(
+ "Org/Model-GGUF", "Q4_K_M", active_root = active.parent
+ )
+ is None
+ )
- assert result.state == "running"
- assert result.generation == 4
+def test_an_unreadable_blobs_dir_is_not_evidence_of_absence(monkeypatch, tmp_path):
+ """EACCES on blobs/ is not an empty blobs/. Swallowing it produced a MEASURED zero -- bytes
+ 0, target_present false, cache_measured true -- and idle hydration retires a persisted job
+ on exactly that shape, though the cache was never actually read."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ (entry / "snapshots" / "rev0").mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry)
+ real_iterdir = Path.iterdir
-def _write_local_model(
- root: Path,
- name: str,
- config: dict,
- *,
- modules: bool = False,
-) -> Path:
- path = root / name
- path.mkdir(parents = True)
- (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
- (path / "model.safetensors").write_bytes(b"\0" * 16)
- if modules:
- (path / "modules.json").write_text("[]", encoding = "utf-8")
- return path
+ def _deny(self):
+ if self.name == "blobs":
+ raise PermissionError("denied")
+ return real_iterdir(self)
+ monkeypatch.setattr(Path, "iterdir", _deny)
- "config, modules, expected",
- [
- ({"architectures": ["LlamaForCausalLM"], "model_type": "llama"}, False, True),
- ({"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"}, False, True),
- ({"auto_map": {"AutoModelForCausalLM": "m.C"}, "model_type": "bert"}, False, True),
- ({"architectures": ["BertModel"], "model_type": "bert"}, False, False),
- ({"architectures": ["BertModel"], "model_type": "bert"}, True, False),
- ({"architectures": ["RobertaForMaskedLM"], "model_type": "roberta"}, False, False),
- ({"architectures": ["CLIPModel"], "model_type": "clip"}, False, False),
- # Unknown architectures must fail OPEN: never hide a real chat model.
- ({"architectures": ["SomeCustomNet"], "model_type": "custom"}, False, None),
- ({}, False, None),
- ],
-)
-def test_local_transformers_chat_classification(tmp_path, config, modules, expected):
- """A safetensors dir is chat-capable on file format alone, so an embedding
- export looked like a chat model, and auto-load tries the smallest first."""
- path = _write_local_model(tmp_path, "row", config, modules = modules)
- assert model_common._local_transformers_can_chat(path) is expected
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 130,
+ )
+ )
+ assert result["target_present"] is None, result
+ assert result.get("cache_measured") is not True, result
-def test_local_embedding_model_is_not_chat_capable(tmp_path):
- """End to end through the scanner: the row is still listed, since that is
- how the user deletes it, but can_chat is false so auto-load skips it."""
- _write_local_model(
- tmp_path,
- "all-MiniLM-L6-v2",
- {"architectures": ["BertModel"], "model_type": "bert"},
- modules = True,
+
+def test_a_manifest_alone_is_not_evidence_the_variant_is_on_disk(monkeypatch, tmp_path):
+ """The state-dir manifest says what the target SHOULD contain. It survives a deletion made
+ outside the app, so with a sibling quant keeping the repo dir alive it made a variant with
+ nothing left on disk read as present -- the phantom job this field exists to retire."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ (entry / "snapshots" / "rev0").mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (entry / "snapshots" / "rev0" / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100, sha256 = "aa")],
+ "http",
+ hub_cache = entry.parent,
)
- _write_local_model(
- tmp_path,
- "tiny-llama",
- {"architectures": ["LlamaForCausalLM"], "model_type": "llama"},
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [entry],
+ )
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
)
- rows = {
- row.display_name: row
- for path in sorted(tmp_path.iterdir())
- for row in model_common._classify_local_path(path, "models_dir")
- }
- assert rows["all-MiniLM-L6-v2"].capabilities.can_chat is False
- assert rows["tiny-llama"].capabilities.can_chat is True
- # Training and LoRA support are unchanged: this only gates chat.
- assert rows["all-MiniLM-L6-v2"].capabilities.can_train is True
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
-def test_cached_encoder_repo_is_not_chat_capable(tmp_path):
- """Cached rows build capabilities from file format too, so a cached BERT
- looked like a chat model to auto-load."""
- snapshot = _write_local_model(
- tmp_path, "snap", {"architectures": ["BertModel"], "model_type": "bert"}
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants, "gguf_variant_requirements", lambda *_a, **_kw: None
)
- fields = cache_inventory._cache_inventory_fields(
- "sentence-transformers/all-MiniLM-L6-v2",
- "safetensors",
- identity = cache_inventory._LoadIdentity(
- load_id = str(snapshot), active_cache = False, load_snapshot = snapshot
- ),
+ monkeypatch.setattr(
+ downloads.gguf_variants, "gguf_variant_blob_hashes", lambda *_a, **_kw: frozenset({"aa"})
)
- assert fields["capabilities"]["can_chat"] is False
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
-def test_cached_generative_repo_stays_chat_capable(tmp_path):
- """Control for the gate above."""
- snapshot = _write_local_model(
- tmp_path, "snap", {"architectures": ["LlamaForCausalLM"], "model_type": "llama"}
+ assert result["completed_bytes"] == 0
+ assert result["target_present"] is False, result
+
+
+def test_one_unknown_cache_keeps_absence_unknown(monkeypatch, tmp_path):
+ """Absence needs EVERY scanned cache to say so. A sibling-only dir reporting false could win
+ the zero-byte tie over a cache with no readable snapshot to identify the variant from --
+ whose shared blobs dir may still hold an unattributable partial -- and the job was retired
+ on the strength of the one reading that could not see it."""
+ sibling = tmp_path / "a" / "models--Org--Model-GGUF"
+ (sibling / "snapshots" / "rev0").mkdir(parents = True)
+ (sibling / "blobs").mkdir(parents = True)
+ (sibling / "snapshots" / "rev0" / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ unknown = tmp_path / "b" / "models--Org--Model-GGUF"
+ (unknown / "blobs").mkdir(parents = True) # no snapshot dir at all: nothing to identify
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, sibling, state = "idle")
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ lambda *_args, **_kwargs: [sibling, unknown],
)
- fields = cache_inventory._cache_inventory_fields(
- "unsloth/Llama-3.2-1B-Instruct",
- "safetensors",
- identity = cache_inventory._LoadIdentity(
- load_id = str(snapshot), active_cache = False, load_snapshot = snapshot
- ),
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
)
- assert fields["capabilities"]["can_chat"] is True
+ assert result["target_present"] is None, result
-def test_cached_row_without_a_snapshot_keeps_its_format_capability(tmp_path):
- """Fails open: no snapshot to inspect must not hide the row."""
- fields = cache_inventory._cache_inventory_fields(
- "unsloth/Llama-3.2-1B-Instruct",
- "safetensors",
- identity = cache_inventory._LoadIdentity(
- load_id = "unsloth/Llama-3.2-1B-Instruct",
- active_cache = True,
- load_snapshot = None,
- ),
+
+def test_an_unattributable_partial_keeps_presence_unknown(monkeypatch, tmp_path):
+ """A restarted download whose hashes could not be resolved has its bytes in an .incomplete
+ blob that is not linked into any snapshot yet, so the by-name scan -- which is what answers
+ presence on that path -- reports a confident absence. Idle hydration retires a persisted job
+ on that verdict, throwing away a partial the user can still resume."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ # A sibling quant keeps the repo dir alive; the requested variant has nothing materialized.
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ (blobs / "somehash.incomplete").write_bytes(b"x" * 40)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry, state = "idle")
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
)
- assert fields["capabilities"]["can_chat"] is True
+ assert result["target_present"] is None, result
- "config",
- [
- {"architectures": ["WhisperForConditionalGeneration"], "model_type": "whisper"},
- {"architectures": ["SomeCustomHead"], "model_type": "whisper"},
- {"architectures": ["VisionEncoderDecoderModel"], "model_type": "vision-encoder-decoder"},
- {"architectures": ["MusicgenForConditionalGeneration"], "model_type": "musicgen"},
- ],
-)
-def test_non_chat_conditional_generation_is_not_chat_capable(tmp_path, config):
- """These end in ForConditionalGeneration but cannot answer a text turn, and
- are small enough that the cascade would stop there. The managed cache
- already hides Whisper; scan folders did not."""
- path = _write_local_model(tmp_path, "row", config)
- assert model_common._local_transformers_can_chat(path) is False
+def test_a_subtree_that_cannot_be_scanned_keeps_presence_unknown(monkeypatch, tmp_path):
+ """Enumeration succeeding does not mean it was complete. Path.rglob suppresses every OSError
+ raised while scanning -- documented behaviour since 3.13 -- so a Windows ACL denial or a
+ network-filesystem hiccup on one subdirectory came back as a short list that reads exactly
+ like an empty one, and the scan then reported the variant absent though the unreadable
+ subtree may hold its main shard. Idle hydration retires a persisted download on that
+ verdict."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ snap.mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900) # a sibling keeps the dir alive
+ denied = snap / "split"
+ denied.mkdir()
+ (denied / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry)
+ real_scandir = os.scandir
- "config",
- [
- {"architectures": ["T5ForConditionalGeneration"], "model_type": "t5"},
- {"architectures": ["Gemma3ForConditionalGeneration"], "model_type": "gemma3"},
- {"architectures": ["BartForConditionalGeneration"], "model_type": "bart"},
- ],
-)
-def test_real_conditional_generation_chat_models_are_unaffected(tmp_path, config):
- """Guard on the list above: multimodal and seq2seq chat models must stay."""
- path = _write_local_model(tmp_path, "row", config)
- assert model_common._local_transformers_can_chat(path) is True
+ def _deny(path, *args, **kwargs):
+ if str(path) == str(denied):
+ raise PermissionError(13, "Permission denied")
+ return real_scandir(path, *args, **kwargs)
+ monkeypatch.setattr(os, "scandir", _deny)
- "config",
- [
- {"architectures": ["ViTModel"], "model_type": "vit"},
- {"architectures": ["Dinov2Model"], "model_type": "dinov2"},
- {"architectures": ["SwinModel"], "model_type": "swin"},
- {"architectures": ["Wav2Vec2Model"], "model_type": "wav2vec2"},
- ],
-)
-def test_bare_vision_and_audio_backbones_are_not_chat_capable(tmp_path, config):
- """Their class names carry no task suffix, so only the model type gives them
- away."""
- path = _write_local_model(tmp_path, "row", config)
- assert model_common._local_transformers_can_chat(path) is False
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+ assert result["target_present"] is None, result
-def test_unreadable_config_never_fails_the_scan(tmp_path):
- """One bad config.json must classify as unknown, not take the inventory
- request down. Deep nesting raises RecursionError, which is neither
- JSONDecodeError nor OSError."""
- cases = {
- "deep": "[" * 60000 + "]" * 60000,
- "truncated": '{"architectures": ["Llam',
- "not_an_object": '["a", "b"]',
- "empty": "",
- }
- for name, body in cases.items():
- path = tmp_path / name
- path.mkdir()
- (path / "config.json").write_text(body, encoding = "utf-8")
- assert model_common._local_transformers_can_chat(path) is None, name
+def test_a_blob_that_cannot_be_stated_keeps_presence_unknown(monkeypatch, tmp_path):
+ """The hashes resolved, so the blob loop is what measures the variant -- and a blob it could
+ not inspect is not a blob that is not there. Swallowing the error produced a MEASURED
+ absence, which hydration reads as gone and retires a persisted download."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ (entry / "snapshots" / "rev0").mkdir(parents = True)
+ blobs = entry / "blobs"
+ blobs.mkdir(parents = True)
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants, "gguf_variant_requirements", lambda *_a, **_kw: None
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_a, **_kw: frozenset({"mainhash"}),
+ )
+ monkeypatch.setattr(snapshot_progress, "preferred_repo_cache_dirs", lambda *_a, **_kw: [entry])
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ )
+ real_stat = Path.stat
+
+ def _deny(self, *a, **kw):
+ if self.name == "mainhash":
+ raise PermissionError("denied")
+ return real_stat(self, *a, **kw)
+
+ monkeypatch.setattr(Path, "stat", _deny)
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+
+ assert result["target_present"] is None, result
-def test_oversized_config_is_skipped_rather_than_read(tmp_path):
- path = tmp_path / "huge"
- path.mkdir()
- (path / "config.json").write_text(
- '{"architectures": ["LlamaForCausalLM"], "pad": "'
- + "a" * (model_common._MAX_LOCAL_JSON_BYTES + 1)
- + '"}',
- encoding = "utf-8",
- )
- assert model_common._local_transformers_can_chat(path) is None
+def test_an_older_snapshot_still_proves_the_variant_is_here(monkeypatch, tmp_path):
+ """A cache can retain several revisions. The requested quant living in an older snapshot
+ while the newest holds only a sibling read as absent, and hydration retired a job whose
+ target is still perfectly usable."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ old_snap = entry / "snapshots" / "rev0"
+ new_snap = entry / "snapshots" / "rev1"
+ old_snap.mkdir(parents = True)
+ new_snap.mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (old_snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (new_snap / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ import os
+ import time
-def test_a_fifo_named_config_json_does_not_block_the_scan(tmp_path):
- """read_text() on a FIFO with no writer blocks forever, hanging the scan."""
- os = pytest.importorskip("os")
- if not hasattr(os, "mkfifo"):
- pytest.skip("no mkfifo on this platform")
- path = tmp_path / "fifo"
- path.mkdir()
- os.mkfifo(path / "config.json")
- assert model_common._local_transformers_can_chat(path) is None
+ # Make rev1 unambiguously the newest, which is the one latest_snapshot_dir picks.
+ os.utime(old_snap, (time.time() - 600, time.time() - 600))
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry, state = "idle")
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
- "model_type",
- ["siglip", "clip", "bert", "vit", "wav2vec2"],
-)
-def test_an_encoder_without_architectures_is_still_not_chat_capable(tmp_path, model_type):
- """google/siglip2-* ships config.json with no architectures key, and the
- encoder-only branch used to require one, so those rows stayed chat-capable
- and sorted ahead of a real chat model."""
- path = tmp_path / model_type
- path.mkdir()
- (path / "config.json").write_text(json.dumps({"model_type": model_type}), encoding = "utf-8")
+ assert result["target_present"] is True, result
- assert model_common._local_transformers_can_chat(path) is False
+def test_a_verified_completion_wins_a_byte_tie_between_caches(monkeypatch, tmp_path):
+ """Two remembered caches can clamp to the same byte total while only one has a manifest that
+ verifies against disk. The byte-ordered pick then carried whichever came first by root
+ order, so the response stayed capped below 100% and kept offering Retry for a variant that
+ is demonstrably complete in the other cache."""
+ unverified = tmp_path / "a" / "models--Org--Model-GGUF"
+ (unverified / "snapshots" / "rev0").mkdir(parents = True)
+ (unverified / "blobs").mkdir(parents = True)
+ (unverified / "snapshots" / "rev0" / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ verified = tmp_path / "b" / "models--Org--Model-GGUF"
+ (verified / "snapshots" / "rev0").mkdir(parents = True)
+ (verified / "blobs").mkdir(parents = True)
+ (verified / "snapshots" / "rev0" / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100)],
+ "http",
+ hub_cache = verified.parent,
+ )
+ _unresolvable_variant_metadata(monkeypatch, unverified, state = "idle")
+ monkeypatch.setattr(
+ snapshot_progress,
+ "preferred_repo_cache_dirs",
+ # The unverified cache first, so root order alone would carry it.
+ lambda *_a, **_kw: [unverified, verified],
+ )
-def test_a_causal_lm_without_architectures_still_fails_open(tmp_path):
- """Control: keyed on the encoder-only type list, so an unknown type with no
- architectures stays inconclusive."""
- path = tmp_path / "custom"
- path.mkdir()
- (path / "config.json").write_text(json.dumps({"model_type": "some_new_llm"}), encoding = "utf-8")
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
- assert model_common._local_transformers_can_chat(path) is None
+ assert result["complete_on_disk"] is True, result
- "config",
- [
- {"model_type": "blip", "architectures": ["BlipForConditionalGeneration"]},
- {"model_type": "blip-2", "architectures": ["Blip2ForConditionalGeneration"]},
- {"model_type": "instructblip", "architectures": ["InstructBlipForConditionalGeneration"]},
- {"model_type": "git", "architectures": ["GitForCausalLM"]},
- ],
-)
-def test_an_image_captioner_is_not_chat_capable(tmp_path, config):
- """These generate text, but only about an image, so a plain text turn fails,
- and the smallest-first cascade would load one and stop looking."""
- path = tmp_path / "captioner"
- path.mkdir()
- (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+def test_an_unstatable_blobs_dir_is_not_an_absent_one(monkeypatch, tmp_path):
+ """Path.is_dir() swallows a whole class of OSError and answers False, so a failure on the
+ blobs directory ITSELF read as "no blobs here" -- a measured absence, which idle hydration
+ retires a persisted download on. ELOOP is the case it hides (a symlink cycle, or a
+ network-filesystem path that stops resolving); EACCES it re-raises, which the same try
+ now contains rather than letting it escape the whole reading."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ (entry / "snapshots" / "rev0").mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ _unresolvable_variant_metadata(monkeypatch, entry, state = "idle")
+ real_stat = os.stat
- assert model_common._local_transformers_can_chat(path) is False
+ denied = {"hit": False}
+ def _deny(path, *a, **kw):
+ if str(path).endswith("blobs"):
+ denied["hit"] = True
+ raise OSError(errno.ELOOP, "too many levels of symbolic links")
+ return real_stat(path, *a, **kw)
- "architecture",
- ["CLIPTextModelWithProjection", "CLIPVisionModelWithProjection", "CLIPTextModel"],
-)
-def test_a_projection_head_encoder_is_not_chat_capable(tmp_path, architecture):
- """The encoder-only branch also required the name to end in Model, so a
- projection variant fell through and kept its format capability."""
- path = tmp_path / "proj"
- path.mkdir()
- (path / "config.json").write_text(
- json.dumps({"model_type": "clip", "architectures": [architecture]}), encoding = "utf-8"
+ monkeypatch.setattr(snapshot_progress.os, "stat", _deny)
+
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
)
- assert model_common._local_transformers_can_chat(path) is False
+ assert result["target_present"] is None, result
+ assert result.get("cache_measured") is not True, result
+ assert denied["hit"], "the test must actually exercise the directory stat"
- "config",
- [
- {"model_type": "bert", "architectures": ["BertLMHeadModel"]},
- {"model_type": "t5", "architectures": ["T5ForConditionalGeneration"]},
- {"model_type": "qwen3", "architectures": ["Qwen3ForCausalLM"]},
- ],
-)
-def test_a_generative_head_still_wins_over_the_encoder_type(tmp_path, config):
- """Control for both gates above: a generative architecture is accepted
- before the type list is consulted."""
- path = tmp_path / "gen"
- path.mkdir()
- (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
+def test_a_variant_complete_in_an_older_snapshot_settles(monkeypatch, tmp_path):
+ """The presence check already looks at every retained snapshot, but the byte reading and the
+ manifest verification did not: a quant complete in an older revision, with the newest
+ holding only a sibling, reported 0 bytes and never settled -- 99% and adoptable forever."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ old_snap = entry / "snapshots" / "rev0"
+ new_snap = entry / "snapshots" / "rev1"
+ old_snap.mkdir(parents = True)
+ new_snap.mkdir(parents = True)
+ (entry / "blobs").mkdir(parents = True)
+ (old_snap / "model-Q4_K_M.gguf").write_bytes(b"x" * 100)
+ (new_snap / "model-Q2_K.gguf").write_bytes(b"z" * 900)
+ os.utime(old_snap, (time.time() - 600, time.time() - 600))
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100)],
+ "http",
+ hub_cache = entry.parent,
+ )
+ _unresolvable_variant_metadata(monkeypatch, entry, state = "idle")
- assert model_common._local_transformers_can_chat(path) is True
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+ assert result["completed_bytes"] == 100, result
+ assert result["complete_on_disk"] is True, result
- "config",
- [
- {"model_type": "llama", "architectures": ["LlamaModel"]},
- {"model_type": "gpt2", "architectures": ["GPT2Model"]},
- {"model_type": "t5", "architectures": ["T5Model"]},
- {"model_type": "mistral", "architectures": ["MistralModel"]},
- ],
-)
-def test_a_bare_text_backbone_is_not_chat_capable(tmp_path, config):
- """AutoModel.save_pretrained writes the backbone name, and a backbone has no
- LM head, so the cascade would stop on one before a usable chat model."""
- path = tmp_path / "backbone"
- path.mkdir()
- (path / "config.json").write_text(json.dumps(config), encoding = "utf-8")
- assert model_common._local_transformers_can_chat(path) is False
+def test_a_deleted_snapshot_link_is_absent_even_with_its_blob_left_behind(monkeypatch, tmp_path):
+ """Deleting a GGUF's snapshot entry normally leaves its finalized blob in the shared blobs/
+ dir, and a companion blob shared with a sibling keeps the tally positive on its own. Reading
+ presence off those counters called a quant that is gone present, and idle hydration
+ re-adopted the phantom and blocked a fresh download of it."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ snap = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ snap.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ # The finalized blob survives; the snapshot entry that named it does not.
+ (blobs / "mainhash").write_bytes(b"x" * 100)
+ (snap / "model-Q2_K.gguf").write_bytes(b"z" * 900) # a sibling keeps the repo dir alive
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
-def test_an_unfamiliar_backbone_still_fails_open(tmp_path):
- """The list is explicit, not shape-matched, so a custom FooModel keeps its
- format capability."""
- path = tmp_path / "custom"
- path.mkdir()
- (path / "config.json").write_text(
- json.dumps({"model_type": "brand_new_arch", "architectures": ["FooModel"]}),
- encoding = "utf-8",
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants, "gguf_variant_requirements", lambda *_a, **_kw: None
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_a, **_kw: frozenset({"mainhash"}),
+ )
+ monkeypatch.setattr(snapshot_progress, "preferred_repo_cache_dirs", lambda *_a, **_kw: [entry])
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
)
- assert model_common._local_transformers_can_chat(path) is None
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
+ assert result["completed_bytes"] == 100, "the orphaned blob is still counted"
+ assert result["target_present"] is False, result
[email protected]("layout", ["flat", "publisher_child"])
-def test_lmstudio_scan_matches_gguf_suffix_case_insensitively(tmp_path, layout):
- """The custom and models-dir scans lower() the suffix; these two did not, so a
- .GGUF was invisible only here. Windows and macOS treat the two spellings as one
- name, so the file is reachable but unlisted."""
- lm_dir = tmp_path / "models"
- holder = lm_dir if layout == "flat" else lm_dir / "publisher"
- holder.mkdir(parents = True)
- for name in ("lower.gguf", "UPPER.GGUF", "Mixed.GguF"):
- (holder / name).write_bytes(b"x")
- found = {Path(row.path).name for row in local_inventory._scan_lmstudio_dir(lm_dir)}
+def test_a_stale_revisions_filenames_do_not_settle_the_resolved_one(monkeypatch, tmp_path):
+ """verify_against_disk compares names and sizes, not sha256. An older retained revision can
+ carry the same filenames at the same sizes, so a blob finalized but never linked (a crash
+ between the two) let the stale snapshot satisfy the check -- the job settled on files the
+ app would not load."""
+ entry = tmp_path / "models--Org--Model-GGUF"
+ stale = entry / "snapshots" / "rev0"
+ blobs = entry / "blobs"
+ stale.mkdir(parents = True)
+ blobs.mkdir(parents = True)
+ (blobs / "oldhash").write_bytes(b"y" * 100)
+ (blobs / "newhash").write_bytes(b"x" * 100) # finalized, never linked
+ os.symlink(blobs / "oldhash", stale / "model-Q4_K_M.gguf")
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
+ assert download_manifest.write_manifest(
+ "model",
+ "Org/Model-GGUF",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = 100)],
+ "http",
+ hub_cache = entry.parent,
+ )
- assert found == {"lower.gguf", "UPPER.GGUF", "Mixed.GguF"}
+ async def _run_inline(fn, *args, **kwargs):
+ return fn(*args, **kwargs)
+ monkeypatch.setattr(downloads.asyncio, "to_thread", _run_inline)
+ monkeypatch.setattr(
+ downloads.gguf_variants, "gguf_variant_requirements", lambda *_a, **_kw: None
+ )
+ monkeypatch.setattr(
+ downloads.gguf_variants,
+ "gguf_variant_blob_hashes",
+ lambda *_a, **_kw: frozenset({"newhash"}),
+ )
+ monkeypatch.setattr(snapshot_progress, "preferred_repo_cache_dirs", lambda *_a, **_kw: [entry])
+ monkeypatch.setattr(
+ downloads,
+ "_registry",
+ SimpleNamespace(get_job = lambda _key: SimpleNamespace(state = "idle")),
+ )
- ("config", "expected"),
- [
- ({"model_type": "bert", "architectures": ["BertModel"]}, False),
- ({"model_type": "clip", "architectures": ["CLIPModel"]}, False),
- ({"model_type": "llama", "architectures": ["LlamaForCausalLM"]}, True),
- ],
-)
-def test_custom_promotion_keeps_the_classifier_verdict(tmp_path, config, expected):
- """Promotion rebuilt capabilities from the format alone, which restored
- can_chat on rows the classifier had ruled out."""
- model_dir = tmp_path / "scan" / "model"
- model_dir.mkdir(parents = True)
- (model_dir / "config.json").write_text(json.dumps(config), encoding = "utf-8")
- (model_dir / "model.safetensors").write_bytes(b"x" * 1024)
+ result = asyncio.run(
+ downloads.get_gguf_download_progress_response(
+ "Org/Model-GGUF",
+ variant = "Q4_K_M",
+ expected_bytes = 100,
+ )
+ )
- rows = local_inventory._scan_custom_folder(tmp_path / "scan")
- assert rows, "the scan produced no row"
- for row in rows:
- promoted = local_inventory._promote_to_custom_source(row)
- assert promoted.source == "custom"
- assert promoted.capabilities.can_chat is expected
+ assert result["complete_on_disk"] is False, result
diff --git a/studio/backend/hub/utils/download_manifest.py b/studio/backend/hub/utils/download_manifest.py
index e011354f6c8..a0df9a73a45 100644
--- a/studio/backend/hub/utils/download_manifest.py
+++ b/studio/backend/hub/utils/download_manifest.py
@@ -46,11 +46,12 @@ from loggers import get_logger
from hub.utils.state_dir import (
RepoType,
- cache_scope_name,
+ cache_scope_names,
cancelled_dir,
manifest_path,
manifests_dir,
marker_path,
+ normalize_hub_cache,
state_filename_is_ambiguous,
variant_filename_prefix,
variant_key_fragments,
@@ -157,18 +158,67 @@ class VerifyResult:
size_mismatched: tuple[str, ...]
-def _canonical_hub_cache(hub_cache: Optional[str | Path] = None) -> Optional[str]:
+def _hub_cache_spellings(
+ hub_cache: Optional[str | Path] = None,
+) -> tuple[Optional[str], Optional[str | Path]]:
+ """``(canonical, as supplied)`` for one cache path, defaulting to the active cache.
+
+ The canonical half is what ownership comparisons and the scope digest are
+ built from. The raw half exists only so a reader can also probe the digest
+ of the spelling it was handed: the two differ exactly when ``resolve``
+ changes the path, and state written while ``resolve`` was unavailable sits
+ under the raw one.
+ """
if hub_cache is None:
try:
from utils.hf_cache_settings import get_hf_cache_paths
hub_cache = get_hf_cache_paths().hub_cache
except Exception:
- return None
+ return None, None
+ # Shared with state_dir.cache_scope_name so the ownership string recorded in
+ # a payload and the cache-<digest> directory it is filed under can never be
+ # derived from two different normalizations of the same directory.
+ return normalize_hub_cache(hub_cache), hub_cache
+
+
+def _canonical_hub_cache(hub_cache: Optional[str | Path] = None) -> Optional[str]:
+ return _hub_cache_spellings(hub_cache)[0]
+
+
+def _scope_spellings(hub_cache: str | Path) -> tuple[str, ...]:
+ """Every scope dir this cache's state can sit in, for a caller whose own
+ spelling may already be resolved.
+
+ ``cache_scope_names`` recovers the pre-``resolve`` digest only from an
+ unresolved path: hand it one that resolves to itself and it returns the
+ canonical digest alone. The read path is fed the raw configured setting and
+ so gets both, but the delete and the inventory index are not -- every
+ production caller of ``purge_all_state_for_repo`` passes
+ ``resolve_delete_target_root``, whose every branch resolves, and
+ ``build_variant_state_index``'s inventory callers pass a directory derived
+ from ``huggingface_hub.scan_cache_dir``, which resolves too. Left alone,
+ reads probe two scopes while deletes clear one: a purged variant stays on
+ disk under the legacy digest for the next read to resurrect, and the two
+ inventory endpoints disagree about state the progress endpoint can see.
+
+ So also probe the configured cache's own spelling -- but only when it names
+ the same directory as the path we were handed. Without that guard, deleting
+ a repo out of a NON-active cache would sweep the active cache's state for
+ the same repo, which is a far worse failure than the one being fixed.
+ """
+ scopes = list(cache_scope_names(hub_cache))
+ canonical = normalize_hub_cache(hub_cache)
try:
- resolved = str(Path(hub_cache).expanduser().resolve(strict = False))
- except (OSError, RuntimeError, ValueError):
- resolved = str(hub_cache)
- return os.path.normcase(resolved)
+ from utils.hf_cache_settings import get_hf_cache_paths
+ configured = get_hf_cache_paths().hub_cache
+ except Exception:
+ return tuple(scopes)
+ if configured is None or normalize_hub_cache(configured) != canonical:
+ return tuple(scopes)
+ for scope in cache_scope_names(configured):
+ if scope not in scopes:
+ scopes.append(scope)
+ return tuple(scopes)
def _read_state_payload(path: Path) -> Optional[dict]:
@@ -300,8 +350,15 @@ def _state_read_path(
return False
return _state_entry_belongs_to_repo(path, payload, repo_type, repo_id, variant)
- requested = _canonical_hub_cache(hub_cache)
- scoped = _state_paths(path_factory, repo_type, repo_id, variant, requested)
+ requested, raw = _hub_cache_spellings(hub_cache)
+ scoped = _state_paths(
+ path_factory,
+ repo_type,
+ repo_id,
+ variant,
+ requested,
+ raw_hub_cache = raw,
+ )
for path in scoped:
try:
if path.is_file() and applies(path):
@@ -327,24 +384,49 @@ def _state_paths(
repo_id: str,
variant: Optional[str],
hub_cache: Optional[str | Path],
+ *,
+ raw_hub_cache: Optional[str | Path] = None,
) -> tuple[Path, ...]:
"""Canonical-first read/delete paths across the filename migration.
Writers use only the default state-dir path. Readers and cleanup also probe
- the prior repository and double-hyphen variant encodings, deduplicating when
- a repository or variant never needed migration.
+ the prior repository and double-hyphen variant encodings, plus the
+ pre-``resolve`` cache-scope digest, deduplicating when a repository, variant
+ or cache scope never needed migration.
+
+ ``raw_hub_cache`` is the caller's own spelling of ``hub_cache`` before
+ canonicalization, and is what the extra scope digest has to come from: the
+ canonical string resolves to itself, so deriving the fallback from it would
+ reproduce the canonical digest and probe nothing. The scope fan-out
+ collapses to one entry whenever the two spellings agree, which is every path
+ that resolves to itself.
"""
- kwargs = {"hub_cache": hub_cache, "create": False}
+ # _scope_spellings, not cache_scope_names, for the reason the repo-wide purge already
+ # uses it: the single-variant delete route hands us a root that resolve_delete_target_root
+ # has ALREADY resolved, so the raw spelling reproduces the canonical digest and the
+ # pre-resolve scope is never probed. The read paths do probe it (they are fed the raw
+ # configured setting), so an exact-variant delete left a legacy-scoped manifest or cancel
+ # marker behind for the next read to resurrect the variant as partial or cancelled.
+ # _scope_spellings adds the configured cache's own spelling only when it names the same
+ # directory, so deleting out of a non-active cache still cannot touch the active one.
+ scopes = (
+ (None,)
+ if hub_cache is None
+ else _scope_spellings(raw_hub_cache if raw_hub_cache is not None else hub_cache)
+ )
paths = [
path_factory(
repo_type,
repo_id,
variant,
+ hub_cache = hub_cache,
+ create = False,
legacy_variant_key = legacy_variant,
legacy_repo_key = legacy_repo,
legacy_hash_key = legacy_hash,
- **kwargs,
+ cache_scope = scope,
)
+ for scope in scopes
for legacy_repo in (False, True)
for legacy_variant in ((False, True) if variant is not None else (False,))
for legacy_hash in (False, True)
@@ -744,6 +826,18 @@ def verify_against_disk(manifest: Manifest, snapshot_dir: Path) -> VerifyResult:
missing: list[str] = []
mismatched: list[str] = []
for expected in manifest.expected_files:
+ # Counted missing rather than skipped, so an unverifiable entry can
+ # never read as verified. A Windows-separator path lands here, and
+ # cannot be folded onto its posix spelling in expected_path_is_safe:
+ # that guard also fronts resolved_dataset_snapshot_file, which splits on
+ # PurePosixPath, where "a\b" is one component and accepting it would
+ # hand a traversal straight through on the platform that disagrees. No
+ # writer in this package produces one -- HF rfilenames are posix and
+ # expected_files_from_snapshot_dir calls as_posix -- and one that
+ # reached a payload would already have failed _manifest_from_payload's
+ # identical check, so this stays defence in depth for a Manifest built
+ # some other way. Should such a writer ever appear, normalize it in
+ # _payload_file_path, not here.
if not expected_path_is_safe(expected.path):
missing.append(expected.path)
continue
@@ -902,8 +996,18 @@ def _owned_state_paths(
requested: Optional[str],
*,
fail_closed: bool,
+ raw_hub_cache: Optional[str | Path] = None,
) -> list[Path]:
- scoped = list(_state_paths(path_factory, repo_type, repo_id, variant, requested))
+ scoped = list(
+ _state_paths(
+ path_factory,
+ repo_type,
+ repo_id,
+ variant,
+ requested,
+ raw_hub_cache = raw_hub_cache,
+ )
+ )
paths = list(scoped)
for legacy in _state_paths(path_factory, repo_type, repo_id, variant, None):
if legacy not in scoped and _legacy_state_applies(
@@ -926,7 +1030,7 @@ def clear_cancel_marker(
download-start (a fresh attempt supersedes prior cancel state) and
again at successful completion (cleans up if the start clear failed).
"""
- requested = _canonical_hub_cache(hub_cache)
+ requested, raw = _hub_cache_spellings(hub_cache)
paths = _owned_state_paths(
marker_path,
repo_type,
@@ -934,6 +1038,7 @@ def clear_cancel_marker(
variant,
requested,
fail_closed = True,
+ raw_hub_cache = raw,
)
paths = [
candidate
@@ -976,7 +1081,7 @@ def delete_manifest(
*,
hub_cache: Optional[str | Path] = None,
) -> bool:
- requested = _canonical_hub_cache(hub_cache)
+ requested, raw = _hub_cache_spellings(hub_cache)
paths = _owned_state_paths(
manifest_path,
repo_type,
@@ -984,6 +1089,7 @@ def delete_manifest(
variant,
requested,
fail_closed = False,
+ raw_hub_cache = raw,
)
paths = [
candidate
@@ -1019,7 +1125,7 @@ def purge_state(
*_all_matching_state_paths(cancelled_dir(), repo_type, repo_id, variant),
)
else:
- requested = _canonical_hub_cache(hub_cache)
+ requested, raw = _hub_cache_spellings(hub_cache)
candidates: list[Path] = []
# Legacy unscoped state is shared: an unowned file belongs to the active
# cache (per _legacy_state_applies), so only purge it when it belongs to
@@ -1037,6 +1143,7 @@ def purge_state(
variant,
requested,
fail_closed = fail_closed,
+ raw_hub_cache = raw,
)
)
paths = tuple(dict.fromkeys(candidates))
@@ -1102,34 +1209,30 @@ def purge_all_state_for_repo(
if parent is not None
]
else:
- # This cache's scoped dir plus the legacy unscoped base; glob (not rglob) so other caches are untouched.
+ # This cache's scoped dirs plus the legacy unscoped base; glob (not rglob) so other caches are untouched.
+ # Both scope spellings, else a repo delete leaves the pre-resolve copy
+ # behind for a later read to resurrect as state for a cache that is gone.
search = []
- for scoped, base, cancel_markers in (
- (
- manifest_path(
- repo_type,
- repo_id,
- None,
- hub_cache = hub_cache,
- create = False,
- ),
- manifests_dir(create = False),
- False,
- ),
- (
- marker_path(
+ # _scope_spellings, not cache_scope_names: every production caller of this
+ # function resolves its target root first, so the raw-spelling probe would
+ # be inert here while the read path still has it -- a purged variant that
+ # the next read brings back.
+ scopes = _scope_spellings(hub_cache)
+ for path_factory, base, cancel_markers in (
+ (manifest_path, manifests_dir(create = False), False),
+ (marker_path, cancelled_dir(create = False), True),
+ ):
+ for scope in scopes:
+ scoped = path_factory(
repo_type,
repo_id,
None,
hub_cache = hub_cache,
create = False,
- ),
- cancelled_dir(create = False),
- True,
- ),
- ):
- if scoped is not None:
- search.append((scoped.parent, False, False, cancel_markers))
+ cache_scope = scope,
+ )
+ if scoped is not None:
+ search.append((scoped.parent, False, False, cancel_markers))
if base is not None:
search.append((base, False, True, cancel_markers))
for parent, recursive, legacy, cancel_markers in search:
@@ -1351,7 +1454,16 @@ def build_variant_state_index(
repo_keys.setdefault(prefix[: -len("--variant--")], set()).add(
(repo_type, normalized_repo)
)
- caches_by_scope.setdefault(cache_scope_name(canonical_cache), set()).add(canonical_cache)
+ # Both spellings of the scope dir, so state filed under the pre-resolve
+ # digest is indexed rather than silently read as "no manifest". Derived
+ # from the caller's own spelling, not the canonical one, which resolves
+ # to itself and would yield the canonical digest twice. Normally one key.
+ # _scope_spellings for the same reason as the delete: the inventory callers
+ # reach here with a directory derived from huggingface_hub.scan_cache_dir,
+ # which has already resolved it, so the raw probe alone finds nothing and
+ # the cached-model views would disagree with the progress endpoint.
+ for scope in _scope_spellings(hub_cache):
+ caches_by_scope.setdefault(scope, set()).add(canonical_cache)
active_cache = _canonical_hub_cache(active_hub_cache)
mutable: dict[
@@ -1481,16 +1593,30 @@ def _iter_variant_state_files(
if parent is None:
return
path_factory = marker_path if cancel_markers else manifest_path
- requested = _canonical_hub_cache(hub_cache)
- scoped_probe = path_factory(
- repo_type,
- repo_id,
- None,
- hub_cache = requested,
- create = False,
- )
- if scoped_probe is None:
- return
+ requested, raw = _hub_cache_spellings(hub_cache)
+ # Every scope this cache's state can sit in, so a variant filed under the
+ # pre-resolve digest is enumerated instead of reading as "no variant state".
+ #
+ # _scope_spellings, not cache_scope_names, for the same reason the delete and index paths
+ # use it: cache_scope_names recovers the legacy digest only from an UNRESOLVED path, and a
+ # variant request carrying local_path arrives here already resolved by
+ # _repo_cache_dir_for_request. On a cache reached through a symlink or a junction that left
+ # the offline listing unable to see its own partial download, or its resume control.
+ scopes = _scope_spellings(raw) if requested is not None and raw is not None else (None,)
+ scoped_dirs: list[Path] = []
+ for scope in scopes:
+ scoped_probe = path_factory(
+ repo_type,
+ repo_id,
+ None,
+ hub_cache = requested,
+ create = False,
+ cache_scope = scope,
+ )
+ if scoped_probe is None:
+ return
+ if scoped_probe.parent not in scoped_dirs:
+ scoped_dirs.append(scoped_probe.parent)
prefixes = tuple(
dict.fromkeys(
variant_filename_prefix(
@@ -1504,8 +1630,8 @@ def _iter_variant_state_files(
)
)
selected: dict[str, tuple[tuple[bool, bool], str, Path]] = {}
- for directory, legacy in ((scoped_probe.parent, False), (parent, True)):
- if legacy and directory == scoped_probe.parent:
+ for directory, legacy in (*((path, False) for path in scoped_dirs), (parent, True)):
+ if legacy and directory in scoped_dirs:
continue
try:
entries = list(directory.iterdir())
@@ -1550,11 +1676,15 @@ def _iter_variant_state_files(
variant_payload = None
variant = _variant_from_state_payload(variant_payload, fallback)
try:
+ # Unscoped: only the basename is compared below, and that is
+ # the same under every scope. Asking for a scoped path would
+ # re-derive the digest -- and pay its ``resolve`` -- once per
+ # candidate file, for a directory component never read.
canonical = path_factory(
repo_type,
repo_id,
variant,
- hub_cache = None if legacy else requested,
+ hub_cache = None,
create = False,
)
except (UnicodeError, ValueError, OSError):
diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.py
index 660ecf1cee5..17f113e9538 100644
--- a/studio/backend/hub/utils/hf_cache_state.py
+++ b/studio/backend/hub/utils/hf_cache_state.py
@@ -4,7 +4,9 @@
from __future__ import annotations
import errno
+import os
import shutil
+import stat as stat_module
import sys
from pathlib import Path, PureWindowsPath
from typing import Iterable, Iterator, Optional
@@ -24,13 +26,27 @@ TRANSPORT_MARKER_NAME = ".transport"
INCOMPLETE_SUFFIX = ".incomplete"
-def _safe_is_dir(path: Path) -> bool:
+def _safe_is_dir(path: Path, scan_errors: Optional[list] = None) -> bool:
"""``Path.is_dir()`` returning False instead of raising when the path or a
parent is unreadable (e.g. a restricted ``~/.cache/huggingface/hub``), so
- cache enumeration skips that root rather than 500ing."""
+ cache enumeration skips that root rather than 500ing.
+
+ ``scan_errors`` collects the swallowed error. A caller that only wants the dirs does not
+ care, but "we could not even stat the root" and "the root is not there" are different
+ answers to a hydrating job -- the first is not evidence the cache was deleted.
+
+ os.stat, not Path.is_dir(): as of 3.14 is_dir() answers False for EVERY OSError instead of
+ raising some and suppressing others, so the handler below could never see a permission or
+ network-mount failure and the root was recorded as a measured absence. Stat says which it
+ was.
+ """
try:
- return path.is_dir()
- except OSError:
+ return stat_module.S_ISDIR(os.stat(path).st_mode)
+ except (FileNotFoundError, NotADirectoryError):
+ return False # genuinely not a directory here; that IS the answer
+ except (OSError, ValueError) as exc:
+ if scan_errors is not None:
+ scan_errors.append(exc)
return False
@@ -41,20 +57,25 @@ def same_existing_path(first: Path, second: Path) -> bool:
return False
-def hf_cache_root(*, create: bool = False, root: Optional[Path] = None) -> Optional[Path]:
+def hf_cache_root(
+ *,
+ create: bool = False,
+ root: Optional[Path] = None,
+ scan_errors: Optional[list] = None,
+) -> Optional[Path]:
from utils.hf_cache_settings import get_hf_cache_paths
root = root or get_hf_cache_paths().hub_cache
if create:
try:
root.mkdir(parents = True, exist_ok = True)
- except OSError:
+ except OSError as exc:
return None
return root
- return root if _safe_is_dir(root) else None
+ return root if _safe_is_dir(root, scan_errors) else None
-def hf_cache_roots() -> list[Path]:
+def hf_cache_roots(scan_errors: Optional[list] = None) -> list[Path]:
from hub.utils.paths import hf_default_cache_dir, legacy_hf_cache_dir
from utils.hf_cache_settings import known_hf_hub_caches
@@ -62,11 +83,17 @@ def hf_cache_roots() -> list[Path]:
seen: set[str] = set()
def _add(path: Optional[Path]) -> None:
- if path is None or not _safe_is_dir(path):
+ if path is None or not _safe_is_dir(path, scan_errors):
return
try:
key = str(path.resolve())
- except OSError:
+ except OSError as exc:
+ # A root that stats but will not resolve -- an intermittent network mount, a
+ # Windows reparse point -- is a root we could not read, not a root that is gone.
+ # Dropping it silently let the progress scan answer "measured, no cache", which
+ # hydration acts on by retiring a download whose files may be entirely intact.
+ if scan_errors is not None:
+ scan_errors.append(exc)
return
if key in seen:
return
@@ -318,14 +345,28 @@ def _repo_dir_has_broken_snapshot_symlinks(repo_dir: Path) -> bool:
return False
-def iter_repo_cache_dirs(repo_type: str, repo_id: str) -> Iterator[Path]:
+def iter_repo_cache_dirs(
+ repo_type: str,
+ repo_id: str,
+ *,
+ scan_errors: Optional[list] = None,
+) -> Iterator[Path]:
+ """Cache dirs for this repo, skipping a root that cannot be listed.
+
+ ``scan_errors`` collects those skips. Suppressing them is right for every caller that
+ only wants the dirs, but hydration reads "no dirs" as "the cache was wiped and this
+ persisted job can be retired" -- and a root that raised EACCES or EIO is not evidence
+ of that. A caller that passes a list can tell the two apart.
+ """
target = target_dir_name(repo_type, repo_id)
- for root in hf_cache_roots():
+ for root in hf_cache_roots(scan_errors = scan_errors):
try:
for entry in root.iterdir():
if entry.name.lower() == target:
yield entry
- except OSError:
+ except OSError as exc:
+ if scan_errors is not None:
+ scan_errors.append(exc)
continue
@@ -363,8 +404,10 @@ def iter_active_repo_cache_dirs(
repo_id: str,
*,
root: Optional[Path] = None,
+ scan_errors: Optional[list] = None,
) -> Iterator[Path]:
- root = hf_cache_root(root = root)
+ # The stat itself can fail on a restricted root, and that is not evidence of absence.
+ root = hf_cache_root(root = root, scan_errors = scan_errors)
if root is None:
return
target = target_dir_name(repo_type, repo_id)
@@ -372,7 +415,9 @@ def iter_active_repo_cache_dirs(
for entry in root.iterdir():
if entry.name.lower() == target:
yield entry
- except OSError:
+ except OSError as exc: # see iter_repo_cache_dirs on why the caller may want this
+ if scan_errors is not None:
+ scan_errors.append(exc)
return
@@ -382,16 +427,41 @@ def preferred_repo_cache_dirs(
*,
force_active: bool = False,
active_root: Optional[Path] = None,
+ scan_errors: Optional[list] = None,
) -> list[Path]:
- active_entries = list(iter_active_repo_cache_dirs(repo_type, repo_id, root = active_root))
+ # iter_active_repo_cache_dirs already matches case-insensitively, so a repo
+ # dir the active root does hold is found whatever its casing; the canonical
+ # name below is only ever a placeholder for one that is not there yet.
+ active_entries = list(
+ iter_active_repo_cache_dirs(repo_type, repo_id, root = active_root, scan_errors = scan_errors)
+ )
if active_entries:
return active_entries
if force_active:
- root = hf_cache_root(root = active_root)
+ # A running or cancelling job writes into the active root and nowhere
+ # else, so its progress may only ever be read from there. hf_cache_root
+ # returns None for a root that is not a directory yet -- the first
+ # download into a freshly configured cache creates it -- and falling
+ # through from there would read a previous cache's completed copy as
+ # this run's progress and finalize a job that has not written a byte.
+ # Name the directory this run will create instead.
+ root = hf_cache_root(root = active_root) or active_root or _configured_hub_cache()
if root is not None:
canonical = repo_cache_dir_name(repo_type, repo_id)
return [root / canonical]
- return list(iter_repo_cache_dirs(repo_type, repo_id))
+ return list(iter_repo_cache_dirs(repo_type, repo_id, scan_errors = scan_errors))
+
+
+def _configured_hub_cache() -> Optional[Path]:
+ # Path()-wrapped: the setting is typed Path, but a caller (or a test) that
+ # hands back a str would otherwise turn `root / name` above into a TypeError
+ # that surfaces as an empty progress reading -- the very card being fixed.
+ try:
+ from utils.hf_cache_settings import get_hf_cache_paths
+ configured = get_hf_cache_paths().hub_cache
+ return Path(configured) if configured else None
+ except Exception:
+ return None
def has_incomplete_blobs(repo_type: str, repo_id: str) -> bool:
diff --git a/studio/backend/hub/utils/state_dir.py b/studio/backend/hub/utils/state_dir.py
index abb8626b156..45cf9950048 100644
--- a/studio/backend/hub/utils/state_dir.py
+++ b/studio/backend/hub/utils/state_dir.py
@@ -253,21 +253,94 @@ def _entry_key(
return f"{prefix}{variant_fragment}"
-def cache_scope_name(hub_cache: str | Path) -> str:
- normalized = os.path.normcase(str(Path(hub_cache).expanduser()))
+def normalize_hub_cache(hub_cache: str | Path) -> str:
+ """The one spelling of a hub cache path every state key is derived from.
+
+ ``resolve`` first so a junction, a mapped drive, an 8.3 short name or a
+ ``~`` all collapse onto the directory they name, then ``normcase`` so a
+ case-insensitive filesystem cannot spell the same directory two ways. Both
+ steps matter on Windows and neither is a no-op there; on POSIX ``normcase``
+ is identity and only ``resolve`` does any work.
+
+ Kept here rather than in download_manifest so the digest and the manifest
+ reader cannot normalize differently: a resolved/unresolved pair of the same
+ directory used to be able to produce two ``cache-<digest>`` scopes, one of
+ which held the manifest while the other was the one looked in -- a complete
+ download that could never report complete.
+ """
+ try:
+ resolved = str(Path(hub_cache).expanduser().resolve(strict = False))
+ except (OSError, RuntimeError, ValueError):
+ # Windows can refuse to resolve a path it can still open (OneDrive
+ # placeholders, a locked junction). Degrade to the expanded spelling
+ # rather than dropping the scope. It has to be exactly what
+ # legacy_cache_scope_name below builds, or that read-side counterpart
+ # would not recover the state this branch writes -- so expanduser here
+ # too, and fall back again if even that is unavailable.
+ try:
+ resolved = str(Path(hub_cache).expanduser())
+ except (OSError, RuntimeError, ValueError):
+ resolved = str(hub_cache)
+ return os.path.normcase(resolved)
+
+
+def _cache_scope_digest(normalized: str) -> str:
digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:_CACHE_SCOPE_DIGEST_LENGTH]
return f"cache-{digest}"
+def cache_scope_name(hub_cache: str | Path) -> str:
+ return _cache_scope_digest(normalize_hub_cache(hub_cache))
+
+
+def legacy_cache_scope_name(hub_cache: str | Path) -> str:
+ """The pre-``resolve`` scope name, for reads only.
+
+ State written while ``resolve`` was unavailable (or by an older build) sits
+ under this digest. Readers probe it after the canonical one so a digest
+ change never orphans an existing manifest or cancel marker; writers only
+ ever use :func:`cache_scope_name`.
+
+ Must be given the caller's own spelling of the path: handed an already
+ canonicalized one it returns the canonical digest and recovers nothing.
+ """
+ try:
+ normalized = os.path.normcase(str(Path(hub_cache).expanduser()))
+ except (OSError, RuntimeError, ValueError):
+ # Guarded like normalize_hub_cache, and for the same reason: this is now
+ # fed the caller's raw spelling, so a homeless "~" that expanduser
+ # refuses would otherwise escape a plain read as a RuntimeError.
+ normalized = os.path.normcase(str(hub_cache))
+ return _cache_scope_digest(normalized)
+
+
+def cache_scope_names(hub_cache: str | Path) -> tuple[str, ...]:
+ """Every scope dir this cache's state can be filed under, canonical first.
+
+ A single entry whenever the resolved and unresolved spellings of the path
+ agree, which is every path that resolves to itself -- so on POSIX, and on
+ Windows for anything that is not a junction, a mapped drive, an 8.3 short
+ name or a OneDrive redirect. The second entry is the read-side recovery for
+ state filed under the unresolved spelling.
+ """
+ canonical = cache_scope_name(hub_cache)
+ legacy = legacy_cache_scope_name(hub_cache)
+ return (canonical,) if legacy == canonical else (canonical, legacy)
+
+
def _cache_scope(
parent: Path,
hub_cache: Optional[str | Path],
*,
create: bool = False,
+ cache_scope: Optional[str] = None,
) -> Optional[Path]:
if hub_cache is None:
return parent
- scoped = parent / cache_scope_name(hub_cache)
+ # A precomputed scope skips re-deriving the digest -- and with it the
+ # ``resolve`` inside it -- once per probe when a caller fans one cache path
+ # out across the filename-migration spellings.
+ scoped = parent / (cache_scope or cache_scope_name(hub_cache))
if not create:
return scoped
try:
@@ -288,12 +361,18 @@ def manifest_path(
legacy_variant_key: bool = False,
legacy_repo_key: bool = False,
legacy_hash_key: bool = False,
+ cache_scope: Optional[str] = None,
) -> Optional[Path]:
"""Path to the manifest file for this triple. May or may not exist."""
parent = _subdir(_MANIFESTS_SUBDIR, create = create)
if parent is None:
return None
- parent = _cache_scope(parent, hub_cache, create = create)
+ parent = _cache_scope(
+ parent,
+ hub_cache,
+ create = create,
+ cache_scope = cache_scope,
+ )
if parent is None:
return None
entry_key = _entry_key(
@@ -317,12 +396,18 @@ def marker_path(
legacy_variant_key: bool = False,
legacy_repo_key: bool = False,
legacy_hash_key: bool = False,
+ cache_scope: Optional[str] = None,
) -> Optional[Path]:
"""Path to the cancel-marker file for this triple. May or may not exist."""
parent = _subdir(_CANCELLED_SUBDIR, create = create)
if parent is None:
return None
- parent = _cache_scope(parent, hub_cache, create = create)
+ parent = _cache_scope(
+ parent,
+ hub_cache,
+ create = create,
+ cache_scope = cache_scope,
+ )
if parent is None:
return None
entry_key = _entry_key(
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 940f7c06317..8605cbd1cd1 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -424,7 +424,9 @@ def test_list_cached_gguf_load_id_breaks_mtime_ties_like_variant_discovery(
models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
)
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
- monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda: [legacy], raising = False)
+ monkeypatch.setattr(
+ "hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [legacy], raising = False
+ )
rows = asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
@@ -692,7 +694,7 @@ def test_a_later_attempts_cancel_marker_does_not_break_the_pinned_quant(monkeypa
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: root if root is not None else active,
+ lambda create = False, root = None, **kw: root if root is not None else active,
)
monkeypatch.setattr(
GV,
@@ -752,7 +754,7 @@ def test_the_pins_excuse_covers_only_the_quants_it_holds(monkeypatch, tmp_path):
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: root if root is not None else active,
+ lambda create = False, root = None, **kw: root if root is not None else active,
)
monkeypatch.setattr(
GV,
@@ -809,7 +811,7 @@ def test_a_later_attempts_incomplete_blob_does_not_break_the_pinned_quant(monkey
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: root if root is not None else active,
+ lambda create = False, root = None, **kw: root if root is not None else active,
)
variant = GgufVariantInfo(
filename = "Model-Q4_K_M.gguf",
@@ -1155,7 +1157,7 @@ def test_vision_is_read_from_the_cache_root_holding_the_row(monkeypatch, tmp_pat
models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
)
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
- monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active, legacy])
row = {
c["repo_id"]: c
@@ -1189,7 +1191,7 @@ def test_vision_is_not_invented_for_a_copy_that_ships_no_projector(monkeypatch,
models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
)
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
- monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active, legacy])
row = {
c["repo_id"]: c
@@ -3514,7 +3516,7 @@ def test_a_cancelled_siblings_resume_survives_the_local_listing(monkeypatch, tmp
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: root if root is not None else active,
+ lambda create = False, root = None, **kw: root if root is not None else active,
)
# Disk-only means disk-only: a remote listing here would be the bug this route avoids.
@@ -3557,7 +3559,7 @@ def test_a_cancelled_sibling_survives_a_failed_remote_listing(monkeypatch, tmp_p
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: root if root is not None else active,
+ lambda create = False, root = None, **kw: root if root is not None else active,
)
def _unreachable(*args, **kwargs):
@@ -3596,7 +3598,7 @@ def test_a_cancelled_siblings_marker_shows_on_the_repo_row(monkeypatch, tmp_path
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: root if root is not None else active,
+ lambda create = False, root = None, **kw: root if root is not None else active,
)
from hub.services.models import cache_inventory
@@ -3963,7 +3965,8 @@ def _pin_caches(monkeypatch, active: Path, roots: list[Path]) -> None:
source = "test",
),
)
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: list(roots))
+ # **kw so the stub keeps matching the real signature, which now takes scan_errors.
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: list(roots))
def _unreachable_hub(monkeypatch) -> None:
diff --git a/studio/backend/tests/test_dataset_cache_paths.py b/studio/backend/tests/test_dataset_cache_paths.py
index 74c8b96ba38..0b5eda0f9fa 100644
--- a/studio/backend/tests/test_dataset_cache_paths.py
+++ b/studio/backend/tests/test_dataset_cache_paths.py
@@ -22,7 +22,7 @@ from hub.utils import (
@pytest.fixture(autouse = True)
def _known_cache_root(monkeypatch, tmp_path):
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"utils.paths.storage_roots.cache_root",
lambda: tmp_path / "app-cache",
@@ -93,7 +93,7 @@ def test_dataset_snapshot_rejects_lookalike_outside_known_cache(monkeypatch, tmp
allowed = tmp_path / "allowed"
allowed.mkdir()
repo_root, _ = _dataset_repo(tmp_path / "outside", "Org/Data")
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [allowed])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [allowed])
assert dataset_cache.dataset_snapshot_from_cache_path(str(repo_root), "Org/Data") is None
@@ -602,7 +602,7 @@ def test_dataset_completion_isolated_and_purged_by_hub_cache(monkeypatch, tmp_pa
(snapshot_a / "train.parquet").write_bytes(b"four")
(snapshot_b / "train.parquet").write_bytes(b"five!")
monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [cache_a, cache_b])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [cache_a, cache_b])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: types.SimpleNamespace(hub_cache = cache_a),
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index 9219c8fe94c..e3ea58a52cb 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -59,7 +59,7 @@ def _ref_names(repo_dir: Path) -> list[str]:
def _scan(cache_root: Path, monkeypatch) -> list:
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [cache_root])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [cache_root])
return inventory_scan._compute_all_hf_cache_scans()
@@ -288,7 +288,7 @@ def _autoload_rows(
from hub.services.models import cache_inventory
from types import SimpleNamespace
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [cache_root])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [cache_root])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = cache_root),
@@ -1474,7 +1474,7 @@ def test_vision_does_not_travel_between_two_cache_roots(tmp_path, monkeypatch):
for name, payload in files.items():
(snapshot / name).write_bytes(payload)
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, previous])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [active, previous])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = active),
@@ -2451,7 +2451,7 @@ def test_a_broken_active_copy_withholds_the_compatibility_row(tmp_path, monkeypa
_repo_with(active, snapshots = {OLDER: torn}, refs = {"main": UPSTREAM_HEAD})
_repo_with(legacy, snapshots = {NEWER: whole}, refs = {"main": NEWER})
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [active, legacy])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = active),
@@ -2466,7 +2466,7 @@ def test_a_broken_active_copy_withholds_the_compatibility_row(tmp_path, monkeypa
assert cached == []
# Control: the broken copy in the other cache leaves the active one publishable.
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [legacy, active])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [legacy, active])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = legacy),
@@ -2961,7 +2961,7 @@ def test_an_all_incomplete_repo_is_offered_by_repo_id_as_partial(tmp_path, monke
snapshots = {SNAPSHOT: {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 16}},
refs = {"main": SNAPSHOT},
)
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = tmp_path),
@@ -2991,7 +2991,7 @@ def test_a_whole_repo_is_still_offered_by_repo_id_as_downloaded(tmp_path, monkey
snapshots = {SNAPSHOT: {"Model-Q4_K_M.gguf": b"\0" * 64}},
refs = {"main": SNAPSHOT},
)
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = tmp_path),
@@ -3027,7 +3027,7 @@ def _split_payload_rows(tmp_path, monkeypatch, *, where: str, refs: dict) -> lis
},
refs = refs,
)
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [active, legacy])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = active),
@@ -3090,7 +3090,7 @@ def test_a_self_contained_snapshot_is_not_made_partial_by_a_second_one(
},
refs = refs,
)
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [active, legacy])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = active),
@@ -3140,7 +3140,7 @@ def test_a_newer_companion_only_snapshot_does_not_make_the_ref_snapshot_partial(
os.utime(repo_dir / "snapshots" / OLDER, (1_000_000, 1_000_000))
os.utime(repo_dir / "snapshots" / SNAPSHOT, (2_000_000, 2_000_000))
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = tmp_path),
@@ -3924,7 +3924,7 @@ def _compat_cached_models(cache_root: Path, monkeypatch) -> list[str]:
import routes.models as models_route
- monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [cache_root])
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda **kw: [cache_root])
monkeypatch.setattr(
"utils.hf_cache_settings.get_hf_cache_paths",
lambda: SimpleNamespace(hub_cache = cache_root),
diff --git a/studio/backend/tests/test_model_cache_snapshot.py b/studio/backend/tests/test_model_cache_snapshot.py
index eedcb4e6970..0e9692368c4 100644
--- a/studio/backend/tests/test_model_cache_snapshot.py
+++ b/studio/backend/tests/test_model_cache_snapshot.py
@@ -14,7 +14,7 @@ latest_snapshot_from_cache_path = hf_cache_state.latest_snapshot_from_cache_path
@pytest.fixture(autouse = True)
def _known_cache_root(monkeypatch, tmp_path):
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
def _model_repo(root: Path, repo_id: str) -> Path:
@@ -138,7 +138,7 @@ def test_rejects_lookalike_repo_outside_known_cache(monkeypatch, tmp_path):
allowed.mkdir()
repo_root = _model_repo(tmp_path / "outside", "Org/Model")
_snapshot(repo_root, "rev", ("config.json",))
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [allowed])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [allowed])
assert (
latest_snapshot_from_cache_path(str(repo_root), "model", "Org/Model", ("config.json",))
diff --git a/studio/backend/tests/test_training_cached_start.py b/studio/backend/tests/test_training_cached_start.py
index c1d2fcd9789..8b53e6c9f36 100644
--- a/studio/backend/tests/test_training_cached_start.py
+++ b/studio/backend/tests/test_training_cached_start.py
@@ -23,7 +23,7 @@ _BACKEND_ROOT = Path(__file__).resolve().parent.parent
@pytest.fixture(autouse = True)
def _known_cache_root(monkeypatch, tmp_path):
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
def _load_route_module(name: str):
diff --git a/studio/backend/tests/test_training_preflight.py b/studio/backend/tests/test_training_preflight.py
index d6bfc4851e4..d02299c0a86 100644
--- a/studio/backend/tests/test_training_preflight.py
+++ b/studio/backend/tests/test_training_preflight.py
@@ -497,7 +497,7 @@ def test_first_remote_train_load_records_exact_dataset_snapshot(monkeypatch, tmp
}
}
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"core.training.trainer.load_dataset",
lambda **_kwargs: train,
@@ -530,7 +530,7 @@ def test_manual_eager_slice_attests_original_hub_stream(monkeypatch, tmp_path):
take = lambda _count: [{"text": "example"}],
)
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
monkeypatch.setattr(
"core.training.trainer.load_dataset",
lambda **kwargs: stream
diff --git a/studio/backend/tests/test_training_provenance.py b/studio/backend/tests/test_training_provenance.py
index 8fcea96ba62..1e9b29c65e2 100644
--- a/studio/backend/tests/test_training_provenance.py
+++ b/studio/backend/tests/test_training_provenance.py
@@ -36,7 +36,7 @@ def _load_training_route():
@pytest.fixture(autouse = True)
def _cache_roots(monkeypatch, tmp_path):
- monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda: [tmp_path])
+ monkeypatch.setattr(hf_cache_state, "hf_cache_roots", lambda **kw: [tmp_path])
datasets_cache = tmp_path / "datasets-processed"
datasets_cache.mkdir()
monkeypatch.setattr(dataset_cache, "hf_datasets_cache_roots", lambda: [datasets_cache])
diff --git a/studio/frontend/src/features/hub/download-manager/adopt-rules.ts b/studio/frontend/src/features/hub/download-manager/adopt-rules.ts
new file mode 100644
index 00000000000..a83f911eaef
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/adopt-rules.ts
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * Two decisions the download manager makes from a single progress reading.
+ *
+ * A leaf module on purpose: both are pure, both used to be wrong in the same way (reading a zero
+ * byte count as evidence of something it is not), and living here they can be exercised without
+ * dragging the poll loop's or the hydrator's import graph into a test.
+ */
+
+/**
+ * Whether an adopted job keeps the persisted byte counters.
+ *
+ * Adopting a DIFFERENT generation means the run those bytes described is over and a new one is in
+ * flight. Seeding them anyway, while `serverGeneration` jumps straight to the new value, leaves
+ * the first poll seeing no generation change: the new run's legitimate zero reads as "could not
+ * measure" and the card stays pinned to the previous run's bytes until a positive count arrives.
+ */
+export function carriesOverSeed(
+ adopt: boolean,
+ persistedGeneration: number | undefined,
+ probedGeneration: number | undefined,
+): boolean {
+ if (!adopt) return false;
+ // An unknown generation on either side is not evidence of a new run, so the seed is kept:
+ // that is the adopt-after-reload path, where the counters are all we have.
+ if (!Number.isSafeInteger(probedGeneration) || persistedGeneration === undefined) return true;
+ return persistedGeneration === probedGeneration;
+}
+
+/**
+ * "active" (the job is adoptable) or "gone" (its cache was wiped), from one raw reading.
+ *
+ * A zero alone is not proof of a wipe: a transient measurement failure comes back as a perfectly
+ * successful all-zero response, and calling that "gone" drops a job whose partial cache is sitting
+ * right there. `cache_path` is the discriminator -- the backend answers null only when no cache dir
+ * for this repo exists at all, and a dir it scanned and measured at zero still names itself. An
+ * older backend that omits the field entirely is unknown rather than absent, so the job survives.
+ *
+ * `cacheMeasured === false` is the backend saying the scan never happened (an unreadable root),
+ * which is unknown rather than absent. It is a field of its own because these readings are
+ * serialized through DownloadProgressResponse, whose `cache_path` defaults to None -- omitting
+ * the key was reinstated as an explicit null before the frontend ever saw it.
+ *
+ * But the repo dir is the wrong granularity for a variant. Sibling quants share one, so deleting
+ * a variant's files leaves the dir standing and this read "zero bytes, and a directory exists" as
+ * resumable -- adopting a phantom that blocked a fresh download of that same variant until the
+ * idle grace expired. `target_present === false` is the backend saying it looked for THIS target
+ * and found nothing; null (unknown, or an older backend) leaves the repo-level rule in charge.
+ */
+export function idleProbeVerdict(
+ downloadedBytes: number,
+ cachePath: string | null | undefined,
+ targetPresent?: boolean | null,
+ cacheMeasured?: boolean,
+): "active" | "gone" {
+ // Unknown first: a scan that could not be completed says nothing either way.
+ if (cacheMeasured === false) return "active";
+ // Then the EXPLICIT verdict, ahead of the byte count. The two can disagree: on the
+ // unknown-hash path the byte reading falls back to a retained manifest and counts a shared
+ // mmproj or MTP companion that outlived the main shard, while the by-name scan correctly
+ // reports the quant itself gone. Believing the bytes there re-adopts the phantom and blocks
+ // a fresh download of the deleted variant.
+ if (targetPresent === false) return "gone";
+ if (downloadedBytes > 0) return "active";
+ // A MEASURED scan with no cache path is an absence, however it was serialized. The GGUF
+ // progress route sets response_model_exclude_none, so its measured-empty answer drops
+ // cache_path entirely rather than sending null -- which read as "older backend, unknown"
+ // and re-adopted a job whose cache was deleted, blocking a fresh download of it. An older
+ // backend sends no cache_measured at all and keeps the null-only rule below.
+ if (cacheMeasured === true) return cachePath == null ? "gone" : "active";
+ return cachePath === null ? "gone" : "active";
+}
diff --git a/studio/frontend/src/features/hub/download-manager/api.ts b/studio/frontend/src/features/hub/download-manager/api.ts
index 5ec3b7996b0..d49ab31e910 100644
--- a/studio/frontend/src/features/hub/download-manager/api.ts
+++ b/studio/frontend/src/features/hub/download-manager/api.ts
@@ -127,6 +127,15 @@ export interface DownloadProgressResponse {
expected_bytes: number;
progress: number;
cache_path: string | null;
+ /**
+ * Whether the backend found anything for THIS target (variant), as opposed to the shared
+ * repo cache directory existing. Null where it cannot say, and absent from an older
+ * backend -- both of which leave the repo-level rule in charge.
+ */
+ target_present?: boolean | null;
+ /** False when the cache could not be scanned at all: unknown, not empty. Absent from an
+ * older backend, which is also unknown. */
+ cache_measured?: boolean;
}
export type DownloadProgressOptions = {
diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
index 3dde57e259e..88d15f696ce 100644
--- a/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
+++ b/studio/frontend/src/features/hub/download-manager/download-manager-types.ts
@@ -100,6 +100,16 @@ export interface ProgressLike {
complete_on_disk?: boolean;
expected_bytes: number;
progress: number;
+ /** The scanned cache dir, or null when no cache for this repo exists at all. Optional so an
+ * older backend's response still satisfies this shape; hydration treats absent as unknown. */
+ cache_path?: string | null;
+ /** Whether the backend found anything for THIS target (variant) rather than the shared repo
+ * cache dir. Null where it cannot say, absent from an older backend; both leave the
+ * repo-level cache_path rule in charge. */
+ target_present?: boolean | null;
+ /** False when the cache could not be scanned at all: unknown, not empty. Absent from an
+ * older backend, which is also unknown. */
+ cache_measured?: boolean;
}
export type Terminal = "complete" | "cancelled" | "error" | "gone";
diff --git a/studio/frontend/src/features/hub/download-manager/hydration.ts b/studio/frontend/src/features/hub/download-manager/hydration.ts
index 84d38312817..b7340344a79 100644
--- a/studio/frontend/src/features/hub/download-manager/hydration.ts
+++ b/studio/frontend/src/features/hub/download-manager/hydration.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { idleProbeVerdict } from "./adopt-rules";
import { disposableTimeoutSignal } from "../lib/abort-signals";
import {
getActiveDatasetDownloads,
@@ -179,14 +180,34 @@ async function probeHydratedIdleProgress(
);
const current = getState().jobs[key];
if (!current || !ACTIVE_STATES.has(current.state)) return "settled";
- const { downloadedBytes } = applyProgressUpdate(key, current, progressResp);
+ applyProgressUpdate(key, current, progressResp);
const updated = getState().jobs[key];
if (!updated || !ACTIVE_STATES.has(updated.state)) return "settled";
if (hasObservedExpectedBytes(updated)) {
finalize(key, "complete", { bytes: updated.downloadedBytes });
return "settled";
}
- return downloadedBytes > 0 ? "active" : "gone";
+ // The raw reading decides this one, not the figure the card keeps. Whether
+ // anything is on disk is a question about the cache, and a persisted job
+ // whose cache was wiped has to read "gone" here rather than adopt and sit
+ // in the panel as a phantom download until the idle-evict grace expires
+ // sixty seconds later, blocking a fresh start for the same repo meanwhile.
+ // The reason the resolved figure holds a zero over -- an unresolvable
+ // variant file set -- is answered on the backend now, so a finished
+ // download does not reach this line reading zero in the first place.
+ //
+ // A zero alone is still not proof, though: a transient measurement failure comes back as a
+ // perfectly successful all-zero response, and calling that "gone" drops a job whose partial
+ // cache is sitting right there. cache_path is the discriminator -- the backend only answers
+ // null when no cache dir for this repo exists at all, and a dir it scanned and measured at
+ // zero still names itself. So the cache being absent is what retires the card, not the
+ // counter being zero.
+ return idleProbeVerdict(
+ progressResp.downloaded_bytes,
+ progressResp.cache_path,
+ progressResp.target_present,
+ progressResp.cache_measured,
+ );
} catch {
return "active";
}
diff --git a/studio/frontend/src/features/hub/download-manager/poll-loop.ts b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
index 13d0604b894..f32d5b3b02b 100644
--- a/studio/frontend/src/features/hub/download-manager/poll-loop.ts
+++ b/studio/frontend/src/features/hub/download-manager/poll-loop.ts
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import { carriesOverSeed } from "./adopt-rules";
import { invalidateGgufVariantsCache } from "../inventory/api";
import { getHfToken } from "../stores/hf-token-store";
import { bumpInventoryVersion } from "../stores/inventory-events";
@@ -21,7 +22,6 @@ import {
HIDDEN_POLL_INTERVAL_MS,
IDLE_EVICT_GRACE_MS,
INVENTORY_BUMP_DEBOUNCE_MS,
- MAX_PROGRESS_FRACTION,
POLL_BACKOFF_AFTER_MS,
POLL_BACKOFF_INTERVAL_MS,
POLL_DEGRADED_AFTER_MS,
@@ -76,6 +76,10 @@ import {
scheduleRemoval,
setExpectedBytesForJob,
} from "./download-manager-state";
+import {
+ hasObservedExpectedBytes,
+ resolveProgressUpdate,
+} from "./progress-reconcile";
import {
clearWatchdog,
runtimeRegistry,
@@ -129,75 +133,7 @@ function withDownloadTimeout<T>(
return withPollRequestTimeout(null, request);
}
-export function hasObservedExpectedBytes(job: ManagedDownload): boolean {
- // Finalized bytes only: an `.incomplete` blob hitting expected size isn't
- // finished until the backend verifies it's usable on disk.
- return (
- job.expectedBytes > 0 &&
- job.completedBytes >= job.expectedBytes &&
- job.completeOnDisk
- );
-}
-
-export function resolveProgressUpdate(
- job: ManagedDownload,
- progressResp: ProgressLike,
- opts: { resetMonotonic?: boolean } = {},
-): {
- expected: number;
- downloadedBytes: number;
- completedBytes: number;
- completeOnDisk: boolean;
- fraction: number;
- madeProgress: boolean;
-} {
- const reported = progressResp.expected_bytes;
- const isGgufVariantJob =
- job.kind === DOWNLOAD_KIND.MODEL && job.variant !== null;
- const backendOwnsGgufProgress = isGgufVariantJob && reported > 0;
- // GGUF totals are backend-owned (non-monotonic); snapshots stay monotonic to
- // absorb jitter, but a generation bump (XET redownload, restart, re-adoption)
- // must drop the stale high-water mark and snap to the new run's bytes.
- const trustBackend = backendOwnsGgufProgress || opts.resetMonotonic === true;
- const expected = trustBackend
- ? reported > 0
- ? reported
- : job.expectedBytes
- : Math.max(reported > 0 ? reported : job.expectedBytes, job.expectedBytes);
- const previousDownloadedBytes = job.downloadedBytes;
- const downloadedBytes = trustBackend
- ? Math.max(0, progressResp.downloaded_bytes)
- : Math.max(previousDownloadedBytes, progressResp.downloaded_bytes);
- const completedBytes = trustBackend
- ? Math.max(0, progressResp.completed_bytes ?? 0)
- : Math.max(job.completedBytes, progressResp.completed_bytes ?? 0);
- const completeOnDisk = progressResp.complete_on_disk === true;
- const madeProgress =
- opts.resetMonotonic === true ||
- downloadedBytes > previousDownloadedBytes ||
- expected !== job.expectedBytes;
- const rawFraction =
- progressResp.progress > 0
- ? progressResp.progress
- : expected > 0
- ? downloadedBytes / expected
- : 0;
- const cappedFraction = Math.min(rawFraction, MAX_PROGRESS_FRACTION);
- // Keep the GGUF variant bar monotonic: backend progress is recomputed from the
- // shared per-repo blobs/ dir, so a sibling quant, generation bump, or
- // no-metadata poll can dip one reading. Resets via startJob's seed fraction.
- const fraction = isGgufVariantJob
- ? Math.max(cappedFraction, job.fraction)
- : cappedFraction;
- return {
- expected,
- downloadedBytes,
- completedBytes,
- completeOnDisk,
- fraction,
- madeProgress,
- };
-}
+export { hasObservedExpectedBytes, resolveProgressUpdate };
export function applyProgressUpdate(
key: string,
@@ -651,9 +587,14 @@ export async function startJob(
teardownRuntime(key);
throw error;
}
- const seedDownloaded = opts.adopt ? (existing?.downloadedBytes ?? 0) : 0;
- const seedCompleted = opts.adopt ? (existing?.completedBytes ?? 0) : 0;
- const seedFraction = opts.adopt ? (existing?.fraction ?? 0) : 0;
+ const carryOverSeed = carriesOverSeed(
+ opts.adopt === true,
+ existing?.serverGeneration,
+ opts.generation,
+ );
+ const seedDownloaded = carryOverSeed ? (existing?.downloadedBytes ?? 0) : 0;
+ const seedCompleted = carryOverSeed ? (existing?.completedBytes ?? 0) : 0;
+ const seedFraction = carryOverSeed ? (existing?.fraction ?? 0) : 0;
// An adopted job never called apiStart, so it learns the run's generation from
// the probe (or persisted value) to scope a later cancel to this exact run.
const seedGeneration = opts.adopt
diff --git a/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts b/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts
new file mode 100644
index 00000000000..c5aadb97c45
--- /dev/null
+++ b/studio/frontend/src/features/hub/download-manager/progress-reconcile.ts
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// One backend progress reading reconciled against the job's current figures.
+// Split out of poll-loop so it can be exercised on its own: poll-loop reaches
+// the store, the toaster and the API client, and this is the part that decides
+// what a card shows and when a download counts as finished.
+
+import { DOWNLOAD_KIND } from "./constants";
+import { MAX_PROGRESS_FRACTION } from "./download-manager-config";
+import type { ManagedDownload, ProgressLike } from "./download-manager-types";
+
+export function hasObservedExpectedBytes(job: ManagedDownload): boolean {
+ // Finalized bytes only: an `.incomplete` blob hitting expected size isn't
+ // finished until the backend verifies it's usable on disk.
+ return (
+ job.expectedBytes > 0 &&
+ job.completedBytes >= job.expectedBytes &&
+ job.completeOnDisk
+ );
+}
+
+// A number off the wire (a byte count or a fraction), or 0 when it is not a usable
+// one. The payload is
+// cast from raw JSON with no runtime validation (apiGetProgress -> ProgressLike),
+// and a NaN or an Infinity survives every comparison below to reach the store as
+// a width of "NaN%" on the progress bar. 0 reads as "not measured", which is the
+// conservative answer here: it holds the card's last figure rather than
+// publishing a garbage one, and never manufactures a completion.
+function finiteReading(value: number | null | undefined): number {
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
+}
+
+export function resolveProgressUpdate(
+ job: ManagedDownload,
+ progressResp: ProgressLike,
+ opts: { resetMonotonic?: boolean } = {},
+): {
+ expected: number;
+ downloadedBytes: number;
+ completedBytes: number;
+ completeOnDisk: boolean;
+ fraction: number;
+ madeProgress: boolean;
+} {
+ const reported = finiteReading(progressResp.expected_bytes);
+ const isGgufVariantJob =
+ job.kind === DOWNLOAD_KIND.MODEL && job.variant !== null;
+ const backendOwnsGgufProgress = isGgufVariantJob && reported > 0;
+ // GGUF totals are backend-owned (non-monotonic); snapshots stay monotonic to
+ // absorb jitter, but a generation bump (XET redownload, restart, re-adoption)
+ // must drop the stale high-water mark and snap to the new run's bytes.
+ const resetMonotonic = opts.resetMonotonic === true;
+ const trustBackend = backendOwnsGgufProgress || resetMonotonic;
+ const expected = trustBackend
+ ? reported > 0
+ ? reported
+ : job.expectedBytes
+ : Math.max(reported > 0 ? reported : job.expectedBytes, job.expectedBytes);
+ const previousDownloadedBytes = job.downloadedBytes;
+ const reportedCompleted = finiteReading(progressResp.completed_bytes);
+ // Hold the last reading through a poll that found nothing, rather than
+ // publishing the "I could not measure this" answer as a measurement. The
+ // backend recomputes both counters from the shared per-repo blobs/ dir every
+ // poll, and when it cannot resolve a variant's expected files it returns an
+ // all-zero reading against the caller's catalog-hinted total; the failure
+ // behind that is negatively cached, so every poll for the whole TTL says the
+ // same thing and a finished card reads "0 B of 33 GB" until the app restarts.
+ //
+ // Deliberately NOT a high-water mark, which is what the fraction below uses.
+ // Bytes have legitimate reasons to fall inside one generation and the
+ // fraction does not: an XET run that falls back to HTTP re-claims with the
+ // same generation and a freshly computed completed_baseline_bytes, and
+ // resuming in XET mode purges the partial outright. A floor would pin the
+ // card near full for the whole retry and starve the rolling-window rate of
+ // the movement it needs to publish a speed or an ETA. Only a zero is ignored,
+ // so every real change -- up or down -- still lands on the next poll.
+ const reportedDownloaded = finiteReading(progressResp.downloaded_bytes);
+ const downloadedBytes = resetMonotonic
+ ? Math.max(0, reportedDownloaded)
+ : reportedDownloaded > 0
+ ? reportedDownloaded
+ : Math.max(previousDownloadedBytes, 0);
+ // Same rule for the finalized counter.
+ const measuredCompleted = resetMonotonic || reportedCompleted > 0;
+ const completedBytes = resetMonotonic
+ ? Math.max(0, reportedCompleted)
+ : measuredCompleted
+ ? reportedCompleted
+ : Math.max(job.completedBytes, 0);
+ // ...and the completion flag is only honoured on a poll that measured the
+ // counter it is a statement about. Holding the bytes over made a new pairing
+ // reachable that the plain reading never was: LAST poll's completed_bytes
+ // beside THIS poll's complete_on_disk, a completion neither reading showed on
+ // its own. The backend does hold the invariant that would rule that out
+ // (complete_on_disk is only set once completed_bytes clears the total), but a
+ // false "complete" retires the card and drops the download, and that is not an
+ // outcome to leave resting on a cross-tier promise no code here checks. Both
+ // halves of hasObservedExpectedBytes now provably come from the same reading.
+ const completeOnDisk = progressResp.complete_on_disk === true && measuredCompleted;
+ const madeProgress =
+ resetMonotonic ||
+ // An UNMEASURED scan is not an idle one. The backend says cache_measured false when it
+ // could not read the cache at all, and the response is then all zeroes -- which the idle
+ // grace reads as "nothing is happening" and finalizes the job as gone. The initial adopt
+ // probe already refuses to retire on that shape; without this the protection lasted only
+ // until the first adopted poll loop ran its grace out.
+ progressResp.cache_measured === false ||
+ downloadedBytes > previousDownloadedBytes ||
+ expected !== job.expectedBytes;
+ const reportedFraction = finiteReading(progressResp.progress);
+ const rawFraction =
+ reportedFraction > 0
+ ? reportedFraction
+ : expected > 0
+ ? downloadedBytes / expected
+ : 0;
+ const cappedFraction = Math.min(rawFraction, MAX_PROGRESS_FRACTION);
+ // Keep the GGUF variant bar monotonic: backend progress is recomputed from the
+ // shared per-repo blobs/ dir, so a sibling quant, generation bump, or
+ // no-metadata poll can dip one reading. Resets via startJob's seed fraction.
+ //
+ // NOT across a generation change, though. `resetMonotonic` is the caller saying another
+ // client restarted this job, and it already clears the byte counters -- carrying the old
+ // generation's high-water mark over pinned a retry that starts at 0 B to the previous run's
+ // 99% for its entire life, which is the stale card this whole path exists to remove.
+ const fraction =
+ isGgufVariantJob && !resetMonotonic
+ ? Math.max(cappedFraction, job.fraction)
+ : cappedFraction;
+ return {
+ expected,
+ downloadedBytes,
+ completedBytes,
+ completeOnDisk,
+ fraction,
+ madeProgress,
+ };
+}
diff --git a/studio/frontend/tests/download-adopt-and-hydrate.test.ts b/studio/frontend/tests/download-adopt-and-hydrate.test.ts
new file mode 100644
index 00000000000..924604438b8
--- /dev/null
+++ b/studio/frontend/tests/download-adopt-and-hydrate.test.ts
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Two decisions the download manager makes from a single reading, both of which used to be
+// wrong in the same way: treating a zero byte count as evidence of something it is not.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { carriesOverSeed, idleProbeVerdict } = await import(
+ "../src/features/hub/download-manager/adopt-rules.ts"
+);
+
+test("adopting a new generation drops the previous run's byte seed", () => {
+ // The persisted job describes generation 4; the backend reports 5 in flight. Seeding 4's bytes
+ // while serverGeneration jumps to 5 leaves the first poll seeing no change, so the new run's
+ // legitimate zero reads as "could not measure" and the card stays pinned to the old bytes.
+ assert.equal(carriesOverSeed(true, 4, 5), false);
+ assert.equal(carriesOverSeed(true, 4, 4), true, "the same run keeps its counters");
+});
+
+test("an unknown generation is not evidence of a new run", () => {
+ // Adopt-after-reload with nothing probed: the persisted counters are all there is, and
+ // discarding them would blank a card that is about to be confirmed.
+ assert.equal(carriesOverSeed(true, 4, undefined), true);
+ assert.equal(carriesOverSeed(true, undefined, 5), true);
+ assert.equal(carriesOverSeed(true, 4, Number.NaN), true);
+ assert.equal(carriesOverSeed(false, 4, 5), false, "a fresh start never seeds");
+});
+
+test("only an absent cache retires a hydrated job, not a zero reading", () => {
+ // A transient measurement failure is a successful all-zero response. Calling that "gone" drops
+ // a job whose partial cache is still on disk, and the user loses the resume.
+ assert.equal(idleProbeVerdict(0, "/hub/models--unsloth--x"), "active");
+ assert.equal(idleProbeVerdict(0, null), "gone");
+ assert.equal(idleProbeVerdict(1024, null), "active", "bytes outrank a missing path");
+});
+
+test("an older backend that omits cache_path leaves the job adoptable", () => {
+ // Absent is unknown, not absent-on-disk: guessing "gone" here would drop live downloads for
+ // every install that has not restarted its backend yet.
+ assert.equal(idleProbeVerdict(0, undefined), "active");
+});
+
+test("a variant whose own files are gone does not survive on a sibling's cache dir", () => {
+ // Sibling quants share one repo cache directory. Delete Q4_K_M's files while Q8_0 keeps the
+ // dir alive and the reading is "zero bytes, and a directory exists" -- which read as
+ // resumable, adopted a phantom, and blocked a fresh download of that same variant until the
+ // idle grace expired sixty seconds later.
+ assert.equal(
+ idleProbeVerdict(0, "/hub/models--unsloth--x", false),
+ "gone",
+ "the repo dir is the wrong granularity for a variant",
+ );
+ // Positive evidence only in that one direction: unknown, and an older backend that never
+ // sends the field, both leave the repo-level rule in charge.
+ assert.equal(idleProbeVerdict(0, "/hub/models--unsloth--x", null), "active");
+ assert.equal(idleProbeVerdict(0, "/hub/models--unsloth--x", undefined), "active");
+ // And an EXPLICIT absence outranks the byte count, which the two can genuinely disagree
+ // about: on the unknown-hash path the byte reading falls back to a retained manifest and
+ // counts a shared mmproj or MTP companion that outlived the main shard, while the by-name
+ // scan correctly reports the quant itself gone. Believing the bytes re-adopts the phantom.
+ assert.equal(idleProbeVerdict(4096, "/hub/models--unsloth--x", false), "gone");
+ // Bytes still decide when presence is unknown.
+ assert.equal(idleProbeVerdict(4096, "/hub/models--unsloth--x", null), "active");
+ assert.equal(idleProbeVerdict(0, null, true), "gone", "no cache at all is still gone");
+});
+
+test("a measured scan with no cache path retires the job however it was serialized", () => {
+ // /api/hub/gguf-download-progress sets response_model_exclude_none, so its measured-empty
+ // answer OMITS cache_path rather than sending null. Read as "older backend, unknown", that
+ // re-adopted a job whose cache directory had been deleted and blocked a fresh download of it.
+ assert.equal(idleProbeVerdict(0, undefined, null, true), "gone");
+ assert.equal(idleProbeVerdict(0, null, null, true), "gone");
+ // A measured scan that DID find the cache is still active, and an unmeasured one is unknown.
+ assert.equal(idleProbeVerdict(0, "/hub/models--unsloth--x", null, true), "active");
+ assert.equal(idleProbeVerdict(0, undefined, null, false), "active");
+ // An older backend sends no flag at all and keeps the null-only rule.
+ assert.equal(idleProbeVerdict(0, undefined, null, undefined), "active");
+});
+
+
+test("a scan that never happened does not retire a job", () => {
+ // The reading is unknown, not empty. It travels as its own flag because these responses go
+ // through DownloadProgressResponse, whose cache_path defaults to null -- so omitting the key
+ // was reinstated as an explicit null on the wire and the distinction died before the
+ // frontend saw it, on every route.
+ assert.equal(idleProbeVerdict(0, null, null, false), "active");
+ // It outranks the target answer too: nothing was established either way.
+ assert.equal(idleProbeVerdict(0, null, false, false), "active");
+ // A measured scan behaves exactly as before, and so does an older backend that omits it.
+ assert.equal(idleProbeVerdict(0, null, null, true), "gone");
+ assert.equal(idleProbeVerdict(0, null, null, undefined), "gone");
+});
diff --git a/studio/frontend/tests/download-progress-reconcile.test.ts b/studio/frontend/tests/download-progress-reconcile.test.ts
new file mode 100644
index 00000000000..c3d2a126e7d
--- /dev/null
+++ b/studio/frontend/tests/download-progress-reconcile.test.ts
@@ -0,0 +1,330 @@
+// 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 download card holds its last reading through a poll that measured nothing,
+// instead of publishing "I could not measure this" as a measurement. The
+// backend recomputes both byte counters from the shared per-repo blobs/ dir
+// every poll and returns an all-zero reading when it cannot resolve a variant's
+// expected files; that failure is negatively cached, so every poll for the
+// whole TTL says the same thing and a finished card read "0 B of 33 GB".
+//
+// The rule is NOT the high-water mark the fraction uses. Bytes have legitimate
+// reasons to fall inside one generation -- an XET run falling back to HTTP
+// re-claims with the same generation and a recomputed completed_baseline_bytes,
+// and an XET resume purges the partial -- so only a zero is ignored.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type {
+ ManagedDownload,
+ ProgressLike,
+} from "../src/features/hub/download-manager/download-manager-types.ts";
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { hasObservedExpectedBytes, resolveProgressUpdate } = await import(
+ "../src/features/hub/download-manager/progress-reconcile.ts"
+);
+
+const GB = 1024 ** 3;
+const EXPECTED = 33 * GB;
+
+function job(overrides: Partial<ManagedDownload> = {}): ManagedDownload {
+ // Keyed the way jobKeyOf spells it, so the fixture stays recognisable.
+ const base: ManagedDownload = {
+ key: "model:org/model-gguf#q4_k_m",
+ kind: "model",
+ repoId: "org/model-GGUF",
+ variant: "Q4_K_M",
+ state: "running",
+ downloadedBytes: EXPECTED,
+ completedBytes: EXPECTED,
+ expectedBytes: EXPECTED,
+ completeOnDisk: false,
+ fraction: 0.99,
+ bytesPerSec: 0,
+ error: null,
+ startedAt: 1,
+ };
+ return { ...base, ...overrides };
+}
+
+/** The backend's `_empty_progress` reply: it found nothing to measure. */
+function emptyReading(overrides: Partial<ProgressLike> = {}): ProgressLike {
+ return {
+ downloaded_bytes: 0,
+ completed_bytes: 0,
+ expected_bytes: EXPECTED,
+ progress: 0,
+ complete_on_disk: false,
+ ...overrides,
+ };
+}
+
+test("an all-zero reading cannot rewrite a variant card to 0 B", () => {
+ const resolved = resolveProgressUpdate(job(), emptyReading());
+
+ assert.equal(resolved.downloadedBytes, EXPECTED);
+ assert.equal(resolved.completedBytes, EXPECTED);
+ // The total stays backend-owned, so a re-resolved variant size still lands.
+ assert.equal(resolved.expected, EXPECTED);
+ assert.equal(resolved.madeProgress, false);
+});
+
+test("a real drop still lands, so a fallback retry tracks its own bytes", () => {
+ // An XET run falling back to HTTP re-claims with the SAME generation and a
+ // freshly computed completed_baseline_bytes, so the reported figures
+ // legitimately restart low. A high-water mark would pin this card near full
+ // for the whole retry and leave the rate estimator with a flat series.
+ const resolved = resolveProgressUpdate(
+ job(),
+ emptyReading({ downloaded_bytes: GB, completed_bytes: 0, progress: 0.03 }),
+ );
+
+ assert.equal(resolved.downloadedBytes, GB);
+ assert.equal(resolved.madeProgress, false); // lower is not progress
+});
+
+test("an XET resume that purged the partial reports what is left", () => {
+ const resolved = resolveProgressUpdate(
+ job({ downloadedBytes: 20 * GB, completedBytes: 12 * GB }),
+ emptyReading({ downloaded_bytes: 12 * GB, completed_bytes: 12 * GB }),
+ );
+
+ assert.equal(resolved.downloadedBytes, 12 * GB);
+ assert.equal(resolved.completedBytes, 12 * GB);
+});
+
+test("the held reading still lets real progress through", () => {
+ const resolved = resolveProgressUpdate(
+ job({ downloadedBytes: 2 * GB, completedBytes: GB, fraction: 0.06 }),
+ emptyReading({
+ downloaded_bytes: 5 * GB,
+ completed_bytes: 4 * GB,
+ progress: 0.15,
+ }),
+ );
+
+ assert.equal(resolved.downloadedBytes, 5 * GB);
+ assert.equal(resolved.completedBytes, 4 * GB);
+ assert.equal(resolved.madeProgress, true);
+});
+
+test("an unmeasured scan keeps the idle grace from finalizing the job", () => {
+ // cache_measured false is the backend saying it could not read the cache at all, and the
+ // reply is then all zeroes. The adopt probe already refuses to retire on that shape; without
+ // the same rule here the protection lasted only until the adopted poll loop's grace ran out,
+ // and a download whose cache was merely unreadable was finalized as gone.
+ const resolved = resolveProgressUpdate(
+ job(),
+ emptyReading({ cache_measured: false }),
+ );
+
+ assert.equal(resolved.madeProgress, true);
+ // Still not a measurement: the card holds its figures.
+ assert.equal(resolved.downloadedBytes, EXPECTED);
+});
+
+test("resetMonotonic publishes the zero for a new generation", () => {
+ // The escape hatch has to keep working, or a restart would show the previous
+ // run's bytes until the new one passed them.
+ const resolved = resolveProgressUpdate(job(), emptyReading(), {
+ resetMonotonic: true,
+ });
+
+ assert.equal(resolved.downloadedBytes, 0);
+ assert.equal(resolved.completedBytes, 0);
+ assert.equal(resolved.madeProgress, true);
+});
+
+test("a snapshot job holds its reading the same way a variant does", () => {
+ const resolved = resolveProgressUpdate(
+ job({ variant: null, key: "model:org/model" }),
+ emptyReading(),
+ );
+
+ assert.equal(resolved.downloadedBytes, EXPECTED);
+ assert.equal(resolved.completedBytes, EXPECTED);
+});
+
+test("a held reading cannot manufacture a completion on its own", () => {
+ // completeOnDisk is never held over, and the backend only sets it on a
+ // reading whose own completed_bytes already cleared the bar, so the two
+ // halves of hasObservedExpectedBytes can never come from different polls.
+ const held = resolveProgressUpdate(job(), emptyReading());
+ const afterEmptyPoll = job({
+ downloadedBytes: held.downloadedBytes,
+ completedBytes: held.completedBytes,
+ completeOnDisk: held.completeOnDisk,
+ });
+ assert.equal(hasObservedExpectedBytes(afterEmptyPoll), false);
+
+ const confirmed = resolveProgressUpdate(
+ afterEmptyPoll,
+ emptyReading({
+ downloaded_bytes: EXPECTED,
+ completed_bytes: EXPECTED,
+ progress: 1,
+ complete_on_disk: true,
+ }),
+ );
+
+ assert.equal(
+ hasObservedExpectedBytes(
+ job({
+ downloadedBytes: confirmed.downloadedBytes,
+ completedBytes: confirmed.completedBytes,
+ expectedBytes: confirmed.expected,
+ completeOnDisk: confirmed.completeOnDisk,
+ }),
+ ),
+ true,
+ );
+});
+
+test("a negative byte count reads as no measurement, not as a drop", () => {
+ const resolved = resolveProgressUpdate(
+ job({ downloadedBytes: 4 * GB, completedBytes: 4 * GB }),
+ emptyReading({ downloaded_bytes: -1, completed_bytes: -1 }),
+ );
+
+ assert.equal(resolved.downloadedBytes, 4 * GB);
+ assert.equal(resolved.completedBytes, 4 * GB);
+});
+
+test("a fresh complete_on_disk cannot promote a HELD byte count to a completion", () => {
+ // The dangerous direction. Holding the last reading over an unmeasured poll
+ // made a pairing reachable that publishing the zero never was: LAST poll's
+ // completed_bytes beside THIS poll's complete_on_disk. Neither reading showed
+ // a completion; together they retire the card and drop the download. The
+ // backend does not currently emit this shape, but nothing on this side checks
+ // that, and the cost of being wrong is a download silently declared finished.
+ const resolved = resolveProgressUpdate(
+ job(),
+ emptyReading({ complete_on_disk: true }),
+ );
+
+ assert.equal(resolved.completedBytes, EXPECTED); // still held, for the card
+ assert.equal(resolved.completeOnDisk, false); // but not asserted as finished
+ assert.equal(
+ hasObservedExpectedBytes(
+ job({
+ completedBytes: resolved.completedBytes,
+ expectedBytes: resolved.expected,
+ completeOnDisk: resolved.completeOnDisk,
+ }),
+ ),
+ false,
+ );
+});
+
+test("a measured completion in the same reading still settles", () => {
+ // The guard above must not cost the real case: when the poll measured the
+ // counter it is making a claim about, the completion lands as before.
+ const resolved = resolveProgressUpdate(
+ job({ downloadedBytes: 32 * GB, completedBytes: 32 * GB, fraction: 0.97 }),
+ emptyReading({
+ downloaded_bytes: EXPECTED,
+ completed_bytes: EXPECTED,
+ progress: 1,
+ complete_on_disk: true,
+ }),
+ );
+
+ assert.equal(resolved.completeOnDisk, true);
+ assert.equal(
+ hasObservedExpectedBytes(
+ job({
+ completedBytes: resolved.completedBytes,
+ expectedBytes: resolved.expected,
+ completeOnDisk: resolved.completeOnDisk,
+ }),
+ ),
+ true,
+ );
+});
+
+test("a reading with no total keeps the card's own total, not zero", () => {
+ // The "of 33 GB" half of the reported card. expected_bytes is the caller's
+ // catalog hint echoed back, and a backend that could not size the repo
+ // returns 0; publishing that would blank the denominator on a card that
+ // already knew it. Untested before: replacing the whole expected branch with
+ // `reported` left every other assertion in this file green.
+ for (const resetMonotonic of [false, true]) {
+ const resolved = resolveProgressUpdate(
+ job({ downloadedBytes: GB, completedBytes: GB }),
+ emptyReading({ downloaded_bytes: 2 * GB, expected_bytes: 0 }),
+ { resetMonotonic },
+ );
+ assert.equal(resolved.expected, EXPECTED, `resetMonotonic=${resetMonotonic}`);
+ }
+});
+
+test("a snapshot total is a high-water mark, a variant total is backend-owned", () => {
+ // The two halves of the expected branch differ, and only one of them is a
+ // floor. A variant's total is re-derived every poll and legitimately shrinks
+ // (a re-resolved file set); a snapshot's must not dip on a jittery reading.
+ const lower = 20 * GB;
+ const variant = resolveProgressUpdate(job(), emptyReading({ expected_bytes: lower }));
+ assert.equal(variant.expected, lower);
+
+ const snapshot = resolveProgressUpdate(
+ job({ variant: null, key: "model:org/model" }),
+ emptyReading({ expected_bytes: lower }),
+ );
+ assert.equal(snapshot.expected, EXPECTED);
+});
+
+test("the bar is capped below full until the backend verifies completion", () => {
+ // Untested before: removing the cap left all eight original tests green. The
+ // cap is what stops a card sitting at 100% while files are still landing.
+ const resolved = resolveProgressUpdate(
+ job({ fraction: 0 }),
+ emptyReading({ downloaded_bytes: EXPECTED, progress: 1 }),
+ );
+
+ assert.equal(resolved.fraction, 0.99);
+});
+
+test("a non-finite reading is not a measurement", () => {
+ // ProgressLike is cast straight off raw JSON with no runtime validation, and
+ // a NaN survives every comparison here to reach the progress bar as a width
+ // of "NaN%". Treat it as "not measured" and hold the card's last figures.
+ for (const bad of [Number.NaN, Number.POSITIVE_INFINITY, null, undefined]) {
+ const resolved = resolveProgressUpdate(
+ job({ downloadedBytes: 4 * GB, completedBytes: 4 * GB, fraction: 0.12 }),
+ emptyReading({
+ downloaded_bytes: bad as unknown as number,
+ completed_bytes: bad as unknown as number,
+ expected_bytes: bad as unknown as number,
+ progress: bad as unknown as number,
+ }),
+ { resetMonotonic: true },
+ );
+
+ assert.ok(Number.isFinite(resolved.downloadedBytes), `downloaded ${String(bad)}`);
+ assert.ok(Number.isFinite(resolved.completedBytes), `completed ${String(bad)}`);
+ assert.ok(Number.isFinite(resolved.expected), `expected ${String(bad)}`);
+ assert.ok(Number.isFinite(resolved.fraction), `fraction ${String(bad)}`);
+ assert.equal(resolved.expected, EXPECTED);
+ }
+});
+
+test("a new generation resets the fraction, not only the bytes", () => {
+ // Another client restarting the same GGUF job is exactly what resetMonotonic signals, and it
+ // already clears the byte counters. The GGUF high-water mark carried the OLD generation's
+ // fraction over, so a retry starting at 0 B sat pinned at the previous run's 99% for its
+ // whole life -- the stale card this path exists to remove.
+ const resolved = resolveProgressUpdate(job({ fraction: 0.99 }), emptyReading(), {
+ resetMonotonic: true,
+ });
+
+ assert.equal(resolved.downloadedBytes, 0);
+ assert.equal(resolved.fraction, 0);
+
+ // Without the reset the mark still holds, which is what keeps a sibling-quant dip off the bar.
+ const held = resolveProgressUpdate(job({ fraction: 0.99 }), emptyReading());
+ assert.equal(held.fraction, 0.99);
+});