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: stop an unreachable Hugging Face endpoint from stalling the backend (#8799)
Long Yixingca7c83fafd8f
diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex 9acdbbcb8e1..dbe22b7782a 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -206,6 +206,110 @@ class LlamaServerBackend:return str(sorted(match, key = lambda f: len(f.name))[0])return None+ @staticmethod+ def _pick_gguf(+ names,+ *,+ key = None,+ require_variant = False,+ ):+ """GGUF pick from `names`, by variant then shortest name; `key` reads the comparable+ name off each entry.++ `require_variant` refuses the fallback to another variant. Falling back on a hub+ listing means the variant is not published; falling back on a cache would serve+ whatever happened to be fetched under an earlier setting."""+ from utils.models.model_config import _is_mtp_drafter++ name_of = key or (lambda n: n)+ usable = [+ n+ for n in names+ if name_of(n).lower().endswith(".gguf")+ and "mmproj" not in name_of(n).lower()+ # A drafter is a companion, never a model in its own right, so it must be+ # excluded everywhere mmproj is. A cache holding only the companion would+ # otherwise be read as holding the embedder.+ and not _is_mtp_drafter(name_of(n))+ ]+ if not usable:+ return None+ variant = config.EMBED_GGUF_VARIANT.lower()+ match = [n for n in usable if variant in name_of(n).lower()]+ if not match:+ if require_variant:+ return None+ match = usable+ # Name breaks a length tie: a directory scan yields no guaranteed order, and among+ # equal-length shard names that would otherwise decide which shard is picked.+ return sorted(match, key = lambda n: (len(name_of(n)), name_of(n)))[0]++ @staticmethod+ def _cached_snapshot_dir(repo_id: str) -> Path | None:+ """The snapshot ``refs/main`` names in the active hub cache, or None.++ Only that revision, because it is the one hf_hub_download serves; the remaining+ snapshot directories are commit hashes, which order by nothing, so choosing among+ them could serve a superseded model.++ A hit therefore pins the embedder to the cached revision until the cache itself+ changes. Deliberate: a stored embedding identity records no revision, so adopting+ republished weights would leave an index answering one model's queries with another+ model's documents."""+ from utils.hf_cache_settings import active_hf_hub_cache+ from utils.paths import resolve_cached_repo_id_case++ # A repo id typed with different casing than the cache folder is still that repo;+ # missing it here would re-download, or fail outright with the hub unreachable.+ cased = resolve_cached_repo_id_case(repo_id)+ repo_dir = Path(active_hf_hub_cache()) / f"models--{cased.replace('/', '--')}"+ try:+ rev = (repo_dir / "refs" / "main").read_text(encoding = "utf-8").strip()+ except (OSError, ValueError):+ return None # not cached here, unreadable, or pinned to a commit+ # A ref file holds a bare commit hash; a separator would join out of the cache.+ if not rev or rev in (".", "..") or "/" in rev or "\\" in rev:+ return None+ snapshot = repo_dir / "snapshots" / rev+ return snapshot if snapshot.is_dir() else None++ @staticmethod+ def _resolve_cached_gguf(repo_id: str, *, require_variant: bool = True) -> str | None:+ """The GGUF this repo already has on disk, found without the network.++ ``_model_path`` is per-process, so without this every restart re-lists the repo to+ name a file it already holds -- unbounded on a host whose route to the hub+ blackholes."""+ from utils.models.model_config import colocated_split_shards++ snapshot = LlamaServerBackend._cached_snapshot_dir(repo_id)+ if snapshot is None:+ return None+ try:+ # Not a "*.gguf" glob: that is case-sensitive, and quant-per-directory layouts+ # put the file a level down, both of which the hub listing handles.+ files = [p for p in snapshot.rglob("*") if p.is_file()]+ except OSError:+ return None+ # llama-server opens sibling shards implicitly, so a split set is servable only when+ # it is whole. An unservable winner is dropped and the pick retried rather than+ # failing the lookup, or an incomplete family would shadow a complete one simply by+ # sorting ahead of it. Verified per winner, not per file: a plain file is a complete+ # one-file set, and a whole-cache filter would walk siblings for every shard present.+ while files:+ pick = LlamaServerBackend._pick_gguf(+ files,+ key = lambda p: p.relative_to(snapshot).as_posix(),+ require_variant = require_variant,+ )+ # exists() guards only the window since the scan; is_file() dropped evicted blobs.+ if pick is None or not pick.exists():+ return None+ if colocated_split_shards(pick)[1]:+ return str(pick)+ files = [p for p in files if p != pick]+ return None+def _resolve_model_path(self) -> str:"""Download (or cache-hit) the variant-matching, non-mmproj GGUF embedder,returning its local path. Re-resolves when the effective repo changed (a@@ -218,13 +322,7 @@ class LlamaServerBackend:return self._model_pathlocal = self._resolve_local_gguf(config.effective_embedding_model())if local is not None:- self._model_path = local- self._model_repo = desired- self._dim = None- return self._model_path- from huggingface_hub import hf_hub_download, list_repo_files-- token = os.environ.get("HF_TOKEN") or None+ return self._adopt_model_path(local, desired)# A custom model derives its "-GGUF" companion repo; when that guess does# not exist, the model repo itself may host the .gguf files.repo = desired@@ -232,40 +330,82 @@ class LlamaServerBackend:model = config.effective_embedding_model()if model != repo:candidates.append(model)- files: list[str] = []- errors: list[str] = []- for candidate in candidates:- try:- files = [- f- for f in list_repo_files(candidate, token = token)- if f.lower().endswith(".gguf") and "mmproj" not in f.lower()- ]- except Exception as e: # noqa: BLE001 - missing/gated repo -> next candidate- errors.append(f"{candidate!r}: {e}")- continue- if files:- repo = candidate- break- errors.append(f"{candidate!r}: no .gguf files")- if not files:- raise RuntimeError("no .gguf embedder found; tried " + "; ".join(errors))- variant = config.EMBED_GGUF_VARIANT.lower()- match = [f for f in files if variant in f.lower()] or files- filename = sorted(match, key = len)[0]- logger.info("resolving GGUF embedder %s/%s", repo, filename)- from utils.hf_cache_settings import active_hf_hub_cache+ # Only the preferred repo. A file cached under the fallback candidate must not+ # pre-empt a companion repo the hub can still resolve, which is the order the+ # listing follows; offline, the relaxed pass below still reaches both.+ cached = self._resolve_cached_gguf(desired)+ if cached is not None:+ return self._adopt_model_path(cached, desired)+ return self._resolve_uncached_model_path(desired, candidates)- self._model_path = hf_hub_download(- repo_id = repo,- filename = filename,- token = token,- cache_dir = active_hf_hub_cache(),- )+ def _adopt_model_path(self, path: str, desired: str) -> str:+ """Serve `path` for `desired`; the width is re-probed against whatever is adopted."""+ self._model_path = pathself._model_repo = desiredself._dim = Nonereturn self._model_path+ # A listing, not a transfer: a working hub answers well inside a second.+ _LIST_DEADLINE_S = 20.0++ def _resolve_uncached_model_path(self, desired: str, candidates: list[str]) -> str:+ """Resolve the GGUF the local cache could not answer for.++ The listing needs the deadline because nothing else caps it: `list_repo_files` takes+ no timeout, and the pagination layer passes an explicit `timeout=None` that overrides+ any client-level default. The guard covers the transfer only by refusing to start one+ against an endpoint already known to be unreachable; once begun it is bounded per+ read, so a blob host that stalls mid-download still holds the lock."""+ from huggingface_hub import hf_hub_download, list_repo_files+ from core.inference.llama_cpp import _hf_offline_if_unreachable+ from utils.utils import call_with_deadline++ token = os.environ.get("HF_TOKEN") or None+ repo = desired+ filename: str | None = None+ errors: list[str] = []+ with _hf_offline_if_unreachable():+ for candidate in candidates:+ try:+ names = call_with_deadline(+ lambda c = candidate: list_repo_files(c, token = token),+ self._LIST_DEADLINE_S,+ name = "embed-gguf-listing",+ )+ filename = self._pick_gguf(names)+ except Exception as e: # noqa: BLE001 - missing/gated/stalled -> next candidate+ errors.append(f"{candidate!r}: {e}")+ continue+ if filename is not None:+ repo = candidate+ break+ errors.append(f"{candidate!r}: no .gguf files")+ if filename is None:+ # Any cached GGUF now beats no embedder. Only where the hub failed to NAME+ # one: a transfer failing on its own (no disk, bad checksum) must surface.+ for candidate in candidates:+ cached = self._resolve_cached_gguf(candidate, require_variant = False)+ if cached is not None:+ logger.warning(+ "using cached GGUF embedder %s: the %s variant could not be "+ "resolved (%s)",+ cached,+ config.EMBED_GGUF_VARIANT,+ "; ".join(errors),+ )+ return self._adopt_model_path(cached, desired)+ raise RuntimeError("no .gguf embedder found; tried " + "; ".join(errors))+ logger.info("resolving GGUF embedder %s/%s", repo, filename)+ from utils.hf_cache_settings import active_hf_hub_cache++ downloaded = hf_hub_download(+ repo_id = repo,+ filename = filename,+ token = token,+ cache_dir = active_hf_hub_cache(),+ )+ return self._adopt_model_path(downloaded, desired)+# Min free VRAM (MiB) for the embedder; below this, auto stays on CPU._MIN_GPU_FREE_MIB = 1024diff --git a/studio/backend/tests/test_llama_cpp_freshness.py b/studio/backend/tests/test_llama_cpp_freshness.pyindex 9f9be4c3ee5..be31c8d38a7 100644--- a/studio/backend/tests/test_llama_cpp_freshness.py+++ b/studio/backend/tests/test_llama_cpp_freshness.py@@ -721,3 +721,21 @@ def test_update_size_missing_inputs_fail_open(monkeypatch):is None)assert fr.update_download_size_bytes({"asset": None}, "b9300", "unslothai/llama.cpp") is None++[email protected]("fetch", ["_fetch_latest_release_tag", "_fetch_latest_release_assets"])+def test_release_fetch_cannot_outlive_its_deadline(monkeypatch, fetch):+ """urllib applies its timeout per address, so /api/inference/status inherits that+ multiplication without a wall-clock deadline; one stalled connect stands in for the+ walk. Both entry points, since they share the fetch."""+ import urllib.request++ def _stalls(req, timeout = 5.0):+ time.sleep(30) # never returns within the deadline+ raise AssertionError("deadline did not cut the fetch short")++ monkeypatch.setattr(urllib.request, "urlopen", _stalls)+ started = time.monotonic()+ assert getattr(fr, fetch)("unslothai/llama.cpp", timeout = 0.25) is None+ # Pins the implemented timeout + 1, not merely "faster than the 30s stall".+ assert time.monotonic() - started < 2.0diff --git a/studio/backend/tests/test_offline_gguf_cache_fallback.py b/studio/backend/tests/test_offline_gguf_cache_fallback.pyindex 13135aaaad4..544613c5743 100644--- a/studio/backend/tests/test_offline_gguf_cache_fallback.py+++ b/studio/backend/tests/test_offline_gguf_cache_fallback.py@@ -1730,6 +1730,72 @@ class TestIpv6Endpoint:assert dns_host_dead("no-such-host.invalid", timeout = 2.0) is True+class TestCallWithDeadline:+ """A connect timeout applies per address and no family is raced, so a blackholed host+ multiplies any nominal cap by the address count."""++ def test_a_stalled_call_raises_rather_than_waiting(self):+ import time as _time++ from utils.utils import call_with_deadline++ started = _time.monotonic()+ with pytest.raises(TimeoutError):+ call_with_deadline(lambda: _time.sleep(30), 0.2)+ assert _time.monotonic() - started < 2.0++ def test_a_completed_call_returns_its_value(self):+ from utils.utils import call_with_deadline+ assert call_with_deadline(lambda: "done", 5.0) == "done"++ def test_slow_but_finished_work_is_not_cut_off(self):+ """The bound is the deadline given, not a shorter internal one: a first download on+ a slow link must not be killed for being slow."""+ import time as _time++ from utils.utils import call_with_deadline++ def _slow():+ _time.sleep(1.4)+ return "done"++ # Longer than any plausible internal floor, so a deadline quietly clamped to a+ # shorter one would cut this off.+ assert call_with_deadline(_slow, 5.0) == "done"++ def test_the_caller_s_log_context_follows_the_work(self):+ """Context is per-thread: without the copy, logging inside the call loses the+ request fields it carries when the same code runs inline."""+ import contextvars++ from utils.utils import call_with_deadline++ request_id = contextvars.ContextVar("request_id")+ request_id.set("abc-123")+ assert call_with_deadline(lambda: request_id.get("missing"), 5.0) == "abc-123"++ def test_a_base_exception_from_the_callable_also_reaches_the_caller(self):+ """Catching only Exception would let SystemExit die with the worker and read as a+ silent None: an unreachable network that never happened."""+ from utils.utils import call_with_deadline++ def _exits():+ raise SystemExit(3)++ with pytest.raises(SystemExit):+ call_with_deadline(_exits, 5.0)++ def test_the_callable_s_own_error_reaches_the_caller(self):+ """Otherwise a deadline turns a bug into an apparent unreachable network."""+ from utils.utils import call_with_deadline++ def _boom():+ raise ValueError("from the worker")++ with pytest.raises(ValueError, match = "from the worker"):+ call_with_deadline(_boom, 5.0)++class TestGuardSkipsLocalPaths:"""A local path never reaches the hub, so probing costs time and prevents nothing."""diff --git a/studio/backend/tests/test_rag_embed_llama_server.py b/studio/backend/tests/test_rag_embed_llama_server.pyindex cc0466ca520..8c9e7723eb6 100644--- a/studio/backend/tests/test_rag_embed_llama_server.py+++ b/studio/backend/tests/test_rag_embed_llama_server.py@@ -3,9 +3,11 @@"""llama-server GGUF embedder tests, every boundary mocked."""+import osimport subprocessimport sysimport textwrap+import timeimport typesfrom pathlib import Path@@ -680,3 +682,421 @@ def test_a_soft_gpu_opt_in_keeps_its_own_cpu_fallback(monkeypatch):backend._spawn() # the reaper killed it; the respawn stays where we landedassert calls == [True, False, False], requestedassert backend._use_gpu() is False, requested+++def _seed_cache(+ root,+ repo_id,+ filenames,+ *,+ revision = "abc123",+ ref = True,+):+ """A hub cache tree built the way hf_hub_download builds one: the snapshot holds+ symlinks into blobs/, not regular files."""+ repo_dir = root / f"models--{repo_id.replace('/', '--')}"+ snapshot = repo_dir / "snapshots" / revision+ blobs = repo_dir / "blobs"+ blobs.mkdir(parents = True, exist_ok = True)+ for name in filenames:+ blob = blobs / name.replace("/", "_")+ blob.write_text("gguf")+ link = snapshot / name+ link.parent.mkdir(parents = True, exist_ok = True)+ link.symlink_to(os.path.relpath(blob, link.parent))+ if ref:+ (repo_dir / "refs").mkdir(parents = True, exist_ok = True)+ (repo_dir / "refs" / "main").write_text(revision)+ return snapshot+++def _use_cache_root(monkeypatch, root):+ import utils.hf_cache_settings as hcs+ monkeypatch.setattr(hcs, "active_hf_hub_cache", lambda: str(root))+++def _no_hub(monkeypatch):+ monkeypatch.setattr(+ LlamaServerBackend,+ "_resolve_uncached_model_path",+ lambda self, *a, **k: pytest.fail("resolved over the hub despite a usable cache"),+ )+++def test_cached_gguf_resolves_without_touching_the_hub(monkeypatch, tmp_path):+ """A repo already on disk must never be re-listed: _model_path is per-process, so+ every restart used to pay a hub call to name a file it already held (#8778)."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ _no_hub(monkeypatch)+ backend = LlamaServerBackend()+ backend._dim = 384 # a width belonging to whatever was served before+ assert backend._resolve_model_path().endswith("bge-F16.gguf")+ assert backend._model_repo == repo+ assert backend._dim is None # re-probed against the file actually adopted+++def test_the_pick_takes_the_shortest_variant_match_and_never_an_mmproj(monkeypatch):+ """An order no directory scan would produce: the wanted file is neither first nor+ shortest overall, and the shortest F16 name is an mmproj projector."""+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ names = [+ "bge-small-en-v1.5-F16-alt.gguf",+ "mmproj-F16.gguf",+ "bge-small-en-v1.5-F16.gguf",+ "bge-Q8_0.gguf",+ "README.md",+ ]+ assert LlamaServerBackend._pick_gguf(names) == "bge-small-en-v1.5-F16.gguf"+++def test_cached_gguf_skips_mmproj_and_honours_the_variant(monkeypatch, tmp_path):+ """The same rule reached through the cache, over a real snapshot layout."""+ repo = config.effective_gguf_repo()+ _seed_cache(+ tmp_path / "hub",+ repo,+ ["mmproj-F16.gguf", "bge-small-en-v1.5-F16.gguf", "bge-Q8_0.gguf", "README.md"],+ )+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ assert LlamaServerBackend._resolve_cached_gguf(repo).endswith("bge-small-en-v1.5-F16.gguf")+++def test_the_pick_is_stable_whatever_order_the_names_arrive_in(monkeypatch):+ """A directory scan has no guaranteed order, unlike a hub listing. Among equal-length+ shard names that order would otherwise decide the answer, and only the first shard+ carries the metadata llama-server needs."""+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ shards = ["model-F16-00001-of-00002.gguf", "model-F16-00002-of-00002.gguf"]+ assert LlamaServerBackend._pick_gguf(shards) == shards[0]+ assert LlamaServerBackend._pick_gguf(list(reversed(shards))) == shards[0]+++def test_an_mtp_drafter_is_never_taken_for_the_embedder(monkeypatch):+ """A drafter is a companion, not a model. A cache holding only the companion must read+ as no embedder rather than as the embedder, and the name sorts ahead of the real weight+ often enough that the length tiebreak alone would not save it."""+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "BF16")+ assert LlamaServerBackend._pick_gguf(["MTP/mtp-model-BF16.gguf"]) is None+ assert (+ LlamaServerBackend._pick_gguf(["MTP/mtp-model-BF16.gguf", "model-BF16.gguf"])+ == "model-BF16.gguf"+ )+++def test_cached_gguf_is_found_in_a_subdirectory(monkeypatch, tmp_path):+ """Quant-per-directory layouts are common, so a snapshot-root-only scan would+ re-download a model that is already cached."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["F16/bge-small.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ resolved = LlamaServerBackend._resolve_cached_gguf(repo)+ assert resolved is not None and resolved.endswith("F16/bge-small.gguf")+++def test_an_incomplete_cached_shard_set_is_not_a_hit(monkeypatch, tmp_path):+ """llama-server opens sibling shards implicitly and only the first carries the metadata,+ so a snapshot holding a trailing shard alone cannot serve the model. Treating it as a+ hit would skip the hub that still has the rest."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["model-F16-00002-of-00002.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ assert LlamaServerBackend._resolve_cached_gguf(repo) is None+++def test_a_complete_cached_shard_set_resolves_to_its_first_shard(monkeypatch, tmp_path):+ """Whole on disk, it is servable -- and must be handed over as shard 1 whatever order+ the scan produced."""+ repo = config.effective_gguf_repo()+ _seed_cache(+ tmp_path / "hub",+ repo,+ ["model-F16-00002-of-00002.gguf", "model-F16-00001-of-00002.gguf"],+ )+ _use_cache_root(monkeypatch, tmp_path / "hub")+ resolved = LlamaServerBackend._resolve_cached_gguf(repo)+ assert resolved is not None and resolved.endswith("model-F16-00001-of-00002.gguf")+++def test_an_incomplete_set_does_not_shadow_a_complete_one(monkeypatch, tmp_path):+ """Completeness has to narrow the candidates, not veto the winner: the short name wins+ the tiebreak, so vetoing it afterwards would report no hit while a servable family sat+ beside it."""+ repo = config.effective_gguf_repo()+ _seed_cache(+ tmp_path / "hub",+ repo,+ [+ "a-F16-00001-of-00002.gguf", # shorter, incomplete: no sibling shard+ "embedding-model-F16-00001-of-00002.gguf",+ "embedding-model-F16-00002-of-00002.gguf",+ ],+ )+ _use_cache_root(monkeypatch, tmp_path / "hub")+ resolved = LlamaServerBackend._resolve_cached_gguf(repo)+ assert resolved is not None+ assert resolved.endswith("embedding-model-F16-00001-of-00002.gguf")+++def test_an_incomplete_variant_match_does_not_hide_a_whole_other_variant(monkeypatch, tmp_path):+ """Offline, the relaxed pass takes any variant. An unservable F16 must not stand in the+ way of a Q8 that is whole -- the difference between a working embedder and none."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["model-F16-00002-of-00002.gguf", "model-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ assert LlamaServerBackend._resolve_cached_gguf(repo) is None # strict: no whole F16+ relaxed = LlamaServerBackend._resolve_cached_gguf(repo, require_variant = False)+ assert relaxed is not None and relaxed.endswith("model-Q8_0.gguf")+++def test_cached_gguf_uses_only_the_revision_refs_main_names(monkeypatch, tmp_path):+ """hf_hub_download serves refs/main. The current revision here sorts neither first nor+ last, so no directory ordering can stand in for reading the ref."""+ repo = config.effective_gguf_repo()+ root = tmp_path / "hub"+ _seed_cache(root, repo, ["aaa-F16.gguf"], revision = "aaa111", ref = False)+ _seed_cache(root, repo, ["live-F16.gguf"], revision = "mmm555", ref = True)+ _seed_cache(root, repo, ["zzz-F16.gguf"], revision = "zzz999", ref = False)+ _use_cache_root(monkeypatch, root)+ assert LlamaServerBackend._resolve_cached_gguf(repo).endswith("live-F16.gguf")+++def test_a_commit_pinned_cache_with_no_ref_defers_to_the_hub(monkeypatch, tmp_path):+ """Snapshot directories are commit hashes, which order by nothing; guessing among them+ could serve a superseded model, so an unnamed revision is no hit at all."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-F16.gguf"], revision = "deadbeef", ref = False)+ _use_cache_root(monkeypatch, tmp_path / "hub")+ assert LlamaServerBackend._resolve_cached_gguf(repo) is None+++def test_a_cached_other_variant_does_not_satisfy_the_configured_one(monkeypatch, tmp_path):+ """Falling back on a listing means the variant is not published; falling back on a+ cache would serve a Q8 left from an earlier setting instead of the configured F16."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ assert LlamaServerBackend._resolve_cached_gguf(repo) is None+++def test_an_unreachable_hub_falls_back_to_whatever_variant_is_cached(monkeypatch, tmp_path):+ """Refusing the wrong variant must not cost the user their embedder outright: a cached+ Q8 beats none, the degrade #8778 asks for."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", contextlib.nullcontext)+ monkeypatch.setattr(+ huggingface_hub,+ "list_repo_files",+ lambda *a, **k: (_ for _ in ()).throw(OSError("offline mode is enabled")),+ )+ backend = LlamaServerBackend()+ assert backend._resolve_model_path().endswith("bge-Q8_0.gguf")+++def test_an_unreachable_hub_still_reaches_the_fallback_repo_s_cache(monkeypatch, tmp_path):+ """The cache-first pass consults only the preferred repo, to keep a reachable companion+ ahead of the fallback. Offline that ordering is moot and the fallback repo's cache is+ all there is, so the relaxed pass must still look there."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/foo")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: "org/foo-GGUF")+ _seed_cache(tmp_path / "hub", "org/foo", ["fallback-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", contextlib.nullcontext)+ monkeypatch.setattr(+ huggingface_hub,+ "list_repo_files",+ lambda *a, **k: (_ for _ in ()).throw(OSError("offline mode is enabled")),+ )+ backend = LlamaServerBackend()+ assert backend._resolve_model_path().endswith("fallback-F16.gguf")+++def test_a_reachable_hub_is_preferred_over_a_cached_other_variant(monkeypatch, tmp_path):+ """A last resort, not a shortcut: a cached Q8 must not pre-empt a hub that can still+ name the configured variant."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", contextlib.nullcontext)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", lambda *a, **k: ["bge-F16.gguf"])+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", lambda **kw: "/cache/bge-F16.gguf")+ backend = LlamaServerBackend()+ assert backend._resolve_model_path() == "/cache/bge-F16.gguf"+++def test_a_failed_transfer_surfaces_instead_of_serving_another_variant(monkeypatch, tmp_path):+ """A download failing for its own reasons (no disk, bad checksum) is no evidence the+ variant is unobtainable, so it must not be answered with a different model."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", contextlib.nullcontext)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", lambda *a, **k: ["bge-F16.gguf"])+ monkeypatch.setattr(+ huggingface_hub,+ "hf_hub_download",+ lambda **kw: (_ for _ in ()).throw(OSError("No space left on device")),+ )+ backend = LlamaServerBackend()+ with pytest.raises(OSError, match = "No space left on device"):+ backend._resolve_model_path()+++def test_a_cached_gguf_is_found_whatever_the_extension_case(monkeypatch, tmp_path):+ """The hub path always matched the suffix case-insensitively; a stricter cache scan+ would re-download a model sitting on disk, or fail outright when offline."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-F16.GGUF"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ assert LlamaServerBackend._resolve_cached_gguf(repo).endswith("bge-F16.GGUF")+++def test_the_adopted_path_is_tagged_with_the_repo_it_was_resolved_for(monkeypatch, tmp_path):+ """A Settings change landing mid-resolution must leave the path tagged with the repo it+ was resolved FOR, so _current() reads it as stale and respawns."""+ repo = config.effective_gguf_repo()+ _seed_cache(tmp_path / "hub", repo, ["bge-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ _no_hub(monkeypatch)+ backend = LlamaServerBackend()++ def _resolve_then_change_the_setting(repo_id, **_kw):+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: "someone/else-GGUF")+ return str(tmp_path / "hub" / "bge-F16.gguf")++ monkeypatch.setattr(+ LlamaServerBackend,+ "_resolve_cached_gguf",+ staticmethod(_resolve_then_change_the_setting),+ )+ backend._resolve_model_path()+ assert backend._model_repo == repo+ assert not backend._current() # the new setting reads as stale, forcing a respawn+++def test_a_cached_fallback_repo_does_not_pre_empt_the_preferred_one(monkeypatch, tmp_path):+ """A custom model resolves through its "-GGUF" companion first and only falls back to+ the model repo when the companion has none. A file cached under the fallback must not+ reorder that, or the backend serves the wrong weights and tags them as current."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/foo")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: "org/foo-GGUF")+ _seed_cache(tmp_path / "hub", "org/foo", ["fallback-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", contextlib.nullcontext)+ monkeypatch.setattr(+ huggingface_hub,+ "list_repo_files",+ lambda repo_id, **k: ["preferred-F16.gguf"] if repo_id == "org/foo-GGUF" else [],+ )+ monkeypatch.setattr(+ huggingface_hub, "hf_hub_download", lambda **kw: "/cache/preferred-F16.gguf"+ )+ backend = LlamaServerBackend()+ assert backend._resolve_model_path() == "/cache/preferred-F16.gguf"+++def test_the_cache_folder_is_named_from_the_resolved_repo_casing(monkeypatch, tmp_path):+ """Settings takes a repo id as typed, while the cache folder carries whatever casing+ downloaded it. Missing that match re-downloads, and fails outright when offline.++ The resolver's answer is deliberately a different id, not a case variant: on a+ case-insensitive filesystem a variant would resolve either way and prove nothing."""+ import utils.paths as paths_pkg++ _seed_cache(tmp_path / "hub", "Cached/Spelling-GGUF", ["bge-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ monkeypatch.setattr(+ paths_pkg, "resolve_cached_repo_id_case", lambda name: "Cached/Spelling-GGUF"+ )+ resolved = LlamaServerBackend._resolve_cached_gguf("as/typed-GGUF")+ assert resolved is not None and resolved.endswith("bge-F16.gguf")+++def test_the_listing_cannot_outlive_its_deadline(monkeypatch, tmp_path):+ """list_repo_files takes no timeout and pagination overrides any client-level default,+ so a blackholed address holds this call, and _lifecycle_lock with it, until the kernel+ exhausts its SYN retries."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ @contextlib.contextmanager+ def reachable():+ yield False++ def _stalls(*_a, **_k):+ time.sleep(30)+ raise AssertionError("deadline did not cut the listing short")++ _use_cache_root(monkeypatch, tmp_path / "empty")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", reachable)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", _stalls)+ monkeypatch.setattr(LlamaServerBackend, "_LIST_DEADLINE_S", 0.3)+ backend = LlamaServerBackend()+ started = time.monotonic()+ with pytest.raises(RuntimeError, match = "no .gguf embedder found"):+ backend._resolve_model_path()+ assert time.monotonic() - started < 3.0+++def test_the_hub_resolve_runs_inside_the_unreachable_guard(monkeypatch, tmp_path):+ """The deadline covers the listing only; the guard is what keeps the transfer from+ starting against an unreachable endpoint."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ active = []++ @contextlib.contextmanager+ def recording_guard():+ active.append(True)+ try:+ yield False+ finally:+ active.pop()++ def _require_guard(*_a, **_k):+ assert active, "hub call made outside the guard"+ return ["bge-F16.gguf"]++ def _download(**_kw):+ assert active, "download made outside the guard"+ return "/cache/bge-F16.gguf"++ _use_cache_root(monkeypatch, tmp_path / "empty")+ monkeypatch.setattr(llama_cpp, "_hf_offline_if_unreachable", recording_guard)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", _require_guard)+ monkeypatch.setattr(huggingface_hub, "hf_hub_download", _download)+ backend = LlamaServerBackend()+ assert backend._resolve_model_path() == "/cache/bge-F16.gguf"+ assert active == []diff --git a/studio/backend/utils/prebuilt/freshness_flow.py b/studio/backend/utils/prebuilt/freshness_flow.pyindex 01495aa5fbc..b878a4aae96 100644--- a/studio/backend/utils/prebuilt/freshness_flow.py+++ b/studio/backend/utils/prebuilt/freshness_flow.py@@ -108,6 +108,29 @@ def save_disk_cache(def _fetch_newest_published_release(repo: str, timeout: float, *, log_message: str+) -> Optional[dict]:+ """Newest published release object for `repo`, bounded by a wall-clock deadline.++ Not redundant with `timeout`: urllib applies that per address, so a host whose leading+ addresses blackhole pays it once for each. /api/inference/status reads this, and that+ multiplication becomes the route's response time.+ """+ from utils.utils import call_with_deadline+ try:+ return call_with_deadline(+ lambda: _fetch_newest_published_release_blocking(+ repo, timeout, log_message = log_message+ ),+ timeout + 1,+ name = "prebuilt-freshness-fetch",+ )+ except TimeoutError as exc:+ logger.debug(log_message, repo = repo, error = str(exc))+ return None+++def _fetch_newest_published_release_blocking(+ repo: str, timeout: float, *, log_message: str) -> Optional[dict]:"""Newest published (non-draft/non-prerelease) release object for `repo`, by``published_at``.diff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex 8cfd9bfaad3..4518d6a1977 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.py@@ -125,6 +125,43 @@ def hf_proxy_configured() -> bool:return hf_proxy_for_endpoint() is not None+def call_with_deadline(+ fn,+ timeout_s: float,+ *,+ name: str = "deadline-call",+):+ """Run `fn()` on a daemon thread; raise TimeoutError if it outlives `timeout_s`.++ For network work that is bounded on paper but not in practice: a connect timeout applies+ per address, so a host whose leading addresses blackhole pays it once for each. A+ timed-out worker is abandoned, not stopped, and holds the callable until the kernel gives+ up, so keep this to short work. The callable's own exception is re-raised rather than+ swallowed, which stops a deadline turning a bug into an apparent dead network.+ """+ import contextvars++ outcome: dict = {}+ # Log context is per-thread: without the copy, fn()'s own logging loses the request+ # fields it carries when the same call runs inline.+ context = contextvars.copy_context()++ def _run() -> None:+ try:+ outcome["value"] = context.run(fn)+ except BaseException as exc: # noqa: BLE001 - re-raised below, in the caller+ outcome["error"] = exc++ t = threading.Thread(target = _run, daemon = True, name = name)+ t.start()+ t.join(timeout_s)+ if t.is_alive():+ raise TimeoutError(f"call did not finish within {timeout_s}s")+ if "error" in outcome:+ raise outcome["error"]+ return outcome.get("value")++def dns_host_dead(host: str, timeout: float = 2.0) -> bool:"""True only when host definitively does not resolve. Daemon thread, so a wedgedresolver cannot block past the deadline and socket.setdefaulttimeout is left alone.