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.

perf(studio): make local model inventory scans linear (#8043)

Long Yixinge96d020741ce
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 94096010017..14e2706e80d 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -18,7 +18,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 import download_manifest, download_registry
from hub.utils.hf_cache_state import snapshot_selection_key
from hub.utils.snapshot_filters import (
snapshot_download_blob_hashes,
@@ -59,6 +59,17 @@ _REPO_SIZE_NEG_TTL = 60.0
_MODEL_METADATA_TIMEOUT_SECONDS = 5.0
_repo_size_cache_lock = threading.Lock()
+
+_cached_inventory_flights: dict[
+ tuple[asyncio.AbstractEventLoop, tuple[str, int]], asyncio.Task[list[dict]]
+] = {}
+
+# Retrying a superseded scan is only worth it while invalidations are occasional;
+# past this the endpoint has to answer instead of restarting the walk forever.
+_INVENTORY_SCAN_MAX_ATTEMPTS = 8
+# Last scan per inventory name that confirmed its epoch, served when the cap is hit.
+_last_confirmed_inventory: dict[str, list[dict]] = {}
+
# Identity for a cached file with no HF blob (Windows without Developer Mode: hf
# moves the blob into snapshots/ and leaves blobs/ empty).
_LOCAL_SIZE_IDENTITY_PREFIX = "size:"
@@ -447,12 +458,41 @@ def _cached_row_task(repo_info, *, gguf: bool) -> Optional[str]:
return None
-def _scan_cached_gguf() -> list[dict]:
- """Synchronous HF-cache disk walk for GGUF repos; runs in a worker thread."""
- cache_scans = all_hf_cache_scans()
- from utils.hf_cache_settings import get_hf_cache_paths
+def _variant_state_repositories(cache_scans):
+ for cache_scan in cache_scans:
+ for repo in cache_scan.repos:
+ try:
+ if str(repo.repo_type) == "model":
+ yield "model", repo.repo_id, Path(repo.repo_path).parent
+ except Exception:
+ continue
- active_hub_cache = get_hf_cache_paths().hub_cache
+
+def _scan_cached_gguf(
+ *, cache_scans: Optional[list] = None, active_hub_cache: Optional[Path] = None
+) -> list[dict]:
+ """Synchronous HF-cache disk walk for GGUF repos; runs in a worker thread."""
+ if cache_scans is None:
+ cache_scans = all_hf_cache_scans()
+ if active_hub_cache is None:
+ from utils.hf_cache_settings import get_hf_cache_paths
+ active_hub_cache = get_hf_cache_paths().hub_cache
+ try:
+ variant_states = download_manifest.build_variant_state_index(
+ _variant_state_repositories(cache_scans),
+ active_hub_cache = active_hub_cache,
+ )
+ except Exception as e:
+ # Symmetric with _scan_cached_models below. The index is built once for the
+ # whole scan and outside the per-repository try, so one malformed repo
+ # identity anywhere in the cache took the endpoint with it: a cache
+ # directory name holding a byte the filesystem encoding cannot decode
+ # arrives as a lone surrogate, hashing it for the repo key raises, and
+ # /api/hub/cached-gguf answers 500 with every valid row hidden. Falling
+ # back to the per-repo reads this replaced costs speed on a broken cache
+ # and nothing else.
+ logger.warning("Could not build shared cached-GGUF state index: %s", e)
+ variant_states = None
seen_lower: dict[str, dict] = {}
for hf_cache in cache_scans:
@@ -462,11 +502,21 @@ def _scan_cached_gguf() -> list[dict]:
continue
repo_id = repo_info.repo_id
repo_path = Path(repo_info.repo_path)
+ variant_state = (
+ variant_states.for_repo(
+ "model",
+ repo_id,
+ hub_cache = repo_path.parent,
+ )
+ if variant_states is not None
+ else None
+ )
snapshot_path = _cached_model_snapshot_path(repo_path)
total_size = _repo_gguf_size_bytes(repo_info)
has_variant_state, variant_state_size = _gguf_variant_state_summary(
repo_id,
hub_cache = repo_path.parent,
+ variant_state = variant_state,
)
is_hidden_infra = _is_hidden_infra_repo(
repo_id,
@@ -485,6 +535,7 @@ def _scan_cached_gguf() -> list[dict]:
repo_id,
repo_path,
snapshot_dir = gguf_snapshot,
+ variant_state = variant_state,
)
if total_size == 0 and not partial:
continue
@@ -535,10 +586,55 @@ def _scan_cached_gguf() -> list[dict]:
return sorted(seen_lower.values(), key = lambda c: c["repo_id"])
+class _CacheSourceChanged(RuntimeError):
+ pass
+
+
+def _scan_cached_inventory_snapshot(scanner, expected_epoch: int) -> list[dict]:
+ from utils.hf_cache_settings import get_hf_cache_paths
+
+ active_hub_cache = get_hf_cache_paths().hub_cache
+ cache_scans = all_hf_cache_scans()
+ if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:
+ raise _CacheSourceChanged
+ rows = scanner(cache_scans = cache_scans, active_hub_cache = active_hub_cache)
+ # The walk itself takes seconds, so a delete or a finished download landing
+ # during it supersedes these rows just as surely as one landing before it:
+ # without this a repo deleted mid-scan is still listed in the response.
+ if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:
+ raise _CacheSourceChanged
+ return rows
+
+
+async def _shared_cached_inventory_scan(name: str, scanner) -> list[dict]:
+ for _attempt in range(_INVENTORY_SCAN_MAX_ATTEMPTS):
+ epoch = hf_cache_scan.hf_cache_scans_epoch()
+ try:
+ rows = await hf_cache_scan.shared_scan(
+ _cached_inventory_flights,
+ (name, epoch),
+ lambda expected_epoch = epoch: asyncio.to_thread(
+ _scan_cached_inventory_snapshot, scanner, expected_epoch
+ ),
+ )
+ except _CacheSourceChanged:
+ continue
+ _last_confirmed_inventory[name] = rows
+ return rows
+ # Invalidations are arriving faster than the walk completes, so no scan will
+ # confirm as current. Answer with the last one that did rather than spin a
+ # full cache walk per epoch forever.
+ logger.warning(
+ "Cached %s inventory kept racing cache invalidations; serving the last confirmed scan",
+ name,
+ )
+ return _last_confirmed_inventory.get(name, [])
+
+
async def list_cached_gguf_response(hf_token: Optional[str] = None):
"""List GGUF repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
try:
- cached = await asyncio.to_thread(_scan_cached_gguf)
+ cached = await _shared_cached_inventory_scan("gguf", _scan_cached_gguf)
return {"cached": cached}
except Exception as e:
logger.error(
@@ -832,12 +928,23 @@ def _cached_model_local_metadata(repo_path: Path, snapshot: Optional[Path] = Non
return result
-def _scan_cached_models() -> list[dict]:
+def _scan_cached_models(
+ *, cache_scans: Optional[list] = None, active_hub_cache: Optional[Path] = None
+) -> list[dict]:
"""Synchronous HF-cache disk walk for non-GGUF model repos; runs in a worker thread."""
- cache_scans = all_hf_cache_scans()
- from utils.hf_cache_settings import get_hf_cache_paths
-
- active_hub_cache = get_hf_cache_paths().hub_cache
+ if cache_scans is None:
+ cache_scans = all_hf_cache_scans()
+ if active_hub_cache is None:
+ from utils.hf_cache_settings import get_hf_cache_paths
+ active_hub_cache = get_hf_cache_paths().hub_cache
+ try:
+ variant_states = download_manifest.build_variant_state_index(
+ _variant_state_repositories(cache_scans),
+ active_hub_cache = active_hub_cache,
+ )
+ except Exception as e:
+ logger.warning("Could not build shared cached-model state index: %s", e)
+ variant_states = None
seen_lower: dict[str, dict] = {}
inspected = 0
@@ -890,6 +997,15 @@ def _scan_cached_models() -> list[dict]:
repo_id,
repo_path,
snapshot_dir = load_snapshot,
+ variant_state = (
+ variant_states.for_repo(
+ "model",
+ repo_id,
+ hub_cache = repo_path.parent,
+ )
+ if variant_states is not None
+ else None
+ ),
)
# A companion-only prefetch (pipeline manifest + VAE / text-encoder but no transformer shards, left by a GGUF load) passes
# the download check yet cannot from_pretrained, so mark it partial and the pickers stop advertising it as on-device.
@@ -969,7 +1085,7 @@ def _scan_cached_models() -> list[dict]:
async def list_cached_models_response(hf_token: Optional[str] = None):
"""List non-GGUF model repos downloaded to HF cache, legacy Unsloth cache, and HF default cache."""
try:
- cached = await asyncio.to_thread(_scan_cached_models)
+ cached = await _shared_cached_inventory_scan("models", _scan_cached_models)
return {"cached": cached}
except Exception as e:
logger.error(
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 150f750924c..c3b8a5b79e1 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -377,11 +377,17 @@ def _prefer_complete_larger(
def _gguf_variant_state_summary(
- repo_id: str, *, hub_cache: Optional[str | Path] = None
+ repo_id: str,
+ *,
+ hub_cache: Optional[str | Path] = None,
+ variant_state = None,
) -> tuple[bool, int]:
"""Whether GGUF variant-scoped state exists and its expected size; a cancelled/in-progress variant may have only manifests/markers/`.incomplete` blobs, which inventory needs to avoid a generic fallback row."""
from hub.utils import download_manifest
+ if variant_state is not None:
+ return variant_state.summary()
+
variant_keys: set[str] = set()
size_by_variant: dict[str, int] = {}
for variant, _path in download_manifest.iter_variant_manifests(
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index 7c204520bf4..9a1b1b60855 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import asyncio
import os
from pathlib import Path
-from typing import List, Optional
+from typing import List, NamedTuple, Optional
from fastapi import HTTPException
from loggers import get_logger
@@ -23,7 +23,7 @@ from hub.storage.scan_folders import (
list_scan_folders,
remove_scan_folder,
)
-from hub.utils import inventory_scan as hf_cache_scan
+from hub.utils import download_manifest, inventory_scan as hf_cache_scan
from hub.utils.paths import (
hf_default_cache_dir,
legacy_hf_cache_dir,
@@ -43,6 +43,35 @@ _MAX_MODELS_PER_CUSTOM_FOLDER = 200
_MAX_CUSTOM_FOLDER_ENTRIES = 2000
_MODEL_SIGNAL_PROBE_LIMIT = 200
+
+class _LocalInventorySources(NamedTuple):
+ hf_cache_dir: Path
+ legacy_hf: Path
+ hf_default: Path
+ lm_dirs: tuple[Path, ...]
+ ollama_dirs: tuple[Path, ...]
+ known_hf_caches: tuple[Path, ...]
+
+
+_LocalInventoryKey = tuple[str, _LocalInventorySources, tuple[str, ...], int]
+_local_inventory_flights: dict[
+ tuple[asyncio.AbstractEventLoop, _LocalInventoryKey], asyncio.Task[LocalModelListResponse]
+] = {}
+
+
+# Retrying a superseded scan is only worth it while invalidations are occasional;
+# past this the endpoint must answer instead of restarting the walk forever.
+_LOCAL_INVENTORY_MAX_ATTEMPTS = 8
+
+
+class _LocalCacheChanged(RuntimeError):
+ def __init__(self, response: LocalModelListResponse) -> None:
+ super().__init__("local inventory sources changed during the scan")
+ # Carried so the attempt cap can serve the freshest scan it has instead
+ # of looping forever or answering with nothing.
+ self.response = response
+
+
# Local aliases keep the extracted code close to the original implementation.
_is_model_directory = model_common._is_model_directory
_local_inventory_id = model_common._local_inventory_id
@@ -110,6 +139,18 @@ def _resolve_hf_cache_dir() -> Path:
return get_hf_cache_paths().hub_cache
+def _local_inventory_sources() -> _LocalInventorySources:
+ from utils.hf_cache_settings import known_hf_hub_caches
+ return _LocalInventorySources(
+ _resolve_hf_cache_dir(),
+ legacy_hf_cache_dir(),
+ hf_default_cache_dir(),
+ tuple(lmstudio_model_dirs()),
+ tuple(ollama_model_dirs()),
+ tuple(known_hf_hub_caches()),
+ )
+
+
def _scan_models_dir(
models_dir: Path,
*,
@@ -199,12 +240,9 @@ def _hf_repo_dir_has_content(repo_dir: Path) -> bool:
return False
-def _scan_hf_cache(
- cache_dir: Path,
- *,
- entry_limit: int | None = None,
- active_cache: bool = True,
-) -> List[LocalModelInfo]:
+def _discover_hf_cache(
+ cache_dir: Path, *, entry_limit: int | None = None
+) -> list[tuple[Path, str, Optional[float]]]:
if not _safe_is_dir(cache_dir):
return []
@@ -233,18 +271,58 @@ def _scan_hf_cache(
except OSError:
updated_at = None
discovered.append((repo_dir, model_id, updated_at))
+ return discovered
+
+
+def _scan_hf_cache(
+ cache_dir: Path,
+ *,
+ entry_limit: int | None = None,
+ active_cache: bool = True,
+ discovered: Optional[list[tuple[Path, str, Optional[float]]]] = None,
+ variant_states: Optional[download_manifest.VariantStateIndex] = None,
+ active_hub_cache: Optional[Path] = None,
+) -> List[LocalModelInfo]:
+ if discovered is None:
+ discovered = _discover_hf_cache(cache_dir, entry_limit = entry_limit)
+ if not discovered:
+ return []
+ if variant_states is None:
+ # Reached precisely when the caller's own guarded build already failed, so
+ # leaving this one bare handed the same exception straight back and undid
+ # that guard. Degrade to the per-repo reads instead, as the callers do.
+ try:
+ variant_states = download_manifest.build_variant_state_index(
+ [("model", model_id, cache_dir) for _repo, model_id, _updated in discovered],
+ active_hub_cache = active_hub_cache
+ or (cache_dir if active_cache else _resolve_hf_cache_dir()),
+ )
+ except Exception as e:
+ logger.warning("Could not build Hub-state index for %s: %s", cache_dir, e)
+ variant_states = None
found: list[LocalModelInfo] = []
for repo_dir, model_id, updated_at in discovered:
+ variant_state = (
+ variant_states.for_repo("model", model_id, hub_cache = cache_dir)
+ if variant_states is not None
+ else None
+ )
snapshot_partial = hf_cache_scan.is_snapshot_partial(
"model",
model_id,
repo_dir,
+ variant_state = variant_state,
+ )
+ gguf_partial = hf_cache_scan.is_gguf_repo_partial(
+ model_id,
+ repo_dir,
+ variant_state = variant_state,
)
- gguf_partial = hf_cache_scan.is_gguf_repo_partial(model_id, repo_dir)
has_gguf_variant_state, gguf_variant_state_size = _gguf_variant_state_summary(
model_id,
hub_cache = cache_dir,
+ variant_state = variant_state,
)
snapshot_partial_transport = (
hf_cache_scan.partial_transport_for(
@@ -456,6 +534,18 @@ def _resolve_allowed_models_dir(models_dir: str, allowed_roots: list[Path]) -> P
raise ValueError("Directory not allowed")
+def _inventory_path_identity(raw_path: str) -> str:
+ """Canonical identity for scan roots used in shared-flight keys."""
+ raw = raw_path.strip()
+ try:
+ normalized = normalize_path(raw)
+ return os.path.normcase(os.path.realpath(os.path.expanduser(normalized)))
+ except (OSError, UnicodeError, ValueError):
+ # Keep malformed sources distinct until the worker's existing request or
+ # per-folder error boundary turns them into a 403/skip.
+ return os.path.normcase(raw)
+
+
def _coerce_scan_folder_path(raw_path: str) -> str:
"""Normalize a scan registration target; the registry stores directories, so a pasted weight-file path is reduced to its parent folder."""
if not raw_path or not raw_path.strip():
@@ -518,45 +608,75 @@ async def _collect_models_from_default_sources(
hf_cache_dir: Path,
legacy_hf: Path,
hf_default: Path,
- lm_dirs: list[Path],
- ollama_dirs: list[Path],
+ lm_dirs: tuple[Path, ...],
+ ollama_dirs: tuple[Path, ...],
+ known_hf_caches: tuple[Path, ...],
+ custom_folders: list[dict],
) -> List[LocalModelInfo]:
local_models = await _scan_source("models directory", _scan_models_dir, models_root)
- local_models += await _scan_source("HF cache", _scan_hf_cache, hf_cache_dir)
+ hf_sources = [("HF cache", hf_cache_dir, True)]
if _safe_is_dir(legacy_hf) and legacy_hf.resolve() != hf_cache_dir.resolve():
- local_models += await _scan_source(
- "legacy HF cache",
- lambda path: _scan_hf_cache(path, active_cache = False),
- legacy_hf,
- )
+ hf_sources.append(("legacy HF cache", legacy_hf, False))
if (
_safe_is_dir(hf_default)
and hf_default.resolve() != hf_cache_dir.resolve()
and hf_default.resolve() != legacy_hf.resolve()
):
- local_models += await _scan_source(
- "default HF cache",
- lambda path: _scan_hf_cache(path, active_cache = False),
- hf_default,
- )
-
- from utils.hf_cache_settings import known_hf_hub_caches
+ hf_sources.append(("default HF cache", hf_default, False))
seen_hf = {
os.path.normcase(str(path.resolve(strict = False)))
for path in (hf_cache_dir, legacy_hf, hf_default)
}
- for previous_cache in known_hf_hub_caches():
+ for previous_cache in known_hf_caches:
key = os.path.normcase(str(previous_cache.resolve(strict = False)))
if key in seen_hf:
continue
seen_hf.add(key)
+ hf_sources.append(("previous HF cache", previous_cache, False))
+
+ discovered_sources = []
+ custom_sources = []
+ state_repositories = []
+ for label, cache_dir, active_cache in hf_sources:
+ discovered = await _scan_source(label, _discover_hf_cache, cache_dir)
+ discovered_sources.append((label, cache_dir, active_cache, discovered))
+ state_repositories.extend(
+ ("model", model_id, cache_dir) for _repo, model_id, _updated in discovered
+ )
+ for folder in custom_folders:
+ folder_path = Path(normalize_path(folder["path"])).expanduser()
+ discovered = await _scan_source(
+ "custom HF cache",
+ lambda path: _discover_hf_cache(path, entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES),
+ folder_path,
+ )
+ custom_sources.append((folder_path, discovered))
+ state_repositories.extend(
+ ("model", model_id, folder_path) for _repo, model_id, _updated in discovered
+ )
+ try:
+ variant_states = await asyncio.to_thread(
+ download_manifest.build_variant_state_index,
+ state_repositories,
+ active_hub_cache = hf_cache_dir,
+ )
+ except Exception as e:
+ logger.warning("Could not build shared Hub-state index: %s", e)
+ variant_states = None
+ for label, cache_dir, active_cache, discovered in discovered_sources:
local_models += await _scan_source(
- "previous HF cache",
- lambda path: _scan_hf_cache(path, active_cache = False),
- previous_cache,
+ label,
+ lambda path, rows = discovered, active = active_cache: _scan_hf_cache(
+ path,
+ active_cache = active,
+ discovered = rows,
+ variant_states = variant_states,
+ active_hub_cache = hf_cache_dir,
+ ),
+ cache_dir,
)
for lm_dir in lm_dirs:
@@ -565,10 +685,30 @@ async def _collect_models_from_default_sources(
for ollama_dir in ollama_dirs:
local_models += await _scan_source("Ollama", scan_ollama_dir, ollama_dir)
+ for folder_path, discovered in custom_sources:
+ try:
+ custom_models = await asyncio.to_thread(
+ _scan_custom_folder,
+ folder_path,
+ discovered = discovered,
+ variant_states = variant_states,
+ active_hub_cache = hf_cache_dir,
+ )
+ except Exception as e:
+ logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)
+ continue
+ local_models.extend(_promote_to_custom_source(model) for model in custom_models)
+
return local_models
-def _scan_custom_folder(folder_path: Path) -> List[LocalModelInfo]:
+def _scan_custom_folder(
+ folder_path: Path,
+ *,
+ discovered: Optional[list[tuple[Path, str, Optional[float]]]] = None,
+ variant_states: Optional[download_manifest.VariantStateIndex] = None,
+ active_hub_cache: Optional[Path] = None,
+) -> List[LocalModelInfo]:
from utils.models.model_config import detect_gguf_model
supported_formats: set[ModelFormat] = {"gguf", "safetensors", "adapter"}
@@ -584,6 +724,9 @@ def _scan_custom_folder(folder_path: Path) -> List[LocalModelInfo]:
folder_path,
entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES,
active_cache = False,
+ discovered = discovered,
+ variant_states = variant_states,
+ active_hub_cache = active_hub_cache,
)
+ _scan_lmstudio_dir(folder_path, entry_limit = _MAX_CUSTOM_FOLDER_ENTRIES)
)
@@ -635,24 +778,13 @@ def _promote_to_custom_source(model: LocalModelInfo) -> LocalModelInfo:
)
-async def _collect_models_from_custom_folders() -> List[LocalModelInfo]:
+async def _load_custom_folders() -> list[dict]:
try:
- custom_folders = await asyncio.to_thread(list_scan_folders)
+ return await asyncio.to_thread(list_scan_folders)
except Exception as e:
logger.warning("Could not load custom scan folders: %s", e)
return []
- local_models: List[LocalModelInfo] = []
- for folder in custom_folders:
- folder_path = Path(normalize_path(folder["path"])).expanduser()
- try:
- custom_models = await asyncio.to_thread(_scan_custom_folder, folder_path)
- except Exception as e:
- logger.warning("Skipping unreadable scan folder %s: %s", folder_path, e)
- continue
- local_models.extend(_promote_to_custom_source(m) for m in custom_models)
- return local_models
-
def _dedupe_local_models(local_models: List[LocalModelInfo]) -> list[LocalModelInfo]:
deduped: dict[str, LocalModelInfo] = {}
@@ -687,7 +819,7 @@ def _dedupe_local_models(local_models: List[LocalModelInfo]) -> list[LocalModelI
deduped[key] = model
return sorted(
deduped.values(),
- key = lambda item: (item.updated_at or 0),
+ key = lambda item: item.updated_at or 0,
reverse = True,
)
@@ -706,13 +838,11 @@ def _filter_hidden_models(local_models: List[LocalModelInfo]) -> list[LocalModel
return visible
-async def list_local_models_response(models_dir: str = "./models") -> LocalModelListResponse:
+async def _scan_local_models_response(
+ models_dir: str, custom_folders: list[dict], sources: _LocalInventorySources
+) -> LocalModelListResponse:
"""List local model candidates from every supported on-device source."""
- hf_cache_dir = _resolve_hf_cache_dir()
- legacy_hf = legacy_hf_cache_dir()
- hf_default = hf_default_cache_dir()
- lm_dirs = lmstudio_model_dirs()
- ollama_dirs = ollama_model_dirs()
+ hf_cache_dir, legacy_hf, hf_default, lm_dirs, ollama_dirs, known_hf_caches = sources
allowed_roots: list[Path] = [Path("./models").resolve(), hf_cache_dir]
if _safe_is_dir(legacy_hf):
@@ -734,17 +864,10 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel
hf_default,
lm_dirs,
ollama_dirs,
+ known_hf_caches,
+ custom_folders,
)
- local_models += await _collect_models_from_custom_folders()
models = _dedupe_local_models(_filter_hidden_models(local_models))
- # Tag each row with its pipeline task, as /api/models/local does: the Images and Video pickers filter On Device rows on
- # it and the chat picker routes a diffusion pick by it, so an untagged row is dropped. Imported lazily to avoid a cycle.
- try:
- from routes.models import _local_model_task
- models = [m.model_copy(update = {"task": _local_model_task(m)}) for m in models]
- except Exception as e: # noqa: BLE001 -- classification never breaks the listing
- logger.warning("Could not classify local model tasks: %s", e)
-
return LocalModelListResponse(
models_dir = str(models_root),
hf_cache_dir = str(hf_cache_dir),
@@ -760,6 +883,66 @@ async def list_local_models_response(models_dir: str = "./models") -> LocalModel
)
+async def list_local_models_response(models_dir: str = "./models") -> LocalModelListResponse:
+ """Coalesce overlapping local inventory requests for the same models root."""
+
+ def classify(response: LocalModelListResponse) -> LocalModelListResponse:
+ # These rows feed the same pickers as /api/models/local. Classified inside the
+ # shared worker so retrying waiters do not repeat GGUF metadata reads, and only
+ # for a response that is actually about to be served.
+ try:
+ from routes.models import _local_model_task
+ models = [
+ model.model_copy(update = {"task": _local_model_task(model)})
+ for model in response.models
+ ]
+ return response.model_copy(update = {"models": models})
+ except Exception as e: # noqa: BLE001 -- classification never breaks the listing
+ logger.warning("Could not classify local model tasks: %s", e)
+ return response
+
+ async def scan_and_classify(
+ expected_epoch: int, custom_folders: list[dict], sources: _LocalInventorySources
+ ) -> LocalModelListResponse:
+ response = await _scan_local_models_response(models_dir, custom_folders, sources)
+ if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:
+ raise _LocalCacheChanged(response)
+ return classify(response)
+
+ # Discard obsolete results and retry their waiters against the current cache epoch.
+ superseded: Optional[LocalModelListResponse] = None
+ for _attempt in range(_LOCAL_INVENTORY_MAX_ATTEMPTS):
+ # Epoch first: the sources and folders below are read after it, so any
+ # change to them lands in a later epoch and the post-scan check sees it.
+ epoch = hf_cache_scan.hf_cache_scans_epoch()
+ custom_folders = await _load_custom_folders()
+ sources = _local_inventory_sources()
+ key: _LocalInventoryKey = (
+ _inventory_path_identity(models_dir),
+ sources,
+ tuple(
+ _inventory_path_identity(str(folder.get("path", ""))) for folder in custom_folders
+ ),
+ epoch,
+ )
+ try:
+ return await hf_cache_scan.shared_scan(
+ _local_inventory_flights,
+ key,
+ lambda expected_epoch = epoch, folders = custom_folders, roots = sources: (
+ scan_and_classify(expected_epoch, folders, roots)
+ ),
+ )
+ except _LocalCacheChanged as changed:
+ superseded = changed.response
+ continue
+ # Invalidations are outpacing the walk, so no scan will ever confirm as
+ # current. Answer with the freshest one (the loop only reaches here through
+ # the retry path, so there is always one) instead of rescanning forever.
+ logger.warning("Local inventory kept racing cache invalidations; serving the last scan")
+ return classify(superseded)
+
+
def get_models_folder_response() -> dict:
"""Return the directory where downloaded models are stored.
diff --git a/studio/backend/hub/tests/conftest.py b/studio/backend/hub/tests/conftest.py
index 254045c8d7a..9b79c738b85 100644
--- a/studio/backend/hub/tests/conftest.py
+++ b/studio/backend/hub/tests/conftest.py
@@ -1,6 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+import itertools
import sys
import types
@@ -109,6 +110,30 @@ sys.modules.setdefault(
import pytest
[email protected](scope = "session")
+def _hub_studio_home_root(tmp_path_factory):
+ """One parent directory for every per-test studio home.
+
+ ``tmp_path_factory.mktemp`` scans the whole basetemp on every call to pick
+ the next number, so calling it once per test is quadratic in the number of
+ tests. Paid once per session here, the per-test cost below is a bare mkdir.
+ """
+ return tmp_path_factory.mktemp("hub_studio_homes")
+
+
+_studio_home_counter = itertools.count()
+
+
[email protected](autouse = True)
+def _isolate_studio_home(_hub_studio_home_root, monkeypatch):
+ home = _hub_studio_home_root / f"home-{next(_studio_home_counter)}"
+ home.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ for name, module in tuple(sys.modules.items()):
+ if name.startswith(("storage.", "hub.storage.")) and hasattr(module, "_schema_ready"):
+ monkeypatch.setattr(module, "_schema_ready", False)
+
+
@pytest.fixture(autouse = True)
def _reset_optional_module_memo():
"""Forget the shim's memoised optional-module results between tests.
diff --git a/studio/backend/hub/tests/test_model_services.py b/studio/backend/hub/tests/test_model_services.py
index 9e39d084a6a..1785f17b691 100644
--- a/studio/backend/hub/tests/test_model_services.py
+++ b/studio/backend/hub/tests/test_model_services.py
@@ -3,7 +3,10 @@
import asyncio
import json
+import os
import sys
+import threading
+from collections import Counter
from pathlib import Path
from types import SimpleNamespace
@@ -403,6 +406,564 @@ def test_inventory_scopes_cancel_markers_to_their_owning_cache(monkeypatch, tmp_
assert inventory_scan.is_variant_partial(repo_id, "Q4_K_M", repo_cache_dir = repo_b) is False
+def test_read_only_download_state_lookup_does_not_create_directories(monkeypatch, tmp_path):
+ studio_cache, hub_cache = tmp_path / "studio-cache", tmp_path / "hub-cache"
+ monkeypatch.setattr(state_dir, "cache_root", lambda: studio_cache)
+ state_key = ("model", "Org/Model", "Q4_K_M")
+ assert download_manifest.read_manifest(*state_key, hub_cache = hub_cache) is None
+ assert not download_manifest.has_cancel_marker(*state_key, hub_cache = hub_cache)
+ assert not studio_cache.exists()
+
+ state_root = studio_cache / "hub-state"
+ for dirname in ("manifests", "cancelled"):
+ (state_root / dirname).mkdir(parents = True)
+ download_manifest.build_variant_state_index(
+ [("model", "Org/Model", hub_cache)], active_hub_cache = hub_cache
+ )
+ scope = state_dir.cache_scope_name(hub_cache)
+ assert all(
+ not (state_root / dirname / scope).exists() for dirname in ("manifests", "cancelled")
+ )
+
+
+def test_cached_gguf_inventory_indexes_and_owns_polluted_state_once(monkeypatch, tmp_path):
+ studio_cache = tmp_path / "studio-cache"
+ hub_caches = [tmp_path / "cache-a", tmp_path / "cache-b"]
+ hub_cache = hub_caches[0]
+ monkeypatch.setattr(state_dir, "cache_root", lambda: studio_cache)
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = hub_cache),
+ )
+ repo_groups = [[], []]
+ repo_ids = ["variant/Model-0", "owner", "owner/variant"]
+ for index, repo_id in enumerate(repo_ids):
+ repo_cache = hub_caches[min(index, 1)]
+ repo_path = repo_cache / f"models--{repo_id.replace('/', '--')}"
+ repo_groups[min(index, 1)].append(
+ SimpleNamespace(repo_id = repo_id, repo_type = "model", repo_path = repo_path)
+ )
+ assert download_manifest.write_manifest(
+ "model",
+ repo_id,
+ "Q4_K_M",
+ [download_manifest.ExpectedFile(path = "model-Q4_K_M.gguf", size = index + 1)],
+ "http",
+ hub_cache = repo_cache,
+ )
+ if index != 1:
+ assert download_manifest.write_cancel_marker(
+ "model", repo_id, "Q4_K_M", "http", hub_cache = repo_cache
+ )
+
+ def marker_variants(repo_id):
+ return [
+ variant
+ for variant, _path in download_manifest.iter_variant_markers(
+ "model", repo_id, hub_cache = hub_caches[1]
+ )
+ ]
+
+ def state_marker(repo_id, variant, **kwargs):
+ return state_dir.marker_path("model", repo_id, variant, hub_cache = hub_caches[1], **kwargs)
+
+ def indexed_state(index, repo_id):
+ return index.for_repo("model", repo_id, hub_cache = hub_caches[1])
+
+ ambiguous = state_marker(repo_ids[2], "Q4_K_M", legacy_repo_key = True)
+ long_marker = state_marker("owner/variant", "Q4_K_M")
+ old_long_marker = state_marker("owner/variant", "Q4_K_M", legacy_hash_key = True)
+ literal_hash_repo = old_long_marker.stem.split("--variant--", 1)[0].removeprefix("models--")
+ assert len({long_marker, old_long_marker, state_marker(literal_hash_repo, "Q4_K_M")}) == 3
+ long_marker.unlink()
+ old_long_marker.write_text(json.dumps({"repo_id": "owner/variant", "variant": "Q4_K_M"}))
+ for order in (("owner/variant", literal_hash_repo), (literal_hash_repo, "owner/variant")):
+ state_index = download_manifest.build_variant_state_index(
+ [("model", repo_id, hub_caches[1]) for repo_id in order],
+ active_hub_cache = hub_caches[1],
+ )
+ assert indexed_state(state_index, "owner/variant").has_marker("Q4_K_M")
+ assert indexed_state(state_index, literal_hash_repo).summary() == (False, 0)
+ old_long_marker.unlink()
+ old_snapshot = state_marker("owner/variant", None, legacy_hash_key = True)
+ old_snapshot.write_text(json.dumps({"repo_id": literal_hash_repo}))
+ assert not download_manifest.purge_state("model", "owner/variant", hub_cache = hub_caches[1])
+ assert download_manifest.purge_state("model", literal_hash_repo, hub_cache = hub_caches[1])
+ old_snapshot.write_text("[")
+ for repo_id in ("owner/variant", literal_hash_repo):
+ assert not download_manifest.purge_state("model", repo_id, hub_cache = hub_caches[1])
+ old_snapshot.unlink()
+ owner_marker = state_marker("owner", "variant--Q4_K_M")
+ old_owner_marker = state_marker("owner", "variant--Q4_K_M", legacy_hash_key = True)
+ literal_hash_variant = old_owner_marker.stem.rsplit("--variant--", 1)[-1]
+ assert len({owner_marker, old_owner_marker, state_marker("owner", literal_hash_variant)}) == 3
+ old_owner_marker.write_text(json.dumps({"repo_id": "owner", "variant": literal_hash_variant}))
+ for variant, remains in (("variant--Q4_K_M", True), (literal_hash_variant, False)):
+ download_manifest.clear_cancel_marker("model", "owner", variant, hub_cache = hub_caches[1])
+ assert old_owner_marker.exists() is remains
+ old_owner_marker.write_text("[")
+ for variant in ("variant--Q4_K_M", literal_hash_variant):
+ download_manifest.clear_cancel_marker("model", "owner", variant, hub_cache = hub_caches[1])
+ assert old_owner_marker.is_file()
+ old_owner_marker.unlink()
+ ambiguous.write_text(json.dumps({"repo_id": "owner", "variant": "variant--Q4_K_M"}))
+ assert download_manifest.write_cancel_marker(
+ "model", "owner/variant", "Q4_K_M", "http", hub_cache = hub_caches[1]
+ )
+ assert download_manifest.has_cancel_marker(
+ "model", "owner", "variant--Q4_K_M", hub_cache = hub_caches[1]
+ )
+ download_manifest.clear_cancel_marker(
+ "model", "owner", "variant--Q4_K_M", hub_cache = hub_caches[1]
+ )
+ assert not ambiguous.exists()
+ old_manifest = state_dir.manifest_path(
+ "model",
+ "migration/model",
+ "legacy--Q4",
+ hub_cache = hub_caches[1],
+ legacy_hash_key = True,
+ )
+ old_manifest.write_text(
+ json.dumps(
+ {
+ "version": 1,
+ "repo_id": "migration/model",
+ "variant": "legacy--Q4",
+ "expected_files": [{"path": "old.gguf", "size": 1}],
+ }
+ )
+ )
+ migrated = download_manifest.read_manifest(
+ "model", "migration/model", "legacy--Q4", hub_cache = hub_caches[1]
+ )
+ assert migrated is not None and migrated.expected_files[0].size == 1
+ literal_hash_variant = old_manifest.stem.rsplit("--variant--", 1)[-1]
+ literal_manifest = download_manifest.read_manifest(
+ "model", "migration/model", literal_hash_variant, hub_cache = hub_caches[1]
+ )
+ assert literal_manifest is None
+ assert download_manifest.write_manifest(
+ "model",
+ "migration/model",
+ "legacy--Q4",
+ [download_manifest.ExpectedFile("new.gguf", 2)],
+ hub_cache = hub_caches[1],
+ )
+ unscoped_manifest = state_dir.manifest_path("model", "migration/model", "legacy--Q4")
+ assert unscoped_manifest is not None
+ stale_payload = json.loads(old_manifest.read_text())
+ stale_payload["expected_files"] = [{"path": "stale.gguf", "size": 3}]
+ unscoped_manifest.write_text(json.dumps(stale_payload))
+ migration = download_manifest.build_variant_state_index(
+ [("model", "migration/model", hub_caches[1])], active_hub_cache = hub_caches[0]
+ ).for_repo("model", "migration/model", hub_cache = hub_caches[1])
+ assert migration.manifest_for("legacy--q4").expected_files[0].size == 2
+ current_manifest = state_dir.manifest_path(
+ "model", "migration/model", "legacy--Q4", hub_cache = hub_caches[1]
+ )
+ current_manifest.unlink()
+ migration = download_manifest.build_variant_state_index(
+ [("model", "migration/model", hub_caches[1])], active_hub_cache = hub_caches[1]
+ ).for_repo("model", "migration/model", hub_cache = hub_caches[1])
+ assert migration.manifest_for("legacy--q4").expected_files[0].size == 1
+ unscoped_manifest.unlink()
+ assert download_manifest.purge_state(
+ "model", "migration/model", "legacy--Q4", hub_cache = hub_caches[1]
+ )
+ assert not old_manifest.exists()
+ ambiguous.write_text(
+ json.dumps({"repo_type": "model", "repo_id": "other/repo", "variant": "Q4_K_M"}),
+ encoding = "utf-8",
+ )
+ assert download_manifest.has_cancel_marker(
+ "model", "owner/variant", "Q4_K_M", hub_cache = hub_caches[1]
+ )
+ assert marker_variants("owner") == ["variant--q4_k_m"]
+ assert marker_variants("owner/variant") == ["Q4_K_M"]
+ partial = gguf.list_partial_gguf_variants_from_state("owner", hub_cache = hub_caches[1])
+ offline = {variant.quant: variant.filename for variant in partial[0]}
+ assert offline["variant--q4_k_m"] == "variant--q4_k_m.gguf"
+ ambiguous.write_text(
+ json.dumps({"repo_type": "model", "repo_id": "owner/variant", "variant": "Q8_0"})
+ )
+ assert marker_variants("owner/variant") == ["Q4_K_M"]
+ mismatched = download_manifest.build_variant_state_index(
+ [("model", repo_id, hub_caches[min(index, 1)]) for index, repo_id in enumerate(repo_ids)],
+ active_hub_cache = hub_caches[0],
+ ).for_repo("model", "owner/variant", hub_cache = hub_caches[1])
+ assert mismatched.has_marker("q4_k_m") and not mismatched.has_marker("q8_0")
+ ambiguous.write_text("[" * 10_000 + "0" + "]" * 10_000)
+ manifest_root = studio_cache / "hub-state" / "manifests"
+ marker_root = studio_cache / "hub-state" / "cancelled"
+ watched = {manifest_root, marker_root, *manifest_root.iterdir(), *marker_root.iterdir()}
+ calls, real_iterdir = Counter(), Path.iterdir
+
+ def counting_iterdir(path):
+ if path in watched:
+ calls[path] += 1
+ return real_iterdir(path)
+
+ monkeypatch.setattr(Path, "iterdir", counting_iterdir)
+ monkeypatch.setattr(
+ cache_inventory,
+ "all_hf_cache_scans",
+ lambda: [SimpleNamespace(repos = repos) for repos in repo_groups],
+ )
+ monkeypatch.setattr(cache_inventory, "_cached_model_snapshot_path", lambda _path: None)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_size_bytes", lambda _repo: 1)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_last_modified", lambda _repo: 0)
+ monkeypatch.setattr(cache_inventory, "_is_hidden_infra_repo", lambda *_args: False)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_payload_snapshots", lambda _repo: (None, ()))
+ monkeypatch.setattr(cache_inventory, "_cache_inventory_fields", lambda *_args, **_kw: {})
+ monkeypatch.setattr(
+ cache_inventory.hf_cache_scan,
+ "is_gguf_repo_partial",
+ lambda repo_id, _path, *, variant_state, **_kw: variant_state.has_marker(
+ "variant--q4_k_m" if repo_id == "owner" else "q4_k_m"
+ ),
+ )
+ rows = cache_inventory._scan_cached_gguf()
+ assert {(row["repo_id"], row["size_bytes"], row["partial"]) for row in rows} == {
+ (repo_id, index + 1, True) for index, repo_id in enumerate(repo_ids)
+ }
+ assert calls == Counter({path: 1 for path in watched})
+ assert download_manifest.write_manifest(
+ "model", "owner", "variant--Q4_K_M", [], "http", hub_cache = hub_caches[1]
+ )
+ assert download_manifest.write_cancel_marker(
+ "model", "owner/variant", "Q4_K_M", "http", hub_cache = hub_caches[1]
+ )
+ purge = download_manifest.purge_all_state_for_repo
+ assert purge("model", "owner", hub_cache = hub_caches[1]) == 2
+ assert ambiguous.is_file()
+ assert download_manifest.write_cancel_marker(
+ "model", "owner", "variant--Q4_K_M", "http", hub_cache = hub_caches[1]
+ )
+ owner_marker = state_marker("owner", "variant--Q4_K_M")
+ assert owner_marker is not None and owner_marker.is_file()
+ assert download_manifest.has_cancel_marker(
+ "model", "owner/variant", "Q4_K_M", hub_cache = hub_caches[1]
+ )
+ download_manifest.clear_cancel_marker(
+ "model", "owner/variant", "Q4_K_M", hub_cache = hub_caches[1]
+ )
+ assert download_manifest.purge_state(
+ "model", "owner/variant", "Q4_K_M", hub_cache = hub_caches[1]
+ )
+ assert owner_marker.is_file()
+ ambiguous.write_text("[" * 10_000 + "0" + "]" * 10_000)
+ assert download_manifest.has_cancel_marker(
+ "model", "owner/variant", "Q4_K_M", hub_cache = hub_caches[1]
+ )
+ assert not purge("model", "owner/variant", hub_cache = hub_caches[1])
+ assert ambiguous.is_file()
+
+
[email protected]("invalid_variant", [False, 0, [], {}])
+def test_manifest_parser_rejects_non_text_v2_variant(invalid_variant):
+ payload = {"version": 2, "repo_type": "model", "repo_id": "x"}
+ payload.update(variant = invalid_variant, expected_files = [])
+ assert download_manifest._manifest_from_payload(payload, "model", "x") is None
+
+
+ ("inventory_request", "scanner_name"),
+ [
+ (cache_inventory.list_cached_gguf_response, "_scan_cached_gguf"),
+ (cache_inventory.list_cached_models_response, "_scan_cached_models"),
+ ],
+)
+def test_cached_inventory_requests_share_scan(monkeypatch, inventory_request, scanner_name):
+ scans = submissions = 0
+ started, releases = [asyncio.Event(), asyncio.Event()], [asyncio.Event(), asyncio.Event()]
+ cached, epoch = [{"repo_id": "Org/Model"}], [0]
+
+ async def fake_to_thread(function, *args):
+ nonlocal submissions
+ index = submissions
+ submissions += 1
+ started[index].set()
+ await releases[index].wait()
+ return function(*args)
+
+ def scan(**_kwargs):
+ nonlocal scans
+ scans += 1
+ return cached
+
+ monkeypatch.setattr(cache_inventory.asyncio, "to_thread", fake_to_thread)
+ monkeypatch.setattr(cache_inventory, scanner_name, scan)
+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: [])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = Path("/cache")),
+ )
+ monkeypatch.setattr(cache_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])
+
+ async def run_requests():
+ first = asyncio.create_task(inventory_request())
+ await asyncio.wait_for(started[0].wait(), 1)
+ second = asyncio.create_task(inventory_request())
+ for _ in range(2):
+ await asyncio.sleep(0)
+ assert submissions == 1
+ first.cancel()
+ await asyncio.gather(first, return_exceptions = True)
+ epoch[0] += 1
+ changed = asyncio.create_task(inventory_request())
+ await asyncio.wait_for(started[1].wait(), 1)
+ releases[0].set()
+ for _ in range(2):
+ await asyncio.sleep(0)
+ releases[1].set()
+ return await asyncio.gather(second, changed)
+
+ assert asyncio.run(run_requests()) == [{"cached": cached}] * 2
+ assert scans == 1 and cache_inventory._cached_inventory_flights == {}
+
+
+ "scanner_name, inventory_call",
+ [
+ ("_scan_cached_gguf", "gguf"),
+ ("_scan_cached_models", "models"),
+ ],
+)
+def test_cached_inventory_discards_a_scan_that_raced_an_invalidation(
+ monkeypatch, scanner_name, inventory_call
+):
+ """A delete landing mid-scan must supersede the rows that scan produced.
+
+ The pre-scan epoch check only covers the source read; the walk itself takes
+ seconds, which is exactly when a download or deletion completes.
+ """
+ epoch, scans = [0], []
+
+ def scan(**_kwargs):
+ scans.append(1)
+ if len(scans) == 1:
+ epoch[0] += 1 # a deletion completes while this walk runs
+ return [{"repo_id": "Org/Deleted"}]
+ return [{"repo_id": "Org/Kept"}]
+
+ monkeypatch.setattr(cache_inventory, scanner_name, scan)
+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: [])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = Path("/cache")),
+ )
+ monkeypatch.setattr(cache_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])
+ monkeypatch.setattr(cache_inventory, "_last_confirmed_inventory", {})
+
+ rows = asyncio.run(cache_inventory._shared_cached_inventory_scan(inventory_call, scan))
+ assert rows == [{"repo_id": "Org/Kept"}], "rows from the superseded walk were served"
+ assert len(scans) == 2, "the superseded walk was not retried"
+ assert cache_inventory._cached_inventory_flights == {}
+
+
+def test_cached_inventory_scan_stops_retrying_under_constant_invalidation(monkeypatch):
+ """Bounded retries: an invalidation rate above the scan rate must still answer."""
+ epoch, scans = [0], []
+
+ def scan(**_kwargs):
+ scans.append(1)
+ epoch[0] += 1 # every walk is superseded before it returns
+ return [{"repo_id": "Org/Model"}]
+
+ monkeypatch.setattr(cache_inventory, "all_hf_cache_scans", lambda: [])
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = Path("/cache")),
+ )
+ monkeypatch.setattr(cache_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])
+ monkeypatch.setattr(cache_inventory, "_last_confirmed_inventory", {})
+
+ async def run():
+ return await asyncio.wait_for(
+ cache_inventory._shared_cached_inventory_scan("gguf", scan), timeout = 5
+ )
+
+ assert asyncio.run(run()) == []
+ assert len(scans) == cache_inventory._INVENTORY_SCAN_MAX_ATTEMPTS
+ assert cache_inventory._cached_inventory_flights == {}
+
+
+def test_shared_scan_scopes_tasks_to_event_loop():
+ flights, results = {}, []
+ barrier = threading.Barrier(3)
+
+ async def factory():
+ await asyncio.to_thread(barrier.wait)
+ return "ok"
+
+ def run():
+ results.append(asyncio.run(inventory_scan.shared_scan(flights, "same", factory)))
+
+ threads = [threading.Thread(target = run) for _ in range(2)]
+ [thread.start() for thread in threads]
+ barrier.wait(timeout = 1)
+ [thread.join() for thread in threads]
+ assert results == ["ok", "ok"] and flights == {}
+
+
+def test_local_inventory_scan_stops_retrying_under_constant_invalidation(monkeypatch):
+ """A churn rate above the scan rate must still answer, not walk the disk forever."""
+ from hub.services.models import local_inventory
+
+ epoch, scans = [0], []
+
+ async def fake_scan(models_dir, custom_folders, sources):
+ scans.append(1)
+ epoch[0] += 1 # every walk is superseded before it returns
+ return SimpleNamespace(models = [], model_copy = lambda update = None: SimpleNamespace(models = []))
+
+ async def no_folders():
+ return []
+
+ monkeypatch.setattr(local_inventory, "_scan_local_models_response", fake_scan)
+ monkeypatch.setattr(local_inventory, "_load_custom_folders", no_folders)
+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: ("roots",))
+ monkeypatch.setattr(local_inventory.hf_cache_scan, "hf_cache_scans_epoch", lambda: epoch[0])
+
+ async def run():
+ return await asyncio.wait_for(
+ local_inventory.list_local_models_response("./models"), timeout = 5
+ )
+
+ response = asyncio.run(run())
+ assert response is not None, "the capped loop must still answer"
+ assert len(scans) == local_inventory._LOCAL_INVENTORY_MAX_ATTEMPTS
+ assert local_inventory._local_inventory_flights == {}
+
+
[email protected]("change_kind", ["folders", "epoch"])
+def test_local_inventory_requests_share_scan(monkeypatch, change_kind):
+ # What the flight key needs from the helper is that it is total and stable on
+ # hostile input, not that it echoes it back. POSIX realpath() rejects an
+ # embedded NUL with ValueError so the raw string is normcased through; Windows
+ # non-strict realpath falls back to abspath and joins the cwd instead. Assert
+ # the property, not one platform's spelling of it.
+ for hostile in ("\0", "\ud800"):
+ identity = local_inventory._inventory_path_identity(hostile)
+ assert identity == local_inventory._inventory_path_identity(hostile)
+ assert identity.endswith(hostile)
+ event = asyncio.Event
+ calls, started, releases = 0, [event(), event()], [event(), event()]
+ loaded, both_loaded, task_calls, epoch = 0, event(), [], [0]
+ epoch_reads, retried = [0], event()
+ model = SimpleNamespace(id = "model")
+ model.model_copy = lambda update: SimpleNamespace(id = model.id, task = update["task"])
+ response = SimpleNamespace(models = [model])
+ response.model_copy = lambda update: SimpleNamespace(models = update["models"])
+ sources = local_inventory._local_inventory_sources()
+ monkeypatch.setattr(local_inventory, "_local_inventory_sources", lambda: sources)
+ monkeypatch.setitem(
+ sys.modules,
+ "routes.models",
+ SimpleNamespace(_local_model_task = lambda row: task_calls.append(row.id) or "task"),
+ )
+
+ async def scan(*_args):
+ nonlocal calls
+ index = calls
+ calls += 1
+ started[index].set()
+ await releases[index].wait()
+ return response
+
+ async def load_folders():
+ nonlocal loaded
+ loaded += 1
+ if loaded == 2:
+ both_loaded.set()
+ return [] if loaded < 4 or change_kind == "epoch" else [{"path": "/changed"}]
+
+ monkeypatch.setattr(local_inventory, "_load_custom_folders", load_folders)
+ monkeypatch.setattr(local_inventory, "_scan_local_models_response", scan)
+
+ def current_epoch():
+ epoch_reads[0] += bool(epoch[0])
+ if epoch_reads[0] == 3:
+ retried.set()
+ return epoch[0]
+
+ monkeypatch.setattr(local_inventory.hf_cache_scan, "hf_cache_scans_epoch", current_epoch)
+
+ async def run_requests():
+ first = asyncio.create_task(local_inventory.list_local_models_response("./models"))
+ await asyncio.wait_for(started[0].wait(), 1)
+ second = asyncio.create_task(
+ local_inventory.list_local_models_response(str(Path("models").resolve()))
+ )
+ await asyncio.wait_for(both_loaded.wait(), 1)
+ await asyncio.sleep(0)
+ assert calls == 1 and sources in next(iter(local_inventory._local_inventory_flights))[1]
+ first.cancel()
+ second.cancel()
+ await asyncio.gather(first, second, return_exceptions = True)
+ second = asyncio.create_task(local_inventory.list_local_models_response())
+ await asyncio.sleep(0)
+ epoch[0] += change_kind == "epoch"
+ changed = asyncio.create_task(local_inventory.list_local_models_response())
+ await asyncio.wait_for(started[1].wait(), 1)
+ assert calls == 2
+ releases[0].set()
+ if change_kind == "epoch":
+ await asyncio.wait_for(retried.wait(), 1)
+ releases[1].set()
+ return await asyncio.gather(second, changed)
+
+ assert [response.models[0].task for response in asyncio.run(run_requests())] == ["task"] * 2
+ expected_calls = ["model"] * (1 if change_kind == "epoch" else 2)
+ assert task_calls == expected_calls and not local_inventory._local_inventory_flights
+
+
+def test_local_inventory_indexes_registered_hf_state_once(monkeypatch, tmp_path):
+ active, custom = tmp_path / "active", tmp_path / "custom"
+ discoveries = {
+ active: [(active / "models--Org--Active", "Org/Active", None)],
+ custom: [(custom / "models--Org--Custom", "Org/Custom", None)],
+ }
+ monkeypatch.setattr(
+ local_inventory, "_discover_hf_cache", lambda path, **_kw: discoveries[path]
+ )
+ monkeypatch.setattr(local_inventory, "_scan_models_dir", lambda *_args, **_kw: [])
+ indexed = SimpleNamespace()
+ builds, propagated = [], []
+ monkeypatch.setattr(
+ download_manifest,
+ "build_variant_state_index",
+ lambda repositories, **_kw: builds.append(tuple(repositories)) or indexed,
+ )
+
+ def record_state(
+ *_args,
+ variant_states = None,
+ **_kwargs,
+ ):
+ propagated.append(variant_states)
+ return []
+
+ for name in ("_scan_hf_cache", "_scan_custom_folder"):
+ monkeypatch.setattr(local_inventory, name, record_state)
+
+ asyncio.run(
+ local_inventory._collect_models_from_default_sources(
+ tmp_path / "models",
+ active,
+ tmp_path / "missing-legacy",
+ tmp_path / "missing-default",
+ (),
+ (),
+ (),
+ [{"path": str(custom)}],
+ )
+ )
+ assert builds == [(("model", "Org/Active", active), ("model", "Org/Custom", custom))]
+ assert propagated == [indexed, indexed]
+
+
def test_list_local_gguf_variants_skips_big_endian_sibling(tmp_path):
(tmp_path / "model-Q4_K_M-be.gguf").write_bytes(b"x" * 100)
(tmp_path / "model-Q4_K_M.gguf").write_bytes(b"y" * 10)
@@ -481,9 +1042,9 @@ def test_download_state_bounds_long_repo_variant_filenames(monkeypatch, tmp_path
hub_cache = hub_cache,
)
- assert marker_path is not None
- assert manifest_path is not None
- assert "--sha256-" in marker_path.name
+ assert "--@sha256-" in marker_path.name
+ assert not state_dir.state_filename_is_ambiguous("models--sha256-model.json")
+ assert not state_dir.state_filename_is_ambiguous("models--owner--variant--sha256-q4.json")
assert len(marker_path.name.encode("utf-8")) <= 255
assert len(f".{marker_path.name}.tmp-00000000".encode("utf-8")) <= 255
assert download_manifest.has_cancel_marker("model", repo_id, variant)
@@ -494,6 +1055,9 @@ def test_download_state_bounds_long_repo_variant_filenames(monkeypatch, tmp_path
assert list(download_manifest.iter_variant_manifests("model", repo_id)) == [
(variant, manifest_path)
]
+ marker_path.write_text("[")
+ download_manifest.clear_cancel_marker("model", repo_id, variant)
+ assert not marker_path.exists()
assert download_manifest.purge_all_state_for_repo("model", repo_id) == 1
assert not download_manifest.has_cancel_marker("model", repo_id, variant)
assert download_manifest.read_manifest("model", repo_id, variant) is None
@@ -510,12 +1074,21 @@ def test_download_state_isolated_across_hub_cache_switches(monkeypatch, tmp_path
monkeypatch.setattr(hf_cache_settings, "get_hf_cache_paths", lambda: selected)
expected_a = [download_manifest.ExpectedFile(path = "a.gguf", size = 1)]
expected_b = [download_manifest.ExpectedFile(path = "b.gguf", size = 2)]
-
assert download_manifest.write_manifest("model", "Owner/Repo", "Q4_K_M", expected_a)
assert download_manifest.write_cancel_marker("model", "Owner/Repo", "Q4_K_M", "http")
selected.hub_cache = cache_b
assert download_manifest.write_manifest("model", "Owner/Repo", "Q4_K_M", expected_b)
+ index = download_manifest.build_variant_state_index(
+ [("model", "Owner/Repo", cache_a), ("model", "Owner/Repo", cache_b)],
+ active_hub_cache = cache_b,
+ )
+ indexed_a = index.for_repo("model", "Owner/Repo", hub_cache = cache_a)
+ indexed_b = index.for_repo("model", "Owner/Repo", hub_cache = cache_b)
+ assert indexed_a.manifest_for("Q4_K_M").expected_files == tuple(expected_a)
+ assert indexed_b.manifest_for("Q4_K_M").expected_files == tuple(expected_b)
+ assert indexed_a.has_marker("Q4_K_M")
+ assert not indexed_b.has_marker("Q4_K_M")
manifest_b = download_manifest.read_manifest("model", "Owner/Repo", "Q4_K_M")
manifest_a = download_manifest.read_manifest(
@@ -547,7 +1120,8 @@ def test_legacy_unscoped_download_state_falls_back_only_for_selected_cache(monke
)
manifest = state_dir.manifest_path("model", "Owner/Repo", "Q4_K_M")
marker = state_dir.marker_path("model", "Owner/Repo", "Q4_K_M")
- assert manifest is not None and marker is not None
+ manifest.parent.mkdir(parents = True)
+ marker.parent.mkdir(parents = True)
manifest.write_text(
json.dumps(
{
@@ -564,6 +1138,14 @@ def test_legacy_unscoped_download_state_falls_back_only_for_selected_cache(monke
json.dumps({"version": 1, "repo_id": "Owner/Repo", "variant": "Q4_K_M"}),
encoding = "utf-8",
)
+ index = download_manifest.build_variant_state_index(
+ [("model", "Owner/Repo", cache_a), ("model", "Owner/Repo", cache_b)],
+ active_hub_cache = cache_a,
+ )
+ legacy_a = index.for_repo("model", "Owner/Repo", hub_cache = cache_a)
+ legacy_b = index.for_repo("model", "Owner/Repo", hub_cache = cache_b)
+ assert legacy_a.manifest_for("Q4_K_M") is not None and legacy_a.has_marker("Q4_K_M")
+ assert legacy_b.summary() == (False, 0)
assert download_manifest.read_manifest("model", "Owner/Repo", "Q4_K_M") is not None
assert download_manifest.has_cancel_marker("model", "Owner/Repo", "Q4_K_M")
@@ -588,6 +1170,194 @@ def test_legacy_unscoped_download_state_falls_back_only_for_selected_cache(monke
"Q4_K_M",
hub_cache = cache_b,
)
+ assert download_manifest.purge_all_state_for_repo("model", "Owner/Repo", hub_cache = cache_b) == 0
+ assert manifest.is_file() and marker.is_file()
+ for invalid_cache in ("\ud800", "\0", "relative-cache", []):
+ marker.write_text(json.dumps({"repo_id": "\ud800", "hub_cache": invalid_cache}))
+ assert download_manifest.has_cancel_marker("model", "Owner/Repo", "Q4_K_M")
+ corrupt_index = download_manifest.build_variant_state_index(
+ [("model", "Owner/Repo", cache_a)], active_hub_cache = cache_a
+ )
+ assert corrupt_index.for_repo("model", "Owner/Repo", hub_cache = cache_a).has_marker("q4_k_m")
+ manifest_payload = json.loads(manifest.read_text(encoding = "utf-8"))
+ manifest_payload["hub_cache"] = 0
+ manifest.write_text(json.dumps(manifest_payload), encoding = "utf-8")
+ assert download_manifest.read_manifest("model", "Owner/Repo", "Q4_K_M") is None
+ manifest_payload.pop("hub_cache")
+ manifest_payload["repo_id"] = "\ud800"
+ manifest_payload["variant"] = "Q8_0"
+ manifest.write_text(json.dumps(manifest_payload), encoding = "utf-8")
+ assert download_manifest.read_manifest("model", "Owner/Repo", "Q4_K_M") is None
+ manifest_payload["repo_id"] = "Owner/Repo"
+ manifest_payload["variant"] = "Q4_K_M"
+ manifest.write_text(json.dumps(manifest_payload), encoding = "utf-8")
+ assert list(download_manifest.iter_variant_markers("model", "Owner/Repo")) == [
+ ("q4_k_m", marker)
+ ]
+ download_manifest.clear_cancel_marker("model", "Owner/Repo", "Q4_K_M")
+ assert not marker.exists()
+ marker.write_text(json.dumps({"repo_id": "Owner/Repo", "variant": "\ud800"}))
+ assert list(download_manifest.iter_variant_markers("model", "Owner/Repo"))[0][0] == "q4_k_m"
+ unsafe_manifest = json.loads(manifest.read_text(encoding = "utf-8"))
+ for unsafe_path in (
+ "\ud800",
+ "\0",
+ "",
+ "/outside",
+ "../outside",
+ "C:\\outside",
+ "\\outside",
+ ):
+ unsafe_manifest["expected_files"][0]["path"] = unsafe_path
+ manifest.write_text(json.dumps(unsafe_manifest), encoding = "utf-8")
+ assert download_manifest.read_manifest("model", "Owner/Repo", "Q4_K_M") is None
+ marker.write_text("[" * 10_000 + "0" + "]" * 10_000)
+ assert download_manifest.purge_state("model", "Owner/Repo", "Q4_K_M", hub_cache = cache_a)
+ assert not marker.exists()
+
+
+ "variant",
+ [
+ "unknown/variant with spaces", # unsafe characters force the hashed filename
+ "double--hyphen", # aliases the --variant-- delimiter, also hashed
+ "Q4_K_M", # spelled literally, the control
+ ],
+)
+def test_index_finds_an_unreadable_marker_stored_under_a_hashed_filename(
+ monkeypatch, tmp_path, variant
+):
+ """The index must agree with has_cancel_marker about a corrupt marker.
+
+ A marker whose payload will not parse stays fail-closed but loses its declared
+ variant, so the only identity left is the filename. When the variant is stored
+ hashed, that identity is the digest, and looking it up by variant name missed
+ it -- so a cancelled variant came back advertised as complete, while the
+ per-variant lookup still found the file by rebuilding the same digest.
+ """
+ hub_cache = tmp_path / "cache-a"
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "studio-cache")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = hub_cache),
+ )
+ assert download_manifest.write_cancel_marker(
+ "model", "Owner/Repo", variant, "http", hub_cache = hub_cache
+ )
+ marker = state_dir.marker_path("model", "Owner/Repo", variant, hub_cache = hub_cache)
+
+ def indexed():
+ index = download_manifest.build_variant_state_index(
+ [("model", "Owner/Repo", hub_cache)], active_hub_cache = hub_cache
+ )
+ return index.for_repo("model", "Owner/Repo", hub_cache = hub_cache).has_marker(variant)
+
+ assert indexed() and download_manifest.has_cancel_marker(
+ "model", "Owner/Repo", variant, hub_cache = hub_cache
+ )
+ marker.write_text("[")
+ assert download_manifest.has_cancel_marker(
+ "model", "Owner/Repo", variant, hub_cache = hub_cache
+ ), "per-variant lookup should stay fail-closed"
+ assert indexed(), "the index disagreed with has_cancel_marker about a corrupt marker"
+
+
+def test_cached_gguf_scan_degrades_when_the_shared_index_cannot_be_built(monkeypatch, tmp_path):
+ """A malformed repo identity must not take every valid row down with it.
+
+ The index is built once per scan and outside the per-repository ``try``, so an
+ exception there reaches the endpoint as a 500 and hides the whole inventory.
+ ``_scan_cached_models`` already degraded to per-repo reads; the GGUF path did
+ not, which is the asymmetry this covers.
+ """
+ hub_cache = tmp_path / "cache-a"
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "studio-cache")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = hub_cache),
+ )
+ # An undecodable byte in a cache directory name reaches us as a lone surrogate,
+ # and the repo key cannot be hashed from it. Spelled directly rather than via
+ # os.fsdecode(b"...\xff...") because Windows decodes filenames as UTF-8 with
+ # surrogatepass, where a bare 0xff raises instead of producing a surrogate.
+ # Nothing here touches the filesystem, so the string alone is the whole case.
+ bad_repo = "Org/Re\udcffpo"
+ repos = [
+ SimpleNamespace(
+ repo_id = repo_id,
+ repo_type = "model",
+ repo_path = hub_cache / f"models--{repo_id.replace('/', '--')}",
+ )
+ for repo_id in ("Org/Good", bad_repo)
+ ]
+ monkeypatch.setattr(
+ cache_inventory, "all_hf_cache_scans", lambda: [SimpleNamespace(repos = repos)]
+ )
+ monkeypatch.setattr(cache_inventory, "_cached_model_snapshot_path", lambda _path: None)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_size_bytes", lambda _repo: 1)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_last_modified", lambda _repo: 0)
+ monkeypatch.setattr(cache_inventory, "_is_hidden_infra_repo", lambda *_args: False)
+ monkeypatch.setattr(cache_inventory, "_repo_gguf_payload_snapshots", lambda _repo: (None, ()))
+ monkeypatch.setattr(cache_inventory, "_cache_inventory_fields", lambda *_a, **_kw: {})
+
+ with pytest.raises(UnicodeEncodeError):
+ download_manifest.build_variant_state_index(
+ [("model", bad_repo, hub_cache)], active_hub_cache = hub_cache
+ )
+
+ rows = cache_inventory._scan_cached_gguf()
+ assert "Org/Good" in {
+ row["repo_id"] for row in rows
+ }, "one unhashable repo identity emptied the whole GGUF inventory"
+
+
+def test_state_scan_survives_a_state_filename_with_an_undecodable_byte(monkeypatch, tmp_path):
+ """One corrupt filename must not take the whole inventory down with it.
+
+ A byte the filesystem encoding cannot decode comes back from iterdir() as a
+ lone surrogate, and hashing that for the canonical spelling raises
+ UnicodeEncodeError. Per-repo reads used to contain the damage to the repo
+ that owned the file. The index is built once per scan and outside the
+ per-repo try, so an escaping hash would 500 the endpoint and hide every
+ cached model, not just this one.
+ """
+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path)
+ cache = tmp_path / "cache-a"
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(hub_cache = cache),
+ )
+ assert download_manifest.write_cancel_marker(
+ "model", "Owner/Repo", "Q4_K_M", "http", hub_cache = cache
+ )
+ marker = state_dir.marker_path("model", "Owner/Repo", "Q4_K_M", hub_cache = cache)
+ corrupt = os.path.join(
+ os.fsencode(str(marker.parent)), b"models--Owner--Repo--variant--q\xff.json"
+ )
+ try:
+ with open(corrupt, "wb") as handle:
+ handle.write(json.dumps({"version": 2, "repo_type": "model"}).encode("utf-8"))
+ except (OSError, UnicodeError) as e:
+ # Only POSIX filesystems that accept arbitrary bytes can hold this name, so
+ # only there is the bug reachable. macOS rejects it with EILSEQ and Windows
+ # has no byte-level filename API at all.
+ pytest.skip(f"filesystem will not hold an undecodable filename: {e}")
+
+ index = download_manifest.build_variant_state_index(
+ [("model", "Owner/Repo", cache)], active_hub_cache = cache
+ )
+ state = index.for_repo("model", "Owner/Repo", hub_cache = cache)
+ assert state.has_marker("q4_k_m"), "the readable marker was lost to its corrupt neighbour"
+ assert state.summary()[0] is True
+
+ # The per-repo iterators keep enumerating past it too, surrogate name and all.
+ variants = [
+ variant
+ for variant, _path in download_manifest.iter_variant_markers(
+ "model", "Owner/Repo", hub_cache = cache
+ )
+ ]
+ assert "Q4_K_M" in variants and any("\udcff" in v for v in variants), variants
class _RecordingLogger:
@@ -943,7 +1713,6 @@ def test_cached_models_scan_hides_non_gguf_embedder(monkeypatch, tmp_path):
"is_snapshot_partial",
lambda _kind, _repo_id, _path, **_kw: False,
)
-
result = {"cached": cache_inventory._scan_cached_models()}
assert [row["repo_id"] for row in result["cached"]] == ["Org/Chat"]
@@ -2615,12 +3384,12 @@ def test_download_state_lookup_is_repo_case_insensitive(monkeypatch, tmp_path):
assert download_manifest.write_manifest(
"model",
"Owner/Repo",
- None,
+ "Q4_K_M",
[download_manifest.ExpectedFile(path = "config.json", size = 12)],
)
- assert download_manifest.write_cancel_marker("model", "Owner/Repo", "Q4_K_M", "http")
+ assert download_manifest.write_cancel_marker("model", "Owner/Repo", "q4_k_m", "http")
- manifest = download_manifest.read_manifest("model", "owner/repo", None)
+ manifest = download_manifest.read_manifest("model", "owner/repo", "q4_k_m")
assert manifest is not None
assert manifest.repo_id == "Owner/Repo"
@@ -2640,9 +3409,9 @@ def test_download_state_lookup_is_repo_case_insensitive(monkeypatch, tmp_path):
"model",
"owner/repo",
)
- ] == ["Q4_K_M"]
- assert download_manifest.purge_all_state_for_repo("model", "owner/repo") == 2
- assert download_manifest.read_manifest("model", "owner/repo", None) is None
+ ] == ["q4_k_m"]
+ assert download_manifest.purge_all_state_for_repo("model", "owner/repo") == 1
+ assert download_manifest.read_manifest("model", "owner/repo", "Q4_K_M") is None
def test_hf_cache_scan_fallback_row_uses_local_model_info_alias(monkeypatch, tmp_path):
diff --git a/studio/backend/hub/utils/download_manifest.py b/studio/backend/hub/utils/download_manifest.py
index f92ec946090..e011354f6c8 100644
--- a/studio/backend/hub/utils/download_manifest.py
+++ b/studio/backend/hub/utils/download_manifest.py
@@ -39,18 +39,21 @@ import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath, PureWindowsPath
-from typing import Iterator, Optional, Sequence
+from typing import Iterable, Iterator, Optional, Sequence
from urllib.parse import unquote
from loggers import get_logger
from hub.utils.state_dir import (
RepoType,
+ cache_scope_name,
cancelled_dir,
manifest_path,
manifests_dir,
marker_path,
+ state_filename_is_ambiguous,
variant_filename_prefix,
+ variant_key_fragments,
)
logger = get_logger(__name__)
@@ -92,6 +95,61 @@ class Manifest:
metadata_derived: bool = False
+class VariantState:
+ def __init__(
+ self,
+ manifests: Optional[dict[str, tuple[str, Optional[Manifest]]]] = None,
+ markers: Optional[dict[str, str]] = None,
+ ) -> None:
+ self._manifests = manifests or {}
+ self._markers = markers or {}
+
+ def manifests(self) -> Iterator[tuple[str, Optional[Manifest]]]:
+ yield from self._manifests.values()
+
+ def marker_variants(self) -> Iterator[str]:
+ yield from self._markers.values()
+
+ def manifest_for(self, variant: str) -> Optional[Manifest]:
+ entry = self._manifests.get(variant.lower())
+ return entry[1] if entry is not None else None
+
+ def has_marker(self, variant: str) -> bool:
+ if variant.lower() in self._markers:
+ return True
+ # An unreadable marker keeps its entry fail-closed but loses the payload,
+ # so its only remaining identity is the filename. For a variant that has to
+ # be stored hashed (slashes, spaces, `--`, an existing hash prefix) that
+ # identity is the digest, not the variant, and a plain lookup misses it --
+ # leaving a cancelled variant advertised as complete even though
+ # has_cancel_marker still finds the file by rebuilding the same digest.
+ # Match the spellings the variant could have been written under, as that
+ # per-variant lookup does.
+ try:
+ fragments = variant_key_fragments(variant)
+ except (UnicodeError, ValueError):
+ return False
+ return any(fragment in self._markers for fragment in fragments)
+
+ def summary(self) -> tuple[bool, int]:
+ return bool(self._manifests or self._markers), sum(
+ sum(max(0, int(file.size or 0)) for file in manifest.expected_files)
+ for _variant, manifest in self._manifests.values()
+ if manifest is not None
+ )
+
+
+class VariantStateIndex:
+ def __init__(self, states: dict[tuple[str, RepoType, str], VariantState]) -> None:
+ self._states = states
+
+ def for_repo(self, repo_type: RepoType, repo_id: str, *, hub_cache: str | Path) -> VariantState:
+ cache = _canonical_hub_cache(hub_cache)
+ if cache is None:
+ return VariantState()
+ return self._states.get((cache, repo_type, repo_id.lower()), VariantState())
+
+
@dataclass(frozen = True)
class VerifyResult:
ok: bool
@@ -116,12 +174,82 @@ def _canonical_hub_cache(hub_cache: Optional[str | Path] = None) -> Optional[str
def _read_state_payload(path: Path) -> Optional[dict]:
try:
data = json.loads(path.read_text(encoding = "utf-8"))
- except (OSError, ValueError) as exc:
+ # The decoder raises RecursionError for adversarially deep JSON. One corrupt
+ # state file must not abort the shared one-pass index: returning None lets
+ # manifests fail open and cancellation markers retain their fail-closed path.
+ except (OSError, ValueError, RecursionError) as exc:
logger.debug("Could not read Hub state %s: %s", path, exc)
return None
return data if isinstance(data, dict) else None
+def _manifest_from_payload(
+ data: Optional[dict], repo_type: RepoType, repo_id: str
+) -> Optional[Manifest]:
+ if data is None:
+ return None
+ version = data.get("version")
+ if (
+ not isinstance(version, int)
+ or isinstance(version, bool)
+ or version not in _SUPPORTED_MANIFEST_VERSIONS
+ ):
+ return None
+ payload_repo_id = _payload_text(data.get("repo_id"))
+ variant_value = data.get("variant")
+ raw_variant = _payload_text(variant_value)
+ if variant_value is not None and raw_variant is None:
+ return None
+ has_metadata_attestation = data.get("metadata_derived") is True
+ if version == _MANIFEST_VERSION or has_metadata_attestation:
+ if (
+ data.get("repo_type") != repo_type
+ or payload_repo_id is None
+ or payload_repo_id.casefold() != repo_id.casefold()
+ ):
+ return None
+ raw_files = data.get("expected_files")
+ if not isinstance(raw_files, list):
+ return None
+ expected: list[ExpectedFile] = []
+ for item in raw_files:
+ if not isinstance(item, dict):
+ return None
+ file_path = _payload_file_path(item.get("path"))
+ size = item.get("size")
+ if (
+ file_path is None
+ or not expected_path_is_safe(file_path)
+ or not isinstance(size, int)
+ or isinstance(size, bool)
+ or size < 0
+ ):
+ return None
+ sha256 = item.get("sha256")
+ expected.append(
+ ExpectedFile(
+ path = file_path,
+ size = size,
+ sha256 = sha256 if isinstance(sha256, str) and sha256 else None,
+ )
+ )
+ transport = data.get("transport")
+ commit_hash = normalized_commit_hash(data.get("commit_hash"))
+ metadata_derived = bool(has_metadata_attestation and commit_hash is not None)
+ return Manifest(
+ repo_type = repo_type,
+ repo_id = payload_repo_id or repo_id,
+ variant = raw_variant if raw_variant else None,
+ started_at = str(data.get("started_at", "")),
+ expected_files = tuple(expected),
+ transport = transport if transport in ("http", "xet") else None,
+ hub_cache = _payload_cache_path(data.get("hub_cache")),
+ version = version,
+ commit_hash = commit_hash if metadata_derived else None,
+ metadata_derived = metadata_derived,
+ )
+
+
def _legacy_state_applies(
path: Path,
requested_hub_cache: Optional[str],
@@ -137,9 +265,12 @@ def _legacy_state_applies(
"""
data = _read_state_payload(path)
if data is not None:
- recorded = data.get("hub_cache")
- if isinstance(recorded, str) and recorded:
+ raw_recorded = data.get("hub_cache")
+ recorded = _payload_cache_path(raw_recorded)
+ if recorded:
return _canonical_hub_cache(recorded) == requested_hub_cache
+ if "hub_cache" in data and raw_recorded not in (None, ""):
+ return fail_closed and requested_hub_cache == _canonical_hub_cache()
elif not fail_closed:
return False
return requested_hub_cache == _canonical_hub_cache()
@@ -154,22 +285,71 @@ def _state_read_path(
*,
fail_closed: bool = False,
) -> Optional[Path]:
+ def applies(path: Path) -> bool:
+ payload = _read_state_payload(path)
+ plausible = _state_payload_identity_matches_entry(path, payload, repo_type)
+ # Cancellation remains fail-closed when a marker cannot identify its
+ # owner. Parseable state from another repository is never borrowed.
+ if fail_closed and not plausible:
+ return True
+ if plausible and variant is not None:
+ recorded_variant = _payload_text(payload.get("variant"))
+ if recorded_variant is None:
+ return fail_closed
+ if recorded_variant.strip().lower() != variant.strip().lower():
+ return False
+ return _state_entry_belongs_to_repo(path, payload, repo_type, repo_id, variant)
+
requested = _canonical_hub_cache(hub_cache)
- scoped = path_factory(repo_type, repo_id, variant, hub_cache = requested)
- try:
- if scoped is not None and scoped.is_file():
- return scoped
- except OSError:
- pass
- legacy = path_factory(repo_type, repo_id, variant)
- if legacy is None or legacy == scoped:
- return None
- try:
- if not legacy.is_file():
- return None
- except OSError:
- return None
- return legacy if _legacy_state_applies(legacy, requested, fail_closed = fail_closed) else None
+ scoped = _state_paths(path_factory, repo_type, repo_id, variant, requested)
+ for path in scoped:
+ try:
+ if path.is_file() and applies(path):
+ return path
+ except OSError:
+ continue
+ for path in _state_paths(path_factory, repo_type, repo_id, variant, None):
+ if path in scoped:
+ continue
+ try:
+ if not path.is_file():
+ continue
+ except OSError:
+ continue
+ if _legacy_state_applies(path, requested, fail_closed = fail_closed) and applies(path):
+ return path
+ return None
+
+
+def _state_paths(
+ path_factory,
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str],
+ hub_cache: Optional[str | Path],
+) -> tuple[Path, ...]:
+ """Canonical-first read/delete paths across the filename migration.
+
+ Writers use only the default state-dir path. Readers and cleanup also probe
+ the prior repository and double-hyphen variant encodings, deduplicating when
+ a repository or variant never needed migration.
+ """
+ kwargs = {"hub_cache": hub_cache, "create": False}
+ paths = [
+ path_factory(
+ repo_type,
+ repo_id,
+ variant,
+ legacy_variant_key = legacy_variant,
+ legacy_repo_key = legacy_repo,
+ legacy_hash_key = legacy_hash,
+ **kwargs,
+ )
+ for legacy_repo in (False, True)
+ for legacy_variant in ((False, True) if variant is not None else (False,))
+ for legacy_hash in (False, True)
+ ]
+ return tuple(path for path in dict.fromkeys(paths) if path is not None)
def _atomic_write_json(path: Path, payload: dict) -> bool:
@@ -203,6 +383,21 @@ def _atomic_write_json(path: Path, payload: dict) -> bool:
return True
+def _unlink_state_paths(paths: Iterable[Optional[Path]]) -> bool:
+ removed = False
+ for path in dict.fromkeys(paths):
+ if path is None:
+ continue
+ try:
+ path.unlink()
+ removed = True
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ logger.debug("Could not remove Hub state %s: %s", path, exc)
+ return removed
+
+
def write_manifest(
repo_type: RepoType,
repo_id: str,
@@ -227,6 +422,7 @@ def write_manifest(
repo_id,
variant,
hub_cache = recorded_hub_cache,
+ create = True,
)
if path is None:
return False
@@ -293,81 +489,27 @@ def read_manifest(
variant,
hub_cache,
)
- if path is None or not path.is_file():
+ if path is None:
return None
data = _read_state_payload(path)
if data is None:
return None
- version = data.get("version")
- if (
- not isinstance(version, int)
- or isinstance(version, bool)
- or version not in _SUPPORTED_MANIFEST_VERSIONS
- ):
- logger.debug(
- "Manifest %s has unknown version %r; ignoring.",
- path,
- data.get("version"),
- )
+ payload_identity = _state_payload_identity(data)
+ if payload_identity is None or not _state_payload_identity_matches_entry(path, data, repo_type):
return None
- has_metadata_attestation = data.get("metadata_derived") is True
- if version == _MANIFEST_VERSION or has_metadata_attestation:
- recorded_repo_type = data.get("repo_type")
- recorded_repo_id = data.get("repo_id")
- recorded_variant = data.get("variant")
- if (
- recorded_repo_type != repo_type
- or not isinstance(recorded_repo_id, str)
- or recorded_repo_id.casefold() != repo_id.casefold()
- or not (recorded_variant is None or isinstance(recorded_variant, str))
- or (
- recorded_variant.strip().casefold()
- if isinstance(recorded_variant, str) and recorded_variant.strip()
- else None
- )
- != (variant.strip().casefold() if variant and variant.strip() else None)
- ):
- return None
- raw_files = data.get("expected_files")
- if not isinstance(raw_files, list):
+ recorded_type, recorded_id = payload_identity
+ if recorded_id != repo_id.lower() or recorded_type not in (None, repo_type):
return None
- expected: list[ExpectedFile] = []
- for item in raw_files:
- if not isinstance(item, dict):
- return None
- file_path = item.get("path")
- size = item.get("size")
- if (
- not isinstance(file_path, str)
- or not isinstance(size, int)
- or isinstance(size, bool)
- or size < 0
- ):
- return None
- sha256 = item.get("sha256")
- expected.append(
- ExpectedFile(
- path = file_path,
- size = size,
- sha256 = sha256 if isinstance(sha256, str) and sha256 else None,
- )
- )
- raw_variant = data.get("variant")
- transport = data.get("transport")
- commit_hash = normalized_commit_hash(data.get("commit_hash"))
- metadata_derived = bool(has_metadata_attestation and commit_hash is not None)
- return Manifest(
- repo_type = repo_type,
- repo_id = str(data.get("repo_id", repo_id)),
- variant = raw_variant if raw_variant else None,
- started_at = str(data.get("started_at", "")),
- expected_files = tuple(expected),
- transport = transport if transport in ("http", "xet") else None,
- hub_cache = data.get("hub_cache") if isinstance(data.get("hub_cache"), str) else None,
- version = version,
- commit_hash = commit_hash if metadata_derived else None,
- metadata_derived = metadata_derived,
+ manifest = _manifest_from_payload(data, repo_type, repo_id)
+ if manifest is None:
+ return None
+ recorded_variant = (
+ manifest.variant.strip().casefold()
+ if manifest.variant and manifest.variant.strip()
+ else None
)
+ requested_variant = variant.strip().casefold() if variant and variant.strip() else None
+ return manifest if recorded_variant == requested_variant else None
def _dataset_completion_variant(commit_hash: str) -> str:
@@ -674,6 +816,7 @@ def write_cancel_marker(
repo_id,
variant,
hub_cache = recorded_hub_cache,
+ create = True,
)
if path is None:
return False
@@ -718,7 +861,7 @@ def read_cancel_marker_transport(
variant,
hub_cache,
)
- if path is None or not path.is_file():
+ if path is None:
return None
data = _read_state_payload(path)
if data is None:
@@ -739,19 +882,37 @@ def _all_matching_state_paths(
) -> tuple[Path, ...]:
if parent is None:
return ()
- legacy_path = (
- manifest_path(repo_type, repo_id, variant)
- if parent.name == "manifests"
- else marker_path(repo_type, repo_id, variant)
- )
- if legacy_path is None:
+ path_factory = manifest_path if parent.name == "manifests" else marker_path
+ probes = _state_paths(path_factory, repo_type, repo_id, variant, None)
+ if not probes:
return ()
try:
- return tuple(path for path in parent.rglob(legacy_path.name) if path.is_file())
+ return tuple(
+ path for probe in probes for path in parent.rglob(probe.name) if path.is_file()
+ )
except OSError:
return ()
+def _owned_state_paths(
+ path_factory,
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str],
+ requested: Optional[str],
+ *,
+ fail_closed: bool,
+) -> list[Path]:
+ scoped = list(_state_paths(path_factory, repo_type, repo_id, variant, requested))
+ paths = list(scoped)
+ for legacy in _state_paths(path_factory, repo_type, repo_id, variant, None):
+ if legacy not in scoped and _legacy_state_applies(
+ legacy, requested, fail_closed = fail_closed
+ ):
+ paths.append(legacy)
+ return paths
+
+
def clear_cancel_marker(
repo_type: RepoType,
repo_id: str,
@@ -766,27 +927,27 @@ def clear_cancel_marker(
again at successful completion (cleans up if the start clear failed).
"""
requested = _canonical_hub_cache(hub_cache)
- path = marker_path(
+ paths = _owned_state_paths(
+ marker_path,
repo_type,
repo_id,
variant,
- hub_cache = requested,
+ requested,
+ fail_closed = True,
)
- legacy = marker_path(repo_type, repo_id, variant)
- paths = [path]
- if (
- legacy is not None
- and legacy != path
- and _legacy_state_applies(legacy, requested, fail_closed = True)
- ):
- paths.append(legacy)
- for target in paths:
- if target is None:
- continue
- try:
- target.unlink(missing_ok = True)
- except OSError as exc:
- logger.debug("Could not clear cancel marker %s: %s", target, exc)
+ paths = [
+ candidate
+ for candidate in paths
+ if candidate is not None
+ and _state_entry_belongs_to_repo(
+ candidate,
+ _read_state_payload(candidate),
+ repo_type,
+ repo_id,
+ variant,
+ )
+ ]
+ _unlink_state_paths(paths)
def has_cancel_marker(
@@ -805,10 +966,7 @@ def has_cancel_marker(
hub_cache,
fail_closed = True,
)
- try:
- return path is not None and path.is_file()
- except OSError:
- return False
+ return path is not None
def delete_manifest(
@@ -819,27 +977,27 @@ def delete_manifest(
hub_cache: Optional[str | Path] = None,
) -> bool:
requested = _canonical_hub_cache(hub_cache)
- path = manifest_path(
+ paths = _owned_state_paths(
+ manifest_path,
repo_type,
repo_id,
variant,
- hub_cache = requested,
+ requested,
+ fail_closed = False,
)
- legacy = manifest_path(repo_type, repo_id, variant)
- paths = [path]
- if legacy is not None and legacy != path and _legacy_state_applies(legacy, requested):
- paths.append(legacy)
- removed = False
- for target in paths:
- if target is None:
- continue
- try:
- if target.is_file():
- target.unlink()
- removed = True
- except OSError as exc:
- logger.debug("Could not delete manifest %s: %s", target, exc)
- return removed
+ paths = [
+ candidate
+ for candidate in paths
+ if candidate is not None
+ and _state_entry_belongs_to_repo(
+ candidate,
+ _read_state_payload(candidate),
+ repo_type,
+ repo_id,
+ variant,
+ )
+ ]
+ return _unlink_state_paths(paths)
def purge_state(
@@ -862,27 +1020,38 @@ def purge_state(
)
else:
requested = _canonical_hub_cache(hub_cache)
- candidates = [
- manifest_path(repo_type, repo_id, variant, hub_cache = hub_cache),
- marker_path(repo_type, repo_id, variant, hub_cache = hub_cache),
- ]
- # Legacy unscoped state is shared: an unowned file belongs to the active cache, so only purge
- # it when it belongs to the cache being deleted, else deleting an inactive cache erases the
- # active cache's resume/cancel state.
- for path_factory in (manifest_path, marker_path):
- legacy = path_factory(repo_type, repo_id, variant)
- if legacy is not None and _legacy_state_applies(legacy, requested):
- candidates.append(legacy)
- paths = tuple(p for p in candidates if p is not None)
- removed = False
- for path in paths:
- try:
- if path.is_file():
- path.unlink()
- removed = True
- except OSError as exc:
- logger.debug("Could not purge Hub state %s: %s", path, exc)
- return removed
+ candidates: list[Path] = []
+ # Legacy unscoped state is shared: an unowned file belongs to the active
+ # cache (per _legacy_state_applies), so only purge it when it belongs to
+ # the cache being deleted -- else deleting an inactive cache would erase
+ # the active cache's resume/cancel state.
+ for path_factory, fail_closed in (
+ (manifest_path, False),
+ (marker_path, True),
+ ):
+ candidates.extend(
+ _owned_state_paths(
+ path_factory,
+ repo_type,
+ repo_id,
+ variant,
+ requested,
+ fail_closed = fail_closed,
+ )
+ )
+ paths = tuple(dict.fromkeys(candidates))
+ paths = tuple(
+ path
+ for path in paths
+ if _state_entry_belongs_to_repo(
+ path,
+ _read_state_payload(path),
+ repo_type,
+ repo_id,
+ variant,
+ )
+ )
+ return _unlink_state_paths(paths)
def purge_all_state_for_repo(
@@ -898,52 +1067,407 @@ def purge_all_state_for_repo(
With ``hub_cache`` set, only that cache's scoped state (plus any legacy
unscoped file) is enumerated and removed, so deleting one cache's copy does
- not clear another cache's resumable/cancel state."""
+ not clear another cache's resumable/cancel state.
+
+ Variant entries are unlinked by their enumerated paths, never by
+ reconstructing the paired manifest/marker name. The legacy filename scheme
+ is not injective when repository IDs or variants contain ``variant``
+ delimiters, so a reconstructed counterpart can belong to another repo.
+ Valid payload identity decides ownership. Corrupt delimiter-ambiguous state
+ is retained as a safe orphan instead of risking an active download marker."""
removed = 0
if purge_state(repo_type, repo_id, None, hub_cache = hub_cache):
removed += 1
- variants: set[str] = set()
- prefix = variant_filename_prefix(repo_type, repo_id)
+ variant_paths: dict[str, set[Path]] = {}
+ prefixes = tuple(
+ dict.fromkeys(
+ variant_filename_prefix(
+ repo_type,
+ repo_id,
+ legacy_repo_key = legacy_repo,
+ legacy_hash_key = legacy_hash,
+ )
+ for legacy_repo in (False, True)
+ for legacy_hash in (False, True)
+ )
+ )
+ requested = _canonical_hub_cache(hub_cache)
if hub_cache is None:
- search = [(p, True) for p in (manifests_dir(), cancelled_dir()) if p is not None]
+ search = [
+ (parent, True, False, cancel_markers)
+ for parent, cancel_markers in (
+ (manifests_dir(), False),
+ (cancelled_dir(), True),
+ )
+ if parent is not None
+ ]
else:
# This cache's scoped dir plus the legacy unscoped base; glob (not rglob) so other caches are untouched.
search = []
- for scoped, base in (
- (manifest_path(repo_type, repo_id, None, hub_cache = hub_cache), manifests_dir()),
- (marker_path(repo_type, repo_id, None, hub_cache = hub_cache), cancelled_dir()),
+ for scoped, base, cancel_markers in (
+ (
+ manifest_path(
+ repo_type,
+ repo_id,
+ None,
+ hub_cache = hub_cache,
+ create = False,
+ ),
+ manifests_dir(create = False),
+ False,
+ ),
+ (
+ marker_path(
+ repo_type,
+ repo_id,
+ None,
+ hub_cache = hub_cache,
+ create = False,
+ ),
+ cancelled_dir(create = False),
+ True,
+ ),
):
if scoped is not None:
- search.append((scoped.parent, False))
+ search.append((scoped.parent, False, False, cancel_markers))
if base is not None:
- search.append((base, False))
- for parent, recursive in search:
+ search.append((base, False, True, cancel_markers))
+ for parent, recursive, legacy, cancel_markers in search:
try:
entries = tuple(
- parent.rglob(f"{prefix}*.json") if recursive else parent.glob(f"{prefix}*.json")
+ dict.fromkeys(
+ entry
+ for prefix in prefixes
+ for entry in (
+ parent.rglob(f"{prefix}*.json")
+ if recursive
+ else parent.glob(f"{prefix}*.json")
+ )
+ )
)
except OSError:
continue
for entry in entries:
if not entry.is_file():
continue
+ if legacy and not _legacy_state_applies(
+ entry,
+ requested,
+ fail_closed = cancel_markers,
+ ):
+ continue
+ prefix = next(
+ candidate for candidate in prefixes if entry.stem.lower().startswith(candidate)
+ )
fallback = entry.stem[len(prefix) :]
- variants.add(fallback)
- for variant in variants:
- if purge_state(repo_type, repo_id, variant, hub_cache = hub_cache):
+ payload = _read_state_payload(entry)
+ if not _state_entry_belongs_to_repo(entry, payload, repo_type, repo_id):
+ continue
+ variant = _variant_from_state_payload(payload, fallback)
+ variant_paths.setdefault(variant.lower(), set()).add(entry)
+ for paths in variant_paths.values():
+ if _unlink_state_paths(paths):
removed += 1
return removed
-def _variant_from_state_file(path: Path, fallback: str) -> str:
- try:
- data = json.loads(path.read_text(encoding = "utf-8"))
- except (OSError, ValueError):
- return fallback
- if not isinstance(data, dict):
+def _variant_from_state_payload(data: Optional[dict], fallback: str) -> str:
+ if data is None:
return fallback
- variant = data.get("variant")
- return variant if isinstance(variant, str) and variant else fallback
+ variant = _payload_text(data.get("variant"))
+ return variant if variant else fallback
+
+
+def _payload_text(value: object) -> Optional[str]:
+ """Return only text safe for the filename hashing and path helpers."""
+ if not isinstance(value, str):
+ return None
+ try:
+ value.encode("utf-8")
+ except UnicodeError:
+ return None
+ return value
+
+
+def _payload_file_path(value: object) -> Optional[str]:
+ """Accept only path text that Python filesystem APIs can consume.
+
+ Rejecting the whole malformed manifest preserves its fail-open contract.
+ """
+ text = _payload_text(value)
+ if text is None or "\0" in text or text in ("", "."):
+ return None
+ posix, windows = PurePosixPath(text), PureWindowsPath(text)
+ if (
+ posix.is_absolute()
+ or windows.is_absolute()
+ or windows.drive
+ or windows.root
+ or ".." in posix.parts
+ or ".." in windows.parts
+ ):
+ return None
+ return text
+
+
+def _payload_cache_path(value: object) -> Optional[str]:
+ """Return cache ownership only when it is safe for path normalization."""
+ text = _payload_text(value)
+ if text is None or "\0" in text:
+ return None
+ if not (PurePosixPath(text).is_absolute() or PureWindowsPath(text).is_absolute()):
+ return None
+ return text
+
+
+def _state_payload_identity(payload: Optional[dict]) -> Optional[tuple[Optional[RepoType], str]]:
+ if payload is None:
+ return None
+ recorded_type = payload.get("repo_type")
+ recorded_id = _payload_text(payload.get("repo_id"))
+ if recorded_id is None:
+ return None
+ repo_type = recorded_type if recorded_type in ("model", "dataset") else None
+ return repo_type, recorded_id.lower()
+
+
+def _state_payload_identity_matches_entry(
+ entry: Path, payload: Optional[dict], fallback_repo_type: RepoType
+) -> bool:
+ """Whether payload ownership could have generated this exact state name.
+
+ False means corrupt ownership, not automatically foreign ownership; callers
+ retain fail-closed or ambiguity-safe behavior according to their operation.
+ """
+ identity = _state_payload_identity(payload)
+ if identity is None:
+ return False
+ recorded_type, recorded_id = identity
+ recorded_variant = _payload_text(payload.get("variant")) if payload is not None else None
+ expected = _state_paths(
+ marker_path,
+ recorded_type or fallback_repo_type,
+ recorded_id,
+ recorded_variant,
+ None,
+ )
+ return any(path.name == entry.name for path in expected)
+
+
+def _state_entry_belongs_to_repo(
+ entry: Path,
+ payload: Optional[dict],
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str] = None,
+) -> bool:
+ """Attribute an exact state path without guessing across legacy delimiter
+ collisions; unreadable ambiguous names are retained rather than deleted."""
+ payload_identity = _state_payload_identity(payload)
+ # A parseable payload is authoritative even when its filename has multiple splits.
+ if payload_identity is not None and _state_payload_identity_matches_entry(
+ entry, payload, repo_type
+ ):
+ recorded_type, recorded_id = payload_identity
+ if recorded_id != repo_id.lower() or recorded_type not in (None, repo_type):
+ return False
+ if variant is None:
+ return True
+ recorded_variant = _payload_text(payload.get("variant"))
+ return recorded_variant is not None and (
+ recorded_variant.strip().lower() == variant.strip().lower()
+ )
+ return not state_filename_is_ambiguous(entry.name)
+
+
+def _state_file_records(
+ entry: Path, repo_keys: dict[str, set[tuple[RepoType, str]]], *, fail_closed: bool
+) -> tuple[tuple[RepoType, str, str, Optional[dict]], ...]:
+ name = entry.name
+ if not name.endswith(".json"):
+ return ()
+ stem = name[: -len(".json")]
+ try:
+ if not entry.is_file():
+ return ()
+ except OSError:
+ return ()
+ payload = _read_state_payload(entry)
+ lower_stem, separator = stem.lower(), "--variant--"
+ matches: list[tuple[tuple[RepoType, str], str]] = []
+ offset = lower_stem.find(separator)
+ while offset >= 0:
+ repos = repo_keys.get(stem[:offset].lower(), ())
+ fallback = stem[offset + len(separator) :]
+ if fallback:
+ matches.extend((repo, fallback) for repo in sorted(repos))
+ offset = lower_stem.find(separator, offset + 1)
+ if not matches:
+ return ()
+ payload_identity = _state_payload_identity(payload)
+ payload_identified = False
+ if payload_identity is not None:
+ if _state_payload_identity_matches_entry(entry, payload, matches[0][0][0]):
+ recorded_type, recorded_id = payload_identity
+ identified = [
+ match
+ for match in matches
+ if match[0][1] == recorded_id
+ and (recorded_type is None or match[0][0] == recorded_type)
+ ]
+ matches = identified
+ payload_identified = bool(identified)
+ elif not fail_closed:
+ matches = []
+ elif not fail_closed:
+ matches = []
+ variant_payload = payload if not fail_closed or payload_identified else None
+ return tuple(
+ (repo[0], repo[1], _variant_from_state_payload(variant_payload, fallback), payload)
+ for repo, fallback in matches
+ )
+
+
+def build_variant_state_index(
+ repositories: Iterable[tuple[RepoType, str, str | Path]], *, active_hub_cache: str | Path
+) -> VariantStateIndex:
+ targets: set[tuple[str, RepoType, str]] = set()
+ repo_keys: dict[str, set[tuple[RepoType, str]]] = {}
+ caches_by_scope: dict[str, set[str]] = {}
+ for repo_type, repo_id, hub_cache in repositories:
+ canonical_cache = _canonical_hub_cache(hub_cache)
+ if canonical_cache is None:
+ continue
+ normalized_repo = repo_id.lower()
+ targets.add((canonical_cache, repo_type, normalized_repo))
+ for legacy_repo in (False, True):
+ for legacy_hash in (False, True):
+ prefix = variant_filename_prefix(
+ repo_type,
+ repo_id,
+ legacy_repo_key = legacy_repo,
+ legacy_hash_key = legacy_hash,
+ )
+ repo_keys.setdefault(prefix[: -len("--variant--")], set()).add(
+ (repo_type, normalized_repo)
+ )
+ caches_by_scope.setdefault(cache_scope_name(canonical_cache), set()).add(canonical_cache)
+
+ active_cache = _canonical_hub_cache(active_hub_cache)
+ mutable: dict[
+ tuple[str, RepoType, str],
+ tuple[dict[str, tuple[str, Optional[Manifest], tuple[bool, bool]]], dict[str, str]],
+ ] = {}
+
+ def add_entry(
+ cache: Optional[str],
+ record: tuple[RepoType, str, str, Optional[dict]],
+ *,
+ cancel_marker: bool,
+ priority: tuple[bool, bool],
+ ) -> None:
+ if cache is None:
+ return
+ repo_type, repo_id, variant, payload = record
+ target = (cache, repo_type, repo_id)
+ if target not in targets:
+ return
+ manifests, markers = mutable.setdefault(target, ({}, {}))
+ key = variant.lower()
+ if cancel_marker:
+ markers.setdefault(key, variant)
+ elif key not in manifests or priority > manifests[key][2]:
+ manifests[key] = (
+ variant,
+ _manifest_from_payload(payload, repo_type, repo_id),
+ priority,
+ )
+
+ def add_path(
+ cache: Optional[str], entry: Path, record, *, cancel_marker: bool, scoped: bool
+ ) -> None:
+ repo_type, repo_id, variant, _payload = record
+ try:
+ canonical = marker_path(repo_type, repo_id, variant, create = False)
+ except (UnicodeError, ValueError, OSError):
+ # A state filename can carry a byte the filesystem encoding cannot
+ # decode, which iterdir() surfaces as a lone surrogate; hashing that
+ # for the canonical spelling raises UnicodeEncodeError. Per-repo
+ # reads used to contain the damage to the one repo that owned the
+ # file. This index is built once for the whole scan and outside the
+ # per-repo try, so letting it escape turns one corrupt filename into
+ # a 500 that hides every cached model. `canonical` only decides the
+ # "is this the canonical filename" half of `priority`, so treat the
+ # entry as non-canonical and keep indexing.
+ canonical = None
+ add_entry(
+ cache,
+ record,
+ cancel_marker = cancel_marker,
+ priority = (scoped, canonical is not None and canonical.name == entry.name),
+ )
+
+ def index_directory(parent: Optional[Path], *, cancel_markers: bool) -> None:
+ if parent is None:
+ return
+ try:
+ entries = list(parent.iterdir())
+ except OSError:
+ return
+ scoped = {entry.name: entry for entry in entries if entry.name in caches_by_scope}
+ for scope, caches in caches_by_scope.items():
+ directory = scoped.get(scope)
+ if directory is None:
+ continue
+ try:
+ scoped_entries = list(directory.iterdir())
+ except OSError:
+ continue
+ for entry in scoped_entries:
+ for record in _state_file_records(entry, repo_keys, fail_closed = cancel_markers):
+ for cache in caches:
+ add_path(
+ cache,
+ entry,
+ record,
+ cancel_marker = cancel_markers,
+ scoped = True,
+ )
+ for entry in entries:
+ for record in _state_file_records(entry, repo_keys, fail_closed = cancel_markers):
+ payload = record[3]
+ raw_cache = payload.get("hub_cache") if payload is not None else None
+ recorded_cache = _payload_cache_path(raw_cache)
+ if recorded_cache:
+ cache = _canonical_hub_cache(recorded_cache)
+ elif payload is not None and "hub_cache" in payload and raw_cache not in (None, ""):
+ cache = active_cache if cancel_markers else None
+ elif payload is not None or cancel_markers:
+ cache = active_cache
+ else:
+ cache = None
+ add_path(
+ cache,
+ entry,
+ record,
+ cancel_marker = cancel_markers,
+ scoped = False,
+ )
+
+ index_directory(manifests_dir(create = False), cancel_markers = False)
+ index_directory(cancelled_dir(create = False), cancel_markers = True)
+ return VariantStateIndex(
+ {
+ key: VariantState(
+ {
+ variant: (name, manifest)
+ for variant, (name, manifest, _priority) in manifests.items()
+ },
+ markers,
+ )
+ for key, (manifests, markers) in mutable.items()
+ }
+ )
def _iter_variant_state_files(
@@ -963,11 +1487,23 @@ def _iter_variant_state_files(
repo_id,
None,
hub_cache = requested,
+ create = False,
)
if scoped_probe is None:
return
- prefix = variant_filename_prefix(repo_type, repo_id)
- seen: set[str] = set()
+ prefixes = tuple(
+ dict.fromkeys(
+ variant_filename_prefix(
+ repo_type,
+ repo_id,
+ legacy_repo_key = legacy_repo,
+ legacy_hash_key = legacy_hash,
+ )
+ for legacy_repo in (False, True)
+ for legacy_hash in (False, True)
+ )
+ )
+ selected: dict[str, tuple[tuple[bool, bool], str, Path]] = {}
for directory, legacy in ((scoped_probe.parent, False), (parent, True)):
if legacy and directory == scoped_probe.parent:
continue
@@ -976,10 +1512,19 @@ def _iter_variant_state_files(
except OSError:
continue
for entry in entries:
- if not entry.is_file() or not entry.name.endswith(".json"):
+ if not entry.name.endswith(".json"):
continue
stem = entry.name[: -len(".json")]
- if not stem.lower().startswith(prefix) or entry.name in seen:
+ prefix = next(
+ (candidate for candidate in prefixes if stem.lower().startswith(candidate)),
+ None,
+ )
+ if prefix is None:
+ continue
+ try:
+ if not entry.is_file():
+ continue
+ except OSError:
continue
if legacy and not _legacy_state_applies(
entry,
@@ -989,8 +1534,42 @@ def _iter_variant_state_files(
continue
fallback = stem[len(prefix) :]
if fallback:
- seen.add(entry.name)
- yield _variant_from_state_file(entry, fallback), entry
+ payload = _read_state_payload(entry)
+ payload_identity = _state_payload_identity(payload)
+ variant_payload = payload
+ if payload_identity is not None:
+ if _state_payload_identity_matches_entry(entry, payload, repo_type):
+ recorded_type, recorded_id = payload_identity
+ if recorded_id != repo_id.lower() or recorded_type not in (None, repo_type):
+ continue
+ elif cancel_markers:
+ variant_payload = None
+ else:
+ continue
+ elif cancel_markers:
+ variant_payload = None
+ variant = _variant_from_state_payload(variant_payload, fallback)
+ try:
+ canonical = path_factory(
+ repo_type,
+ repo_id,
+ variant,
+ hub_cache = None if legacy else requested,
+ create = False,
+ )
+ except (UnicodeError, ValueError, OSError):
+ # Same undecodable-filename case guarded in add_path: a lone
+ # surrogate from iterdir() cannot be hashed for the canonical
+ # spelling. Before, this loop yielded such an entry as-is;
+ # letting the hash escape would instead abort the whole
+ # iteration and lose the repo's valid state alongside it.
+ canonical = None
+ priority = (not legacy, canonical is not None and canonical.name == entry.name)
+ key = variant.lower()
+ if key not in selected or priority > selected[key][0]:
+ selected[key] = (priority, variant, entry)
+ for _priority, variant, entry in selected.values():
+ yield variant, entry
def iter_variant_manifests(
@@ -1003,7 +1582,7 @@ def iter_variant_manifests(
written for this repo. Used by is_gguf_repo_partial to enumerate all
variants present on disk so the all-variants-broken gate can run."""
yield from _iter_variant_state_files(
- manifests_dir(),
+ manifests_dir(create = False),
repo_type,
repo_id,
hub_cache,
@@ -1021,7 +1600,7 @@ def iter_variant_markers(
Companion to iter_variant_manifests: catches variants cancelled
before download-start ever wrote a manifest (very early failures)."""
yield from _iter_variant_state_files(
- cancelled_dir(),
+ cancelled_dir(create = False),
repo_type,
repo_id,
hub_cache,
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index ce6cd1ba26b..1122eb0cfaf 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -13,14 +13,16 @@ layers built on top of these primitives live in download_registry.py.
from __future__ import annotations
+import asyncio
import hashlib
import json
import re
+import stat
import threading
import time
from dataclasses import dataclass, replace
from pathlib import Path, PurePosixPath, PureWindowsPath
-from typing import Callable, NamedTuple, Optional
+from typing import Awaitable, Callable, Hashable, NamedTuple, Optional, TypeVar
from loggers import get_logger
@@ -70,6 +72,28 @@ _hf_cache_scans_cached_at: float = 0.0
# neither cached nor served to callers that arrived after the mutation.
_hf_cache_scans_epoch: int = 0
+_T = TypeVar("_T")
+
+
+async def shared_scan(
+ flights: dict[Hashable, asyncio.Task[_T]], key: Hashable, factory: Callable[[], Awaitable[_T]]
+) -> _T:
+ """Shield same-loop callers behind one task for the same inventory key."""
+ flight_key = (asyncio.get_running_loop(), key)
+ flight = flights.get(flight_key)
+ if flight is None or flight.done():
+ flight = asyncio.create_task(factory())
+ flights[flight_key] = flight
+
+ def clear(task: asyncio.Task[_T]) -> None:
+ if flights.get(flight_key) is task:
+ flights.pop(flight_key, None)
+ if not task.cancelled():
+ task.exception()
+
+ flight.add_done_callback(clear)
+ return await asyncio.shield(flight)
+
def invalidate_hf_cache_scans() -> None:
global _hf_cache_scans_result, _hf_cache_scans_cached_at, _hf_cache_scans_epoch
@@ -79,6 +103,11 @@ def invalidate_hf_cache_scans() -> None:
_hf_cache_scans_epoch += 1
+def hf_cache_scans_epoch() -> int:
+ with _hf_cache_scans_lock:
+ return _hf_cache_scans_epoch
+
+
def all_hf_cache_scans() -> list:
global _hf_cache_scans_flight, _hf_cache_scans_result, _hf_cache_scans_cached_at
@@ -634,23 +663,34 @@ def _repo_signal_applies_to_snapshot(
def _gguf_variant_manifest_blob_hashes(
- repo_id: str, repo_cache_dir: Optional[Path] = None
+ repo_id: str,
+ repo_cache_dir: Optional[Path] = None,
+ variant_state = None,
) -> frozenset[str]:
from hub.utils import download_manifest
hashes: set[str] = set()
hub_cache = _hub_cache_for_repo_dir(repo_cache_dir)
- for variant, _path in download_manifest.iter_variant_manifests(
- "model",
- repo_id,
- hub_cache = hub_cache,
- ):
- manifest = download_manifest.read_manifest(
- "model",
- repo_id,
- variant,
- hub_cache = hub_cache,
+ if variant_state is not None:
+ manifests = variant_state.manifests()
+ else:
+ manifests = (
+ (
+ variant,
+ download_manifest.read_manifest(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = hub_cache,
+ ),
+ )
+ for variant, _path in download_manifest.iter_variant_manifests(
+ "model",
+ repo_id,
+ hub_cache = hub_cache,
+ )
)
+ for _variant, manifest in manifests:
if manifest is None:
continue
for expected in manifest.expected_files:
@@ -682,10 +722,15 @@ def _snapshot_legacy_partial(
repo_id: str,
repo_cache_dir: Optional[Path] = None,
snapshot_dir: Optional[Path] = None,
+ variant_state = None,
) -> bool:
if repo_type != "model":
return _legacy_partial(repo_type, repo_id, repo_cache_dir)
- ignored_hashes = _gguf_variant_manifest_blob_hashes(repo_id, repo_cache_dir)
+ ignored_hashes = _gguf_variant_manifest_blob_hashes(
+ repo_id,
+ repo_cache_dir,
+ variant_state,
+ )
if repo_cache_dir is not None:
return _repo_cache_dir_has_snapshot_legacy_partial(
repo_cache_dir,
@@ -1089,15 +1134,7 @@ def _index_cannot_serve_its_shards(index_path: Path, family_files: set[str]) ->
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
+ shards: set[PurePosixPath] = set()
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:
@@ -1109,23 +1146,28 @@ def _index_cannot_serve_its_shards(index_path: Path, family_files: set[str]) ->
windows = PureWindowsPath(shard)
if parts.is_absolute() or ".." in parts.parts or windows.is_absolute() or windows.drive:
return True
+ shards.add(parts)
+ named = {shard.name for shard in shards}
+ # 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 shards:
try:
- named = index_path.parent / parts
- if not named.is_file() or named.stat().st_size <= 0:
+ named = index_path.parent / shard
+ shard_stat = named.stat()
+ if not stat.S_ISREG(shard_stat.st_mode) or shard_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)
+ for shard in shards:
+ match = _WEIGHT_SHARD_RE.search(shard.name)
if match is None:
continue
- key = (str(rel.parent), rel.name[: match.start()], int(match.group(2)))
+ key = (str(shard.parent), shard.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())
@@ -1353,14 +1395,19 @@ def _manifest_partial(
variant: Optional[str] = None,
snapshot_dir: Optional[Path] = None,
repo_cache_dir: Optional[Path] = None,
+ variant_state = None,
) -> bool:
from hub.utils import download_manifest
- manifest = download_manifest.read_manifest(
- repo_type,
- repo_id,
- variant,
- hub_cache = _hub_cache_for_repo_dir(repo_cache_dir),
+ manifest = (
+ variant_state.manifest_for(variant)
+ if variant_state is not None and variant is not None
+ else download_manifest.read_manifest(
+ repo_type,
+ repo_id,
+ variant,
+ hub_cache = _hub_cache_for_repo_dir(repo_cache_dir),
+ )
)
if manifest is None:
return False
@@ -1425,6 +1472,7 @@ def is_snapshot_partial(
repo_id: str,
repo_cache_dir: Optional[Path] = None,
snapshot_dir: Optional[Path] = None,
+ variant_state = None,
) -> bool:
"""Repo-row partial flag for snapshot-style downloads (full-snapshot models, i.e.
safetensors/adapter/checkpoint, and all datasets).
@@ -1446,21 +1494,31 @@ def is_snapshot_partial(
repo_cache_dir, snapshot_dir, quants = False
)
return _compose_partial(
- 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: (
+ 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, snapshot_dir),
- lambda: repo_signal_applies
- and _manifest_partial(
+ lambda: _snapshot_legacy_partial(
repo_type,
repo_id,
- None,
- snapshot_dir,
repo_cache_dir,
+ snapshot_dir,
+ variant_state,
+ ),
+ lambda: (
+ repo_signal_applies
+ and _manifest_partial(
+ repo_type,
+ repo_id,
+ None,
+ snapshot_dir,
+ repo_cache_dir,
+ )
),
lambda: _recovered_snapshot_cannot_serve(repo_cache_dir, snapshot_dir, quants = False),
)
@@ -1751,6 +1809,7 @@ def is_variant_partial(
variant_blob_hashes: Optional[frozenset[str]] = None,
repo_cache_dir: Optional[Path] = None,
repo_signal_applies: bool = True,
+ variant_state = None,
) -> bool:
"""Per-variant partial detection. Owns its manifest, owns its marker.
@@ -1762,27 +1821,38 @@ def is_variant_partial(
the per-variant endpoint still reports a cancelled quant as broken."""
from hub.utils import download_manifest
return _compose_partial(
- 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: (
+ repo_signal_applies
+ and (
+ variant_state.has_marker(variant)
+ if variant_state is not None
+ else download_manifest.has_cancel_marker(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = _hub_cache_for_repo_dir(repo_cache_dir),
+ )
+ )
),
# 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: (
+ repo_signal_applies
+ and bool(
+ incomplete_blob_hashes
+ and variant_blob_hashes
+ and incomplete_blob_hashes.intersection(variant_blob_hashes)
+ )
),
- lambda: repo_signal_applies
- and _manifest_partial(
- "model",
- repo_id,
- variant,
- snapshot_dir,
- repo_cache_dir,
+ lambda: (
+ repo_signal_applies
+ and _manifest_partial(
+ "model",
+ repo_id,
+ variant,
+ snapshot_dir,
+ repo_cache_dir,
+ variant_state,
+ )
),
)
@@ -1792,6 +1862,7 @@ def is_gguf_repo_partial(
repo_cache_dir: Optional[Path] = None,
*,
snapshot_dir: Optional[Path] = None,
+ variant_state = 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
@@ -1824,33 +1895,43 @@ def is_gguf_repo_partial(
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",
- repo_id,
- hub_cache = hub_cache,
- ):
- if (
- download_manifest.read_manifest(
+ if variant_state is not None:
+ manifests = variant_state.manifests()
+ else:
+ manifests = (
+ (
+ variant,
+ download_manifest.read_manifest(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = hub_cache,
+ ),
+ )
+ for variant, _path in download_manifest.iter_variant_manifests(
"model",
repo_id,
- variant,
hub_cache = hub_cache,
)
- is not None
- ):
+ )
+ for variant, manifest in manifests:
+ if manifest is not None:
variants.add(variant)
- for variant, _path in download_manifest.iter_variant_markers(
- "model",
- repo_id,
- hub_cache = hub_cache,
- ):
- if download_manifest.has_cancel_marker(
+ if variant_state is not None:
+ variants.update(variant_state.marker_variants())
+ else:
+ for variant, _path in download_manifest.iter_variant_markers(
"model",
repo_id,
- variant,
hub_cache = hub_cache,
):
- variants.add(variant)
+ if download_manifest.has_cancel_marker(
+ "model",
+ repo_id,
+ variant,
+ hub_cache = hub_cache,
+ ):
+ variants.add(variant)
if not variants:
# Nothing named a quant: an interrupted attempt leaves only torn shards.
return has_legacy_partial or _recovered_snapshot_cannot_serve(
@@ -1866,6 +1947,7 @@ def is_gguf_repo_partial(
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,
+ variant_state = variant_state,
):
has_broken = True
else:
diff --git a/studio/backend/hub/utils/state_dir.py b/studio/backend/hub/utils/state_dir.py
index 4650b973814..31f05374c47 100644
--- a/studio/backend/hub/utils/state_dir.py
+++ b/studio/backend/hub/utils/state_dir.py
@@ -10,7 +10,6 @@ cache lifecycle. Two subdirectories:
<studio cache>/hub-state/
manifests/cache-<digest>/<key>.json expected-files manifest
cancelled/cache-<digest>/<key>.json cancel marker
-
The cache digest isolates state for the same repo across selectable Hub caches.
The ``<key>`` mirrors HF's cache dir naming while the resulting manifest,
cancel-marker, and atomic-write temp filenames fit common filesystem basename
@@ -20,11 +19,9 @@ limits. Very long repo IDs use a stable hash in the state key:
models--<owner>--<name>--variant--<variant> GGUF variant
datasets--<owner>--<name> dataset snapshot
-All path accessors return ``Optional[Path]`` and yield ``None`` when
-the directory can't be created (read-only FS, permission error).
-Callers must treat ``None`` as "no state available" and fall through
-to existing on-disk-only behavior; this module never raises on a
-configuration failure.
+Path accessors are read-only by default. Writers pass ``create=True`` explicitly.
+All accessors return ``Optional[Path]`` and yield ``None`` when requested
+directory creation fails; callers fall through to existing on-disk-only behavior.
"""
from __future__ import annotations
@@ -58,11 +55,15 @@ _STATE_EXTENSION = ".json"
_ATOMIC_WRITE_TMP_OVERHEAD = len(".") + len(".tmp-") + 8
_MAX_VARIANT_FRAGMENT_LENGTH = 64
_CACHE_SCOPE_DIGEST_LENGTH = 32
+_HASH_PREFIXES = ("sha256-", "@sha256-")
+_LEGACY_HASH_FRAGMENT = re.compile(r"sha256-[0-9a-f]{32}")
-def state_root() -> Optional[Path]:
- """Return the Hub state root, creating it if needed. ``None`` on failure."""
+def state_root(*, create: bool = False) -> Optional[Path]:
+ """Return the Hub state root, optionally creating it. ``None`` on failure."""
root = cache_root() / _HUB_STATE_DIRNAME
+ if not create:
+ return root
try:
root.mkdir(parents = True, exist_ok = True)
except OSError as exc:
@@ -71,11 +72,13 @@ def state_root() -> Optional[Path]:
return root
-def _subdir(name: str) -> Optional[Path]:
- root = state_root()
+def _subdir(name: str, *, create: bool = False) -> Optional[Path]:
+ root = state_root(create = create)
if root is None:
return None
path = root / name
+ if not create:
+ return path
try:
path.mkdir(parents = True, exist_ok = True)
except OSError as exc:
@@ -102,43 +105,157 @@ def _state_filename_fits(entry_key: str) -> bool:
return _filename_bytes(filename) + _ATOMIC_WRITE_TMP_OVERHEAD <= _MAX_STATE_BASENAME_BYTES
-def _state_repo_key(repo_type: RepoType, repo_id: str) -> str:
+def state_filename_is_ambiguous(name: str) -> bool:
+ """Whether an unreadable state filename has multiple possible owners."""
+ stem, separator = name.removesuffix(_STATE_EXTENSION).lower(), "--variant--"
+ boundary = stem.find(separator)
+ if boundary >= 0 and stem.find(separator, boundary + 1) >= 0:
+ return True
+ repo_key = stem[:boundary] if boundary >= 0 else stem
+ repo_fragment = repo_key.partition("--")[2]
+ variant_fragment = stem.rsplit(separator, 1)[-1] if boundary >= 0 else ""
+ return bool(
+ _LEGACY_HASH_FRAGMENT.fullmatch(repo_fragment)
+ or _LEGACY_HASH_FRAGMENT.fullmatch(variant_fragment)
+ )
+
+
+def _state_repo_key(
+ repo_type: RepoType,
+ repo_id: str,
+ *,
+ legacy_repo_key: bool = False,
+ legacy_hash_key: bool = False,
+) -> str:
+ """Return an injective write key, or the pre-migration key for reads.
+
+ Repositories ending in ``variant`` otherwise alias a shorter repository's
+ legacy double-hyphen variant. Both collision sides use hashes for new state.
+ """
base = repo_cache_basename(repo_type, repo_id)
+ repo_fragment = base.partition("--")[2]
variant_prefix = f"{base}--variant--"
longest_variant_key = f"{variant_prefix}{'x' * _MAX_VARIANT_FRAGMENT_LENGTH}"
- if _state_filename_fits(longest_variant_key):
+ if _state_filename_fits(longest_variant_key) and (
+ legacy_repo_key
+ or (not base.endswith("--variant") and not repo_fragment.startswith(_HASH_PREFIXES))
+ ):
return base
digest = hashlib.sha256(base.encode("utf-8")).hexdigest()[:32]
- return f"{repo_type}s--sha256-{digest}"
+ tag = "sha256-" if legacy_hash_key else "@sha256-"
+ return f"{repo_type}s--{tag}{digest}"
-def variant_filename_prefix(repo_type: RepoType, repo_id: str) -> str:
+def variant_filename_prefix(
+ repo_type: RepoType,
+ repo_id: str,
+ *,
+ legacy_repo_key: bool = False,
+ legacy_hash_key: bool = False,
+) -> str:
"""Lowercased prefix every variant-keyed state file for this repo shares.
The single source the download_manifest enumerators match against, so the
scheme in :func:`_entry_key` cannot drift from them silently."""
- return f"{_state_repo_key(repo_type, repo_id)}--variant--"
+ repo_key = _state_repo_key(
+ repo_type,
+ repo_id,
+ legacy_repo_key = legacy_repo_key,
+ legacy_hash_key = legacy_hash_key,
+ )
+ return f"{repo_key}--variant--"
-def _entry_key(repo_type: RepoType, repo_id: str, variant: Optional[str]) -> str:
- base = _state_repo_key(repo_type, repo_id)
+def _variant_fragment(
+ variant: str,
+ *,
+ legacy_variant_key: bool = False,
+ legacy_hash_key: bool = False,
+) -> str:
+ normalized_variant = variant.strip().lower()
+ # Double-hyphen variants can alias a repository component plus the
+ # ``--variant--`` delimiter, so give them an injective hashed fragment.
+ if _SAFE_VARIANT_FRAGMENT.fullmatch(normalized_variant) and (
+ legacy_variant_key
+ or ("--" not in normalized_variant and not normalized_variant.startswith(_HASH_PREFIXES))
+ ):
+ return normalized_variant
+ digest = hashlib.sha256(normalized_variant.encode("utf-8")).hexdigest()[:32]
+ tag = "sha256-" if legacy_hash_key else "@sha256-"
+ return f"{tag}{digest}"
+
+
+def variant_key_fragments(variant: str) -> tuple[str, ...]:
+ """Every ``--variant--`` fragment this variant can be stored under.
+
+ A variant that cannot be spelled literally in a filename is stored hashed, so
+ a reader that recovers identity from the filename alone recovers the hash and
+ not the variant. Callers holding the variant string need these to match it.
+ """
+ fragments: list[str] = []
+ for legacy_variant_key in (False, True):
+ for legacy_hash_key in (False, True):
+ try:
+ fragment = _variant_fragment(
+ variant,
+ legacy_variant_key = legacy_variant_key,
+ legacy_hash_key = legacy_hash_key,
+ )
+ except (UnicodeError, ValueError):
+ continue
+ if fragment not in fragments:
+ fragments.append(fragment)
+ return tuple(fragments)
+
+
+def _entry_key(
+ repo_type: RepoType,
+ repo_id: str,
+ variant: Optional[str],
+ *,
+ legacy_variant_key: bool = False,
+ legacy_repo_key: bool = False,
+ legacy_hash_key: bool = False,
+) -> str:
+ base = _state_repo_key(
+ repo_type,
+ repo_id,
+ legacy_repo_key = legacy_repo_key,
+ legacy_hash_key = legacy_hash_key,
+ )
if not variant:
return base
- normalized_variant = variant.strip().lower()
- if _SAFE_VARIANT_FRAGMENT.fullmatch(normalized_variant):
- variant_fragment = normalized_variant
- else:
- digest = hashlib.sha256(normalized_variant.encode("utf-8")).hexdigest()[:32]
- variant_fragment = f"sha256-{digest}"
- return f"{variant_filename_prefix(repo_type, repo_id)}{variant_fragment}"
+ variant_fragment = _variant_fragment(
+ variant,
+ legacy_variant_key = legacy_variant_key,
+ legacy_hash_key = legacy_hash_key,
+ )
+ prefix = variant_filename_prefix(
+ repo_type,
+ repo_id,
+ legacy_repo_key = legacy_repo_key,
+ legacy_hash_key = legacy_hash_key,
+ )
+ return f"{prefix}{variant_fragment}"
+
+
+def cache_scope_name(hub_cache: str | Path) -> str:
+ normalized = os.path.normcase(str(Path(hub_cache).expanduser()))
+ digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:_CACHE_SCOPE_DIGEST_LENGTH]
+ return f"cache-{digest}"
-def _cache_scope(parent: Path, hub_cache: Optional[str | Path]) -> Optional[Path]:
+def _cache_scope(
+ parent: Path,
+ hub_cache: Optional[str | Path],
+ *,
+ create: bool = False,
+) -> Optional[Path]:
if hub_cache is None:
return parent
- normalized = os.path.normcase(str(Path(hub_cache).expanduser()))
- digest = hashlib.sha256(normalized.encode("utf-8")).hexdigest()[:_CACHE_SCOPE_DIGEST_LENGTH]
- scoped = parent / f"cache-{digest}"
+ scoped = parent / cache_scope_name(hub_cache)
+ if not create:
+ return scoped
try:
scoped.mkdir(parents = True, exist_ok = True)
except OSError as exc:
@@ -153,15 +270,27 @@ def manifest_path(
variant: Optional[str] = None,
*,
hub_cache: Optional[str | Path] = None,
+ create: bool = False,
+ legacy_variant_key: bool = False,
+ legacy_repo_key: bool = False,
+ legacy_hash_key: bool = False,
) -> Optional[Path]:
"""Path to the manifest file for this triple. May or may not exist."""
- parent = _subdir(_MANIFESTS_SUBDIR)
+ parent = _subdir(_MANIFESTS_SUBDIR, create = create)
if parent is None:
return None
- parent = _cache_scope(parent, hub_cache)
+ parent = _cache_scope(parent, hub_cache, create = create)
if parent is None:
return None
- return parent / f"{_entry_key(repo_type, repo_id, variant)}.json"
+ entry_key = _entry_key(
+ repo_type,
+ repo_id,
+ variant,
+ legacy_variant_key = legacy_variant_key,
+ legacy_repo_key = legacy_repo_key,
+ legacy_hash_key = legacy_hash_key,
+ )
+ return parent / f"{entry_key}.json"
def marker_path(
@@ -170,31 +299,43 @@ def marker_path(
variant: Optional[str] = None,
*,
hub_cache: Optional[str | Path] = None,
+ create: bool = False,
+ legacy_variant_key: bool = False,
+ legacy_repo_key: bool = False,
+ legacy_hash_key: bool = False,
) -> Optional[Path]:
"""Path to the cancel-marker file for this triple. May or may not exist."""
- parent = _subdir(_CANCELLED_SUBDIR)
+ parent = _subdir(_CANCELLED_SUBDIR, create = create)
if parent is None:
return None
- parent = _cache_scope(parent, hub_cache)
+ parent = _cache_scope(parent, hub_cache, create = create)
if parent is None:
return None
- return parent / f"{_entry_key(repo_type, repo_id, variant)}.json"
-
-
-def manifests_dir() -> Optional[Path]:
+ entry_key = _entry_key(
+ repo_type,
+ repo_id,
+ variant,
+ legacy_variant_key = legacy_variant_key,
+ legacy_repo_key = legacy_repo_key,
+ legacy_hash_key = legacy_hash_key,
+ )
+ return parent / f"{entry_key}.json"
+
+
+def manifests_dir(*, create: bool = False) -> Optional[Path]:
"""Manifests subdirectory, created on demand. ``None`` on failure.
Exposed for iter_variant_manifests, which enumerates the directory to find
every variant-keyed manifest for a repo (the path helpers above answer
"where would key X go" but not "what keys exist")."""
- return _subdir(_MANIFESTS_SUBDIR)
+ return _subdir(_MANIFESTS_SUBDIR, create = create)
-def cancelled_dir() -> Optional[Path]:
+def cancelled_dir(*, create: bool = False) -> Optional[Path]:
"""Cancel-marker subdirectory, created on demand. ``None`` on failure.
See manifests_dir for why this iteration entry point is needed."""
- return _subdir(_CANCELLED_SUBDIR)
+ return _subdir(_CANCELLED_SUBDIR, create = create)
def workers_dir() -> Optional[Path]:
@@ -203,4 +344,4 @@ def workers_dir() -> Optional[Path]:
Each live download worker drops one breadcrumb here so a backend that
restarts after a hard crash can reap workers it can no longer reach through
its in-memory registry."""
- return _subdir(_WORKERS_SUBDIR)
+ return _subdir(_WORKERS_SUBDIR, create = True)
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index 6d8d0d2479b..699adabce12 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -17,7 +17,7 @@ import weakref
from pathlib import Path
from fastapi import APIRouter, Body, Depends, Header, HTTPException, Query
from pydantic import BaseModel
-from typing import List, Optional
+from typing import List, NamedTuple, Optional
import structlog
from loggers import get_logger
@@ -436,6 +436,7 @@ def _scan_hf_cache(
*,
active_cache: bool = True,
classify_format: bool = True,
+ variant_states = None,
) -> List[LocalModelInfo]:
if not cache_dir.exists() or not cache_dir.is_dir():
return []
@@ -457,8 +458,17 @@ def _scan_hf_cache(
except OSError:
updated_at = None
- partial = hf_cache_scan.is_snapshot_partial("model", model_id, repo_dir)
- partial = partial or hf_cache_scan.is_gguf_repo_partial(model_id, repo_dir)
+ variant_state = (
+ variant_states.for_repo("model", model_id, hub_cache = cache_dir)
+ if variant_states is not None
+ else None
+ )
+ partial = hf_cache_scan.is_snapshot_partial(
+ "model", model_id, repo_dir, variant_state = variant_state
+ )
+ partial = partial or hf_cache_scan.is_gguf_repo_partial(
+ model_id, repo_dir, variant_state = variant_state
+ )
load_id = model_id
snapshot = _resolve_hf_cache_realpath(repo_dir)
@@ -857,7 +867,32 @@ def _scan_ollama_dir(ollama_dir: Path, limit: Optional[int] = None) -> List[Loca
return found
-def collect_local_models(models_root: Path) -> List[LocalModelInfo]:
+class _CompatLocalInventorySources(NamedTuple):
+ hf_cache_dir: Path
+ legacy_hf: Path
+ hf_default: Path
+ lm_dirs: tuple[Path, ...]
+ known_hf_caches: tuple[Path, ...]
+
+
+def _compat_local_inventory_sources() -> _CompatLocalInventorySources:
+ from utils.paths import hf_default_cache_dir, legacy_hf_cache_dir, lmstudio_model_dirs
+ from utils.hf_cache_settings import known_hf_hub_caches
+ return _CompatLocalInventorySources(
+ _resolve_hf_cache_dir(),
+ legacy_hf_cache_dir(),
+ hf_default_cache_dir(),
+ tuple(lmstudio_model_dirs()),
+ tuple(known_hf_hub_caches()),
+ )
+
+
+def collect_local_models(
+ models_root: Path,
+ *,
+ custom_folders: Optional[list[dict]] = None,
+ sources: Optional[_CompatLocalInventorySources] = None,
+) -> List[LocalModelInfo]:
"""Scan ``models_root``, the HF caches, LM Studio dirs, and user scan folders,
returning a deduplicated, hidden-filtered list of discovered local models.
@@ -867,25 +902,27 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:
"""
from storage.studio_db import list_scan_folders
from utils.models.model_config import detect_gguf_model
- from utils.paths import (
- hf_default_cache_dir,
- legacy_hf_cache_dir,
- lmstudio_model_dirs,
- )
- from utils.hf_cache_settings import known_hf_hub_caches
- hf_cache_dir = _resolve_hf_cache_dir()
- legacy_hf = legacy_hf_cache_dir()
- hf_default = hf_default_cache_dir()
- lm_dirs = lmstudio_model_dirs()
+ sources = sources or _compat_local_inventory_sources()
+ hf_cache_dir = sources.hf_cache_dir
+ legacy_hf = sources.legacy_hf
+ hf_default = sources.hf_default
+ lm_dirs = sources.lm_dirs
+ if custom_folders is None:
+ try:
+ custom_folders = list_scan_folders()
+ except Exception as e:
+ logger.warning("Could not load custom scan folders: %s", e)
+ custom_folders = []
local_models = _scan_models_dir(models_root)
active_cache_real = _safe_resolve(hf_cache_dir)
active_cache_key = os.path.normcase(active_cache_real) if active_cache_real else None
seen_hf: set[str] = set()
+ hf_sources: list[tuple[Path, bool]] = []
for cache_dir in (
hf_cache_dir,
- *known_hf_hub_caches(),
+ *sources.known_hf_caches,
legacy_hf,
hf_default,
):
@@ -896,9 +933,34 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:
if cache_key in seen_hf:
continue
seen_hf.add(cache_key)
+ hf_sources.append((cache_dir, cache_key == active_cache_key))
+
+ state_repositories = []
+ state_cache_dirs = [cache_dir for cache_dir, _active_cache in hf_sources]
+ state_cache_dirs.extend(Path(folder["path"]) for folder in custom_folders)
+ for cache_dir in dict.fromkeys(state_cache_dirs):
+ try:
+ for repo_dir in cache_dir.glob("models--*"):
+ repo_name = repo_dir.name[len("models--") :]
+ if repo_name and repo_dir.is_dir():
+ state_repositories.append(("model", repo_name.replace("--", "/"), cache_dir))
+ except OSError:
+ continue
+ try:
+ from hub.utils import download_manifest
+ variant_states = download_manifest.build_variant_state_index(
+ state_repositories,
+ active_hub_cache = hf_cache_dir,
+ )
+ except Exception as e:
+ logger.warning("Could not build shared legacy Hub-state index: %s", e)
+ variant_states = None
+
+ for cache_dir, active_cache in hf_sources:
local_models += _scan_hf_cache(
cache_dir,
- active_cache = cache_key == active_cache_key,
+ active_cache = active_cache,
+ variant_states = variant_states,
)
for lm_dir in lm_dirs:
@@ -906,11 +968,6 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:
# Scan user-added custom folders (per-folder cap).
_MAX_MODELS_PER_FOLDER = 200
- try:
- custom_folders = list_scan_folders()
- except Exception as e:
- logger.warning("Could not load custom scan folders: %s", e)
- custom_folders = []
for folder in custom_folders:
folder_path = Path(folder["path"])
try:
@@ -919,7 +976,11 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:
m
for m in (
_scan_models_dir(folder_path, limit = _MAX_MODELS_PER_FOLDER)
- + _scan_hf_cache(folder_path, active_cache = False)
+ + _scan_hf_cache(
+ folder_path,
+ active_cache = False,
+ variant_states = variant_states,
+ )
+ _scan_lmstudio_dir(folder_path)
)
if not any(p in (".studio_links", "ollama_links") for p in Path(m.path).parts)
@@ -984,6 +1045,95 @@ def collect_local_models(models_root: Path) -> List[LocalModelInfo]:
return [m for m in models if not _is_hidden_model(m.id, m.model_id, m.path)]
+_CompatLocalInventoryKey = tuple[Path, _CompatLocalInventorySources, tuple[str, ...], int]
+_compat_local_inventory_flights: dict[
+ tuple[asyncio.AbstractEventLoop, _CompatLocalInventoryKey], asyncio.Task[List[LocalModelInfo]]
+] = {}
+
+
+# Retrying a superseded scan is only worth it while invalidations are occasional;
+# past this the endpoint must answer instead of restarting the walk forever.
+_COMPAT_LOCAL_INVENTORY_MAX_ATTEMPTS = 8
+
+
+class _CompatLocalCacheChanged(RuntimeError):
+ def __init__(self, models: List[LocalModelInfo]) -> None:
+ super().__init__("local inventory sources changed during the scan")
+ # Carried so the attempt cap can serve the freshest scan it has instead
+ # of looping forever or answering with nothing.
+ self.models = models
+
+
+def _compat_inventory_path_identity(path: object) -> str:
+ """Canonical source identity for compatibility inventory flights."""
+ raw = str(path)
+ try:
+ return os.path.normcase(os.path.realpath(os.path.expanduser(raw)))
+ except (OSError, UnicodeError, ValueError):
+ return os.path.normcase(raw)
+
+
+async def _shared_compat_local_inventory_scan(
+ models_root: Path, sources: Optional[_CompatLocalInventorySources] = None
+) -> List[LocalModelInfo]:
+ from storage.studio_db import list_scan_folders
+ from hub.utils import inventory_scan as hf_cache_scan
+
+ requested_sources = sources
+
+ async def collect(
+ expected_epoch: int, custom_folders: List[dict], scan_sources: _CompatLocalInventorySources
+ ) -> List[LocalModelInfo]:
+ models = await asyncio.to_thread(
+ collect_local_models,
+ models_root,
+ custom_folders = custom_folders,
+ sources = scan_sources,
+ )
+ if hf_cache_scan.hf_cache_scans_epoch() != expected_epoch:
+ raise _CompatLocalCacheChanged(models)
+ return models
+
+ # Discard obsolete results and retry their waiters against the current cache epoch.
+ superseded: Optional[List[LocalModelInfo]] = None
+ for _attempt in range(_COMPAT_LOCAL_INVENTORY_MAX_ATTEMPTS):
+ # Epoch first: the sources and folders below are read after it, so any
+ # change to them lands in a later epoch and the post-scan check sees it.
+ # A caller-supplied ``sources`` stays pinned - the /local route validated
+ # its models_dir against exactly those roots.
+ epoch = hf_cache_scan.hf_cache_scans_epoch()
+ scan_sources = requested_sources or _compat_local_inventory_sources()
+ try:
+ custom_folders = await asyncio.to_thread(list_scan_folders)
+ except Exception as e:
+ logger.warning("Could not load custom scan folders: %s", e)
+ custom_folders = []
+ key: _CompatLocalInventoryKey = (
+ Path(_compat_inventory_path_identity(models_root)),
+ scan_sources,
+ tuple(
+ _compat_inventory_path_identity(folder.get("path", "")) for folder in custom_folders
+ ),
+ epoch,
+ )
+ try:
+ return await hf_cache_scan.shared_scan(
+ _compat_local_inventory_flights,
+ key,
+ lambda expected_epoch = epoch, folders = custom_folders, roots = scan_sources: (
+ collect(expected_epoch, folders, roots)
+ ),
+ )
+ except _CompatLocalCacheChanged as changed:
+ superseded = changed.models
+ continue
+ # Invalidations are outpacing the walk, so no scan will ever confirm as
+ # current. Answer with the freshest one (the loop only reaches here through
+ # the retry path, so there is always one) instead of rescanning forever.
+ logger.warning("Compat local inventory kept racing cache invalidations; serving the last scan")
+ return superseded
+
+
@router.get("/local", response_model = LocalModelListResponse)
async def list_local_models(
models_dir: str = Query(
@@ -992,16 +1142,12 @@ async def list_local_models(
current_subject: str = Depends(get_current_subject),
):
"""List local model candidates from the models dir, HF caches, and LM Studio dirs."""
- from utils.paths import (
- legacy_hf_cache_dir,
- hf_default_cache_dir,
- lmstudio_model_dirs,
- )
-
- hf_cache_dir = _resolve_hf_cache_dir()
- legacy_hf = legacy_hf_cache_dir()
- hf_default = hf_default_cache_dir()
- lm_dirs = lmstudio_model_dirs()
+ # Resolve all scan directories up front.
+ sources = _compat_local_inventory_sources()
+ hf_cache_dir = sources.hf_cache_dir
+ legacy_hf = sources.legacy_hf
+ hf_default = sources.hf_default
+ lm_dirs = sources.lm_dirs
# Validate models_dir against an allowlist of trusted dirs. Only the trusted Path objects
# are used for FS access; the user string is for matching only, never path construction.
@@ -1030,7 +1176,7 @@ async def list_local_models(
)
try:
- models = collect_local_models(models_root)
+ models = await _shared_compat_local_inventory_scan(models_root, sources)
# Tag each model with its task so the Images picker can filter to diffusion.
models = [m.model_copy(update = {"task": _local_model_task(m)}) for m in models]
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index a1f6f095ace..b21e810991f 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -11,6 +11,7 @@ Model/variant for the managed mode resolve from ``--unsloth-model`` /
``--unsloth-gguf-variant``, then env vars, then ``test_studio_api.py`` defaults.
"""
+import itertools
import os
import sys
from pathlib import Path
@@ -30,6 +31,30 @@ os.environ.setdefault("UNSLOTH_ALLOW_CPU", "1")
os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")
[email protected](scope = "session")
+def _studio_home_root(tmp_path_factory):
+ """One parent directory for every per-test studio home.
+
+ ``tmp_path_factory.mktemp`` scans the whole basetemp on every call to pick
+ the next number, so calling it once per test is quadratic in the number of
+ tests. Paid once per session here, the per-test cost below is a bare mkdir.
+ """
+ return tmp_path_factory.mktemp("studio_homes")
+
+
+_studio_home_counter = itertools.count()
+
+
[email protected](autouse = True)
+def _isolate_studio_home(_studio_home_root, monkeypatch):
+ home = _studio_home_root / f"home-{next(_studio_home_counter)}"
+ home.mkdir()
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))
+ for name, module in tuple(sys.modules.items()):
+ if name.startswith(("storage.", "hub.storage.")) and hasattr(module, "_schema_ready"):
+ monkeypatch.setattr(module, "_schema_ready", False)
+
+
# Pytest CLI options
@@ -78,6 +103,7 @@ def _isolate_xet_health_home(tmp_path_factory):
from huggingface_hub import constants as hf_constants
mp = MonkeyPatch()
+ mp.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path_factory.mktemp("studio_home_session")))
# Pin these to what the hub resolved from the REAL environment before moving HF_HOME, which
# also defaults HF_HUB_CACHE, HF_XET_CACHE and HF_TOKEN_PATH: moving it alone would send the
# E2E server to an empty cache and token store, so a ~1.1GB GGUF redownload inside the 120s
@@ -273,7 +299,7 @@ def stub_embeddings(monkeypatch):
monkeypatch.setattr(
embeddings,
"token_counter",
- lambda model_name = None: (lambda t: len(t.split())),
+ lambda model_name = None: lambda t: len(t.split()),
)
monkeypatch.setattr(embeddings, "warm", lambda model_name = None: None)
return dim
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 9b76ce0b1f0..743ee8a4817 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -123,6 +123,8 @@ def test_collect_local_models_scans_previous_cache(monkeypatch, tmp_path):
def test_collect_local_models_prefers_complete_previous_copy(monkeypatch, tmp_path):
+ from hub.utils import download_manifest
+
active = tmp_path / "active"
previous = tmp_path / "previous"
active_partial = active / "models--Org--Model" / "blobs" / "abc.incomplete"
@@ -131,23 +133,94 @@ def test_collect_local_models_prefers_complete_previous_copy(monkeypatch, tmp_pa
snapshot = previous / "models--Org--Model" / "snapshots" / "revision"
snapshot.mkdir(parents = True)
(snapshot / "model.safetensors").write_bytes(b"complete")
+ build_calls = []
+ real_build = download_manifest.build_variant_state_index
+
+ def record_build(repositories, **kwargs):
+ repositories = tuple(repositories)
+ build_calls.append(repositories)
+ return real_build(repositories, **kwargs)
+ monkeypatch.setattr("hub.utils.download_manifest.build_variant_state_index", record_build)
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: active)
monkeypatch.setattr("utils.paths.legacy_hf_cache_dir", lambda: tmp_path / "legacy")
monkeypatch.setattr("utils.paths.hf_default_cache_dir", lambda: tmp_path / "default")
monkeypatch.setattr("utils.paths.lmstudio_model_dirs", lambda: [])
- monkeypatch.setattr(
- "utils.hf_cache_settings.known_hf_hub_caches",
- lambda: [active, previous],
- )
+ monkeypatch.setattr("utils.hf_cache_settings.known_hf_hub_caches", lambda: [active, previous])
monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [])
rows = models_route.collect_local_models(tmp_path / "models")
-
[row] = [row for row in rows if row.model_id == "Org/Model"]
assert row.id == str(snapshot.resolve())
assert row.partial is False
assert row.active_cache is False
+ assert len(build_calls) == 1
+ assert set(build_calls[0]) == {
+ ("model", "Org/Model", active),
+ ("model", "Org/Model", previous),
+ }
+
+
+def test_compat_local_inventory_requests_share_scan(monkeypatch, tmp_path):
+ # Total and stable on hostile input is the whole contract here; the exact
+ # string is platform-dependent. POSIX realpath() rejects an embedded NUL with
+ # ValueError so the raw string is normcased through, while Windows non-strict
+ # realpath falls back to abspath and joins the cwd.
+ for hostile in ("\0", "\ud800"):
+ identity = models_route._compat_inventory_path_identity(hostile)
+ assert identity == models_route._compat_inventory_path_identity(hostile)
+ assert identity.endswith(hostile)
+ sources = models_route._CompatLocalInventorySources(
+ tmp_path / "active",
+ tmp_path / "legacy",
+ tmp_path / "default",
+ (tmp_path / "lm",),
+ (tmp_path / "known",),
+ )
+ folders = [[{"id": 1, "path": "/custom", "created_at": "now"}]]
+ monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: folders[0])
+ started, release, workers = [asyncio.Event(), asyncio.Event()], asyncio.Event(), []
+
+ async def fake_to_thread(function, *args, **kwargs):
+ if function is models_route.collect_local_models:
+ workers.append((args, kwargs))
+ started[len(workers) - 1].set()
+ await release.wait()
+ return []
+ return function(*args, **kwargs)
+
+ monkeypatch.setattr(models_route.asyncio, "to_thread", fake_to_thread)
+
+ async def run_requests():
+ request = lambda root = tmp_path: models_route._shared_compat_local_inventory_scan(
+ root, sources
+ )
+ first = asyncio.create_task(request(tmp_path))
+ await asyncio.wait_for(started[0].wait(), 1)
+ second = asyncio.create_task(request(tmp_path / "alias" / ".."))
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ assert len(workers) == 1
+ key = next(iter(models_route._compat_local_inventory_flights))[1]
+ assert sources in key and isinstance(key[-1], int)
+ first.cancel()
+ second.cancel()
+ await asyncio.gather(first, second, return_exceptions = True)
+ second = asyncio.create_task(request())
+ await asyncio.sleep(0)
+ folders[0] = [{"id": 2, "path": "/changed", "created_at": "later"}]
+ changed = asyncio.create_task(request())
+ await asyncio.wait_for(started[1].wait(), 1)
+ assert [worker[1]["custom_folders"] for worker in workers] == [
+ [{"id": 1, "path": "/custom", "created_at": "now"}],
+ folders[0],
+ ]
+ release.set()
+ return await asyncio.gather(second, changed)
+
+ assert (
+ asyncio.run(run_requests()) == [[], []] and not models_route._compat_local_inventory_flights
+ )
def test_legacy_custom_inventory_filters_registered_mtp_root(tmp_path, monkeypatch):
@@ -185,14 +258,19 @@ def test_legacy_custom_inventory_filters_registered_mtp_root(tmp_path, monkeypat
"utils.models.model_config._iter_gguf_files",
fail_recursive_variant_scan,
)
- monkeypatch.setattr("storage.studio_db.list_scan_folders", lambda: [{"path": str(root)}])
+ monkeypatch.setattr(
+ "storage.studio_db.list_scan_folders",
+ lambda: pytest.fail("captured custom folders were reloaded"),
+ )
monkeypatch.setattr("utils.paths.lmstudio_model_dirs", lambda: [])
monkeypatch.setattr("utils.paths.legacy_hf_cache_dir", lambda: tmp_path / "legacy")
monkeypatch.setattr("utils.paths.hf_default_cache_dir", lambda: tmp_path / "default")
monkeypatch.setattr("utils.hf_cache_settings.known_hf_hub_caches", lambda: [])
monkeypatch.setattr(models_route, "_resolve_hf_cache_dir", lambda: tmp_path / "active")
- rows = models_route.collect_local_models(tmp_path / "models")
+ rows = models_route.collect_local_models(
+ tmp_path / "models", custom_folders = [{"path": str(root)}]
+ )
paths = {row.path for row in rows}
assert {str(main), str(model_dir), str(snapshot.resolve())} <= paths
@@ -614,7 +692,7 @@ def test_a_later_attempts_cancel_marker_does_not_break_the_pinned_quant(monkeypa
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: (root if root is not None else active),
+ lambda create = False, root = None: root if root is not None else active,
)
monkeypatch.setattr(
GV,
@@ -674,7 +752,7 @@ def test_the_pins_excuse_covers_only_the_quants_it_holds(monkeypatch, tmp_path):
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: (root if root is not None else active),
+ lambda create = False, root = None: root if root is not None else active,
)
monkeypatch.setattr(
GV,
@@ -731,7 +809,7 @@ def test_a_later_attempts_incomplete_blob_does_not_break_the_pinned_quant(monkey
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: (root if root is not None else active),
+ lambda create = False, root = None: root if root is not None else active,
)
variant = GgufVariantInfo(
filename = "Model-Q4_K_M.gguf",
@@ -2965,7 +3043,7 @@ def test_list_cached_models_flags_single_file_diffusion_repos(monkeypatch, tmp_p
monkeypatch.setattr(
models_route,
"_cached_repo_task",
- lambda repo_info: ("text-to-image" if "Qwen-Image" in repo_info.repo_id else None),
+ lambda repo_info: "text-to-image" if "Qwen-Image" in repo_info.repo_id else None,
)
monkeypatch.setattr(
models_route,
@@ -3436,7 +3514,7 @@ def test_a_cancelled_siblings_resume_survives_the_local_listing(monkeypatch, tmp
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: (root if root is not None else active),
+ lambda create = False, root = None: root if root is not None else active,
)
# Disk-only means disk-only: a remote listing here would be the bug this route avoids.
@@ -3479,7 +3557,7 @@ def test_a_cancelled_sibling_survives_a_failed_remote_listing(monkeypatch, tmp_p
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: (root if root is not None else active),
+ lambda create = False, root = None: root if root is not None else active,
)
def _unreachable(*args, **kwargs):
@@ -3518,7 +3596,7 @@ def test_a_cancelled_siblings_marker_shows_on_the_repo_row(monkeypatch, tmp_path
monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
monkeypatch.setattr(
"hub.utils.hf_cache_state.hf_cache_root",
- lambda create = False, root = None: (root if root is not None else active),
+ lambda create = False, root = None: root if root is not None else active,
)
from hub.services.models import cache_inventory
diff --git a/studio/frontend/src/components/resource-picker/picker-tab-policy.ts b/studio/frontend/src/components/resource-picker/picker-tab-policy.ts
index c0a0ac1d9ad..78c529759f7 100644
--- a/studio/frontend/src/components/resource-picker/picker-tab-policy.ts
+++ b/studio/frontend/src/components/resource-picker/picker-tab-policy.ts
@@ -8,6 +8,12 @@ export interface PickerDeviceInventoryState {
isDeviceInventorySettled: boolean;
}
+export function shouldRefreshPickerInventoryOnMount(
+ readyAtMount: boolean,
+): boolean {
+ return readyAtMount;
+}
+
export type PickerDeviceListState =
| "empty"
| "error"
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 f6fc97f114d..955285709b0 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
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useNavigate } from "@tanstack/react-router";
+import { shouldRefreshPickerInventoryOnMount } from "@/components/resource-picker/picker-tab-policy";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Spinner } from "@/components/ui/spinner";
@@ -2094,6 +2095,7 @@ export function HubModelPicker({
const pickerInventory = useChatPickerInventory({ enabled: true });
const { cachedGguf, cachedModels, cachedReady, refreshInventory } =
pickerInventory;
+ const cachedReadyAtMount = useRef(cachedReady);
const lmStudioModels = useMemo(
() =>
sortLmStudio(
@@ -2281,6 +2283,9 @@ export function HubModelPicker({
}, [refreshScanFolders]);
useEffect(() => {
+ if (!shouldRefreshPickerInventoryOnMount(cachedReadyAtMount.current)) {
+ return;
+ }
void refreshInventory();
}, [refreshInventory]);
diff --git a/studio/frontend/tests/picker-tab-policy.test.ts b/studio/frontend/tests/picker-tab-policy.test.ts
index 04878c685aa..eca2a354f6b 100644
--- a/studio/frontend/tests/picker-tab-policy.test.ts
+++ b/studio/frontend/tests/picker-tab-policy.test.ts
@@ -7,6 +7,7 @@ import {
resolveInferredPickerTabLock,
resolvePickerDeviceListState,
resolvePickerTab,
+ shouldRefreshPickerInventoryOnMount,
} from "../src/components/resource-picker/picker-tab-policy.ts";
const inferredBase = {
@@ -122,6 +123,10 @@ test("keeps the opening tab stable when inventory settles", () => {
);
});
+test("refreshes picker inventory only when it was ready at mount", () => {
+ assert.deepEqual([false, true].map(shouldRefreshPickerInventoryOnMount), [false, true]);
+});
+
test("preserves explicit, locked, and offline tab decisions", () => {
assert.equal(
resolvePickerTab({