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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: fix delayed chat streaming for already-loaded GGUFs (#8371)
oobabooga0e488c211bc9
diff --git a/studio/backend/core/inference/local_model_resolver.py b/studio/backend/core/inference/local_model_resolver.pyindex 4b680098d07..3503c20a79d 100644--- a/studio/backend/core/inference/local_model_resolver.py+++ b/studio/backend/core/inference/local_model_resolver.py@@ -32,6 +32,9 @@ class _LocalGgufEntry:_CACHE_TTL_S = 5.0+# Monotonic timestamps are nonnegative, so a negative stamp encodes "additions-only+# invalidated at -stamp". Keeps that trust inside the atomically published _scan+# tuple instead of a second global, and keeps it time-bounded like any other._lock = threading.Lock()_scan: tuple[float, dict[str, _LocalGgufEntry]] = (0.0, {})# Not _lock: that is held for the whole scan, so the request path would wait on it.@@ -40,6 +43,10 @@ _warm_lock = threading.Lock()# else covers them until the next scan, and the request path must not call them absent._just_downloaded: set[str] = set()_warming = False+# An invalidation landing while a warmer owns the slot asks it for another pass, so+# a snapshot published already-stale is rebuilt off the request path. Callers still+# pair invalidate_index() with warm_index_soon() for the case where it has retired.+_warm_pending = False_last_scan_s = 0.0# Rescan at most a tenth of the time: on the TTL alone a slow scan would run continuously._WARM_DUTY = 10.0@@ -341,19 +348,43 @@ def recently_downloaded(repo_id: str) -> bool:return repo_id.strip().lower() in _just_downloaded-def invalidate_index() -> None:- """Mark the cached scan stale so the next resolve sees a just-finished download- instead of waiting out the TTL.+def _snapshot_is_trusted(timestamp: float, now: float) -> bool:+ """Whether a snapshot stamped *timestamp* may answer a model switch at *now*.- Keeps the entries: the request path reads this cache without scanning, so- emptying it would leave it with no evidence about any local model until the- rebuild lands, and a bare request for one would be answered by whatever is- resident. Only a completed download invalidates, and that only adds, so the- retained entries stay true.+ Positive is an ordinary scan, trusted for the TTL. Negative is when an+ additions-only download invalidated it, trusted only while its rebuild could+ still be running: one that keeps failing must not leave entries trusted forever,+ or a model deleted on disk could still trigger a switch. Zero is revoked."""- global _scan+ if timestamp > 0.0:+ return now - timestamp < _CACHE_TTL_S+ if timestamp < 0.0:+ return now + timestamp < max(_CACHE_TTL_S, _last_scan_s * _WARM_DUTY)+ return False+++def invalidate_index(*, additions_only: bool = False) -> None:+ """Mark the cached scan stale.++ Entries stay available so an additions-only download invalidation can keep+ serving known positive hits while its background rebuild adds the new model.+ 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_pendingwith _lock:- _scan = (0.0, _scan[1])+ now = time.monotonic()+ 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+ # fresh timestamp paired with already-revoked trust.+ stamp = -now if additions_only and _snapshot_is_trusted(timestamp, now) else 0.0+ _scan = (stamp, retained)+ # This may have waited out a scan on _lock, so the warmer that just published can+ # still own the slot with a snapshot that is stale again. See _warm_pending.+ with _warm_lock:+ if _warming:+ _warm_pending = Truedef _index() -> dict[str, _LocalGgufEntry]:@@ -363,7 +394,9 @@ def _index() -> dict[str, _LocalGgufEntry]:with _lock:now = time.monotonic()ts, cached = _scan- if now - ts < _CACHE_TTL_S:+ # ``ts > 0``: monotonic() counts from boot, so under a TTL of uptime an+ # invalidated stamp reads as recent and would serve what was just revoked.+ if ts > 0.0 and now - ts < _CACHE_TTL_S:return cachedfresh = _build_index()# Stamp AFTER the scan, not with the pre-scan ``now``: a multi-root scan on@@ -382,7 +415,24 @@ def index_is_built() -> bool:park the request path on the scan it is trying to stay off. Safe because``_scan`` is only ever rebound, never mutated."""- return bool(_scan[0])+ return _scan[0] > 0.0+++def resolve_trusted_cached_local_gguf(requested: str) -> Optional[tuple[str, Optional[str], str]]:+ """Resolve a positive cache hit only when its snapshot is safe to trust.++ A snapshot is trustworthy while fresh, or after an explicit additions-only+ invalidation. A positive hit from ordinary TTL expiry or a scan-root change+ must be rebuilt before it can trigger a model switch. The identity checks close+ the race where invalidation publishes a different snapshot during resolution or+ while the trust state is being evaluated.+ """+ snapshot = _scan+ resolved = _resolve_from_index(requested, snapshot[1])+ if resolved is None or _scan is not snapshot:+ return None+ trusted = _snapshot_is_trusted(snapshot[0], time.monotonic())+ return resolved if trusted and _scan is snapshot else Nonedef warm_index_soon() -> None:@@ -393,25 +443,39 @@ def warm_index_soon() -> None:scan folder has no invalidation hook and would otherwise stay invisible to themfor the life of the process. Never blocks, and never touches ``_lock``."""- global _warming- if time.monotonic() - _scan[0] < max(_CACHE_TTL_S, _last_scan_s * _WARM_DUTY):+ global _warming, _warm_pending+ stamp = _scan[0]+ if stamp > 0.0 and time.monotonic() - stamp < max(_CACHE_TTL_S, _last_scan_s * _WARM_DUTY):returnwith _warm_lock:if _warming:return_warming = True+ _warm_pending = Falsedef _run() -> None:- global _warming, _last_scan_s- started = time.monotonic()+ global _warming, _warm_pending, _last_scan_s+ released = Falsetry:- _index()- except Exception:- pass+ while True:+ started = time.monotonic()+ try:+ _index()+ except Exception:+ pass+ _last_scan_s = time.monotonic() - started+ with _warm_lock:+ if _warm_pending:+ _warm_pending = False+ continue+ _warming, released = False, True+ returnfinally:- _last_scan_s = time.monotonic() - started- with _warm_lock:- _warming = False+ # Only on a BaseException: leaving the slot held would kill background+ # warming for the life of the process and put scans back on requests.+ if not released:+ with _warm_lock:+ _warming = _warm_pending = Falsethreading.Thread(target = _run, name = "local-model-index-warm", daemon = True).start()@@ -428,16 +492,27 @@ def resolve_local_gguf(off and resolves only when that quant is on disk, unless it names no quant atall (an Ollama-style ":latest"), which means the repo.- ``allow_scan=False`` answers from the last built index and never rebuilds, for- the request path: the scan walks several model dirs and HF caches, takes seconds- on a large install, and holds a lock everyone queues behind. Stale is fine there,- since disk barely moves and a finished download calls :func:`invalidate_index`.+ ``allow_scan=False`` answers from the last built index and never rebuilds. It is+ a raw snapshot read for callers that separately decide whether the snapshot is+ trustworthy; use :func:`resolve_trusted_cached_local_gguf` for model switching."""if not isinstance(requested, str) or not requested.strip():return Nonerequested = requested.strip()try:index = _index() if allow_scan else _scan[1]+ return _resolve_from_index(requested, index)+ except Exception:+ # Best-effort: any resolver failure falls through to the loaded model,+ # so a malformed name can never turn a servable request into a 500.+ return None+++def _resolve_from_index(+ requested: str, index: dict[str, _LocalGgufEntry]+) -> Optional[tuple[str, Optional[str], str]]:+ """Resolve *requested* against one immutable published index mapping."""+ try:entry = index.get(requested.lower())if entry is not None:variant = entry.variants[0] if entry.variants else None@@ -461,8 +536,6 @@ def resolve_local_gguf(# is not on disk still misses, or a swap would serve the wrong weights.return entry.load_path, (entry.variants[0] if entry.variants else None), entry.loader_idexcept Exception:- # Best-effort: any resolver failure falls through to the loaded model,- # so a malformed name can never turn a servable request into a 500.return Nonediff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex f549002012c..5dc4b0763ab 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -337,7 +337,7 @@ def finalize_worker_exit()note_downloaded(repo_id)- invalidate_index()+ invalidate_index(additions_only = True)# Rebuild here, not on the first request, to keep the scan off the# request path.warm_index_soon()diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.pyindex 8a6a0d76b5f..6a123ec8a34 100644--- a/studio/backend/hub/services/models/local_inventory.py+++ b/studio/backend/hub/services/models/local_inventory.py@@ -19,7 +19,7 @@ from loggers import get_loggerfrom hub.schemas.inventory import LocalModelInfo, LocalModelListResponse, ModelFormatfrom hub.storage.scan_folders import (- add_scan_folder,+ add_scan_folder_with_status,list_scan_folders,remove_scan_folder,)@@ -1013,15 +1013,24 @@ def get_scan_folders_response() -> dict:def add_scan_folder_response(path: str) -> dict:try:- folder = add_scan_folder(_coerce_scan_folder_path(path))+ folder, inserted = add_scan_folder_with_status(_coerce_scan_folder_path(path))except ValueError as e:logger.warning("Scan folder rejected: %s (path=%s)", e, path)raise HTTPException(status_code = 400, detail = str(e))logger.info("Scan folder added: %s", folder.get("path"))+ if inserted:+ from core.inference.local_model_resolver import invalidate_index, warm_index_soon+ invalidate_index()+ warm_index_soon()return folderdef remove_scan_folder_response(folder_id: int) -> dict:- remove_scan_folder(folder_id)- logger.info("Scan folder removed: id=%s", folder_id)+ removed = remove_scan_folder(folder_id)+ if removed:+ logger.info("Scan folder removed: id=%s", folder_id)+ from core.inference.local_model_resolver import invalidate_index, warm_index_soon++ invalidate_index()+ warm_index_soon()return {"ok": True}diff --git a/studio/backend/hub/storage/scan_folders.py b/studio/backend/hub/storage/scan_folders.pyindex 81623d27591..a88317662ec 100644--- a/studio/backend/hub/storage/scan_folders.py+++ b/studio/backend/hub/storage/scan_folders.py@@ -115,8 +115,8 @@ def list_scan_folders() -> list[dict]:conn.close()-def add_scan_folder(path: str) -> dict:- """Add a readable directory for the local OS user; not a multi-user sandbox."""+def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:+ """Add a readable scan folder and return its row plus whether it was inserted."""if not path or not path.strip():raise ValueError("Path cannot be empty")normalized = os.path.realpath(os.path.expanduser(normalize_path(path.strip())))@@ -157,13 +157,15 @@ def add_scan_folder(path: str) -> dict:(normalized,),).fetchone()if existing is not None:- return dict(existing)+ return dict(existing), False+ inserted = Falsetry:conn.execute("INSERT INTO scan_folders (path, created_at) VALUES (?, ?)",(normalized, now),)conn.commit()+ inserted = Trueexcept sqlite3.IntegrityError:passfallback_sql = (@@ -174,19 +176,26 @@ def add_scan_folder(path: str) -> dict:row = conn.execute(fallback_sql, (normalized,)).fetchone()if row is None:raise ValueError("Folder was concurrently removed")- return dict(row)+ return dict(row), insertedfinally:conn.close()-def remove_scan_folder(id: int) -> None:+def add_scan_folder(path: str) -> dict:+ """Add a readable directory for the local OS user; not a multi-user sandbox."""+ row, _ = add_scan_folder_with_status(path)+ return row+++def remove_scan_folder(id: int) -> bool:# sqlite INTEGER is signed 64-bit; ids outside that range cannot exist.if not -(2**63) <= id < 2**63:- return+ return Falseconn = get_connection()try:_ensure_schema(conn)- conn.execute("DELETE FROM scan_folders WHERE id = ?", (id,))+ cursor = conn.execute("DELETE FROM scan_folders WHERE id = ?", (id,))conn.commit()+ return cursor.rowcount > 0finally:conn.close()diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex 76252b67d5a..5ec4b94dc62 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -179,7 +179,7 @@ async def get_export_status(current_subject: str = Depends(get_current_subject))# does, so the success banner shows an identical path on either route.last_op_output_path = Noneif last_op and last_op.get("output_path"):- details = _export_details(last_op["output_path"])+ details = await asyncio.to_thread(_export_details, last_op["output_path"])last_op_output_path = (details or {}).get("output_path")return ExportStatusResponse(current_checkpoint = backend.current_checkpoint,@@ -254,18 +254,27 @@ async def get_export_logs()-def _try_register_external_export(path: Path) -> tuple[bool, Optional[str]]:+def _try_register_external_export(+ path: Path, *, refresh_index: bool = False+) -> tuple[bool, Optional[str]]:"""Best-effort registration so absolute exports show up in local scans."""try:- from storage.studio_db import add_scan_folder- folder = add_scan_folder(str(path))+ from storage.studio_db import add_scan_folder_with_status++ folder, inserted = add_scan_folder_with_status(str(path))+ if inserted or refresh_index:+ from core.inference.local_model_resolver import invalidate_index, warm_index_soon+ invalidate_index()+ warm_index_soon()return True, str(folder.get("path") or path)except Exception as exc:logger.warning("Could not register export scan folder %s: %s", path, exc)return False, None-def _export_details(output_path: Optional[str]) -> Optional[Dict[str, Any]]:+def _export_details(+ output_path: Optional[str], *, refresh_index: bool = False+) -> Optional[Dict[str, Any]]:"""Return relative export paths, keeping external absolute paths visible."""if not output_path:return None@@ -279,7 +288,9 @@ def _export_details(output_path: Optional[str]) -> Optional[Dict[str, Any]]:try:path.resolve().relative_to(exports_root().resolve())except ValueError:- registered, registered_path = _try_register_external_export(path)+ registered, registered_path = _try_register_external_export(+ path, refresh_index = refresh_index+ )return {"output_path": str(path),"scan_folder_registered": registered,@@ -319,7 +330,7 @@ async def export_merged_model(return ExportOperationResponse(success = True,message = message,- details = _export_details(output_path),+ details = await asyncio.to_thread(_export_details, output_path, refresh_index = True),)except HTTPException:raise@@ -363,7 +374,7 @@ async def export_base_model(return ExportOperationResponse(success = True,message = message,- details = _export_details(output_path),+ details = await asyncio.to_thread(_export_details, output_path, refresh_index = True),)except HTTPException:raise@@ -409,7 +420,7 @@ async def export_gguf(return ExportOperationResponse(success = True,message = message,- details = _export_details(output_path),+ details = await asyncio.to_thread(_export_details, output_path, refresh_index = True),)except HTTPException:raise@@ -454,7 +465,7 @@ async def export_lora_adapter(return ExportOperationResponse(success = True,message = message,- details = _export_details(output_path),+ details = await asyncio.to_thread(_export_details, output_path, refresh_index = True),)except HTTPException:raisediff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 495ff1be5b9..06e6fa69eef 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -4750,6 +4750,33 @@ def _loaded_satisfies(requested: str) -> bool:return _matches_any(base, [active, public_model_id(active)])+def _loaded_identity_satisfies(requested: str) -> bool:+ """Whether an explicit resident identity answers to *requested*.++ Unlike :func:`_loaded_satisfies`, this excludes a public id derived from a+ filesystem path, so a request naming that alias still passes through the+ resolver and the serving backend records it for responses and ``/v1/models``.+ A request naming the load path itself is held back until that recording has+ happened, for the same reason.+ """+ from core.inference.openai_auto_download import split_model_ref++ base, _ = split_model_ref(requested)+ llama_backend = get_llama_cpp_backend()+ if getattr(llama_backend, "is_loaded", False):+ identifier = getattr(llama_backend, "model_identifier", None)+ advertised = getattr(llama_backend, "_openai_advertised_id", None)+ # A manual load of a local path advertises nothing, so only the path could match+ # and answering from it would skip the recording: /v1/models and every response+ # would report the filename. One request pays the resolver, the rest match the+ # alias it recorded and land here.+ if advertised is None and identifier and _looks_like_local_path(identifier):+ return False+ return _matches_any(base, (identifier, advertised)) and _loaded_satisfies(requested)+ active = getattr(get_inference_backend(), "active_model_name", None)+ return bool(active and _matches_any(base, [active]) and _loaded_satisfies(requested))++def _raise_still_indexing(requested_model: str, fastapi_request) -> None:"""Refuse a name we cannot yet place, rather than answer it with another model."""path = getattr(getattr(fastapi_request, "url", None), "path", None)@@ -5021,7 +5048,11 @@ async def _maybe_auto_switch_model(idle_unload_is_configured,model_override_load_kwargs,)- from core.inference.local_model_resolver import resolve_local_gguf+ from core.inference.local_model_resolver import (+ resolve_local_gguf,+ resolve_trusted_cached_local_gguf,+ warm_index_soon,+ )from core.inference.llama_keepwarm import (get_last_unloaded_model,inference_lifecycle_gate,@@ -5048,16 +5079,29 @@ async def _maybe_auto_switch_model(await _reject_unservable_model(requested_model, fastapi_request)return+ # The common Studio path names the model that is already serving. Resolve that+ # from resident state before consulting the filesystem index: rebuilding a stale+ # multi-root index here used to hold the request for seconds before streaming.+ if auto_switch_on and await asyncio.to_thread(_loaded_identity_satisfies, requested_model):+ warm_index_soon()+ return+async def _resolve_and_switch() -> None:# Off the loop: a cold-cache rebuild walks several model dirs + HF caches.# With auto-switch off (or an omitted-model reload-only request), skip the# resolve so only the reload-stash path runs and no name is ever matched.reload_only = requested_model == _RELOAD_ONLY_MODEL- resolved = (- await asyncio.to_thread(resolve_local_gguf, requested_model)- if auto_switch_on and not reload_only- else None- )+ resolved = None+ if auto_switch_on and not reload_only:+ # Fresh hits and entries retained across an additions-only download are+ # safe to use immediately. An expired/config-invalidated hit, a cold+ # cache, and every miss must refresh before an unrelated resident model+ # can answer or an entry from a removed scan root can trigger a switch.+ resolved = resolve_trusted_cached_local_gguf(requested_model)+ if resolved is not None:+ warm_index_soon()+ else:+ resolved = await asyncio.to_thread(resolve_local_gguf, requested_model)if resolved is None:# Not on disk. Opt-in: fetch in the background and ask the caller to retry.if auto_switch_on and not reload_only:diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.pyindex 027c7cfe27c..e578889cc6a 100644--- a/studio/backend/routes/models.py+++ b/studio/backend/routes/models.py@@ -1213,16 +1213,20 @@ async def add_scan_folder_endpoint(body: AddScanFolderRequest, current_subject: str = Depends(get_current_subject)):"""Register a new directory to scan for local models."""- from storage.studio_db import add_scan_folder+ from storage.studio_db import add_scan_folder_with_statustry:- folder = add_scan_folder(body.path)+ folder, inserted = await asyncio.to_thread(add_scan_folder_with_status, body.path)except ValueError as e:logger.warning("Scan folder rejected: %s (path=%s)", e, body.path)# Forward the curated, path-free validation message.rejection_message = str(e)raise HTTPException(status_code = 400, detail = rejection_message)logger.info("Scan folder added: %s", folder.get("path"))+ if inserted:+ from core.inference.local_model_resolver import invalidate_index, warm_index_soon+ await asyncio.to_thread(invalidate_index)+ warm_index_soon()return folder@@ -1233,8 +1237,13 @@ async def remove_scan_folder_endpoint("""Remove a registered custom scan folder."""from storage.studio_db import remove_scan_folder- remove_scan_folder(folder_id)- logger.info("Scan folder removed: id=%s", folder_id)+ removed = await asyncio.to_thread(remove_scan_folder, folder_id)+ if removed:+ logger.info("Scan folder removed: id=%s", folder_id)+ from core.inference.local_model_resolver import invalidate_index, warm_index_soon++ await asyncio.to_thread(invalidate_index)+ warm_index_soon()return {"ok": True}diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex a83f7d1bf2a..bcf59124544 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -1508,8 +1508,8 @@ def list_scan_folders() -> list[dict]:conn.close()-def add_scan_folder(path: str) -> dict:- """Add a directory to the custom scan folder list. Returns the row."""+def add_scan_folder_with_status(path: str) -> tuple[dict, bool]:+ """Add a custom scan folder and return its row plus whether it was inserted."""if not path or not path.strip():raise ValueError("Path cannot be empty")normalized = os.path.realpath(os.path.expanduser(path.strip()))@@ -1553,13 +1553,15 @@ def add_scan_folder(path: str) -> dict:(normalized,),).fetchone()if existing is not None:- return dict(existing)+ return dict(existing), False+ inserted = Falsetry:conn.execute("INSERT INTO scan_folders (path, created_at) VALUES (?, ?)",(normalized, now),)conn.commit()+ inserted = Trueexcept sqlite3.IntegrityError:pass # duplicate; fall through to SELECT# Same collation as the pre-check to catch concurrent writes (Windows).@@ -1571,16 +1573,23 @@ def add_scan_folder(path: str) -> dict:row = conn.execute(fallback_sql, (normalized,)).fetchone()if row is None:raise ValueError("Folder was concurrently removed")- return dict(row)+ return dict(row), insertedfinally:conn.close()-def remove_scan_folder(id: int) -> None:+def add_scan_folder(path: str) -> dict:+ """Add a directory to the custom scan folder list. Returns the row."""+ row, _ = add_scan_folder_with_status(path)+ return row+++def remove_scan_folder(id: int) -> bool:conn = get_connection()try:- conn.execute("DELETE FROM scan_folders WHERE id = ?", (id,))+ cursor = conn.execute("DELETE FROM scan_folders WHERE id = ?", (id,))conn.commit()+ return cursor.rowcount > 0finally:conn.close()diff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.pyindex 1687ffcfccc..3d7899ace70 100644--- a/studio/backend/tests/test_export_absolute_paths.py+++ b/studio/backend/tests/test_export_absolute_paths.py@@ -712,7 +712,7 @@ def test_export_details_registers_external_absolute_output(tmp_path, monkeypatchmonkeypatch.setattr(export_route,"_try_register_external_export",- lambda path: (registered.append(path) is None, str(path)),+ lambda path, **_kwargs: (registered.append(path) is None, str(path)),)monkeypatch.setattr("utils.paths.storage_roots.exports_root",@@ -729,6 +729,42 @@ def test_export_details_registers_external_absolute_output(tmp_path, monkeypatchassert registered == [output]+def test_recovered_external_export_invalidates_only_when_first_registered(tmp_path, monkeypatch):+ _install_lightweight_backend_stubs(monkeypatch)+ export_route = _load_module(+ "test_routes_export_registration_invalidation",+ "routes/export.py",+ monkeypatch,+ )+ output = tmp_path / "Gemma4_26B_gguf"+ output.mkdir()+ insertions = iter((True, False, False))+ invalidations = []+ warms = []++ storage_pkg = types.ModuleType("storage")+ studio_db = types.ModuleType("storage.studio_db")+ studio_db.add_scan_folder_with_status = lambda path: (+ {"id": 1, "path": path, "created_at": "fake"},+ next(insertions),+ )+ resolver = types.ModuleType("core.inference.local_model_resolver")+ resolver.invalidate_index = lambda: invalidations.append(1)+ resolver.warm_index_soon = lambda: warms.append(1)+ monkeypatch.setitem(sys.modules, "storage", storage_pkg)+ monkeypatch.setitem(sys.modules, "storage.studio_db", studio_db)+ monkeypatch.setitem(sys.modules, "core.inference.local_model_resolver", resolver)++ assert export_route._try_register_external_export(output) == (True, str(output))+ assert export_route._try_register_external_export(output) == (True, str(output))+ assert export_route._try_register_external_export(output, refresh_index = True) == (+ True,+ str(output),+ )+ assert invalidations == [1, 1]+ assert warms == [1, 1]++def test_export_details_does_not_register_contained_exports(tmp_path, monkeypatch):_install_lightweight_backend_stubs(monkeypatch)export_route = _load_module(diff --git a/studio/backend/tests/test_openai_auto_download.py b/studio/backend/tests/test_openai_auto_download.pyindex 2b12418d74b..94d6292c76d 100644--- a/studio/backend/tests/test_openai_auto_download.py+++ b/studio/backend/tests/test_openai_auto_download.py@@ -1448,6 +1448,65 @@ def test_warming_the_index_never_waits_on_the_scan_lock(monkeypatch):assert elapsed < 0.5, f"request path blocked on the warm scan for {elapsed:.2f}s"+def test_invalidation_during_a_warm_preserves_a_second_scan(monkeypatch):+ import threading+ import time as _time++ from core.inference import local_model_resolver as resolver++ first_scan_started = threading.Event()+ release_first_scan = threading.Event()+ invalidation_finished = threading.Event()+ second_scan_finished = threading.Event()+ scans = []++ def _index():+ scans.append(1)+ if len(scans) == 1:+ # Match the real _index(): keep invalidation blocked until this pass+ # publishes, then keep the worker alive until invalidation has marked+ # the just-published snapshot stale.+ with resolver._lock:+ first_scan_started.set()+ assert release_first_scan.wait(5)+ resolver._scan = (_time.monotonic(), {})+ assert invalidation_finished.wait(5)+ else:+ second_scan_finished.set()+ return {}++ monkeypatch.setattr(resolver, "_scan", (0.0, {}))+ monkeypatch.setattr(resolver, "_warming", False)+ monkeypatch.setattr(resolver, "_warm_pending", False)+ monkeypatch.setattr(resolver, "_last_scan_s", 0.0)+ monkeypatch.setattr(resolver, "_index", _index)++ _real_warm_index_soon()+ assert first_scan_started.wait(5)++ def _invalidate_and_warm():+ resolver.invalidate_index()+ _real_warm_index_soon()+ invalidation_finished.set()++ invalidator = threading.Thread(target = _invalidate_and_warm)+ invalidator.start()+ release_first_scan.set()+ invalidator.join(timeout = 5)++ try:+ assert not invalidator.is_alive()+ assert second_scan_finished.wait(5)+ assert scans == [1, 1]+ finally:+ release_first_scan.set()+ invalidation_finished.set()+ for _ in range(500):+ if not resolver._warming:+ break+ _time.sleep(0.01)++def test_a_stale_index_is_refreshed_so_a_hub_download_becomes_visible(monkeypatch):# Only the auto-download watcher calls invalidate_index, so a Hub UI download is seen# only if the warm can run again.diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.pyindex e9ea88b2101..b9d13a69499 100644--- a/studio/backend/tests/test_openai_auto_switch.py+++ b/studio/backend/tests/test_openai_auto_switch.py@@ -11,6 +11,8 @@ import asyncioimport jsonimport osimport threading+import time+import typesimport pytestfrom fastapi import HTTPException@@ -186,6 +188,151 @@ def test_known_unloaded_model_switches_once(monkeypatch):assert backend.model_identifier == "unsloth/B-GGUF"+def test_resident_model_skips_the_filesystem_resolver(monkeypatch):+ backend = _FakeBackend("unsloth/Muse-Glimmer-30B-GGUF", "UD-Q4_K_XL")+ rec = _LoadRecorder(backend)+ _wire(monkeypatch, enabled = True, resolves_to = None, backend = backend, recorder = rec)+ warmed = []+ monkeypatch.setattr(resolver, "warm_index_soon", lambda: warmed.append(1))++ def _unexpected_resolve(*_args, **_kwargs):+ raise AssertionError("the resident model must not touch the filesystem index")++ monkeypatch.setattr(resolver, "resolve_local_gguf", _unexpected_resolve)+ _run_hook("unsloth/Muse-Glimmer-30B-GGUF")+ assert rec.calls == []+ assert warmed == [1]+++def test_auto_switch_reads_an_additions_only_snapshot_without_rebuilding_it(monkeypatch):+ real_resolve = resolver.resolve_local_gguf+ backend = _FakeBackend("unsloth/A-GGUF", "Q4_K_M")+ rec = _LoadRecorder(backend)+ _wire(monkeypatch, enabled = True, resolves_to = None, backend = backend, recorder = rec)+ calls = []+ warmed = []++ entry = resolver._LocalGgufEntry("unsloth/B-GGUF", "/models/unsloth/B-GGUF", ("Q4_K_M",))+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"unsloth/b-gguf": entry}))+ resolver.invalidate_index(additions_only = True)+ assert resolver._scan[0] < 0.0 # additions-only: the time of the invalidation+ assert resolver.index_is_built() is False++ def _resolve(name, **kwargs):+ calls.append((name, kwargs))+ return real_resolve(name, **kwargs)++ monkeypatch.setattr(resolver, "warm_index_soon", lambda: warmed.append(1))+ monkeypatch.setattr(resolver, "resolve_local_gguf", _resolve)++ async def _accept_loaded_target(*_args, **_kwargs):+ assert backend.model_identifier == "/models/unsloth/B-GGUF"+ assert backend._openai_advertised_id == "unsloth/B-GGUF"++ monkeypatch.setattr(inference_route, "_reject_unservable_model", _accept_loaded_target)++ _run_hook("unsloth/B-GGUF:Q4_K_M")++ assert calls == []+ assert warmed == [1]+ assert len(rec.calls) == 1+++def test_non_additive_invalidation_keeps_unservable_check_cold(monkeypatch):+ from types import SimpleNamespace++ real_resolve = resolver.resolve_local_gguf+ backend = _FakeBackend("unsloth/A-GGUF", "Q4_K_M")+ rec = _LoadRecorder(backend)+ _wire(monkeypatch, enabled = False, resolves_to = None, backend = backend, recorder = rec)+ monkeypatch.setattr(resolver, "resolve_local_gguf", real_resolve)+ monkeypatch.setattr(+ inference_route,+ "get_inference_backend",+ lambda: SimpleNamespace(active_model_name = None),+ )++ old = resolver._LocalGgufEntry("unsloth/A-GGUF", "/models/unsloth/A-GGUF", ("Q4_K_M",))+ added = resolver._LocalGgufEntry("unsloth/B-GGUF", "/models/unsloth/B-GGUF", ("Q4_K_M",))+ resolver._scan = (time.monotonic(), {"unsloth/a-gguf": old})+ resolver.invalidate_index()+ assert resolver.index_is_built() is False+ monkeypatch.setattr(+ resolver,+ "_build_index",+ lambda: {"unsloth/a-gguf": old, "unsloth/b-gguf": added},+ )++ with pytest.raises(HTTPException) as excinfo:+ _run_hook("unsloth/B-GGUF")++ assert excinfo.value.status_code == 404+ assert "Switch model by request" in str(excinfo.value.detail)+ assert rec.calls == []+++def test_an_expired_positive_hit_refreshes_before_switching(monkeypatch):+ real_resolve = resolver.resolve_local_gguf+ backend = _FakeBackend("unsloth/A-GGUF", "Q4_K_M")+ rec = _LoadRecorder(backend)+ _wire(monkeypatch, enabled = True, resolves_to = None, backend = backend, recorder = rec)+ removed = resolver._LocalGgufEntry(+ "unsloth/B-GGUF", "/removed-root/unsloth/B-GGUF", ("Q4_K_M",)+ )+ monkeypatch.setattr(resolver, "_scan", (1.0, {"unsloth/b-gguf": removed}))+ scans = []+ calls = []+ monkeypatch.setattr(resolver, "_build_index", lambda: scans.append(1) or {})++ def _resolve(name, **kwargs):+ calls.append((name, kwargs))+ return real_resolve(name, **kwargs)++ monkeypatch.setattr(resolver, "resolve_local_gguf", _resolve)++ _run_hook("unsloth/B-GGUF")++ assert calls == [("unsloth/B-GGUF", {}), ("unsloth/B-GGUF", {"allow_scan": False})]+ assert scans == [1]+ assert rec.calls == []+ assert backend.model_identifier == "unsloth/A-GGUF"+++def test_a_stale_miss_refreshes_before_the_resident_model_can_answer(monkeypatch):+ real_resolve = resolver.resolve_local_gguf+ backend = _FakeBackend("unsloth/A-GGUF", "Q4_K_M")+ rec = _LoadRecorder(backend)+ _wire(monkeypatch, enabled = True, resolves_to = None, backend = backend, recorder = rec)+ old = resolver._LocalGgufEntry("unsloth/A-GGUF", "/models/unsloth/A-GGUF", ("Q4_K_M",))+ added = resolver._LocalGgufEntry("unsloth/B-GGUF", "/models/unsloth/B-GGUF", ("Q4_K_M",))+ monkeypatch.setattr(resolver, "_scan", (1.0, {"unsloth/a-gguf": old}))+ scans = []+ calls = []+ monkeypatch.setattr(+ resolver,+ "_build_index",+ lambda: scans.append(1) or {"unsloth/a-gguf": old, "unsloth/b-gguf": added},+ )++ def _resolve(name, **kwargs):+ calls.append((name, kwargs))+ return real_resolve(name, **kwargs)++ monkeypatch.setattr(resolver, "resolve_local_gguf", _resolve)++ async def _accept_loaded_target(*_args, **_kwargs):+ assert backend.model_identifier == "/models/unsloth/B-GGUF"+ assert backend._openai_advertised_id == "unsloth/B-GGUF"++ monkeypatch.setattr(inference_route, "_reject_unservable_model", _accept_loaded_target)++ _run_hook("unsloth/B-GGUF")++ assert calls == [("unsloth/B-GGUF", {})]+ assert scans == [1]+ assert len(rec.calls) == 1++def test_concurrent_same_target_loads_once(monkeypatch):backend = _FakeBackend(None)rec = _LoadRecorder(backend)@@ -1617,6 +1764,32 @@ def test_already_serving_by_path_records_advertised_alias(monkeypatch):assert backend._openai_advertised_id == "org/Repo-GGUF" # alias now recorded+def test_already_serving_requested_by_path_records_advertised_alias(monkeypatch):+ # The resident short circuit matches on model_identifier, which is the load path+ # for a manual local load. Answering from it skips the alias recording above, so a+ # loose .gguf whose scanner alias is not its filename would be advertised, and+ # reported in every response, as the filename instead.+ path = "/models/lmstudio/TheBloke/weights-file-01.gguf"+ backend = _FakeBackend(path) # loaded by path, no advertised id+ rec = _LoadRecorder(backend)+ _wire(+ monkeypatch,+ enabled = True,+ resolves_to = (path, None, "Qwen3-4B-Instruct-GGUF"),+ backend = backend,+ recorder = rec,+ )+ _run_hook(path)+ assert rec.calls == [] # already serving -> no reload+ assert backend._openai_advertised_id == "Qwen3-4B-Instruct-GGUF"+ assert inference_route._llama_public_model_id(backend) == "Qwen3-4B-Instruct-GGUF"+ # Recorded, so the path now short circuits without the resolver.+ monkeypatch.setattr(+ resolver, "resolve_local_gguf", lambda _m, **_kw: pytest.fail("resolver re-entered")+ )+ _run_hook(path)++def test_streaming_responses_uses_advertised_id_helper():# Codex P2: streamed /v1/responses envelopes must derive the model id from# _llama_public_model_id (which prefers _openai_advertised_id), not the raw@@ -6272,7 +6445,7 @@ def test_any_finished_download_drops_the_resolver_cache(monkeypatch):def set_job(self, key, state):self.state = state- resolver._scan = (1234.0, {"already-here": "entry"})+ resolver._scan = (time.monotonic(), {"already-here": "entry"})assert (download_lifecycle.finalize_worker_exit(_Registry(),@@ -6288,7 +6461,7 @@ def test_any_finished_download_drops_the_resolver_cache(monkeypatch):== "complete")stamp, entries = resolver._scan- assert stamp == 0.0, "a finished download left the scan looking fresh"+ assert stamp < 0.0 and resolver._snapshot_is_trusted(stamp, time.monotonic())# Evidence for models already indexed has to survive, or a bare request for one# of them during the rebuild is answered by whatever is resident.assert entries == {"already-here": "entry"}@@ -6298,8 +6471,6 @@ def test_invalidating_keeps_the_entries_it_already_had(monkeypatch):# The request path reads this cache without scanning, so emptying it leaves no# evidence until the rebuild lands. Only a completed download invalidates, and# that only adds, so the entries stay true.- import time-entry = resolver._LocalGgufEntry("org/old", "/srv/models/org--old", ("Q4_K_M",))monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"org/old": entry}))resolver.invalidate_index()@@ -6309,6 +6480,147 @@ def test_invalidating_keeps_the_entries_it_already_had(monkeypatch):"Q4_K_M","org/old",)+ assert resolver.resolve_trusted_cached_local_gguf("org/old") is None+++def test_trusted_cache_rechecks_snapshot_after_freshness(monkeypatch):+ entry = resolver._LocalGgufEntry("org/old", "/custom/org--old", ("Q4_K_M",))+ snapshot = (time.monotonic(), {"org/old": entry})+ monkeypatch.setattr(resolver, "_scan", snapshot)+ invalidated = False++ def _invalidate_while_deciding_trust():+ nonlocal invalidated+ if not invalidated:+ invalidated = True+ resolver.invalidate_index()+ return snapshot[0]++ monkeypatch.setattr(resolver.time, "monotonic", _invalidate_while_deciding_trust)++ assert resolver.resolve_trusted_cached_local_gguf("org/old") is None+++def test_async_scan_folder_routes_offload_storage_and_invalidation(monkeypatch):+ from types import SimpleNamespace++ import routes.models as model_routes++ event_loop_thread = threading.get_ident()+ calls = []++ def _add(path):+ calls.append(("add", threading.get_ident()))+ return {"id": 7, "path": path, "created_at": "fake"}, True++ def _remove(folder_id):+ calls.append((f"remove:{folder_id}", threading.get_ident()))+ return True++ def _invalidate():+ calls.append(("invalidate", threading.get_ident()))++ monkeypatch.setattr("storage.studio_db.add_scan_folder_with_status", _add)+ monkeypatch.setattr("storage.studio_db.remove_scan_folder", _remove)+ monkeypatch.setattr(resolver, "invalidate_index", _invalidate)+ monkeypatch.setattr(resolver, "warm_index_soon", lambda: None)++ async def _run():+ folder = await model_routes.add_scan_folder_endpoint(+ SimpleNamespace(path = "/models/custom"), current_subject = "tester"+ )+ removed = await model_routes.remove_scan_folder_endpoint(7, current_subject = "tester")+ return folder, removed++ folder, removed = asyncio.run(_run())++ assert folder["path"] == "/models/custom"+ assert removed == {"ok": True}+ assert [name for name, _ in calls] == ["add", "invalidate", "remove:7", "invalidate"]+ assert all(thread_id != event_loop_thread for _, thread_id in calls)+++def test_scan_folder_removal_revokes_additions_only_cache_trust(monkeypatch):+ import routes.models as model_routes+ from hub.services.models import local_inventory++ entry = resolver._LocalGgufEntry("org/old", "/custom/org--old", ("Q4_K_M",))+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"org/old": entry}))+ removed = []+ warmed = []++ def _remove(folder_id):+ removed.append(folder_id)+ return True++ monkeypatch.setattr(resolver, "warm_index_soon", lambda: warmed.append(1))+ monkeypatch.setattr("storage.studio_db.remove_scan_folder", _remove)+ monkeypatch.setattr(local_inventory, "remove_scan_folder", _remove)++ resolver._scan = (time.monotonic(), {"org/old": entry})+ resolver.invalidate_index(additions_only = True)+ assert resolver.resolve_trusted_cached_local_gguf("org/old") is not None+ asyncio.run(model_routes.remove_scan_folder_endpoint(7, current_subject = "tester"))+ assert resolver.resolve_trusted_cached_local_gguf("org/old") is None++ resolver._scan = (time.monotonic(), {"org/old": entry})+ resolver.invalidate_index(additions_only = True)+ assert resolver.resolve_trusted_cached_local_gguf("org/old") is not None+ assert local_inventory.remove_scan_folder_response(8) == {"ok": True}+ assert resolver.resolve_trusted_cached_local_gguf("org/old") is None+ assert removed == [7, 8]+ assert warmed == [1, 1]+++def test_scan_folder_storage_removals_report_if_a_row_changed(monkeypatch):+ from types import SimpleNamespace++ from hub.storage import scan_folders+ from storage import studio_db++ class _Connection:+ def __init__(self, rowcount):+ self.rowcount = rowcount+ self.committed = False+ self.closed = False++ def execute(self, _sql, _params):+ return SimpleNamespace(rowcount = self.rowcount)++ def commit(self):+ self.committed = True++ def close(self):+ self.closed = True++ monkeypatch.setattr(scan_folders, "_ensure_schema", lambda _conn: None)+ for storage in (studio_db, scan_folders):+ for rowcount, expected in ((1, True), (0, False)):+ connection = _Connection(rowcount)+ monkeypatch.setattr(storage, "get_connection", lambda connection = connection: connection)++ assert storage.remove_scan_folder(7) is expected+ assert connection.committed+ assert connection.closed+++def test_noop_scan_folder_removals_do_not_invalidate_the_index(monkeypatch):+ import routes.models as model_routes+ from hub.services.models import local_inventory++ invalidated = []+ warmed = []+ monkeypatch.setattr(resolver, "invalidate_index", lambda: invalidated.append(1))+ monkeypatch.setattr(resolver, "warm_index_soon", lambda: warmed.append(1))+ monkeypatch.setattr("storage.studio_db.remove_scan_folder", lambda _folder_id: False)+ monkeypatch.setattr(local_inventory, "remove_scan_folder", lambda _folder_id: False)++ assert asyncio.run(model_routes.remove_scan_folder_endpoint(404, current_subject = "tester")) == {+ "ok": True+ }+ assert local_inventory.remove_scan_folder_response(404) == {"ok": True}+ assert invalidated == []+ assert warmed == []def test_a_bare_local_id_takes_the_quant_a_plain_load_would(monkeypatch, tmp_path):@@ -7095,3 +7407,120 @@ def test_api_only_turned_on_mid_save_still_spares_the_model(monkeypatch, tmp_patassert backend.is_loaded is Trueassert deleted == [manifest] # nothing was unloaded, so nothing may be stashedassert kw._kv_resume is None+++def _age_resolver_clock(monkeypatch, seconds):+ """Advance the resolver's monotonic clock by *seconds*.++ Ageing a snapshot by rewriting its stamp assumes the host has been up longer+ than the age; a fresh CI runner has not, and the subtraction flips the sign.+ """+ base = time.monotonic()+ monkeypatch.setattr(resolver, "time", types.SimpleNamespace(monotonic = lambda: base + seconds))+++def test_additions_only_trust_expires_if_the_rebuild_never_lands(monkeypatch):+ # A background rebuild that keeps failing must not leave the retained entries+ # trusted forever: a model deleted on disk would still trigger a switch.+ entry = resolver._LocalGgufEntry("org/a", "/srv/models/org--a", ("Q4_K_M",))+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"org/a": entry}))+ monkeypatch.setattr(resolver, "_last_scan_s", 0.0)+ resolver.invalidate_index(additions_only = True)+ assert resolver.resolve_trusted_cached_local_gguf("org/a") is not None+ _age_resolver_clock(monkeypatch, 600.0)+ assert resolver.resolve_trusted_cached_local_gguf("org/a") is None+++def test_additions_only_trust_outlasts_a_scan_slower_than_the_ttl(monkeypatch):+ # The window tracks the rebuild's own cost, so the install this fix targets (a+ # multi-second multi-root scan) is not pushed back onto the request path.+ entry = resolver._LocalGgufEntry("org/a", "/srv/models/org--a", ("Q4_K_M",))+ monkeypatch.setattr(resolver, "_scan", (time.monotonic(), {"org/a": entry}))+ monkeypatch.setattr(resolver, "_last_scan_s", 16.0)+ resolver.invalidate_index(additions_only = True)+ _age_resolver_clock(monkeypatch, resolver._CACHE_TTL_S * 4)+ assert resolver.resolve_trusted_cached_local_gguf("org/a") is not None+++def test_a_dead_warm_worker_releases_the_slot(monkeypatch):+ # BaseException out of the scan used to leave _warming set, killing background+ # warming for the life of the process and putting scans back on requests.+ monkeypatch.setattr(resolver, "_scan", (0.0, {}))+ monkeypatch.setattr(resolver, "_warming", False)+ monkeypatch.setattr(resolver, "_warm_pending", False)+ monkeypatch.setattr(resolver, "_last_scan_s", 0.0)++ def _die():+ raise KeyboardInterrupt++ monkeypatch.setattr(resolver, "_build_index", _die)+ resolver.warm_index_soon()+ for _ in range(100):+ if not resolver._warming:+ break+ time.sleep(0.05)+ assert resolver._warming is False+ assert resolver._warm_pending is False+++def test_an_invalidated_index_rebuilds_on_a_host_that_just_booted(monkeypatch):+ # monotonic() counts from boot, so on a host whose uptime is still under the+ # TTL an invalidated stamp used to read as recent and serve what was revoked.+ # Patch the module's reference, not the real time module: a stray warm thread+ # shares that one, and a frozen global clock hangs its duty-cycle arithmetic.+ monkeypatch.setattr(resolver, "time", types.SimpleNamespace(monotonic = lambda: 1.0))+ for kwargs in ({}, {"additions_only": True}):+ monkeypatch.setattr(resolver, "_scan", (1.0, {"org/a": "entry"}))+ resolver.invalidate_index(**kwargs)+ built = []+ monkeypatch.setattr(resolver, "_build_index", lambda: (built.append(1), {})[1])+ resolver._index()+ assert built == [1], kwargs+++# The resident short circuit is the one path that answers without consulting the+# index, so it must never say yes where the pre-existing resident check says no.+# Anything it accepts, main would have accepted too: a miss only costs the scan.+_IDENTITIES = [+ "unsloth/Muse-GGUF",+ "/srv/models/unsloth--Muse-GGUF",+ "/srv/models/Muse.gguf",+ None,+]+_REQUESTS = [+ "unsloth/Muse-GGUF",+ "unsloth/muse-gguf",+ "unsloth/Muse-GGUF:Q4_K_M",+ "unsloth/Muse-GGUF:Q8_0",+ "unsloth/Muse-GGUF:latest",+ "unsloth/Other-GGUF",+ "/srv/models/Muse.gguf",+ "/srv/models/MUSE.gguf",+ "muse.gguf",+ "../../etc/passwd",+ "unsloth/",+ ":Q4_K_M",+ "unsloth/Muse GGUF",+]++[email protected]("identity", _IDENTITIES)[email protected]("requested", _REQUESTS)[email protected]("quant", [None, "Q4_K_M"])+def test_the_resident_shortcut_never_answers_where_the_full_check_would_not(+ monkeypatch, identity, requested, quant+):+ backend = _FakeBackend(identity, hf_variant = quant) if identity else _FakeBackend(None)+ backend.is_loaded = identity is not None+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)+ fast = inference_route._loaded_identity_satisfies(requested)+ assert not (+ fast and not inference_route._loaded_satisfies(requested)+ ), f"shortcut served {requested!r} against {identity!r} (quant={quant!r})"+++def test_the_resident_shortcut_refuses_an_explicit_quant_mismatch(monkeypatch):+ backend = _FakeBackend("unsloth/Muse-GGUF", hf_variant = "Q4_K_M")+ monkeypatch.setattr(inference_route, "get_llama_cpp_backend", lambda: backend)+ assert inference_route._loaded_identity_satisfies("unsloth/Muse-GGUF:Q8_0") is False+ assert inference_route._loaded_identity_satisfies("unsloth/Muse-GGUF:Q4_K_M") is True