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: cache the servability scan behind GET /v1/models (#9998)

Daniel Hana251534efcd8
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.py
index 92b132f4de7..eaca4a593ee 100644
--- a/studio/backend/core/inference/local_model_resolver.py
+++ b/studio/backend/core/inference/local_model_resolver.py
@@ -577,6 +577,17 @@ def _snapshot_is_trusted(timestamp: float, now: float) -> bool:
return False
+# Bumped by every invalidate_index() call. A cache built on top of this index can key
+# on it and be dropped by the same call that drops the index, rather than each new
+# invalidation site having to remember one more cache to clear.
+_generation = 0
+
+
+def index_generation() -> int:
+ """How many times the local scan has been invalidated since this process started."""
+ return _generation
+
+
def invalidate_index(*, additions_only: bool = False) -> None:
"""Mark the cached scan stale.
@@ -585,9 +596,10 @@ def invalidate_index(*, additions_only: bool = False) -> None:
Other invalidations retain the allocation but revoke that trust, since a scan
root may have been removed. Ordinary TTL expiry is likewise not additions-only.
"""
- global _scan, _warm_pending
+ global _scan, _warm_pending, _generation
with _lock:
now = time.monotonic()
+ _generation += 1
timestamp, retained = _scan
# Publish entries and their trust state together. A lock-free reader sees
# either the complete old snapshot or the complete invalidated one, never a
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 3289e5a330f..7c8b7122d82 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -6837,8 +6837,7 @@ def _target_accepts_request_input(
_AUDIO_IMAGE_INPUT_DETAIL = (
- "This model takes audio or an image in one message, not both."
- " Send the image on its own turn."
+ "This model takes audio or an image in one message, not both. Send the image on its own turn."
)
@@ -23916,35 +23915,163 @@ async def _cached_local_catalog() -> list:
return _CATALOG_CACHE["models"]
-def _servable_catalog_rows(catalog) -> list[tuple[object, bool, tuple[str, ...], bool]]:
+# One tuple, published in a single assignment: the fast path below reads it without the
+# lock, and three separate fields could be caught half-replaced -- old stamp and old
+# catalog still matching while `rows` already held the next catalog's rows.
+# How long a scan may answer without any counter having moved. Bounds the one case the
+# counters cannot see, a file added or removed from a scan folder outside Studio, while
+# still collapsing the burst of polls that motivated the cache: at 5s a client polling
+# every second still takes four hits out of five.
+_SERVABLE_SCAN_TTL_S = 5.0
+_SERVABLE_SCAN_CACHE: dict = {"entry": None} # (catalog_at, catalog, generation, at, rows)
+_SERVABLE_SCAN_CACHE_LOCK = threading.Lock()
+
+
+def _servability_generation() -> tuple[int, int, int]:
+ """Every counter the cached servability answer depends on.
+
+ A tuple rather than one number: the three move independently and no single existing
+ counter covers the others, so combining them here is what keeps a stale row from
+ outliving any one of the events that should have retired it. All three are cheap
+ reads of module state; nothing here touches the filesystem.
+
+ Nothing is caught. A missing counter would silently pin this key at a constant and
+ quietly undo the invalidation it exists to provide, which is worse than the import
+ error that says so.
+ """
+ from core.inference.local_model_resolver import index_generation
+ from utils.hardware import hardware as hw
+
+ from hub.utils.inventory_scan import hf_cache_scans_epoch
+
+ return (
+ index_generation(),
+ int(hf_cache_scans_epoch()),
+ int(hw.DETECTION_GENERATION),
+ )
+
+
+def _servable_catalog_scan(catalog, catalog_at: Optional[float]):
+ """``(info, is_gguf, quants, resident_key)`` per servable entry, rebuilt only when
+ the shared catalog scan is replaced.
+
+ ``local_servable_model`` stats many files and reads a ``config.json`` per entry, and
+ /v1/models re-ran that for the whole catalog on every request even though the catalog
+ behind it was already cached -- 316-621ms against 13-34ms for the internal list, which
+ touches no filesystem. Keyed on the catalog stamp like ``_validated_media_picks``, so
+ a rescan is what invalidates it and nothing goes stale behind a separate TTL.
+ """
+ from core.inference.local_model_resolver import (
+ index_generation,
+ local_load_dir,
+ local_servable_model,
+ )
+ from hub.services.models.catalog_classification import _UNSUPPORTED_DIFFUSION_TASK
+
+ # Identity as well as the stamp: _CATALOG_CACHE["at"] only advances inside
+ # _cached_local_catalog, so a caller that supplies a catalog from anywhere else
+ # would otherwise be served the previous scan under an unchanged stamp.
+ #
+ # And every signal the servability decision itself reads, because the catalog is the
+ # coarsest of them and would otherwise pin a stale answer for the rest of its TTL,
+ # where the per-request scan re-derived one each time:
+ #
+ # resolver index a model or quant deleted from ./models, an export, a download
+ # HF cache epoch a cached Hub repo deleted; deletion.py invalidates only this
+ # detection gen hardware.DEVICE changing under the resolver, which is what
+ # decides servability for non-GGUF checkpoints. An Apple Silicon
+ # MLX self-repair flips CPU to MLX after startup, and an early
+ # /v1/models would otherwise hide those checkpoints until the TTL.
+ def _fresh():
+ """Read the entry and the generation as one validated snapshot.
+
+ Generation, entry, generation. The counter only ever advances, so equal ends mean
+ no invalidation landed between them; an unequal pair means one did and the rows in
+ hand may predate it. Without the second read a delete that completes between the
+ generation read and the entry read is accepted anyway, on the lock-free path and
+ under the lock alike, since invalidate_index does not take this lock.
+ """
+ before = _servability_generation()
+ entry = _SERVABLE_SCAN_CACHE["entry"] # one read, so the tuple cannot tear
+ if entry is None or catalog_at is None:
+ return None
+ at, cached_catalog, cached_generation, scanned_at, rows = entry
+ if cached_generation != before or _servability_generation() != before:
+ return None
+ # Its own TTL as well as the generation. The counters cover Studio's own download
+ # and delete paths; a file removed from a scan folder by hand moves none of them,
+ # and the per-request scan used to notice that immediately. A directory mtime
+ # would not help: editing or deleting a file inside a nested directory does not
+ # bump the root's mtime, which is why the resolver's own mtime memo was dropped.
+ if time.monotonic() - scanned_at > _SERVABLE_SCAN_TTL_S:
+ return None
+ return rows if at == catalog_at and cached_catalog is catalog else None
+
+ hit = _fresh()
+ if hit is not None:
+ return hit
+ with _SERVABLE_SCAN_CACHE_LOCK:
+ hit = _fresh()
+ if hit is not None:
+ return hit
+ # Captured before the scan: an invalidation that lands while it runs must make
+ # the stored entry stale rather than be stamped in as if the scan had seen it.
+ generation = _servability_generation()
+ scanned = []
+ for info in catalog:
+ if getattr(info, "task", None) in (
+ *_MEDIA_MODEL_TASKS,
+ _STT_MODEL_TASK,
+ _TTS_MODEL_TASK,
+ _UNSUPPORTED_DIFFUSION_TASK,
+ ):
+ continue
+ servable = local_servable_model(info)
+ if servable is None:
+ continue
+ is_gguf, quants = servable
+ # The source path, not the resolved load dir: an HF repo's snapshot pointer can
+ # move within the catalog's lifetime, and a cached snapshot path would then
+ # report a freshly loaded model as unloaded. Residency resolves it per call.
+ scanned.append((info, is_gguf, quants, getattr(info, "path", None)))
+ if catalog_at is not None:
+ # The generation read BEFORE the scan, not after: an invalidation that
+ # landed while the scan ran would otherwise be stamped in as if the scan
+ # had seen it, and the very delete this guards against would be cached.
+ _SERVABLE_SCAN_CACHE["entry"] = (
+ catalog_at,
+ catalog,
+ generation,
+ time.monotonic(),
+ scanned,
+ )
+ return scanned
+
+
+def _servable_catalog_rows(
+ catalog, catalog_at: Optional[float] = None
+) -> list[tuple[object, bool, tuple[str, ...], bool]]:
"""``(info, is_gguf, quants, resident)`` per catalog entry this server can serve
from disk. Module scope, and always called through ``asyncio.to_thread``: the file
- checks stat many files and the residency check reads the inference singleton."""
- from core.inference.local_model_resolver import local_load_dir, local_servable_model
- from hub.services.models.catalog_classification import _UNSUPPORTED_DIFFUSION_TASK
+ checks stat many files and the residency check reads the inference singleton.
- rows = []
- for info in catalog:
- if getattr(info, "task", None) in (
- *_MEDIA_MODEL_TASKS,
- _STT_MODEL_TASK,
- _TTS_MODEL_TASK,
- _UNSUPPORTED_DIFFUSION_TASK,
- ):
- continue
- servable = local_servable_model(info)
- if servable is None:
- continue
- is_gguf, quants = servable
- path = getattr(info, "path", None)
- # the load dir, since an HF cache repo loads as a snapshot exact_only cannot match.
- resident = _resolves_to_resident(
- path if is_gguf else local_load_dir(path),
- llama_only = is_gguf,
- exact_only = not is_gguf,
+ Residency is read per request; only the scan is cached. That includes resolving the
+ HF snapshot a non-GGUF path currently points at, since a download can move it inside
+ the catalog's lifetime and a cached snapshot would report a loaded model as unloaded."""
+ from core.inference.local_model_resolver import local_load_dir
+ return [
+ (
+ info,
+ is_gguf,
+ quants,
+ _resolves_to_resident(
+ path if is_gguf else local_load_dir(path),
+ llama_only = is_gguf,
+ exact_only = not is_gguf,
+ ),
)
- rows.append((info, is_gguf, quants, resident))
- return rows
+ for info, is_gguf, quants, path in _servable_catalog_scan(catalog, catalog_at)
+ ]
async def _openai_catalog_objects() -> list[dict]:
@@ -23964,7 +24091,10 @@ async def _openai_catalog_objects() -> list[dict]:
# Downloaded but unloaded: GGUF via llama.cpp, other weights via the orchestrator.
catalog = await _cached_local_catalog()
- for info, is_gguf, quants, loaded in await asyncio.to_thread(_servable_catalog_rows, catalog):
+ catalog_at = _CATALOG_CACHE["at"]
+ for info, is_gguf, quants, loaded in await asyncio.to_thread(
+ _servable_catalog_rows, catalog, catalog_at
+ ):
cid = getattr(info, "model_id", None) or public_model_id(getattr(info, "id", None))
if not cid or cid in by_id:
continue
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index a0f9d256881..2e058e921c6 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -1292,8 +1292,8 @@ async def _shared_compat_local_inventory_scan(
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)
+ lambda expected_epoch = epoch, folders = custom_folders, roots = scan_sources: collect(
+ expected_epoch, folders, roots
),
)
except _CompatLocalCacheChanged as changed:
@@ -1306,6 +1306,22 @@ async def _shared_compat_local_inventory_scan(
return await asyncio.to_thread(classify, superseded)
+async def _invalidate_local_scans() -> None:
+ """Retire the cached local scans after something was deleted from disk.
+
+ Every successful deletion branch has to call this. The /v1/models servability scan is
+ cached against the resolver generation, so a branch that returns without bumping it
+ keeps advertising what was just removed until the catalog TTL expires.
+
+ Off the loop, like the other async invalidation sites in this file: invalidate_index
+ takes the resolver lock, and _index() holds that across a full multi-root filesystem
+ scan, so calling it inline from an async route would stall unrelated requests and
+ in-flight inference streams behind a rebuild.
+ """
+ from core.inference.local_model_resolver import invalidate_index
+ await asyncio.to_thread(invalidate_index)
+
+
@router.get("/local", response_model = LocalModelListResponse)
async def list_local_models(
models_dir: str = Query(
@@ -3345,6 +3361,7 @@ async def delete_finetuned_model(
_prune_empty_parents(target_path, allowed_root)
except OSError:
pass
+ await _invalidate_local_scans()
logger.info(
"Deleted %s GGUF file(s) for exported model at %s variant %s (%0.1f MB freed)",
deleted_count,
@@ -3371,6 +3388,7 @@ async def delete_finetuned_model(
_prune_empty_parents(target_path, allowed_root)
+ await _invalidate_local_scans()
logger.info("Deleted fine-tuned model at %s", target_path)
return {"status": "deleted", "path": str(target_path)}
except HTTPException:
diff --git a/studio/backend/tests/test_openai_models_servable_cache.py b/studio/backend/tests/test_openai_models_servable_cache.py
new file mode 100644
index 00000000000..629def7f91c
--- /dev/null
+++ b/studio/backend/tests/test_openai_models_servable_cache.py
@@ -0,0 +1,100 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Tests for the servability scan cache behind GET /v1/models.
+
+A user's log showed /v1/models at 316-621ms while the internal /api/models/list,
+which touches no filesystem, ran in 13-34ms. The catalog scan was already cached
+for 30s, but the per-entry servability check (stat many files plus a config.json
+read for every model) was re-run on every request. It is now keyed on the catalog
+stamp, the same way _validated_media_picks is, so a catalog rescan is the only
+thing that invalidates it and nothing can go stale behind a second TTL.
+
+Residency must stay per request: it changes on every load/unload.
+"""
+
+from types import SimpleNamespace
+
+import pytest
+
+import routes.inference as inf
+
+
[email protected](autouse = True)
+def _clean_cache():
+ inf._SERVABLE_SCAN_CACHE["entry"] = None
+ yield
+ inf._SERVABLE_SCAN_CACHE["entry"] = None
+
+
+def _catalog(n = 3):
+ return [SimpleNamespace(id = f"repo/m{i}", path = f"/models/m{i}", task = None) for i in range(n)]
+
+
+def _stub(monkeypatch):
+ """Count servability resolutions and make residency observable."""
+ counts = {"servable": 0, "resident": 0}
+
+ def _servable(info):
+ counts["servable"] += 1
+ return (True, ("Q4_K_M",))
+
+ monkeypatch.setattr("core.inference.local_model_resolver.local_servable_model", _servable)
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+
+ def _resident(key, **kw):
+ counts["resident"] += 1
+ return False
+
+ monkeypatch.setattr(inf, "_resolves_to_resident", _resident)
+ return counts
+
+
+def test_same_catalog_stamp_scans_once(_stub):
+ catalog = _catalog(3)
+ for _ in range(10):
+ inf._servable_catalog_rows(catalog, 111.0)
+ assert _stub["servable"] == 3, "one scan for three entries, not one per call"
+
+
+def test_residency_is_recomputed_every_call(_stub):
+ catalog = _catalog(3)
+ for _ in range(10):
+ inf._servable_catalog_rows(catalog, 111.0)
+ # Residency changes on load/unload, so it must never ride the cache.
+ assert _stub["resident"] == 30
+
+
+def test_new_catalog_stamp_rescans(_stub):
+ catalog = _catalog(2)
+ inf._servable_catalog_rows(catalog, 111.0)
+ assert _stub["servable"] == 2
+ inf._servable_catalog_rows(catalog, 222.0)
+ assert _stub["servable"] == 4, "a replaced catalog must be rescanned"
+
+
+def test_no_stamp_disables_caching(_stub):
+ # Direct callers that pass no stamp keep the original uncached behaviour.
+ catalog = _catalog(2)
+ inf._servable_catalog_rows(catalog)
+ inf._servable_catalog_rows(catalog)
+ assert _stub["servable"] == 4
+
+
+def test_rows_shape_is_unchanged(_stub):
+ rows = inf._servable_catalog_rows(_catalog(1), 111.0)
+ assert len(rows) == 1
+ info, is_gguf, quants, resident = rows[0]
+ assert info.id == "repo/m0"
+ assert is_gguf is True
+ assert quants == ("Q4_K_M",)
+ assert resident is False
+
+
+def test_unservable_entries_are_dropped(monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model", lambda info: None
+ )
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+ assert inf._servable_catalog_rows(_catalog(3), 111.0) == []
diff --git a/studio/backend/tests/test_openai_models_servable_cache_edges.py b/studio/backend/tests/test_openai_models_servable_cache_edges.py
new file mode 100644
index 00000000000..c31efd9e085
--- /dev/null
+++ b/studio/backend/tests/test_openai_models_servable_cache_edges.py
@@ -0,0 +1,545 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Simulation suite: edge cases for the /v1/models servability cache.
+
+The cache sits on a request path that several clients poll, so it has to be correct
+under concurrency, correct when the catalog is replaced, and must never let a stale
+residency answer through. A wrong answer here is worse than the latency it saves:
+it would advertise a model the server cannot serve, or hide one it can.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+import time
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
+if _BACKEND_DIR not in sys.path:
+ sys.path.insert(0, _BACKEND_DIR)
+
+import routes.inference as inf # noqa: E402
+
+
[email protected](autouse = True)
+def _clean_cache():
+ def _reset():
+ inf._SERVABLE_SCAN_CACHE["entry"] = None
+
+ _reset()
+ yield
+ _reset()
+
+
+def _catalog(n = 3, tag = "m"):
+ return [
+ SimpleNamespace(id = f"repo/{tag}{i}", path = f"/models/{tag}{i}", task = None) for i in range(n)
+ ]
+
+
+def stub(monkeypatch):
+ counts = {"servable": 0, "resident": 0}
+
+ def _servable(info):
+ counts["servable"] += 1
+ return (True, ("Q4_K_M",))
+
+ monkeypatch.setattr("core.inference.local_model_resolver.local_servable_model", _servable)
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+
+ def _resident(key, **kw):
+ counts["resident"] += 1
+ return False
+
+ monkeypatch.setattr(inf, "_resolves_to_resident", _resident)
+ return counts
+
+
+def test_concurrent_callers_do_not_corrupt_the_cache(stub):
+ catalog = _catalog(5)
+ results: list[int] = []
+ errors: list[BaseException] = []
+ barrier = threading.Barrier(16)
+
+ def _go():
+ try:
+ barrier.wait()
+ for _ in range(20):
+ rows = inf._servable_catalog_rows(catalog, 111.0)
+ results.append(len(rows))
+ except BaseException as exc: # noqa: BLE001
+ errors.append(exc)
+
+ threads = [threading.Thread(target = _go) for _ in range(16)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join(timeout = 60)
+ assert not errors, f"concurrent access raised: {errors}"
+ assert set(results) == {5}, "every caller must see the whole catalog"
+
+
+def test_a_replaced_catalog_is_never_served_from_the_old_entry(stub):
+ first, second = _catalog(2, "a"), _catalog(3, "b")
+ rows = inf._servable_catalog_rows(first, 111.0)
+ assert [r[0].id for r in rows] == ["repo/a0", "repo/a1"]
+ # Same stamp, different catalog object: identity must defeat the stamp.
+ rows = inf._servable_catalog_rows(second, 111.0)
+ assert [r[0].id for r in rows] == ["repo/b0", "repo/b1", "repo/b2"]
+
+
+def test_the_zero_stamp_of_a_fresh_process_does_not_pin_the_cache(stub):
+ # _CATALOG_CACHE["at"] starts at 0.0 and only advances inside
+ # _cached_local_catalog. A caller that supplies a catalog from anywhere else
+ # keeps that 0.0, so the stamp alone cannot be trusted.
+ first, second = _catalog(1, "a"), _catalog(1, "b")
+ assert inf._servable_catalog_rows(first, 0.0)[0][0].id == "repo/a0"
+ assert inf._servable_catalog_rows(second, 0.0)[0][0].id == "repo/b0"
+
+
+def test_residency_is_never_cached(stub):
+ catalog = _catalog(2)
+ for _ in range(10):
+ inf._servable_catalog_rows(catalog, 111.0)
+ assert stub["servable"] == 2, "the scan is cached"
+ assert stub["resident"] == 20, "residency is not"
+
+
+def test_residency_flips_are_visible_immediately(monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (True, ()),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ flag = {"resident": False}
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: flag["resident"])
+
+ catalog = _catalog(1)
+ assert inf._servable_catalog_rows(catalog, 111.0)[0][3] is False
+ flag["resident"] = True # a /load happened
+ assert inf._servable_catalog_rows(catalog, 111.0)[0][3] is True
+
+
+def test_an_empty_catalog_is_cached_without_confusing_a_miss(stub):
+ assert inf._servable_catalog_rows([], 111.0) == []
+ assert inf._servable_catalog_rows([], 111.0) == []
+ assert stub["servable"] == 0
+
+
+def test_no_stamp_never_populates_the_cache(stub):
+ catalog = _catalog(2)
+ inf._servable_catalog_rows(catalog)
+ assert inf._SERVABLE_SCAN_CACHE["entry"] is None
+ inf._servable_catalog_rows(catalog)
+ assert stub["servable"] == 4
+
+
+def test_media_and_stt_tasks_stay_excluded(monkeypatch):
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (True, ()),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+ catalog = [
+ SimpleNamespace(id = "repo/text", path = "/m/text", task = None),
+ SimpleNamespace(id = "repo/stt", path = "/m/stt", task = inf._STT_MODEL_TASK),
+ SimpleNamespace(id = "repo/tts", path = "/m/tts", task = inf._TTS_MODEL_TASK),
+ ]
+ rows = inf._servable_catalog_rows(catalog, 111.0)
+ assert [r[0].id for r in rows] == ["repo/text"]
+
+
+def test_a_raising_resolver_is_not_cached_as_an_empty_catalog(monkeypatch):
+ # If the scan blows up, the failure must propagate rather than silently
+ # caching "this server can serve nothing" for the life of the catalog.
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (_ for _ in ()).throw(RuntimeError("scan failed")),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+ with pytest.raises(RuntimeError):
+ inf._servable_catalog_rows(_catalog(1), 111.0)
+ assert inf._SERVABLE_SCAN_CACHE["entry"] is None, "a failed scan must not be cached"
+
+
+def test_the_cache_entry_is_published_atomically(stub):
+ # The fast path reads without the lock. Separate fields could be caught
+ # half-replaced: old stamp and old catalog still matching while rows already held
+ # the next catalog's rows, so an in-flight request got another catalog's models.
+ first, second = _catalog(2, "a"), _catalog(3, "b")
+ inf._servable_catalog_rows(first, 111.0)
+ entry = inf._SERVABLE_SCAN_CACHE["entry"]
+ assert entry is not None and len(entry) == 5, "the tuple must be one object"
+ at, cached, generation, _scanned_at, rows = entry
+ assert at == 111.0 and cached is first and len(rows) == 2
+ assert isinstance(generation, tuple) and len(generation) == 3
+
+ inf._servable_catalog_rows(second, 222.0)
+ at, cached, _generation, _at2, rows = inf._SERVABLE_SCAN_CACHE["entry"]
+ assert (at, cached is second, len(rows)) == (
+ 222.0,
+ True,
+ 3,
+ ), "stamp, catalog, generation and rows move together"
+
+
+def test_residency_resolves_the_current_snapshot_each_call(monkeypatch):
+ # A non-GGUF HF repo path resolves to a snapshot dir. A download can move that
+ # pointer inside the catalog's 30s lifetime, and caching the resolved dir would
+ # report a freshly loaded model as unloaded until the catalog expired.
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (False, ()), # non-GGUF, so residency goes through local_load_dir
+ )
+ snapshot = {"dir": "/models/m0/snapshots/old"}
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_load_dir", lambda p: snapshot["dir"]
+ )
+ seen: list[str] = []
+
+ def _resident(key, **kw):
+ seen.append(key)
+ return key == "/models/m0/snapshots/new"
+
+ monkeypatch.setattr(inf, "_resolves_to_resident", _resident)
+
+ catalog = _catalog(1)
+ assert inf._servable_catalog_rows(catalog, 111.0)[0][3] is False
+ snapshot["dir"] = "/models/m0/snapshots/new" # a download moved the pointer
+ assert (
+ inf._servable_catalog_rows(catalog, 111.0)[0][3] is True
+ ), "the snapshot must be re-resolved per call, not cached with the scan"
+ assert seen == ["/models/m0/snapshots/old", "/models/m0/snapshots/new"]
+
+
+def test_large_catalog_stays_correct(stub):
+ catalog = _catalog(500)
+ rows = inf._servable_catalog_rows(catalog, 111.0)
+ assert len(rows) == 500
+ assert stub["servable"] == 500
+ rows = inf._servable_catalog_rows(catalog, 111.0)
+ assert len(rows) == 500
+ assert stub["servable"] == 500, "second call must be free"
+
+
+# ------------------------------------------------------- deletion during the catalog TTL
+
+
+def test_a_deleted_model_leaves_the_listing_within_the_catalog_ttl(monkeypatch):
+ """A delete invalidates the resolver, not _CATALOG_CACHE, so the catalog behind this
+ cache can stay standing for the rest of its 30s TTL. Keying on the resolver
+ generation is what stops the removed model being advertised for that window, which
+ the per-request scan used to drop at once."""
+ from core.inference import local_model_resolver as resolver
+
+ catalog = _catalog(2, "d")
+ gone: set[str] = set()
+
+ def _servable(info):
+ return None if info.path in gone else (True, ("Q4_K_M",))
+
+ monkeypatch.setattr("core.inference.local_model_resolver.local_servable_model", _servable)
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ assert [r[0].id for r in inf._servable_catalog_rows(catalog, 111.0)] == ["repo/d0", "repo/d1"]
+ gone.add("/models/d1")
+ # Same catalog, same stamp: without the generation this still answers from the cache.
+ resolver.invalidate_index()
+ assert [r[0].id for r in inf._servable_catalog_rows(catalog, 111.0)] == ["repo/d0"]
+
+
+def test_an_additions_only_invalidation_also_refreshes_the_scan(monkeypatch):
+ """A finished download invalidates additions-only, and a new quant must appear
+ without waiting out the catalog TTL."""
+ from core.inference import local_model_resolver as resolver
+
+ catalog = _catalog(1, "q")
+ quants = {"/models/q0": ("Q4_K_M",)}
+
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (True, quants[info.path]),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ assert inf._servable_catalog_rows(catalog, 222.0)[0][2] == ("Q4_K_M",)
+ quants["/models/q0"] = ("Q8_0", "Q4_K_M")
+ resolver.invalidate_index(additions_only = True)
+ assert inf._servable_catalog_rows(catalog, 222.0)[0][2] == ("Q8_0", "Q4_K_M")
+
+
+def test_an_invalidation_during_a_scan_is_not_stamped_in(monkeypatch):
+ """The generation is read before the scan, so an invalidation that lands while the
+ scan runs makes the stored entry stale rather than being cached as already seen."""
+ from core.inference import local_model_resolver as resolver
+
+ catalog = _catalog(1, "r")
+ state = {"racing": True}
+
+ def _servable(info):
+ if state["racing"]:
+ state["racing"] = False
+ resolver.invalidate_index()
+ return (True, ("Q4_K_M",))
+
+ monkeypatch.setattr("core.inference.local_model_resolver.local_servable_model", _servable)
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ inf._servable_catalog_rows(catalog, 333.0)
+ entry = inf._SERVABLE_SCAN_CACHE["entry"]
+ assert entry is not None
+ assert entry[2] != resolver.index_generation(), "the racing scan must not read as fresh"
+
+
+def test_the_generation_only_moves_on_invalidation(monkeypatch):
+ """A quiet process must still get the cache: if the generation drifted on its own,
+ every request would rescan and the fix would undo the performance work."""
+ from core.inference import local_model_resolver as resolver
+
+ before = resolver.index_generation()
+ catalog = _catalog(3, "s")
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (True, ("Q4_K_M",)),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ calls = {"n": 0}
+
+ def _resident(key, **kw):
+ calls["n"] += 1
+ return False
+
+ monkeypatch.setattr(inf, "_resolves_to_resident", _resident)
+ for _ in range(5):
+ inf._servable_catalog_rows(catalog, 444.0)
+ assert resolver.index_generation() == before
+ # Residency is deliberately per call; the scan behind it ran once.
+ assert calls["n"] == 15
+
+
+# ----------------------------------------------- every signal servability depends on
+
+
+def test_a_hub_cache_deletion_leaves_the_listing(monkeypatch):
+ """deletion.py invalidates the HF cache scans and nothing else, so the resolver
+ generation alone would keep advertising a deleted cached repo for the catalog TTL."""
+ from hub.utils import inventory_scan
+
+ catalog = _catalog(2, "h")
+ gone: set[str] = set()
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: None if info.path in gone else (True, ("Q4_K_M",)),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ assert len(inf._servable_catalog_rows(catalog, 555.0)) == 2
+ gone.add("/models/h1")
+ inventory_scan.invalidate_hf_cache_scans()
+ assert [r[0].id for r in inf._servable_catalog_rows(catalog, 555.0)] == ["repo/h0"]
+
+
+def test_a_hardware_redetect_reveals_newly_servable_checkpoints(monkeypatch):
+ """local_servable_model decides non-GGUF servability from hardware.DEVICE. An Apple
+ Silicon MLX self-repair flips CPU to MLX after startup, so an early /v1/models must
+ not pin 'unservable' for the rest of the catalog TTL."""
+ from utils.hardware import hardware as hw
+
+ catalog = _catalog(1, "k")
+ servable = {"ok": False}
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: (False, ()) if servable["ok"] else None,
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ assert inf._servable_catalog_rows(catalog, 666.0) == []
+ servable["ok"] = True
+ monkeypatch.setattr(hw, "DETECTION_GENERATION", hw.DETECTION_GENERATION + 1)
+ assert len(inf._servable_catalog_rows(catalog, 666.0)) == 1
+
+
+def test_the_generation_key_names_all_three_signals():
+ """A missing counter would silently pin the key and undo the invalidation, so the
+ shape is asserted rather than left to the two behavioural tests above."""
+ from core.inference.local_model_resolver import index_generation
+ from hub.utils.inventory_scan import hf_cache_scans_epoch
+ from utils.hardware import hardware as hw
+
+ assert inf._servability_generation() == (
+ index_generation(),
+ int(hf_cache_scans_epoch()),
+ int(hw.DETECTION_GENERATION),
+ )
+
+
+def test_every_delete_branch_invalidates_the_scan():
+ """An outputs/exports directory can be a registered scan folder, so a model deleted
+ through delete_finetuned_model may be one /v1/models is advertising. Both successful
+ branches count: deleting a single GGUF variant returns earlier than the full-model
+ delete, and only the later one was covered at first."""
+ import inspect
+
+ from routes import models as models_route
+
+ lines = inspect.getsource(models_route.delete_finetuned_model).split("\n")
+ # The variant branch returns a multi-line dict, so match the status rather than a
+ # one-line prefix; a mid-function `return {` with no status is an error path.
+ successes = [
+ n
+ for n, line in enumerate(lines)
+ if '"status": "deleted"' in line or '"deleted"' in line and "status" in line
+ ]
+ invalidations = [n for n, line in enumerate(lines) if "_invalidate_local_scans()" in line]
+ assert len(successes) == 2, f"expected two success returns, found {len(successes)}"
+ assert (
+ len(invalidations) == 2
+ ), f"expected one invalidation per success branch, found {len(invalidations)}"
+ for at in successes:
+ before = [n for n in invalidations if n < at]
+ assert before, "a successful deletion branch reports success without invalidating"
+ # Belongs to THIS branch: nothing else returns between the two.
+ assert not [
+ n for n in successes if before[-1] < n < at
+ ], "the invalidation must belong to this branch, not to one above it"
+
+
+def test_a_generation_bump_while_waiting_for_the_lock_is_not_accepted(monkeypatch):
+ """Two callers miss together, one scans while the other queues on the lock, and a
+ delete lands during that scan. The scanner stamps its entry with the generation it
+ STARTED with, which is correct, so a waiter comparing against the value it captured
+ before queueing would be handed rows examined before the delete."""
+ from core.inference import local_model_resolver as resolver
+
+ catalog = _catalog(1, "w")
+ scanned = {"n": 0}
+
+ def _servable(info):
+ scanned["n"] += 1
+ return (True, ("Q4_K_M",))
+
+ monkeypatch.setattr("core.inference.local_model_resolver.local_servable_model", _servable)
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ generation_at_queue = inf._servability_generation()
+ stale_rows = [("scanned-before-the-delete",)]
+
+ class _LockThatLosesTheRace:
+ """Stands in for the wait: the other scanner publishes and a delete lands here."""
+
+ def __enter__(self):
+ inf._SERVABLE_SCAN_CACHE["entry"] = (
+ 777.0,
+ catalog,
+ generation_at_queue,
+ time.monotonic(),
+ stale_rows,
+ )
+ resolver.invalidate_index()
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ monkeypatch.setattr(inf, "_SERVABLE_SCAN_CACHE_LOCK", _LockThatLosesTheRace())
+ rows = inf._servable_catalog_rows(catalog, 777.0)
+ assert rows != stale_rows, "the waiter accepted rows scanned before the delete"
+ assert scanned["n"] > 0, "it must have rescanned rather than reused the entry"
+
+
+def test_the_invalidation_helper_stays_off_the_event_loop():
+ """invalidate_index takes the resolver lock and _index() holds it across a full
+ multi-root filesystem scan, so an async route calling it inline would stall unrelated
+ requests and in-flight inference streams behind a rebuild."""
+ import asyncio as _asyncio
+ import inspect
+
+ from routes import models as models_route
+
+ assert _asyncio.iscoroutinefunction(models_route._invalidate_local_scans)
+ source = inspect.getsource(models_route._invalidate_local_scans)
+ assert (
+ "asyncio.to_thread(invalidate_index)" in source
+ ), "the invalidation must be offloaded, matching the other async sites in this file"
+ # And every call site must await it, or the coroutine is created and dropped.
+ route = inspect.getsource(models_route.delete_finetuned_model)
+ calls = route.count("_invalidate_local_scans()")
+ awaited = route.count("await _invalidate_local_scans()")
+ assert calls == awaited == 2, f"{calls} call(s), {awaited} awaited"
+
+
+def test_a_hit_is_rejected_when_the_generation_moves_mid_read(monkeypatch):
+ """Seqlock: generation, entry, generation. A delete completing between the first two
+ reads was accepted anyway, and the lock-free path is where most requests land."""
+ from core.inference import local_model_resolver as resolver
+
+ catalog = _catalog(1, "s")
+ scanned = {"n": 0}
+
+ def _servable(info):
+ scanned["n"] += 1
+ return (True, ("Q4_K_M",))
+
+ monkeypatch.setattr("core.inference.local_model_resolver.local_servable_model", _servable)
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ real = inf._servability_generation
+ entry_generation = real()
+ inf._SERVABLE_SCAN_CACHE["entry"] = (
+ 888.0,
+ catalog,
+ entry_generation,
+ time.monotonic(),
+ [("stale",)],
+ )
+ calls = {"n": 0}
+
+ def _moves_after_the_first_read():
+ # The entry read sits between the two generation reads. The delete lands there.
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return entry_generation
+ resolver.invalidate_index()
+ return real()
+
+ monkeypatch.setattr(inf, "_servability_generation", _moves_after_the_first_read)
+ rows = inf._servable_catalog_rows(catalog, 888.0)
+ assert rows != [("stale",)], "a delete completing mid-read must not be served"
+ assert scanned["n"] > 0, "the request must fall through to a real scan"
+
+
+def test_an_out_of_band_file_change_is_picked_up_within_the_scan_ttl(monkeypatch):
+ """No counter moves when a file is removed from a scan folder by hand, and the
+ per-request scan used to notice immediately. The entry's own TTL bounds that."""
+ catalog = _catalog(2, "o")
+ gone: set[str] = set()
+ monkeypatch.setattr(
+ "core.inference.local_model_resolver.local_servable_model",
+ lambda info: None if info.path in gone else (True, ("Q4_K_M",)),
+ )
+ monkeypatch.setattr("core.inference.local_model_resolver.local_load_dir", lambda p: p)
+ monkeypatch.setattr(inf, "_resolves_to_resident", lambda key, **kw: False)
+
+ clock = {"t": 1000.0}
+ monkeypatch.setattr(inf.time, "monotonic", lambda: clock["t"])
+
+ assert len(inf._servable_catalog_rows(catalog, 999.0)) == 2
+ gone.add("/models/o1") # rm, outside every instrumented path
+ assert len(inf._servable_catalog_rows(catalog, 999.0)) == 2, "still inside the TTL"
+ clock["t"] += inf._SERVABLE_SCAN_TTL_S + 0.1
+ assert [r[0].id for r in inf._servable_catalog_rows(catalog, 999.0)] == ["repo/o0"]