Skip to content

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

Studio: keep a downloaded model listed when upstream moves on (#9347)

oobaboogab4240405d063
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 3db058108b8..d63d75e85e5 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -1572,7 +1572,11 @@ def _fetch_swa_entry_from_hf(repo_id: str) -> Optional[object]:
try:
from huggingface_hub import hf_hub_download
from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.hf_probe import hf_file_definitely_absent
+ # Avoid caching the expected 404 for GGUF repos without config.json.
+ if hf_file_definitely_absent(repo_id, "config.json"):
+ return None
cfg_path = hf_hub_download(
repo_id,
"config.json",
diff --git a/studio/backend/hub/utils/inventory_scan.py b/studio/backend/hub/utils/inventory_scan.py
index 08d896d205a..710a1d63b54 100644
--- a/studio/backend/hub/utils/inventory_scan.py
+++ b/studio/backend/hub/utils/inventory_scan.py
@@ -252,13 +252,12 @@ def _read_refs_by_commit(refs_dir: Path) -> Optional[dict[str, set[str]]]:
return refs_by_commit
-def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_RecoveredRepoInfo]:
- """Rebuild the scan entry for a repo dropped *solely* over leftover refs.
+def _recover_repo_dropped_by_scan(repo_dir: Path) -> Optional[_RecoveredRepoInfo]:
+ """Recover readable revisions from a repo omitted by ``scan_cache_dir``.
- ``scan_cache_dir`` omits an intact repo when a ``refs/<branch>`` names a commit with no
- ``snapshots/<commit>/`` dir, which ``snapshot_download`` creates by writing ``refs/main`` before
- fetching the first file, hiding the repo from every inventory endpoint. Read-only: pruning the
- ref cannot be race-free. None whenever anything other than leftover refs failed the scan.
+ Dangling refs, broken snapshot links, and stray snapshot files can hide an otherwise usable
+ repo. Skip those bad entries and rebuild a read-only row from the intact files. Return None
+ when nothing remains or the on-disk state does not explain the omission.
"""
identity = _hf_repo_identity(repo_dir.name)
if identity is None:
@@ -278,16 +277,20 @@ def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_Recovered
blob_stats: dict[Path, object] = {}
revisions: set[_RecoveredRevisionInfo] = set()
dangling = dict(refs_by_commit)
+ # Entries that explain why upstream dropped the repo.
+ skipped = 0
for snapshot in snapshot_entries:
if snapshot.name in _CACHE_ENTRIES_TO_IGNORE:
continue
try:
if not snapshot.is_dir():
- # Upstream treats a file here as corruption; defer to it.
- return None
+ # A stray file is not a revision.
+ skipped += 1
+ continue
entries = drop_appledouble_metadata(sorted(snapshot.rglob("*")))
except OSError:
- return None
+ skipped += 1
+ continue
files: set[_RecoveredFileInfo] = set()
for entry in entries:
try:
@@ -296,8 +299,9 @@ def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_Recovered
blob_path = entry.resolve()
stat = blob_stats.get(blob_path) or blob_path.stat()
except OSError:
- # Broken symlink / unreadable blob: upstream raises here too.
- return None
+ # Keep the revision; broken links remain a separate partial signal.
+ skipped += 1
+ continue
blob_stats[blob_path] = stat
files.add(
_RecoveredFileInfo(
@@ -314,7 +318,8 @@ def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_Recovered
max(f.blob_last_modified for f in files) if files else snapshot.stat().st_mtime
)
except OSError:
- return None
+ skipped += 1
+ continue
revisions.add(
_RecoveredRevisionInfo(
commit_hash = snapshot.name,
@@ -328,8 +333,8 @@ def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_Recovered
# Nothing fetched yet, so the repo is not on disk.
if not revisions:
return None
- # Every ref resolved, so upstream dropped this repo for some other reason.
- if not dangling:
+ # Nothing here explains why upstream omitted the repo.
+ if not dangling and not skipped:
return None
try:
repo_stats = repo_dir.stat()
@@ -351,8 +356,8 @@ def _recover_repo_hidden_by_dangling_refs(repo_dir: Path) -> Optional[_Recovered
)
-def _with_repos_hidden_by_dangling_refs(scan, cache_root: Path):
- """Add back the repos ``scan_cache_dir`` dropped over a dangling ref."""
+def _with_repos_dropped_by_scan(scan, cache_root: Path):
+ """Add back the repos ``scan_cache_dir`` dropped over one bad entry."""
try:
repo_dirs = sorted(entry for entry in cache_root.iterdir() if "--" in entry.name)
except OSError:
@@ -369,14 +374,15 @@ def _with_repos_hidden_by_dangling_refs(scan, cache_root: Path):
try:
if str(repo_dir.resolve(strict = False)) in scanned:
continue
- entry = _recover_repo_hidden_by_dangling_refs(repo_dir)
+ entry = _recover_repo_dropped_by_scan(repo_dir)
except (OSError, RuntimeError, ValueError):
continue
if entry is None:
continue
logger.info(
- "Recovered HF cache repo %s hidden by a dangling ref (%d revision(s) on disk)",
+ "Recovered HF cache repo %s hidden by %s (%d revision(s) on disk)",
entry.repo_id,
+ "a dangling ref" if _repo_has_a_dangling_ref(repo_dir) else "an unreadable entry",
len(entry.revisions),
)
recovered.append(entry)
@@ -404,7 +410,7 @@ def _compute_all_hf_cache_scans() -> list:
scan = scan_cache_dir(cache_dir = str(cache_root))
# Only a warned-about scan can hide a repo, so never walk a healthy cache twice.
if getattr(scan, "warnings", None):
- scan = _with_repos_hidden_by_dangling_refs(scan, cache_root)
+ scan = _with_repos_dropped_by_scan(scan, cache_root)
scans.append(scan)
except Exception as exc:
logger.warning("Could not scan HF cache %s: %s", cache_root, exc)
@@ -615,9 +621,8 @@ def default_ref_offers_no_whole_quant(repo_cache_dir: Path) -> bool:
def _repo_has_a_dangling_ref(repo_cache_dir: Path) -> bool:
"""Whether ANY ref under ``refs/`` names a commit with no snapshot dir.
- ``_default_ref_names_an_absent_snapshot`` only checks ``refs/main``, but the recovery admits a
- repo over a leftover ref of any name, so the two must agree or a repo recovered over
- ``refs/stale`` is judged as though upstream had published it.
+ Check every ref because recovery is not limited to ``refs/main``. Repos recovered only for
+ unreadable entries correctly return False.
"""
refs_by_commit = _read_refs_by_commit(repo_cache_dir / "refs")
if refs_by_commit is None:
@@ -1291,6 +1296,9 @@ def _recovered_snapshot_cannot_serve(
manifest and ``.incomplete``/broken-symlink all read false and a snapshot short a shard looks
runnable; its contents are the only evidence left. Scoped to the dangling case: where the ref
resolves, upstream already publishes the row.
+
+ Other recovered cases retain their own evidence: broken links mark the repo partial, while a
+ stray snapshot file never represented a revision.
"""
if repo_cache_dir is None or snapshot_dir is None:
return False
diff --git a/studio/backend/picker/service.py b/studio/backend/picker/service.py
index 1dc9c3b870e..ac1642ef0db 100644
--- a/studio/backend/picker/service.py
+++ b/studio/backend/picker/service.py
@@ -379,25 +379,21 @@ def read_default_chat_template(
_api = HfApi()
- def _remote_exceeds_cap(rel: str) -> bool:
- # Best-effort: skip the download when the remote's advertised size
- # exceeds the cap, so a maliciously large sidecar is never fetched.
+ def _remote_worth_downloading(rel: str) -> bool:
+ # Reuse the size lookup to skip absent or oversized files.
try:
infos = _api.get_paths_info(resolved, [rel], repo_type = "model", token = hf_token)
except Exception:
+ # An inconclusive lookup preserves the existing download behavior.
+ return True
+ matched = [info for info in infos if getattr(info, "path", None) == rel]
+ if not matched:
return False
- for info in infos:
- size = getattr(info, "size", None)
- if (
- getattr(info, "path", None) == rel
- and isinstance(size, int)
- and size > MAX_TEMPLATE_METADATA_BYTES
- ):
- return True
- return False
+ size = getattr(matched[0], "size", None)
+ return not (isinstance(size, int) and size > MAX_TEMPLATE_METADATA_BYTES)
def _download_text(rel: str) -> Optional[str]:
- if _remote_exceeds_cap(rel):
+ if not _remote_worth_downloading(rel):
return None
try:
path = hf_hub_download(
diff --git a/studio/backend/tests/test_hf_cache_dangling_refs.py b/studio/backend/tests/test_hf_cache_dangling_refs.py
index 5c748eadd6c..cf39d5aa9eb 100644
--- a/studio/backend/tests/test_hf_cache_dangling_refs.py
+++ b/studio/backend/tests/test_hf_cache_dangling_refs.py
@@ -1,13 +1,10 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""A dangling ``refs/<branch>`` must not hide an intact repo from the scan.
+"""A bad cache entry must not hide an otherwise usable repo.
-``scan_cache_dir`` raises CorruptedCacheException for a repo whose ref names a commit with no
-``snapshots/<commit>/`` directory and omits it from ``.repos``, so the model stays visible in the
-picker (a plain directory walk) but vanishes from every Hub inventory endpoint chat auto-load reads.
-The repair is read-only: refs are written with an unlocked in-place ``write_text``, so no external
-process can delete one race-free.
+Recovery handles dangling refs, broken snapshot links, and stray snapshot files without mutating
+the cache. Ref deletion cannot be race-free because Hub writes refs in place.
"""
from __future__ import annotations
@@ -178,15 +175,45 @@ def test_a_download_that_has_only_written_its_ref_is_not_invented(tmp_path, monk
assert _ref_names(repo_dir) == ["main"]
-def test_a_repo_corrupted_beyond_a_dangling_ref_stays_omitted(tmp_path, monkeypatch):
- """A broken snapshot symlink is corruption hub rejects for its own reasons."""
- repo_dir = _build_repo(tmp_path)
+def test_a_broken_symlink_costs_its_file_and_not_the_repo(tmp_path, monkeypatch):
+ """A broken link must not hide readable files beside it."""
+ repo_dir = _build_repo(tmp_path, ref = SNAPSHOT)
broken = repo_dir / "snapshots" / SNAPSHOT / "weights.bin"
try:
os.symlink(repo_dir / "blobs" / "missing", broken)
except (NotImplementedError, OSError):
pytest.skip("symlinks unavailable (Windows without developer mode)")
+ repo = _only_repo(tmp_path, monkeypatch)
+
+ names = {file.file_name for revision in repo.revisions for file in revision.files}
+ assert names == {"model.safetensors"}, "the readable payload must survive"
+ assert _ref_names(repo_dir) == ["main"], "the repair stays read-only"
+
+
+def test_a_stray_file_under_snapshots_costs_itself_and_not_the_repo(tmp_path, monkeypatch):
+ """A stray snapshot file is not a revision."""
+ repo_dir = _build_repo(tmp_path, ref = SNAPSHOT)
+ (repo_dir / "snapshots" / "notes.txt").write_text("stray", encoding = "utf-8")
+
+ repo = _only_repo(tmp_path, monkeypatch)
+
+ assert {revision.commit_hash for revision in repo.revisions} == {SNAPSHOT}
+
+
+def test_a_repo_dropped_for_a_reason_this_cannot_see_is_not_invented(tmp_path):
+ """Do not invent a row when the on-disk state does not explain the omission."""
+ repo_dir = _build_repo(tmp_path, ref = SNAPSHOT)
+
+ assert inventory_scan._recover_repo_dropped_by_scan(repo_dir) is None
+
+
+def test_a_refs_file_where_the_refs_directory_belongs_stays_omitted(tmp_path, monkeypatch):
+ """Unreadable refs provide too little information to recover the repo."""
+ repo_dir = _build_repo(tmp_path, ref = None)
+ shutil.rmtree(repo_dir / "refs")
+ (repo_dir / "refs").write_text(SNAPSHOT, encoding = "utf-8")
+
assert _scanned_repo_ids(tmp_path, monkeypatch) == []
@@ -211,7 +238,7 @@ def test_an_unreadable_repo_does_not_abort_the_recovery(tmp_path):
pytest.skip("filesystem does not enforce directory permissions")
try:
scan = _empty_cache_info(HFCacheInfo)
- merged = inventory_scan._with_repos_hidden_by_dangling_refs(scan, tmp_path)
+ merged = inventory_scan._with_repos_dropped_by_scan(scan, tmp_path)
assert sorted(repo.repo_id for repo in merged.repos) == ["Org/Model"]
assert _ref_names(hidden) == ["main"]
finally:
@@ -605,6 +632,32 @@ def test_gguf_variants_still_list_when_no_snapshot_is_complete(
assert _local_gguf_variants_for_autoload(rows[0], tmp_path) == offered
+def test_a_broken_symlink_costs_its_quant_and_leaves_the_clean_one_loadable(tmp_path, monkeypatch):
+ """Recovery keeps a clean quant loadable without offering the broken one."""
+ repo_dir = tmp_path / "models--Org--Model"
+ snapshot = repo_dir / "snapshots" / SNAPSHOT
+ snapshot.mkdir(parents = True)
+ (repo_dir / "blobs").mkdir()
+ (repo_dir / "refs").mkdir()
+ (repo_dir / "refs" / "main").write_text(SNAPSHOT, encoding = "utf-8")
+ good = repo_dir / "blobs" / ("1" * 64)
+ good.write_bytes(b"\0" * 2048)
+ try:
+ os.symlink(good, snapshot / "Model-Q4_K_M.gguf")
+ os.symlink(repo_dir / "blobs" / ("2" * 64), snapshot / "Model-Q8_0.gguf")
+ except (NotImplementedError, OSError):
+ pytest.skip("symlinks unavailable (Windows without developer mode)")
+
+ rows = _autoload_gguf_rows(tmp_path, monkeypatch)
+
+ assert [row["repo_id"] for row in rows] == ["Org/Model"]
+ assert rows[0]["partial"] is False, "one dead quant must not cost the clean one can_chat"
+ assert rows[0]["capabilities"]["can_chat"] is True
+ # Keep both visible, but offer only the readable quant for loading.
+ assert _listed_gguf_variants(rows[0], tmp_path) == ["Q4_K_M", "Q8_0"]
+ assert _local_gguf_variants_for_autoload(rows[0], tmp_path) == ["Q4_K_M"]
+
+
def test_a_whole_quant_in_a_mixed_newest_snapshot_beats_an_older_larger_one(tmp_path, monkeypatch):
"""A whole small quant can sit in the newest snapshot beside an interrupted split one while an
older snapshot holds only a whole larger quant. Auto-load takes the smallest offered, so skipping
@@ -1522,7 +1575,7 @@ _MTIME_READERS = {
"hub/utils/gguf.py": frozenset(),
"hub/services/models/cache_inventory.py": frozenset({"_blob_mtime"}),
# Mirrors what huggingface_hub records per revision; it selects nothing.
- "hub/utils/inventory_scan.py": frozenset({"_recover_repo_hidden_by_dangling_refs"}),
+ "hub/utils/inventory_scan.py": frozenset({"_recover_repo_dropped_by_scan"}),
# The compatibility routes, listed so the two snapshot selectors cannot reintroduce their own
# mtime reads. The names left rank directories or repo/blob mtimes, never snapshots.
"routes/models.py": frozenset(
diff --git a/studio/backend/tests/test_hf_optional_file_probe.py b/studio/backend/tests/test_hf_optional_file_probe.py
new file mode 100644
index 00000000000..eff0c7c99db
--- /dev/null
+++ b/studio/backend/tests/test_hf_optional_file_probe.py
@@ -0,0 +1,247 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Optional Hub file probes must not mutate the cache.
+
+Cached 404s can leave refs pointing to absent snapshots, causing cache scans to omit the repo.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+
+from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
+
+from utils.hf_probe import hf_file_definitely_absent
+
+
+def _http_error(name: str, *, fallback: str | None = None) -> Exception:
+ """Build an HTTP-shaped error for either supported Hub exception layout."""
+ import requests
+
+ from huggingface_hub import errors
+
+ cls = getattr(errors, name, None)
+ if cls is None:
+ assert fallback is not None, f"{name} is missing and no fallback was named"
+ cls = getattr(errors, fallback)
+ response = requests.Response()
+ response.status_code = 404 if "Entry" in name else 401
+ try:
+ return cls(name, response = response)
+ except TypeError:
+ # The plain-Exception base takes a message and nothing else.
+ return cls(name)
+
+
+_BACKEND = Path(__file__).resolve().parents[1]
+
+# Optional-file readers and the guard each must call before downloading. The template reader
+# reuses its existing path lookup instead of adding another request.
+_GUARDED = {
+ "core/inference/llama_cpp.py": {"_fetch_swa_entry_from_hf": "hf_file_definitely_absent"},
+ "picker/service.py": {"read_default_chat_template": "get_paths_info"},
+ "utils/models/model_config.py": {
+ "_raw_config_has_vision_config": "hf_file_definitely_absent",
+ "get_base_model_from_lora_identifier": "hf_file_definitely_absent",
+ },
+ "utils/security/consent.py": {"_load_remote_code_configs": "hf_file_definitely_absent"},
+ "utils/security/file_security.py": {"_indexed_shard_paths": "hf_file_definitely_absent"},
+ "utils/security/remote_code_scan.py": {
+ "external_auto_map_repos": "hf_file_definitely_absent",
+ "repo_remote_code_files": "hf_file_definitely_absent",
+ },
+}
+
+
+def _raise(exc):
+ def _fn(*_args, **_kwargs):
+ raise exc
+
+ return _fn
+
+
+def _patch_metadata(monkeypatch, behavior):
+ import huggingface_hub
+ monkeypatch.setattr(huggingface_hub, "get_hf_file_metadata", behavior)
+
+
+# --- what counts as absent ---------------------------------------------------
+
+
+def test_the_real_remote_404_reads_as_absent(monkeypatch):
+ """Both supported Hub exception layouts report a remote 404 as absent."""
+ _patch_metadata(
+ monkeypatch,
+ _raise(_http_error("RemoteEntryNotFoundError", fallback = "EntryNotFoundError")),
+ )
+
+ assert hf_file_definitely_absent("Org/Model", "adapter_config.json") is True
+
+
+def test_a_remote_404_is_the_only_absent_answer(monkeypatch):
+ _patch_metadata(monkeypatch, _raise(EntryNotFoundError("no such file")))
+
+ assert hf_file_definitely_absent("Org/Model", "adapter_config.json") is True
+
+
+def test_offline_is_not_absence(monkeypatch):
+ """A local cache miss means offline, not remote absence."""
+ _patch_metadata(monkeypatch, _raise(LocalEntryNotFoundError("offline")))
+
+ assert hf_file_definitely_absent("Org/Model", "adapter_config.json") is False
+
+
+ "make_exc",
+ [
+ lambda: _http_error("GatedRepoError"),
+ lambda: _http_error("RepositoryNotFoundError"),
+ lambda: TimeoutError("slow"),
+ lambda: ValueError("nonsense"),
+ ],
+ ids = ["gated", "missing-repo", "timeout", "unexpected"],
+)
+def test_every_other_failure_falls_through_to_the_caller(monkeypatch, make_exc):
+ """Only confirmed remote 404s may short-circuit caller behavior."""
+ _patch_metadata(monkeypatch, _raise(make_exc()))
+
+ assert hf_file_definitely_absent("Org/Model", "config.json") is False
+
+
+def test_a_present_file_is_not_absent(monkeypatch):
+ _patch_metadata(monkeypatch, lambda *_a, **_k: object())
+
+ assert hf_file_definitely_absent("Org/Model", "config.json") is False
+
+
+def test_an_unimportable_hub_is_not_an_answer(monkeypatch):
+ """An import failure is not proof of absence."""
+ import builtins
+
+ real_import = builtins.__import__
+
+ def _fail(name, *args, **kwargs):
+ if name == "huggingface_hub":
+ raise ImportError("no hub")
+ return real_import(name, *args, **kwargs)
+
+ monkeypatch.setattr(builtins, "__import__", _fail)
+
+ assert hf_file_definitely_absent("Org/Model", "config.json") is False
+
+
+# --- the cache is never touched ----------------------------------------------
+
+
+def test_the_probe_writes_nothing_to_the_cache(monkeypatch, tmp_path):
+ """A 404 probe leaves refs, snapshots, and no-exist markers unchanged."""
+ repo_dir = tmp_path / "models--Org--Model"
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "snapshots" / ("a" * 40)).mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("a" * 40, encoding = "utf-8")
+
+ before = sorted(str(p.relative_to(tmp_path)) for p in tmp_path.rglob("*"))
+ _patch_metadata(monkeypatch, _raise(EntryNotFoundError("no such file")))
+
+ assert hf_file_definitely_absent("Org/Model", "adapter_config.json") is True
+ assert sorted(str(p.relative_to(tmp_path)) for p in tmp_path.rglob("*")) == before
+ assert (repo_dir / "refs" / "main").read_text(encoding = "utf-8") == "a" * 40
+
+
+def test_the_lora_base_probe_skips_the_download_when_the_file_is_absent(monkeypatch):
+ import huggingface_hub
+
+ from utils.models import model_config
+
+ calls = []
+ monkeypatch.setattr(
+ huggingface_hub,
+ "hf_hub_download",
+ lambda *args, **kwargs: calls.append(args) or "/dev/null",
+ )
+ _patch_metadata(monkeypatch, _raise(EntryNotFoundError("no such file")))
+
+ assert model_config.get_base_model_from_lora_identifier("unsloth/Qwen3-1.7B-GGUF") is None
+ assert calls == [], "a file the Hub says is absent must never reach the cache"
+
+
+def test_a_present_adapter_config_still_resolves_its_base(monkeypatch, tmp_path):
+ import huggingface_hub
+
+ from utils.models import model_config
+
+ cfg = tmp_path / "adapter_config.json"
+ cfg.write_text('{"base_model_name_or_path": "unsloth/Qwen3-1.7B"}', encoding = "utf-8")
+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", lambda *_a, **_k: str(cfg))
+ _patch_metadata(monkeypatch, lambda *_a, **_k: object())
+
+ assert model_config.get_base_model_from_lora_identifier("Org/Adapter") == "unsloth/Qwen3-1.7B"
+
+
+def test_the_chat_template_search_skips_paths_the_listing_does_not_name(monkeypatch):
+ """The existing path lookup must gate absent template downloads."""
+ import huggingface_hub
+
+ from picker import service
+
+ listed: list[str] = []
+ downloads: list[str] = []
+
+ monkeypatch.setattr(
+ huggingface_hub.HfApi,
+ "get_paths_info",
+ lambda self, repo_id, paths, **kwargs: listed.extend(paths) or [],
+ )
+ monkeypatch.setattr(
+ huggingface_hub,
+ "hf_hub_download",
+ lambda *args, **kwargs: downloads.append(args) or "/dev/null",
+ )
+
+ assert service.read_default_chat_template("Org/Model") is None
+ assert listed, "the listing must still run; it is what answers both questions"
+ assert downloads == [], "a path the listing does not name must never reach the cache"
+
+
+# --- the guard cannot be dropped ---------------------------------------------
+
+
+def _functions(path: Path) -> dict:
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ return {
+ node.name: node
+ for node in ast.walk(tree)
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+
+def _called_names(node: ast.AST) -> set[str]:
+ """Every function and method name called anywhere inside *node*, nested defs included."""
+ names: set[str] = set()
+ for child in ast.walk(node):
+ if not isinstance(child, ast.Call):
+ continue
+ if isinstance(child.func, ast.Name):
+ names.add(child.func.id)
+ elif isinstance(child.func, ast.Attribute):
+ names.add(child.func.attr)
+ return names
+
+
[email protected]("rel", sorted(_GUARDED))
+def test_every_optional_file_read_on_the_load_path_probes_first(rel):
+ defined = _functions(_BACKEND / rel)
+ for name, guard in sorted(_GUARDED[rel].items()):
+ assert name in defined, f"{rel}::{name} was renamed; update _GUARDED"
+ called = _called_names(defined[name])
+ assert (
+ "hf_hub_download" in called
+ ), f"{rel}::{name} no longer downloads; drop it from _GUARDED"
+ assert guard in called, (
+ f"{rel}::{name} downloads an optional file without asking {guard} first, so a 404 "
+ "there rewrites refs/main and hides the repo from the Hub cached inventory"
+ )
diff --git a/studio/backend/utils/hf_probe.py b/studio/backend/utils/hf_probe.py
new file mode 100644
index 00000000000..501ad6043a3
--- /dev/null
+++ b/studio/backend/utils/hf_probe.py
@@ -0,0 +1,54 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Probe optional Hub files without caching missing entries.
+
+``hf_hub_download`` can leave a ref pointing to a snapshot that is not on disk after a 404, causing
+``scan_cache_dir`` to omit the repo. Metadata requests answer the same question without changing
+the cache.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from loggers import get_logger
+
+logger = get_logger(__name__)
+
+
+def hf_file_definitely_absent(
+ repo_id: str,
+ filename: str,
+ *,
+ repo_type: str = "model",
+ revision: Optional[str] = None,
+ token: Optional[str] = None,
+) -> bool:
+ """Return True only when the Hub confirms that *filename* is absent.
+
+ Offline, authentication, rate-limit, and resolution failures return False so callers preserve
+ their existing download and error handling.
+ """
+ try:
+ from huggingface_hub import get_hf_file_metadata, hf_hub_url
+ from huggingface_hub.errors import EntryNotFoundError, LocalEntryNotFoundError
+ except Exception: # noqa: BLE001 - an unimportable hub is the caller's problem, not ours
+ return False
+
+ try:
+ url = hf_hub_url(
+ repo_id = repo_id,
+ filename = filename,
+ repo_type = repo_type,
+ revision = revision,
+ )
+ get_hf_file_metadata(url, token = token)
+ except LocalEntryNotFoundError:
+ return False
+ except EntryNotFoundError:
+ return True
+ except Exception as exc: # noqa: BLE001 - no answer is not an answer of "absent"
+ logger.debug("Could not probe %s for %s: %s", repo_id, filename, exc)
+ return False
+ return False
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index dcfef11d118..d9bcd97837f 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -690,7 +690,17 @@ def _raw_config_has_vision_config(
config_path = Path(normalize_path(model_name)).expanduser() / "config.json"
else:
from huggingface_hub import hf_hub_download
+ from utils.hf_probe import hf_file_definitely_absent
+ # Avoid caching the expected 404 for GGUF repos without config.json.
+ if not local_files_only and hf_file_definitely_absent(
+ model_name,
+ "config.json",
+ revision = revision,
+ token = hf_token,
+ ):
+ logger.debug("'%s' has no config.json on the Hub", model_name)
+ return None
download_kwargs = {
"repo_id": model_name,
"filename": "config.json",
@@ -3454,6 +3464,15 @@ def get_base_model_from_lora_identifier(
# Remote repo id: read base_model_name_or_path from adapter_config.json only.
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError
+ from utils.hf_probe import hf_file_definitely_absent
+
+ # Plain model repos normally lack adapter_config.json, so probe without caching its 404.
+ if hf_file_definitely_absent(
+ identifier,
+ "adapter_config.json",
+ token = hf_token if hf_token else None,
+ ):
+ return None
last_exc = None
for _attempt in range(2): # one retry: a transient blip must not skip the base
diff --git a/studio/backend/utils/security/consent.py b/studio/backend/utils/security/consent.py
index a51e213dca8..86f9e225d55 100644
--- a/studio/backend/utils/security/consent.py
+++ b/studio/backend/utils/security/consent.py
@@ -151,9 +151,13 @@ def _load_remote_code_configs(
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import EntryNotFoundError
from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.hf_probe import hf_file_definitely_absent
configs = []
for name in remote_code_config_paths(load_subdirs):
+ # Probe optional configs without caching 404s; other failures still fail closed.
+ if hf_file_definitely_absent(model_name, name, token = hf_token):
+ continue
try:
p = hf_hub_download(
repo_id = model_name,
diff --git a/studio/backend/utils/security/file_security.py b/studio/backend/utils/security/file_security.py
index a6d5e620a36..10cf4fb4d64 100644
--- a/studio/backend/utils/security/file_security.py
+++ b/studio/backend/utils/security/file_security.py
@@ -175,6 +175,7 @@ def _indexed_shard_paths(
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import EntryNotFoundError
from utils.hf_cache_settings import active_hf_hub_cache
+ from utils.hf_probe import hf_file_definitely_absent
except Exception:
return None
@@ -182,6 +183,11 @@ def _indexed_shard_paths(
inconclusive = False
for prefix in _index_prefixes(load_subdirs):
for filename in _TRANSFORMERS_INDEX_FILES:
+ # Most repos are unsharded, so avoid caching expected 404s for optional indexes.
+ if hf_file_definitely_absent(
+ model_name, prefix + filename, revision = revision, token = hf_token or None
+ ):
+ continue
try:
index_path = hf_hub_download(
model_name,
diff --git a/studio/backend/utils/security/remote_code_scan.py b/studio/backend/utils/security/remote_code_scan.py
index 9a071a502cd..fe13a38170e 100644
--- a/studio/backend/utils/security/remote_code_scan.py
+++ b/studio/backend/utils/security/remote_code_scan.py
@@ -521,12 +521,16 @@ def repo_remote_code_files(
from huggingface_hub import hf_hub_download, list_repo_files
from huggingface_hub.utils import EntryNotFoundError
+ from utils.hf_probe import hf_file_definitely_absent
# Collect auto_map refs from EVERY config that can declare one. A 404
# (EntryNotFoundError) means the config is absent -> skip; any other failure is
# transient/auth and could hide an auto_map, so fail closed (unscannable).
refs = set()
for cfg_name in remote_code_config_paths(load_subdirs):
+ # Avoid caching expected 404s; other failures still reach the fail-closed path.
+ if hf_file_definitely_absent(model_name, cfg_name, token = hf_token):
+ continue
try:
cfg_path = hf_hub_download(
model_name,
@@ -687,8 +691,12 @@ def external_auto_map_repos(
from huggingface_hub import hf_hub_download
from huggingface_hub.utils import EntryNotFoundError
+ from utils.hf_probe import hf_file_definitely_absent
for cfg_name in remote_code_config_paths(load_subdirs):
+ # Same guard as the scanner above; see utils/hf_probe.py.
+ if hf_file_definitely_absent(model_name, cfg_name, token = hf_token):
+ continue
try:
cfg_path = hf_hub_download(
model_name,