Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: restore cached models hidden by a dangling HF ref, and stop auto-load downloading after a failed load (#7374) (#7375)

Souravrajvi0d36e3e1c4cc5
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 807ec709912..862b1eeb24f 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -19,6 +19,7 @@ from loggers import get_logger
from hub.schemas.inventory import ModelFormat
from hub.utils import inventory_scan as hf_cache_scan
from hub.utils import download_registry
+from hub.utils.hf_cache_state import snapshot_selection_key
from hub.utils.snapshot_filters import (
snapshot_download_blob_hashes,
snapshot_download_size,
@@ -29,6 +30,7 @@ from hub.services.models.common import (
_gguf_variant_state_summary,
_is_adapter_weight_name,
_is_checkpoint_weight_name,
+ _is_training_artefact_name,
_is_gguf_filename,
_is_main_gguf_filename,
_is_mmproj_filename,
@@ -118,13 +120,15 @@ def _repo_gguf_size_bytes(repo_info) -> int:
for revision in repo_info.revisions:
rev_id = getattr(revision, "commit_hash", None) or str(id(revision))
for f in revision.files:
- if _is_main_gguf_filename(f.file_name):
+ # Snapshot-relative: only the directory marks an MTP/ drafter as a companion.
+ name = _cached_repo_file_name(f)
+ if _is_main_gguf_filename(name):
blob_path = getattr(f, "blob_path", None)
size = f.size_on_disk or 0
if blob_path:
unique_blobs[str(blob_path)] = size
else:
- unique_blobs[f"{rev_id}:{f.file_name}"] = size
+ unique_blobs[f"{rev_id}:{name}"] = size
return sum(unique_blobs.values())
@@ -149,7 +153,7 @@ def _repo_gguf_last_modified(repo_info) -> float:
latest = 0.0
for revision in repo_info.revisions:
for f in revision.files:
- if _is_main_gguf_filename(f.file_name):
+ if _is_main_gguf_filename(_cached_repo_file_name(f)):
latest = max(latest, _blob_mtime(f))
return latest
@@ -227,15 +231,15 @@ def _repo_gguf_blob_map(repo_info, *, include_companions: bool = False) -> dict[
repo_path = getattr(repo_info, "repo_path", None)
for revision in repo_info.revisions:
for f in revision.files:
+ name = _cached_repo_file_name(f)
if include_companions:
- if not _is_gguf_filename(f.file_name):
+ if not _is_gguf_filename(name):
continue
- elif not _is_main_gguf_filename(f.file_name):
+ elif not _is_main_gguf_filename(name):
continue
blob_path = getattr(f, "blob_path", None)
if not blob_path:
continue
- name = _cached_repo_file_name(f)
identity = _cached_blob_hash(blob_path, repo_path)
if identity is None:
size = int(getattr(f, "size_on_disk", 0) or 0)
@@ -260,16 +264,33 @@ def _prefer_cache_row(candidate: dict, existing: Optional[dict]) -> bool:
return int(candidate.get("size_bytes") or 0) > int(existing.get("size_bytes") or 0)
-def _cache_inventory_fields(
+class _LoadIdentity(NamedTuple):
+ """A row's load target and the directory it lands in.
+
+ *load_snapshot* is not always ``Path(load_id)``: a *load_id* left as the repo id resolves
+ through ``refs/main``, so the row describes THAT snapshot.
+ """
+
+ load_id: str
+ active_cache: bool
+ load_snapshot: Optional[Path]
+
+
+def _resolve_load_identity(
repo_id: str,
- model_format: ModelFormat,
*,
repo_path: Optional[Path] = None,
snapshot_path: Optional[Path] = None,
active_hub_cache: Optional[Path] = None,
- partial: bool = False,
- requires_variant: bool = False,
-) -> dict:
+ payload_snapshots: Optional[frozenset[str]] = None,
+) -> _LoadIdentity:
+ """Single answer to "what will this row load, and from which directory".
+
+ The partial flag, the metadata probe and the load id must agree on one directory, so resolve it
+ once here. *snapshot_path* becomes the load identity whenever the repo id will not resolve, so
+ pass a snapshot holding this row's payload, not merely the newest. *payload_snapshots* is every
+ snapshot that does; None means the caller does not track them, so *snapshot_path* is trusted.
+ """
load_id = repo_id
active_cache = True
if repo_path is not None:
@@ -285,19 +306,86 @@ def _cache_inventory_fields(
except (OSError, RuntimeError, ValueError):
active_cache = False
load_id = str(snapshot_path or repo_path)
+ # Only pin a snapshot known to hold the payload; the newest may be unusable.
+ default_snapshot: Optional[Path] = None
+ if (
+ load_id == repo_id
+ and snapshot_path is not None
+ and repo_path is not None
+ and (payload_snapshots is None or str(snapshot_path) in payload_snapshots)
+ ):
+ default_snapshot = hf_cache_scan.default_ref_snapshot(repo_path)
+ # No usable refs/main: from_pretrained would fail offline or fetch HEAD, so pin the payload.
+ if (
+ default_snapshot is None
+ or (payload_snapshots and str(default_snapshot) not in payload_snapshots)
+ # refs/main can land on a torn revision, so keep the id only if it lands on a complete one.
+ or (
+ default_snapshot != snapshot_path
+ and not hf_cache_scan.snapshot_holds_a_complete_payload(
+ default_snapshot, quants = False
+ )
+ and hf_cache_scan.snapshot_holds_a_complete_payload(snapshot_path, quants = False)
+ )
+ ):
+ load_id = str(snapshot_path)
+ # Keeping the repo id lets refs/main decide, possibly an older payload snapshot.
+ load_snapshot = (default_snapshot or snapshot_path) if load_id == repo_id else snapshot_path
+ return _LoadIdentity(load_id, active_cache, load_snapshot)
+
+
+def _cache_inventory_fields(
+ repo_id: str,
+ model_format: ModelFormat,
+ *,
+ repo_path: Optional[Path] = None,
+ snapshot_path: Optional[Path] = None,
+ active_hub_cache: Optional[Path] = None,
+ partial: bool = False,
+ requires_variant: bool = False,
+ payload_snapshots: Optional[frozenset[str]] = None,
+ identity: Optional[_LoadIdentity] = None,
+ gguf_snapshot: Optional[Path] = None,
+ repo_info = None,
+ hidden_infra: bool = False,
+) -> dict:
+ """Load identity plus the capability block for one cache row.
+
+ The SOLE producer of a row's ``capabilities``: every flag is derived from the snapshot this row
+ describes, so add new flags here rather than patching them on afterwards. *identity* is accepted
+ already resolved so it cannot be resolved twice to different answers.
+ """
+ if identity is None:
+ identity = _resolve_load_identity(
+ repo_id,
+ repo_path = repo_path,
+ snapshot_path = snapshot_path,
+ active_hub_cache = active_hub_cache,
+ payload_snapshots = payload_snapshots,
+ )
+ capabilities = _capabilities_for_format(
+ model_format,
+ "hf_cache",
+ partial = partial,
+ requires_variant = requires_variant,
+ ).model_dump()
+ # The loader's companion search never leaves the quants' snapshot.
+ if model_format == "gguf" and (
+ hf_cache_scan.snapshot_has_gguf_projector(gguf_snapshot)
+ if gguf_snapshot is not None
+ else repo_info is not None and _repo_has_mmproj(repo_info)
+ ):
+ capabilities["supports_vision"] = True
+ if hidden_infra:
+ capabilities["can_chat"] = False
return {
"inventory_id": _local_inventory_id("cache", model_format, repo_id),
- "load_id": load_id,
- "active_cache": active_cache,
+ "load_id": identity.load_id,
+ "active_cache": identity.active_cache,
"model_format": model_format,
"runtime": _runtime_for_format(model_format),
"format_variant": None,
- "capabilities": _capabilities_for_format(
- model_format,
- "hf_cache",
- partial = partial,
- requires_variant = requires_variant,
- ).model_dump(),
+ "capabilities": capabilities,
}
@@ -344,9 +432,12 @@ def _scan_cached_gguf() -> list[dict]:
continue
if total_size == 0 and not has_variant_state:
continue
+ # Must run after the skips above and before the partial walk it scopes.
+ gguf_snapshot, gguf_payload_snapshots = _repo_gguf_payload_snapshots(repo_info)
partial = hf_cache_scan.is_gguf_repo_partial(
repo_id,
repo_path,
+ snapshot_dir = gguf_snapshot,
)
if total_size == 0 and not partial:
continue
@@ -370,26 +461,23 @@ def _scan_cached_gguf() -> list[dict]:
repo_id,
"gguf",
repo_path = repo_path,
- snapshot_path = snapshot_path,
+ snapshot_path = gguf_snapshot or snapshot_path,
active_hub_cache = active_hub_cache,
partial = bool(row["partial"]),
requires_variant = True,
+ payload_snapshots = gguf_payload_snapshots,
+ # Scopes the row's vision flag to one directory.
+ gguf_snapshot = gguf_snapshot,
+ repo_info = repo_info,
+ # Visible infra variants remain management-only.
+ hidden_infra = is_hidden_infra,
)
)
- if _repo_has_mmproj(repo_info):
- row["capabilities"]["supports_vision"] = True
- # Visible infra variants remain management-only.
- if is_hidden_infra:
- row["capabilities"]["can_chat"] = False
+ # Only the winning cache root loads, so the loser's vision flag must not carry over.
if _prefer_cache_row(row, existing):
- if existing and existing["capabilities"].get("supports_vision"):
- row["capabilities"]["supports_vision"] = True
seen_lower[key] = row
- else:
- if last_modified > existing.get("last_modified", 0.0):
- existing["last_modified"] = last_modified
- if row["capabilities"].get("supports_vision"):
- existing["capabilities"]["supports_vision"] = True
+ elif last_modified > existing.get("last_modified", 0.0):
+ existing["last_modified"] = last_modified
except Exception as e:
repo_label = getattr(repo_info, "repo_id", "<unknown>")
logger.warning(f"Skipping cached GGUF repo {repo_label}: {e}")
@@ -418,6 +506,70 @@ class _CachedNonGgufPayload(NamedTuple):
has_runnable_weights: bool
model_format: ModelFormat
last_modified: float
+ payload_snapshot: Optional[Path]
+ payload_snapshots: frozenset[str]
+
+
+# Keys mirror _classify_non_gguf_model_format's kwargs, so a revision classifies like the repo.
+_PAYLOAD_FLAGS = (
+ "has_config",
+ "has_adapter_config",
+ "has_adapter_weights",
+ "has_safetensors",
+ "has_transformers_safetensors",
+ "has_checkpoint_weights",
+)
+
+
+def _newest_snapshot_dir(candidates) -> Optional[Path]:
+ """Newest of *candidates*, or None when there are none.
+
+ Ordered by ``snapshot_selection_key``, shared with ``latest_snapshot_dir`` and
+ ``iter_hf_cache_snapshots`` so every consumer agrees; mtime alone left frozenset ties unbroken.
+ """
+ paths = [Path(candidate) for candidate in candidates]
+ if not paths:
+ return None
+ best = max(paths, key = snapshot_selection_key)
+ try:
+ return best.resolve()
+ except OSError:
+ return best
+
+
+def _resolved_snapshot_ids(candidates) -> frozenset[str]:
+ """The same strings ``_newest_snapshot_dir`` would return, for membership."""
+ resolved: set[str] = set()
+ for candidate in candidates:
+ path = Path(candidate)
+ try:
+ resolved.add(str(path.resolve()))
+ except OSError:
+ resolved.add(str(path))
+ return frozenset(resolved)
+
+
+def _repo_gguf_payload_snapshots(repo_info) -> tuple[Optional[Path], frozenset[str]]:
+ """Snapshot dirs a GGUF load can actually use, plus the newest of them.
+
+ Size sums quants over every revision but variant resolution reads only the ``load_id`` directory,
+ so they must agree or an advertised quant resolves to nothing. Prefer a snapshot holding a whole
+ quant (a mixed one counts; the lister trims to the completed subset), else any primary GGUF.
+ """
+ # Snapshot-relative: only the directory marks an ``MTP/`` drafter as a companion.
+ with_gguf = [
+ snapshot
+ for revision in repo_info.revisions
+ if (snapshot := getattr(revision, "snapshot_path", None)) is not None
+ and any(_is_main_gguf_filename(_cached_repo_file_name(f)) for f in revision.files)
+ ]
+ complete = [
+ snapshot
+ for snapshot in with_gguf
+ if hf_cache_scan.snapshot_has_complete_variants(str(snapshot))
+ ]
+ usable = complete or with_gguf
+ return _newest_snapshot_dir(usable), _resolved_snapshot_ids(usable)
def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:
@@ -425,12 +577,8 @@ def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:
adapter_blobs: dict[str, tuple[int, float]] = {}
safetensors_blobs: dict[str, tuple[int, float]] = {}
checkpoint_blobs: dict[str, tuple[int, float]] = {}
- has_config = False
- has_adapter_config = False
- has_adapter_weights = False
- has_safetensors = False
- has_transformers_safetensors = False
- has_checkpoint = False
+ repo_flags = dict.fromkeys(_PAYLOAD_FLAGS, False)
+ revision_flags: list[tuple[Path, dict[str, bool]]] = []
def _record_blob(
target: dict[str, tuple[int, float]], file_obj, rev_id: str, file_name: str
@@ -444,45 +592,84 @@ def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:
for revision in repo_info.revisions:
rev_id = getattr(revision, "commit_hash", None) or str(id(revision))
+ flags = dict.fromkeys(_PAYLOAD_FLAGS, False)
for f in revision.files:
file_name = str(f.file_name)
lower = file_name.lower()
name = lower.replace("\\", "/").rsplit("/", 1)[-1]
if _is_gguf_filename(lower):
continue
- if name == "config.json":
- has_config = True
- continue
- if name == "adapter_config.json":
- has_adapter_config = True
+ # Configs are opened by exact name at the snapshot root: probed below, not here.
+ if name in ("config.json", "adapter_config.json"):
continue
is_adapter = _is_adapter_weight_name(name)
- is_safetensors = name.endswith(".safetensors") and not is_adapter
- is_checkpoint = _is_checkpoint_weight_name(name)
+ is_safetensors = (
+ name.endswith(".safetensors")
+ and not is_adapter
+ # Trainer state is not the model, so it cannot classify a revision as one.
+ and not _is_training_artefact_name(name)
+ )
+ is_checkpoint = _is_checkpoint_weight_name(name) and not _is_training_artefact_name(
+ name
+ )
if is_adapter:
- has_adapter_weights = True
+ flags["has_adapter_weights"] = True
_record_blob(adapter_blobs, f, rev_id, file_name)
if is_safetensors:
- has_safetensors = True
+ flags["has_safetensors"] = True
if _is_transformers_safetensors_weight_name(name):
- has_transformers_safetensors = True
+ flags["has_transformers_safetensors"] = True
_record_blob(safetensors_blobs, f, rev_id, file_name)
if is_checkpoint:
- has_checkpoint = True
+ flags["has_checkpoint_weights"] = True
_record_blob(checkpoint_blobs, f, rev_id, file_name)
+ snapshot = getattr(revision, "snapshot_path", None)
+ if snapshot is not None:
+ for config_name, key in (
+ ("config.json", "has_config"),
+ ("adapter_config.json", "has_adapter_config"),
+ ):
+ try:
+ if (Path(snapshot) / config_name).is_file():
+ flags[key] = True
+ except OSError:
+ continue
+ revision_flags.append((Path(snapshot), flags))
+ for key, seen in flags.items():
+ if seen:
+ repo_flags[key] = True
model_format = (
- _classify_non_gguf_model_format(
- has_config = has_config,
- has_adapter_config = has_adapter_config,
- has_adapter_weights = has_adapter_weights,
- has_safetensors = has_safetensors,
- has_transformers_safetensors = has_transformers_safetensors,
- has_checkpoint_weights = has_checkpoint,
- trusted_hf_cache_repo = True,
- )
- or "unknown"
+ _classify_non_gguf_model_format(**repo_flags, trusted_hf_cache_repo = True) or "unknown"
)
+
+ def _revisions_of(fmt: str) -> tuple[list, list]:
+ # Weights pool across revisions, so the pinned snapshot must classify alone; trusted=False
+ # because from_pretrained needs config.json in that one directory. Filename classification
+ # also matches torn revisions, so the whole ones are tracked separately.
+ snapshots = [
+ snapshot
+ for snapshot, flags in revision_flags
+ if _classify_non_gguf_model_format(**flags, trusted_hf_cache_repo = False) == fmt
+ ]
+ return snapshots, [
+ s for s in snapshots if hf_cache_scan.snapshot_holds_a_complete_payload(s, quants = False)
+ ]
+
+ payload_snapshots, complete = _revisions_of(model_format)
+ if not complete:
+ # The repo-wide flags are OR-ed across revisions, so they can name a format whose every
+ # revision is torn while another format has a whole one sitting right there. Load what
+ # loads: an interrupted safetensors attempt must not hide a complete checkpoint.
+ for candidate in ("safetensors", "checkpoint", "adapter"):
+ if candidate == model_format:
+ continue
+ candidate_snapshots, candidate_complete = _revisions_of(candidate)
+ if candidate_complete:
+ model_format = candidate
+ payload_snapshots, complete = candidate_snapshots, candidate_complete
+ break
+
if model_format == "adapter":
selected_blobs = adapter_blobs
elif model_format == "safetensors":
@@ -491,12 +678,13 @@ def _repo_non_gguf_model_payload(repo_info) -> _CachedNonGgufPayload:
selected_blobs = checkpoint_blobs
else:
selected_blobs = all_weight_blobs
-
return _CachedNonGgufPayload(
size_bytes = sum(size for size, _mtime in selected_blobs.values()),
has_runnable_weights = model_format != "unknown",
model_format = model_format,
last_modified = max((mtime for _size, mtime in selected_blobs.values()), default = 0.0),
+ payload_snapshot = _newest_snapshot_dir(complete or payload_snapshots),
+ payload_snapshots = _resolved_snapshot_ids(payload_snapshots),
)
@@ -553,8 +741,10 @@ def _read_model_card_frontmatter(path: Path) -> dict:
return {}
-def _cached_model_local_metadata(repo_path: Path) -> dict:
- snapshot = _cached_model_snapshot_path(repo_path)
+def _cached_model_local_metadata(repo_path: Path, snapshot: Optional[Path] = None) -> dict:
+ # Describe the directory the row hands out, not merely the newest.
+ if snapshot is None:
+ snapshot = _cached_model_snapshot_path(repo_path)
if snapshot is None:
return {}
@@ -624,15 +814,30 @@ def _scan_cached_models() -> list[dict]:
continue
key = repo_id.lower()
existing = seen_lower.get(key)
- local_metadata = _cached_model_local_metadata(repo_path)
+ # Resolved once so the metadata probe, partial walk and load id agree.
+ identity = _resolve_load_identity(
+ repo_id,
+ repo_path = repo_path,
+ snapshot_path = payload.payload_snapshot or snapshot_path,
+ active_hub_cache = active_hub_cache,
+ payload_snapshots = payload.payload_snapshots,
+ )
+ load_snapshot = identity.load_snapshot
+ local_metadata = _cached_model_local_metadata(repo_path, load_snapshot)
if local_metadata.pop("_hidden_stt", False):
skipped_stt += 1
continue
+ # Scoped to the row's snapshot, so an incomplete newer revision cannot flip can_chat.
snapshot_partial = hf_cache_scan.is_snapshot_partial(
"model",
repo_id,
repo_path,
+ snapshot_dir = load_snapshot,
)
+ # Flags are OR-ed over revisions, so no payload snapshot means no directory
+ # serves the row and it would reach for the Hub.
+ if not payload.payload_snapshots:
+ snapshot_partial = True
row = {
"repo_id": repo_id,
"size_bytes": payload.size_bytes,
@@ -659,9 +864,7 @@ def _scan_cached_models() -> list[dict]:
_cache_inventory_fields(
repo_id,
payload.model_format,
- repo_path = repo_path,
- snapshot_path = snapshot_path,
- active_hub_cache = active_hub_cache,
+ identity = identity,
partial = bool(row["partial"]),
)
)
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 4c0e296fdce..f7f694c7481 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -229,6 +229,22 @@ def _is_adapter_weight_name(name: str) -> bool:
return lower.startswith("adapter_model") and lower.endswith((".safetensors", ".bin"))
+# Trainer state saved beside the weights, not the model. The .bin side is already an allow list.
+_TRAINING_ARTEFACT_PREFIXES = (
+ "optimizer",
+ "scheduler",
+ "rng_state",
+ "trainer_state",
+ "scaler",
+ "training_args",
+)
+
+
+def _is_training_artefact_name(name: str) -> bool:
+ """Whether *name* is trainer state rather than weights any row loads."""
+ return _weight_basename(name).startswith(_TRAINING_ARTEFACT_PREFIXES)
+
+
def _is_transformers_safetensors_weight_name(name: str) -> bool:
lower = _weight_basename(name)
return lower.endswith(".safetensors") and lower.startswith(
@@ -250,6 +266,14 @@ def _is_checkpoint_weight_name(name: str) -> bool:
return lower.endswith(_LOCAL_CHECKPOINT_EXTENSIONS)
+def _is_discoverable_ungrouped_weight_name(name: str) -> bool:
+ """Ungrouped payloads a runtime opens by name: diffusers components, single-file checkpoints."""
+ lower = _weight_basename(name)
+ if lower.endswith(".safetensors"):
+ return lower.startswith("diffusion_pytorch_model")
+ return _is_checkpoint_weight_name(lower)
+
+
def _is_adapter_weight_file(path: Path) -> bool:
return _is_adapter_weight_name(path.name)
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index 533fd2ca5a6..bfbc939f62c 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -455,6 +455,32 @@ def delete_variant_incomplete_blobs_result(
return VariantIncompleteDeleteResult(deleted = deleted, unresolved = False)
+def _snapshot_scope_for_request(repo_id: str, local_path: Optional[str]) -> Optional[Path]:
+ """The one snapshot *local_path* names, when it names one of *repo_id*'s.
+
+ A row pinned to a snapshot loads out of that directory and nothing else, so readiness has to be
+ counted there: a quant sitting in a sibling revision is not one this row can resolve. The
+ answer carries the requested repo's identity, so the directory has to be that repo's cache;
+ any cache root will do, since the same repo is cached under the same name in each.
+ """
+ if not local_path:
+ return None
+ try:
+ local = Path(local_path).expanduser().resolve(strict = False)
+ except (OSError, RuntimeError, ValueError):
+ return None
+ if local.parent.name != "snapshots" or not local.is_dir():
+ return None
+ expected = repo_cache_dir_name("model", repo_id).lower()
+ return local if local.parent.parent.name.lower() == expected else None
+
+
+def pinned_snapshot_for_request(repo_id: str, local_path: Optional[str]) -> Optional[str]:
+ """The snapshot *local_path* pins, for callers outside this module that must read that copy."""
+ scope = _snapshot_scope_for_request(repo_id, local_path)
+ return str(scope) if scope is not None else None
+
+
def _repo_cache_dir_for_request(repo_id: str, local_path: Optional[str]) -> Path:
"""Resolve the one Hub repo cache represented by this variant request."""
expected_name = repo_cache_dir_name("model", repo_id).lower()
@@ -503,6 +529,18 @@ def _mark_empty_dir_cleanables(
return response.model_copy(update = {"variants": variants})
+def _complete_quants_under(snapshot: str):
+ """Quants whose shards are all present under *snapshot*, or None if unknown.
+
+ None on any error, so every row reports downloaded as before: a scan problem must not mark a
+ working folder unusable.
+ """
+ try:
+ return hf_cache_scan.complete_snapshot_variants(snapshot)
+ except Exception:
+ return None
+
+
async def get_gguf_variants_response(
repo_id: str,
prefer_local_cache: bool = False,
@@ -524,13 +562,28 @@ async def get_gguf_variants_response(
None if is_local_path(repo_id) else _repo_cache_dir_for_request(repo_id, local_path)
)
hub_cache = repo_cache_dir.parent if repo_cache_dir is not None else None
+ snapshot_scope = _snapshot_scope_for_request(repo_id, local_path)
def _local_response(
- response_repo_id: str, variants, has_vision: bool
+ response_repo_id: str,
+ variants,
+ has_vision: bool,
+ complete = None,
) -> GgufVariantsResponse:
- filenames = [v.filename for v in variants]
- best = pick_best_gguf(filenames)
+ """*complete* is the set of quants whose shards are all on disk; None reports every row
+ downloaded. A quant short a shard stays listed to resume or delete, but is not offered
+ as ready, since the loader would ask llama-server for files that are not there.
+ """
+
+ def _downloaded(v) -> bool:
+ # An unlabelled quant cannot be judged, so it is kept as ready.
+ return complete is None or not v.quant or v.quant in complete
+
+ # The default comes from the ready rows; with none ready every row is the fallback.
+ ready = [v for v in variants if _downloaded(v)]
+ best = pick_best_gguf([v.filename for v in (ready or variants)])
default_variant = extract_quant_label(best) if best else None
+
return GgufVariantsResponse(
repo_id = response_repo_id,
variants = [
@@ -540,7 +593,8 @@ async def get_gguf_variants_response(
display_label = v.display_label,
size_bytes = v.size_bytes,
download_size_bytes = v.size_bytes,
- downloaded = True,
+ downloaded = _downloaded(v),
+ partial = not _downloaded(v),
)
for v in variants
],
@@ -580,24 +634,42 @@ async def get_gguf_variants_response(
# Local directory path (e.g. LM Studio models) — scan filesystem
if is_local_path(repo_id):
variants, has_vision = list_local_gguf_variants(repo_id)
-
- return _local_response(repo_id, variants, has_vision)
+ # The load id is this path, so a quant offered here has to resolve here.
+ return _local_response(repo_id, variants, has_vision, _complete_quants_under(repo_id))
# Reject invalid remote repo_ids up front (like download/delete) so a
# malformed id returns 400 instead of a 500 from the HF client.
if not _is_valid_repo_id(repo_id):
raise HTTPException(status_code = 400, detail = f"Invalid repo_id: {repo_id!r}")
+ def _scoped_local_response():
+ """The pinned snapshot's own answer, or None when it holds nothing."""
+ if snapshot_scope is None:
+ return None
+ variants, has_vision = list_local_gguf_variants(str(snapshot_scope))
+ if not (variants or has_vision):
+ return None
+ return _local_response(
+ repo_id, variants, has_vision, _complete_quants_under(str(snapshot_scope))
+ )
+
local_only = prefer_local_cache or offline
if local_only:
+ scoped_response = _scoped_local_response()
+ if scoped_response is not None:
+ return scoped_response
cached = list_gguf_variants_from_hf_cache(repo_id, root = hub_cache)
if cached is not None:
- variants, has_vision = cached
- return _local_response(repo_id, variants, has_vision)
+ variants, has_vision, complete = cached
+ # The lister leaves torn quants in: they stay listed for management, but not ready.
+ return _local_response(repo_id, variants, has_vision, complete)
if local_path and is_local_path(local_path):
variants, has_vision = list_local_gguf_variants(local_path)
if variants or has_vision:
- return _local_response(repo_id, variants, has_vision)
+ # Same reason as the is_local_path branch above.
+ return _local_response(
+ repo_id, variants, has_vision, _complete_quants_under(local_path)
+ )
partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)
if partial is not None:
variants, has_vision = partial
@@ -618,10 +690,14 @@ async def get_gguf_variants_response(
try:
variants, has_vision, siblings = list_gguf_variants(repo_id, hf_token = hf_token)
except Exception:
+ scoped_response = _scoped_local_response()
+ if scoped_response is not None:
+ return scoped_response
cached = list_gguf_variants_from_hf_cache(repo_id, root = hub_cache)
if cached is not None:
- variants, has_vision = cached
- return _local_response(repo_id, variants, has_vision)
+ variants, has_vision, complete = cached
+ # Same reason as the local_only branch above.
+ return _local_response(repo_id, variants, has_vision, complete)
partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)
if partial is not None:
variants, has_vision = partial
@@ -639,7 +715,13 @@ async def get_gguf_variants_response(
cached_filenames_by_snapshot: list[dict[str, int]] = []
cached_quant_bytes_by_snapshot: list[dict[str, int]] = []
if _is_valid_repo_id(repo_id):
- for snap in iter_hf_cache_snapshots(repo_id, root = hub_cache):
+ # A pinned row resolves inside one directory, so nothing else counts as downloaded.
+ scoped_snapshots = (
+ [snapshot_scope]
+ if snapshot_scope is not None
+ else iter_hf_cache_snapshots(repo_id, root = hub_cache)
+ )
+ for snap in scoped_snapshots:
try:
gguf_paths = list(_iter_gguf_paths(snap))
except (OSError, RuntimeError, ValueError) as e:
@@ -761,11 +843,28 @@ async def get_gguf_variants_response(
except Exception as e:
logger.warning(f"Failed to compute partial GGUF variants for {repo_id}: {e}")
incomplete_hashes = set()
- scan_snapshot_dir = hf_cache_scan.resolve_snapshot_dir_for_scan(
+ scan_snapshot_dir = snapshot_scope or hf_cache_scan.resolve_snapshot_dir_for_scan(
"model",
repo_id,
repo_cache_dir,
)
+ # A marker or manifest carries no revision, so attribute it like the inventory row.
+ repo_signal_applies = hf_cache_scan.repo_signal_applies_to_snapshot(
+ repo_cache_dir, scan_snapshot_dir
+ )
+ # The excuse is that this snapshot holds the quant whole, so a quant it lacks stays the
+ # cancelled download and keeps its resume and delete affordances.
+ excused_quants = (
+ frozenset()
+ if repo_signal_applies or scan_snapshot_dir is None
+ else frozenset(
+ q.lower() for q in (_complete_quants_under(str(scan_snapshot_dir)) or ())
+ )
+ )
+
+ def _repo_signals_apply_to(quant: str) -> bool:
+ return repo_signal_applies or quant.lower() not in excused_quants
+
# Manifest + marker + main incomplete-blob check: catches variants whose
# download was cancelled or whose expected shards are missing/undersized.
for variant in variants:
@@ -787,6 +886,7 @@ async def get_gguf_variants_response(
incomplete_blob_hashes = incomplete_hashes,
variant_blob_hashes = variant_hashes,
repo_cache_dir = repo_cache_dir,
+ repo_signal_applies = _repo_signals_apply_to(variant.quant),
):
partial_quants.add(variant.quant)
partial_quant_transports[variant.quant] = _partial_transport_for_variant(
@@ -798,10 +898,11 @@ async def get_gguf_variants_response(
logger.warning(
f"Manifest-based partial check failed for " f"{repo_id}/{variant.quant}: {e}"
)
+ # Same attribution as above: a pinned snapshot is not judged by a newer attempt's blobs.
if incomplete_hashes:
for variant in variants:
requirement = requirements_by_quant.get(variant.quant.lower())
- if requirement is None:
+ if requirement is None or not _repo_signals_apply_to(variant.quant):
continue
# companion_hashes adds the MTP drafter (mmproj_hashes covers
# every mmproj precision in the repo, not just the planned one).
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 54f167c7ad9..e39b2fc4e70 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -745,7 +745,7 @@ def test_cached_gguf_scan_dedupes_and_excludes_mmproj_only(monkeypatch, tmp_path
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: False,
+ lambda _repo_id, _path, **_kw: False,
)
result = {"cached": cache_inventory._scan_cached_gguf()}
@@ -766,7 +766,7 @@ def test_cached_gguf_scan_preserves_partial_flag(monkeypatch, tmp_path):
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: True,
+ lambda _repo_id, _path, **_kw: True,
)
result = {"cached": cache_inventory._scan_cached_gguf()}
@@ -809,7 +809,7 @@ def test_cached_gguf_scan_includes_variant_state_without_completed_gguf(monkeypa
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: True,
+ lambda _repo_id, _path, **_kw: True,
)
result = {"cached": cache_inventory._scan_cached_gguf()}
@@ -842,7 +842,7 @@ def test_cached_gguf_scan_hides_infra_repos_without_user_downloads(monkeypatch,
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: False,
+ lambda _repo_id, _path, **_kw: False,
)
result = {"cached": cache_inventory._scan_cached_gguf()}
@@ -877,7 +877,7 @@ def test_cached_gguf_scan_keeps_infra_repo_with_user_downloaded_variant(monkeypa
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: False,
+ lambda _repo_id, _path, **_kw: False,
)
result = {"cached": cache_inventory._scan_cached_gguf()}
@@ -909,7 +909,7 @@ def test_cached_models_scan_hides_non_gguf_embedder(monkeypatch, tmp_path):
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_snapshot_partial",
- lambda _kind, _repo_id, _path: False,
+ lambda _kind, _repo_id, _path, **_kw: False,
)
result = {"cached": cache_inventory._scan_cached_models()}
@@ -952,12 +952,12 @@ def test_cached_scans_hide_embedders_configured_by_cache_path(monkeypatch, tmp_p
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: False,
+ lambda _repo_id, _path, **_kw: False,
)
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_snapshot_partial",
- lambda _kind, _repo_id, _path: False,
+ lambda _kind, _repo_id, _path, **_kw: False,
)
assert cache_inventory._scan_cached_gguf() == []
@@ -1015,12 +1015,12 @@ def test_cached_scans_hide_embedders_configured_by_snapshot_path(monkeypatch, tm
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: False,
+ lambda _repo_id, _path, **_kw: False,
)
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_snapshot_partial",
- lambda _kind, _repo_id, _path: False,
+ lambda _kind, _repo_id, _path, **_kw: False,
)
assert cache_inventory._scan_cached_gguf() == []
@@ -1058,7 +1058,7 @@ def test_cached_models_scan_keeps_unrelated_repo_with_custom_generic_embedder(
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_snapshot_partial",
- lambda _kind, _repo_id, _path: False,
+ lambda _kind, _repo_id, _path, **_kw: False,
)
result = {"cached": cache_inventory._scan_cached_models()}
@@ -1092,12 +1092,12 @@ def test_cached_scans_hide_stale_default_embedder_after_custom_setting(monkeypat
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_gguf_repo_partial",
- lambda _repo_id, _path: False,
+ lambda _repo_id, _path, **_kw: False,
)
monkeypatch.setattr(
cache_inventory.hf_cache_scan,
"is_snapshot_partial",
- lambda _kind, _repo_id, _path: False,
+ lambda _kind, _repo_id, _path, **_kw: False,
)
assert cache_inventory._scan_cached_gguf() == []
diff --git a/studio/backend/hub/utils/gguf.py b/studio/backend/hub/utils/gguf.py
index b58ccbd4126..0af79c85cc6 100644
--- a/studio/backend/hub/utils/gguf.py
+++ b/studio/backend/hub/utils/gguf.py
@@ -254,7 +254,11 @@ def _env_offline() -> bool:
def iter_hf_cache_snapshots(repo_id: str, root: Optional[Path] = None):
- from hub.utils.hf_cache_state import iter_active_repo_cache_dirs, iter_repo_cache_dirs
+ from hub.utils.hf_cache_state import (
+ iter_active_repo_cache_dirs,
+ iter_repo_cache_dirs,
+ snapshot_selection_key,
+ )
snapshots: list[Path] = []
repo_dirs = (
@@ -271,13 +275,8 @@ def iter_hf_cache_snapshots(repo_id: str, root: Optional[Path] = None):
except OSError:
continue
- def _mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
- snapshots.sort(key = _mtime, reverse = True)
+ # Same key the inventory row selects with, so both name one snapshot.
+ snapshots.sort(key = snapshot_selection_key, reverse = True)
yield from snapshots
@@ -315,17 +314,33 @@ def list_empty_gguf_variant_dirs(repo_id: str, root: Optional[Path] = None) -> s
def list_gguf_variants_from_hf_cache(
repo_id: str, root: Optional[Path] = None
-) -> Optional[tuple[list[GgufVariantInfo], bool]]:
+) -> Optional[tuple[list[GgufVariantInfo], bool, set]]:
+ """``(variants, has_vision, complete)`` for the snapshot a load would read.
+
+ Everything in that snapshot is listed, so a torn download stays visible to resume or delete;
+ *complete* is the subset whose shards are all present, so the caller marks the rest partial
+ rather than ready, as the snapshot-path form of this call does.
+ """
+ # Local import: inventory_scan imports this module.
+ from hub.utils.inventory_scan import complete_snapshot_variants
+
snapshots = (
iter_hf_cache_snapshots(repo_id, root = root)
if root is not None
else iter_hf_cache_snapshots(repo_id)
)
+ # Pick the snapshot the inventory row does: newest holding a whole quant, else first non-empty.
+ fallback: Optional[tuple[list[GgufVariantInfo], bool, set]] = None
for snapshot in snapshots:
variants, has_vision = list_local_gguf_variants(str(snapshot))
- if variants or has_vision:
- return variants, has_vision
- return None
+ complete = complete_snapshot_variants(str(snapshot)) if variants else set()
+ if variants:
+ # Selection only: an unlabelled quant cannot be judged, so it counts as usable.
+ if any(not v.quant or v.quant in complete for v in variants):
+ return variants, has_vision, complete
+ if fallback is None and (variants or has_vision):
+ fallback = (variants, has_vision, complete)
+ return fallback
def list_partial_gguf_variants_from_state(
@@ -422,11 +437,35 @@ def list_partial_gguf_variants_from_state(
return variants, has_vision
+def iter_snapshots_preferring_whole(
+ repo_id: str,
+ gguf_variant: Optional[str],
+ root = None,
+):
+ """Cache snapshots newest first, but ones holding *gguf_variant* whole ahead of ones short a
+ shard. The lister and the load both take the whole copy, so mtime order alone would read
+ metadata out of a newer half download nothing will load.
+ """
+ ordered = list(iter_hf_cache_snapshots(repo_id, root = root))
+ if not gguf_variant or len(ordered) < 2:
+ return ordered
+ from hub.utils.inventory_scan import complete_snapshot_variants
+
+ whole, torn = [], []
+ for snapshot in ordered:
+ try:
+ is_whole = gguf_variant in complete_snapshot_variants(str(snapshot))
+ except Exception:
+ is_whole = True
+ (whole if is_whole else torn).append(snapshot)
+ return whole + torn
+
+
def resolve_local_gguf_path(repo_id: str, gguf_variant: Optional[str]) -> Optional[str]:
"""Absolute path to the (shard-1) GGUF file for ``repo_id`` + ``gguf_variant``
if it is already downloaded in the HF cache, else ``None``. Read-only — never
triggers a download. Lets callers read header metadata before a load."""
- for snapshot in iter_hf_cache_snapshots(repo_id):
+ for snapshot in iter_snapshots_preferring_whole(repo_id, gguf_variant):
variants, _ = list_local_gguf_variants(str(snapshot))
for variant in variants:
if gguf_variant is None or variant.quant == gguf_variant:
@@ -436,6 +475,14 @@ def resolve_local_gguf_path(repo_id: str, gguf_variant: Optional[str]) -> Option
return None
+def _ready_cached_variants(cached: tuple) -> tuple[list[GgufVariantInfo], bool, None]:
+ """Cache result for a caller with nowhere to put readiness: drop the quants short a shard, but
+ keep the whole list when none is complete so the folder still shows up to manage."""
+ variants, has_vision, complete = cached
+ whole = [v for v in variants if not v.quant or v.quant in complete]
+ return whole or variants, has_vision, None
+
+
def list_gguf_variants(
repo_id: str, hf_token: Optional[str] = None
) -> tuple[list[GgufVariantInfo], bool, Optional[list]]:
@@ -444,7 +491,7 @@ def list_gguf_variants(
if _env_offline():
cached = list_gguf_variants_from_hf_cache(repo_id)
if cached is not None:
- return (*cached, None)
+ return _ready_cached_variants(cached)
try:
info = HfApi(token = hf_token).model_info(
@@ -467,7 +514,7 @@ def list_gguf_variants(
repo_id,
exc.__class__.__name__,
)
- return (*cached, None)
+ return _ready_cached_variants(cached)
raise
variants: list[GgufVariantInfo] = []
@@ -541,7 +588,11 @@ def list_local_gguf_variants(
for file in sorted(iter_gguf_files(root, recursive = True)):
if is_mmproj_filename(file.name):
- has_vision = True
+ # A projector llama.cpp cannot open is not vision support.
+ try:
+ has_vision = has_vision or file.stat().st_size > 0
+ except OSError:
+ pass
continue
try:
size = file.stat().st_size
diff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.py
index 49a28c813ce..c5d47d27091 100644
--- a/studio/backend/hub/utils/hf_cache_state.py
+++ b/studio/backend/hub/utils/hf_cache_state.py
@@ -139,11 +139,28 @@ def _windows_allocated_size(path: Path) -> Optional[int]:
return None
+def snapshot_selection_key(snapshot: Path) -> tuple[float, str]:
+ """The one ordering every snapshot selector uses: mtime, then resolved path.
+
+ mtime alone is not a total order, and each selector broke ties by its own
+ iteration order (frozenset vs iterdir), so the inventory row and the variant
+ picker could name different snapshots. The path breaks ties identically.
+ """
+ try:
+ mtime = snapshot.stat().st_mtime
+ except OSError:
+ mtime = 0.0
+ try:
+ return mtime, str(snapshot.resolve())
+ except (OSError, RuntimeError, ValueError):
+ return mtime, str(snapshot)
+
+
def latest_snapshot_dir(repo_dir: Path) -> Optional[Path]:
- """Newest immediate child of ``repo_dir/snapshots`` by mtime, or None.
+ """Newest immediate child of ``repo_dir/snapshots``, or None.
- mtime is the signal huggingface_hub's from_pretrained resolves to, so this
- points at whatever snapshot most recently landed on disk.
+ mtime is the signal huggingface_hub's from_pretrained resolves to; ties fall
+ to ``snapshot_selection_key`` so every caller names the same directory.
"""
snapshots_dir = repo_dir / "snapshots"
try:
@@ -152,7 +169,7 @@ def latest_snapshot_dir(repo_dir: Path) -> Optional[Path]:
snapshots = [entry for entry in snapshots_dir.iterdir() if entry.is_dir()]
if not snapshots:
return None
- return max(snapshots, key = lambda entry: entry.stat().st_mtime)
+ return max(snapshots, key = snapshot_selection_key)
except OSError:
return None
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index 058fdf9b656..72c888060c6 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -14,12 +14,13 @@ layers built on top of these primitives live in download_registry.py.
from __future__ import annotations
import hashlib
+import json
import re
import threading
import time
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Callable, Optional
+from dataclasses import dataclass, replace
+from pathlib import Path, PurePosixPath
+from typing import Callable, NamedTuple, Optional
from loggers import get_logger
@@ -27,6 +28,7 @@ logger = get_logger(__name__)
from hub.utils.gguf import (
extract_quant_label,
+ is_big_endian_gguf_path,
is_gguf_filename,
is_mmproj_filename,
is_mtp_drafter_path,
@@ -47,6 +49,8 @@ from hub.utils.hf_cache_state import (
# on rapid UI navigation.
_HF_CACHE_SCANS_TTL_SECONDS = 15.0
_GGUF_SPLIT_RE = re.compile(r"-(\d{3,})-of-(\d{3,})(?=\.gguf$)", re.IGNORECASE)
+# transformers shard naming: each shard names the set's total.
+_WEIGHT_SHARD_RE = re.compile(r"-(\d{3,})-of-(\d{3,})(?=\.(?:safetensors|bin)$)", re.IGNORECASE)
_hf_cache_scans_lock = threading.Lock()
@@ -125,18 +129,281 @@ def all_hf_cache_scans() -> list:
flight.event.set()
+def _cache_entries_to_ignore() -> frozenset:
+ """huggingface_hub's ignore list: a stray OS file is not corruption.
+
+ Read from upstream, not frozen: newer hub versions skip more names (``Thumbs.db``,
+ ``desktop.ini``), and hardcoding the old set made an Explorer file read as corruption. The
+ literal is the fallback.
+ """
+ try:
+ from huggingface_hub.utils import _cache_manager
+ names = getattr(_cache_manager, "FILES_TO_IGNORE", None)
+ if names:
+ return frozenset(names)
+ except Exception:
+ pass
+ return frozenset({".DS_Store"})
+
+
+_CACHE_ENTRIES_TO_IGNORE = _cache_entries_to_ignore()
+_HF_REPO_TYPES = frozenset({"model", "dataset", "space"})
+
+
+# Mirrors huggingface_hub's Cached{File,Revision,Repo}Info field-for-field; frozen because
+# HFCacheInfo.delete_revisions() set-diffs ``revisions``.
+@dataclass(frozen = True)
+class _RecoveredFileInfo:
+ file_name: str
+ file_path: Path
+ size_on_disk: int
+ blob_path: Path
+ blob_last_accessed: float
+ blob_last_modified: float
+
+
+@dataclass(frozen = True)
+class _RecoveredRevisionInfo:
+ commit_hash: str
+ snapshot_path: Path
+ size_on_disk: int
+ files: frozenset
+ refs: frozenset
+ last_modified: float
+
+
+@dataclass(frozen = True)
+class _RecoveredRepoInfo:
+ repo_id: str
+ repo_type: str
+ repo_path: Path
+ size_on_disk: int
+ nb_files: int
+ revisions: frozenset
+ last_accessed: float
+ last_modified: float
+
+ @property
+ def refs(self) -> dict:
+ return {ref: rev for rev in self.revisions for ref in rev.refs}
+
+
+def _hf_repo_identity(repo_dir_name: str) -> Optional[tuple[str, str]]:
+ """``models--Org--Model`` -> ``("model", "Org/Model")``, as huggingface_hub parses it."""
+ if "--" not in repo_dir_name:
+ return None
+ repo_type, _, repo_id = repo_dir_name.partition("--")
+ repo_type = repo_type[:-1]
+ if repo_type not in _HF_REPO_TYPES or not repo_id:
+ return None
+ return repo_type, repo_id.replace("--", "/")
+
+
+def _read_refs_by_commit(refs_dir: Path) -> Optional[dict[str, set[str]]]:
+ """Map commit hash -> ref names under ``refs/``. None if unreadable."""
+ refs_by_commit: dict[str, set[str]] = {}
+ if not refs_dir.exists():
+ return refs_by_commit
+ if refs_dir.is_file():
+ return None
+ try:
+ entries = sorted(refs_dir.rglob("*"))
+ except OSError:
+ return None
+ for ref_path in entries:
+ try:
+ if ref_path.is_dir() or ref_path.name in _CACHE_ENTRIES_TO_IGNORE:
+ continue
+ commit = ref_path.read_text(encoding = "utf-8")
+ except (OSError, UnicodeDecodeError):
+ return None
+ # Ref names keep the platform-native separator huggingface_hub stores.
+ refs_by_commit.setdefault(commit, set()).add(str(ref_path.relative_to(refs_dir)))
+ return refs_by_commit
+
+
+def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_RecoveredRepoInfo]:
+ """Rebuild the scan entry for a repo dropped *solely* over leftover refs.
+
+ ``scan_cache_dir`` omits an intact repo when a ``refs/<branch>`` names a commit with no
+ ``snapshots/<commit>/`` dir, which ``snapshot_download`` creates by writing ``refs/main`` before
+ fetching the first file, hiding the repo from every inventory endpoint. Read-only: pruning the
+ ref cannot be race-free. None whenever anything other than leftover refs failed the scan.
+ """
+ identity = _hf_repo_identity(repo_dir.name)
+ if identity is None:
+ return None
+ repo_type, repo_id = identity
+ snapshots_dir = repo_dir / "snapshots"
+ refs_by_commit = _read_refs_by_commit(repo_dir / "refs")
+ if refs_by_commit is None:
+ return None
+ try:
+ if not snapshots_dir.is_dir():
+ return None
+ snapshot_entries = sorted(snapshots_dir.iterdir())
+ except OSError:
+ return None
+
+ blob_stats: dict[Path, object] = {}
+ revisions: set[_RecoveredRevisionInfo] = set()
+ dangling = dict(refs_by_commit)
+ for snapshot in snapshot_entries:
+ if snapshot.name in _CACHE_ENTRIES_TO_IGNORE:
+ continue
+ try:
+ if not snapshot.is_dir():
+ # Upstream treats a file here as corruption; defer to it.
+ return None
+ entries = sorted(snapshot.rglob("*"))
+ except OSError:
+ return None
+ files: set[_RecoveredFileInfo] = set()
+ for entry in entries:
+ try:
+ if entry.is_dir():
+ continue
+ blob_path = entry.resolve()
+ stat = blob_stats.get(blob_path) or blob_path.stat()
+ except OSError:
+ # Broken symlink / unreadable blob: upstream raises here too.
+ return None
+ blob_stats[blob_path] = stat
+ files.add(
+ _RecoveredFileInfo(
+ file_name = entry.name,
+ file_path = entry,
+ size_on_disk = stat.st_size,
+ blob_path = blob_path,
+ blob_last_accessed = stat.st_atime,
+ blob_last_modified = stat.st_mtime,
+ )
+ )
+ try:
+ last_modified = (
+ max(f.blob_last_modified for f in files) if files else snapshot.stat().st_mtime
+ )
+ except OSError:
+ return None
+ revisions.add(
+ _RecoveredRevisionInfo(
+ commit_hash = snapshot.name,
+ snapshot_path = snapshot,
+ size_on_disk = sum(blob_stats[blob].st_size for blob in {f.blob_path for f in files}),
+ files = frozenset(files),
+ refs = frozenset(dangling.pop(snapshot.name, set())),
+ last_modified = last_modified,
+ )
+ )
+ # Nothing fetched yet, so the repo is not on disk.
+ if not revisions:
+ return None
+ # Every ref resolved, so upstream dropped this repo for some other reason.
+ if not dangling:
+ return None
+ try:
+ repo_stats = repo_dir.stat()
+ except OSError:
+ return None
+ return _RecoveredRepoInfo(
+ repo_id = repo_id,
+ repo_type = repo_type,
+ repo_path = repo_dir,
+ size_on_disk = sum(stat.st_size for stat in blob_stats.values()),
+ nb_files = len(blob_stats),
+ revisions = frozenset(revisions),
+ last_accessed = (
+ max((stat.st_atime for stat in blob_stats.values()), default = repo_stats.st_atime)
+ ),
+ last_modified = (
+ max((stat.st_mtime for stat in blob_stats.values()), default = repo_stats.st_mtime)
+ ),
+ )
+
+
+def _with_repos_hidden_by_dangling_refs(scan, cache_root: Path):
+ """Add back the repos ``scan_cache_dir`` dropped over a dangling ref."""
+ try:
+ repo_dirs = sorted(entry for entry in cache_root.iterdir() if "--" in entry.name)
+ except OSError:
+ return scan
+ known = getattr(scan, "repos", ())
+ scanned: set[str] = set()
+ for repo in known:
+ try:
+ scanned.add(str(Path(repo.repo_path).resolve(strict = False)))
+ except (AttributeError, OSError, RuntimeError, TypeError, ValueError):
+ continue
+ recovered: list[_RecoveredRepoInfo] = []
+ for repo_dir in repo_dirs:
+ try:
+ if str(repo_dir.resolve(strict = False)) in scanned:
+ continue
+ entry = _recover_repo_hidden_by_dangling_refs(repo_dir)
+ except (OSError, RuntimeError, ValueError):
+ continue
+ if entry is None:
+ continue
+ logger.info(
+ "Recovered HF cache repo %s hidden by a dangling ref (%d revision(s) on disk)",
+ entry.repo_id,
+ len(entry.revisions),
+ )
+ recovered.append(entry)
+ if not recovered:
+ return scan
+ try:
+ return replace(
+ scan,
+ repos = frozenset(known) | frozenset(recovered),
+ size_on_disk = getattr(scan, "size_on_disk", 0)
+ + sum(entry.size_on_disk for entry in recovered),
+ )
+ except (AttributeError, TypeError, ValueError) as exc:
+ # A scan shape we cannot rebuild is left untouched rather than dropped.
+ logger.debug("Could not attach recovered HF cache repos: %s", exc)
+ return scan
+
+
def _compute_all_hf_cache_scans() -> list:
from huggingface_hub import scan_cache_dir
scans: list = []
for cache_root in hf_cache_roots():
try:
- scans.append(scan_cache_dir(cache_dir = str(cache_root)))
+ scan = scan_cache_dir(cache_dir = str(cache_root))
+ # Only a warned-about scan can hide a repo, so never walk a healthy cache twice.
+ if getattr(scan, "warnings", None):
+ scan = _with_repos_hidden_by_dangling_refs(scan, cache_root)
+ scans.append(scan)
except Exception as exc:
logger.warning("Could not scan HF cache %s: %s", cache_root, exc)
return scans
+def default_ref_snapshot(repo_dir: Path) -> Optional[Path]:
+ """Snapshot dir that ``refs/main`` names in *repo_dir*, or ``None``.
+
+ Where ``from_pretrained(repo_id)`` lands, so the repo id is safe as a load id only when this
+ matches the snapshot the row advertises.
+ """
+ ref_path = repo_dir / "refs" / "main"
+ try:
+ # No strip: huggingface_hub matches raw ref contents to the dir name.
+ commit = ref_path.read_text(encoding = "utf-8")
+ except (OSError, UnicodeDecodeError):
+ return None
+ if not commit:
+ return None
+ snapshot = repo_dir / "snapshots" / commit
+ try:
+ if not snapshot.is_dir():
+ return None
+ return snapshot.resolve()
+ except (OSError, ValueError):
+ return None
+
+
def token_fingerprint(hf_token: Optional[str]) -> str:
"""16-char SHA256 prefix used as a cache-key qualifier for gated repos.
@@ -236,19 +503,21 @@ def _repo_cache_dir_incomplete_hashes(repo_cache_dir: Path) -> set[str]:
return hashes
-def _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(repo_cache_dir: Path) -> bool:
- latest = latest_snapshot_dir(repo_cache_dir)
- if latest is None:
+def _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(
+ repo_cache_dir: Path, snapshot_dir: Optional[Path] = None
+) -> bool:
+ target = snapshot_dir if snapshot_dir is not None else latest_snapshot_dir(repo_cache_dir)
+ if target is None:
return False
try:
- entries = list(latest.rglob("*"))
+ entries = list(target.rglob("*"))
except OSError:
return False
for entry in entries:
try:
if not entry.is_symlink() or entry.exists():
continue
- rel = entry.relative_to(latest).as_posix()
+ rel = entry.relative_to(target).as_posix()
if is_gguf_filename(rel):
continue
return True
@@ -257,6 +526,113 @@ def _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(repo_cache_dir: Path)
return False
+def _is_latest_snapshot(repo_cache_dir: Path, snapshot_dir: Path) -> bool:
+ latest = latest_snapshot_dir(repo_cache_dir)
+ if latest is None:
+ return False
+ try:
+ return latest.resolve() == snapshot_dir.resolve()
+ except OSError:
+ return latest == snapshot_dir
+
+
+def _default_ref_names_an_absent_snapshot(repo_cache_dir: Path) -> bool:
+ """Whether ``refs/main`` is present and names a commit with no snapshot dir.
+
+ The window between ``snapshot_download`` rewriting the ref and the first file landing. A
+ *missing* ref is different: a commit-pinned fetch never writes one.
+ """
+ ref_path = repo_cache_dir / "refs" / "main"
+ try:
+ commit = ref_path.read_text(encoding = "utf-8")
+ except (OSError, UnicodeDecodeError):
+ return False
+ if not commit:
+ return False
+ try:
+ return not (repo_cache_dir / "snapshots" / commit).is_dir()
+ except (OSError, ValueError):
+ return False
+
+
+def repo_id_will_not_resolve(repo_cache_dir: Path) -> bool:
+ """Whether loading *repo_cache_dir* by repo id lands on nothing.
+
+ The active cache normally makes the id the right target, but not while ``refs/main`` names a
+ commit with no directory: the load finds nothing even though a snapshot sits beside it.
+ """
+ return _default_ref_names_an_absent_snapshot(repo_cache_dir)
+
+
+def default_ref_offers_no_whole_quant(repo_cache_dir: Path) -> bool:
+ """Whether ``refs/main`` resolves to a snapshot whose every quant is short a shard.
+
+ Loading by repo id follows that ref, so such a row needs a snapshot pinned even though the
+ id resolves. A ref naming no snapshot belongs to ``repo_id_will_not_resolve``.
+ """
+ snapshot = default_ref_snapshot(repo_cache_dir)
+ if snapshot is None:
+ return False
+ offered = _offered_gguf_quants(snapshot)
+ if not offered:
+ return False
+ return not (offered & _completed_gguf_variants(snapshot))
+
+
+def _repo_has_a_dangling_ref(repo_cache_dir: Path) -> bool:
+ """Whether ANY ref under ``refs/`` names a commit with no snapshot dir.
+
+ ``_default_ref_names_an_absent_snapshot`` only checks ``refs/main``, but the recovery admits a
+ repo over a leftover ref of any name, so the two must agree or a repo recovered over
+ ``refs/stale`` is judged as though upstream had published it.
+ """
+ refs_by_commit = _read_refs_by_commit(repo_cache_dir / "refs")
+ if refs_by_commit is None:
+ return False
+ snapshots_dir = repo_cache_dir / "snapshots"
+ for commit in refs_by_commit:
+ try:
+ if not (snapshots_dir / commit).is_dir():
+ return True
+ except (OSError, ValueError):
+ return False
+ return False
+
+
+def repo_signal_applies_to_snapshot(
+ repo_cache_dir: Optional[Path], snapshot_dir: Optional[Path]
+) -> bool:
+ """Public form of the attribution the inventory row uses, for callers pinning a snapshot."""
+ return _repo_signal_applies_to_snapshot(repo_cache_dir, snapshot_dir)
+
+
+def _repo_signal_applies_to_snapshot(
+ repo_cache_dir: Optional[Path],
+ snapshot_dir: Optional[Path],
+ *,
+ quants: Optional[bool] = None,
+) -> bool:
+ """Whether a repo-wide partial signal describes *snapshot_dir*.
+
+ Cancel markers, ``.incomplete`` blobs and the repo-wide manifest carry no revision and are
+ rewritten by each attempt, so they belong to the newest snapshot; an older complete one must not
+ inherit them and lose ``can_chat``. With nothing to attribute against, keep them. A ``refs/main``
+ naming a commit with no directory pins that attempt to a revision absent from disk, so no
+ snapshot inherits it, but that excuses only a snapshot that can serve the row.
+
+ Keyed on ``refs/main`` alone, unlike the recovery guard: where ``refs/main`` resolves the row
+ loads by id and the manifest describes what that load reads, so a stale tag must not suppress it.
+ """
+ if repo_cache_dir is None or snapshot_dir is None:
+ return True
+ if _default_ref_names_an_absent_snapshot(repo_cache_dir):
+ return _snapshot_cannot_serve_its_payload(snapshot_dir, quants = quants)
+ # Only excuse a non-newest snapshot while it can still serve the row.
+ return _is_latest_snapshot(repo_cache_dir, snapshot_dir) or (
+ _snapshot_cannot_serve_its_payload(snapshot_dir, quants = quants)
+ )
+
+
def _gguf_variant_manifest_blob_hashes(
repo_id: str, repo_cache_dir: Optional[Path] = None
) -> frozenset[str]:
@@ -284,18 +660,28 @@ def _gguf_variant_manifest_blob_hashes(
def _repo_cache_dir_has_snapshot_legacy_partial(
- repo_cache_dir: Path, *, ignored_blob_hashes: frozenset[str]
+ repo_cache_dir: Path,
+ *,
+ ignored_blob_hashes: frozenset[str],
+ snapshot_dir: Optional[Path] = None,
) -> bool:
- incomplete_hashes = _repo_cache_dir_incomplete_hashes(repo_cache_dir)
- if any(blob_hash not in ignored_blob_hashes for blob_hash in incomplete_hashes):
+ if _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(repo_cache_dir, snapshot_dir):
return True
- return _repo_cache_dir_has_non_gguf_broken_snapshot_symlinks(repo_cache_dir)
+ # ``.incomplete`` blobs carry no revision, so they need attributing. Judged on this row's
+ # weights alone: a torn quant beside them is another row's payload, not this one's.
+ if snapshot_dir is not None and not _repo_signal_applies_to_snapshot(
+ repo_cache_dir, snapshot_dir, quants = False
+ ):
+ return False
+ incomplete_hashes = _repo_cache_dir_incomplete_hashes(repo_cache_dir)
+ return any(blob_hash not in ignored_blob_hashes for blob_hash in incomplete_hashes)
def _snapshot_legacy_partial(
repo_type: str,
repo_id: str,
repo_cache_dir: Optional[Path] = None,
+ snapshot_dir: Optional[Path] = None,
) -> bool:
if repo_type != "model":
return _legacy_partial(repo_type, repo_id, repo_cache_dir)
@@ -304,7 +690,9 @@ def _snapshot_legacy_partial(
return _repo_cache_dir_has_snapshot_legacy_partial(
repo_cache_dir,
ignored_blob_hashes = ignored_hashes,
+ snapshot_dir = snapshot_dir,
)
+ # No repo dir to attribute against, so the signal is kept.
return any(
_repo_cache_dir_has_snapshot_legacy_partial(
entry,
@@ -314,42 +702,640 @@ def _snapshot_legacy_partial(
)
+_UNJUDGEABLE_FAMILY = object()
+
+
def _completed_gguf_variants(snapshot_dir: Optional[Path]) -> set[str]:
if snapshot_dir is None:
return set()
- complete: set[str] = set()
- split_groups: dict[str, dict[int, set[int]]] = {}
+ # A load id can name the .gguf file itself, so resolve to its parent like the lister.
+ from hub.utils.gguf import _resolve_gguf_dir
+
+ snapshot_dir = _resolve_gguf_dir(snapshot_dir) or snapshot_dir
+ # Keyed on quant, then on shard family (directory, prefix, total); one quant can cover several.
+ split_groups: dict[str, dict[tuple[str, str, int], set[int]]] = {}
+ # Lister and loader both take the lexicographically first file, hence the sort.
+ # None = no total named; _UNJUDGEABLE_FAMILY = bad spec.
+ selected: dict[str, object] = {}
try:
- paths = list(snapshot_dir.rglob("*"))
+ paths = sorted(snapshot_dir.rglob("*"))
except OSError:
return set()
for path in paths:
try:
- if not path.is_file() or path.stat().st_size <= 0:
+ if not path.is_file():
continue
+ empty = path.stat().st_size <= 0
except OSError:
continue
rel = path.relative_to(snapshot_dir).as_posix()
if not is_gguf_filename(rel) or is_mmproj_filename(rel) or is_mtp_drafter_path(rel):
continue
quant = extract_quant_label(rel)
+ # Mirror the lister: a big-endian build is never offered, so it cannot vouch for the quant.
+ if is_big_endian_gguf_path(rel, quant):
+ continue
+ if empty:
+ # The resolver still opens this file, so a zero-byte first pick is unjudgeable.
+ selected.setdefault(quant, _UNJUDGEABLE_FAMILY)
+ continue
split = _GGUF_SPLIT_RE.search(path.name)
if split is None:
- complete.add(quant)
+ selected.setdefault(quant, None)
continue
index = int(split.group(1))
total = int(split.group(2))
if index <= 0 or total <= 0 or index > total:
+ selected.setdefault(quant, _UNJUDGEABLE_FAMILY)
continue
- split_groups.setdefault(quant, {}).setdefault(total, set()).add(index)
- for quant, groups in split_groups.items():
- for total, indices in groups.items():
- if indices == set(range(1, total + 1)):
+ family = (
+ path.parent.relative_to(snapshot_dir).as_posix(),
+ path.name[: split.start()],
+ total,
+ )
+ # Record every shard: the rest of the selected family sorts after the one that selected it.
+ split_groups.setdefault(quant, {}).setdefault(family, set()).add(index)
+ selected.setdefault(quant, family)
+ complete: set[str] = set()
+ for quant, family in selected.items():
+ if family is None:
+ complete.add(quant)
+ elif isinstance(family, tuple):
+ if _shard_family_is_whole(family, split_groups.get(quant, {}).get(family) or set()):
complete.add(quant)
- break
return complete
+def _offered_gguf_quants(snapshot_dir: Path) -> set[str]:
+ from hub.utils.gguf import list_local_gguf_variants
+ try:
+ variants, _ = list_local_gguf_variants(str(snapshot_dir))
+ return {v.quant for v in variants if getattr(v, "quant", None)}
+ except Exception:
+ return set()
+
+
+# The name each loader opens first; nothing else under that suffix is a fallback.
+_LOADER_WEIGHT_NAMES = {
+ "base": {".safetensors": "model.safetensors", ".bin": "pytorch_model.bin"},
+ "adapter": {".safetensors": "adapter_model.safetensors", ".bin": "adapter_model.bin"},
+}
+
+
+def _weight_family_kind(name: str) -> Optional[str]:
+ """``"base"``, ``"adapter"``, or ``None`` for a training artefact such as ``optimizer.bin`` that
+ no row loads, so an auxiliary set is never counted as a runnable family."""
+ # Local import: hub.services imports hub.utils.
+ from hub.services.models.common import (
+ _is_adapter_weight_name,
+ _is_transformers_bin_weight_name,
+ _is_transformers_safetensors_weight_name,
+ )
+
+ if _is_adapter_weight_name(name):
+ return "adapter"
+ if _is_transformers_safetensors_weight_name(name) or _is_transformers_bin_weight_name(name):
+ return "base"
+ return None
+
+
+class _SnapshotPayload(NamedTuple):
+ """What one snapshot directory can load on its own."""
+
+ model_format: Optional[str]
+ # Shard families per kind, keyed on (dir, prefix, total, suffix).
+ groups: dict
+ # Suffixes per kind holding a file that names no total, i.e. a family of one.
+ whole: dict
+ # Required configs that exist but are empty, by format.
+ unreadable_config_formats: frozenset
+ # Shard families the loader picks and then fails on.
+ unloadable_families: frozenset
+ # Shard families the loader never looks for, so it moves on to the next name.
+ invisible_families: frozenset
+ # Kinds whose payload is here but names no family this walk groups.
+ ungrouped: frozenset
+ # Kinds whose only ungroupable payload (.ckpt, diffusion prefix) is empty.
+ empty_ungrouped: frozenset
+ # Suffixes per kind whose unsharded name is present but empty.
+ empty_whole: dict
+ # Kinds whose weights are here but only under a subdirectory no loader opens.
+ nested: frozenset
+ # Suffixes whose canonical root index exists, shards recovered or not.
+ root_indexes: frozenset
+ # Of those, the ones naming a file that is missing or empty.
+ unusable_root_indexes: frozenset
+ # Kinds whose root payload no loader opens by name, e.g. an arbitrary foo.safetensors.
+ unreachable_root: frozenset
+
+
+def _root_file_is_empty(snapshot_dir: Path, name: str) -> Optional[bool]:
+ """None when *name* is not a file at the root, else whether it is zero bytes.
+
+ The loaders open exact paths, so the filesystem answers the case question: a Config.json serves
+ config.json on a case-insensitive volume and not on a case-sensitive one, and lowercasing every
+ basename got that wrong in one direction or the other.
+ """
+ path = snapshot_dir / name
+ try:
+ if not path.is_file():
+ return None
+ return path.stat().st_size <= 0
+ except OSError:
+ return None
+
+
+def _required_config_is_unreadable(path: Path, empty: bool) -> bool:
+ """Whether a config the loader requires is one it cannot use.
+
+ Empty is the obvious case, but from_pretrained parses this file before it looks at a single
+ weight, so a truncated or non-object one fails the load just as surely.
+ """
+ if empty:
+ return True
+ try:
+ with path.open("rb") as handle:
+ return not isinstance(json.load(handle), dict)
+ except (OSError, ValueError):
+ return True
+
+
+def _shard_family_is_whole(family: tuple, indices: set) -> bool:
+ """Whether *indices* is exactly 1..total for *family*.
+
+ Compared without building the range: the total comes out of a filename, so it can name a set
+ far larger than anything on disk.
+ """
+ total = family[2]
+ return bool(indices) and len(indices) == total and min(indices) == 1 and max(indices) == total
+
+
+def _weight_shard_family(snapshot_dir: Path, path: Path, match) -> tuple:
+ """The key grouping ``path`` with its siblings.
+
+ The suffix is part of the key: a .safetensors shard and a .bin shard sharing a prefix and a
+ total are different sets, and merging them made two half sets look like one whole one.
+ Numbering that cannot be satisfied (index 0, or one past the total) still names a family:
+ dropping it left a snapshot that classifies by filename with no family to be short of.
+ """
+ return (
+ path.parent.relative_to(snapshot_dir).as_posix(),
+ path.name[: match.start()],
+ int(match.group(2)),
+ path.suffix.lower(),
+ )
+
+
+def _snapshot_payload(snapshot_dir: Path) -> Optional[_SnapshotPayload]:
+ """Classify *snapshot_dir* from its own contents, or None if it cannot be read.
+
+ Untrusted, like ``_repo_non_gguf_model_payload``'s per-revision pass: a directory serves a load
+ only if it holds the config its format needs. Presence is by filename, so an empty config still
+ classifies and is reported separately.
+ """
+ from hub.services.models.common import (
+ _classify_non_gguf_model_format,
+ _is_adapter_weight_name,
+ _is_checkpoint_weight_name,
+ _is_discoverable_ungrouped_weight_name,
+ _is_training_artefact_name,
+ _is_transformers_safetensors_weight_name,
+ )
+
+ flags = dict.fromkeys(
+ (
+ "has_config",
+ "has_adapter_config",
+ "has_adapter_weights",
+ "has_safetensors",
+ "has_transformers_safetensors",
+ "has_checkpoint_weights",
+ ),
+ False,
+ )
+ groups: dict[str, dict[tuple[str, str, int, str], set[int]]] = {"base": {}, "adapter": {}}
+ whole: dict[str, set[str]] = {"base": set(), "adapter": set()}
+ shard_names: dict[tuple[str, str, int, str], set[str]] = {}
+ ungrouped: set[str] = set()
+ empty_whole: dict[str, set[str]] = {"base": set(), "adapter": set()}
+ empty_ungrouped: set[str] = set()
+ nested: set[str] = set()
+ unreachable_root: set[str] = set()
+ unreadable: set[str] = set()
+ try:
+ paths = list(snapshot_dir.rglob("*"))
+ except OSError:
+ return None
+ for path in paths:
+ try:
+ if not path.is_file():
+ continue
+ empty = path.stat().st_size <= 0
+ except OSError:
+ continue
+ name = path.name.lower()
+ if is_gguf_filename(name):
+ continue
+ # Configs are opened by exact name at the handed directory: probed below, not matched here.
+ at_root = path.parent == snapshot_dir
+ if name in ("config.json", "adapter_config.json"):
+ continue
+ if empty:
+ # The loader picks a name by existence, so a zero-byte weight is opened and unreadable.
+ empty_kind = _weight_family_kind(path.name)
+ empty_match = _WEIGHT_SHARD_RE.search(path.name)
+ if empty_kind is None:
+ # Judged on nothing else, so remember it. Same set the walk below counts.
+ if (
+ not _is_adapter_weight_name(name)
+ and not _is_training_artefact_name(name)
+ and (name.endswith(".safetensors") or _is_checkpoint_weight_name(name))
+ ):
+ if at_root:
+ empty_ungrouped.add("base")
+ else:
+ nested.add("base")
+ continue
+ if empty_match is None:
+ # Same rule as the whole file below: only the root name is one the loader opens.
+ if at_root:
+ empty_whole[empty_kind].add(name)
+ else:
+ nested.add(empty_kind)
+ continue
+ # An empty numbered shard is absent from its family, but the family still needs naming.
+ empty_family = _weight_shard_family(snapshot_dir, path, empty_match)
+ groups[empty_kind].setdefault(empty_family, set())
+ shard_names.setdefault(empty_family, set()).add(path.name)
+ continue
+ is_adapter = _is_adapter_weight_name(name)
+ base_evidence = False
+ if is_adapter:
+ flags["has_adapter_weights"] = True
+ elif name.endswith(".safetensors") and not _is_training_artefact_name(name):
+ flags["has_safetensors"] = True
+ base_evidence = True
+ if _is_transformers_safetensors_weight_name(name):
+ flags["has_transformers_safetensors"] = True
+ if _is_checkpoint_weight_name(name) and not _is_training_artefact_name(name):
+ flags["has_checkpoint_weights"] = True
+ base_evidence = not is_adapter
+ kind = _weight_family_kind(path.name)
+ if kind is None:
+ # Ungroupable but still a payload; only a root copy is found.
+ if base_evidence:
+ if not at_root:
+ nested.add("base")
+ elif _is_discoverable_ungrouped_weight_name(name):
+ ungrouped.add("base")
+ else:
+ unreachable_root.add("base")
+ continue
+ match = _WEIGHT_SHARD_RE.search(path.name)
+ if match is None:
+ # Only the root copy is the name the loader opens, so a nested one proves nothing.
+ if at_root:
+ whole[kind].add(name)
+ else:
+ nested.add(kind)
+ continue
+ family = _weight_shard_family(snapshot_dir, path, match)
+ if not at_root:
+ nested.add(kind)
+ groups[kind].setdefault(family, set()).add(int(match.group(1)))
+ shard_names.setdefault(family, set()).add(path.name)
+ for config_name, formats in (
+ ("config.json", ("safetensors", "checkpoint")),
+ ("adapter_config.json", ("adapter",)),
+ ):
+ config_empty = _root_file_is_empty(snapshot_dir, config_name)
+ if config_empty is None:
+ continue
+ flags["has_config" if config_name == "config.json" else "has_adapter_config"] = True
+ if _required_config_is_unreadable(snapshot_dir / config_name, config_empty):
+ unreadable.update(formats)
+ model_format = _classify_non_gguf_model_format(**flags, trusted_hf_cache_repo = False)
+ # from_pretrained never globs, so shards with no index are invisible and neither serve nor veto.
+ # An unusable index is picked and failed on instead.
+ unloadable: set = set()
+ invisible: set = set()
+ # Selected by its own name, so it counts even when the walk grouped no shard of it, and it
+ # carries its own paths: every weight_map entry resolves against the index.
+ root_indexes: set[str] = set()
+ unusable_root_indexes: set[str] = set()
+ for suffix, canonical in _LOADER_WEIGHT_NAMES["base"].items():
+ index_path = snapshot_dir / f"{canonical}.index.json"
+ try:
+ if not index_path.is_file():
+ continue
+ except OSError:
+ continue
+ root_indexes.add(suffix)
+ if _index_cannot_serve_its_shards(index_path, set()):
+ unusable_root_indexes.add(suffix)
+ for family in groups["base"]:
+ # Only the canonical index is probed, so a set behind any other name is one it never opens.
+ index_path = (
+ snapshot_dir / family[0] / f"{_LOADER_WEIGHT_NAMES['base'][family[3]]}.index.json"
+ )
+ try:
+ present = index_path.is_file()
+ except OSError:
+ present = False
+ if not present:
+ invisible.add(family)
+ elif _index_cannot_serve_its_shards(index_path, shard_names.get(family, set())):
+ unloadable.add(family)
+ # peft resolves only the singular adapter_model.*, so it never looks at a numbered adapter set.
+ invisible |= set(groups["adapter"])
+ return _SnapshotPayload(
+ model_format,
+ groups,
+ whole,
+ frozenset(unreadable),
+ frozenset(unloadable),
+ frozenset(invisible),
+ frozenset(ungrouped),
+ frozenset(empty_ungrouped),
+ empty_whole,
+ frozenset(nested),
+ frozenset(root_indexes),
+ frozenset(unusable_root_indexes),
+ frozenset(unreachable_root),
+ )
+
+
+def _index_cannot_serve_its_shards(index_path: Path, family_files: set[str]) -> bool:
+ """Whether *index_path* would fail to hand ``from_pretrained`` the family in *family_files*.
+
+ Existing is not enough: the loader parses it and opens every ``weight_map`` name, so a truncated
+ index or one naming a shard never written is as unloadable as no index at all. The map is also
+ the only list of files read, so one covering part of the numbered family silently drops the rest.
+ """
+ try:
+ if not index_path.is_file() or index_path.stat().st_size <= 0:
+ return True
+ with index_path.open(encoding = "utf-8") as handle:
+ index = json.load(handle)
+ except (OSError, UnicodeDecodeError, ValueError):
+ return True
+ weight_map = index.get("weight_map") if isinstance(index, dict) else None
+ if not isinstance(weight_map, dict) or not weight_map:
+ return True
+ named = {
+ shard.replace("\\", "/").rsplit("/", 1)[-1]
+ for shard in weight_map.values()
+ if isinstance(shard, str)
+ }
+ # Coverage matters only for the family this index describes: one it names nothing of is stale
+ # content beside it, which the loader never reads because it opens weight_map and nothing else.
+ if not family_files <= named and not named.isdisjoint(family_files):
+ return True
+ for shard in weight_map.values():
+ # Names are relative to the index: anything reaching outside is not a shard of this family.
+ if not isinstance(shard, str) or not shard:
+ return True
+ parts = PurePosixPath(shard.replace("\\", "/"))
+ if parts.is_absolute() or ".." in parts.parts:
+ return True
+ try:
+ named = index_path.parent / parts
+ if not named.is_file() or named.stat().st_size <= 0:
+ return True
+ except (OSError, ValueError):
+ return True
+ # A shard names its own total, so an index listing one of a set has to list the whole set: the
+ # loader opens exactly what is mapped and silently drops whatever the map leaves out.
+ declared: dict[tuple[str, str, int], set[int]] = {}
+ for shard in weight_map.values():
+ if not isinstance(shard, str):
+ continue
+ rel = PurePosixPath(shard.replace("\\", "/"))
+ match = _WEIGHT_SHARD_RE.search(rel.name)
+ if match is None:
+ continue
+ key = (str(rel.parent), rel.name[: match.start()], int(match.group(2)))
+ declared.setdefault(key, set()).add(int(match.group(1)))
+ return any(total <= 0 or len(seen) < total for (_d, _p, total), seen in declared.items())
+
+
+def _snapshot_lacks_a_complete_weight_family(snapshot_dir: Path) -> bool:
+ """Whether the payload *snapshot_dir* carries is short a shard.
+
+ ``from_pretrained`` loads one family, so a whole safetensors set beside an interrupted ``.bin``
+ one still serves the row. Only the family the classified format names is judged: a snapshot can
+ hold both a config.json and an adapter_config.json, so the config alone does not say which.
+ """
+ payload = _snapshot_payload(snapshot_dir)
+ if payload is None:
+ return False
+ # Recognised by filename, so it classifies, but nothing can parse it.
+ if payload.model_format in payload.unreadable_config_formats:
+ return True
+ wanted = "adapter" if payload.model_format == "adapter" else "base"
+ other = "base" if wanted == "adapter" else "adapter"
+ order = (wanted, other)
+ for kind in order:
+ # Both loaders try safetensors before pickle and never fall back, so judge in that order.
+ unreachable = False
+ for suffix in (".safetensors", ".bin"):
+ selected = _LOADER_WEIGHT_NAMES[kind][suffix]
+ # Probed, not matched: the walk folds case, so it would accept MODEL.SAFETENSORS here.
+ canonical_empty = _root_file_is_empty(snapshot_dir, selected)
+ if canonical_empty is True:
+ # The loader opens this name first and finds it empty. Same exemption as below.
+ return kind == wanted or wanted not in payload.ungrouped
+ if canonical_empty is False:
+ # Only the row's own kind proves it loads, and it vetoes nothing once that kind's
+ # payload is here but names no family.
+ return kind != wanted and wanted not in payload.ungrouped
+ # from_pretrained reads the snapshot root, so only families named there are judged; a
+ # subdirectory layout is carried by ungrouped instead.
+ if kind == "base" and suffix in payload.root_indexes:
+ # Selected and loaded for exactly what it names, wherever those paths point, so
+ # judge its contents rather than this walk's families: a numbered file it names
+ # nothing of is never read. The next name is never tried.
+ if suffix in payload.unusable_root_indexes:
+ return kind == wanted or wanted not in payload.ungrouped
+ return kind != wanted and wanted not in payload.ungrouped
+ families = {
+ family: indices
+ for family, indices in payload.groups[kind].items()
+ if family[3] == suffix and family[0] in ("", ".")
+ }
+ if not families:
+ if any(
+ root.endswith(suffix)
+ for root in payload.whole[kind] | payload.empty_whole[kind]
+ ):
+ # A whole root weight the loader never opens, e.g. consolidated.safetensors.
+ unreachable = True
+ continue
+ if all(family in payload.invisible_families for family in families):
+ # Nothing names these shards, so they neither serve nor veto.
+ unreachable = True
+ continue
+ # An unloadable family is incomplete, not a veto: a whole one beside it still serves.
+ return all(
+ not _shard_family_is_whole(family, indices) or family in payload.unloadable_families
+ for family, indices in families.items()
+ )
+ # Nested weights decide only when the root offered nothing of this kind, groupable or not.
+ if unreachable or (
+ kind == wanted and kind in payload.nested and kind not in payload.ungrouped
+ ):
+ # This kind's weights are here but no name the loader tries reaches them.
+ return True
+ # No family: an ungroupable payload is evidence only when alone and empty or unreachable.
+ return (
+ wanted in payload.empty_ungrouped or wanted in payload.unreachable_root
+ ) and wanted not in payload.ungrouped
+
+
+def _snapshot_cannot_serve_its_payload(
+ snapshot_dir: Optional[Path], *, quants: Optional[bool] = None
+) -> bool:
+ """Whether *snapshot_dir*'s own contents prove it cannot serve a row.
+
+ Judged on the pinned snapshot alone, since the dangling ref is exactly what stopped being
+ evidence. Quants are judged on quants, otherwise on safetensors/checkpoint families, under
+ ``is_gguf_repo_partial``'s rule: one complete quant or family is enough, and only a file naming
+ its own total counts as proof.
+
+ *quants* picks the row's format in a hybrid repo: True quants, False families, None either.
+ Otherwise a torn quant vetoes a whole weights row, and a whole one vouches for a torn family.
+ """
+ if snapshot_dir is None:
+ return False
+ if quants is not False:
+ offered = _offered_gguf_quants(snapshot_dir)
+ if offered:
+ return not (offered & _completed_gguf_variants(snapshot_dir))
+ if quants:
+ # A quant row with no quant here: its evidence is pooled across revisions.
+ return False
+ return _snapshot_lacks_a_complete_weight_family(snapshot_dir)
+
+
+def _recovered_snapshot_cannot_serve(
+ repo_cache_dir: Optional[Path],
+ snapshot_dir: Optional[Path],
+ *,
+ quants: Optional[bool] = None,
+) -> bool:
+ """Partial signal for a snapshot the dangling-ref recovery put back on a row.
+
+ The interrupted attempt that wrote the ref may have left nothing else behind, so marker,
+ manifest and ``.incomplete``/broken-symlink all read false and a snapshot short a shard looks
+ runnable; its contents are the only evidence left. Scoped to the dangling case: where the ref
+ resolves, upstream already publishes the row.
+ """
+ if repo_cache_dir is None or snapshot_dir is None:
+ return False
+ if not _repo_has_a_dangling_ref(repo_cache_dir):
+ return False
+ return _snapshot_cannot_serve_its_payload(snapshot_dir, quants = quants)
+
+
+def snapshot_holds_a_complete_payload(
+ snapshot_dir: Optional[Path], *, quants: Optional[bool] = None
+) -> bool:
+ """Whether *snapshot_dir* can serve a load from its own contents alone.
+
+ The selection-side counterpart to the partial check: a row picks the newest snapshot that
+ classifies, and filename-only classification cannot tell a whole payload from one short a shard,
+ so without this a broken newer revision hides a complete older one.
+ """
+ if snapshot_dir is None:
+ return False
+ return not _snapshot_cannot_serve_its_payload(snapshot_dir, quants = quants)
+
+
+def recovered_repo_is_unusable_by_repo_id(repo_info) -> bool:
+ """Whether a recovered repo is one a caller that can only say ``repo_id`` must skip.
+
+ The Hub inventory carries ``partial`` and a ``load_id``, so it describes these rows honestly.
+ The compatibility ``/api/models/cached-models`` schema has neither, so an unusable recovery
+ reads there as a plain cached model. False for every repo upstream already returns, so this
+ only withholds rows this recovery added.
+ """
+ if not isinstance(repo_info, _RecoveredRepoInfo):
+ return False
+ repo_path = getattr(repo_info, "repo_path", None)
+ if repo_path is None:
+ return True
+ # Recovery also fires when a secondary ref dangles while refs/main resolves; those load by id.
+ landing = default_ref_snapshot(repo_path)
+ if landing is None:
+ return True
+ if _snapshot_cannot_serve_its_payload(landing):
+ return True
+ # Weights pool across revisions, so the directory refs/main lands on must classify on its own.
+ if _offered_gguf_quants(landing):
+ return False
+ payload = _snapshot_payload(landing)
+ return payload is None or payload.model_format is None
+
+
+def snapshot_variants_all_complete(snapshot: str) -> bool:
+ """True when every quant the lister would advertise from *snapshot* is on disk.
+
+ One complete quant is not enough: the picker enumerates the whole directory, so a half-downloaded
+ split quant beside a good one still gets offered.
+ """
+ from hub.utils.gguf import list_local_gguf_variants
+ try:
+ variants, _ = list_local_gguf_variants(snapshot)
+ offered = {v.quant for v in variants if getattr(v, "quant", None)}
+ if not offered:
+ return False
+ return offered <= _completed_gguf_variants(Path(snapshot))
+ except Exception:
+ return False
+
+
+def snapshot_has_complete_variants(snapshot: str) -> bool:
+ """True when at least one quant the lister advertises from *snapshot* is on disk.
+
+ Weaker than ``snapshot_variants_all_complete`` on purpose: a snapshot mixing a whole quant with
+ an interrupted split one still loads the whole one, and the lister trims the offer to that
+ subset. Every load-id pin uses this, so selection and offered variants name one directory.
+ """
+ from hub.utils.gguf import list_local_gguf_variants
+ try:
+ variants, _ = list_local_gguf_variants(snapshot)
+ offered = {v.quant for v in variants if getattr(v, "quant", None)}
+ if not offered:
+ return False
+ return bool(offered & _completed_gguf_variants(Path(snapshot)))
+ except Exception:
+ return False
+
+
+def snapshot_has_gguf_projector(snapshot: Optional[Path]) -> bool:
+ """Whether *snapshot* itself holds a GGUF vision projector.
+
+ Same walk the variant lister reports ``has_vision`` from, so row capability and picker flag
+ cannot name different revisions.
+ """
+ if snapshot is None:
+ return False
+ from hub.utils.gguf import list_local_gguf_variants
+
+ try:
+ return bool(list_local_gguf_variants(str(snapshot))[1])
+ except Exception:
+ return False
+
+
+def complete_snapshot_variants(snapshot: str) -> set[str]:
+ """Quant labels in *snapshot* whose files are all on disk."""
+ try:
+ return _completed_gguf_variants(Path(snapshot))
+ except (OSError, RuntimeError, ValueError):
+ return set()
+
+
def _manifest_partial(
repo_type: RepoType,
repo_id: str,
@@ -427,33 +1413,45 @@ def is_snapshot_partial(
repo_type: RepoType,
repo_id: str,
repo_cache_dir: Optional[Path] = None,
+ snapshot_dir: Optional[Path] = None,
) -> bool:
- """Repo-row partial flag for snapshot-style downloads (full-snapshot
- models — safetensors/adapter/checkpoint — and all datasets).
+ """Repo-row partial flag for snapshot-style downloads (full-snapshot models, i.e.
+ safetensors/adapter/checkpoint, and all datasets).
- Composes three signals, cheapest first:
- 1. Cancel marker (single stat).
+ Composes four signals, cheapest first:
+ 1. Cancel marker (single stat), charged to the newest snapshot.
2. Snapshot-attributed legacy .incomplete blob / broken-symlink check.
3. Manifest walk (stat per expected file under the latest snapshot).
+ 4. A recovered snapshot short a shard, for the dangling-ref rows the first three cannot judge.
- A manifest without a resolvable snapshot is partial: the worker got
- far enough to record expectations but did not leave a usable snapshot."""
+ A manifest without a resolvable snapshot is partial: the worker recorded expectations but left
+ no usable snapshot. *snapshot_dir* pins the legacy and manifest walks to the row's load identity;
+ without it a metadata-only revision beside a complete download flags the row partial. Repo-wide
+ signals are attributed by ``_repo_signal_applies_to_snapshot``."""
from hub.utils import download_manifest
+
+ # A snapshot-style row loads weights, so a quant beside them is another row's payload.
+ repo_signal_applies = _repo_signal_applies_to_snapshot(
+ repo_cache_dir, snapshot_dir, quants = False
+ )
return _compose_partial(
- lambda: download_manifest.has_cancel_marker(
+ lambda: repo_signal_applies
+ and download_manifest.has_cancel_marker(
repo_type,
repo_id,
None,
hub_cache = _hub_cache_for_repo_dir(repo_cache_dir),
),
- lambda: _snapshot_legacy_partial(repo_type, repo_id, repo_cache_dir),
- lambda: _manifest_partial(
+ lambda: _snapshot_legacy_partial(repo_type, repo_id, repo_cache_dir, snapshot_dir),
+ lambda: repo_signal_applies
+ and _manifest_partial(
repo_type,
repo_id,
None,
- None,
+ snapshot_dir,
repo_cache_dir,
),
+ lambda: _recovered_snapshot_cannot_serve(repo_cache_dir, snapshot_dir, quants = False),
)
@@ -465,28 +1463,34 @@ def is_variant_partial(
incomplete_blob_hashes: Optional[set[str]] = None,
variant_blob_hashes: Optional[frozenset[str]] = None,
repo_cache_dir: Optional[Path] = None,
+ repo_signal_applies: bool = True,
) -> bool:
"""Per-variant partial detection. Owns its manifest, owns its marker.
- Used by the GGUF variants endpoint to flag a specific quant as broken
- without contaminating other quants in the same repo.
- snapshot_dir is an optional hint to avoid re-walking the cache when a
- caller is checking many variants of the same repo (see
- is_gguf_repo_partial for that usage)."""
+ Used by the GGUF variants endpoint to flag one quant as broken without contaminating the others
+ in the same repo. *snapshot_dir* is an optional hint to avoid re-walking the cache when checking
+ many variants of one repo (see is_gguf_repo_partial). ``repo_signal_applies`` is
+ ``_repo_signal_applies_to_snapshot``'s verdict: a caller pinning an older revision passes False
+ rather than judge that quant by another revision's marker, manifest or blobs. Defaults True so
+ the per-variant endpoint still reports a cancelled quant as broken."""
from hub.utils import download_manifest
return _compose_partial(
- lambda: download_manifest.has_cancel_marker(
+ lambda: repo_signal_applies
+ and download_manifest.has_cancel_marker(
"model",
repo_id,
variant,
hub_cache = _hub_cache_for_repo_dir(repo_cache_dir),
),
- lambda: bool(
+ # blobs/ is repo-wide, so a retry's .incomplete belongs to the newest snapshot.
+ lambda: repo_signal_applies
+ and bool(
incomplete_blob_hashes
and variant_blob_hashes
and incomplete_blob_hashes.intersection(variant_blob_hashes)
),
- lambda: _manifest_partial(
+ lambda: repo_signal_applies
+ and _manifest_partial(
"model",
repo_id,
variant,
@@ -496,35 +1500,42 @@ def is_variant_partial(
)
-def is_gguf_repo_partial(repo_id: str, repo_cache_dir: Optional[Path] = None) -> bool:
+def is_gguf_repo_partial(
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+ *,
+ snapshot_dir: Optional[Path] = None,
+) -> bool:
"""Repo-row partial flag for a GGUF repo. The inventory shows ONE row per
GGUF repo (requires_variant=True); per-variant detail lives in
GET /api/models/gguf-variants and uses is_variant_partial.
*** DO NOT simplify this to "any variant partial -> repo partial" ***
- Tripwire scenario: user downloads Q8_0 fully, then starts Q4_K_M and
- cancels. Both variants share ONE inventory row. If row.partial flips True,
- _capabilities_for_format flips can_chat=False, so the user can no longer
- chat with the perfectly-good Q8_0 because of an unrelated cancelled Q4_K_M.
+ Tripwire scenario: user downloads Q8_0 fully, then starts Q4_K_M and cancels. Both variants share
+ ONE inventory row, so flipping row.partial True flips can_chat=False and the perfectly-good Q8_0
+ becomes unchattable over an unrelated cancelled Q4_K_M.
- Correct semantics: partial=True only when at least one variant is broken
- AND no other variant is clean. "Simplifying" to the obvious "any broken"
- form re-introduces this Q8+Q4 mixed-state regression.
-
- Composes signals:
- 1. Cheap legacy fast-path (.incomplete blobs / broken symlinks).
- 2. Per-variant manifest + marker enumeration, gated on "all broken".
+ Correct semantics: partial=True only when at least one variant is broken AND no other variant is
+ clean. Composes a cheap legacy fast-path (.incomplete blobs / broken symlinks) with a per-variant
+ manifest + marker enumeration gated on "all broken". *snapshot_dir* pins both to the row's load
+ id; without it an interrupted re-download flips can_chat off for the older complete quant.
"""
from hub.utils import download_manifest
- has_legacy_partial = _legacy_partial("model", repo_id, repo_cache_dir)
- snapshot_dir = resolve_snapshot_dir_for_scan(
- "model",
- repo_id,
- repo_cache_dir,
+ if snapshot_dir is None:
+ snapshot_dir = resolve_snapshot_dir_for_scan(
+ "model",
+ repo_id,
+ repo_cache_dir,
+ )
+ # Same attribution as is_snapshot_partial, judged on this row's quants rather than its weights.
+ repo_signal_applies = _repo_signal_applies_to_snapshot(
+ repo_cache_dir, snapshot_dir, quants = True
)
- variants: set[str] = set(_completed_gguf_variants(snapshot_dir))
+ has_legacy_partial = repo_signal_applies and _legacy_partial("model", repo_id, repo_cache_dir)
+ complete_here = _completed_gguf_variants(snapshot_dir)
+ variants: set[str] = set(complete_here)
hub_cache = _hub_cache_for_repo_dir(repo_cache_dir)
for variant, _path in download_manifest.iter_variant_manifests(
"model",
@@ -554,7 +1565,10 @@ def is_gguf_repo_partial(repo_id: str, repo_cache_dir: Optional[Path] = None) ->
):
variants.add(variant)
if not variants:
- return has_legacy_partial
+ # Nothing named a quant: an interrupted attempt leaves only torn shards.
+ return has_legacy_partial or _recovered_snapshot_cannot_serve(
+ repo_cache_dir, snapshot_dir, quants = True
+ )
has_clean = False
has_broken = has_legacy_partial
for variant in variants:
@@ -563,6 +1577,8 @@ def is_gguf_repo_partial(repo_id: str, repo_cache_dir: Optional[Path] = None) ->
variant,
snapshot_dir,
repo_cache_dir = repo_cache_dir,
+ # A quant whole in the pinned snapshot loads whatever a newer attempt says.
+ repo_signal_applies = repo_signal_applies or variant not in complete_here,
):
has_broken = True
else:
diff --git a/studio/backend/picker/service.py b/studio/backend/picker/service.py
index ccf9c3e152a..7b08bc6e48a 100644
--- a/studio/backend/picker/service.py
+++ b/studio/backend/picker/service.py
@@ -14,7 +14,7 @@ from hub.services.models.folder_browser import (
_build_browse_allowlist,
_is_path_inside_allowlist,
)
-from hub.utils.gguf import extract_quant_label, iter_hf_cache_snapshots
+from hub.utils.gguf import extract_quant_label, iter_snapshots_preferring_whole
from utils.models.gguf_metadata import read_gguf_chat_template
from utils.models.model_config import (
_extract_quant_label,
@@ -346,7 +346,7 @@ def read_default_chat_template(
# Resolve within each cached revision, newest first. A revision's sidecar
# supersedes its own embedded GGUF copy, but must not override a newer
# revision, so precedence stays per-snapshot rather than global.
- for snapshot in iter_hf_cache_snapshots(resolved):
+ for snapshot in iter_snapshots_preferring_whole(resolved, gguf_variant):
template = _chat_template_from_dir(snapshot, gguf_variant)
if template:
return template
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 836efc4e56c..f43d1580440 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -1913,7 +1913,7 @@ def _request_used_api_key(request: Any) -> bool:
from state.tool_approvals import resolve_tool_decision
from core.inference.key_exchange import decrypt_api_key
-from core.inference.model_ids import public_model_id
+from core.inference.model_ids import model_id_matches, public_model_id
from core.inference.api_monitor import api_monitor
from core.inference.llama_http import nonstreaming_client
from core.inference.tool_call_parser import (
@@ -5529,6 +5529,46 @@ async def _drain_and_recancel_before_teardown(*, force: bool, action: str) -> No
_UNRESOLVED_BACKEND_STATE = object()
+def _names_the_resident_model(resident: Optional[str], model_path: str) -> bool:
+ """Whether a client's ``model_path`` names ``resident``.
+
+ A cached row can pin a snapshot directory, so the load sends that path while the status the
+ client reads back reports the repo id it maps to. Both name the same model, and an unload
+ arriving under either has to find it.
+ """
+ return bool(resident) and model_id_matches(model_path, resident)
+
+
+def _names_the_loading_model(loading: str, model_path: str) -> bool:
+ """Whether a client's ``model_path`` names the load already in flight.
+
+ Cancel sends the id the picker shows, which for a pinned row is not the path the load is
+ running as, so a raw compare left Stop loading reporting success on a load still running.
+ """
+ return (
+ model_path == loading
+ or model_path.lower() == loading.lower()
+ or _names_the_resident_model(loading, model_path)
+ )
+
+
+def _resident_standard_model_name(backend, model_path: str) -> str:
+ """The registry name to unload for ``model_path``, or ``model_path`` when nothing matches.
+
+ The backend refuses a name it never loaded, so a pinned load has to be evicted under the
+ name it was registered with rather than the id the client shows.
+ """
+ active = getattr(backend, "active_model_name", None)
+ if isinstance(active, str) and _names_the_resident_model(active, model_path):
+ return active
+ loaded = getattr(backend, "models", None)
+ if isinstance(loaded, dict):
+ for name in loaded:
+ if isinstance(name, str) and _names_the_resident_model(name, model_path):
+ return name
+ return model_path
+
+
def _unload_evicts_standard_backend(backend, model_path: str) -> bool:
"""Whether ``backend.unload_model(model_path)`` will really evict something.
@@ -5547,7 +5587,13 @@ def _unload_evicts_standard_backend(backend, model_path: str) -> bool:
return True
if isinstance(active, str) and active and active.lower() == (model_path or "").lower():
return True
- return isinstance(loaded, dict) and model_path in loaded
+ if isinstance(active, str) and _names_the_resident_model(active, model_path):
+ return True
+ if not isinstance(loaded, dict):
+ return False
+ return model_path in loaded or any(
+ isinstance(name, str) and _names_the_resident_model(name, model_path) for name in loaded
+ )
def _unload_may_evict(model_path: str) -> bool:
@@ -5571,13 +5617,14 @@ def _unload_may_evict(model_path: str) -> bool:
if (
loading is not None
and hasattr(backend, "cancel_load")
- and (model_path == loading or model_path.lower() == loading.lower())
+ and _names_the_loading_model(loading, model_path)
):
return True
llama_backend = get_llama_cpp_backend()
if llama_backend.is_active and (
llama_backend.model_identifier == model_path
or is_registered_native_path_label(llama_backend.model_identifier, model_path)
+ or _names_the_resident_model(llama_backend.model_identifier, model_path)
# Up but not serving is mid-load, evicted whatever model was named.
or not llama_backend.is_loaded
):
@@ -7237,9 +7284,10 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):
if (
loading is not None
and hasattr(backend, "cancel_load")
- and (request.model_path == loading or request.model_path.lower() == loading.lower())
+ and _names_the_loading_model(loading, request.model_path)
):
- if await asyncio.to_thread(backend.cancel_load, request.model_path):
+ # Cancel under the name the load runs as, which a pinned row states as a path.
+ if await asyncio.to_thread(backend.cancel_load, loading):
note_model_unloaded()
logger.info(f"Cancelled in-flight load: {request.model_path}")
return UnloadResponse(status = "unloaded", model = request.model_path)
@@ -7258,6 +7306,7 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):
or is_registered_native_path_label(
llama_backend.model_identifier, request.model_path
)
+ or _names_the_resident_model(llama_backend.model_identifier, request.model_path)
)
):
await asyncio.to_thread(llama_backend.unload_model)
@@ -7301,6 +7350,7 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):
or is_registered_native_path_label(
llama_backend.model_identifier, request.model_path
)
+ or _names_the_resident_model(llama_backend.model_identifier, request.model_path)
or not llama_backend.is_loaded
):
# Read the identity before teardown clears it, so the row reads repo:QUANT.
@@ -7342,7 +7392,9 @@ async def _unload_model_impl(request: UnloadRequest, current_subject: str):
await _drain_and_recancel_before_teardown(
force = request.force_cancel_active, action = "Unloading the model"
)
- await asyncio.to_thread(backend.unload_model, request.model_path)
+ await asyncio.to_thread(
+ backend.unload_model, _resident_standard_model_name(backend, request.model_path)
+ )
note_model_unloaded()
api_monitor.record_lifecycle(
event = "unload",
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 7e0a8a5acaa..51c1bd34061 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -2858,7 +2858,8 @@ async def get_gguf_variants(
local_path = local_path,
hf_token = hf_token,
)
- context_model = (
+ # A pin names the copy that will load; a repo-wide walk can read another revision's length.
+ context_model = hub_gguf_variants.pinned_snapshot_for_request(repo_id, local_path) or (
local_path
if prefer_local_cache and local_path and is_local_path(local_path)
else repo_id
@@ -2918,22 +2919,14 @@ async def get_gguf_download_progress(
def _resolve_hf_cache_realpath(repo_dir: Path) -> Optional[str]:
- """Pick the most useful on-disk path for a HF cache repo.
+ """Most useful on-disk path for a HF cache repo.
- Prefers the most-recent snapshot dir (what ``from_pretrained`` uses),
- falling back to the cache repo root. Returns the resolved realpath so
- snapshot symlinks follow back to blobs/.
+ Delegates to the Hub scanner's function of the same name so this route and
+ ``/api/hub/local-models`` name one directory: the newest snapshot dir, ties broken by
+ ``snapshot_selection_key``.
"""
- try:
- snapshots_dir = repo_dir / "snapshots"
- if snapshots_dir.is_dir():
- snaps = [s for s in snapshots_dir.iterdir() if s.is_dir()]
- if snaps:
- latest = max(snaps, key = lambda s: s.stat().st_mtime)
- return str(latest.resolve())
- return str(repo_dir.resolve())
- except Exception:
- return None
+ from hub.utils import inventory_scan as hf_cache_scan
+ return hf_cache_scan.resolve_hf_cache_realpath(repo_dir)
@router.get("/download-progress")
@@ -3002,9 +2995,57 @@ def _is_mmproj_filename(name: str) -> bool:
def _is_main_gguf_filename(name: str) -> bool:
- """A GGUF file that is a primary weight, not an mmproj vision
- adapter."""
- return _is_gguf_filename(name) and not _is_mmproj_filename(name)
+ """A primary GGUF weight, not an mmproj vision adapter or an MTP drafter. Same rule as
+ ``hub.services.models.common``; pass a snapshot-relative path to catch ``MTP/`` copies too."""
+ return _is_gguf_filename(name) and not _is_mmproj_filename(name) and not _is_mtp_drafter(name)
+
+
+def _recovered_repo_is_unusable_by_repo_id(repo_info) -> bool:
+ """See hub.utils.inventory_scan; False for anything upstream already returns."""
+ from hub.utils.inventory_scan import recovered_repo_is_unusable_by_repo_id as impl
+ return impl(repo_info)
+
+
+def _repo_id_will_not_resolve(repo_cache_dir: Path) -> bool:
+ """See hub.utils.inventory_scan; True only in the dangling refs/main window."""
+ from hub.utils.inventory_scan import repo_id_will_not_resolve as impl
+ return impl(repo_cache_dir)
+
+
+def _default_ref_offers_no_whole_quant(repo_cache_dir: Path) -> bool:
+ """See hub.utils.inventory_scan; True when refs/main resolves onto a torn quant."""
+ from hub.utils.inventory_scan import default_ref_offers_no_whole_quant as impl
+ return impl(repo_cache_dir)
+
+
+def _gguf_copy_is_usable(repo_info, load_id: Optional[str]) -> bool:
+ """Whether this copy of the repo holds a quant a load can reach.
+
+ A pinned copy names a complete snapshot. An unpinned one is usable when its id resolves onto a
+ whole quant, which is exactly what withheld the pin.
+ """
+ if load_id:
+ return True
+ try:
+ repo_path = Path(repo_info.repo_path)
+ return not _repo_id_will_not_resolve(repo_path) and not _default_ref_offers_no_whole_quant(
+ repo_path
+ )
+ except (OSError, RuntimeError, ValueError):
+ return False
+
+
+def _snapshot_has_gguf_projector(snapshot: str) -> bool:
+ """See hub.utils.inventory_scan; reads the same walk the variant lister reports from."""
+ from hub.utils.inventory_scan import snapshot_has_gguf_projector as impl
+ return impl(Path(snapshot))
+
+
+def _cached_repo_file_name(file_obj) -> str:
+ """Snapshot-relative name for a cached file: huggingface_hub records the bare ``file_name``,
+ which cannot tell an ``MTP/`` drafter from a quant."""
+ from hub.services.models.cache_inventory import _cached_repo_file_name as impl
+ return impl(file_obj)
def _main_variant_gguf_label(rel_path: str) -> Optional[str]:
@@ -3031,6 +3072,34 @@ def _repo_has_mmproj(repo_info) -> bool:
)
+def _cached_gguf_row_has_vision(repo_info, load_id: Optional[str]) -> bool:
+ """Whether the copy this row loads ships a projector.
+
+ The loader opens the projector out of the snapshot it loads from, so one in a revision the
+ load never reaches is not vision support. A pinned row is judged on its snapshot, an unpinned
+ one on the first snapshot the load's own ordering finds a quant in. Judged per snapshot, not
+ per file: a split quant can sit in a subdirectory while the projector sits at the root.
+ """
+ if load_id:
+ return _snapshot_has_gguf_projector(load_id)
+ # No projector in any revision means none to reach, and saves a cache walk.
+ if not _repo_has_mmproj(repo_info):
+ return False
+ try:
+ from hub.utils.gguf import iter_snapshots_preferring_whole, list_local_gguf_variants
+
+ # The row describes this copy; a duplicate in another root is one the load never reaches.
+ root = Path(repo_info.repo_path).parent
+ for snapshot in iter_snapshots_preferring_whole(repo_info.repo_id, None, root = root):
+ variants, has_vision = list_local_gguf_variants(str(snapshot))
+ if variants:
+ return bool(has_vision)
+ except Exception:
+ pass
+ # Nothing on disk to load, so the row describes the repo rather than a copy of it.
+ return True
+
+
def _iter_gguf_paths(root: Path):
for path in root.rglob("*"):
if path.is_file() and _is_gguf_filename(path.name):
@@ -3053,13 +3122,15 @@ def _repo_gguf_size_bytes(repo_info) -> int:
for revision in repo_info.revisions:
rev_id = getattr(revision, "commit_hash", None) or str(id(revision))
for f in revision.files:
- if _is_main_gguf_filename(f.file_name):
+ # Snapshot-relative: only the directory tells an MTP/ drafter from a primary quant.
+ name = _cached_repo_file_name(f)
+ if _is_main_gguf_filename(name):
blob_path = getattr(f, "blob_path", None)
size = f.size_on_disk or 0
if blob_path:
unique_blobs[str(blob_path)] = size
else:
- unique_blobs[f"{rev_id}:{f.file_name}"] = size
+ unique_blobs[f"{rev_id}:{name}"] = size
return sum(unique_blobs.values())
@@ -3097,32 +3168,21 @@ def _repo_gguf_last_modified(repo_info) -> float:
latest = 0.0
for revision in repo_info.revisions:
for f in revision.files:
- if _is_main_gguf_filename(f.file_name):
+ if _is_main_gguf_filename(_cached_repo_file_name(f)):
latest = max(latest, _blob_mtime(f))
return latest
def snapshot_variants_all_complete(snapshot: str) -> bool:
- """True when every quant the variant lister would advertise from *snapshot* is
- fully on disk.
-
- One complete quant is not enough: the picker enumerates the whole directory, so a
- half-downloaded split quant sitting beside a good one still gets offered and the
- generated command asks llama-server for shards that are absent. Both sides derive
- their labels from ``extract_quant_label`` over paths relative to the snapshot, so
- the sets are directly comparable.
- """
+ """Re-export; the predicate lives beside the completed-variant walk it uses."""
from hub.utils import inventory_scan
- from hub.utils.gguf import list_local_gguf_variants
+ return inventory_scan.snapshot_variants_all_complete(snapshot)
- try:
- variants, _ = list_local_gguf_variants(snapshot)
- offered = {v.quant for v in variants if getattr(v, "quant", None)}
- if not offered:
- return False
- return offered <= inventory_scan._completed_gguf_variants(Path(snapshot))
- except Exception:
- return False
+
+def snapshot_has_complete_variants(snapshot: str) -> bool:
+ """Re-export of the predicate every load-id pin shares; see above."""
+ from hub.utils import inventory_scan
+ return inventory_scan.snapshot_has_complete_variants(snapshot)
def _repo_gguf_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:
@@ -3130,43 +3190,58 @@ def _repo_gguf_load_id(repo_info, active_root: Optional[Path]) -> Optional[str]:
hub cache that does not resolve by id. ``None`` when the id works or no
snapshot is recorded, since the repo dir itself is not loadable.
"""
+ from hub.utils.hf_cache_state import snapshot_selection_key
+
repo_path = getattr(repo_info, "repo_path", None)
if repo_path is None or active_root is None:
return None
try:
- if repo_path.parent.resolve(strict = False) == active_root:
+ # A recovered repo's refs/main names nothing, so its id resolves nowhere and needs a pin.
+ if (
+ repo_path.parent.resolve(strict = False) == active_root
+ and not _repo_id_will_not_resolve(repo_path)
+ and not _default_ref_offers_no_whole_quant(repo_path)
+ ):
return None
except (OSError, RuntimeError, ValueError):
pass
- # Order by snapshot directory mtime, matching hub.utils.gguf.iter_hf_cache_snapshots,
- # which is what variant discovery reads. Blob mtimes would disagree with it whenever
- # Hugging Face reuses an older blob in a newer snapshot, and the command would then
- # name a snapshot that does not hold the quant the picker offered.
- candidates: List[tuple[float, str]] = []
- for revision in repo_info.revisions:
- snapshot = getattr(revision, "snapshot_path", None)
- if snapshot is None:
- continue
- if not any(_is_main_gguf_filename(f.file_name) for f in revision.files):
- continue
- try:
- mtime = Path(snapshot).stat().st_mtime
- except OSError:
- mtime = 0.0
- candidates.append((mtime, str(snapshot)))
- candidates.sort(key = lambda c: c[0], reverse = True)
- # Newest first, but skip one holding only part of a split quant: an interrupted
- # download would otherwise beat an older snapshot that can still load. Scanning
- # stops at the first usable snapshot, so the usual case walks one directory.
- for _, snapshot in candidates:
- if snapshot_variants_all_complete(snapshot):
- return snapshot
+ # Shared selection key, so this route and the /gguf-variants lister name one snapshot.
+ candidates = [
+ Path(snapshot)
+ for revision in repo_info.revisions
+ if (snapshot := getattr(revision, "snapshot_path", None)) is not None
+ and any(_is_main_gguf_filename(_cached_repo_file_name(f)) for f in revision.files)
+ ]
+ candidates.sort(key = snapshot_selection_key, reverse = True)
+ # Newest first, skipping any holding no whole quant, else a torn download beats a loadable one.
+ for snapshot in candidates:
+ if snapshot_has_complete_variants(str(snapshot)):
+ return str(snapshot)
# Nothing complete anywhere: publishing a half-downloaded snapshot would put that
# path in the copied command and fail on load. Drop the id so the repo id is used,
# which fetches the missing shards instead.
return None
+def _preferred_gguf_copy(
+ rows: dict, ranks: dict, key: str, candidate: tuple[bool, bool], size: int
+) -> bool:
+ """Whether this copy should replace the one already kept for *key*.
+
+ Same order the Hub inventory deduplicates by: a copy that cannot load loses to one that can,
+ whichever cache holds it, then the active cache wins, then the larger download.
+ """
+ existing = rows.get(key)
+ if existing is None:
+ return True
+ kept = ranks.get(key, (True, True))
+ if candidate[0] != kept[0]:
+ return candidate[0]
+ if candidate[1] != kept[1]:
+ return candidate[1]
+ return size > int(existing.get("size_bytes") or 0)
+
+
@router.get("/cached-gguf")
async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
"""List GGUF repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
@@ -3178,6 +3253,8 @@ async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
active_root = None
seen_lower: dict[str, dict] = {}
+ # How each kept row's copy ranks, since the compatibility schema carries neither field.
+ seen_rank: dict[str, tuple[bool, bool]] = {}
for hf_cache in cache_scans:
for repo_info in hf_cache.repos:
try:
@@ -3194,14 +3271,19 @@ async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
key = repo_id.lower()
existing = seen_lower.get(key)
last_modified = _repo_gguf_last_modified(repo_info)
- if existing is None or total_size > existing["size_bytes"]:
+ load_id = _repo_gguf_load_id(repo_info, active_root)
+ rank = (
+ _gguf_copy_is_usable(repo_info, load_id),
+ active_root is not None
+ and Path(repo_info.repo_path).parent.resolve(strict = False) == active_root,
+ )
+ if _preferred_gguf_copy(seen_lower, seen_rank, key, rank, total_size):
row = {
"repo_id": repo_id,
"size_bytes": total_size,
"cache_path": str(repo_info.repo_path),
- "has_vision": _repo_has_mmproj(repo_info),
+ "has_vision": _cached_gguf_row_has_vision(repo_info, load_id),
}
- load_id = _repo_gguf_load_id(repo_info, active_root)
if load_id:
row["load_id"] = load_id
# Keep the newest timestamp across duplicate caches;
@@ -3210,6 +3292,7 @@ async def list_cached_gguf(current_subject: str = Depends(get_current_subject)):
if lm > 0:
row["last_modified"] = lm
seen_lower[key] = row
+ seen_rank[key] = rank
elif last_modified > existing.get("last_modified", 0.0):
existing["last_modified"] = last_modified
except Exception as e:
@@ -3238,8 +3321,14 @@ async def list_cached_models(
try:
cache_scans = _all_hf_cache_scans()
+ try:
+ active_root = _resolve_hf_cache_dir().resolve(strict = False)
+ except Exception:
+ active_root = None
seen_lower: dict[str, dict] = {}
+ # Repos whose active-cache copy cannot be loaded by id; this schema carries no path.
+ unusable_active: set[str] = set()
for hf_cache in cache_scans:
for repo_info in hf_cache.repos:
try:
@@ -3250,6 +3339,18 @@ async def list_cached_models(
# custom Whisper checkpoints, not just curated repo ids.
if _is_hidden_model(repo_id, str(repo_info.repo_path)):
continue
+ # No partial or load id here, so a snapshot-path-only repo would read as ready.
+ if _recovered_repo_is_unusable_by_repo_id(repo_info):
+ try:
+ if (
+ active_root is not None
+ and Path(repo_info.repo_path).parent.resolve(strict = False)
+ == active_root
+ ):
+ unusable_active.add(repo_id.lower())
+ except (OSError, RuntimeError, ValueError):
+ pass
+ continue
if _repo_has_gguf_files(repo_info):
continue
total_size = sum(
@@ -3289,7 +3390,7 @@ async def list_cached_models(
logger.warning(f"Skipping cached model repo {repo_label}: {e}")
continue
- rows = list(seen_lower.values())
+ rows = [row for key, row in seen_lower.items() if key not in unusable_active]
# Local-only list path: update checks are GGUF-only and happen lazily
# when a repo's variants are viewed.
cached = sorted(
diff --git a/studio/backend/tests/test_active_generations.py b/studio/backend/tests/test_active_generations.py
index 2f86f8efdcc..13acf519b34 100644
--- a/studio/backend/tests/test_active_generations.py
+++ b/studio/backend/tests/test_active_generations.py
@@ -563,6 +563,104 @@ def _run_unload(
)
+_PINNED_SNAPSHOT = "/tmp/hf/hub/models--Org--Quant/snapshots/" + "d" * 40
+
+
+def test_unload_finds_a_gguf_loaded_from_a_pinned_snapshot(monkeypatch):
+ """A cached row that pins a snapshot is loaded by that path, while the status the client
+ reads back reports the repo id. An unload naming the id has to reach the same server, or
+ Eject reports success and leaves it resident."""
+ _route_gate()
+ import routes.inference as inf_mod
+
+ torn_down: list[str] = []
+ _run_unload(
+ inf_mod,
+ monkeypatch,
+ loaded_gguf = _PINNED_SNAPSHOT,
+ requested = "Org/Quant",
+ force = False,
+ torn_down = torn_down,
+ )
+ assert torn_down == ["gguf"]
+
+ # Control: another repo's id names a different model and must leave this one up.
+ other: list[str] = []
+ _run_unload(
+ inf_mod,
+ monkeypatch,
+ loaded_gguf = _PINNED_SNAPSHOT,
+ requested = "Org/Other",
+ force = False,
+ torn_down = other,
+ )
+ assert other == ["unsloth"]
+
+
+def test_stop_loading_cancels_an_in_flight_pinned_load(monkeypatch):
+ """Cancel sends the id the picker shows. A pinned row loads under a snapshot path, so a raw
+ compare let Stop loading report success while the multi minute load kept running."""
+ _route_gate()
+ import asyncio
+ from types import SimpleNamespace
+
+ from models.inference import UnloadRequest
+
+ def _cancel(loading, requested):
+ cancelled: list[str] = []
+ inf_mod, _kw = _stub_unload_backends(
+ monkeypatch,
+ llama = SimpleNamespace(is_active = False, is_loaded = False, model_identifier = None),
+ backend = SimpleNamespace(
+ get_loading_model = lambda: loading,
+ cancel_load = lambda path: (cancelled.append(path), True)[1],
+ active_model_name = None,
+ models = {},
+ unload_model = lambda path: None,
+ ),
+ )
+ asyncio.run(
+ inf_mod.unload_model(
+ UnloadRequest(model_path = requested, force_cancel_active = False), "tester"
+ )
+ )
+ return cancelled
+
+ # Cancelled under the name the load runs as, not the one the client sent.
+ assert _cancel(_PINNED_SNAPSHOT, "Org/Quant") == [_PINNED_SNAPSHOT]
+ assert _cancel("Org/Quant", "Org/Quant") == ["Org/Quant"]
+ # Control: naming another repo cancels nothing.
+ assert _cancel(_PINNED_SNAPSHOT, "Org/Other") == []
+
+
+def test_unload_evicts_a_pinned_standard_model_under_its_registered_name(monkeypatch):
+ """The standard backend refuses a name it never loaded, so a pinned load has to be evicted
+ under the path it was registered with rather than the id the picker shows."""
+ _route_gate()
+ import asyncio
+ from types import SimpleNamespace
+
+ from models.inference import UnloadRequest
+
+ unloaded: list[str] = []
+ inf_mod, _kw = _stub_unload_backends(
+ monkeypatch,
+ llama = SimpleNamespace(is_active = False, is_loaded = False, model_identifier = None),
+ backend = SimpleNamespace(
+ get_loading_model = lambda: None,
+ active_model_name = _PINNED_SNAPSHOT,
+ models = {_PINNED_SNAPSHOT: {}},
+ unload_model = lambda path: unloaded.append(path),
+ ),
+ )
+ asyncio.run(
+ inf_mod.unload_model(
+ UnloadRequest(model_path = "Org/Quant", force_cancel_active = False), "tester"
+ )
+ )
+ assert unloaded == [_PINNED_SNAPSHOT]
+
+
def test_forced_unload_of_a_stale_model_path_leaves_the_chats_alone(monkeypatch):
# Eject naming a model another tab swapped out: a no-op success; cancelling first loses runs.
_route_gate()
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 0cb84172fed..05e3efaa2ff 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -7,6 +7,8 @@ import types
from pathlib import Path
from types import SimpleNamespace
+import pytest
+
# Keep this test runnable without optional logging deps.
if "structlog" not in sys.modules:
@@ -206,6 +208,45 @@ def test_list_cached_gguf_reports_snapshot_load_id_for_inactive_cache(monkeypatc
assert "load_id" not in rows["Org/Here"]
+def test_list_cached_gguf_pins_a_snapshot_for_a_recovered_active_cache_repo(monkeypatch, tmp_path):
+ """Being in the active cache normally makes the repo id the load target, but not while refs/main
+ names a commit with no directory: an offline client would follow the dangling ref and fail."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Recovered"
+ snapshot = repo_dir / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("c" * 40, encoding = "utf-8")
+
+ recovered = _repo(
+ "Org/Recovered",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("Model-Q4_K_M.gguf", 256)], snapshot_path = snapshot),
+ ],
+ )
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [recovered])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }
+ assert rows["Org/Recovered"]["load_id"] == str(snapshot)
+
+ # Control: the same repo with a resolving ref keeps the repo id.
+ (repo_dir / "refs" / "main").write_text("a" * 40, encoding = "utf-8")
+ rows = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }
+ assert "load_id" not in rows["Org/Recovered"]
+
+
def test_list_cached_gguf_load_id_follows_snapshot_dir_mtime(monkeypatch, tmp_path):
"""Pick the snapshot variant discovery reads: newest directory, not newest blob."""
import os
@@ -246,6 +287,53 @@ def test_list_cached_gguf_load_id_follows_snapshot_dir_mtime(monkeypatch, tmp_pa
assert rows[0]["load_id"] == str(newer)
[email protected]("reverse", [False, True])
+def test_list_cached_gguf_load_id_breaks_mtime_ties_like_variant_discovery(
+ reverse, monkeypatch, tmp_path
+):
+ """Equal snapshot mtimes must not leave the load id to iteration order.
+
+ ``repo_info.revisions`` is a ``frozenset``, so on a coarse-timestamp filesystem this route
+ published whichever snapshot the hash seed reached first while ``/api/models/gguf-variants``
+ named the one ``snapshot_selection_key`` picks. Both revision orders are driven for that reason.
+ """
+ import os
+
+ from hub.utils.gguf import iter_hf_cache_snapshots
+ from hub.utils.hf_cache_state import snapshot_selection_key
+
+ active = tmp_path / "active"
+ legacy = tmp_path / "legacy"
+ repo_dir = legacy / "models--Org--Tied"
+ low, high = repo_dir / "snapshots" / "rev-a", repo_dir / "snapshots" / "rev-b"
+ for path in (low, high):
+ path.mkdir(parents = True)
+ (low / "Model-Q4_K_M.gguf").write_bytes(b"\0")
+ (high / "Model-Q5_K_M.gguf").write_bytes(b"\0")
+ # One timestamp for both: the tie is the case.
+ for path in (low, high):
+ os.utime(path, (1_700_000_000, 1_700_000_000))
+
+ revisions = [
+ SimpleNamespace(files = [_file("Model-Q4_K_M.gguf", 5_000)], snapshot_path = low),
+ SimpleNamespace(files = [_file("Model-Q5_K_M.gguf", 6_000)], snapshot_path = high),
+ ]
+ repo = _repo("Org/Tied", [], repo_dir, revisions = revisions[::-1] if reverse else revisions)
+
+ monkeypatch.setattr(
+ 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)
+
+ rows = asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+
+ # The shared key's answer, and the directory variant discovery walks first.
+ expected = max((low, high), key = snapshot_selection_key)
+ assert rows[0].get("load_id") == str(expected)
+ assert next(iter(iter_hf_cache_snapshots("Org/Tied"))) == expected
+
+
def test_list_cached_gguf_load_id_skips_partial_split_snapshot(monkeypatch, tmp_path):
"""A half-downloaded split quant must not beat an older snapshot that can load."""
import os
@@ -312,8 +400,9 @@ def test_list_cached_gguf_omits_load_id_when_no_snapshot_is_complete(monkeypatch
assert "load_id" not in rows[0]
-def test_list_cached_gguf_skips_snapshot_with_one_incomplete_variant(monkeypatch, tmp_path):
- """A good quant beside a half-downloaded one is still not a safe load target."""
+def test_list_cached_gguf_load_id_takes_the_snapshot_holding_a_whole_quant(monkeypatch, tmp_path):
+ """One whole quant beside a half-downloaded one is still a safe load target:
+ the lister behind /gguf-variants trims its offer to the completed subset."""
import os
active = tmp_path / "active"
@@ -321,9 +410,8 @@ def test_list_cached_gguf_skips_snapshot_with_one_incomplete_variant(monkeypatch
older, newer = repo_dir / "snapshots" / "rev-a", repo_dir / "snapshots" / "rev-b"
for path in (older, newer):
path.mkdir(parents = True)
- (older / "Model-Q8_0.gguf").write_bytes(b"\0")
- # rev-b has a complete Q8_0 AND a half-downloaded split Q4_K_M. The picker
- # enumerates the whole directory, so it would offer the broken one.
+ (older / "Model-Q4_K_M.gguf").write_bytes(b"\0")
+ # rev-b has a complete Q8_0 AND a half-downloaded split Q4_K_M.
(newer / "Model-Q8_0.gguf").write_bytes(b"\0")
(newer / "Model-Q4_K_M-00001-of-00003.gguf").write_bytes(b"\0")
os.utime(older, (1_000, 1_000))
@@ -334,7 +422,7 @@ def test_list_cached_gguf_skips_snapshot_with_one_incomplete_variant(monkeypatch
[],
repo_dir,
revisions = [
- SimpleNamespace(files = [_file("Model-Q8_0.gguf", 5_000)], snapshot_path = older),
+ SimpleNamespace(files = [_file("Model-Q4_K_M.gguf", 5_000)], snapshot_path = older),
SimpleNamespace(
files = [
_file("Model-Q8_0.gguf", 5_000),
@@ -352,7 +440,688 @@ def test_list_cached_gguf_skips_snapshot_with_one_incomplete_variant(monkeypatch
rows = asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
- assert rows[0]["load_id"] == str(older)
+ assert rows[0].get("load_id") == str(newer)
+ # Every quant that offer advertises is on disk in the snapshot it pinned.
+ from hub.utils.gguf import list_local_gguf_variants
+ from hub.utils.inventory_scan import complete_snapshot_variants
+
+ pinned = rows[0]["load_id"]
+ offered = {v.quant for v in list_local_gguf_variants(pinned)[0] if v.quant}
+ advertised = offered & complete_snapshot_variants(pinned)
+ assert advertised == {"Q8_0"}
+ assert advertised - {v.quant for v in list_local_gguf_variants(str(older))[0] if v.quant}
+
+
+def test_a_zero_byte_first_gguf_leaves_the_quant_incomplete(tmp_path):
+ """The resolver takes the lexicographically first file under a label. Skipping a zero-byte one
+ handed the label to the next file, so the quant read complete while the load opened the empty
+ file it names."""
+ from hub.utils.inventory_scan import complete_snapshot_variants
+ from utils.models.model_config import _find_local_gguf_by_variant
+
+ snapshot = tmp_path / "models--Org--Quant" / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "A-Q4_K_M.gguf").write_bytes(b"")
+ (snapshot / "B-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+
+ assert Path(_find_local_gguf_by_variant(str(snapshot), "Q4_K_M")).name == "A-Q4_K_M.gguf"
+ assert complete_snapshot_variants(str(snapshot)) == set()
+
+ # Control: the same pair with the empty file sorting second, which the resolver never opens.
+ (snapshot / "A-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (snapshot / "B-Q4_K_M.gguf").write_bytes(b"")
+ assert complete_snapshot_variants(str(snapshot)) == {"Q4_K_M"}
+
+
+def test_a_snapshot_scope_from_another_repo_is_not_used(tmp_path):
+ """The response carries the requested repo's identity, so a local_path pointing into a
+ different repo's cache must not become the scope its files are counted in."""
+ other = tmp_path / "models--Org--Other" / "snapshots" / ("a" * 40)
+ mine = tmp_path / "models--Org--Quant" / "snapshots" / ("b" * 40)
+ for path in (other, mine):
+ path.mkdir(parents = True)
+
+ assert GV._snapshot_scope_for_request("Org/Quant", str(other)) is None
+ assert GV._snapshot_scope_for_request("Org/Quant", str(mine)) == mine
+ # Casing follows the cache directory, which need not match the requested id.
+ assert GV._snapshot_scope_for_request("org/quant", str(mine)) == mine
+
+
+ ("files", "expected_default", "expected_ready"),
+ [
+ pytest.param(
+ {"Model-Q8_0.gguf": b"\0" * 256, "Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 256},
+ "Q8_0",
+ {"Q8_0"},
+ id = "the-preferred-quant-is-short-a-shard",
+ ),
+ pytest.param(
+ {"Model-Q8_0.gguf": b"\0" * 256, "Model-Q4_K_M.gguf": b"\0" * 128},
+ "Q4_K_M",
+ {"Q4_K_M", "Q8_0"},
+ id = "both-whole-so-the-usual-preference-stands",
+ ),
+ pytest.param(
+ {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 256},
+ "Q4_K_M",
+ set(),
+ id = "nothing-ready-so-the-default-is-a-download-target",
+ ),
+ ],
+)
+def test_the_local_default_variant_is_one_that_can_load(
+ tmp_path, files, expected_default, expected_ready
+):
+ """The picker re-checks only that default_variant fits in memory, never that it is downloaded,
+ so a quant short a shard gets recommended over a whole one sitting beside it."""
+ snapshot = tmp_path / "models--Org--Model" / "snapshots" / ("a" * 40)
+ snapshot.mkdir(parents = True)
+ for name, blob in files.items():
+ (snapshot / name).write_bytes(blob)
+
+ response = asyncio.run(GV.get_gguf_variants_response(str(snapshot), hf_token = None))
+
+ assert response.default_variant == expected_default
+ assert {v.quant for v in response.variants if v.downloaded} == expected_ready
+
+
+def test_variant_readiness_is_counted_in_the_snapshot_the_row_pinned(monkeypatch, tmp_path):
+ """A pinned row resolves inside one directory. Counting readiness across the repo offered a
+ quant living in a sibling revision, which the pinned load then cannot find."""
+ import os
+
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ pinned, sibling = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (pinned, sibling):
+ path.mkdir(parents = True)
+ (pinned / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (sibling / "Model-Q8_0.gguf").write_bytes(b"\0" * 256)
+ os.utime(pinned, (1_000, 1_000))
+ os.utime(sibling, (2_000, 2_000))
+
+ monkeypatch.setattr(
+ "hub.utils.gguf.iter_hf_cache_snapshots",
+ lambda repo_id, root = None: [sibling, pinned],
+ )
+ monkeypatch.setattr(
+ "hub.services.models.gguf_variants.iter_hf_cache_snapshots",
+ lambda repo_id, root = None: [sibling, pinned],
+ )
+
+ scoped = asyncio.run(
+ GV.get_gguf_variants_response("Org/Quant", prefer_local_cache = True, local_path = str(pinned))
+ )
+ assert {v.quant for v in scoped.variants if v.downloaded} == {"Q4_K_M"}
+
+ # Control: naming the sibling counts that directory instead.
+ other = asyncio.run(
+ GV.get_gguf_variants_response("Org/Quant", prefer_local_cache = True, local_path = str(sibling))
+ )
+ assert {v.quant for v in other.variants if v.downloaded} == {"Q8_0"}
+
+
+def test_a_later_attempts_cancel_marker_does_not_break_the_pinned_quant(monkeypatch, tmp_path):
+ """A marker carries no revision and is rewritten by each attempt, so it belongs to the newest
+ snapshot. The row already attributes it that way; the variants endpoint has to agree, or the
+ one quant the pinned snapshot can load is hidden."""
+ import os
+
+ from hub.utils import download_manifest
+ from hub.utils.gguf import GgufVariantInfo
+
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ pinned, newer = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (pinned, newer):
+ path.mkdir(parents = True)
+ (pinned / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ os.utime(pinned, (1_000, 1_000))
+ os.utime(newer, (2_000, 2_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ # Dangling, so the row pins the older complete snapshot.
+ (repo_dir / "refs" / "main").write_text("c" * 40, encoding = "utf-8")
+
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(
+ hub_cache = active, hf_home = tmp_path, source = "studio", cache_home = 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),
+ )
+ monkeypatch.setattr(
+ GV,
+ "list_gguf_variants",
+ lambda repo_id, hf_token = None: (
+ [
+ GgufVariantInfo(
+ filename = "Model-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ display_label = "Q4_K_M",
+ size_bytes = 256,
+ )
+ ],
+ False,
+ [],
+ ),
+ )
+ assert download_manifest.write_cancel_marker("model", "Org/Quant", "Q4_K_M", hub_cache = active)
+
+ response = asyncio.run(GV.get_gguf_variants_response("Org/Quant", local_path = str(pinned)))
+ assert {v.quant for v in response.variants if v.downloaded} == {"Q4_K_M"}
+ assert not any(v.partial for v in response.variants)
+
+ # Control: with refs/main resolving, the marker describes what a repo-id load reads.
+ (repo_dir / "refs" / "main").write_text("e" * 40, encoding = "utf-8")
+ unpinned = asyncio.run(GV.get_gguf_variants_response("Org/Quant"))
+ assert all(v.partial for v in unpinned.variants)
+
+
+def test_the_pins_excuse_covers_only_the_quants_it_holds(monkeypatch, tmp_path):
+ """The pinned snapshot excuses a revision-less signal because it holds that quant whole. A quant
+ it does not hold is still the cancelled download the marker describes, and hiding that leaves it
+ listed as a plain undownloaded row with nothing to resume or delete."""
+ import os
+
+ from hub.utils import download_manifest
+ from hub.utils.gguf import GgufVariantInfo
+
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ pinned, newer = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (pinned, newer):
+ path.mkdir(parents = True)
+ (pinned / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (newer / "Model-Q8_0-00001-of-00002.gguf").write_bytes(b"\0" * 16)
+ os.utime(pinned, (1_000, 1_000))
+ os.utime(newer, (2_000, 2_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("e" * 40, encoding = "utf-8")
+
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(
+ hub_cache = active, hf_home = tmp_path, source = "studio", cache_home = 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),
+ )
+ monkeypatch.setattr(
+ GV,
+ "list_gguf_variants",
+ lambda repo_id, hf_token = None: (
+ [
+ GgufVariantInfo(filename = "Model-Q4_K_M.gguf", quant = "Q4_K_M", size_bytes = 256),
+ GgufVariantInfo(filename = "Model-Q8_0.gguf", quant = "Q8_0", size_bytes = 512),
+ ],
+ False,
+ [],
+ ),
+ )
+ assert download_manifest.write_cancel_marker("model", "Org/Quant", "Q8_0", hub_cache = active)
+
+ response = asyncio.run(GV.get_gguf_variants_response("Org/Quant", local_path = str(pinned)))
+ by_quant = {v.quant: v for v in response.variants}
+ assert by_quant["Q4_K_M"].downloaded is True and by_quant["Q4_K_M"].partial is False
+ assert by_quant["Q8_0"].partial is True
+
+
+def test_a_later_attempts_incomplete_blob_does_not_break_the_pinned_quant(monkeypatch, tmp_path):
+ """blobs/ is repo-wide and each attempt rewrites it, so a retry's .incomplete belongs to the
+ newest snapshot exactly as a cancel marker does. Judging the pinned quant by it hid the one
+ copy that loads."""
+ import os
+
+ from hub.utils import download_registry
+ from hub.utils.download_manifest import ExpectedFile
+ from hub.utils.gguf import GgufVariantInfo
+ from hub.utils.gguf_plan import plan_from_expected_files
+
+ sha = "f" * 64
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ pinned, newer = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (pinned, newer):
+ path.mkdir(parents = True)
+ (pinned / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (newer / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 16)
+ os.utime(pinned, (1_000, 1_000))
+ os.utime(newer, (2_000, 2_000))
+ (repo_dir / "blobs").mkdir(parents = True)
+ (repo_dir / "blobs" / f"{sha}.incomplete").write_bytes(b"\0" * 8)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("e" * 40, encoding = "utf-8")
+
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(
+ hub_cache = active, hf_home = tmp_path, source = "studio", cache_home = 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),
+ )
+ variant = GgufVariantInfo(
+ filename = "Model-Q4_K_M.gguf",
+ quant = "Q4_K_M",
+ display_label = "Q4_K_M",
+ size_bytes = 256,
+ )
+ monkeypatch.setattr(
+ GV, "list_gguf_variants", lambda repo_id, hf_token = None: ([variant], False, [])
+ )
+ monkeypatch.setattr(
+ GV,
+ "_gguf_all_variant_requirements",
+ lambda repo_id, hf_token, siblings = None: {
+ "q4_k_m": plan_from_expected_files(
+ "Q4_K_M", [ExpectedFile(path = "Model-Q4_K_M.gguf", size = 256, sha256 = sha)]
+ )
+ },
+ )
+ monkeypatch.setattr(GV, "_variant_requirement_cache_get", lambda key: None)
+ monkeypatch.setattr(download_registry, "incomplete_blob_hashes", lambda *a, **kw: {sha})
+
+ response = asyncio.run(GV.get_gguf_variants_response("Org/Quant", local_path = str(pinned)))
+ assert {v.quant for v in response.variants if v.downloaded} == {"Q4_K_M"}
+ assert not any(v.partial for v in response.variants)
+
+ # Controls: unpinned, and pinned to the snapshot the blob does belong to.
+ for target in (None, str(newer)):
+ other = asyncio.run(
+ GV.get_gguf_variants_response(
+ "Org/Quant", **({} if target is None else {"local_path": target})
+ )
+ )
+ assert all(v.partial for v in other.variants)
+
+
+def test_a_copy_that_loads_beats_a_bigger_one_that_does_not(monkeypatch, tmp_path):
+ """Two caches holding one repo are two directories, and only one of them loads. Keeping the
+ larger download put an unusable copy on the row while a whole one sat in the other cache."""
+ active, legacy = tmp_path / "active", tmp_path / "legacy"
+ torn = active / "models--Org--Quant" / "snapshots" / ("d" * 40)
+ whole = legacy / "models--Org--Quant" / "snapshots" / ("e" * 40)
+ for path in (torn, whole):
+ path.mkdir(parents = True)
+ # Bigger, and half a split: size alone would keep this one.
+ (torn / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 4096)
+ for shard in ("00001", "00002"):
+ (whole / f"Model-Q4_K_M-{shard}-of-00002.gguf").write_bytes(b"\0" * 256)
+ for repo_dir, ref in ((torn.parent.parent, "c" * 40), (whole.parent.parent, "e" * 40)):
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text(ref, encoding = "utf-8")
+
+ def _repo_for(snapshot, size, repo_dir):
+ return _repo(
+ "Org/Quant",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file(f.name, size) for f in sorted(snapshot.iterdir())],
+ snapshot_path = snapshot,
+ )
+ ],
+ )
+
+ monkeypatch.setattr(
+ models_route,
+ "_all_hf_cache_scans",
+ lambda: [
+ SimpleNamespace(repos = [_repo_for(torn, 4096, torn.parent.parent)]),
+ SimpleNamespace(repos = [_repo_for(whole, 256, whole.parent.parent)]),
+ ],
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ row = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }["Org/Quant"]
+ assert row["cache_path"] == str(whole.parent.parent)
+ assert row["load_id"] == str(whole)
+
+
+def test_list_cached_gguf_pins_a_snapshot_when_the_default_ref_quant_is_torn(monkeypatch, tmp_path):
+ """The repo id resolving is not enough: refs/main can land on a revision holding half a split
+ while an older one is whole. The compat schema carries no partial flag, so a client loading the
+ id follows the torn ref and fails with a complete copy one directory away."""
+ import os
+
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ older, newer = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (older, newer):
+ path.mkdir(parents = True)
+ for shard in ("00001", "00002"):
+ (older / f"Model-Q4_K_M-{shard}-of-00002.gguf").write_bytes(b"\0" * 256)
+ (newer / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 256)
+ os.utime(older, (1_000, 1_000))
+ os.utime(newer, (2_000, 2_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("e" * 40, encoding = "utf-8")
+
+ repo = _repo(
+ "Org/Quant",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file("Model-Q4_K_M-00001-of-00002.gguf", 256)], snapshot_path = newer
+ ),
+ SimpleNamespace(
+ files = [
+ _file("Model-Q4_K_M-00001-of-00002.gguf", 256),
+ _file("Model-Q4_K_M-00002-of-00002.gguf", 256),
+ ],
+ snapshot_path = older,
+ ),
+ ],
+ )
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ rows = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }
+ assert rows["Org/Quant"]["load_id"] == str(older)
+
+ # Control: point the ref at the whole copy and the repo id is what loads again.
+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")
+ rows = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }
+ assert "load_id" not in rows["Org/Quant"]
+
+
+def test_vision_is_read_from_the_snapshot_the_row_pins(monkeypatch, tmp_path):
+ """A projector in a revision the row does not point at is one the loader never opens, so
+ advertising vision off it offers a capability the pinned copy cannot deliver."""
+ import os
+
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Vision"
+ older, newer = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (older, newer):
+ path.mkdir(parents = True)
+ for shard in ("00001", "00002"):
+ (older / f"Model-Q4_K_M-{shard}-of-00002.gguf").write_bytes(b"\0" * 256)
+ (newer / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 256)
+ (newer / "mmproj-F16.gguf").write_bytes(b"\0" * 256)
+ os.utime(older, (1_000, 1_000))
+ os.utime(newer, (2_000, 2_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("e" * 40, encoding = "utf-8")
+
+ repo = _repo(
+ "Org/Vision",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [
+ _file("Model-Q4_K_M-00001-of-00002.gguf", 256),
+ _file("mmproj-F16.gguf", 256),
+ ],
+ snapshot_path = newer,
+ ),
+ SimpleNamespace(
+ files = [
+ _file("Model-Q4_K_M-00001-of-00002.gguf", 256),
+ _file("Model-Q4_K_M-00002-of-00002.gguf", 256),
+ ],
+ snapshot_path = older,
+ ),
+ ],
+ )
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+
+ def _row():
+ return {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))[
+ "cached"
+ ]
+ }["Org/Vision"]
+
+ row = _row()
+ assert row["load_id"] == str(older)
+ assert row["has_vision"] is False
+
+ # Control: put a projector beside the copy that loads and the capability is real again.
+ (older / "mmproj-F16.gguf").write_bytes(b"\0" * 256)
+ repo.revisions[1].files = list(repo.revisions[1].files) + [_file("mmproj-F16.gguf", 256)]
+ row = _row()
+ assert row["load_id"] == str(older)
+ assert row["has_vision"] is True
+
+
+def test_vision_is_read_from_the_snapshot_a_repo_id_load_resolves(monkeypatch, tmp_path):
+ """A row that pins nothing still loads from one snapshot, the one the resolver returns. A
+ projector in a revision that resolution never reaches is not vision support either."""
+ import os
+
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Vision"
+ main, other = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (main, other):
+ path.mkdir(parents = True)
+ for shard in ("00001", "00002"):
+ (main / f"Model-Q4_K_M-{shard}-of-00002.gguf").write_bytes(b"\0" * 256)
+ # Newest, and holds only the projector: nothing here for a load to land on.
+ (other / "mmproj-F16.gguf").write_bytes(b"\0" * 256)
+ os.utime(main, (1_000, 1_000))
+ os.utime(other, (2_000, 2_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")
+
+ repo = _repo(
+ "Org/Vision",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(files = [_file("mmproj-F16.gguf", 256)], snapshot_path = other),
+ SimpleNamespace(
+ files = [
+ _file("Model-Q4_K_M-00001-of-00002.gguf", 256),
+ _file("Model-Q4_K_M-00002-of-00002.gguf", 256),
+ ],
+ snapshot_path = main,
+ ),
+ ],
+ )
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+ monkeypatch.setattr(
+ "hub.utils.gguf.iter_hf_cache_snapshots", lambda repo_id, root = None: [other, main]
+ )
+
+ def _row():
+ return {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))[
+ "cached"
+ ]
+ }["Org/Vision"]
+
+ row = _row()
+ assert "load_id" not in row
+ assert row["has_vision"] is False
+
+ # Control: the projector beside the quant that resolves is reachable.
+ (main / "mmproj-F16.gguf").write_bytes(b"\0" * 256)
+ row = _row()
+ assert row["has_vision"] is True
+
+
+def test_a_projector_at_the_snapshot_root_serves_a_quant_in_a_subdirectory(monkeypatch, tmp_path):
+ """Split quants live in a per quant subdirectory while the projector stays at the snapshot
+ root, so vision has to be judged on the snapshot rather than on the file's own directory."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Nested"
+ snapshot = repo_dir / "snapshots" / ("d" * 40)
+ (snapshot / "UD-Q4_K_XL").mkdir(parents = True)
+ for shard in ("00001", "00002"):
+ (snapshot / "UD-Q4_K_XL" / f"Model-UD-Q4_K_XL-{shard}-of-00002.gguf").write_bytes(
+ b"\0" * 256
+ )
+ (snapshot / "mmproj-F16.gguf").write_bytes(b"\0" * 256)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")
+
+ repo = _repo(
+ "Org/Nested",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [
+ _file("Model-UD-Q4_K_XL-00001-of-00002.gguf", 256),
+ _file("Model-UD-Q4_K_XL-00002-of-00002.gguf", 256),
+ _file("mmproj-F16.gguf", 256),
+ ],
+ snapshot_path = snapshot,
+ )
+ ],
+ )
+ monkeypatch.setattr(
+ models_route, "_all_hf_cache_scans", lambda: [SimpleNamespace(repos = [repo])]
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+ monkeypatch.setattr(
+ "hub.utils.gguf.iter_hf_cache_snapshots", lambda repo_id, root = None: [snapshot]
+ )
+
+ row = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }["Org/Nested"]
+ assert "load_id" not in row
+ assert row["has_vision"] is True
+
+
+def test_vision_is_read_from_the_cache_root_holding_the_row(monkeypatch, tmp_path):
+ """The same repo can sit in several cache roots, and the row describes one copy: a duplicate
+ elsewhere is a download the load never reaches, so it cannot answer for this row's projector."""
+ import os
+
+ active = tmp_path / "active"
+ legacy = tmp_path / "legacy"
+ repo_dir = active / "models--Org--Split"
+ here = repo_dir / "snapshots" / ("a" * 40)
+ there = legacy / "models--Org--Split" / "snapshots" / ("b" * 40)
+ here.mkdir(parents = True)
+ there.mkdir(parents = True)
+ for name in ("Model-Q4_K_M.gguf", "mmproj-F16.gguf"):
+ (here / name).write_bytes(b"\0" * 256)
+ (there / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ os.utime(here, (1_000, 1_000))
+ os.utime(there, (2_000, 2_000))
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("a" * 40, encoding = "utf-8")
+
+ repo = _repo(
+ "Org/Split",
+ [],
+ repo_dir,
+ revisions = [
+ SimpleNamespace(
+ files = [_file("Model-Q4_K_M.gguf", 256), _file("mmproj-F16.gguf", 256)],
+ snapshot_path = here,
+ )
+ ],
+ )
+ monkeypatch.setattr(
+ 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])
+
+ row = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }["Org/Split"]
+ assert row["has_vision"] is True
+
+
+def test_vision_is_not_invented_for_a_copy_that_ships_no_projector(monkeypatch, tmp_path):
+ """Control for the test above: scoping the lookup must not turn every row vision capable."""
+ active = tmp_path / "active"
+ legacy = tmp_path / "legacy"
+ repo_dir = active / "models--Org--Plain"
+ here = repo_dir / "snapshots" / ("a" * 40)
+ there = legacy / "models--Org--Plain" / "snapshots" / ("b" * 40)
+ here.mkdir(parents = True)
+ there.mkdir(parents = True)
+ (here / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ for name in ("Model-Q4_K_M.gguf", "mmproj-F16.gguf"):
+ (there / name).write_bytes(b"\0" * 256)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("a" * 40, encoding = "utf-8")
+
+ repo = _repo(
+ "Org/Plain",
+ [],
+ repo_dir,
+ revisions = [SimpleNamespace(files = [_file("Model-Q4_K_M.gguf", 256)], snapshot_path = here)],
+ )
+ monkeypatch.setattr(
+ 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])
+
+ row = {
+ c["repo_id"]: c
+ for c in asyncio.run(models_route.list_cached_gguf(current_subject = "test-user"))["cached"]
+ }["Org/Plain"]
+ assert row["has_vision"] is False
+
+
+def test_metadata_resolves_from_the_snapshot_holding_the_whole_quant(monkeypatch, tmp_path):
+ """The lister and the load take the whole copy, so mtime order alone would read metadata out of
+ a newer half download nothing loads."""
+ import os
+
+ from hub.utils.gguf import iter_snapshots_preferring_whole
+
+ repo_dir = tmp_path / "models--Org--Quant"
+ older, newer = repo_dir / "snapshots" / ("d" * 40), repo_dir / "snapshots" / ("e" * 40)
+ for path in (older, newer):
+ path.mkdir(parents = True)
+ for shard in ("00001", "00002"):
+ (older / f"Model-Q4_K_M-{shard}-of-00002.gguf").write_bytes(b"\0" * 256)
+ (newer / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 256)
+ os.utime(older, (1_000, 1_000))
+ os.utime(newer, (2_000, 2_000))
+
+ monkeypatch.setattr(
+ "hub.utils.gguf.iter_hf_cache_snapshots", lambda repo_id, root = None: [newer, older]
+ )
+
+ assert iter_snapshots_preferring_whole("Org/Quant", "Q4_K_M") == [older, newer]
+ # No variant to judge, so mtime order stands.
+ assert iter_snapshots_preferring_whole("Org/Quant", None) == [newer, older]
def test_list_cached_gguf_includes_non_suffix_repo_when_cache_contains_gguf(monkeypatch, tmp_path):
@@ -1091,6 +1860,66 @@ def test_gguf_variants_route_scopes_local_probe_to_selected_cache(monkeypatch, t
assert result.context_length == 8192
+def test_gguf_variants_route_reads_context_from_the_pinned_snapshot(monkeypatch, tmp_path):
+ """Enumeration may be repo wide, but the native context must come from the pinned snapshot
+ or the dialog offers a length the model cannot serve."""
+ snapshot = tmp_path / "active" / "models--org--repo" / "snapshots" / "rev"
+ snapshot.mkdir(parents = True)
+
+ async def scoped_variants(repo_id, **kwargs):
+ return SimpleNamespace(repo_id = repo_id, variants = [], has_vision = False, default_variant = None)
+
+ context_calls = []
+ monkeypatch.setattr(GV, "get_gguf_variants_response", scoped_variants)
+ monkeypatch.setattr(
+ models_route,
+ "_read_native_context_length",
+ lambda model, *, is_local: context_calls.append((model, is_local)) or 4096,
+ )
+
+ asyncio.run(
+ models_route.get_gguf_variants(
+ repo_id = "org/repo",
+ prefer_local_cache = False,
+ local_path = str(snapshot),
+ hf_token = None,
+ current_subject = "test-user",
+ )
+ )
+
+ assert context_calls == [(str(snapshot.resolve()), True)]
+
+
+def test_gguf_variants_route_ignores_a_pin_naming_another_repo(monkeypatch, tmp_path):
+ """Control: a pin naming another repo falls back to the repo id rather than reporting a
+ stranger's metadata."""
+ other = tmp_path / "active" / "models--org--other" / "snapshots" / "rev"
+ other.mkdir(parents = True)
+
+ async def scoped_variants(repo_id, **kwargs):
+ return SimpleNamespace(repo_id = repo_id, variants = [], has_vision = False, default_variant = None)
+
+ context_calls = []
+ monkeypatch.setattr(GV, "get_gguf_variants_response", scoped_variants)
+ monkeypatch.setattr(
+ models_route,
+ "_read_native_context_length",
+ lambda model, *, is_local: context_calls.append((model, is_local)) or 4096,
+ )
+
+ asyncio.run(
+ models_route.get_gguf_variants(
+ repo_id = "org/repo",
+ prefer_local_cache = False,
+ local_path = str(other),
+ hf_token = None,
+ current_subject = "test-user",
+ )
+ )
+
+ assert context_calls == [("org/repo", False)]
+
+
def test_gguf_variants_ignore_big_endian_siblings(monkeypatch, tmp_path):
siblings = [
SimpleNamespace(rfilename = "model-Q4_K_M-be.gguf", size = 100),
diff --git a/studio/backend/tests/test_detect_mmproj_file.py b/studio/backend/tests/test_detect_mmproj_file.py
index 64dd8ebd90e..5cda0362789 100644
--- a/studio/backend/tests/test_detect_mmproj_file.py
+++ b/studio/backend/tests/test_detect_mmproj_file.py
@@ -35,8 +35,10 @@ def _gguf_with_general(path: Path, fields: dict) -> Path:
def _touch(path: Path) -> Path:
+ """A headerless GGUF: selection falls to the filename, but non-empty since zero bytes now
+ means an interrupted download."""
path.parent.mkdir(parents = True, exist_ok = True)
- path.write_bytes(b"")
+ path.write_bytes(b"\0" * 32)
return path
@@ -319,3 +321,22 @@ def test_metadata_score_outranks_filename_prefix(tmp_path: Path):
},
)
assert detect_mmproj_file(str(weight)) == str(correct.resolve())
+
+
+def test_a_zero_byte_projector_is_not_offered_to_the_loader(tmp_path: Path):
+ """llama-server cannot open an interrupted download, and the inventory already reports such
+ a row text-only, so handing the path over would fail the whole load."""
+ weight = _touch(tmp_path / "Model-Q4_K_M.gguf")
+ (tmp_path / "mmproj-F16.gguf").write_bytes(b"")
+
+ assert detect_mmproj_file(str(weight)) is None
+ assert detect_mmproj_file(str(tmp_path)) is None
+
+
+def test_a_zero_byte_projector_does_not_shadow_a_whole_one(tmp_path: Path):
+ """Control: only the empty one is skipped, so a projector beside it is still found."""
+ weight = _touch(tmp_path / "Model-Q4_K_M.gguf")
+ (tmp_path / "mmproj-F16.gguf").write_bytes(b"")
+ whole = _touch(tmp_path / "mmproj-Q8_0.gguf")
+
+ assert detect_mmproj_file(str(weight)) == str(whole.resolve())
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
new file mode 100644
index 00000000000..d3957409f3f
--- /dev/null
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -0,0 +1,3968 @@
+# 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 dangling ``refs/<branch>`` must not hide an intact repo from the scan.
+
+``scan_cache_dir`` raises CorruptedCacheException for a repo whose ref names a commit with no
+``snapshots/<commit>/`` directory and omits it from ``.repos``, so the model stays visible in the
+picker (a plain directory walk) but vanishes from every Hub inventory endpoint chat auto-load reads.
+The repair is read-only: refs are written with an unlocked in-place ``write_text``, so no external
+process can delete one race-free.
+"""
+
+from __future__ import annotations
+
+import dataclasses
+import json
+import os
+import stat
+import tracemalloc
+from pathlib import Path
+
+import pytest
+
+from hub.utils import inventory_scan
+
+SNAPSHOT = "a" * 40
+UPSTREAM_HEAD = "b" * 40
+
+
+def _build_repo(
+ cache_root: Path,
+ *,
+ ref: str | None = UPSTREAM_HEAD,
+ extra_refs: dict[str, str] | None = None,
+ name: str = "models--Org--Model",
+ payload: bytes = b"\0" * 11,
+ snapshots: tuple[str, ...] = (SNAPSHOT,),
+) -> Path:
+ """A cache repo shaped like HF's, using regular files rather than symlinks: a regular file
+ resolves to itself, so the real scanner runs without the Windows symlink privilege."""
+ repo_dir = cache_root / name
+ refs = repo_dir / "refs"
+ refs.mkdir(parents = True, exist_ok = True)
+ (repo_dir / "blobs").mkdir(parents = True, exist_ok = True)
+ for commit in snapshots:
+ snapshot = repo_dir / "snapshots" / commit
+ snapshot.mkdir(parents = True, exist_ok = True)
+ (snapshot / "model.safetensors").write_bytes(payload)
+ if ref is not None:
+ (refs / "main").write_text(ref, encoding = "utf-8")
+ for ref_name, commit in (extra_refs or {}).items():
+ (refs / ref_name).write_text(commit, encoding = "utf-8")
+ return repo_dir
+
+
+def _ref_names(repo_dir: Path) -> list[str]:
+ return sorted(entry.name for entry in (repo_dir / "refs").rglob("*") if entry.is_file())
+
+
+def _scan(cache_root: Path, monkeypatch) -> list:
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [cache_root])
+ return inventory_scan._compute_all_hf_cache_scans()
+
+
+def _scanned_repo_ids(cache_root: Path, monkeypatch) -> list[str]:
+ return sorted(repo.repo_id for scan in _scan(cache_root, monkeypatch) for repo in scan.repos)
+
+
+def _only_repo(cache_root: Path, monkeypatch):
+ repos = [repo for scan in _scan(cache_root, monkeypatch) for repo in scan.repos]
+ assert [repo.repo_id for repo in repos] == ["Org/Model"], "repo hidden from the scan"
+ return repos[0]
+
+
+def _empty_cache_info(cls):
+ """An empty ``HFCacheInfo``: fields are read off the dataclass rather than named, so a release
+ adding or dropping one cannot fail this test on a signature it never exercises."""
+ known = {"size_on_disk": 0, "repos": frozenset(), "warnings": []}
+ return cls(**{f.name: known.get(f.name, frozenset()) for f in dataclasses.fields(cls)})
+
+
+# --- the #7374 symptom -------------------------------------------------------
+
+
+def test_huggingface_hub_really_hides_a_repo_behind_a_dangling_ref(tmp_path):
+ """Baseline for the bug: the snapshot is intact, yet the repo is dropped."""
+ from huggingface_hub import scan_cache_dir
+
+ repo_dir = _build_repo(tmp_path)
+
+ raw = scan_cache_dir(cache_dir = str(tmp_path))
+
+ assert [repo.repo_id for repo in raw.repos] == []
+ assert raw.warnings
+ assert (repo_dir / "snapshots" / SNAPSHOT / "model.safetensors").is_file()
+
+
+def test_dangling_ref_no_longer_hides_an_intact_repo(tmp_path, monkeypatch):
+ repo_dir = _build_repo(tmp_path)
+
+ repo = _only_repo(tmp_path, monkeypatch)
+
+ assert repo.repo_id == "Org/Model"
+ assert repo.repo_type == "model"
+ # routes/models.py does repo_path.parent, so this stays a real Path.
+ assert isinstance(repo.repo_path, Path) and repo.repo_path == repo_dir
+ assert repo.size_on_disk == 11
+ # The recovered revision keeps the identity the snapshot is loadable by.
+ revision = next(iter(repo.revisions))
+ assert revision.commit_hash == SNAPSHOT
+ assert revision.snapshot_path == repo_dir / "snapshots" / SNAPSHOT
+ assert {f.file_name for f in revision.files} == {"model.safetensors"}
+ # The dangling ref maps to no revision...
+ assert revision.refs == frozenset()
+ # ...and is still on disk: the repair never writes to the cache.
+ assert _ref_names(repo_dir) == ["main"]
+ assert (repo_dir / "refs" / "main").read_text(encoding = "utf-8") == UPSTREAM_HEAD
+
+
+def test_recovery_reads_a_multi_file_multi_revision_repo(tmp_path, monkeypatch):
+ other = "c" * 40
+ repo_dir = _build_repo(tmp_path, snapshots = (SNAPSHOT, other))
+ (repo_dir / "snapshots" / SNAPSHOT / "nested").mkdir()
+ (repo_dir / "snapshots" / SNAPSHOT / "nested" / "extra.json").write_bytes(b"{}")
+
+ repo = _only_repo(tmp_path, monkeypatch)
+
+ assert {rev.commit_hash for rev in repo.revisions} == {SNAPSHOT, other}
+ files = {f.file_path for rev in repo.revisions for f in rev.files}
+ assert repo_dir / "snapshots" / SNAPSHOT / "nested" / "extra.json" in files
+ # _resolve_cached_model_path relativises file_path against snapshot_path.
+ for rev in repo.revisions:
+ for f in rev.files:
+ assert f.file_path.relative_to(rev.snapshot_path)
+
+
+def test_a_still_resolvable_ref_keeps_its_revision_mapping(tmp_path, monkeypatch):
+ """One good ref plus one stale ref: hub drops the repo, we keep the mapping."""
+ repo_dir = _build_repo(tmp_path, ref = SNAPSHOT, extra_refs = {"stale": UPSTREAM_HEAD})
+
+ repo = _only_repo(tmp_path, monkeypatch)
+
+ assert next(iter(repo.revisions)).refs == frozenset({"main"})
+ assert _ref_names(repo_dir) == ["main", "stale"]
+
+
+# --- the repair must not widen past the leftover-refs assertion --------------
+
+
+def test_a_healthy_cache_is_returned_untouched(tmp_path, monkeypatch):
+ import huggingface_hub
+
+ repo_dir = _build_repo(tmp_path, ref = SNAPSHOT, extra_refs = {"v1.0": SNAPSHOT})
+ calls: list[str] = []
+ real_scan = huggingface_hub.scan_cache_dir
+
+ def counting_scan(cache_dir = None):
+ calls.append(str(cache_dir))
+ return real_scan(cache_dir = cache_dir)
+
+ monkeypatch.setattr(huggingface_hub, "scan_cache_dir", counting_scan)
+
+ assert _scanned_repo_ids(tmp_path, monkeypatch) == ["Org/Model"]
+ assert len(calls) == 1
+ assert _ref_names(repo_dir) == ["main", "v1.0"]
+
+
+def test_a_download_that_has_only_written_its_ref_is_not_invented(tmp_path, monkeypatch):
+ """snapshot_download writes refs/<revision> before fetching the first file, so there is no
+ snapshot to recover yet and nothing may be reported as downloaded."""
+ repo_dir = tmp_path / "models--Org--Model"
+ (repo_dir / "snapshots").mkdir(parents = True)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text(UPSTREAM_HEAD, encoding = "utf-8")
+
+ assert _scanned_repo_ids(tmp_path, monkeypatch) == []
+ assert _ref_names(repo_dir) == ["main"]
+
+
+def test_a_repo_corrupted_beyond_a_dangling_ref_stays_omitted(tmp_path, monkeypatch):
+ """A broken snapshot symlink is corruption hub rejects for its own reasons."""
+ repo_dir = _build_repo(tmp_path)
+ broken = repo_dir / "snapshots" / SNAPSHOT / "weights.bin"
+ try:
+ os.symlink(repo_dir / "blobs" / "missing", broken)
+ except (NotImplementedError, OSError):
+ pytest.skip("symlinks unavailable (Windows without developer mode)")
+
+ assert _scanned_repo_ids(tmp_path, monkeypatch) == []
+
+
+def test_an_unrelated_repo_is_never_disturbed(tmp_path, monkeypatch):
+ hidden = _build_repo(tmp_path)
+ healthy = _build_repo(tmp_path, ref = SNAPSHOT, name = "models--Org--Healthy")
+
+ assert _scanned_repo_ids(tmp_path, monkeypatch) == ["Org/Healthy", "Org/Model"]
+ assert _ref_names(hidden) == ["main"]
+ assert _ref_names(healthy) == ["main"]
+
+
+def test_an_unreadable_repo_does_not_abort_the_recovery(tmp_path):
+ """One unreadable repo must not stop the others being recovered. Scoped to the recovery pass:
+ scan_cache_dir itself raises on an unreadable repo dir, upstream of this code."""
+ from huggingface_hub import HFCacheInfo
+
+ hidden = _build_repo(tmp_path)
+ locked = _build_repo(tmp_path, ref = SNAPSHOT, name = "models--Org--Locked")
+ locked.chmod(0)
+ if os.access(locked / "refs", os.R_OK):
+ pytest.skip("filesystem does not enforce directory permissions")
+ try:
+ scan = _empty_cache_info(HFCacheInfo)
+ merged = inventory_scan._with_repos_hidden_by_dangling_refs(scan, tmp_path)
+ assert sorted(repo.repo_id for repo in merged.repos) == ["Org/Model"]
+ assert _ref_names(hidden) == ["main"]
+ finally:
+ locked.chmod(stat.S_IRWXU)
+
+
+def test_a_non_repo_directory_is_ignored(tmp_path, monkeypatch):
+ _build_repo(tmp_path)
+ (tmp_path / ".locks").mkdir()
+ (tmp_path / "notarepo").mkdir()
+ (tmp_path / "spaces--Org--Thing").mkdir()
+
+ assert _scanned_repo_ids(tmp_path, monkeypatch) == ["Org/Model"]
+
+
+def test_a_scan_object_without_warnings_still_reaches_the_caller(tmp_path, monkeypatch):
+ """The gate must read .warnings defensively: an AttributeError here lands in the per-root
+ ``except Exception`` and silently blanks the whole cache."""
+ from types import SimpleNamespace
+
+ import huggingface_hub
+
+ monkeypatch.setattr(
+ huggingface_hub,
+ "scan_cache_dir",
+ lambda cache_dir = None: SimpleNamespace(cache_dir = cache_dir),
+ )
+
+ assert len(_scan(tmp_path, monkeypatch)) == 1
+
+
+# --- version robustness ------------------------------------------------------
+
+
+def test_recovered_entries_match_the_huggingface_hub_field_surface():
+ """The recovered entries are duck-typed rather than built with hub's own constructors; this is
+ the tripwire for upstream field drift."""
+ from huggingface_hub import CachedFileInfo, CachedRepoInfo, CachedRevisionInfo
+
+ pairs = (
+ (inventory_scan._RecoveredFileInfo, CachedFileInfo),
+ (inventory_scan._RecoveredRevisionInfo, CachedRevisionInfo),
+ (inventory_scan._RecoveredRepoInfo, CachedRepoInfo),
+ )
+ for ours, theirs in pairs:
+ missing = {f.name for f in dataclasses.fields(theirs)} - {
+ f.name for f in dataclasses.fields(ours)
+ }
+ assert not missing, f"{ours.__name__} is missing {sorted(missing)}"
+
+
+def test_a_recovered_repo_survives_delete_revisions(tmp_path, monkeypatch):
+ """Deleting a recovered model routes through HFCacheInfo.delete_revisions, which keys a dict by
+ repo and takes a set difference over .revisions."""
+ repo_dir = _build_repo(tmp_path)
+ scan = _scan(tmp_path, monkeypatch)[0]
+
+ strategy = scan.delete_revisions(SNAPSHOT)
+
+ assert strategy.repos == frozenset({repo_dir})
+ assert strategy.expected_freed_size == 11
+
+
+# --- load identity for a recovered snapshot ----------------------------------
+
+
+def _autoload_rows(
+ cache_root: Path,
+ monkeypatch,
+ *,
+ gguf: bool = False,
+) -> list[dict]:
+ """What chat auto-load sees: GET /api/hub/cached-models, or /cached-gguf with *gguf* set."""
+ from hub.services.models import cache_inventory
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [cache_root])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = cache_root),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ if gguf:
+ return cache_inventory._scan_cached_gguf()
+ return cache_inventory._scan_cached_models()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+
+
+def test_auto_load_sees_a_model_hidden_behind_a_dangling_ref(tmp_path, monkeypatch):
+ """End to end: the snapshot is on disk and the picker lists it, but the inventory reported
+ nothing downloaded and the app re-downloaded."""
+ repo_dir = _build_repo(tmp_path)
+ snapshot = repo_dir / "snapshots" / SNAPSHOT
+ (snapshot / "config.json").write_text("{}", encoding = "utf-8")
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ # Recovered rows pin the snapshot: refs/main dangles, so from_pretrained(repo id) misses it.
+ assert rows[0]["load_id"] == str(snapshot)
+ assert rows[0]["active_cache"] is True
+
+
+def test_a_resolvable_repo_still_loads_by_repo_id(tmp_path, monkeypatch):
+ repo_dir = _build_repo(tmp_path, ref = SNAPSHOT)
+ (repo_dir / "snapshots" / SNAPSHOT / "config.json").write_text("{}", encoding = "utf-8")
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["load_id"] == "Org/Model"
+
+
+def test_default_ref_resolves_only_when_main_names_a_snapshot(tmp_path):
+ """The pin only defers to refs/main when it names a directory actually on disk; a dangling or
+ absent ref has to fall through."""
+ dangling = _build_repo(tmp_path, name = "models--Org--Dangling")
+ resolved = _build_repo(tmp_path, ref = SNAPSHOT, name = "models--Org--Resolved")
+ detached = _build_repo(tmp_path, ref = None, name = "models--Org--Detached")
+
+ assert inventory_scan.default_ref_snapshot(dangling) is None
+ assert inventory_scan.default_ref_snapshot(resolved) is not None
+ assert inventory_scan.default_ref_snapshot(detached) is None
+
+
+# --- the load id must name a snapshot that holds the advertised payload ------
+
+OLDER = "d" * 40
+
+
+# from_pretrained opens every name this map lists, so they must be real.
+def _shard_index(*shards: str) -> bytes:
+ return json.dumps(
+ {"metadata": {}, "weight_map": {f"w{i}": name for i, name in enumerate(shards)}}
+ ).encode()
+
+
+_SHARD_INDEX = _shard_index("model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors")
+_BIN_SHARD_INDEX = _shard_index(
+ "pytorch_model-00001-of-00002.bin", "pytorch_model-00002-of-00002.bin"
+)
+NEWER = "e" * 40
+
+
+def _age(path: Path, seconds: float) -> None:
+ """Backdate a snapshot dir; snapshot selection orders by directory mtime."""
+ stamp = os.stat(path).st_mtime - seconds
+ os.utime(path, (stamp, stamp))
+
+
+def _autoload_gguf_rows(cache_root: Path, monkeypatch) -> list[dict]:
+ """What chat auto-load sees for GGUF: GET /api/hub/cached-gguf."""
+ return _autoload_rows(cache_root, monkeypatch, gguf = True)
+
+
+def _two_snapshot_repo(
+ cache_root: Path,
+ older_files: dict,
+ newer_files: dict,
+ *,
+ ref: str | None = UPSTREAM_HEAD,
+) -> Path:
+ """A repo whose payload sits in the older of two snapshots: a metadata probe against a moved-on
+ commit materialises a newer, weightless snapshot beside the download. ``ref = None`` is what a
+ commit-pinned fetch leaves, since only a branch or tag gets a ref."""
+ repo_dir = cache_root / "models--Org--Model"
+ (repo_dir / "blobs").mkdir(parents = True, exist_ok = True)
+ (repo_dir / "refs").mkdir(parents = True, exist_ok = True)
+ if ref is not None:
+ (repo_dir / "refs" / "main").write_text(ref, encoding = "utf-8")
+ for commit, files in ((OLDER, older_files), (NEWER, newer_files)):
+ snapshot = repo_dir / "snapshots" / commit
+ snapshot.mkdir(parents = True, exist_ok = True)
+ for name, payload in files.items():
+ # Keys may name a subdir ("MTP/...") the way real GGUF repos ship companions.
+ (snapshot / name).parent.mkdir(parents = True, exist_ok = True)
+ (snapshot / name).write_bytes(payload)
+ _age(repo_dir / "snapshots" / OLDER, 600)
+ return repo_dir
+
+
+def test_load_id_names_the_snapshot_holding_the_safetensors_payload(tmp_path, monkeypatch):
+ """The row aggregates weights over every revision, so the payload it advertises can live in an
+ older snapshot than the newest directory."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}", "model.safetensors": b"\0" * 11},
+ newer_files = {"config.json": b"{}"},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["model_format"] == "safetensors"
+ load_dir = Path(rows[0]["load_id"])
+ # from_pretrained(load_id) must find the weights the row advertised.
+ assert any(
+ entry.suffix == ".safetensors" for entry in load_dir.iterdir()
+ ), f"load_id {load_dir.name} holds no weights; payload is in {OLDER[:8]}"
+ assert load_dir == repo_dir / "snapshots" / OLDER
+
+
+def test_load_id_names_the_snapshot_holding_the_advertised_gguf_quant(tmp_path, monkeypatch):
+ """Same for GGUF: the row's size sums quants across revisions, while local variant resolution
+ only ever reads the one directory in ``load_id``."""
+ from hub.utils.gguf import list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}", "Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"config.json": b"{}"},
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["size_bytes"] == 32
+ load_dir = Path(rows[0]["load_id"])
+ variants, _has_vision = list_local_gguf_variants(str(load_dir))
+ assert [v.quant for v in variants] == [
+ "Q4_K_M"
+ ], f"no variant resolves under load_id {load_dir.name}; the quant is in {OLDER[:8]}"
+ assert load_dir == repo_dir / "snapshots" / OLDER
+
+
+def test_load_id_still_prefers_the_newest_snapshot_that_holds_the_payload(tmp_path, monkeypatch):
+ """The payload rule must not pin loads to stale revisions: with both snapshots runnable, the
+ newest still wins."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}", "model.safetensors": b"\0" * 11},
+ newer_files = {"config.json": b"{}", "model.safetensors": b"\0" * 13},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / NEWER
+
+
+def test_load_id_leaves_the_payload_snapshot_when_main_resolves_elsewhere(tmp_path, monkeypatch):
+ """A resolving ``refs/main`` is not enough: the metadata probe that strands the weights in an
+ older snapshot repoints it at the weightless one, so loading by repo id finds no weights."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}", "model.safetensors": b"\0" * 11},
+ newer_files = {"config.json": b"{}"},
+ ref = NEWER,
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ load_id = rows[0]["load_id"]
+ # Follow the load identity the way a load would (repo id via refs/main).
+ resolved = (
+ repo_dir / "snapshots" / (repo_dir / "refs" / "main").read_text(encoding = "utf-8")
+ if load_id == "Org/Model"
+ else Path(load_id)
+ )
+ assert any(
+ entry.suffix == ".safetensors" for entry in resolved.iterdir()
+ ), f"load_id {load_id} resolves to {resolved.name}, which holds no weights"
+ assert Path(load_id) == repo_dir / "snapshots" / OLDER
+
+
+def test_load_id_stays_the_repo_id_when_main_resolves_onto_the_payload(tmp_path, monkeypatch):
+ """The rule must stay narrow: when ``refs/main`` names a snapshot that does hold the payload,
+ the pinned revision keeps winning and the row keeps the repo id."""
+ _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}", "model.safetensors": b"\0" * 11},
+ newer_files = {"config.json": b"{}", "model.safetensors": b"\0" * 13},
+ ref = OLDER,
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["load_id"] == "Org/Model"
+
+
+# --- everything the row advertises must resolve under its load id ------------
+
+
+def _local_gguf_variants_for_autoload(row: dict, cache_root: Path) -> list[str]:
+ """The quants chat auto-load is offered: GET /api/models/gguf-variants with ``preferLocalCache``
+ and the row's ``cache_path``, exactly as chat-adapter calls it before /load."""
+ import asyncio
+
+ from hub.services.models import gguf_variants
+
+ response = asyncio.run(
+ gguf_variants.get_gguf_variants_response(
+ row["repo_id"],
+ prefer_local_cache = True,
+ local_path = row["cache_path"],
+ )
+ )
+ return [variant.quant for variant in response.variants if variant.downloaded]
+
+
+def _listed_gguf_variants(row: dict, cache_root: Path) -> list[str]:
+ """Every quant the same call reports, ready or not: what Settings and the Hub cards show, so a
+ torn download can still be resumed or deleted."""
+ import asyncio
+
+ from hub.services.models import gguf_variants
+
+ response = asyncio.run(
+ gguf_variants.get_gguf_variants_response(
+ row["repo_id"],
+ prefer_local_cache = True,
+ local_path = row["cache_path"],
+ )
+ )
+ return sorted(variant.quant for variant in response.variants)
+
+
+def test_a_half_split_quant_shadows_neither_the_load_id_nor_the_variants(tmp_path, monkeypatch):
+ """The newest snapshot can hold shard 1 of an interrupted split download while a complete quant
+ sits in an older one. Both ends are asserted because they are only correct together: the load id
+ and the quants offered under it must name one directory."""
+ from hub.utils.gguf import list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"Model-Q8_0-00001-of-00002.gguf": b"\0" * 16},
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ load_dir = Path(rows[0]["load_id"])
+ held = {v.quant for v in list_local_gguf_variants(str(load_dir))[0] if v.quant}
+ complete = inventory_scan._completed_gguf_variants(load_dir)
+ assert held and held <= complete, (
+ f"load_id {load_dir.name} offers {sorted(held)} with only "
+ f"{sorted(complete)} complete; the usable quant is in {OLDER[:8]}"
+ )
+ assert load_dir == repo_dir / "snapshots" / OLDER
+ offered = _local_gguf_variants_for_autoload(rows[0], tmp_path)
+ resolvable = {v.quant for v in list_local_gguf_variants(str(load_dir))[0]}
+ # Every quant offered as downloaded resolves under the load id, unshadowed by the broken one.
+ assert set(offered) <= resolvable, (
+ f"auto-load is offered {sorted(offered)} but load_id {load_dir.name[:8]} "
+ f"resolves only {sorted(resolvable)}"
+ )
+ assert offered == ["Q4_K_M"]
+
+
+ "newer_files, listed, offered",
+ [
+ # With nothing complete the newest snapshot holding quants is reported but not loadable.
+ pytest.param(
+ {"Model-Q8_0-00001-of-00002.gguf": b"\0" * 16},
+ ["Q8_0"],
+ [],
+ id = "nothing-complete-anywhere",
+ ),
+ # When that snapshot holds a whole quant too, offering both shadows it.
+ pytest.param(
+ {
+ "Model-Q8_0.gguf": b"\0" * 64,
+ "Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 16,
+ },
+ ["Q4_K_M", "Q8_0"],
+ ["Q8_0"],
+ id = "one-whole-quant-beside-a-half-one",
+ ),
+ ],
+)
+def test_gguf_variants_still_list_when_no_snapshot_is_complete(
+ newer_files, listed, offered, tmp_path, monkeypatch
+):
+ """The completeness preference must not empty the list, nor offer a quant short a shard while a
+ whole one sits beside it."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 32},
+ newer_files = newer_files,
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ load_dir = Path(rows[0]["load_id"])
+ assert load_dir == repo_dir / "snapshots" / NEWER
+ assert _listed_gguf_variants(rows[0], tmp_path) == listed
+ assert _local_gguf_variants_for_autoload(rows[0], tmp_path) == offered
+
+
+def test_a_whole_quant_in_a_mixed_newest_snapshot_beats_an_older_larger_one(tmp_path, monkeypatch):
+ """A whole small quant can sit in the newest snapshot beside an interrupted split one while an
+ older snapshot holds only a whole larger quant. Auto-load takes the smallest offered, so skipping
+ the newest snapshot spends the attempt on the larger one; only its completed subset is offered,
+ so both ends still name one directory."""
+ from hub.utils.gguf import list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q6_K.gguf": b"\0" * 96},
+ newer_files = {
+ "Model-Q4_K_M.gguf": b"\0" * 16,
+ "Model-Q8_0-00001-of-00002.gguf": b"\0" * 8,
+ },
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ load_dir = Path(rows[0]["load_id"])
+ assert load_dir == repo_dir / "snapshots" / NEWER
+ offered = _local_gguf_variants_for_autoload(rows[0], tmp_path)
+ assert offered == ["Q4_K_M"]
+ # The pair still has to agree on one directory, without offering the interrupted split quant.
+ resolvable = {v.quant for v in list_local_gguf_variants(str(load_dir))[0]}
+ assert set(offered) <= resolvable, (
+ f"auto-load is offered {sorted(offered)} but load_id {load_dir.name[:8]} "
+ f"resolves only {sorted(resolvable)}"
+ )
+ assert "Q8_0" not in offered
+ # Pinning the snapshot holding the interrupted download must not flip the row partial.
+ assert rows[0].get("partial") is False
+ assert rows[0].get("capabilities", {}).get("can_chat") is True
+
+
+def test_load_id_is_not_pinned_to_a_snapshot_that_has_no_config(tmp_path, monkeypatch):
+ """The repo-level format may rest on transformer-named weights alone, but a pinned load id names
+ one directory and from_pretrained needs ``config.json`` inside it. Keep the repo id, which can
+ still fill the config in from the hub, rather than pin a weight-only snapshot."""
+ _two_snapshot_repo(
+ tmp_path,
+ older_files = {"model.safetensors": b"\0" * 11},
+ newer_files = {"config.json": b"{}"},
+ ref = NEWER,
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["model_format"] == "safetensors"
+ load_id = rows[0]["load_id"]
+ assert load_id == "Org/Model", (
+ f"load_id {Path(load_id).name[:8]} holds no config.json, so a local "
+ "from_pretrained on it cannot resolve the architecture"
+ )
+
+
+def test_no_snapshot_holds_the_payload_so_a_dangling_ref_pins_nothing(tmp_path, monkeypatch):
+ """Same repo, but with the dangling ``refs/main`` this branch exists for. That arm must not pin
+ the fallback newest snapshot, known not to hold the payload: a directory the load cannot use is
+ worse than the repo id, which can still complete the config."""
+ _two_snapshot_repo(
+ tmp_path,
+ older_files = {"model.safetensors": b"\0" * 11},
+ newer_files = {"config.json": b"{}"},
+ ref = UPSTREAM_HEAD,
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ load_id = rows[0]["load_id"]
+ if load_id != "Org/Model":
+ # A pinned directory is only useful if from_pretrained can read weights out of it.
+ pinned = Path(load_id)
+ held = sorted(entry.name for entry in pinned.iterdir())
+ assert (pinned / "config.json").is_file() and any(
+ entry.endswith(".safetensors") for entry in held
+ ), f"load_id pins {pinned.name[:8]}, which holds only {held}"
+ assert load_id == "Org/Model"
+
+
+# --- the metadata must describe the snapshot the row hands out ---------------
+
+QUANTIZED_CONFIG = b'{"quantization_config": {"quant_method": "bitsandbytes"}}'
+MODEL_CARD = b"---\npipeline_tag: text-generation\nlibrary_name: transformers\n---\n"
+
+
+ "older_files, newer_files, ref, pinned",
+ [
+ # Reading the newest snapshot while the load id names the payload one judges absent data.
+ pytest.param(
+ {
+ "config.json": QUANTIZED_CONFIG,
+ "model.safetensors": b"\0" * 11,
+ "README.md": MODEL_CARD,
+ },
+ {"config.json": b"{}"},
+ NEWER,
+ True,
+ id = "payload-snapshot-supplies-the-row",
+ ),
+ # The rule stays narrow: with no self-contained snapshot the newest still supplies the row.
+ pytest.param(
+ {"model.safetensors": b"\0" * 11},
+ {"config.json": QUANTIZED_CONFIG, "README.md": MODEL_CARD},
+ NEWER,
+ False,
+ id = "newest-snapshot-fallback",
+ ),
+ # Both revisions are self-contained and refs/main resolves onto the OLDER one.
+ pytest.param(
+ {
+ "config.json": QUANTIZED_CONFIG,
+ "model.safetensors": b"\0" * 11,
+ "README.md": MODEL_CARD,
+ },
+ {"config.json": b"{}", "model.safetensors": b"\0" * 13},
+ OLDER,
+ False,
+ id = "repo-id-resolves-onto-the-older-payload",
+ ),
+ ],
+)
+def test_metadata_describes_the_snapshot_the_row_hands_out(
+ older_files, newer_files, ref, pinned, tmp_path, monkeypatch
+):
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = older_files,
+ newer_files = newer_files,
+ ref = ref,
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ expected_load_id = str(repo_dir / "snapshots" / OLDER) if pinned else "Org/Model"
+ assert rows[0]["load_id"] == expected_load_id
+ assert rows[0].get("quant_method") == "bitsandbytes"
+ assert rows[0].get("pipeline_tag") == "text-generation"
+ assert rows[0].get("library_name") == "transformers"
+
+
+# --- the signals paired with the pinned snapshot ------------------------------
+
+
+def test_a_companion_only_snapshot_is_not_a_gguf_payload(tmp_path, monkeypatch):
+ """``MTP/`` drafters are recognisable only from the snapshot-relative path (``huggingface_hub``
+ sets ``file_name`` to the bare name for nested files). Matching bare names let a drafter-only
+ snapshot win the load id, where the variant lister offers nothing."""
+ from hub.utils.gguf import list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 32},
+ newer_files = {"MTP/Model-Q8_0-MTP.gguf": b"\0" * 64},
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ load_dir = Path(rows[0]["load_id"])
+ variants, _has_vision = list_local_gguf_variants(str(load_dir))
+ assert [v.quant for v in variants], (
+ f"load_id {load_dir.name[:8]} offers no quant at all; it holds only a " "companion drafter"
+ )
+ assert load_dir == repo_dir / "snapshots" / OLDER
+
+
+ "older_files, newer_files, has_vision",
+ [
+ # A lone projector lands in a newer quantless snapshot, so the row pins the older one.
+ pytest.param(
+ {"Model-Q4_K_M.gguf": b"\0" * 32},
+ {"mmproj-F16.gguf": b"\0" * 64},
+ False,
+ id = "projector-stranded-in-another-snapshot",
+ ),
+ # Negative side: colocated with the pinned quant it is reachable, so the flag must survive.
+ pytest.param(
+ {"Model-Q4_K_M.gguf": b"\0" * 32, "mmproj-F16.gguf": b"\0" * 64},
+ {"config.json": b"{}"},
+ True,
+ id = "projector-beside-the-pinned-quant",
+ ),
+ ],
+)
+def test_vision_is_reported_only_from_the_snapshot_the_row_pins(
+ older_files, newer_files, has_vision, tmp_path, monkeypatch
+):
+ """The load path looks for companions no higher than the selected snapshot directory, so a
+ projector in any other snapshot is unreachable and must not be advertised."""
+ from hub.utils.gguf import list_gguf_variants_from_hf_cache
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = older_files,
+ newer_files = newer_files,
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+ load_dir = Path(rows[0]["load_id"])
+ assert load_dir == repo_dir / "snapshots" / OLDER
+
+ listed = list_gguf_variants_from_hf_cache("Org/Model", root = tmp_path)
+ assert listed is not None
+ variants, reported_vision, _complete = listed
+ # The quant on disk stays offered either way; only the flag may move.
+ assert [v.quant for v in variants] == ["Q4_K_M"]
+ assert reported_vision is has_vision
+ # The picker prefers the row's own copy of the flag over the one above.
+ assert rows[0]["capabilities"].get("supports_vision") is has_vision
+ # The loader's companion search stops at the pinned snapshot.
+ assert (load_dir / "mmproj-F16.gguf").is_file() is has_vision
+
+
+ ("projector", "has_vision"),
+ [
+ pytest.param(b"", False, id = "a-projector-with-nothing-behind-the-name"),
+ pytest.param(b"\0" * 128, True, id = "a-projector-with-content"),
+ ],
+)
+def test_an_empty_projector_is_not_vision_support(tmp_path, monkeypatch, projector, has_vision):
+ """has_vision came off the filename alone, so an interrupted companion download advertised a
+ projector llama.cpp cannot open while the row's own quant stayed whole."""
+ from hub.utils.gguf import list_local_gguf_variants
+
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {"Model-Q4_K_M.gguf": b"\0" * 256, "mmproj-F16.gguf": projector},
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+ assert rows[0]["capabilities"].get("supports_vision") is has_vision
+ # The lister and the row capability read the same walk, so they cannot drift apart.
+ snapshot = tmp_path / "models--Org--Model" / "snapshots" / SNAPSHOT
+ assert list_local_gguf_variants(str(snapshot))[1] is has_vision
+
+
+ ("files", "torn"),
+ [
+ pytest.param(
+ {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 256},
+ True,
+ id = "the-only-quant-is-half-a-split",
+ ),
+ pytest.param(
+ {
+ "Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 256,
+ "Model-Q4_K_M-00002-of-00002.gguf": b"\0" * 256,
+ },
+ False,
+ id = "the-split-is-whole",
+ ),
+ pytest.param(
+ {
+ "Model-Q8_0.gguf": b"\0" * 256,
+ "Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 256,
+ },
+ False,
+ id = "a-whole-quant-beside-the-torn-one",
+ ),
+ pytest.param({"Model-Q4_K_M.gguf": b"\0" * 256}, False, id = "one-unsplit-quant"),
+ ],
+)
+def test_a_manifestless_torn_quant_is_still_reported(tmp_path, monkeypatch, files, torn):
+ """Every other quant signal comes from a manifest, a marker or the completed set, and an
+ interrupted attempt leaves none of those, so the shards are the only evidence of a torn split."""
+ _repo_with(tmp_path, snapshots = {SNAPSHOT: files}, refs = {"main": UPSTREAM_HEAD})
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is torn
+ assert rows[0]["capabilities"]["can_chat"] is not torn
+
+
+def test_a_repo_root_drafter_still_leaves_a_real_quant_selectable(tmp_path, monkeypatch):
+ """The rule must stay narrow: a snapshot holding a drafter *and* a real quant is still a
+ payload snapshot."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"mtp-Model-Q8_0.gguf": b"\0" * 64, "Model-Q8_0.gguf": b"\0" * 128},
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / NEWER
+
+
+def _write_repo_wide_signal(kind: str, hub_cache: Path) -> None:
+ """Either repo-wide partial signal, neither of which records a revision. The manifest names a
+ file the pinned older snapshot holds at a different size, as a renamed revision leaves behind."""
+ from hub.utils import download_manifest
+
+ if kind == "marker":
+ download_manifest.write_cancel_marker(
+ "model", "Org/Model", None, "http", hub_cache = hub_cache
+ )
+ return
+ download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ None,
+ [download_manifest.ExpectedFile("model.safetensors", 99)],
+ "http",
+ hub_cache = hub_cache,
+ )
+
+
[email protected]("signal", ["marker", "manifest"])
+ "newer_files, ref, advertised, partial",
+ [
+ # The signal belongs to the newest snapshot while the row advertises an older, complete one.
+ pytest.param({"config.json": b"{}"}, NEWER, OLDER, False, id = "pinned-older-snapshot"),
+ # Negative side: the signal does describe the snapshot the row advertises. No refs/main
+ # (a commit-pinned fetch) carries no evidence either way.
+ pytest.param(
+ {"config.json": b"{}", "model.safetensors": b"\0" * 13},
+ None,
+ NEWER,
+ True,
+ id = "advertised-snapshot",
+ ),
+ # A refs/main naming no directory does carry evidence: that attempt landed no file.
+ pytest.param(
+ {"config.json": b"{}", "model.safetensors": b"\0" * 13},
+ UPSTREAM_HEAD,
+ NEWER,
+ False,
+ id = "unmaterialised-attempt",
+ ),
+ # refs/main resolves onto the OLDER payload snapshot though the newer one is self-contained too.
+ pytest.param(
+ {"config.json": b"{}", "model.safetensors": b"\0" * 13},
+ OLDER,
+ "Org/Model",
+ False,
+ id = "repo-id-resolves-onto-the-older-payload",
+ ),
+ ],
+)
+def test_repo_wide_partial_signals_are_charged_to_the_newest_snapshot(
+ signal, newer_files, ref, advertised, partial, tmp_path, monkeypatch
+):
+ """A cancel marker and a repo-wide manifest both record only the *last* attempt (the marker is
+ cleared at every download start and on success; the manifest is overwritten), so both belong to
+ the newest snapshot and neither may be verified against an older revision's payload."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}", "model.safetensors": b"\0" * 11},
+ newer_files = newer_files,
+ ref = ref,
+ )
+ _write_repo_wide_signal(signal, tmp_path)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ # *advertised* is a commit whose snapshot the row pins, or the repo id when refs/main resolves.
+ expected_load_id = (
+ advertised if advertised == "Org/Model" else str(repo_dir / "snapshots" / advertised)
+ )
+ assert rows[0]["load_id"] == expected_load_id
+ assert rows[0].get("partial") is partial
+ assert rows[0]["capabilities"].get("can_chat") is not partial
+
+
+def test_gguf_partial_is_judged_against_the_snapshot_the_row_advertises(tmp_path, monkeypatch):
+ """The GGUF row picked its payload snapshot after computing ``partial``, a walk over the repo's
+ blobs plus the newest snapshot, so an interrupted re-download flipped ``can_chat`` off for the
+ older complete quant."""
+ from hub.utils.gguf import list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"Model-Q8_0-00001-of-00002.gguf": b"\0" * 16},
+ )
+ (repo_dir / "blobs" / ("a" * 40 + ".incomplete")).write_bytes(b"\0" * 3)
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ load_dir = Path(rows[0]["load_id"])
+ assert load_dir == repo_dir / "snapshots" / OLDER
+ variants, _has_vision = list_local_gguf_variants(str(load_dir))
+ assert [v.quant for v in variants] == ["Q4_K_M"]
+ assert rows[0].get("partial") is False
+ assert rows[0]["capabilities"].get("can_chat") is True
+
+
+def test_a_gguf_download_interrupted_in_its_own_snapshot_is_still_partial(tmp_path, monkeypatch):
+ """Negative side of the same rule: with no complete quant anywhere the row falls back to the
+ newest snapshot, the ``.incomplete`` blob does belong to it, and the row must still be
+ partial."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 32},
+ newer_files = {"Model-Q8_0-00001-of-00002.gguf": b"\0" * 16},
+ ref = None,
+ )
+ (repo_dir / "blobs" / ("a" * 40 + ".incomplete")).write_bytes(b"\0" * 3)
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / NEWER
+ assert rows[0].get("partial") is True
+ assert rows[0]["capabilities"].get("can_chat") is False
+
+
+ "older_files, partial",
+ [
+ # Half a split quant and no manifest or marker: the .incomplete blob is the only evidence.
+ pytest.param(
+ {"Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 32},
+ True,
+ id = "pinned-snapshot-holds-half-a-split-quant",
+ ),
+ # Negative side: the pinned snapshot serves the whole quant, so the row stays chattable.
+ pytest.param(
+ {
+ "Model-Q4_K_M-00001-of-00002.gguf": b"\0" * 32,
+ "Model-Q4_K_M-00002-of-00002.gguf": b"\0" * 32,
+ },
+ False,
+ id = "pinned-snapshot-holds-the-whole-quant",
+ ),
+ ],
+)
+def test_a_dangling_ref_keeps_a_legacy_partial_signal_for_a_broken_snapshot(
+ older_files, partial, tmp_path, monkeypatch
+):
+ """A legacy interrupted GGUF download predates the manifest, so its only trace is an
+ ``.incomplete`` blob. A later update rewrote ``refs/main`` and fetched no file, making the ref
+ dangle; suppressing every repo-wide signal on sight then reported the row chattable."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = older_files,
+ newer_files = {"config.json": b"{}"},
+ ref = UPSTREAM_HEAD,
+ )
+ (repo_dir / "blobs" / ("a" * 40 + ".incomplete")).write_bytes(b"\0" * 3)
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / OLDER
+ assert rows[0].get("partial") is partial
+ assert rows[0]["capabilities"].get("can_chat") is not partial
+
+
+ "older_files, partial",
+ [
+ # The safetensors half of the case above: a shard names the total, so half a set is provable.
+ pytest.param(
+ {"config.json": b"{}", "model-00001-of-00002.safetensors": b"\0" * 32},
+ True,
+ id = "pinned-snapshot-holds-half-a-sharded-set",
+ ),
+ # Negative side: the whole set is here, so the row stays chattable.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "model-00002-of-00002.safetensors": b"\0" * 32,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ False,
+ id = "pinned-snapshot-holds-the-whole-sharded-set",
+ ),
+ # Nothing names a total, so nothing proves breakage: the #7374 shape must keep loading.
+ pytest.param(
+ {"config.json": b"{}", "model.safetensors": b"\0" * 32},
+ False,
+ id = "pinned-snapshot-holds-an-unsharded-payload",
+ ),
+ # from_pretrained loads one family, so a torn set beside a complete one keeps auto-load.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model.safetensors": b"\0" * 32,
+ "pytorch_model-00001-of-00002.bin": b"\0" * 32,
+ },
+ False,
+ id = "pinned-snapshot-holds-a-whole-family-beside-a-broken-one",
+ ),
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "model-00002-of-00002.safetensors": b"\0" * 32,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ "pytorch_model-00001-of-00003.bin": b"\0" * 32,
+ },
+ False,
+ id = "pinned-snapshot-holds-a-whole-sharded-family-beside-a-broken-one",
+ ),
+ # The half-fetched set stays proof: no training artefact or adapter is a base family.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "training_args.bin": b"\0" * 8,
+ "optimizer.bin": b"\0" * 8,
+ },
+ True,
+ id = "half-a-sharded-set-beside-training-artefacts",
+ ),
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "adapter_model.safetensors": b"\0" * 8,
+ },
+ True,
+ id = "half-a-sharded-set-beside-an-adapter",
+ ),
+ # A COMPLETE auxiliary set is not a base family either, so it cannot stand in for one.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "adapter_model-00001-of-00002.safetensors": b"\0" * 8,
+ "adapter_model-00002-of-00002.safetensors": b"\0" * 8,
+ },
+ True,
+ id = "half-a-sharded-set-beside-a-whole-sharded-adapter",
+ ),
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "optimizer-00001-of-00002.bin": b"\0" * 8,
+ "optimizer-00002-of-00002.bin": b"\0" * 8,
+ },
+ True,
+ id = "half-a-sharded-set-beside-a-whole-sharded-optimizer",
+ ),
+ ],
+)
+def test_a_dangling_ref_keeps_a_legacy_partial_signal_for_a_half_fetched_snapshot(
+ older_files, partial, tmp_path, monkeypatch
+):
+ """The same bytes on disk went partial while ``refs/main`` resolved, then chattable once a later
+ attempt rewrote the ref and materialised no directory, so the row offered unfetched shards."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = older_files,
+ newer_files = {"config.json": b"{}"},
+ ref = UPSTREAM_HEAD,
+ )
+ (repo_dir / "blobs" / ("a" * 40 + ".incomplete")).write_bytes(b"\0" * 3)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / OLDER
+ assert rows[0].get("partial") is partial
+ assert (rows[0].get("capabilities") or {}).get("can_chat") is not partial
+
+
+ "older_files, partial",
+ [
+ # Half a sharded set and NO other trace, as a cleaned-up fetch or a copied cache leaves.
+ pytest.param(
+ {"config.json": b"{}", "model-00001-of-00002.safetensors": b"\0" * 32},
+ True,
+ id = "half-a-sharded-set-and-no-other-trace",
+ ),
+ # Negative side, and #7374's own shape: the payload is whole, so the row loads from disk.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "model-00002-of-00002.safetensors": b"\0" * 32,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ False,
+ id = "a-whole-sharded-set-and-no-other-trace",
+ ),
+ # Nothing names a total, so nothing proves breakage and the row loads.
+ pytest.param(
+ {"config.json": b"{}", "model.safetensors": b"\0" * 32},
+ False,
+ id = "an-unsharded-payload-and-no-other-trace",
+ ),
+ # One whole family beside a torn one still loads, as with an .incomplete blob present.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model.safetensors": b"\0" * 32,
+ "pytorch_model-00001-of-00002.bin": b"\0" * 32,
+ },
+ False,
+ id = "a-whole-family-beside-a-torn-one-and-no-other-trace",
+ ),
+ # A complete auxiliary set does not vouch for torn base shards either.
+ pytest.param(
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ "adapter_model-00001-of-00002.safetensors": b"\0" * 8,
+ "adapter_model-00002-of-00002.safetensors": b"\0" * 8,
+ },
+ True,
+ id = "half-a-base-set-beside-a-whole-adapter-and-no-other-trace",
+ ),
+ ],
+)
+def test_a_recovered_snapshot_short_a_shard_is_partial_with_no_other_signal(
+ older_files, partial, tmp_path, monkeypatch
+):
+ """The recovery is what puts this row on screen at all (``scan_cache_dir`` drops the repo), so a
+ snapshot it restores must be judged on its own contents when the interrupted attempt left
+ nothing else behind, or the row advertises ``can_chat`` for a payload short a shard."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = older_files,
+ newer_files = {"config.json": b"{}"},
+ ref = UPSTREAM_HEAD,
+ )
+ # No .incomplete blob, no marker, no manifest: the point of this case.
+ assert not any((repo_dir / "blobs").iterdir())
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / OLDER
+ assert rows[0].get("partial") is partial
+ assert (rows[0].get("capabilities") or {}).get("can_chat") is not partial
+
+
+def test_a_resolving_ref_is_not_judged_on_the_recovery_walk(tmp_path, monkeypatch):
+ """The new signal is scoped to the rows the recovery adds. With ``refs/main`` naming a snapshot
+ on disk the repo is one ``scan_cache_dir`` already returns, and its answer is left alone."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 32,
+ },
+ newer_files = {"config.json": b"{}"},
+ ref = OLDER,
+ )
+
+ assert inventory_scan.default_ref_snapshot(repo_dir) is not None
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ # The ref resolves, so the load id stays the repo id and the row keeps its pre-recovery answer.
+ assert rows[0]["load_id"] == "Org/Model"
+ assert rows[0].get("partial") is False
+
+
[email protected]("signal", ["marker", "manifest"])
+def test_an_update_that_never_materialised_leaves_the_cached_payload_chattable(
+ signal, tmp_path, monkeypatch
+):
+ """The recovered row's own scenario. ``refs/main`` is rewritten before the first byte and the
+ manifest earlier still, so an update interrupted that early leaves the previous complete snapshot
+ as the only payload under a ref that resolves nowhere: it must not arrive partial."""
+ repo_dir = _build_repo(tmp_path, ref = UPSTREAM_HEAD)
+ snapshot = repo_dir / "snapshots" / SNAPSHOT
+ (snapshot / "config.json").write_text("{}", encoding = "utf-8")
+ _write_repo_wide_signal(signal, tmp_path)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == snapshot
+ assert rows[0].get("partial") is False
+ assert rows[0]["capabilities"].get("can_chat") is True
+
+
+ "older_files, newer_files, ref, advertised, partial",
+ [
+ # A re-download that stops before materialising its snapshot leaves a NEW-revision manifest.
+ pytest.param(
+ {"Model-Q4_K_M.gguf": b"\0" * 32},
+ {"config.json": b"{}"},
+ NEWER,
+ OLDER,
+ False,
+ id = "pinned-older-snapshot",
+ ),
+ # Negative side: the manifest's quant is incomplete under the pinned snapshot, which judges.
+ pytest.param(
+ {"config.json": b"{}"},
+ {"Model-Q4_K_M.gguf": b"\0" * 32},
+ None,
+ NEWER,
+ True,
+ id = "advertised-snapshot",
+ ),
+ ],
+)
+def test_a_gguf_variant_manifest_is_scoped_to_the_snapshot_the_row_pins(
+ older_files, newer_files, ref, advertised, partial, tmp_path, monkeypatch
+):
+ from hub.utils import download_manifest
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = older_files,
+ newer_files = newer_files,
+ ref = ref,
+ )
+ download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ "Q4_K_M",
+ [download_manifest.ExpectedFile("Model-Q4_K_M.gguf", 999)],
+ "http",
+ hub_cache = tmp_path,
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / advertised
+ assert rows[0].get("partial") is partial
+ assert rows[0]["capabilities"].get("can_chat") is not partial
+
+
+def test_a_gguf_variant_marker_from_a_newer_attempt_does_not_disable_the_pinned_quant(
+ tmp_path, monkeypatch
+):
+ """The GGUF twin of the repo-wide marker rule. A cancel marker is keyed by (repo, variant) with
+ no revision, so cancelling a re-download of a held quant marked the complete copy broken."""
+ from hub.utils import download_manifest
+ from hub.utils.gguf import list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"config.json": b"{}"},
+ ref = NEWER,
+ )
+ download_manifest.write_cancel_marker(
+ "model", "Org/Model", "Q4_K_M", "http", hub_cache = tmp_path
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ load_dir = Path(rows[0]["load_id"])
+ assert load_dir == repo_dir / "snapshots" / OLDER
+ # The quant the marker names resolves under the load id.
+ assert [v.quant for v in list_local_gguf_variants(str(load_dir))[0]] == ["Q4_K_M"]
+ assert rows[0].get("partial") is False
+ assert rows[0]["capabilities"].get("can_chat") is True
+
+
+def test_a_gguf_variant_marker_against_the_advertised_snapshot_is_still_partial(
+ tmp_path, monkeypatch
+):
+ """Negative side of the same rule: when the row advertises the newest snapshot the marker does
+ describe the attempt that wrote it, so the quant stays broken and the row keeps its resume."""
+ from hub.utils import download_manifest
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"config.json": b"{}"},
+ newer_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ ref = None,
+ )
+ download_manifest.write_cancel_marker(
+ "model", "Org/Model", "Q4_K_M", "http", hub_cache = tmp_path
+ )
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / NEWER
+ assert rows[0].get("partial") is True
+ assert rows[0]["capabilities"].get("can_chat") is False
+
+
+def test_a_marker_for_another_quant_still_leaves_the_pinned_one_chattable(tmp_path, monkeypatch):
+ """The Q8+Q4 mixed-state rule holds across snapshots: a cancelled quant the load id does not
+ resolve must not veto the clean one."""
+ from hub.utils import download_manifest
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"config.json": b"{}"},
+ ref = NEWER,
+ )
+ download_manifest.write_cancel_marker("model", "Org/Model", "Q8_0", "http", hub_cache = tmp_path)
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert Path(rows[0]["load_id"]) == repo_dir / "snapshots" / OLDER
+ assert rows[0].get("partial") is False
+ assert rows[0]["capabilities"].get("can_chat") is True
+
+
+# --- one snapshot ordering, so the row and the picker cannot disagree ---------
+
+
+def test_equal_mtime_snapshots_order_the_same_way_whatever_the_iteration_order(tmp_path):
+ """Selection ran off directory mtime alone, which is not a total order: candidates reach the row
+ through a ``frozenset`` and the variant walk through ``iterdir()``, so equal mtimes picked
+ different directories."""
+ from hub.services.models import cache_inventory
+
+ first = tmp_path / "snapshots" / OLDER
+ second = tmp_path / "snapshots" / NEWER
+ for snapshot in (first, second):
+ snapshot.mkdir(parents = True)
+ os.utime(snapshot, (1_700_000_000, 1_700_000_000))
+
+ forward = cache_inventory._newest_snapshot_dir([first, second])
+ backward = cache_inventory._newest_snapshot_dir([second, first])
+
+ assert forward == backward, "the pick moved with the order the candidates arrived in"
+ assert forward == second.resolve()
+
+
+def test_the_row_and_the_picker_agree_on_equal_mtime_snapshots(tmp_path, monkeypatch):
+ """End to end at the tie: whichever snapshot wins, the quants offered as downloaded must resolve
+ under the load id the row hands out. On a coarse timestamp filesystem the row pinned one
+ snapshot while the picker offered the other one's quant."""
+ from hub.utils.gguf import iter_hf_cache_snapshots, list_local_gguf_variants
+
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {"Model-Q4_K_M.gguf": b"\0" * 32},
+ newer_files = {"Model-Q8_0.gguf": b"\0" * 64},
+ )
+ for commit in (OLDER, NEWER):
+ os.utime(repo_dir / "snapshots" / commit, (1_700_000_000, 1_700_000_000))
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ load_dir = Path(rows[0]["load_id"])
+ offered = _local_gguf_variants_for_autoload(rows[0], tmp_path)
+ resolvable = {v.quant for v in list_local_gguf_variants(str(load_dir))[0] if v.quant}
+ assert set(offered) <= resolvable, (
+ f"auto-load is offered {sorted(offered)} but load_id {load_dir.name[:8]} "
+ f"resolves only {sorted(resolvable)}"
+ )
+ # Both selectors head the same list, so the tie cannot split them again.
+ assert load_dir == next(iter(iter_hf_cache_snapshots("Org/Model", root = tmp_path)))
+
+
+def test_vision_does_not_travel_between_two_cache_roots(tmp_path, monkeypatch):
+ """The same repo can sit in the active hub cache and in a previous one. One row survives the
+ merge and only its directory loads, so the loser's projector flag must not carry over."""
+ from types import SimpleNamespace
+
+ from hub.services.models import cache_inventory
+
+ active = tmp_path / "active"
+ previous = tmp_path / "previous"
+ for root, files in (
+ (active, {"Model-Q4_K_M.gguf": b"\0" * 32}),
+ (previous, {"Model-Q4_K_M.gguf": b"\0" * 32, "mmproj-F16.gguf": b"\0" * 64}),
+ ):
+ snapshot = root / "models--Org--Model" / "snapshots" / SNAPSHOT
+ snapshot.mkdir(parents = True)
+ (root / "models--Org--Model" / "refs").mkdir(parents = True)
+ (root / "models--Org--Model" / "refs" / "main").write_text(SNAPSHOT, encoding = "utf-8")
+ for name, payload in files.items():
+ (snapshot / name).write_bytes(payload)
+
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, previous])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = active),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ rows = cache_inventory._scan_cached_gguf()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["active_cache"] is True
+ # The row the picker shows loads out of the active root, which holds no projector.
+ assert not (active / "models--Org--Model" / "snapshots" / SNAPSHOT / "mmproj-F16.gguf").exists()
+ assert rows[0]["capabilities"].get("supports_vision") is False
+
+
+# --- the chokepoints, so a new signal cannot pick its own snapshot ------------
+
+_BACKEND = Path(__file__).resolve().parents[1]
+# Every helper the per-repo scan may hand the whole repo to. Each aggregates across revisions on
+# purpose, so a new name here is a new repo-wide signal on a one-directory row.
+_REPO_WIDE_HELPERS = frozenset(
+ {
+ "_cache_inventory_fields",
+ "_repo_gguf_last_modified",
+ "_repo_gguf_payload_snapshots",
+ "_repo_gguf_size_bytes",
+ "_repo_has_gguf_files",
+ "_repo_non_gguf_model_payload",
+ "getattr",
+ }
+)
+# Only the shared ordering key may read a snapshot dir's mtime; _blob_mtime orders nothing.
+_MTIME_READERS = {
+ "hub/utils/hf_cache_state.py": frozenset({"snapshot_selection_key"}),
+ "hub/utils/gguf.py": frozenset(),
+ "hub/services/models/cache_inventory.py": frozenset({"_blob_mtime"}),
+ # Mirrors what huggingface_hub records per revision; it selects nothing.
+ "hub/utils/inventory_scan.py": frozenset({"_recover_repo_hidden_by_dangling_refs"}),
+ # The compatibility routes, listed so the two snapshot selectors cannot reintroduce their own
+ # mtime reads. The names left rank directories or repo/blob mtimes, never snapshots.
+ "routes/models.py": frozenset(
+ {
+ "_blob_mtime",
+ "_scan_hf_cache",
+ "_scan_lmstudio_dir",
+ "_scan_models_dir",
+ "_scan_ollama_dir",
+ }
+ ),
+}
+
+
+def _function_defs(path: Path) -> dict:
+ import ast
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ return {
+ node.name: node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+
[email protected]("scan", ["_scan_cached_gguf", "_scan_cached_models"])
+def test_the_scan_loop_cannot_advertise_a_signal_it_did_not_scope(scan):
+ """A row's flags come from ``_cache_inventory_fields``, the sole producer, which has exactly one
+ snapshot in scope. Setting one afterwards, or walking ``repo_info.revisions`` in the loop, puts
+ the whole repo back in scope."""
+ import ast
+
+ node = _function_defs(_BACKEND / "hub/services/models/cache_inventory.py")[scan]
+
+ mutations = [
+ ast.unparse(target)
+ for stmt in ast.walk(node)
+ if isinstance(stmt, ast.Assign)
+ for target in stmt.targets
+ if isinstance(target, ast.Subscript) and "capabilities" in ast.unparse(target)
+ ]
+ assert mutations == [], f"{scan} sets a capability outside _cache_inventory_fields: {mutations}"
+
+ revision_reads = [
+ ast.unparse(sub)
+ for sub in ast.walk(node)
+ if isinstance(sub, ast.Attribute)
+ and sub.attr == "revisions"
+ and isinstance(sub.value, ast.Name)
+ and sub.value.id == "repo_info"
+ ]
+ assert revision_reads == [], f"{scan} walks every revision itself: {revision_reads}"
+
+ handed_off = sorted(
+ {
+ ast.unparse(call.func)
+ for call in ast.walk(node)
+ if isinstance(call, ast.Call)
+ and any(
+ isinstance(arg, ast.Name) and arg.id == "repo_info"
+ for arg in [*call.args, *(kw.value for kw in call.keywords)]
+ )
+ }
+ )
+ assert (
+ set(handed_off) <= _REPO_WIDE_HELPERS
+ ), f"{scan} hands the whole repo to {sorted(set(handed_off) - _REPO_WIDE_HELPERS)}"
+
+
[email protected]("module, allowed", sorted(_MTIME_READERS.items()))
+def test_only_the_shared_key_orders_snapshots_by_mtime(module, allowed):
+ """Two selectors with their own mtime read disagree on equal timestamps."""
+ import ast
+
+ readers = {
+ name
+ for name, node in _function_defs(_BACKEND / module).items()
+ if any(isinstance(sub, ast.Attribute) and sub.attr == "st_mtime" for sub in ast.walk(node))
+ }
+ assert readers == set(
+ allowed
+ ), f"{module} reads a snapshot mtime outside snapshot_selection_key: {sorted(readers)}"
+
+
+# --- review-round regressions -------------------------------------------------
+
+
+def _repo_with(
+ cache_root: Path,
+ snapshots: dict,
+ refs: dict,
+ name: str = "models--Org--Model",
+):
+ """A cache repo with arbitrary per-snapshot contents and ref targets."""
+ repo_dir = cache_root / name
+ (repo_dir / "blobs").mkdir(parents = True, exist_ok = True)
+ (repo_dir / "refs").mkdir(parents = True, exist_ok = True)
+ for commit, files in snapshots.items():
+ snapshot = repo_dir / "snapshots" / commit
+ snapshot.mkdir(parents = True, exist_ok = True)
+ for rel, payload in files.items():
+ (snapshot / rel).parent.mkdir(parents = True, exist_ok = True)
+ (snapshot / rel).write_bytes(payload)
+ for ref_name, commit in refs.items():
+ (repo_dir / "refs" / ref_name).write_text(commit, encoding = "utf-8")
+ return repo_dir
+
+
+def test_a_secondary_dangling_ref_still_judges_the_recovered_snapshot(tmp_path, monkeypatch):
+ """refs/main resolves while refs/stale dangles, so recovery fires but the default-ref test does
+ not. The pinned snapshot is short a shard with no marker, manifest or .incomplete blob, so its
+ contents are the only evidence: the guard has to key on ANY dangling ref, not just refs/main."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": SNAPSHOT, "stale": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [r["repo_id"] for r in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_torn_payload_stays_partial_when_the_ref_resolves(tmp_path, monkeypatch):
+ """Excusing a non-newest snapshot from the repo-wide signals is the point of the attribution,
+ but it only holds while that snapshot can serve the row. A torn one has no other evidence it is
+ unfinished, so an interrupted attempt on another revision must not make it chattable."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ },
+ newer_files = {"README.md": b"probe"},
+ ref = OLDER,
+ )
+ (repo_dir / "blobs" / "deadbeef.incomplete").write_bytes(b"\0" * 8)
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+ "weight",
+ ["model.safetensors", "adapter_model.safetensors"],
+ ids = ["base", "adapter"],
+)
+def test_selection_passes_over_a_newer_snapshot_whose_weight_file_is_empty(
+ tmp_path, monkeypatch, weight
+):
+ """A zero-byte weight used to be skipped outright, so the newer revision read as holding nothing
+ broken and beat a whole older one. The loader picks the name by existence, then cannot open."""
+ config = "adapter_config.json" if weight.startswith("adapter") else "config.json"
+ body = b'{"peft_type":"LORA"}' if config == "adapter_config.json" else b'{"model_type":"llama"}'
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {config: body, weight: b"\0" * 256},
+ NEWER: {config: body, weight: b""},
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+ assert rows[0]["load_id"] == str(repo_dir / "snapshots" / OLDER)
+
+
+def test_a_snapshot_whose_every_shard_is_empty_names_no_family_to_miss(tmp_path, monkeypatch):
+ """An empty numbered shard reads as absent from its family rather than unreadable, so a
+ snapshot holding nothing but one named no family at all and read as having nothing missing."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model-00002-of-00002.safetensors": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ NEWER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"",
+ },
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+ assert rows[0]["load_id"] == str(repo_dir / "snapshots" / OLDER)
+
+
+ "config_body",
+ [b'{"model_type": "llam', b"[1,2,3]", b""],
+ ids = ["truncated", "not-an-object", "empty"],
+)
+def test_a_required_config_has_to_parse_before_it_proves_a_payload(
+ tmp_path, monkeypatch, config_body
+):
+ """from_pretrained parses config.json before it looks at a single weight, so one that does not
+ parse fails the load as surely as a zero-byte one and cannot mark the snapshot ready."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": config_body,
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model-00002-of-00002.safetensors": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+ "artefact",
+ ["optimizer.safetensors", "scheduler.safetensors", "trainer_state.safetensors"],
+)
+def test_trainer_state_is_not_the_model_it_was_saved_beside(tmp_path, monkeypatch, artefact):
+ """A trainer writes these next to the weights. They end in .safetensors and from_pretrained
+ will not load one, so a snapshot holding nothing else has no payload to offer."""
+ _repo_with(
+ tmp_path,
+ snapshots = {OLDER: {"config.json": b'{"model_type":"llama"}', artefact: b"\0" * 256}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ assert _autoload_rows(tmp_path, monkeypatch) == []
+
+
+def test_trainer_state_beside_real_weights_changes_nothing(tmp_path, monkeypatch):
+ """Negative control for the test above: the artefact is ignored, not held against the row."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "optimizer.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_an_empty_stray_adapter_does_not_veto_a_checkpoint(tmp_path, monkeypatch):
+ """A zero-byte file from the other family is not what this row loads. The non-empty case is
+ already exempted when the row's own payload names no family, and this is the same shape."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.ckpt": b"\0" * 256,
+ "adapter_model.safetensors": b"",
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_an_empty_weight_of_the_rows_own_kind_still_vetoes(tmp_path, monkeypatch):
+ """Negative control for the test above: the loader stops on a name of the kind it wants."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"",
+ "adapter_model.bin": b"",
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ assert _autoload_rows(tmp_path, monkeypatch) == []
+
+
+ "weight",
+ [
+ "model-00000-of-00002.safetensors",
+ "model-00003-of-00002.safetensors",
+ "model-00001-of-00000.safetensors",
+ ],
+ ids = ["index-zero", "index-past-total", "total-zero"],
+)
+def test_numbering_no_set_of_shards_can_satisfy_is_a_family_short(tmp_path, monkeypatch, weight):
+ """The name still classifies the snapshot, so dropping the family left nothing to be short of
+ and it read as complete. Neither transformers nor peft can assemble one of these."""
+ _repo_with(
+ tmp_path,
+ snapshots = {OLDER: {"config.json": b'{"model_type":"llama"}', weight: b"\0" * 256}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
[email protected]("artefact", ["optimizer.pt", "scheduler.pth", "rng_state.npz"])
+def test_trainer_state_in_checkpoint_format_is_not_a_payload_either(
+ tmp_path, monkeypatch, artefact
+):
+ """The checkpoint extensions are a suffix test, so trainer state saved as .pt read as weights
+ the same way optimizer.safetensors did before it was excluded."""
+ _repo_with(
+ tmp_path,
+ snapshots = {OLDER: {"config.json": b'{"model_type":"llama"}', artefact: b"\0" * 256}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ assert _autoload_rows(tmp_path, monkeypatch) == []
+
+
+def test_an_empty_checkpoint_is_not_a_payload_this_walk_can_excuse(tmp_path, monkeypatch):
+ """A .ckpt names no family, so absence of one cannot be held against it. An empty one is
+ different: the file is there, the loader opens it, and there is nothing inside."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {"config.json": b'{"model_type":"llama"}', "model.ckpt": b"\0" * 256},
+ NEWER: {"config.json": b'{"model_type":"llama"}', "model.ckpt": b""},
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["load_id"] == str(repo_dir / "snapshots" / OLDER)
+
+
+def test_an_empty_diffusion_weight_is_judged_like_an_empty_checkpoint(tmp_path, monkeypatch):
+ """A diffusion .safetensors names no family either, and the walk counts a non-empty one as
+ payload. An empty one has to count the same way, or the newer snapshot holding it wins the
+ selection and the pinned load opens a zero-byte weight."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "diffusion_pytorch_model.safetensors": b"\0" * 256,
+ },
+ NEWER: {
+ "config.json": b'{"model_type":"llama"}',
+ "diffusion_pytorch_model.safetensors": b"",
+ },
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["load_id"] == str(repo_dir / "snapshots" / OLDER)
+
+
+def test_a_family_in_a_subdirectory_does_not_stand_in_for_the_root_one(tmp_path, monkeypatch):
+ """from_pretrained reads the snapshot root and fails on the index it finds there. It does not
+ go looking for an unrelated set under backup/, so that set cannot vouch for the row."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ "backup/model-00001-of-00002.safetensors": b"\0" * 64,
+ "backup/model-00002-of-00002.safetensors": b"\0" * 64,
+ "backup/model.safetensors.index.json": _SHARD_INDEX,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_layout_that_keeps_every_weight_in_a_subdirectory_cannot_serve_the_root(
+ tmp_path, monkeypatch
+):
+ """Companion to the test above: from_pretrained opens the names it finds at the snapshot root,
+ so a set that lives only under backup/ is not one the pinned load can reach either. A layout
+ that genuinely keeps its weights in subdirectories names no family this walk groups, so it is
+ carried by the ungrouped payload rather than by this one."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "backup/model-00001-of-00002.safetensors": b"\0" * 64,
+ "backup/model-00002-of-00002.safetensors": b"\0" * 64,
+ "backup/model.safetensors.index.json": _SHARD_INDEX,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_an_unsharded_weight_under_a_subdirectory_does_not_serve_the_root(tmp_path, monkeypatch):
+ """The unsharded twin of the test above. A lone backup/adapter_model.safetensors is not the
+ name peft opens at the snapshot root, so it cannot make the pinned snapshot loadable."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "backup/adapter_model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_config_the_loader_cannot_open_by_name_does_not_classify(tmp_path, monkeypatch):
+ """The loaders open config.json by its exact path, so on a case-sensitive volume a Config.json
+ is not the file they find. The filesystem answers that, not a lowercased basename."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {"Config.json": b'{"model_type":"llama"}', "model.safetensors": b"\0" * 256}
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ probe = tmp_path / "case-probe"
+ probe.mkdir()
+ (probe / "A").write_bytes(b"")
+ case_sensitive = not (probe / "a").is_file()
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ if case_sensitive:
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+ else:
+ assert rows[0]["partial"] is False
+
+
+def test_a_weight_the_loader_cannot_open_by_name_does_not_serve(tmp_path, monkeypatch):
+ """Same rule as the config above, for the weight itself: the loader opens these names by exact
+ path, so on a case-sensitive volume MODEL.SAFETENSORS is not the file it finds."""
+ probe = tmp_path / "case-probe"
+ probe.mkdir()
+ (probe / "A").write_bytes(b"")
+ case_sensitive = not (probe / "a").is_file()
+
+ for config, weight in (
+ ('{"model_type":"llama"}', "MODEL.SAFETENSORS"),
+ ('{"model_type":"llama"}', "PyTorch_Model.bin"),
+ ('{"peft_type":"LORA"}', "ADAPTER_MODEL.SAFETENSORS"),
+ ):
+ root = tmp_path / weight.replace(".", "_")
+ config_name = "adapter_config.json" if "peft_type" in config else "config.json"
+ _repo_with(
+ root,
+ snapshots = {OLDER: {config_name: config.encode(), weight: b"\0" * 256}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is case_sensitive
+ assert rows[0]["capabilities"]["can_chat"] is not case_sensitive
+
+
+def test_a_weight_under_the_wrong_case_does_not_hide_one_under_the_right_case(
+ tmp_path, monkeypatch
+):
+ """Control: the name the loader opens decides, beside a miscased copy or later in the chain."""
+ for extra in ({"model.safetensors": b"\0" * 256}, {"pytorch_model.bin": b"\0" * 256}):
+ root = tmp_path / next(iter(extra)).replace(".", "_")
+ _repo_with(
+ root,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "MODEL.SAFETENSORS": b"\0" * 256,
+ **extra,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_root_index_naming_shards_in_a_subdirectory_still_serves(tmp_path, monkeypatch):
+ """The loader resolves every weight_map entry against the index it selected, so a canonical root
+ index pointing into weights/ is one it can load. Only the index's own paths are judged."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _shard_index(
+ "weights/model-00001-of-00001.safetensors"
+ ),
+ "weights/model-00001-of-00001.safetensors": b"\0" * 64,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_canonical_index_with_no_shards_is_not_skipped_for_the_bin(tmp_path, monkeypatch):
+ """_get_resolved_checkpoint_files tries model.safetensors.index.json before pytorch_model.bin,
+ and the branches are exclusive, so a whole .bin beside an index whose shards were never
+ recovered is not the file the loader reaches."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model.bin": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_bin_with_no_safetensors_index_beside_it_still_serves(tmp_path, monkeypatch):
+ """Control for the test above: with no safetensors name of any kind, pytorch_model.bin is the
+ file the loader reaches."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model.bin": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_family_behind_an_alternate_index_name_is_not_visible(tmp_path, monkeypatch):
+ """transformers probes model.safetensors.index.json, never model-copy.safetensors.index.json, so
+ a set behind the alternate name is one the pinned load never opens."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-copy-00001-of-00001.safetensors": b"\0" * 64,
+ "model-copy.safetensors.index.json": _shard_index(
+ "model-copy-00001-of-00001.safetensors"
+ ),
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_an_alternate_index_family_does_not_rescue_a_broken_canonical_one(tmp_path, monkeypatch):
+ """Same reason from the other side: the loader opens the canonical index, fails on the shard it
+ is short, and never reaches the alternate set sitting beside it."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ "model-copy-00001-of-00001.safetensors": b"\0" * 64,
+ "model-copy.safetensors.index.json": _shard_index(
+ "model-copy-00001-of-00001.safetensors"
+ ),
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_an_empty_canonical_weight_is_not_excused_by_another_root_file(tmp_path, monkeypatch):
+ """_get_resolved_checkpoint_files opens model.safetensors first and pytorch_model.bin next, and
+ falls back to neither once the name it picked exists. A whole consolidated.safetensors beside an
+ empty model.safetensors therefore vouches for nothing."""
+ for empty, whole in (
+ ("model.safetensors", "consolidated.safetensors"),
+ ("pytorch_model.bin", "consolidated.bin"),
+ ):
+ root = tmp_path / empty.replace(".", "_")
+ _repo_with(
+ root,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ empty: b"",
+ whole: b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_whole_canonical_weight_beside_another_root_file_still_serves(tmp_path, monkeypatch):
+ """Control for the test above: with the name the loader picks whole, the second root file is
+ beside the point."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "consolidated.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_torn_quant_does_not_veto_the_weights_row_beside_it(tmp_path, monkeypatch):
+ """The weights row loads model.safetensors and never opens a .gguf, so an interrupted quant
+ download beside it says nothing about the row."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "Model-Q4_K_M-00001-of-00002.gguf": b"GGUF" + b"\0" * 252,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_whole_quant_does_not_vouch_for_the_weights_row_beside_it(tmp_path, monkeypatch):
+ """The converse: a complete quant is not evidence that a shard-short safetensors set loads."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _shard_index(
+ "model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"
+ ),
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "Model-Q8_0.gguf": b"GGUF" + b"\0" * 252,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_root_weight_under_a_name_the_loader_never_opens_does_not_serve(tmp_path, monkeypatch):
+ """The loader probes model.safetensors, its index, pytorch_model.bin and its index, and peft
+ only the singular adapter_model.*; every other root name is one nothing opens, however whole."""
+ for config, weight in (
+ ('{"model_type":"llama"}', "consolidated.safetensors"),
+ ('{"model_type":"llama"}', "consolidated.bin"),
+ ('{"model_type":"llama"}', "model.fp16.safetensors"),
+ ('{"peft_type":"LORA"}', "adapter_model_v2.safetensors"),
+ ):
+ root = tmp_path / weight.replace(".", "_")
+ config_name = "adapter_config.json" if "peft_type" in config else "config.json"
+ _repo_with(
+ root,
+ snapshots = {OLDER: {config_name: config.encode(), weight: b"\0" * 256}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_root_weight_the_loader_never_opens_does_not_veto_the_name_it_does(tmp_path, monkeypatch):
+ """Control: an unopened name is no evidence, so the next name in the chain still decides."""
+ for extra in ({"pytorch_model.bin": b"\0" * 256}, {"model.safetensors": b"\0" * 256}):
+ root = tmp_path / next(iter(extra)).replace(".", "_")
+ _repo_with(
+ root,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "consolidated.safetensors": b"\0" * 256,
+ **extra,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_an_ungroupable_payload_under_a_subdirectory_does_not_serve_the_root(tmp_path, monkeypatch):
+ """A .ckpt or diffusion weight names no family this walk groups, which exempts it from the
+ family checks. That exemption only holds at the snapshot root: the loader cannot discover one
+ under backup/ any more than it can a nested shard set."""
+ for weights in ("backup/model.ckpt", "backup/diffusion_pytorch_model.safetensors"):
+ root = tmp_path / weights.replace("/", "_")
+ _repo_with(
+ root,
+ snapshots = {OLDER: {"config.json": b'{"model_type":"llama"}', weights: b"\0" * 256}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_root_ungroupable_payload_is_not_vetoed_by_a_nested_copy(tmp_path, monkeypatch):
+ """Control for the test above: the root holds one the loader opens, so a second copy
+ underneath it is beside the point."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.ckpt": b"\0" * 256,
+ "backup/model.ckpt": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_an_unsharded_weight_at_the_root_beside_a_nested_copy_still_serves(tmp_path, monkeypatch):
+ """Control for the test above: the root holds the name the loader opens, so a second copy
+ underneath it changes nothing."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "backup/model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_config_in_a_subdirectory_does_not_serve_the_snapshot_root(tmp_path, monkeypatch):
+ """The pin names the snapshot root, and from_pretrained opens the config there. A copy under
+ backup/ is not the one that load finds, so it cannot classify the snapshot as loadable."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "backup/config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_nested_config_beside_the_root_one_leaves_the_row_alone(tmp_path, monkeypatch):
+ """Negative control: the root config is what the loader opens, so a second copy underneath it
+ changes nothing."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "backup/config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+ assert rows[0]["load_id"] == str(repo_dir / "snapshots" / OLDER)
+
+
+def test_a_nested_adapter_config_does_not_serve_the_snapshot_root(tmp_path, monkeypatch):
+ """peft resolves adapter_config.json at the directory it is handed, the same as the base
+ loader, so a nested copy cannot classify the snapshot as an adapter either."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "backup/adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows == [] or rows[0]["partial"] is True
+
+
+def test_a_broken_active_copy_withholds_the_compatibility_row(tmp_path, monkeypatch):
+ """The compatibility model list carries no path, so a client loads by id out of the active
+ cache. With a broken copy there, publishing another cache's copy under the same id offers a
+ load that follows the broken one. The Hub inventory still lists it, with a path."""
+ import asyncio
+
+ import routes.models as models_route
+
+ active, legacy = tmp_path / "active", tmp_path / "legacy"
+ whole = {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ }
+ torn = dict(whole)
+ del torn["model-00002-of-00002.safetensors"]
+ # Active: half a set behind a dangling ref. Legacy: the same repo, whole.
+ _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(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = active),
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
+ inventory_scan.invalidate_hf_cache_scans()
+
+ response = asyncio.run(
+ models_route.list_cached_models(current_subject = "test-user", hf_token = None)
+ )
+ cached = response["cached"] if isinstance(response, dict) else response.cached
+ 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(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = legacy),
+ )
+ monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: legacy)
+ inventory_scan.invalidate_hf_cache_scans()
+
+ response = asyncio.run(
+ models_route.list_cached_models(current_subject = "test-user", hf_token = None)
+ )
+ cached = response["cached"] if isinstance(response, dict) else response.cached
+ assert len(cached) == 1
+
+
+def test_a_config_that_parses_still_proves_a_payload(tmp_path, monkeypatch):
+ """Negative control for the test above: the same shape with a readable config."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model-00002-of-00002.safetensors": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_whole_payload_under_a_resolving_ref_is_still_chattable(tmp_path, monkeypatch):
+ """Negative control for the test above: same shape, but the pinned payload is whole."""
+ repo_dir = _two_snapshot_repo(
+ tmp_path,
+ older_files = {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model-00002-of-00002.safetensors": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ newer_files = {"README.md": b"probe"},
+ ref = OLDER,
+ )
+ (repo_dir / "blobs" / "deadbeef.incomplete").write_bytes(b"\0" * 8)
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+_WHOLE_SHARDS = {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model-00002-of-00002.safetensors": b"\0" * 256,
+}
+
+
+ ("index", "torn"),
+ [
+ pytest.param(_SHARD_INDEX, False, id = "a-map-naming-both-shards"),
+ pytest.param(
+ b'{"metadata": {}, "weight_map": {"w0": "model-00001-of-0',
+ True,
+ id = "an-index-truncated-mid-write",
+ ),
+ pytest.param(
+ _shard_index("model-00001-of-00003.safetensors"),
+ True,
+ id = "a-map-naming-a-shard-that-is-not-here",
+ ),
+ pytest.param(b'{"metadata": {}}', True, id = "an-index-with-no-weight-map"),
+ pytest.param(
+ _shard_index("model-00001-of-00002.safetensors"),
+ True,
+ id = "a-map-covering-only-part-of-the-numbered-family",
+ ),
+ pytest.param(_shard_index(), True, id = "a-map-naming-nothing"),
+ pytest.param(
+ _shard_index("../../elsewhere.safetensors"),
+ True,
+ id = "a-map-reaching-outside-the-snapshot",
+ ),
+ ],
+)
+def test_a_shard_index_has_to_resolve_before_the_family_counts(tmp_path, monkeypatch, index, torn):
+ """Present and non-empty is not enough: the index must parse and every weight_map name must
+ resolve, or the numbered files read as a whole family that nothing can load."""
+ _repo_with(
+ tmp_path,
+ snapshots = {SNAPSHOT: {**_WHOLE_SHARDS, "model.safetensors.index.json": index}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is torn
+ assert rows[0]["capabilities"]["can_chat"] is not torn
+
+
+ ("files", "torn"),
+ [
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model.bin": b"\0" * 256,
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _shard_index(
+ "model-00001-of-00002.safetensors", "model-00009-of-00009.safetensors"
+ ),
+ },
+ True,
+ id = "a-whole-bin-cannot-vouch-for-a-broken-safetensors-index",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model.bin": b"\0" * 256,
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ False,
+ id = "the-same-shape-with-an-index-that-resolves",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _shard_index(
+ "model-00001-of-00002.safetensors", "model-00009-of-00009.safetensors"
+ ),
+ },
+ False,
+ id = "a-whole-model-safetensors-is-picked-before-any-index",
+ ),
+ pytest.param(
+ {"config.json": b'{"model_type":"llama"}', "pytorch_model.bin": b"\0" * 256},
+ False,
+ id = "a-whole-bin-with-nothing-safetensors-beside-it",
+ ),
+ pytest.param(
+ {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model-00001-of-00002.safetensors": b"\0" * 64,
+ "adapter_model-00002-of-00002.safetensors": b"\0" * 64,
+ },
+ True,
+ id = "a-numbered-adapter-set-with-every-file-present",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model.ckpt": b"\0" * 256,
+ "adapter_model.bin": b"\0" * 128,
+ },
+ False,
+ id = "a-whole-ckpt-payload-beside-a-stray-adapter-file",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "diffusion_pytorch_model.safetensors": b"\0" * 256,
+ "adapter_model.bin": b"\0" * 128,
+ },
+ False,
+ id = "a-diffusion-payload-beside-a-stray-adapter-file",
+ ),
+ pytest.param(
+ {"config.json": b'{"model_type":"llama"}', "adapter_model.bin": b"\0" * 128},
+ True,
+ id = "an-adapter-file-standing-in-for-base-weights-that-are-not-here",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "pytorch_model.bin": b"\0" * 256,
+ },
+ False,
+ id = "index-less-shards-are-looked-past-to-the-whole-bin",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ },
+ True,
+ id = "index-less-shards-with-nothing-else-to-fall-back-to",
+ ),
+ pytest.param(
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "optimizer.bin": b"\0" * 256,
+ "adapter_model.bin": b"\0" * 128,
+ },
+ True,
+ id = "a-training-artefact-is-not-a-payload-either",
+ ),
+ pytest.param(
+ {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"\0" * 256,
+ },
+ False,
+ id = "the-singular-name-peft-resolves",
+ ),
+ pytest.param(
+ {"adapter_config.json": b'{"peft_type":"LORA"}', "adapter_model.bin": b"\0" * 256},
+ False,
+ id = "the-singular-pickle-name",
+ ),
+ pytest.param(
+ {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"\0" * 256,
+ "adapter_model-00001-of-00002.safetensors": b"\0" * 64,
+ },
+ False,
+ id = "a-whole-singular-adapter-beside-a-numbered-set",
+ ),
+ ],
+)
+def test_the_family_a_loader_would_pick_is_the_one_judged(tmp_path, monkeypatch, files, torn):
+ """transformers takes model.safetensors, then its index, then pytorch_model.bin, and never falls
+ back once one matches, so a whole .bin cannot vouch for a broken safetensors index. peft
+ resolves only the singular adapter names and has no shard path, so numbered sets never load."""
+ _repo_with(tmp_path, snapshots = {SNAPSHOT: files}, refs = {"main": UPSTREAM_HEAD})
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is torn
+ assert rows[0]["capabilities"]["can_chat"] is not torn
+
+
+def test_the_load_id_pins_the_whole_snapshot_when_the_default_ref_is_torn(tmp_path, monkeypatch):
+ """Recovery fires off a secondary dangling ref while refs/main resolves to a torn revision, and
+ that revision classifies, so membership alone would hand the row back to the half download."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {**_WHOLE_SHARDS, "model.safetensors.index.json": _SHARD_INDEX},
+ NEWER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ },
+ refs = {"main": NEWER, "stale": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+ assert rows[0]["load_id"] == str(repo_dir / "snapshots" / OLDER)
+
+
+def test_the_load_id_stays_the_repo_id_when_the_default_ref_is_whole(tmp_path, monkeypatch):
+ """Control: where refs/main lands on the complete payload the repo id is what loads."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ NEWER: {**_WHOLE_SHARDS, "model.safetensors.index.json": _SHARD_INDEX},
+ },
+ refs = {"main": NEWER, "stale": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+ assert rows[0]["load_id"] == "Org/Model"
+
+
+def test_a_payload_split_across_snapshots_is_not_advertised_runnable(tmp_path, monkeypatch):
+ """The payload flags are OR-ed over every revision, so config.json in one snapshot and the
+ weights in another look runnable while no single directory can serve the row. With no
+ self-contained snapshot and no refs/main, from_pretrained(repo_id) resolves to nothing."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {"model.safetensors": b"\0" * 256},
+ NEWER: {"config.json": b'{"model_type":"llama"}'},
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ name = "models--Org--Split",
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [r["repo_id"] for r in rows] == ["Org/Split"]
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_complete_quant_family_does_not_vouch_for_a_torn_sibling(tmp_path):
+ """One quant label can cover several shard families and the lister offers only the
+ lexicographically first file under it, so grouping on the shard total alone let the complete B
+ family mark the torn A file downloadable."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ for name in (
+ "A-Q4_K_M-00001-of-00002.gguf",
+ "B-Q4_K_M-00001-of-00002.gguf",
+ "B-Q4_K_M-00002-of-00002.gguf",
+ ):
+ (snapshot / name).write_bytes(b"\0" * 64)
+ from hub.utils.gguf import list_local_gguf_variants
+
+ advertised = {v.filename for v in list_local_gguf_variants(str(snapshot))[0]}
+ assert advertised == {"A-Q4_K_M-00001-of-00002.gguf"}
+ assert inventory_scan._completed_gguf_variants(snapshot) == set()
+
+
+def test_a_big_endian_build_does_not_vouch_for_a_torn_little_endian_quant(tmp_path):
+ """The lister never offers a big-endian build, so it must not make the little-endian quant of
+ the same name look complete either."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "Model-Q8_0-BE.gguf").write_bytes(b"\0" * 64)
+ (snapshot / "Model-Q8_0-00001-of-00002.gguf").write_bytes(b"\0" * 64)
+ assert inventory_scan._completed_gguf_variants(snapshot) == set()
+
+
+def _local_offer(snapshot: Path) -> list:
+ """What GET /api/models/gguf-variants reports for a directory path, the shape of a snapshot load
+ id."""
+ import asyncio
+
+ from hub.services.models import gguf_variants
+
+ response = asyncio.run(
+ gguf_variants.get_gguf_variants_response(str(snapshot), prefer_local_cache = True)
+ )
+ return sorted((v.quant, bool(v.downloaded)) for v in response.variants)
+
+
+def test_a_torn_quant_is_not_reported_downloaded_under_a_snapshot_load_id(tmp_path):
+ """The load id is an absolute snapshot path and get_gguf_variants_response short-circuits on
+ is_local_path, so the completeness check has to live at that shared offer site. The torn quant
+ stays listed to resume or delete; it just is not offered as ready."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "Model-Q8_0.gguf").write_bytes(b"\0" * 64)
+ (snapshot / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 16)
+ assert _local_offer(snapshot) == [("Q4_K_M", False), ("Q8_0", True)]
+
+
+def test_a_big_endian_sibling_does_not_make_a_torn_quant_downloadable(tmp_path):
+ """End to end for the completion walk: the lister drops the big-endian build and offers the torn
+ little-endian file under the same label, so counting the big-endian one complete marked it
+ ready."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "model-Q4_K_M-be.gguf").write_bytes(b"\0" * 64)
+ (snapshot / "model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 16)
+ assert _local_offer(snapshot) == [("Q4_K_M", False)]
+
+
+def test_a_resume_only_folder_still_lists_when_nothing_is_complete(tmp_path):
+ """A folder holding only a half-fetched download still shows up so it can be resumed or deleted,
+ rather than vanishing from the picker."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 16)
+ assert _local_offer(snapshot) == [("Q4_K_M", False)]
+
+
+def test_a_whole_folder_is_still_reported_downloaded(tmp_path):
+ """Negative control: completeness must not make a good folder look broken."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ (snapshot / "Model-Q8_0.gguf").write_bytes(b"\0" * 64)
+ (snapshot / "Model-Q4_K_M-00001-of-00002.gguf").write_bytes(b"\0" * 16)
+ (snapshot / "Model-Q4_K_M-00002-of-00002.gguf").write_bytes(b"\0" * 16)
+ assert _local_offer(snapshot) == [("Q4_K_M", True), ("Q8_0", True)]
+
+
+def test_the_ignored_cache_entries_track_huggingface_hub(tmp_path):
+ """huggingface_hub 1.x skips Thumbs.db and desktop.ini as well as .DS_Store. Hardcoding the
+ older set meant an Explorer artefact in snapshots/ made the recovery decline a repo a newer hub
+ had dropped for the dangling ref alone."""
+ from huggingface_hub.utils import _cache_manager
+
+ upstream = getattr(_cache_manager, "FILES_TO_IGNORE", None)
+ if not upstream:
+ pytest.skip("this huggingface_hub does not export FILES_TO_IGNORE")
+ assert set(inventory_scan._CACHE_ENTRIES_TO_IGNORE) == set(upstream)
+
+
+def _primary_gguf_predicates(rel_paths: list[str]) -> dict:
+ """Both copies of the primary-GGUF classification, fed one revision whose files sit at
+ *rel_paths* under the snapshot. huggingface_hub records only the bare file_name, so a companion
+ is identifiable from file_path alone."""
+ from types import SimpleNamespace
+
+ from hub.services.models import cache_inventory
+ from routes import models as models_route
+
+ files = [
+ SimpleNamespace(
+ file_path = f"/cache/models--Org--Model/snapshots/{SNAPSHOT}/{rel}",
+ file_name = rel.rsplit("/", 1)[-1],
+ size_on_disk = 64,
+ blob_path = None,
+ blob_last_modified = 1.0,
+ )
+ for rel in rel_paths
+ ]
+ repo_info = SimpleNamespace(
+ repo_path = None,
+ revisions = [SimpleNamespace(commit_hash = SNAPSHOT, snapshot_path = "/s", files = files)],
+ )
+ return {
+ "inventory": cache_inventory._repo_gguf_size_bytes(repo_info),
+ "route": models_route._repo_gguf_size_bytes(repo_info),
+ }
+
+
+ "rel_paths",
+ [
+ ["MTP/drafter-Q4_K_M.gguf"],
+ ["mtp-model-Q8_0.gguf"],
+ ["mmproj-F16.gguf"],
+ ],
+)
+def test_a_companion_only_repo_is_not_a_gguf_model(rel_paths):
+ """An MTP drafter or a vision projector is a companion, never a loadable weight. Counting one
+ made the repo a chattable GGUF row with no selectable variant, and hid a real Transformers model
+ sharing the repo behind a GGUF that does not exist."""
+ assert _primary_gguf_predicates(rel_paths) == {"inventory": 0, "route": 0}
+
+
+def test_a_companion_beside_a_real_quant_is_not_counted_twice():
+ """Negative control: the companion drops out of the size, the primary weight still makes the
+ repo a GGUF model."""
+ assert _primary_gguf_predicates(["Model-Q4_K_M.gguf", "MTP/drafter-Q4_K_M.gguf"]) == {
+ "inventory": 64,
+ "route": 64,
+ }
+
+
+def test_the_two_primary_gguf_predicates_agree():
+ """routes.models keeps its own copy for the compatibility route. They drifted once already; a
+ disagreement means one endpoint lists a repo the other hides."""
+ from routes import models as models_route
+ from hub.services.models import common
+
+ names = [
+ "Model-Q4_K_M.gguf",
+ "MTP/drafter-Q4_K_M.gguf",
+ "mtp-model-Q8_0.gguf",
+ "mmproj-F16.gguf",
+ "config.json",
+ ]
+ assert [models_route._is_main_gguf_filename(n) for n in names] == [
+ common._is_main_gguf_filename(n) for n in names
+ ]
+
+
+def test_an_mtp_only_recovered_repo_does_not_become_a_chattable_gguf_row(tmp_path, monkeypatch):
+ """End to end for the recovery path. Un-hiding a repo behind a dangling ref must not classify it
+ more loosely than a healthy one: with only a drafter in the snapshot there is nothing to
+ load."""
+ _repo_with(
+ tmp_path,
+ snapshots = {SNAPSHOT: {"MTP/drafter-Q4_K_M.gguf": b"\0" * 64}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ assert _autoload_rows(tmp_path, monkeypatch, gguf = True) == []
+
+
+def test_an_all_incomplete_repo_is_offered_by_repo_id_as_partial(tmp_path, monkeypatch):
+ """The lister returns its untrimmed offer when no snapshot holds a whole quant, so the repo
+ stays manageable. That fallback carried no completeness set, so every torn quant reached the
+ repo-id caller marked ready, and Settings/Agents filters on the per-variant flag."""
+ import asyncio
+ from types import SimpleNamespace
+
+ from hub.services.models import gguf_variants
+
+ _repo_with(
+ tmp_path,
+ 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(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = tmp_path),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ response = asyncio.run(
+ gguf_variants.get_gguf_variants_response("Org/Model", prefer_local_cache = True)
+ )
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+ assert [(v.quant, bool(v.downloaded), bool(v.partial)) for v in response.variants] == [
+ ("Q4_K_M", False, True)
+ ]
+
+
+def test_a_whole_repo_is_still_offered_by_repo_id_as_downloaded(tmp_path, monkeypatch):
+ """Negative control for the fallback: passing the completeness set through must not demote a
+ repo whose quant is actually whole."""
+ import asyncio
+ from types import SimpleNamespace
+
+ from hub.services.models import gguf_variants
+
+ _repo_with(
+ tmp_path,
+ 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(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = tmp_path),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ response = asyncio.run(
+ gguf_variants.get_gguf_variants_response("Org/Model", prefer_local_cache = True)
+ )
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+ assert [(v.quant, bool(v.downloaded), bool(v.partial)) for v in response.variants] == [
+ ("Q4_K_M", True, False)
+ ]
+
+
+def _split_payload_rows(tmp_path, monkeypatch, *, where: str, refs: dict) -> list[dict]:
+ """A repo whose config.json and weights sit in DIFFERENT snapshots, so no single directory can
+ serve a load, placed in the active or in a legacy cache."""
+ from types import SimpleNamespace
+
+ from hub.services.models import cache_inventory
+
+ active = tmp_path / "active"
+ legacy = tmp_path / "legacy"
+ active.mkdir()
+ legacy.mkdir()
+ _repo_with(
+ active if where == "active" else legacy,
+ snapshots = {
+ SNAPSHOT: {"config.json": b'{"model_type":"llama"}'},
+ OLDER: {"model.safetensors": b"\0" * 256},
+ },
+ refs = refs,
+ )
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = active),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ return cache_inventory._scan_cached_models()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+
+
[email protected]("where", ["active", "legacy"])
+ "ref_label, refs",
+ [
+ ("dangling", {"main": UPSTREAM_HEAD}),
+ ("resolves-to-the-config-half", {"main": SNAPSHOT}),
+ ("resolves-to-the-weights-half", {"main": OLDER}),
+ ("no-refs", {}),
+ ],
+)
+def test_a_split_payload_is_partial_wherever_it_is_cached(
+ where, ref_label, refs, tmp_path, monkeypatch
+):
+ """The payload flags are OR-ed over revisions, so a repo holding config.json in one snapshot and
+ the weights in another reads as runnable while nothing on disk can serve it. Neither the cache it
+ sits in nor the state of refs/main changes that: a resolving ref only ever lands on one half,
+ since a directory that could serve the payload would be a payload snapshot."""
+ rows = _split_payload_rows(tmp_path, monkeypatch, where = where, refs = refs)
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
[email protected]("where", ["active", "legacy"])
+ "ref_label, refs", [("dangling", {"main": UPSTREAM_HEAD}), ("resolving", {"main": SNAPSHOT})]
+)
+def test_a_self_contained_snapshot_is_not_made_partial_by_a_second_one(
+ where, ref_label, refs, tmp_path, monkeypatch
+):
+ """The negative control that matters most: one snapshot holds a whole payload and a second holds
+ only weights, so a payload snapshot exists and the row stays chattable."""
+ from types import SimpleNamespace
+
+ from hub.services.models import cache_inventory
+
+ active = tmp_path / "active"
+ legacy = tmp_path / "legacy"
+ active.mkdir()
+ legacy.mkdir()
+ _repo_with(
+ active if where == "active" else legacy,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ },
+ OLDER: {"model.safetensors": b"\0" * 256},
+ },
+ refs = refs,
+ )
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [active, legacy])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = active),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ rows = cache_inventory._scan_cached_models()
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def _snapshot_with(tmp_path, files: dict) -> Path:
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ for name, size in files.items():
+ (snapshot / name).write_bytes(b"\0" * size)
+ return snapshot
+
+
+def test_a_torn_sibling_family_does_not_veto_the_quant_that_loads(tmp_path):
+ """Two families can share one quant label. The lister offers the lexicographically first file
+ and the loader loads that family alone, so the torn z- set beside a whole a-Q4_K_M.gguf is
+ never selected and must not make the label unavailable."""
+ snapshot = _snapshot_with(
+ tmp_path,
+ {"a-Q4_K_M.gguf": 64, "z-Q4_K_M-00001-of-00002.gguf": 16},
+ )
+ assert inventory_scan._completed_gguf_variants(snapshot) == {"Q4_K_M"}
+ assert _local_offer(snapshot) == [("Q4_K_M", True)]
+
+
+def test_a_whole_sibling_family_does_not_vouch_for_the_torn_one_that_loads(tmp_path):
+ """The other direction, which is why this keys on the selected family rather than on any
+ complete one: the torn set sorts first, so that is what the loader picks."""
+ snapshot = _snapshot_with(
+ tmp_path,
+ {"a-Q4_K_M-00001-of-00002.gguf": 16, "z-Q4_K_M.gguf": 64},
+ )
+ assert inventory_scan._completed_gguf_variants(snapshot) == set()
+ assert _local_offer(snapshot) == [("Q4_K_M", False)]
+
+
+def test_the_selected_family_is_judged_on_its_own_shards(tmp_path):
+ """A complete split set selected ahead of a torn sibling stays complete: the missing shard
+ belongs to a family nothing reads."""
+ snapshot = _snapshot_with(
+ tmp_path,
+ {
+ "a-Q4_K_M-00001-of-00002.gguf": 16,
+ "a-Q4_K_M-00002-of-00002.gguf": 16,
+ "z-Q4_K_M-00001-of-00003.gguf": 16,
+ },
+ )
+ assert inventory_scan._completed_gguf_variants(snapshot) == {"Q4_K_M"}
+
+
+def test_two_torn_families_under_one_label_stay_incomplete(tmp_path):
+ """Control: selecting one family must not turn two broken sets into a load."""
+ snapshot = _snapshot_with(
+ tmp_path,
+ {"a-Q4_K_M-00001-of-00002.gguf": 16, "z-Q4_K_M-00001-of-00002.gguf": 16},
+ )
+ assert inventory_scan._completed_gguf_variants(snapshot) == set()
+
+
+def test_a_nonsensical_shard_spec_is_never_complete(tmp_path):
+ """A shard numbered past its own total cannot be loaded, and an empty index set must not read
+ as a satisfied range."""
+ snapshot = _snapshot_with(tmp_path, {"Model-Q4_K_M-00003-of-00002.gguf": 16})
+ assert inventory_scan._completed_gguf_variants(snapshot) == set()
+
+
+def test_the_loader_and_the_inventory_break_an_mtime_tie_the_same_way(tmp_path):
+ """Two snapshots can carry the same mtime, and mtime alone is not a total order. The inventory
+ pins by (mtime, resolved path); the loader's walk let filesystem order settle the rest, so the
+ row could advertise one revision while /load read weights from the other."""
+ import os
+
+ from hub.utils.hf_cache_state import latest_snapshot_dir
+ from utils.models.model_config import _iter_hf_cache_snapshots
+
+ cache = tmp_path / "hub"
+ repo = _repo_with(
+ cache,
+ snapshots = {
+ SNAPSHOT: {"Model-Q4_K_M.gguf": b"\0" * 64},
+ OLDER: {"Model-Q4_K_M.gguf": b"\0" * 64},
+ },
+ refs = {"main": SNAPSHOT},
+ )
+ stamp = 1_700_000_000
+ for commit in (SNAPSHOT, OLDER):
+ os.utime(repo / "snapshots" / commit, (stamp, stamp))
+ assert len({(repo / "snapshots" / c).stat().st_mtime for c in (SNAPSHOT, OLDER)}) == 1
+
+ loader_order = list(_iter_hf_cache_snapshots("Org/Model", cache_dir = cache))
+ assert loader_order, "the loader must still find the snapshots"
+ assert loader_order[0] == latest_snapshot_dir(repo)
+
+
+def test_the_two_snapshot_orderings_agree_on_every_permutation(tmp_path):
+ """The keys must be one ordering, not merely agree on the winner: a caller taking the
+ second-newest has to see the same sequence."""
+ import os
+
+ from hub.utils.hf_cache_state import snapshot_selection_key
+ from utils.models.model_config import _snapshot_selection_key
+
+ cache = tmp_path / "hub"
+ commits = [c * 40 for c in "abcd"]
+ repo = _repo_with(
+ cache,
+ snapshots = {c: {"Model-Q4_K_M.gguf": b"\0" * 64} for c in commits},
+ refs = {"main": commits[0]},
+ )
+ stamp = 1_700_000_000
+ for index, commit in enumerate(commits):
+ # Two pairs at equal mtimes, so ties decide half the ordering.
+ moment = stamp + (index // 2)
+ os.utime(repo / "snapshots" / commit, (moment, moment))
+
+ snapshots = sorted((repo / "snapshots").iterdir())
+ assert [snapshot_selection_key(s) for s in snapshots] == [
+ _snapshot_selection_key(s) for s in snapshots
+ ]
+ assert list(_iter_hf_cache_snapshots_names(cache)) == [
+ s.name for s in sorted(snapshots, key = snapshot_selection_key, reverse = True)
+ ]
+
+
+def _iter_hf_cache_snapshots_names(cache: Path) -> list[str]:
+ from utils.models.model_config import _iter_hf_cache_snapshots
+ return [s.name for s in _iter_hf_cache_snapshots("Org/Model", cache_dir = cache)]
+
+
+ "ref_label, refs", [("dangling", {"main": UPSTREAM_HEAD}), ("resolving", {"main": SNAPSHOT})]
+)
+def test_a_stray_base_shard_does_not_veto_a_complete_adapter(
+ ref_label, refs, tmp_path, monkeypatch
+):
+ """A LoRA snapshot can carry an unrelated interrupted base family. The row classifies as an
+ adapter and the adapter is whole, so it loads; judging base first regardless of format let that
+ stray shard veto it. No config.json is what says this snapshot can only be an adapter."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"\0" * 128,
+ "pytorch_model-00001-of-00002.bin": b"\0" * 64,
+ }
+ },
+ refs = refs,
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["model_format"] == "adapter"
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+ "files, cannot_serve",
+ [
+ # A real transformers file beside a config.json outranks the adapter, so the torn base
+ # decides and the whole adapter cannot stand in.
+ (
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "adapter_config.json": b"{}",
+ "adapter_model.safetensors": b"\0" * 64,
+ },
+ True,
+ ),
+ # Same two configs, but the only real weights are the adapter's, so this loads as adapter.
+ (
+ {
+ "config.json": b"{}",
+ "pytorch_model-00001-of-00002.bin": b"\0" * 64,
+ "adapter_config.json": b"{}",
+ "adapter_model.safetensors": b"\0" * 64,
+ },
+ False,
+ ),
+ # A config.json that exists but is empty still classifies by name, and nothing can parse it.
+ ({"config.json": b"", "model.safetensors": b"\0" * 256}, True),
+ # Mixed extensions never form one family: two half sets are not one whole set.
+ (
+ {
+ "config.json": b"{}",
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.bin": b"\0" * 64,
+ },
+ True,
+ ),
+ # No config.json, so the row is the torn adapter and a whole base family cannot stand in.
+ (
+ {
+ "adapter_config.json": b"{}",
+ "adapter_model-00001-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors": b"\0" * 256,
+ },
+ True,
+ ),
+ ({"config.json": b"{}", "model.safetensors": b"\0" * 256}, False),
+ ],
+)
+def test_the_judged_weight_family_follows_the_row_format(files, cannot_serve, tmp_path):
+ """Both directions, so the fix cannot be read as "an adapter always rescues the snapshot"."""
+ snapshot = tmp_path / "snap"
+ snapshot.mkdir()
+ for name, payload in files.items():
+ (snapshot / name).write_bytes(payload)
+ assert inventory_scan._snapshot_lacks_a_complete_weight_family(snapshot) is cannot_serve
+
+
+def _compat_cached_models(cache_root: Path, monkeypatch) -> list[str]:
+ """GET /api/models/cached-models. Its schema has no partial and no load_id, so it can only
+ describe a repo that loads by id."""
+ import asyncio
+ from types import SimpleNamespace
+
+ import routes.models as models_route
+
+ monkeypatch.setattr(inventory_scan, "hf_cache_roots", lambda: [cache_root])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = cache_root),
+ )
+ inventory_scan.invalidate_hf_cache_scans()
+ try:
+ response = asyncio.run(
+ models_route.list_cached_models(current_subject = "tester", hf_token = None)
+ )
+ finally:
+ inventory_scan.invalidate_hf_cache_scans()
+ return [row["repo_id"] for row in response["cached"]]
+
+
+ "snapshot_files",
+ [
+ {"config.json": b"{}", "model-00001-of-00002.safetensors": b"\0" * 256},
+ {"config.json": b"{}", "model.safetensors": b"\0" * 256},
+ ],
+ ids = ["short-a-shard", "whole-but-only-loadable-by-path"],
+)
+def test_the_compatibility_route_withholds_a_recovery_it_cannot_describe(
+ snapshot_files, tmp_path, monkeypatch
+):
+ """Un-hiding a repo must not smuggle it into a response that cannot say what is wrong with it:
+ with neither partial nor a load id, a torn recovery reads as a plain cached model and a whole
+ one is offered under a repo id that does not resolve."""
+ _repo_with(tmp_path, snapshots = {SNAPSHOT: snapshot_files}, refs = {"main": UPSTREAM_HEAD})
+ assert _compat_cached_models(tmp_path, monkeypatch) == []
+ # The Hub inventory still lists it, with the fields to describe it.
+ assert [row["repo_id"] for row in _autoload_rows(tmp_path, monkeypatch)] == ["Org/Model"]
+
+
+def test_the_compatibility_route_still_lists_what_upstream_returns(tmp_path, monkeypatch):
+ """The control that bounds the gate: a repo whose refs/main resolves is one upstream already
+ returned, so it is unaffected."""
+ _repo_with(
+ tmp_path,
+ snapshots = {SNAPSHOT: {"config.json": b"{}", "model.safetensors": b"\0" * 256}},
+ refs = {"main": SNAPSHOT},
+ )
+ assert _compat_cached_models(tmp_path, monkeypatch) == ["Org/Model"]
+
+
+def test_a_recovery_whose_default_ref_resolves_is_still_listed(tmp_path, monkeypatch):
+ """Recovery also fires when a secondary ref dangles while refs/main resolves.
+ Those load by id perfectly well, so the gate must not swallow them."""
+ _repo_with(
+ tmp_path,
+ snapshots = {SNAPSHOT: {"config.json": b"{}", "model.safetensors": b"\0" * 256}},
+ refs = {"main": SNAPSHOT, "stale": UPSTREAM_HEAD},
+ )
+ assert _compat_cached_models(tmp_path, monkeypatch) == ["Org/Model"]
+
+
+ "refs, on_disk, partial",
+ [
+ # The case this fixes: refs/main resolves, so the manifest describes what a repo-id load
+ # reads and a stale ref elsewhere must not suppress it.
+ ({"main": SNAPSHOT, "stale": UPSTREAM_HEAD}, 13, True),
+ ({"main": SNAPSHOT}, 13, True),
+ # refs/main dangling is the exemption: that attempt is pinned to a revision not on disk.
+ ({"main": UPSTREAM_HEAD}, 13, False),
+ # Negative control: a stale ref must not flag a snapshot that matches.
+ ({"main": SNAPSHOT, "stale": UPSTREAM_HEAD}, 999, False),
+ ],
+ ids = ["stale-ref-beside-a-resolving-main", "no-stale-ref", "main-dangles", "matches-manifest"],
+)
+def test_a_stale_ref_does_not_suppress_the_manifest_on_the_loaded_snapshot(
+ refs, on_disk, partial, tmp_path
+):
+ """Repo-wide signals are excused only when the load target itself is absent. Keying that on any
+ dangling ref let a leftover tag hide a manifest mismatch on the very snapshot refs/main
+ resolves to, so a truncated download went out ready. Only attribution narrowed; the recovery
+ guard still keys on any ref."""
+ from hub.utils import download_manifest
+
+ repo = _repo_with(
+ tmp_path,
+ snapshots = {SNAPSHOT: {"config.json": b"{}", "model.safetensors": b"\0" * on_disk}},
+ refs = refs,
+ )
+ download_manifest.write_manifest(
+ "model",
+ "Org/Model",
+ None,
+ [download_manifest.ExpectedFile("model.safetensors", 999)],
+ "http",
+ hub_cache = tmp_path,
+ )
+ snapshot = repo / "snapshots" / SNAPSHOT
+ assert (
+ inventory_scan.is_snapshot_partial("model", "Org/Model", repo, snapshot_dir = snapshot)
+ is partial
+ )
+
+
+def test_the_compatibility_route_withholds_a_half_payload_landing(tmp_path, monkeypatch):
+ """Weights pool across revisions, so a repo can look runnable while the snapshot refs/main
+ lands on holds only the config. That directory is what an id-only caller loads, so it has to
+ classify on its own: the shard check says nothing about a snapshot carrying no weights."""
+ _repo_with(
+ tmp_path,
+ snapshots = {SNAPSHOT: {"config.json": b"{}"}, OLDER: {"model.safetensors": b"\0" * 256}},
+ refs = {"main": SNAPSHOT, "stale": UPSTREAM_HEAD},
+ )
+ assert _compat_cached_models(tmp_path, monkeypatch) == []
+
+
+def test_the_compatibility_route_lists_a_self_contained_landing(tmp_path, monkeypatch):
+ """Control for the above: the same shape with the config and the weights together in the
+ snapshot refs/main names is loadable by id and stays listed."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {"config.json": b"{}", "model.safetensors": b"\0" * 256},
+ OLDER: {"model.safetensors": b"\0" * 256},
+ },
+ refs = {"main": SNAPSHOT, "stale": UPSTREAM_HEAD},
+ )
+ assert _compat_cached_models(tmp_path, monkeypatch) == ["Org/Model"]
+
+
+def test_an_adapter_beside_a_config_json_is_still_an_adapter(tmp_path, monkeypatch):
+ """A LoRA snapshot legitimately ships the base model's config.json next to
+ adapter_config.json. Reading the config alone as "this is a base row" made a whole adapter
+ unusable whenever an unrelated torn base shard sat beside it."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"\0" * 128,
+ "pytorch_model-00001-of-00002.bin": b"\0" * 64,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["model_format"] == "adapter"
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+ "files, partial",
+ [
+ # Neither transformers family is whole; merging them made one look complete.
+ (
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.bin": b"\0" * 64,
+ },
+ True,
+ ),
+ # Control: one family whole in its own extension still loads.
+ (
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ False,
+ ),
+ # A zero-byte config.json fails to parse, whole weights or not.
+ ({"config.json": b"", "model.safetensors": b"\0" * 256}, True),
+ ],
+ ids = ["shards-split-across-extensions", "one-whole-family", "empty-config"],
+)
+def test_a_recovered_snapshot_that_cannot_load_is_not_chattable(
+ files, partial, tmp_path, monkeypatch
+):
+ """Three ways a recovered snapshot passes a shard count yet cannot be loaded."""
+ _repo_with(tmp_path, snapshots = {SNAPSHOT: files}, refs = {"main": UPSTREAM_HEAD})
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is partial
+ assert rows[0]["capabilities"]["can_chat"] is not partial
+
+
+def test_a_complete_older_snapshot_beats_a_torn_newer_one(tmp_path, monkeypatch):
+ """The payload classification is by filename, so a revision interrupted mid-download still
+ qualifies. Pinning the newest that merely classifies hid a complete older payload and made the
+ row resume-only, with can_chat false, for a model that loads."""
+ import os
+
+ repo = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {"config.json": b'{"model_type":"llama"}', "model.safetensors": b"\0" * 256},
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ },
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ os.utime(repo / "snapshots" / OLDER, (1_700_000_000, 1_700_000_000))
+ os.utime(repo / "snapshots" / SNAPSHOT, (1_700_009_999, 1_700_009_999))
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert Path(rows[0]["load_id"]) == repo / "snapshots" / OLDER
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_the_newest_snapshot_still_wins_when_both_are_complete(tmp_path, monkeypatch):
+ """Control: preferring a complete payload must not turn into preferring an older one."""
+ import os
+
+ repo = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {"config.json": b'{"model_type":"llama"}', "model.safetensors": b"\0" * 256},
+ SNAPSHOT: {"config.json": b'{"model_type":"llama"}', "model.safetensors": b"\0" * 256},
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ os.utime(repo / "snapshots" / OLDER, (1_700_000_000, 1_700_000_000))
+ os.utime(repo / "snapshots" / SNAPSHOT, (1_700_009_999, 1_700_009_999))
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert Path(rows[0]["load_id"]) == repo / "snapshots" / SNAPSHOT
+ assert rows[0]["partial"] is False
+
+
+def test_an_empty_adapter_config_is_not_loadable(tmp_path, monkeypatch):
+ """The adapter's required config gets the same treatment as config.json: recognised by name so
+ the snapshot classifies, but peft cannot parse an empty one, so whole weights are not enough."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {"adapter_config.json": b"", "adapter_model.safetensors": b"\0" * 128}
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["model_format"] == "adapter"
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_an_empty_base_config_does_not_block_an_adapter_row(tmp_path, monkeypatch):
+ """The veto is scoped to the format that has to parse the file. An adapter loads through
+ adapter_config.json, so a stray empty config.json beside it is not its problem."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b"",
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model.safetensors": b"\0" * 128,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["model_format"] == "adapter"
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_local_gguf_file_path_is_judged_on_its_directory(tmp_path):
+ """A load id can name the .gguf file itself. The lister resolves that to the parent, so the
+ completion walk has to as well: walking a regular file finds no quants, and every variant of a
+ whole local model came back partial and unofferable."""
+ folder = tmp_path / "local_model"
+ folder.mkdir()
+ (folder / "config.json").write_bytes(b'{"model_type":"llama"}')
+ (folder / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 64)
+
+ assert inventory_scan._completed_gguf_variants(folder / "Model-Q4_K_M.gguf") == {"Q4_K_M"}
+ assert _local_offer(folder / "Model-Q4_K_M.gguf") == [("Q4_K_M", True)]
+
+
+def test_a_bare_gguf_file_with_no_marker_is_not_resolved(tmp_path):
+ """The resolve only fires where the lister's does, on a parent holding one of its marker files.
+ Without one the lister offers nothing, so there is nothing to call complete either."""
+ folder = tmp_path / "loose"
+ folder.mkdir()
+ (folder / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 64)
+
+ assert inventory_scan._completed_gguf_variants(folder / "Model-Q4_K_M.gguf") == set()
+
+
+def test_an_adapter_file_does_not_stand_in_for_a_checkpoint_row(tmp_path, monkeypatch):
+ """adapter_model.bin reads as checkpoint-like, so a snapshot holding it beside a config.json
+ and no adapter_config.json classifies checkpoint. The completeness walk then accepted the
+ adapter file as that row's payload, though a checkpoint load finds no base weights."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {"config.json": b'{"model_type":"llama"}', "adapter_model.bin": b"\0" * 256}
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["model_format"] == "checkpoint"
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+ "files",
+ [
+ {"config.json": b"{}", "model.safetensors": b"\0" * 256},
+ {"adapter_config.json": b'{"peft_type":"LORA"}', "adapter_model.bin": b"\0" * 256},
+ # Classifies from the suffix while naming no family, and absence of one is not evidence.
+ {"config.json": b"{}", "diffusion_pytorch_model.safetensors": b"\0" * 256},
+ {"config.json": b"{}", "model.ckpt": b"\0" * 256},
+ ],
+ ids = ["safetensors", "adapter", "diffusion", "ckpt-file"],
+)
+def test_a_payload_whose_own_kind_is_present_stays_chattable(files, tmp_path, monkeypatch):
+ """The controls that bound the rule above: only weights of the OTHER kind standing in is
+ evidence of a mismatch, and finding no family at all is not."""
+ _repo_with(tmp_path, snapshots = {SNAPSHOT: files}, refs = {"main": UPSTREAM_HEAD})
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+ "files, partial",
+ [
+ # from_pretrained never globs, so without an index the set is unreachable.
+ (
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ },
+ True,
+ ),
+ # An empty index parses no map, so it is no better than an absent one.
+ (
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": b"",
+ },
+ True,
+ ),
+ (
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "model-00001-of-00002.safetensors": b"\0" * 64,
+ "model-00002-of-00002.safetensors": b"\0" * 64,
+ "model.safetensors.index.json": _SHARD_INDEX,
+ },
+ False,
+ ),
+ # The index is named for its family: a .bin set wants pytorch_model.bin.index.json.
+ (
+ {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model-00001-of-00002.bin": b"\0" * 64,
+ "pytorch_model-00002-of-00002.bin": b"\0" * 64,
+ "pytorch_model.bin.index.json": _BIN_SHARD_INDEX,
+ },
+ False,
+ ),
+ # No index rescues a numbered adapter set: peft resolves only the singular name.
+ (
+ {
+ "adapter_config.json": b'{"peft_type":"LORA"}',
+ "adapter_model-00001-of-00002.safetensors": b"\0" * 64,
+ "adapter_model-00002-of-00002.safetensors": b"\0" * 64,
+ "adapter_model.safetensors.index.json": _shard_index(
+ "adapter_model-00001-of-00002.safetensors",
+ "adapter_model-00002-of-00002.safetensors",
+ ),
+ },
+ True,
+ ),
+ ],
+ ids = ["no-index", "empty-index", "with-index", "bin-index", "adapter-shards-never-load"],
+)
+def test_a_sharded_base_family_needs_its_index(files, partial, tmp_path, monkeypatch):
+ """A complete shard set is not a loadable payload on its own."""
+ _repo_with(tmp_path, snapshots = {SNAPSHOT: files}, refs = {"main": UPSTREAM_HEAD})
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is partial
+ assert rows[0]["capabilities"]["can_chat"] is not partial
+
+
+def test_an_index_less_shard_set_does_not_veto_a_whole_family(tmp_path, monkeypatch):
+ """The index makes a family uncountable, not the snapshot unusable. A whole model.safetensors
+ beside an index-less .bin set still serves the row, the same as beside a torn one."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "pytorch_model-00001-of-00002.bin": b"\0" * 64,
+ "pytorch_model-00002-of-00002.bin": b"\0" * 64,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ rows = _autoload_rows(tmp_path, monkeypatch)
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_root_weight_no_runtime_discovers_by_name_does_not_serve(tmp_path, monkeypatch):
+ """An arbitrary root .safetensors names no family and is no diffusers component, so nothing
+ opens it. A .ckpt or diffusion weight is discovered by name and still serves."""
+ for weights, serves in (
+ ({"foo.safetensors": b"\0" * 256}, False),
+ ({"foo.safetensors": b"\0" * 256, "bar.safetensors": b"\0" * 256}, False),
+ ({"model.ckpt": b"\0" * 256}, True),
+ ({"diffusion_pytorch_model.safetensors": b"\0" * 256}, True),
+ ):
+ root = tmp_path / "-".join(sorted(weights)).replace(".", "_")
+ _repo_with(
+ root,
+ snapshots = {OLDER: {"config.json": b'{"model_type":"llama"}', **weights}},
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(root, monkeypatch)
+
+ assert rows[0]["partial"] is not serves
+ assert rows[0]["capabilities"]["can_chat"] is serves
+
+
+def test_a_root_weight_no_runtime_discovers_does_not_veto_one_it_does(tmp_path, monkeypatch):
+ """Control for the test above: an unopened name is no evidence; a canonical weight decides."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "foo.safetensors": b"\0" * 256,
+ "model.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_torn_quant_does_not_charge_a_stale_incomplete_blob_to_the_weights_row(
+ tmp_path, monkeypatch
+):
+ """The legacy .incomplete walk attributes a repo-wide signal, and that question is per row: a
+ weights row never opens a .gguf, so a torn quant must not charge it the leftover blob."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors": b"\0" * 256,
+ "Model-Q4_K_M-00001-of-00002.gguf": b"GGUF" + b"\0" * 252,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ (repo_dir / "blobs" / "abc123.incomplete").write_bytes(b"\0" * 8)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_stale_incomplete_blob_still_reaches_the_snapshot_it_describes(tmp_path, monkeypatch):
+ """Control for the test above: with no quant to mis-attribute, the blob charges the row."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _shard_index(
+ "model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"
+ ),
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ (repo_dir / "blobs" / "abc123.incomplete").write_bytes(b"\0" * 8)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_an_index_whose_map_holds_a_non_string_does_not_hide_the_repo(tmp_path, monkeypatch):
+ """A weight_map value is whatever the file says, not necessarily a path. Reading one has to
+ survive it: a raised TypeError escapes the scan and drops every row for the repo, so a hand
+ edited index next to a loadable checkpoint would make the whole model disappear."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model.bin": b"\0" * 256,
+ "model.safetensors.index.json": json.dumps(
+ {"metadata": {}, "weight_map": {"w0": []}}
+ ).encode(),
+ }
+ },
+ refs = {"main": SNAPSHOT},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_stale_root_shard_beside_a_whole_index_does_not_tear_the_snapshot(tmp_path, monkeypatch):
+ """The index names nested shards and every one of them is there, so from_pretrained reads a
+ whole model. A leftover root shard the map names nothing of is never opened, and judging the
+ walk's families ahead of the index that was selected charges the load for it anyway."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _shard_index(
+ "weights/model-00001-of-00001.safetensors"
+ ),
+ "weights/model-00001-of-00001.safetensors": b"\0" * 256,
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_an_index_naming_half_of_the_family_it_describes_still_reads_as_torn(tmp_path, monkeypatch):
+ """Control for the test above. A shard names its own total, so an index listing one of a set
+ has to list the whole set: the loader opens exactly what is mapped and silently drops the
+ rest, which is an interrupted download rather than stale content beside a whole one."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ SNAPSHOT: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _shard_index("model-00001-of-00002.safetensors"),
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_torn_revision_does_not_choose_the_format_over_a_whole_one(tmp_path, monkeypatch):
+ """The repo-wide format flags are OR-ed across revisions, so they can name a format whose every
+ revision is torn while another format has a whole revision sitting right there. Load what
+ loads: an interrupted safetensors attempt must not hide the checkpoint beside it."""
+ repo_dir = _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _SHARD_INDEX,
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ },
+ NEWER: {
+ "config.json": b'{"model_type":"llama"}',
+ "pytorch_model.bin": b"\0" * 256,
+ },
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+ _age(repo_dir / "snapshots" / OLDER, 600)
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["model_format"] == "checkpoint"
+ assert Path(rows[0]["load_id"]).name == NEWER
+ assert rows[0]["partial"] is False
+ assert rows[0]["capabilities"]["can_chat"] is True
+
+
+def test_a_repo_whose_only_format_is_torn_still_reads_as_torn(tmp_path, monkeypatch):
+ """Control for the test above: with no whole revision in any other format there is nothing to
+ fall back to, so the torn safetensors revision stays the answer."""
+ _repo_with(
+ tmp_path,
+ snapshots = {
+ OLDER: {
+ "config.json": b'{"model_type":"llama"}',
+ "model.safetensors.index.json": _SHARD_INDEX,
+ "model-00001-of-00002.safetensors": b"\0" * 256,
+ }
+ },
+ refs = {"main": UPSTREAM_HEAD},
+ )
+
+ rows = _autoload_rows(tmp_path, monkeypatch)
+
+ assert rows[0]["model_format"] == "safetensors"
+ assert rows[0]["partial"] is True
+ assert rows[0]["capabilities"]["can_chat"] is False
+
+
+def test_a_shard_total_from_a_filename_is_not_materialised(tmp_path):
+ """The total comes out of a repo-controlled filename, so it can name a set far larger than
+ anything on disk. Recovery runs this check over repos scan_cache_dir used to drop, so listing
+ cached models must not allocate a set per declared shard: -of-999999999 costs gigabytes."""
+ snapshot = tmp_path / "snapshots" / SNAPSHOT
+ snapshot.mkdir(parents = True)
+ (snapshot / "Model-Q4_K_M-00001-of-1000000.gguf").write_bytes(b"GGUF" + b"\0" * 252)
+
+ tracemalloc.start()
+ try:
+ complete = inventory_scan._completed_gguf_variants(snapshot)
+ _current, peak = tracemalloc.get_traced_memory()
+ finally:
+ tracemalloc.stop()
+
+ assert complete == set()
+ assert peak < 8 * 1024 * 1024, f"allocated {peak} bytes for a declared set of 1000000 shards"
+
+
+def test_a_whole_split_quant_is_still_complete(tmp_path):
+ """Control for the test above: a set whose shards are all present still reads complete."""
+ snapshot = tmp_path / "snapshots" / SNAPSHOT
+ snapshot.mkdir(parents = True)
+ for index in (1, 2):
+ (snapshot / f"Model-Q4_K_M-0000{index}-of-00002.gguf").write_bytes(b"GGUF" + b"\0" * 252)
+
+ assert inventory_scan._completed_gguf_variants(snapshot) == {"Q4_K_M"}
diff --git a/studio/backend/tests/test_picker_service.py b/studio/backend/tests/test_picker_service.py
index 1bdfc135e38..30b117f6239 100644
--- a/studio/backend/tests/test_picker_service.py
+++ b/studio/backend/tests/test_picker_service.py
@@ -210,7 +210,9 @@ def test_remote_template_over_size_limit_is_skipped_before_download(monkeypatch)
import huggingface_hub
monkeypatch.setattr("picker.service.resolve_cached_repo_id_case", lambda name: name)
- monkeypatch.setattr("picker.service.iter_hf_cache_snapshots", lambda resolved: [])
+ monkeypatch.setattr(
+ "picker.service.iter_snapshots_preferring_whole", lambda resolved, variant: []
+ )
def _fail_download(*args, **kwargs):
raise AssertionError("oversized remote template must not be downloaded")
@@ -245,7 +247,9 @@ def test_remote_oversized_jinja_falls_through_to_tokenizer_template(tmp_path, mo
observed_cache_dirs = []
monkeypatch.setattr("picker.service.resolve_cached_repo_id_case", lambda name: name)
- monkeypatch.setattr("picker.service.iter_hf_cache_snapshots", lambda resolved: [])
+ monkeypatch.setattr(
+ "picker.service.iter_snapshots_preferring_whole", lambda resolved, variant: []
+ )
monkeypatch.setattr("picker.service.active_hf_hub_cache", lambda: str(selected_cache))
def _fake_download(repo_id, rel, **kwargs):
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index 45a77b6eb34..eae831c7011 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -1460,6 +1460,10 @@ def detect_mmproj_file(path: str, search_root: Optional[str] = None) -> Optional
for f in _iter_gguf_files(d):
try:
resolved = f.resolve()
+ # Interrupted download: llama-server cannot open it, the inventory already reports
+ # such a row text-only, and it must not shadow a whole projector beside it.
+ if resolved.stat().st_size <= 0:
+ continue
except OSError:
continue
if resolved in seen_resolved:
@@ -1976,6 +1980,23 @@ def _local_gguf_companion_search_root(selected_path: str, gguf_file: str) -> str
return str(search_dir)
+def _snapshot_selection_key(snapshot: Path) -> tuple[float, str]:
+ """Order snapshots by mtime, then by resolved path.
+
+ Mirrors hub.utils.hf_cache_state.snapshot_selection_key (utils cannot import hub) and must change
+ in lockstep: mtime alone is not a total order, so a tie broken differently would let the
+ inventory row advertise one revision while the load reads the other.
+ """
+ try:
+ mtime = snapshot.stat().st_mtime
+ except OSError:
+ mtime = 0.0
+ try:
+ return mtime, str(snapshot.resolve())
+ except (OSError, RuntimeError, ValueError):
+ return mtime, str(snapshot)
+
+
def _iter_hf_cache_snapshots(repo_id: str, cache_dir: Optional[str | Path] = None):
"""Yield HF cache snapshot dirs for *repo_id*, newest first.
@@ -2018,14 +2039,15 @@ def _iter_hf_cache_snapshots(repo_id: str, cache_dir: Optional[str | Path] = Non
continue
if not snap_dirs:
return
- snap_dirs_with_mtime = []
+ ordered = []
for snap_dir in snap_dirs:
try:
- snap_dirs_with_mtime.append((snap_dir.stat().st_mtime, snap_dir))
+ snap_dir.stat()
except OSError:
continue
- snap_dirs_with_mtime.sort(key = lambda item: item[0], reverse = True)
- yield from (snap_dir for _, snap_dir in snap_dirs_with_mtime)
+ ordered.append((_snapshot_selection_key(snap_dir), snap_dir))
+ ordered.sort(key = lambda item: item[0], reverse = True)
+ yield from (snap_dir for _key, snap_dir in ordered)
def _list_gguf_variants_from_hf_cache(repo_id: str) -> Optional[tuple[list[GgufVariantInfo], bool]]:
diff --git a/studio/frontend/src/features/auth/api.ts b/studio/frontend/src/features/auth/api.ts
index 38ab9aa5ea3..cb72ba97ecd 100644
--- a/studio/frontend/src/features/auth/api.ts
+++ b/studio/frontend/src/features/auth/api.ts
@@ -89,6 +89,24 @@ async function redirectToAuth(): Promise<void> {
window.location.href = target;
}
+function asTransportFailure(err: unknown): unknown {
+ // fetch TypeError = offline | backend down | CORS/DNS. Tauri is always backend-down; the web
+ // build distinguishes offline. Tagged so callers tell "never reached" from "rejected".
+ if (!(err instanceof TypeError)) return err;
+ if (!isTauri && typeof navigator !== "undefined" && navigator.onLine === false) {
+ return Object.assign(
+ new Error(
+ "You appear to be offline. Check your network connection and try again.",
+ ),
+ { unslothTransportFailure: true },
+ );
+ }
+ return Object.assign(
+ new Error("Unsloth isn't running -- please relaunch it."),
+ { unslothTransportFailure: true },
+ );
+}
+
async function retryWithCurrentToken(
input: RequestInfo | URL,
init?: RequestInit,
@@ -96,7 +114,13 @@ async function retryWithCurrentToken(
const retryHeaders = new Headers(init?.headers);
const token = getAuthToken();
if (token) retryHeaders.set("Authorization", `Bearer ${token}`);
- return fetchWithTauriNetworkRetry(input, { ...init, headers: retryHeaders });
+ // Retries are tagged like the first attempt; an untagged TypeError reads as a rejection and
+ // lets auto-load fall through to the default download.
+ try {
+ return await fetchWithTauriNetworkRetry(input, { ...init, headers: retryHeaders });
+ } catch (err) {
+ throw asTransportFailure(err);
+ }
}
async function retryWithTauriAutoAuth(
@@ -171,17 +195,7 @@ export async function authFetch(
headers,
});
} catch (err) {
- if (err instanceof TypeError) {
- // fetch TypeError = offline | backend down | CORS/DNS. Tauri is always
- // backend-down; the web build distinguishes offline for the right message.
- if (!isTauri && typeof navigator !== "undefined" && navigator.onLine === false) {
- throw new Error(
- "You appear to be offline. Check your network connection and try again.",
- );
- }
- throw new Error("Unsloth isn't running -- please relaunch it.");
- }
- throw err;
+ throw asTransportFailure(err);
}
if (await isPasswordChangeRequiredResponse(response)) {
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 0917e2304f8..8585bed6948 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1447,9 +1447,19 @@ function isAutoLoadableGgufVariant(variant: GgufVariantDetail | null): boolean {
return !hasBigEndianGgufMarker(filename, variant.quant);
}
+/** Whether a cache row is chattable. Both fields are optional so an older backend keeps trying. */
+function isChattableCachedRepo(repo: {
+ partial?: boolean;
+ capabilities?: { can_chat?: boolean } | null;
+}): boolean {
+ return repo.partial !== true && repo.capabilities?.can_chat !== false;
+}
+
async function autoLoadSmallestModel(): Promise<{
loaded: boolean;
blockedByTrustRemoteCode: boolean;
+ /** A load failure was already toasted, so callers must not replace it with generic advice. */
+ loadFailureReported?: boolean;
}> {
if (await tryAdoptServerActiveModel()) {
return { loaded: true, blockedByTrustRemoteCode: false };
@@ -1496,6 +1506,31 @@ async function autoLoadSmallestModel(): Promise<{
let hadNonTrustFailure = false;
let loadAttempts = 0;
const skippedAutoLoadCandidates = new Set<string>();
+ // Why the last load attempt failed. Boxed: a `let` set only in a nested fn narrows to `null`.
+ const loadFailure: {
+ current: { label: string; detail: string; blamesModel: boolean } | null;
+ } = { current: null };
+
+ // Set once the user declines the HF token dialog, so nothing asks again.
+ let autoLoadCancelled = false;
+
+ function noteLoadFailure(label: string, error: unknown): void {
+ const detail =
+ error instanceof Error && error.message.trim() ? error.message.trim() : "";
+ // loadModel also rejects before /api/inference/load is sent (dismissed token dialog, dead
+ // backend): those stop the Hub download, but must not blame the model.
+ const marker = error as { unslothTransportFailure?: boolean; unslothUserCancelled?: boolean };
+ const blamesModel = !(
+ marker?.unslothTransportFailure === true || marker?.unslothUserCancelled === true
+ );
+ loadFailure.current = {
+ label,
+ // Older backends and non-Error throws carry no detail; still name the model that failed.
+ detail:
+ detail || "The server did not report a reason. Check the Studio logs.",
+ blamesModel,
+ };
+ }
async function canAutoLoad(payload: {
model_path: string;
@@ -1535,14 +1570,43 @@ async function autoLoadSmallestModel(): Promise<{
return true;
}
+ function recordCandidateFailure(label: string, error: unknown): void {
+ // Every rejection is recorded: the sweep's catches are bare, so one left unrecorded reads as
+ // "nothing was cached" and fetches the default. Only cancelling ends the sweep.
+ const marker = error as { unslothUserCancelled?: boolean };
+ noteLoadFailure(label, error);
+ if (marker?.unslothUserCancelled === true) {
+ // The next candidate would reopen the same dialog, so stop rather than ask per repo. A
+ // transport failure deliberately does NOT: the backend can come back mid-sweep.
+ autoLoadCancelled = true;
+ }
+ }
+
+ async function canAutoLoadRecordingFailures(
+ label: string,
+ payload: Parameters<typeof canAutoLoad>[0],
+ ): Promise<boolean> {
+ try {
+ return await canAutoLoad(payload);
+ } catch (error) {
+ // validateModel prepares the token too, so a dismissed dialog or dead backend surfaces here,
+ // where the sweep's bare catches would drop it and hit the Hub download.
+ recordCandidateFailure(label, error);
+ throw error;
+ }
+ }
+
async function loadAutoLoadCandidate(
candidate: AutoLoadCandidate,
): Promise<boolean> {
- if (loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) {
+ if (autoLoadCancelled || loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) {
return false;
}
const currentStore = useChatRuntimeStore.getState();
const modelPath = candidate.loadId ?? candidate.id;
+ const failureLabel = candidate.ggufVariant
+ ? `${candidate.id} (${candidate.ggufVariant})`
+ : candidate.id;
const { config } = resolveInitialConfig(candidate.id, candidate.ggufVariant);
const effectiveMaxSeqLength = resolveLoadMaxSeqLength({
modelId: candidate.id,
@@ -1583,13 +1647,23 @@ async function autoLoadSmallestModel(): Promise<{
// replacement-token recovery flow could run.
const preparedToken = await prepareHfTokenForUse(hfToken);
if (!preparedToken.proceed) {
- throw new Error("Model load cancelled.");
+ // Raised before loadModel, so route it through the same helper or every later candidate
+ // reopens the dialog.
+ const cancelled = Object.assign(new Error("Model load cancelled."), {
+ unslothUserCancelled: true,
+ });
+ recordCandidateFailure(failureLabel, cancelled);
+ throw cancelled;
}
isDiffusion = (
await fetchGgufStagedMetadata({
model_path: modelPath,
gguf_variant: candidate.ggufVariant,
hf_token: preparedToken.token,
+ }).catch((error: unknown) => {
+ // Same authFetch as validate and load, so a dead backend throws here first.
+ recordCandidateFailure(failureLabel, error);
+ throw error;
})
).isDiffusion;
}
@@ -1623,7 +1697,7 @@ async function autoLoadSmallestModel(): Promise<{
? config.chatTemplateOverride
: null;
if (
- !(await canAutoLoad({
+ !(await canAutoLoadRecordingFailures(failureLabel, {
model_path: modelPath,
max_seq_length: fitMaxSeqLength,
is_lora: false,
@@ -1673,6 +1747,10 @@ async function autoLoadSmallestModel(): Promise<{
n_parallel: config.nParallel ?? null,
}
: {}),
+ }).catch((error: unknown) => {
+ // The sweep's parameterless catches discard this error, so record it before rethrowing.
+ noteLoadFailure(failureLabel, error);
+ throw error;
});
// Only persist the global preference when the value came from the global
// settings. A per-model config's choice must stay load-local, or autoloading
@@ -1683,6 +1761,11 @@ async function autoLoadSmallestModel(): Promise<{
// Self-gates on is_gguf (skips diffusion), so persists only for a real GGUF load.
persistGpuMemoryModeOnLoad(loadResp, effectiveGpuMemoryMode);
const loadedModelId = loadResp.model || modelPath;
+ // The identity stays the backend's, per the inactive-cache contract; the pin is recorded
+ // alongside it so a later reload finds the same directory.
+ useChatRuntimeStore.setState({
+ activeLoadId: modelPath === candidate.id ? null : modelPath,
+ });
useChatRuntimeStore
.getState()
.setCheckpoint(loadedModelId, candidate.ggufVariant ?? undefined);
@@ -1801,10 +1884,13 @@ async function autoLoadSmallestModel(): Promise<{
return true;
}
try {
- const [ggufRepos, modelRepos] = await Promise.all([
+ const [allGgufRepos, allModelRepos] = await Promise.all([
listCachedGguf().catch(() => []),
listCachedModels().catch(() => []),
]);
+ // Filtered once, so the last-used lookup sees the same set as the sweeps.
+ const ggufRepos = allGgufRepos.filter(isChattableCachedRepo);
+ const modelRepos = allModelRepos.filter(isChattableCachedRepo);
if (lastLoaded) {
if (lastLoaded.kind === "gguf") {
@@ -1956,12 +2042,29 @@ async function autoLoadSmallestModel(): Promise<{
// Cap also gates the default download, so total /api/inference/load
// budget across cached + fallback is MAX_AUTO_LOAD_ATTEMPTS, not +1.
- if (loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS) {
+ // A tried-and-failed cached model stops here: that reason beats an unrelated Hub default.
+ // An empty cache never sets loadFailure and still falls through.
+ if (loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS || loadFailure.current) {
toast.dismiss(toastId);
+ if (loadFailure.current) {
+ toast.error(
+ loadFailure.current.blamesModel
+ ? `Could not load ${loadFailure.current.label}`
+ : loadFailure.current.detail,
+ {
+ description: loadFailure.current.blamesModel
+ ? loadFailure.current.detail
+ : `Stopped before loading ${loadFailure.current.label}.`,
+ duration: 10000,
+ closeButton: true,
+ },
+ );
+ }
return {
loaded: false,
blockedByTrustRemoteCode:
blockedByTrustRemoteCode && !hadNonTrustFailure,
+ loadFailureReported: loadFailure.current !== null,
};
}
@@ -2132,19 +2235,22 @@ export function createOpenAIStreamAdapter(
await waitForModelReady(abortSignal);
}
if (!useChatRuntimeStore.getState().params.checkpoint) {
- const { loaded, blockedByTrustRemoteCode } =
+ const { loaded, blockedByTrustRemoteCode, loadFailureReported } =
await autoLoadSmallestModel();
if (!loaded) {
- toast.error(
- blockedByTrustRemoteCode
- ? "This model needs custom code approval"
- : "No model loaded",
- {
- description: blockedByTrustRemoteCode
- ? "Select it from the top bar to review and approve its custom code, or pick another model."
- : "Pick a model in the top bar, then retry.",
- },
- );
+ // A reported failure already names the model; generic advice buries it.
+ if (!loadFailureReported) {
+ toast.error(
+ blockedByTrustRemoteCode
+ ? "This model needs custom code approval"
+ : "No model loaded",
+ {
+ description: blockedByTrustRemoteCode
+ ? "Select it from the top bar to review and approve its custom code, or pick another model."
+ : "Pick a model in the top bar, then retry.",
+ },
+ );
+ }
throw new Error("Load a model first.");
}
}
@@ -2424,24 +2530,28 @@ export function createOpenAIStreamAdapter(
// Prefer a model already loaded by the CLI/API before auto-loading.
let loaded: boolean;
let blockedByTrustRemoteCode: boolean;
+ let loadFailureReported: boolean | undefined;
try {
- ({ loaded, blockedByTrustRemoteCode } =
+ ({ loaded, blockedByTrustRemoteCode, loadFailureReported } =
await autoLoadSmallestModel());
} catch (error) {
clearSelectedImageEditReference();
throw error;
}
if (!loaded) {
- toast.error(
- blockedByTrustRemoteCode
- ? "This model needs custom code approval"
- : "No model loaded",
- {
- description: blockedByTrustRemoteCode
- ? "Select it from the top bar to review and approve its custom code, or pick another model."
- : "Pick a model in the top bar, then retry.",
- },
- );
+ // A reported failure already names the model; generic advice buries it.
+ if (!loadFailureReported) {
+ toast.error(
+ blockedByTrustRemoteCode
+ ? "This model needs custom code approval"
+ : "No model loaded",
+ {
+ description: blockedByTrustRemoteCode
+ ? "Select it from the top bar to review and approve its custom code, or pick another model."
+ : "Pick a model in the top bar, then retry.",
+ },
+ );
+ }
clearSelectedImageEditReference();
throw new Error("Load a model first.");
}
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index c6a383861ca..240a23429b3 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -193,7 +193,11 @@ export async function loadModel(
payload: LoadModelRequest,
): Promise<LoadModelResponse> {
const preparedToken = await prepareHfTokenForUse(payload.hf_token);
- if (!preparedToken.proceed) throw new Error("Model load cancelled.");
+ // Tagged so auto-load can tell a user cancellation from a backend rejection.
+ if (!preparedToken.proceed)
+ throw Object.assign(new Error("Model load cancelled."), {
+ unslothUserCancelled: true,
+ });
const response = await authFetch("/api/inference/load", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -211,7 +215,10 @@ export async function validateModel(
payload: LoadModelRequest,
): Promise<ValidateModelResponse> {
const preparedToken = await prepareHfTokenForUse(payload.hf_token);
- if (!preparedToken.proceed) throw new Error("Model load cancelled.");
+ if (!preparedToken.proceed)
+ throw Object.assign(new Error("Model load cancelled."), {
+ unslothUserCancelled: true,
+ });
const response = await authFetch("/api/inference/validate", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -338,6 +345,13 @@ export interface CachedGgufRepo {
/** True when the repo ships an mmproj adapter (image inputs). Optional for
* older-backend compatibility. */
has_vision?: boolean;
+ partial?: boolean;
+ capabilities?: CachedRepoCapabilities | null;
+}
+
+/** The subset of a row's capabilities auto-load acts on; Hub view models have a wider type. */
+export interface CachedRepoCapabilities {
+ can_chat?: boolean;
}
export async function getGgufDownloadProgress(
@@ -457,6 +471,8 @@ export interface CachedModelRepo {
/** Owning cache dir; sent so a delete targets this copy, not the active
* cache. Optional for older-backend compatibility. */
cache_path?: string | null;
+ partial?: boolean;
+ capabilities?: CachedRepoCapabilities | null;
}
export async function listCachedModels(
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 80e5841f3b3..81d3c3ed7dc 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -2775,6 +2775,7 @@ export function ChatPage({
}
const selection = {
id: value,
+ loadId: meta?.loadId,
source: meta?.source,
isLora: meta?.isLora,
ggufVariant: meta?.ggufVariant,
@@ -2803,6 +2804,7 @@ export function ChatPage({
const checkpoint = inferenceParams.checkpoint;
if (!checkpoint) return;
const runtime = useChatRuntimeStore.getState();
+ const activeLoadId = runtime.activeLoadId;
const nativeToken = runtime.activeNativePathToken;
const nativeExpiry = runtime.activeNativePathExpiresAtMs;
// A file-picked GGUF is reachable only via its native path token, which
@@ -2818,6 +2820,8 @@ export function ChatPage({
handleCheckpointChange(checkpoint, {
source: "local",
isLora: activeModelIsLora,
+ // The checkpoint is the id, so a pinned model reloads from that same snapshot.
+ loadId: activeLoadId,
ggufVariant: activeGgufVariant ?? undefined,
// Without the native token the reload validates the display label as a
// repo and fails.
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index c6148d76a60..4a3f331db7c 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -75,6 +75,8 @@ import type {
export type SelectedModelInput = {
id: string;
+ /** Sent as model_path in place of the id, which stays the identity the UI shows. */
+ loadId?: string | null;
isLora?: boolean;
ggufVariant?: string;
/** Where the pick came from (e.g. "hub", "local", "external"). Used to decide
@@ -311,6 +313,14 @@ async function syncInferenceStatusToStore(options?: {
if (checkpointId) {
const previousGgufVariant =
useChatRuntimeStore.getState().activeGgufVariant;
+ // A model loaded outside this tab replaces the resident one, and the pin belonged to the
+ // old one: keeping it reloads that one from another's settings.
+ if (
+ checkpointId !== selectedCheckpoint ||
+ (statusRes.gguf_variant ?? null) !== (previousGgufVariant ?? null)
+ ) {
+ useChatRuntimeStore.setState({ activeLoadId: null });
+ }
setCheckpoint(checkpointId, statusRes.gguf_variant);
applyActiveModelStatusToStore(statusRes, {
previousCheckpoint: selectedCheckpoint,
@@ -491,6 +501,8 @@ export function useChatModelRuntime() {
const selectModel = useCallback(
async (selection: string | SelectedModelInput) => {
const modelId = typeof selection === "string" ? selection : selection.id;
+ const loadPath =
+ (typeof selection === "string" ? null : selection.loadId) || modelId;
const ggufVariant =
typeof selection === "string" ? undefined : selection.ggufVariant;
const forceReload =
@@ -576,6 +588,11 @@ export function useChatModelRuntime() {
}
const previousGgufVariant =
useChatRuntimeStore.getState().activeGgufVariant;
+ // The poll skips its own clearing while an external pick is active, so a pin taken
+ // for an earlier resident can survive; Apply would then reload that old model.
+ if (useChatRuntimeStore.getState().activeLoadId !== modelId) {
+ useChatRuntimeStore.setState({ activeLoadId: null });
+ }
useChatRuntimeStore
.getState()
.setCheckpoint(modelId, residentStatus.gguf_variant);
@@ -710,7 +727,7 @@ export function useChatModelRuntime() {
}
isDiffusion = (
await fetchGgufStagedMetadata({
- model_path: modelId,
+ model_path: loadPath,
gguf_variant: ggufVariant ?? null,
hf_token: preparedToken.token,
nativePathToken: nativePathToken ?? null,
@@ -733,6 +750,7 @@ export function useChatModelRuntime() {
stateBeforeUnload.params.maxSeqLength;
const previousActiveNativePathToken =
stateBeforeUnload.activeNativePathToken;
+ const previousActiveLoadId = stateBeforeUnload.activeLoadId;
const previousIsGguf =
previousModel?.isGguf === true
|| previousVariant != null
@@ -877,7 +895,7 @@ export function useChatModelRuntime() {
}),
);
const validation = await validateModel({
- model_path: modelId,
+ model_path: loadPath,
nativePathLease: validateNativePathLease,
hf_token: hfToken,
max_seq_length: validateMaxSeqLength,
@@ -1053,7 +1071,7 @@ export function useChatModelRuntime() {
const effectiveChatTemplateOverride =
loadChatTemplateOverride?.trim() ? loadChatTemplateOverride : null;
const loadResponse = await loadModel({
- model_path: modelId,
+ model_path: loadPath,
nativePathLease: loadNativePathLease,
hf_token: hfToken,
max_seq_length: loadMaxSeqLength,
@@ -1186,6 +1204,8 @@ export function useChatModelRuntime() {
? stateBeforeUnload.reasoningEnabled
: reasoningDefault;
rememberApprovedRemoteCode(modelId, approvedRemoteCodeFingerprint);
+ // A later rollback reads the snapshot path, not the id this was stored under.
+ rememberApprovedRemoteCode(loadPath, approvedRemoteCodeFingerprint);
useChatRuntimeStore.setState({
ggufContextLength: nativeCtx,
ggufMaxContextLength,
@@ -1228,6 +1248,7 @@ export function useChatModelRuntime() {
loadedIsMultimodal: isMultimodalResponse(loadResponse),
loadedIsDiffusion: loadResponse.is_diffusion ?? false,
activeModelIsLocal: loadResponse.is_local_model ?? false,
+ activeLoadId: loadPath === modelId ? null : loadPath,
activeNativePathToken: nativePathToken ?? null,
activeNativePathExpiresAtMs: nativePathToken
? nativePathExpiresAtMs
@@ -1304,7 +1325,8 @@ export function useChatModelRuntime() {
}
try {
const rollbackResponse = await loadModel({
- model_path: previousCheckpoint,
+ // The pin it loaded from: without it this retries the ref that needed pinning.
+ model_path: previousActiveLoadId || previousCheckpoint,
nativePathLease: rollbackNativePathLease,
hf_token: hfToken,
max_seq_length: rollbackMaxSeqLength,
@@ -1341,6 +1363,7 @@ export function useChatModelRuntime() {
);
useChatRuntimeStore.setState({
activeModelIsLocal: rollbackResponse.is_local_model ?? false,
+ activeLoadId: previousActiveLoadId ?? null,
activeNativePathToken: previousActiveNativePathToken ?? null,
// Restore the previous token's lease together with the token so a
// rollback never pairs restored token A with failed load B's expiry.
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 5f1df072b05..b86c31548fd 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -1105,6 +1105,9 @@ type ChatRuntimeStore = {
contextUsageByThreadId: Record<string, ContextUsageSnapshot>;
modelLoading: boolean;
loadingModelPick: LoadingModelPick | null;
+ // What the resident model loaded from, when that is not its id. A reload rebuilds its target
+ // from the checkpoint, so without this it goes back down the ref the pin avoided.
+ activeLoadId: string | null;
activeNativePathToken: string | null;
// Wall-clock expiry (ms) of the active native path token. The desktop host
// prunes file leases after a TTL, so a reload checks this to prompt
@@ -1593,6 +1596,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
contextUsageByThreadId: {},
modelLoading: false,
loadingModelPick: null,
+ activeLoadId: null,
activeNativePathToken: null,
activeNativePathExpiresAtMs: null,
hydratePersistedSettings: async () => {
@@ -1910,6 +1914,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
},
activeGgufVariant: null,
activeModelIsLocal: false,
+ activeLoadId: null,
activeNativePathToken: null,
activeNativePathExpiresAtMs: null,
ggufContextLength: null,
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
index ad1586bc41c..68d86bb4fff 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx
@@ -717,6 +717,8 @@ function ggufVariantExpectedBytes(variant: GgufVariantDetail): number {
function GgufVariantExpander({
repoId,
+ loadId,
+ cachePath,
onSelect,
gpuGb,
systemRamGb,
@@ -733,6 +735,10 @@ function GgufVariantExpander({
onHasVision,
}: {
repoId: string;
+ /** Snapshot the cached listing pinned this repo to, if any. */
+ loadId?: string | null;
+ /** Cache directory this downloaded row represents, if any. */
+ cachePath?: string | null;
onSelect: (id: string, meta: ModelSelectorChangeMeta) => void;
gpuGb?: number;
systemRamGb?: number;
@@ -792,6 +798,7 @@ function GgufVariantExpander({
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [refreshKey, setRefreshKey] = useState(0);
+ const localSource = loadId || cachePath || null;
useEffect(() => {
let canceled = false;
@@ -801,7 +808,9 @@ function GgufVariantExpander({
setError(null);
});
- listGgufVariants(repoId, hfToken)
+ // The row's own directory, so disk contents count against that cache, not the active one. No
+ // preferLocalCache: it answers from disk alone and drops the undownloaded.
+ listGgufVariants(repoId, hfToken, localSource ? { localPath: localSource } : undefined)
.then((res) => {
if (canceled) return;
const normalized = normalizeGgufVariantsResponse(res);
@@ -824,7 +833,7 @@ function GgufVariantExpander({
return () => {
canceled = true;
};
- }, [repoId, refreshKey, hfToken]);
+ }, [repoId, localSource, refreshKey, hfToken]);
// Covers Unix absolute (/), Windows drive (C:\, D:/), UNC (\\server), relative (./, ../), tilde (~/)
const isLocalPath = /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(
@@ -837,6 +846,8 @@ function GgufVariantExpander({
onSelect(repoId, {
source: sourceOverride ?? (isLocalPath ? "local" : "hub"),
isLora: false,
+ // Only for a quant already in the pinned snapshot: a new download lands elsewhere.
+ loadId: downloaded === true ? loadId : undefined,
ggufVariant: quant,
isDownloaded: isLocalPath ? true : downloaded,
expectedBytes: sizeBytes,
@@ -844,7 +855,7 @@ function GgufVariantExpander({
isGguf: true,
});
},
- [repoId, isLocalPath, onSelect, sourceOverride, nativeContext],
+ [repoId, loadId, isLocalPath, onSelect, sourceOverride, nativeContext],
);
// GGUF fit classification matching llama-server's _select_gpus logic:
@@ -1003,6 +1014,8 @@ function GgufVariantExpander({
const oom = fit === "oom";
const tight = fit === "tight";
const expectedBytes = ggufVariantExpectedBytes(v);
+ // A folder has no download to resume; a quant short a shard has no files to load.
+ const unusableLocal = isLocalPath && v.partial === true;
const keyBase = `${repoId}:${v.filename}`;
const variantOptionKey = makeModelOptionKey("gguf-variant", keyBase);
return (
@@ -1010,11 +1023,14 @@ function GgufVariantExpander({
<button
type="button"
{...variantList.getOptionProps(variantOptionKey, false)}
+ disabled={unusableLocal}
onClick={() =>
handleVariantClick(v.quant, v.downloaded, expectedBytes)
}
className={cn(
"flex min-w-0 flex-1 items-center justify-between gap-2 rounded-full py-1 pl-2 pr-1.5 text-left text-sm transition-colors hover:bg-[#ececec] focus-visible:bg-[#ececec] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring dark:hover:bg-[var(--sidebar-accent)] dark:focus-visible:bg-[var(--sidebar-accent)]",
+ unusableLocal &&
+ "cursor-default opacity-50 hover:bg-transparent dark:hover:bg-transparent",
)}
>
<span className="min-w-0 flex-1 truncate font-mono text-xs">
@@ -1023,7 +1039,11 @@ function GgufVariantExpander({
>
{v.quant}
</span>
- {v.downloaded ? (
+ {unusableLocal ? (
+ <span className="ml-1.5 text-ui-9 font-sans font-medium text-amber-700 dark:text-amber-300">
+ incomplete
+ </span>
+ ) : v.downloaded ? (
<>
<span className="ml-1.5 text-ui-9 font-sans font-medium text-green-600/90 dark:text-green-400/80">
downloaded
@@ -1064,6 +1084,7 @@ function GgufVariantExpander({
onConfigure(repoId, {
source: sourceOverride ?? (isLocalPath ? "local" : "hub"),
isLora: false,
+ loadId,
ggufVariant: v.quant,
isDownloaded: true,
expectedBytes,
@@ -2910,6 +2931,8 @@ export function HubModelPicker({
{isGgufExpanded(c.repo_id) && (
<GgufVariantExpander
repoId={c.repo_id}
+ loadId={c.load_id}
+ cachePath={c.cache_path}
onDevice={true}
allowPin={true}
onHasVision={(v) => reportVision(c.repo_id, v)}
@@ -2968,6 +2991,7 @@ export function HubModelPicker({
onSelect(c.repo_id, {
source: "hub",
isLora: false,
+ loadId: c.load_id,
isDownloaded: true,
})
}
@@ -2982,6 +3006,7 @@ export function HubModelPicker({
onConfigure(c.repo_id, {
source: "hub",
isLora: false,
+ loadId: c.load_id,
isDownloaded: true,
isGguf: false,
})
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/types.ts b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
index a621c5134ad..f25e0c6a283 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/types.ts
+++ b/studio/frontend/src/features/model-picker/components/model-selector/types.ts
@@ -41,6 +41,8 @@ export interface ModelSelectorChangeMeta {
isDiffusion?: boolean;
config?: PerModelConfig;
forceReload?: boolean;
+ /** model_path to send when the pick loads from elsewhere, e.g. a pinned snapshot dir. */
+ loadId?: string | null;
/** Native path token so an active-model reload can reopen a file-picked GGUF. */
nativePathToken?: string;
nativePathExpiresAtMs?: number | null;
diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
index b46e83819cd..d60995011ad 100644
--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
@@ -28,6 +28,8 @@ function isCompleteCachedRow(row: CachedInventoryRow): boolean {
function toCachedGgufRepo(row: CachedInventoryRow): CachedGgufRepo {
return {
repo_id: row.repoId,
+ // Listed by repo id, loaded by the pinned id: dropping it sends the picker back down the ref.
+ load_id: row.loadId,
size_bytes: row.bytes,
cache_path: row.cachePath ?? "",
last_modified: row.lastModified ?? undefined,
@@ -38,6 +40,9 @@ function toCachedGgufRepo(row: CachedInventoryRow): CachedGgufRepo {
function toCachedModelRepo(row: CachedInventoryRow): CachedModelRepo {
return {
repo_id: row.repoId,
+ load_id: row.loadId,
+ // Delete targets the copy the row describes; without it the request hits the active cache.
+ cache_path: row.cachePath,
size_bytes: row.bytes,
last_modified: row.lastModified ?? undefined,
};
diff --git a/tests/studio/load_freeze/test_load_orchestrator.py b/tests/studio/load_freeze/test_load_orchestrator.py
index 5cec40653bc..e37d7ee15fb 100644
--- a/tests/studio/load_freeze/test_load_orchestrator.py
+++ b/tests/studio/load_freeze/test_load_orchestrator.py
@@ -50,24 +50,16 @@ import logging as _logging # noqa: E402
_loggers_stub = types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: _logging.getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
-# structlog is a hard studio.txt requirement, but it is only imported lazily, so a
-# bare setdefault here used to park an empty placeholder BEFORE anything imported
-# the real package -- and it then shadowed it for the rest of the session. Every
-# later file importing a studio module that calls structlog.get_logger at module
-# scope (routes.inference -> core.inference.external_provider, utils.mlx_repair)
-# blew up with AttributeError, but only when this file was collected first, so the
-# same test passed alone and failed under `pytest tests/studio`. Only stub when the
-# package is genuinely missing, and give the stub the attribute those callers use.
-# Guard on sys.modules FIRST: another test module may have parked its own bare
-# stub, and find_spec() raises ValueError on a module whose __spec__ is None.
-# Anything already there (real or stub) is left alone; only a genuinely absent
-# package gets stubbed.
-if "structlog" not in sys.modules and importlib.util.find_spec("structlog") is None:
- _structlog_stub = types.ModuleType("structlog")
- _structlog_stub.get_logger = lambda *args, **kwargs: _logging.getLogger(
+# structlog is a hard studio.txt requirement imported only lazily, so a bare setdefault would
+# shadow the real package. Stub only a genuinely absent one (check sys.modules first: find_spec()
+# raises ValueError on another module's bare stub), then backfill get_logger.
+_structlog = sys.modules.get("structlog")
+if _structlog is None and importlib.util.find_spec("structlog") is None:
+ _structlog = sys.modules.setdefault("structlog", types.ModuleType("structlog"))
+if _structlog is not None and not hasattr(_structlog, "get_logger"):
+ _structlog.get_logger = lambda *args, **kwargs: _logging.getLogger(
args[0] if args else "structlog"
)
- sys.modules["structlog"] = _structlog_stub
import httpx # noqa: E402
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
new file mode 100644
index 00000000000..770755c1020
--- /dev/null
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -0,0 +1,487 @@
+# 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 failed auto-load of a cached model must not become a Hub download.
+
+Runs the real ``autoLoadSmallestModel`` from chat-adapter.ts under node with the module boundary
+stubbed, so these assert behaviour, not source text. The sweep's catches are parameterless, so a
+cached repo whose load rejected fell through to fetching an unrelated default model.
+"""
+
+import json
+import os
+import shutil
+import subprocess
+import tempfile
+import textwrap
+from pathlib import Path
+
+import pytest
+
+WORKDIR = Path(__file__).resolve().parents[2]
+
+
+def _source_path(relative_path: str) -> Path:
+ direct = WORKDIR / relative_path
+ if direct.exists():
+ return direct
+ return WORKDIR / "unsloth_repo" / relative_path
+
+
+ADAPTER = _source_path("studio/frontend/src/features/chat/api/chat-adapter.ts")
+TEMP = WORKDIR / "temp" / "chat_autoload_failure_gate"
+DEFAULT_MODEL = "unsloth/Qwen3.5-4B-MTP-GGUF"
+GEMMA_REPO = "unsloth/gemma-4-26B-A4B-it-qat-GGUF"
+
+# Stubs for everything autoLoadSmallestModel imports; each scenario supplies the cache inventory
+# and how /validate and /load answer per model_path.
+PREAMBLE = """
+type LastLocalModelKind = "gguf" | "model";
+type GgufVariantDetail = {
+ quant?: string | null;
+ filename?: string | null;
+ downloaded?: boolean;
+ size_bytes: number;
+};
+type ChatModelSummary = Record<string, unknown>;
+
+export type Scenario = {
+ ggufRepos: any[];
+ modelRepos: any[];
+ variants: Record<string, any>;
+ lastLoaded: any;
+ validate: (payload: any) => any;
+ load: (payload: any) => any;
+};
+
+export const EVENTS: any[] = [];
+let SCENARIO: Scenario;
+export function setScenario(scenario: Scenario) {
+ SCENARIO = scenario;
+ EVENTS.length = 0;
+ STORE = makeStore();
+}
+
+const GPU_LAYERS_AUTO = -1;
+
+function makeStore(): any {
+ const state: any = {
+ hfToken: null,
+ params: { maxSeqLength: 4096, checkpoint: "" },
+ activeGgufVariant: null,
+ activePresetSource: null,
+ gpuMemoryMode: "auto",
+ selectedGpuIds: null,
+ models: [],
+ setCheckpoint: () => {},
+ setModelRequiresTrustRemoteCode: () => {},
+ setParams: (p: any) => { state.params = p; },
+ setModels: (m: any[]) => { state.models = m; },
+ };
+ return state;
+}
+let STORE: any = makeStore();
+const useChatRuntimeStore = {
+ getState: () => STORE,
+ setState: (_p: any) => {},
+};
+
+function createLoadingToastIcon() { return null; }
+const toast: any = Object.assign(
+ (_msg: string, _opts?: any) => "toast-id",
+ {
+ message: (msg: string, opts?: any) => {
+ EVENTS.push({ kind: "toast.message", msg, description: opts?.description });
+ return "toast-id";
+ },
+ success: (msg: string) => EVENTS.push({ kind: "toast.success", msg }),
+ error: (msg: string, opts?: any) =>
+ EVENTS.push({ kind: "toast.error", msg, description: opts?.description }),
+ dismiss: () => EVENTS.push({ kind: "toast.dismiss" }),
+ info: (msg: string) => EVENTS.push({ kind: "toast.info", msg }),
+ },
+);
+
+async function tryAdoptServerActiveModel() { return false; }
+function resolveSpeculativeSettingsForLoad() {
+ return { speculativeType: null, specDraftNMax: 0 };
+}
+function readLastLocalModelLoad() { return SCENARIO.lastLoaded; }
+function recordLastLocalModelLoad(_x: any) {}
+function resolveInitialConfig(_id: string, _variant: any) {
+ return { config: {
+ customContextLength: null, maxSeqLength: null, gpuMemoryMode: null,
+ gpuLayers: null, nCpuMoe: null, selectedGpuIds: undefined,
+ speculativeType: null, specDraftNMax: null, chatTemplateOverride: null,
+ kvCacheDtype: null, tensorParallel: false,
+ } };
+}
+function resolveLoadMaxSeqLength(args: any) { return args.maxSeqLength ?? 0; }
+function resolveFitMaxSeqLength(..._a: any[]) { return 0; }
+function resolveManualAutoCtxPin(..._a: any[]) { return null; }
+async function ensureGpuDeviceCache() {}
+function reconcilePersistedGpuIds(ids: any) { return ids; }
+function saveSpeculativeType(_x: any) {}
+function persistGpuMemoryModeOnLoad(..._a: any[]) {}
+function reasoningCapsFromLoad(_x: any) { return {}; }
+function resolveToolsEnabledOnLoad(_x: any) { return {}; }
+function loadedGpuMemoryFields(_x: any) { return {}; }
+function resolveLoadedSpeculativeSettings(_x: any) { return {}; }
+function isMultimodalResponse(_x: any) { return false; }
+
+async function listCachedGguf() { return SCENARIO.ggufRepos as any; }
+async function listCachedModels() { return SCENARIO.modelRepos as any; }
+async function listGgufVariants(repoId: string, _b?: any, _c?: any) {
+ const entry = SCENARIO.variants[repoId];
+ if (entry === "throw") throw new Error("variant listing failed");
+ return entry ?? { variants: [] };
+}
+async function validateModel(payload: any) {
+ const result = SCENARIO.validate(payload);
+ if (result instanceof Error) throw result;
+ return result;
+}
+async function loadModel(payload: any) {
+ const result = SCENARIO.load(payload);
+ EVENTS.push({
+ kind: "loadModel",
+ model_path: payload.model_path,
+ gguf_variant: payload.gguf_variant ?? null,
+ rejected: result instanceof Error,
+ });
+ if (result instanceof Error) throw result;
+ return result;
+}
+"""
+
+SCENARIO_HELPERS = """
+ const GEMMA = {
+ repo_id: "unsloth/gemma-4-26B-A4B-it-qat-GGUF",
+ load_id: "unsloth/gemma-4-26B-A4B-it-qat-GGUF",
+ cache_path:
+ "/home/john-doe/.cache/huggingface/hub/models--unsloth--gemma-4-26B-A4B-it-qat-GGUF",
+ size_bytes: 15800000000,
+ };
+ const GEMMA_VARIANTS = {
+ variants: [{
+ quant: "UD-Q4_K_XL",
+ filename: "UD-Q4_K_XL/gemma-4-26B-A4B-it-qat-UD-Q4_K_XL.gguf",
+ downloaded: true,
+ size_bytes: 15800000000,
+ }],
+ };
+ const OOM =
+ "Failed to load model: llama-server was stopped by the operating system " +
+ "(signal 9), most likely out of memory.";
+ const VALIDATE_OK = () => ({
+ requires_trust_remote_code: false,
+ requires_security_review: false,
+ requires_transformers_upgrade: false,
+ });
+ const LOADED = (payload) => ({
+ model: payload.model_path,
+ is_gguf: true,
+ context_length: 32768,
+ });
+ const scenario = (over) => ({
+ ggufRepos: [],
+ modelRepos: [],
+ variants: {},
+ lastLoaded: null,
+ validate: VALIDATE_OK,
+ load: LOADED,
+ ...over,
+ });
+"""
+
+
+def _require_node():
+ if shutil.which("node") is None:
+ pytest.skip("node not available")
+ if not ADAPTER.exists():
+ pytest.skip("studio chat sources not present")
+ try:
+ result = subprocess.run(
+ ["node", "--experimental-strip-types", "--version"],
+ capture_output = True,
+ text = True,
+ # A cold Windows runner is slow to start node; an impatient probe would fail the gate.
+ timeout = 60,
+ )
+ except (OSError, subprocess.SubprocessError):
+ pytest.skip("node could not be started")
+ if result.returncode != 0:
+ pytest.skip("node --experimental-strip-types not available")
+
+
+def _build_harness(run_dir: Path):
+ """Slice autoLoadSmallestModel and its helpers verbatim out of the adapter."""
+ lines = ADAPTER.read_text(encoding = "utf-8").splitlines()
+ start = next(
+ (i for i, line in enumerate(lines) if line.startswith("const MAX_AUTO_LOAD_ATTEMPTS")),
+ None,
+ )
+ end = next(
+ (
+ i
+ for i, line in enumerate(lines)
+ if line.startswith("export function createOpenAIStreamAdapter")
+ ),
+ None,
+ )
+ assert (
+ start is not None and end is not None and start < end
+ ), "could not locate the auto-load region in chat-adapter.ts"
+ body = "\n".join(lines[start:end])
+ assert "async function autoLoadSmallestModel" in body
+ (run_dir / "harness.ts").write_text(
+ "// @ts-nocheck\n" + PREAMBLE + "\n" + body + "\nexport { autoLoadSmallestModel };\n",
+ encoding = "utf-8",
+ )
+
+
+def _run(scenario_expr: str) -> dict:
+ _require_node()
+ # Its own directory per invocation: a shared file lets one runner read another's rewrite.
+ TEMP.mkdir(parents = True, exist_ok = True)
+ run_dir = Path(tempfile.mkdtemp(prefix = "run", dir = TEMP))
+ _build_harness(run_dir)
+ script = (
+ textwrap.dedent(
+ """
+ // @ts-nocheck
+ import { autoLoadSmallestModel, setScenario, EVENTS } from "./harness.ts";
+ """
+ )
+ + SCENARIO_HELPERS
+ + textwrap.dedent(
+ f"""
+ setScenario({scenario_expr});
+ const result = await autoLoadSmallestModel();
+ console.log(JSON.stringify({{ result, events: EVENTS }}));
+ """
+ )
+ )
+ (run_dir / "run.mts").write_text(script, encoding = "utf-8")
+ completed = subprocess.run(
+ ["node", "--experimental-strip-types", "--no-warnings", "run.mts"],
+ cwd = str(run_dir),
+ capture_output = True,
+ text = True,
+ timeout = 60,
+ env = dict(os.environ, NODE_NO_WARNINGS = "1"),
+ )
+ assert completed.returncode == 0, f"stderr: {completed.stderr}\nstdout: {completed.stdout}"
+ last = [line for line in completed.stdout.strip().splitlines() if line.strip()][-1]
+ return json.loads(last)
+
+
+def _loaded_paths(out: dict) -> list[str]:
+ return [event["model_path"] for event in out["events"] if event["kind"] == "loadModel"]
+
+
+def _toasts(out: dict, kind: str) -> list[dict]:
+ return [event for event in out["events"] if event["kind"] == kind]
+
+
+def test_failed_cached_load_does_not_download_the_default_model():
+ """The reported case: the only cached repo enumerates fine but its load OOMs, so auto-load stops
+ there rather than fetch a model the user never asked for."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " load: (p) => p.model_path === GEMMA.repo_id ? new Error(OOM) : LOADED(p) })"
+ )
+
+ assert _loaded_paths(out) == ["unsloth/gemma-4-26B-A4B-it-qat-GGUF"]
+ assert DEFAULT_MODEL not in _loaded_paths(out)
+ assert out["result"]["loaded"] is False
+ assert _toasts(out, "toast.success") == []
+ assert not any(
+ "Downloading a small model" in event["msg"] for event in _toasts(out, "toast.message")
+ )
+
+
+def test_failed_cached_load_surfaces_the_backend_reason():
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " load: () => new Error(OOM) })"
+ )
+
+ [error] = _toasts(out, "toast.error")
+ assert error["msg"] == "Could not load unsloth/gemma-4-26B-A4B-it-qat-GGUF (UD-Q4_K_XL)"
+ assert "out of memory" in error["description"]
+
+
+def test_load_rejection_without_a_message_still_names_the_model():
+ """Old backends and non-Error throws carry no detail; still name the model, not the default."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " load: () => new Error('') })"
+ )
+
+ assert DEFAULT_MODEL not in _loaded_paths(out)
+ [error] = _toasts(out, "toast.error")
+ assert "unsloth/gemma-4-26B-A4B-it-qat-GGUF (UD-Q4_K_XL)" in error["msg"]
+ assert error["description"]
+
+
+def test_empty_device_still_downloads_the_default_model():
+ """Nothing cached means nothing failed, so the download path is untouched."""
+ out = _run("scenario({})")
+
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert out["result"]["loaded"] is True
+ assert _toasts(out, "toast.error") == []
+ assert [event["msg"] for event in _toasts(out, "toast.success")] == [
+ "Loaded Qwen3.5-4B-MTP (UD-Q4_K_XL)"
+ ]
+
+
+def test_enumeration_failure_still_downloads_the_default_model():
+ """A repo whose variants cannot be listed never reached /load, so it keeps falling through."""
+ out = _run("scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: 'throw' } })")
+
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert out["result"]["loaded"] is True
+
+
+def test_consent_gated_candidate_still_downloads_the_default_model():
+ """trust_remote_code / security review block before the load: a deferral, not a failure."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " validate: (p) => p.model_path === GEMMA.repo_id"
+ " ? { requires_trust_remote_code: true, requires_security_review: false,"
+ " requires_transformers_upgrade: false } : VALIDATE_OK() })"
+ )
+
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert out["result"]["loaded"] is True
+
+
+def test_attempt_cap_still_gates_the_default_download():
+ """Four broken repos: the sweep tries smaller candidates, stops at three, never reaches the Hub."""
+ out = _run(
+ "scenario({ ggufRepos: [1, 2, 3, 4].map((i) => ({ ...GEMMA, repo_id: `r${i}`,"
+ " load_id: `r${i}`, size_bytes: i })),"
+ " variants: Object.fromEntries([1, 2, 3, 4].map((i) => [`r${i}`, GEMMA_VARIANTS])),"
+ " load: () => new Error(OOM) })"
+ )
+
+ assert _loaded_paths(out) == ["r1", "r2", "r3"]
+ assert DEFAULT_MODEL not in _loaded_paths(out)
+
+
+def test_a_later_cached_model_can_still_load_after_an_earlier_failure():
+ """One broken repo must not veto a working one; the failure toast is only for an empty sweep."""
+ out = _run(
+ "scenario({ ggufRepos: [1, 2].map((i) => ({ ...GEMMA, repo_id: `r${i}`,"
+ " load_id: `r${i}`, size_bytes: i })),"
+ " variants: { r1: GEMMA_VARIANTS, r2: GEMMA_VARIANTS },"
+ " load: (p) => p.model_path === 'r1' ? new Error(OOM) : LOADED(p) })"
+ )
+
+ assert _loaded_paths(out) == ["r1", "r2"]
+ assert out["result"]["loaded"] is True
+ assert _toasts(out, "toast.error") == []
+
+
+def test_reported_failure_is_flagged_so_callers_drop_the_generic_advice():
+ """Both send paths toast a generic "No model loaded" on loaded: false, burying the detailed one."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " load: () => new Error(OOM) })"
+ )
+
+ assert out["result"]["loaded"] is False
+ assert out["result"]["loadFailureReported"] is True
+
+
+def test_empty_device_does_not_flag_a_reported_failure():
+ """Nothing was attempted, so the callers must keep their generic advice."""
+ out = _run("scenario({ ggufRepos: [], models: [] })")
+
+ assert out["result"].get("loadFailureReported") is not True
+
+
+def test_a_resume_only_cached_row_is_skipped_so_the_default_still_downloads():
+ """An interrupted download leaves a partial / can_chat=false row for resume and delete; sweeping
+ it anyway would let its rejection suppress the default download."""
+ out = _run(
+ "scenario({ modelRepos: [{ repo_id: 'org/half', load_id: 'org/half',"
+ " size_bytes: 1, partial: true, capabilities: { can_chat: false } }],"
+ " load: (p) => p.model_path === 'org/half'"
+ " ? new Error('config.json not found') : LOADED(p) })"
+ )
+
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert out["result"]["loaded"] is True
+ assert _toasts(out, "toast.error") == []
+
+
+def test_a_can_chat_false_cached_row_is_skipped_on_its_own():
+ """The two fields are set independently, so can_chat alone must be enough to skip a row."""
+ out = _run(
+ "scenario({ ggufRepos: [{ ...GEMMA, capabilities: { can_chat: false } }],"
+ " variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " load: (p) => p.model_path === GEMMA.repo_id ? new Error(OOM) : LOADED(p) })"
+ )
+
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert out["result"]["loaded"] is True
+
+
+def test_the_last_used_model_is_skipped_when_its_row_went_partial():
+ """The last-used shortcut reads the same rows, so a cancelled update must not spend an attempt."""
+ out = _run(
+ "scenario({ ggufRepos: [{ ...GEMMA, partial: true }],"
+ " variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " lastLoaded: { id: GEMMA.repo_id, kind: 'gguf', ggufVariant: 'UD-Q4_K_XL' },"
+ " load: (p) => p.model_path === GEMMA.repo_id ? new Error(OOM) : LOADED(p) })"
+ )
+
+ assert _loaded_paths(out) == [DEFAULT_MODEL]
+ assert out["result"]["loaded"] is True
+
+
+def test_a_complete_cached_row_is_still_attempted():
+ """Guard on the filter: a healthy row is still swept, and an older backend omitting the fields
+ keeps its behaviour."""
+ out = _run(
+ "scenario({ ggufRepos: [{ ...GEMMA, partial: false, capabilities: { can_chat: true } }],"
+ " variants: { [GEMMA.repo_id]: GEMMA_VARIANTS } })"
+ )
+
+ assert _loaded_paths(out) == [GEMMA_REPO]
+ assert out["result"]["loaded"] is True
+
+
+def test_a_rejected_validation_does_not_download_the_default_model():
+ """A cached candidate can be refused by /validate rather than /load. The sweep's catches are
+ bare, so an unrecorded rejection reads as an empty device and fetches an unasked-for model."""
+ out = _run(
+ "scenario({ ggufRepos: [GEMMA], variants: { [GEMMA.repo_id]: GEMMA_VARIANTS },"
+ " validate: (p) => p.model_path === GEMMA.repo_id"
+ " ? new Error('snapshot no longer exists') : ({}) })"
+ )
+
+ assert DEFAULT_MODEL not in _loaded_paths(out)
+ assert out["result"]["loaded"] is False
+ assert out["result"]["loadFailureReported"] is True
+ [error] = _toasts(out, "toast.error")
+ assert error["msg"] == "Could not load unsloth/gemma-4-26B-A4B-it-qat-GGUF (UD-Q4_K_XL)"
+ assert "snapshot no longer exists" in error["description"]
+
+
+def test_a_rejected_validation_still_lets_a_later_cached_model_load():
+ """Control for the test above: recording must not end the sweep; only a declined dialog does."""
+ out = _run(
+ "scenario({ ggufRepos: [1, 2].map((i) => ({ ...GEMMA, repo_id: `r${i}`,"
+ " load_id: `r${i}`, size_bytes: i })),"
+ " variants: { r1: GEMMA_VARIANTS, r2: GEMMA_VARIANTS },"
+ " validate: (p) => p.model_path === 'r1'"
+ " ? new Error('snapshot no longer exists') : ({}) })"
+ )
+
+ assert _loaded_paths(out) == ["r2"]
+ assert out["result"]["loaded"] is True
+ assert _toasts(out, "toast.error") == []
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 0af3017a1fd..2c6adb90ad0 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -370,6 +370,74 @@ def test_local_picker_rows_require_chat_capability():
assert "row.capabilities.canChat" in memo.group(0)
+def test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned():
+ """The cached listing pins a snapshot when the repo's default ref reaches no copy
+ that loads, and it is the load that has to follow the pin. The id stays the repo
+ id everywhere it is shown, deduped or stored, so only model_path changes."""
+ inventory = _read("features/model-picker/inventory/use-chat-picker-inventory.ts")
+ for mapper in ("toCachedGgufRepo", "toCachedModelRepo"):
+ body = re.search(rf"function {mapper}\(.*?\n}}", inventory, re.S)
+ assert body, f"{mapper} not found"
+ assert "load_id: row.loadId" in body.group(0), f"{mapper} drops the pinned id"
+ # Delete sends this to remove the copy on screen, not the active cache's.
+ assert "cache_path: row.cachePath" in body.group(0), f"{mapper} drops the cache path"
+
+ meta = _read("features/model-picker/components/model-selector/types.ts")
+ assert "loadId?: string | null;" in meta
+
+ picker = _read("features/model-picker/components/model-selector/pickers.tsx")
+ assert "loadId={c.load_id}" in picker, "the quant list cannot pass on a pin it never gets"
+ # Both rows and the gear beside each: Run reloads through the same meta.
+ assert picker.count("loadId: c.load_id") == 2, "the safetensors row and its gear need the pin"
+ block = re.search(r"onConfigure\(repoId, \{.*?\n\s*\}", picker, re.S)
+ assert block and "loadId," in block.group(0), "the GGUF gear drops the pin"
+ # The variant click withholds it: a quant outside the pinned snapshot lands in a different one.
+ block = re.search(r"onSelect\(repoId, \{.*?\n\s*\}", picker, re.S)
+ assert block and "loadId: downloaded === true ? loadId : undefined," in block.group(0)
+ # localPath alone: preferLocalCache would answer from disk and drop the undownloaded quants.
+ assert (
+ "listGgufVariants(repoId, hfToken, localSource ? { localPath: localSource } : undefined)"
+ in picker
+ )
+ assert "cachePath={c.cache_path}" in picker
+
+ # A reload rebuilds its target from the checkpoint id, so the resident model remembers the pin.
+ page = _read("features/chat/chat-page.tsx")
+ assert "loadId: activeLoadId," in page
+ assert "activeLoadId: string | null;" in _read("features/chat/stores/chat-runtime-store.ts")
+
+ runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")
+ assert "activeLoadId: loadPath === modelId ? null : loadPath," in runtime
+ # A failed swap already unloaded the pinned model: reload it from the same place, pin and all.
+ assert "model_path: previousActiveLoadId || previousCheckpoint," in runtime
+ assert "activeLoadId: previousActiveLoadId ?? null," in runtime
+ # A model loaded outside this tab replaces the resident one, and the pin belonged to the old.
+ assert "useChatRuntimeStore.setState({ activeLoadId: null });" in runtime
+
+ # Auto-load keys identity off the backend, so the pin is recorded beside it, not in place of it.
+ adapter = _read("features/chat/api/chat-adapter.ts")
+ assert "activeLoadId: modelPath === candidate.id ? null : modelPath," in adapter
+ assert (
+ '(typeof selection === "string" ? null : selection.loadId) || modelId' in runtime
+ ), "loadPath must fall back to the id, so an unpinned pick is unchanged"
+ # Staged metadata, validate and load: all three read the copy that loads.
+ assert runtime.count("model_path: loadPath,") == 3
+ assert "model_path: modelId," not in runtime
+ # A rollback reads the approval under the snapshot path, so store it under both keys.
+ assert "rememberApprovedRemoteCode(loadPath, approvedRemoteCodeFingerprint);" in runtime
+ assert "approvedRemoteCodeFingerprints.get(previousCheckpoint) ?? null," in runtime
+
+
+def test_a_local_quant_short_a_shard_is_not_selectable():
+ """The variants endpoint now reports a local folder's torn quant as partial. A folder has no
+ download to resume, so the row has to say so and refuse the pick rather than send validate and
+ load at files that are not on disk."""
+ picker = _read("features/model-picker/components/model-selector/pickers.tsx")
+ assert "const unusableLocal = isLocalPath && v.partial === true;" in picker
+ assert "disabled={unusableLocal}" in picker
+ assert "incomplete" in picker
+
+
def test_model_picker_toolbar_reflows_before_crossing_picker_edge():
"""The content-sized section tabs and fixed-width dropdowns must reflow,
while an oversized tab group must shrink labels but preserve its icons."""
@@ -831,7 +899,10 @@ def test_chat_autoload_prepares_hf_token_before_gguf_metadata_preflight():
metadata = autoload.index("fetchGgufStagedMetadata({", prepare)
assert prepare < metadata
assert "hf_token: preparedToken.token" in autoload
- assert 'throw new Error("Model load cancelled.")' in autoload
+ # The throw carries the cancellation marker, so the sweep stops rather than reopen the dialog.
+ assert 'new Error("Model load cancelled.")' in autoload
+ assert "unslothUserCancelled: true" in autoload
+ assert "recordCandidateFailure(failureLabel, cancelled)" in autoload
def test_cpu_only_llama_build_hides_gpu_picker():
@@ -1201,6 +1272,74 @@ def test_vulkan_inference_devices_are_the_pickable_set():
assert 'diffusionPinnable: diffusionBackend && d.index_kind === "physical",' in src
+def test_chat_autoload_records_every_validation_failure():
+ """canAutoLoad runs validateModel, which prepares the token, so a dismissed dialog, a dead
+ backend or a model-specific rejection throws there rather than from loadModel. The sweep's
+ catches are bare, so an unrecorded one reads as an empty device and fetches the Hub default.
+ Only a declined dialog ends the sweep."""
+ adapter = _read("features/chat/api/chat-adapter.ts")
+ recorder = adapter.split("function recordCandidateFailure", 1)[1]
+ recorder = recorder.split("async function canAutoLoadRecordingFailures", 1)[0]
+ # Unconditional: no tag is consulted before recording, so a plain rejection counts too.
+ assert recorder.count("noteLoadFailure(label, error)") == 1
+ assert recorder.index("noteLoadFailure(label, error)") < recorder.index(
+ "unslothUserCancelled === true"
+ ), "recording must not sit behind a marker test"
+ # A declined dialog halts the sweep (retrying reopens it); nothing else does.
+ assert "unslothUserCancelled === true" in recorder
+ assert recorder.count("autoLoadCancelled = true;") == 1
+ assert recorder.index("unslothUserCancelled === true") < recorder.index(
+ "autoLoadCancelled = true;"
+ ), "the halt belongs to the cancellation branch alone"
+ # Rethrown by the wrapper, so the candidate still fails and control flow is unchanged.
+ wrapper = adapter.split("async function canAutoLoadRecordingFailures", 1)[1]
+ wrapper = wrapper.split("async function loadAutoLoadCandidate", 1)[0]
+ assert "recordCandidateFailure(label, error)" in wrapper
+ assert "throw error;" in wrapper
+ autoload = adapter.split("async function loadAutoLoadCandidate", 1)[1]
+ autoload = autoload.split("async function autoLoadSmallestModel", 1)[0]
+ # The preflight and the GGUF metadata probe both record, and a cancelled sweep skips the rest.
+ assert "canAutoLoadRecordingFailures(failureLabel, {" in autoload
+ assert "recordCandidateFailure(failureLabel, error)" in autoload
+ # The preflight's own cancellation goes through the helper too, or it records without halting.
+ assert "recordCandidateFailure(failureLabel, cancelled)" in autoload
+ assert "noteLoadFailure(failureLabel, cancelled)" not in autoload
+ assert "if (autoLoadCancelled || loadAttempts >= MAX_AUTO_LOAD_ATTEMPTS)" in autoload
+
+
+def test_auth_retries_tag_transport_failures_like_the_first_attempt():
+ """noteLoadFailure keys on the tag, so an untagged TypeError from a retry reads as a
+ rejection: retries reissue through retryWithCurrentToken, so it tags like the first attempt."""
+ src = (WORKDIR / "studio" / "frontend" / "src" / "features" / "auth" / "api.ts").read_text(
+ encoding = "utf-8"
+ )
+ assert src.count("unslothTransportFailure: true") == 2, "one tag per message, in one helper"
+ tagger = src.split("function asTransportFailure", 1)[1].split("\n}\n", 1)[0]
+ assert "err instanceof TypeError" in tagger
+ assert "navigator.onLine === false" in tagger
+ retry = src.split("async function retryWithCurrentToken", 1)[1]
+ retry = retry.split("\n}\n", 1)[0]
+ assert "fetchWithTauriNetworkRetry" in retry
+ assert "throw asTransportFailure(err);" in retry
+ first = src.split("export async function authFetch", 1)[1]
+ assert "throw asTransportFailure(err);" in first
+
+
+def test_external_readoption_drops_a_pin_taken_for_another_model():
+ """Status polling skips its own pin clearing while an external provider is selected, so the
+ re-adoption branch can adopt a resident the pin was never taken for and Apply would reload the
+ old model. The branch has to clear it itself."""
+ src = _read("features/chat/hooks/use-chat-model-runtime.ts")
+ branch = src.split("if (!forceReload && isExternalModelId(selectedCheckpoint))", 1)[1]
+ branch = branch.split("const stopDecision = await confirmStopRunningChatsIfNeeded", 1)[0]
+ assert "activeLoadId !== modelId" in branch
+ assert "setState({ activeLoadId: null })" in branch
+ # Clearing must land before the checkpoint moves, so nothing reads the pair half updated.
+ assert branch.index("activeLoadId: null") < branch.index(
+ ".setCheckpoint(modelId, residentStatus.gguf_variant)"
+ ), "the pin must be cleared before the checkpoint is adopted"
+
+
def test_only_gguf_configs_are_mirrored_to_the_server():
"""The server override map is read by the OpenAI-compatible auto-switch, and its
resolver indexes GGUFs only."""