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: embedding model picker searches the Hub and downloads what you pick (#9739)
Michael Hanbe9e5aadad84
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.pyindex 883f90b8d6e..169bc5dd010 100644--- a/studio/backend/core/rag/config.py+++ b/studio/backend/core/rag/config.py@@ -179,6 +179,32 @@ def _names_gguf(model: str) -> bool:return "gguf" in re.split(r"[^a-z0-9]+", model.lower())+# Suffixes unsloth puts on an unquantized re-upload; the GGUF sits on the base+# name (embeddinggemma-300m-qat-q8_0-unquantized -> embeddinggemma-300m-GGUF).+_QUANT_SUFFIX_RE = re.compile(r"(?:-qat)?(?:-q\d+_\d+[a-z]*)?-unquantized$", re.I)+++def gguf_repo_candidates(model: str) -> list[str]:+ """Repos that may hold ``model``'s GGUF, in preference order. Shared by the+ loader and the settings resolve endpoint so they cannot pick different repos."""+ if "RAG_EMBED_GGUF_REPO" in os.environ:+ return [EMBED_GGUF_REPO]+ if _names_gguf(model):+ return [model]+ owner, _, name = model.rpartition("/")+ out = [f"{model}-GGUF"]+ base = _QUANT_SUFFIX_RE.sub("", name)+ if base != name:+ out.append(f"{owner}/{base}-GGUF" if owner else f"{base}-GGUF")+ out.append(model)+ return list(dict.fromkeys(out))+++def gguf_repo_is_explicit() -> bool:+ """Whether one GGUF repository was explicitly pinned for every embedder."""+ return "RAG_EMBED_GGUF_REPO" in os.environ++def gguf_repo_for_embedding_model(model: str) -> str:"""GGUF repo for ``model``, honoring an explicit companion override."""if "RAG_EMBED_GGUF_REPO" in os.environ:@@ -198,12 +224,34 @@ def default_gguf_repo() -> str:def effective_gguf_repo() -> str:"""GGUF repo for the llama-server backend, tracking the effective model.- An explicit ``RAG_EMBED_GGUF_REPO`` env always wins. Otherwise any custom- model (saved in Settings or via ``RAG_EMBEDDING_MODEL``) maps to its- ``-GGUF`` companion repo (the unsloth convention the default pair follows),- or is used as-is when it already names a GGUF repo.+ An explicit ``RAG_EMBED_GGUF_REPO`` env always wins, then the repo the picker+ resolved and stored for this model (which need not follow any naming rule),+ then the ``-GGUF`` companion convention."""- return gguf_repo_for_embedding_model(effective_embedding_model())+ return effective_gguf_repo_for_embedding_model(effective_embedding_model())+++def effective_gguf_repo_for_embedding_model(model: str) -> str:+ """GGUF repo the loader/identity use for ``model``.++ The resolved repo is part of the vector space identity, not merely a load+ location: two different conversions of the same source model need separate+ tags or their document/query vectors can be mixed.+ """+ if "RAG_EMBED_GGUF_REPO" in os.environ:+ return EMBED_GGUF_REPO+ try:+ from utils.embedding_model_settings import get_stored_gguf_repo, remembered_gguf_repo+ stored = get_stored_gguf_repo(model)+ if stored is None:+ # One stored record, so saving another model takes this one's repo+ # away while a job pinned to it is still ingesting; the derived name+ # would move that job's identity mid-run and split one document set+ # across two tags. The memo is what this process last saw for it.+ stored = remembered_gguf_repo(model)+ except Exception: # noqa: BLE001 - store unavailable: fall back to the convention+ stored = None+ return stored or gguf_repo_for_embedding_model(model)# llama-server backend only. F16 over Q8_0: faster (no per-block dequant for thisdiff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.pyindex d049b0a8ba7..9e9103711b1 100644--- a/studio/backend/core/rag/embed_llama_server.py+++ b/studio/backend/core/rag/embed_llama_server.py@@ -23,6 +23,7 @@ import subprocessimport sysimport threadingimport time+from contextlib import contextmanagerfrom functools import lru_cachefrom pathlib import Path@@ -95,15 +96,26 @@ class LlamaServerBackend:def __init__(self) -> None:# Lifecycle (spawn/restart/kill) is serialized; HTTP requests are not.self._lifecycle_lock = threading.Lock()+ # Unload closes the client/process only after every encode/tokenize/probe+ # that already entered has left, and blocks late callers from restarting+ # the backend after it was unpublished.+ self._operation_condition = threading.Condition()+ self._active_operations = 0+ self._operation_local = threading.local()+ self._closed = Falseself._process: subprocess.Popen | None = Noneself._port: int | None = Noneself._stdout_lines: list[str] = []self._stdout_thread: threading.Thread | None = None- # No lock: probes are idempotent (a duplicate 1-text encode is benign)- # and dim() -> encode() -> _ensure_ready() -> _resolve_model_path() can- # re-enter on a mid-probe model change, which would self-deadlock a- # non-reentrant lock held across the probe.+ # Belongs to whichever model the one subprocess serves, so dim() takes the+ # same _serve_lock the request path does. Reentrant because+ # dim() -> encode() -> _ensure_ready() re-enters it on one thread.self._dim: int | None = None+ # One subprocess serves one GGUF, so readiness and the request relying on+ # it must be indivisible: otherwise a swap between them lands A's POST on+ # B's server, storing B's vectors under A's identity. Reentrant because+ # dim() -> encode() -> _post() re-enters on one thread.+ self._serve_lock = threading.RLock()self._model_path: str | None = None# Effective GGUF repo the cached path/dim belong to; a Settings change# makes it stale, forcing a re-resolve + respawn (see _ensure_ready).@@ -116,6 +128,26 @@ class LlamaServerBackend:self._client = httpx.Client(timeout = config.EMBED_REQUEST_TIMEOUT_S, trust_env = False)atexit.register(self._shutdown)+ @contextmanager+ def _operation(self):+ depth = getattr(self._operation_local, "depth", 0)+ with self._operation_condition:+ if self._closed and depth == 0:+ raise RuntimeError("llama-server embedding backend was unloaded")+ if depth == 0:+ self._active_operations += 1+ self._operation_local.depth = depth + 1+ try:+ yield+ finally:+ with self._operation_condition:+ next_depth = self._operation_local.depth - 1+ self._operation_local.depth = next_depth+ if next_depth == 0:+ self._active_operations -= 1+ if self._active_operations == 0:+ self._operation_condition.notify_all()+@propertydef _base_url(self) -> str:return f"http://{config.EMBED_HOST}:{self._port}"@@ -195,25 +227,92 @@ class LlamaServerBackend:def _resolve_local_gguf(model: str) -> str | None:"""A custom model may be a local .gguf file or a directory holding one;resolve it without the hub. None when the value is not a local path."""- p = Path(model).expanduser()+ from utils.models.model_config import _local_gguf_load_path, colocated_split_shards+ from utils.paths import normalize_path++ # Same normalization the sentence-transformers and settings probes already+ # apply, so a drive-letter path is recognized here too. Without it a WSL+ # user's `C:\models\...` GGUF resolved as a filename that cannot exist and+ # went to the Hub, which then reported no weights in `C:\models\...-GGUF`.+ p = Path(normalize_path(model)).expanduser()if p.is_file() and p.suffix.lower() == ".gguf":return None if is_appledouble_metadata(p) else str(p)if p.is_dir():- files = [- f- for f in p.iterdir()- if f.suffix.lower() == ".gguf"- and "mmproj" not in f.name.lower()- and not is_appledouble_metadata(f)- ]- if not files:- raise RuntimeError(f"no .gguf file found in local model dir {model!r}")- variant = config.EMBED_GGUF_VARIANT.lower()- match = [f for f in files if variant in f.name.lower()] or files- return str(sorted(match, key = lambda f: len(f.name))[0])+ files = [f for f in p.iterdir() if not is_appledouble_metadata(f)]+ # Same pick as a hub listing gets, so a directory and the repo it was+ # downloaded from cannot disagree about which quant the embedder opens.+ # Its name tiebreak is what makes a directory of split shards resolve to+ # shard 1 rather than to whichever one `iterdir` happened to yield first.+ remaining = list(files)+ while remaining:+ picked = LlamaServerBackend._pick_gguf(remaining, key = lambda f: f.name)+ if picked is None:+ break+ # llama-server opens the siblings implicitly, so a torn family is+ # not a usable answer even though shard 1 is sitting right there.+ if colocated_split_shards(picked)[1]:+ # Enters the family at shard 1 and keeps a complete symlink set+ # intact, the same way the chat loader resolves a local GGUF.+ return str(_local_gguf_load_path(picked))+ remaining = [f for f in remaining if f != picked]+ raise RuntimeError(f"no .gguf file found in local model dir {model!r}")return None+ @classmethod+ def _pick_complete_gguf(cls, names):+ """``(picked, family)`` for the preferred GGUF whose family is whole.++ A torn family is skipped rather than returned, so the candidate loop moves+ on to the next repo instead of adopting a repo it cannot finish.+ """+ remaining = list(names)+ while remaining:+ picked = cls._pick_gguf(remaining)+ if picked is None:+ return None, []+ family = cls._split_family(names, picked)+ if family:+ return picked, family+ remaining = [name for name in remaining if name != picked]+ return None, []++ @staticmethod+ def _split_family(names, picked: str):+ """Every file `picked` needs, or None when the published family is torn.++ llama-server opens split siblings implicitly, so one selected shard is not a+ downloadable plan. Shared with the settings resolver so the plan it offers and+ the transfer this loader performs name the same set of files.+ """+ from pathlib import PurePosixPath+ from utils.models.model_config import _GGUF_SPLIT_FILE_RE++ path = PurePosixPath(picked)+ match = _GGUF_SPLIT_FILE_RE.match(path.name)+ if match is None:+ return [picked]+ total = int(match.group("total"))+ if total < 1:+ return None+ found: dict[int, str] = {}+ for name in names:+ other = PurePosixPath(name)+ other_match = _GGUF_SPLIT_FILE_RE.match(other.name)+ if (+ other.parent != path.parent+ or other_match is None+ or other_match.group("prefix").casefold() != match.group("prefix").casefold()+ or other_match.group("total") != match.group("total")+ ):+ continue+ index = int(other_match.group("index"))+ if 1 <= index <= total:+ found[index] = name+ if len(found) != total:+ return None+ return [found[index] for index in range(1, total + 1)]+@staticmethoddef _pick_gguf(names,@@ -323,34 +422,151 @@ class LlamaServerBackend:files = [p for p in files if p != pick]return None- def _resolve_model_path(self) -> str:+ def _resolve_model_path(self, model_name: str | None = None) -> str:"""Download (or cache-hit) the variant-matching, non-mmproj GGUF embedder,returning its local path. Re-resolves when the effective repo changed (a- custom model was saved in Settings)."""+ custom model was saved in Settings).++ ``model_name`` is the model the caller pinned; the live setting would+ resolve B's weights for a job still tagging its vectors as A."""+ model = model_name or config.effective_embedding_model()# Captured once: if the setting changes mid-download, the path must stay# tagged with the repo it was resolved FOR, so _current() sees the new# setting as stale and respawns instead of serving the old model.- desired = config.effective_gguf_repo()+ desired = config.effective_gguf_repo_for_embedding_model(model)if self._model_path is not None and self._model_repo == desired:return self._model_path- local = self._resolve_local_gguf(config.effective_embedding_model())+ local = self._resolve_local_gguf(model)if local is not 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.+ # The planned family whenever it is on disk, ahead of the variant lookup.+ # Identity carries the model and repo but not the file, so a preferred+ # variant arriving later would otherwise change the weights under an+ # existing index without changing its tag. Consulted after completion too,+ # which is what makes the record an identity, not a transfer receipt.+ planned = self._planned_family_path(model, desired)+ if planned is not None:+ try:+ from utils.embedding_model_settings import clear_stored_download_pending+ clear_stored_download_pending(model)+ except Exception: # noqa: BLE001 - a settings write must not fail a load+ pass+ return self._adopt_model_path(planned, desired)+ # Companion repo, then the naming variants, then the model repo itself.repo = desired- candidates = [repo]- model = config.effective_embedding_model()- if model != repo:- candidates.append(model)+ candidates = list(dict.fromkeys([repo, *config.gguf_repo_candidates(model)]))# 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:+ # The configured variant is present in the preferred repo, which is+ # what the picker advertised, so any pending marker has been answered.+ # Retire it here or the model stays cache-only for the life of the+ # install and a later eviction reads as "never downloaded".+ try:+ from utils.embedding_model_settings import clear_stored_download_pending+ clear_stored_download_pending(model)+ except Exception: # noqa: BLE001 - a settings write must not fail a load+ passreturn self._adopt_model_path(cached, desired)+ try:+ from utils.embedding_model_settings import get_stored_download_pending+ download_pending = get_stored_download_pending(model)+ except Exception: # noqa: BLE001 - old/unavailable settings store+ download_pending = False+ if download_pending:+ # A published repo may not carry the configured quant; the picker+ # deliberately downloaded the complete family the Hub resolver+ # selected, so accept any complete cached quant here. Never fall+ # through to the online loader while the explicit transfer is+ # pending/cancelled.+ cached = self._resolve_cached_gguf(desired, require_variant = False)+ if cached is not None:+ # Reaching here means the configured variant is NOT cached (the+ # strict pass returned if it were), which happens two ways that+ # need opposite answers.+ if self._is_planned_family(model, desired, cached):+ # The repo publishes no such variant, so this quant is what+ # the picker advertised and fetched. Retire the marker, or the+ # model stays cache-only and a later eviction refuses to index+ # something that did finish downloading.+ try:+ from utils.embedding_model_settings import clear_stored_download_pending+ clear_stored_download_pending(model)+ except Exception: # noqa: BLE001 - a settings write must not fail a load+ pass+ # Otherwise a quant left by an earlier setting, or a record too old+ # to say. Serve it rather than fail the index, but leave the marker:+ # retiring on a stand-in would pin this model to the wrong quant.+ return self._adopt_model_path(cached, desired)+ raise RuntimeError(+ f"Embedding model {model!r} is not downloaded yet. "+ "Finish its Settings download before indexing documents."+ )return self._resolve_uncached_model_path(desired, candidates)+ @staticmethod+ def _planned_family_path(model: str, repo_id: str) -> str | None:+ """The entry file of ``model``'s planned family, when all of it is cached.++ Whole family or nothing: a partially present one is a torn transfer, and+ answering with its first shard would serve llama-server a model it cannot+ finish opening. None when no family was recorded, which is every+ resolution written before it was stored."""+ try:+ from pathlib import PurePosixPath+ from utils.embedding_model_settings import get_stored_gguf_files++ planned = get_stored_gguf_files(model)+ if not planned:+ return None+ snapshot = LlamaServerBackend._cached_snapshot_dir(repo_id)+ if snapshot is None:+ return None+ paths = []+ for name in planned:+ relative = PurePosixPath(name)+ if relative.is_absolute() or ".." in relative.parts:+ return None+ path = snapshot.joinpath(*relative.parts)+ if not path.is_file():+ return None+ paths.append(path)+ # Ordered shard 1..N by the planner, so the first is where llama-server+ # enters the family.+ return str(paths[0]) if paths else None+ except Exception: # noqa: BLE001 - an unreadable record answers nothing+ return None++ @staticmethod+ def _is_planned_family(model: str, repo_id: str, path: str) -> bool:+ """Whether ``path`` is one of the files the picker planned for ``model``.++ Compared by the path relative to the snapshot, which is the layout the+ record's repo-relative names already describe. Base names are not enough:+ a repo that files each quant in its own directory publishes+ ``Q8_0/model.gguf`` beside ``Q4_K_M/model.gguf``, and matching on the name+ alone would let a stale quant pass for the planned one.++ False when no family was recorded, which is every resolution written before+ it was stored, so the caller keeps its conservative answer on those."""+ try:+ from pathlib import PurePosixPath+ from utils.embedding_model_settings import get_stored_gguf_files++ planned = get_stored_gguf_files(model)+ if not planned:+ return False+ snapshot = LlamaServerBackend._cached_snapshot_dir(repo_id)+ if snapshot is None:+ return False+ relative = Path(path).relative_to(snapshot)+ names = {PurePosixPath(name).as_posix().casefold() for name in planned}+ return PurePosixPath(relative.as_posix()).as_posix().casefold() in names+ except Exception: # noqa: BLE001 - an unreadable record or an outside path answers nothing+ return False+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 = path@@ -376,6 +592,7 @@ class LlamaServerBackend:token = os.environ.get("HF_TOKEN") or Nonerepo = desiredfilename: str | None = None+ family: list[str] = []errors: list[str] = []with _hf_offline_if_unreachable():for candidate in candidates:@@ -385,7 +602,7 @@ class LlamaServerBackend:self._LIST_DEADLINE_S,name = "embed-gguf-listing",)- filename = self._pick_gguf(names)+ filename, family = self._pick_complete_gguf(names)except Exception as e: # noqa: BLE001 - missing/gated/stalled -> next candidateerrors.append(f"{candidate!r}: {e}")continue@@ -411,12 +628,20 @@ class LlamaServerBackend: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(),- )+ cache_dir = active_hf_hub_cache()+ # Fetch the whole split family, not just the shard that was picked:+ # `-m shard1` makes llama-server open the siblings itself, so a+ # one-file transfer fails at startup on a repo it just downloaded.+ downloaded = None+ for name in family:+ fetched = hf_hub_download(+ repo_id = repo,+ filename = name,+ token = token,+ cache_dir = cache_dir,+ )+ if name == filename:+ downloaded = fetchedreturn self._adopt_model_path(downloaded, desired)# Min free VRAM (MiB) for the embedder; below this, auto stays on CPU.@@ -573,23 +798,27 @@ class LlamaServerBackend:except Exception: # noqa: BLE001 - drain thread must never raisepass- def _spawn(self) -> None:+ def _spawn(self, model_name: str | None = None) -> None:"""Start the embed server (caller holds the lock). A failed GPU start fallsback to CPU once, unless ``RAG_EMBED_DEVICE`` is the literal ``gpu``."""use_gpu = self._use_gpu()try:- self._spawn_once(use_gpu)+ self._spawn_once(use_gpu, model_name)except RuntimeError:if use_gpu and not config.embed_device_requires_gpu():logger.warning("embed server GPU start failed; falling back to CPU")self._force_cpu = True- self._spawn_once(False)+ self._spawn_once(False, model_name)else:raise- def _spawn_once(self, use_gpu: bool) -> None:+ def _spawn_once(+ self,+ use_gpu: bool,+ model_name: str | None = None,+ ) -> None:binary = self._resolve_binary()- model_path = self._resolve_model_path()+ model_path = self._resolve_model_path(model_name)port = config.EMBED_PORT or self._find_free_port()env = self._build_env(binary, use_gpu = use_gpu)cmd = self._build_cmd(binary, model_path, port, use_gpu = use_gpu)@@ -660,24 +889,32 @@ class LlamaServerBackend:def _process_alive(self) -> bool:return self._process is not None and self._process.poll() is None- def _current(self) -> bool:- """Alive AND serving the effective repo (a Settings model change makes a- live server stale)."""+ def _current(self, model_name: str | None = None) -> bool:+ """Alive AND serving the repo for ``model_name`` (a Settings model change,+ or a request pinned to a different model, makes a live server stale)."""from utils.llama_cpp_path_settings import custom_llama_cpp_path_revision++ desired = config.effective_gguf_repo_for_embedding_model(+ model_name or config.effective_embedding_model()+ )return (self._process_alive()- and self._model_repo == config.effective_gguf_repo()+ and self._model_repo == desiredand self._binary_path_revision == custom_llama_cpp_path_revision())- def _ensure_ready(self) -> None:- """Guarantee a live server on the effective model, (re)spawning if needed.+ def _ensure_ready(self, model_name: str | None = None) -> None:+ """Guarantee a live server on ``model_name``, (re)spawning if needed.Double-checked so the current path takes no lock; self-heals after the- chat reaper kills us and re-resolves after a Settings model change."""- if self._current():+ chat reaper kills us and re-resolves after a Settings model change.++ One subprocess serves one GGUF, so a request pinned to a model the server+ is not serving respawns onto it rather than answering from the wrong+ weights."""+ if self._current(model_name):returnwith self._lifecycle_lock:- if self._current():+ if self._current(model_name):returnself._kill_process()from utils.llama_cpp_path_settings import custom_llama_cpp_path_revision@@ -685,12 +922,12 @@ class LlamaServerBackend:if self._binary_path_revision != custom_llama_cpp_path_revision():self._binary = Noneself._binary_path_revision = None- self._spawn()+ self._spawn(model_name)- def _restart(self) -> None:+ def _restart(self, model_name: str | None = None) -> None:with self._lifecycle_lock:self._kill_process()- self._spawn()+ self._spawn(model_name)def _kill_process(self) -> None:proc = self._process@@ -719,35 +956,65 @@ class LlamaServerBackend:self._stdout_thread = Nonedef _shutdown(self) -> None:+ with self._operation_condition:+ self._closed = True+ while self._active_operations:+ self._operation_condition.wait()try:- self._kill_process()+ with self._lifecycle_lock:+ self._kill_process()finally:try:self._client.close()except Exception: # noqa: BLE001pass+ # Drop the interpreter-exit hook with the backend it belonged to.+ # Unload/rebuild is an ordinary cycle here (Settings exposes it as a+ # button), and a registry that only ever grows pins every retired+ # backend, and its captured stdout tail, for the life of the process.+ try:+ atexit.unregister(self._shutdown)+ except Exception: # noqa: BLE001 - teardown must not raise+ pass- def _post(self, path: str, payload: dict) -> dict:+ def _post(+ self,+ path: str,+ payload: dict,+ model_name: str | None = None,+ ) -> dict:"""POST to the server, restarting once and retrying on a dropped connection(the reaper may have killed us) or a timeout (the bundled build sometimeswedges a request); a fresh server unsticks both."""+ with self._operation():+ return self._post_active(path, payload, model_name)++ def _post_active(+ self,+ path: str,+ payload: dict,+ model_name: str | None = None,+ ) -> dict:last_exc: Exception | None = Nonefor attempt in range(2):- self._ensure_ready()- try:- resp = self._client.post(f"{self._base_url}{path}", json = payload)- resp.raise_for_status()- return resp.json()- except (*_TRANSPORT_ERRORS, httpx.TimeoutException) as e:- last_exc = e- if attempt == 0:- self._restart()- continue- except httpx.HTTPStatusError as e:- body = e.response.text[:500] if e.response is not None else ""- raise RuntimeError(- f"llama-server embedder POST {path} -> {e.response.status_code}: {body}"- ) from e+ with self._serve_lock:+ # Held across readiness AND the request, so a swap can only land+ # between whole requests.+ self._ensure_ready(model_name)+ try:+ resp = self._client.post(f"{self._base_url}{path}", json = payload)+ resp.raise_for_status()+ return resp.json()+ except (*_TRANSPORT_ERRORS, httpx.TimeoutException) as e:+ last_exc = e+ if attempt == 0:+ self._restart(model_name)+ continue+ except httpx.HTTPStatusError as e:+ body = e.response.text[:500] if e.response is not None else ""+ raise RuntimeError(+ f"llama-server embedder POST {path} -> {e.response.status_code}: {body}"+ ) from eraise RuntimeError(f"llama-server embedder POST {path} failed after retry") from last_excdef encode(@@ -757,11 +1024,22 @@ class LlamaServerBackend:model_name = None,normalize = True,):- """Embed texts -> (N, dim) float32. ``model_name`` is ignored (the GGUF is- fixed by config). Normalizes in Python to match the ST backend."""+ """Embed texts -> (N, dim) float32. ``model_name`` pins which GGUF serves+ the request, so a Settings change cannot answer it from another model.+ Normalizes in Python to match the ST backend."""+ with self._operation():+ return self._encode_active(texts, normalize = normalize, model_name = model_name)++ def _encode_active(+ self,+ texts,+ *,+ normalize = True,+ model_name = None,+ ):n = len(texts)if n == 0:- return np.zeros((0, self.dim()), dtype = np.float32)+ return np.zeros((0, self.dim(model_name = model_name)), dtype = np.float32)rows: list[list[float]] = []batch = max(1, config.EMBED_BATCH)for start in range(0, n, batch):@@ -769,6 +1047,7 @@ class LlamaServerBackend:data = self._post("/v1/embeddings",{"input": chunk, "model": "embedding", "encoding_format": "float"},+ model_name = model_name,)items = data.get("data", [])if len(items) != len(chunk):@@ -790,21 +1069,31 @@ class LlamaServerBackend:def dim(self, *, model_name = None) -> int:"""Embedding width, probed via a 1-text encode and cached per model(_resolve_model_path clears it when the effective repo changes).- Unlocked: concurrent probes are benign, and locking would deadlock when- the probe's encode respawns onto a changed model (see __init__)."""- self._ensure_ready()- cached = self._dim- if cached is not None:- return cached- vec = self.encode(["x"], normalize = False)- width = int(vec.shape[1])- self._dim = width- return width++ Under the same lock the request path uses, for the same reason: ``_dim``+ belongs to the one subprocess, so with two jobs pinned to models of+ different width, one could ready A, have the other switch to B and cache+ B's width, and then answer A with it. Reentrant, so the probe's own encode+ re-enters rather than deadlocking."""+ with self._operation(), self._serve_lock:+ self._ensure_ready(model_name)+ cached = self._dim+ if cached is not None:+ return cached+ vec = self.encode(["x"], normalize = False, model_name = model_name)+ width = int(vec.shape[1])+ self._dim = width+ return widthdef warm(self, *, model_name = None) -> None:- """Start the server and probe dim off the request path."""- self._ensure_ready()- self.dim()+ """Start the server and probe dim off the request path.++ Readiness is left to ``dim``, which takes ``_serve_lock`` for it. Calling it+ here as well put a kill-and-respawn outside that lock, so warming B could+ move the port out from under an encode pinned to A that had already passed+ its own readiness check, and store B's vectors under A's identity."""+ with self._operation():+ self.dim(model_name = model_name)def token_counter(self, *, model_name = None):"""Count tokens via the GGUF's /tokenize so chunk sizing matches the@@ -812,7 +1101,12 @@ class LlamaServerBackend:@lru_cache(maxsize = 4096)def _count(text: str) -> int:- data = self._post("/tokenize", {"content": text, "add_special": False})- return len(data.get("tokens", []))+ with self._operation():+ data = self._post(+ "/tokenize",+ {"content": text, "add_special": False},+ model_name = model_name,+ )+ return len(data.get("tokens", []))return _countdiff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.pyindex 767b542e201..be3a409c807 100644--- a/studio/backend/core/rag/embeddings.py+++ b/studio/backend/core/rag/embeddings.py@@ -118,20 +118,26 @@ def _load_device() -> str:_torchao_stub_done = False+# Guards the stub's one-shot state and the import that must follow it. Its own+# lock, not ``_lock``: that one is held across a whole model construction, so+# borrowing it made a preflight probe wait out someone else's download. Taken+# innermost, so there is no ordering to get wrong.+_stub_lock = threading.Lock()def _install_torchao_stub_once() -> None:"""Neutralize torchao before importing sentence-transformers. On Windows ROCm,torchao (pulled in by transformers.quantizers) imports an absent c10d backendand aborts, dropping the embedder to llama-server. Workers stub it too; the- embedder runs in the main process. No-op elsewhere; runs once under ``_lock``."""+ embedder runs in the main process. No-op elsewhere; runs once."""global _torchao_stub_done- if _torchao_stub_done:- return- _torchao_stub_done = True- from core._torchao_stub import install_torchao_windows_rocm_stub+ with _stub_lock:+ if _torchao_stub_done:+ return+ _torchao_stub_done = True+ from core._torchao_stub import install_torchao_windows_rocm_stub- install_torchao_windows_rocm_stub()+ install_torchao_windows_rocm_stub()class UnsafeEmbeddingModelError(RuntimeError):@@ -140,6 +146,10 @@ class UnsafeEmbeddingModelError(RuntimeError):routine ST failure."""+class EmbeddingModelDownloadRequiredError(RuntimeError):+ """The picker activated a model whose explicit transfer is still pending."""++def _ambient_hf_token() -> str | None:"""The HF token the loader itself would use (HF_TOKEN env or the cached login), sothe scan can reach a gated/private repo instead of failing open. None if unavailable."""@@ -415,7 +425,18 @@ def _get(model_name: str | None = None):name = model_name or config.effective_embedding_model()# Capture offline state once so the gate and the load agree (no window where the gate is# skipped as offline but the constructor then reaches the network).- local_only = hf_env_offline()+ try:+ from utils.embedding_model_settings import get_stored_download_pending+ download_pending = get_stored_download_pending(name)+ except Exception: # noqa: BLE001 - old/unavailable settings store+ download_pending = False+ offline = hf_env_offline()+ # Two different questions. `local_only` says "load from cache, do not fetch",+ # which a pending transfer also demands. `offline` is whether the Hub is+ # reachable, which is what the security gate needs: told offline while online+ # it applies the fail-closed cached-pickle rule and rejects a .bin-only repo+ # the resolver just accepted and scanned, failing the first index outright.+ local_only = offline or download_pendingwith _lock:if _model is None or _name != name:# Probe before loading sentence-transformers on the selected device.@@ -425,7 +446,6 @@ def _get(model_name: str | None = None):from utils.hf_cache_settings import active_hf_hub_cachelogger.info("loading embedding model %s on %s", name, device)- _guard_model_security(name, local_only)st_kwargs = dict(device = device,cache_folder = active_hf_hub_cache(),@@ -438,16 +458,58 @@ def _get(model_name: str | None = None):model_kwargs = dtype_kwargs("float32" if device == "cpu" else "float16"),)load_target = name+ from utils.paths import is_local_path+ from utils.utils import cached_st_source, hf_cache_snapshot_dir++ # The repo AND the directory that supplied the weights, together: a+ # slashless name can match under sentence-transformers/ while a stale+ # literal cache entry is what a second lookup would return, and ST+ # weights alone are satisfied by the first finalized shard of a+ # transfer still in flight.+ #+ # Repo ids only. A local path IS the artifact the resolver accepted,+ # and the picker takes a slashless relative directory, so a folder+ # named all-MiniLM-L6-v2 beside a cached sentence-transformers/ copy+ # would load the Hub's weights under the local path's identity.+ st_source = None if is_local_path(name) else cached_st_source(name)+ if not local_only and st_source is not None:+ # Settings reported this model on-device off the same predicate, so+ # handing SentenceTransformer the repo id here is what lets it reach+ # the Hub for a revision published since, and fetch it during the+ # first index. That is the invisible transfer the picker exists to+ # replace, and it changes the vectors without changing the identity+ # they are tagged with. Load the snapshot that was called cached.+ load_target = str(st_source[1])if local_only:- from utils.utils import hf_cache_snapshot_dir- snapshot = hf_cache_snapshot_dir(name)+ # ST-specific AND complete: a hybrid repo whose GGUF is cached, or a+ # transfer that has finalized only its first shard, would otherwise+ # retire the marker and be handed to SentenceTransformer.+ if download_pending and st_source is None:+ raise EmbeddingModelDownloadRequiredError(+ f"Embedding model {name!r} is not downloaded yet. "+ "Finish its Settings download before indexing documents."+ )+ snapshot = st_source[1] if st_source else hf_cache_snapshot_dir(name)if snapshot is not None:# Load from the local snapshot dir: a local path never touches the Hub, so# this is offline-safe on ANY sentence-transformers version (even ones# predating local_files_only).load_target = str(snapshot)+ elif download_pending:+ # Defensive: a loadable check and snapshot lookup share no+ # lock, so eviction between them is still a pending model.+ raise EmbeddingModelDownloadRequiredError(+ f"Embedding model {name!r} is not downloaded yet. "+ "Finish its Settings download before indexing documents."+ )elif _st_accepts_local_files_only(SentenceTransformer):st_kwargs["local_files_only"] = True+ # After load_target is settled, so this scans what is about to be+ # deserialized: on the repo id it checked the Hub's current commit while+ # the load opened an older cached one. evaluate_file_security recovers+ # the repo and exact commit from a snapshot path, and fails closed+ # locally when the Hub cannot answer.+ _guard_model_security(load_target, offline)with _quiet_transformers_load() as report:# The re-emit runs in finally: a load that raises after transformers# wrote its report is exactly when a MISSING or MISMATCH line matters,@@ -457,6 +519,17 @@ def _get(model_name: str | None = None):finally:_emit_load_reports(report)_name = name+ if download_pending:+ # Only once the model is actually constructed. Retiring it before+ # the constructor let an unsupported architecture or a device that+ # cannot initialize fall through to llama-server with no marker+ # left, so the fallback was free to fetch the GGUF companion+ # during the first index: the unapproved transfer this replaces.+ try:+ from utils.embedding_model_settings import clear_stored_download_pending+ clear_stored_download_pending(name)+ except Exception: # noqa: BLE001 - a settings write must not fail a load+ passreturn _model@@ -484,8 +557,11 @@ def _st_encode():"""ST encode -> (N, dim) float32. Serialized (fast-tokenizer borrow check),under inference_mode when torch is present, with rayon enabled for the call."""- model = _get(model_name)with _compute_lock:+ # Admission and model lookup are one lease. If lookup happened first,+ # unload could clear the globals and return while this call retained a+ # strong local reference and had not begun inference yet.+ model = _get(model_name)os.environ["TOKENIZERS_PARALLELISM"] = "true"try:with _inference_ctx():@@ -504,17 +580,22 @@ def _st_encode(def _st_dim(model_name: str | None = None) -> int:- return _get(model_name).get_sentence_embedding_dimension()+ with _compute_lock:+ return _get(model_name).get_sentence_embedding_dimension()def _st_token_counter(model_name: str | None = None) -> Callable[[str], int]:"""Token counter using the model's tokenizer, under the compute lock (the samefast tokenizer backs encode and isn't thread-safe), with rayon enabled for the- call. Mirrors ``_st_encode``."""- tok = _get(model_name).tokenizer+ call. Mirrors ``_st_encode``: admission and model lookup are one lease, so the+ tokenizer is read per call inside the lock rather than captured here. Chunking+ holds this callable for a whole document, and a tokenizer captured up front+ outlives the unload that retired it -- counting on with weights nobody can+ reach, while the endpoint reports the model as gone."""def _count(t: str) -> int:with _compute_lock:+ tok = _get(model_name).tokenizeros.environ["TOKENIZERS_PARALLELISM"] = "true"try:return len(tok.encode(t, add_special_tokens = False))@@ -524,6 +605,17 @@ def _st_token_counter(model_name: str | None = None) -> Callable[[str], int]:return _count+def _release_st_model() -> bool:+ """Drop the module-level SentenceTransformer without racing an encode."""+ global _model, _name+ with _compute_lock:+ with _lock:+ released = _model is not None+ _model = None+ _name = None+ return released++class _SentenceTransformersBackend:"""Default backend; delegates to the module-level ST helpers so the ``_get``monkeypatch in tests keeps working."""@@ -537,12 +629,12 @@ class _SentenceTransformersBackend:):try:return _st_encode(texts, model_name = model_name, normalize = normalize)- except UnsafeEmbeddingModelError:- raise # a security block must hard-fail, not fall back to llama-server+ except (UnsafeEmbeddingModelError, EmbeddingModelDownloadRequiredError):+ raise # policy failures must hard-fail, not change backend/downloadexcept Exception as st_err: # noqa: BLE001 - runtime ST/CUDA encode failure# ST loaded but this encode blew up; swap the process to the llama-server# embedder (so later encodes stay in one space) and retry.- fallback = _switch_to_llama_fallback(st_err)+ fallback = _switch_to_llama_fallback(st_err, model_name)if fallback is None:raise_served_by.backend = fallback@@ -561,6 +653,17 @@ class _SentenceTransformersBackend:_backend_lock = threading.Lock()_backend = None_backend_key: str | None = None+# Per model: an ST runtime/load failure pins llama-server for THAT model, so the+# swap survives the next rebuild while a later safetensors-only selection can+# still build ST. Keyed by model because one (key, model) pair let a second+# failing model erase the first one's pin and send a still-running job back to ST.+# Cleared only by a reset or an explicit unload, both of which are a fresh start.+#+# Read WITHOUT _backend_lock throughout: _get_backend holds that lock across a+# whole model load, and every reader here is a probe the resolver's own budget is+# supposed to bound. dict.get is atomic, and a pin that lands mid-probe is+# answered on the next call.+_forced_backends: dict[str, str] = {}_ST_ALIASES = frozenset({"sentence-transformers", "sentence_transformers", "st"})_LLAMA_ALIASES = frozenset(@@ -588,6 +691,140 @@ def _resolve_auto() -> str:return "sentence-transformers"+def _model_is_local_gguf(model: str | None) -> bool:+ """Whether ``model`` names a local .gguf file, or a folder holding one.++ Gated on ``is_local_path`` first: a plain repo id costs no filesystem walk on+ the hot ``_get_backend`` path."""+ if not model:+ return False+ try:+ from utils.paths import is_local_path++ if not is_local_path(model):+ return False+ from core.rag.embed_llama_server import LlamaServerBackend++ return LlamaServerBackend._resolve_local_gguf(model) is not None+ except Exception: # noqa: BLE001 - filesystem oddity is not a llama signal+ return False+++def _model_names_gguf_repo(model: str | None) -> bool:+ """Whether ``model`` is a repo id that names GGUF weights.++ The `-GGUF` companion suffix is the convention the resolver derives and the+ picker's on-device dot follows, so such a repo publishes no safetensors for+ sentence-transformers to open. A pure name test: the remote counterpart of+ ``_model_is_local_gguf``, which cannot see a repo that is not on disk yet."""+ if not model:+ return False+ try:+ from utils.paths import is_local_path++ # A directory may be named anything: `~/models/my-gguf` holding safetensors+ # is a sentence-transformers model, and only the filesystem can say so.+ # _model_is_local_gguf has already answered for every local id.+ if is_local_path(model):+ return False+ except Exception: # noqa: BLE001 - unparseable path is not a repo id either+ return False+ # config's predicate, not a second opinion: gguf_repo_candidates already+ # counts "gguf" as a whole name segment, so owner/GGUF-model is a GGUF repo+ # there and must not be a sentence-transformers one here.+ return config._names_gguf(model.strip().rstrip("/").rsplit("/", 1)[-1])+++def _resolve_auto_for_model(model_name: str | None = None) -> str:+ """``auto``, but honouring the backend recorded for the saved model.++ An embedder with no GGUF still runs on sentence-transformers, so the picker+ records that choice; the hardware default would send it to llama-server,+ which has nothing to open."""+ model = model_name or config.effective_embedding_model()+ # Ahead of the stored record: the filesystem was asked, not guessed at, and a+ # stored ST record for a .gguf can only come from a force-save that failed.+ # Only ``auto`` consults this, so an explicit RAG_EMBED_BACKEND still wins.+ if _model_is_local_gguf(model):+ return "llama-server"+ try:+ from utils.embedding_model_settings import get_stored_backend+ stored = get_stored_backend(model)+ except Exception: # noqa: BLE001 - store unavailable: fall back to hardware+ stored = None+ if stored:+ key = stored.strip().lower()+ if key in _ST_ALIASES or key in _LLAMA_ALIASES:+ return key+ # Nothing validated, so read the name. _resolve_auto answers+ # "sentence-transformers" on any GPU host, and a GGUF repo resolved as ST is+ # rejected for publishing no safetensors, saveable only over that error --+ # which leaves it pending, and _get() refuses a pending ST model before the+ # llama fallback can run. Below the stored record, though, since a name is+ # only a guess: a repo with a torn GGUF family and usable safetensors has a+ # validated ST plan that overruling would fail as "not downloaded".+ if _model_names_gguf_repo(model):+ return "llama-server"+ return _resolve_auto()+++def sentence_transformers_runtime_available() -> bool:+ """Whether the ST backend can reach the model-loading step in this process.++ This deliberately mirrors the environment-dependent prefix of ``_get`` but+ does not construct a model (which could download the snapshot the picker is+ still planning). It catches missing/broken torch or sentence-transformers+ installs and the fatal device mismatch that ``_build_st_backend_or_fallback``+ would otherwise discover only after an ST-only plan was persisted.+ """+ try:+ _load_device()+ # Not under ``_lock``. Both the resolve GET and the PUT run this before any+ # deadline-bounded Hub call, and ``_get`` holds ``_lock`` across an entire+ # SentenceTransformer construction, download included: sharing it meant+ # opening or saving Settings during a slow first load blocked for as long+ # as that load took, past every deadline the resolver applies to itself.+ # The stub keeps its ordering guarantee under its own lock.+ _install_torchao_stub_once()+ from sentence_transformers import SentenceTransformer++ return callable(SentenceTransformer)+ except Exception as exc: # noqa: BLE001 - any failed runtime import selects the fallback+ logger.debug("sentence-transformers runtime preflight failed: %s", exc)+ return False+++def _llama_server_runtime_available() -> bool:+ """Whether the fallback that ST construction would use can be built."""+ try:+ from core.inference.llama_cpp import LlamaCppBackend+ return bool(LlamaCppBackend._find_llama_server_binary())+ except Exception: # noqa: BLE001 - an unavailable fallback cannot be planned+ return False+++def resolved_backend_for_model(model_name: str) -> str:+ """Backend a fresh operation for ``model_name`` would actually select."""+ raw = _raw_backend()+ forced = _forced_backends.get(model_name)+ key = forced or (_resolve_auto_for_model(model_name) if raw in _AUTO_ALIASES else raw)+ if key in _ST_ALIASES and not sentence_transformers_runtime_available():+ # Match _build_st_backend_or_fallback before Settings commits an+ # ST-only pending download. Without a real llama binary ST remains the+ # only possible plan, and its eventual error is more useful than a+ # fabricated GGUF destination.+ if _llama_server_runtime_available():+ key = "llama-server"+ if key in _LLAMA_ALIASES:+ return "llama-server"+ if key in _ST_ALIASES:+ return "sentence-transformers"+ raise ValueError(+ f"Unknown RAG_EMBED_BACKEND={config.EMBED_BACKEND!r}; expected "+ "'auto', 'sentence-transformers' or 'llama-server'"+ )++def _try_make_llama_backend():"""A llama-server GGUF embedding backend if its binary is present, else None.Construction is lazy -- no server starts until warm."""@@ -600,17 +837,21 @@ def _try_make_llama_backend():return LlamaServerBackend()-def _build_st_backend_or_fallback():+def _build_st_backend_or_fallback(model_name: str | None = None):"""Build the ST backend, probing it by loading the model now. If the proberaises (no torch, CUDA mismatch, bad wheel) and the GGUF llama-server embedderis available, fall back to it. The probe runs before any vector is produced, so- this never mixes spaces. Re-raises if no embedder can start."""+ this never mixes spaces. Re-raises if no embedder can start.++ ``model_name`` is the model the caller pinned. Warming ``None`` reads the live+ setting, so a job pinned to A probed B once Settings moved, failing the valid+ A job before its first encode."""backend = _SentenceTransformersBackend()try:- backend.warm(model_name = None)+ backend.warm(model_name = model_name)return backend- except UnsafeEmbeddingModelError:- raise # a security block must hard-fail, not fall back to llama-server+ except (UnsafeEmbeddingModelError, EmbeddingModelDownloadRequiredError):+ raise # policy failures must hard-fail, not change backend/downloadexcept Exception as st_err: # noqa: BLE001 - any ST/torch import or load failurefallback = _try_make_llama_backend()if fallback is None:@@ -623,12 +864,14 @@ def _build_st_backend_or_fallback():return fallback-def _switch_to_llama_fallback(err):+def _switch_to_llama_fallback(err, model_name: str | None = None):"""An ST encode failed at runtime even though the model had loaded. Swap theprocess embedder to llama-server so every later encode stays in one space, andreturn it (None if no binary). Vectors written before the swap were ST, so anyKB already embedded with ST should be reindexed."""global _backend, _backend_key+ failed_model = model_name or config.effective_embedding_model()+ old = Nonewith _backend_lock:if not isinstance(_backend, _SentenceTransformersBackend):return _backend # another thread already swapped (or was never ST)@@ -641,45 +884,187 @@ def _switch_to_llama_fallback(err):"was already embedded with sentence-transformers.",err,)- _backend = fallback- _backend_key = (config.EMBED_BACKEND or "auto").strip().lower()- return fallback+ old, _backend = _backend, fallback+ _forced_backends[failed_model] = "llama-server"+ _backend_key = _backend_cache_key(_raw_backend(), "llama-server")+ # The failed ST wrapper is no longer published, but its module-level model+ # would otherwise survive even a later unload of the llama replacement.+ _dispose_replaced_backend(old, fallback)+ return fallback++def _raw_backend() -> str:+ return (config.EMBED_BACKEND or "auto").strip().lower()-def _get_backend():++def sentence_transformers_fallback_allowed(model_name: str | None = None) -> bool:+ """Whether a resolved ST plan can actually be selected for a new model.++ An explicit llama configuration ignores the per-model stored backend, and+ a runtime ST failure deliberately pins llama until unload. In either state,+ offering safetensors would save a model the first index cannot load.+ """+ raw = _raw_backend()+ model = model_name or config.effective_embedding_model()+ if _forced_backends.get(model) in _LLAMA_ALIASES:+ return False+ return raw in _AUTO_ALIASES or raw in _ST_ALIASES+++def _current_backend_key() -> str:+ """The cache key the backend in use should carry right now. Tests that install a+ stub backend set ``_backend_key`` from this so it is not rebuilt under them."""+ raw = _raw_backend()+ forced = _forced_backends.get(config.effective_embedding_model())+ if forced:+ return _backend_cache_key(raw, forced)+ key = _resolve_auto_for_model() if raw in _AUTO_ALIASES else raw+ return _backend_cache_key(raw, key)+++def _backend_cache_key(raw: str, key: str) -> str:+ """Cache key for a built backend. It carries the RESOLVED choice, not just the+ raw config, so saving a model that needs the other backend rebuilds instead of+ serving the one already built for the previous model."""+ return f"{raw}\x00{key}"+++def _dispose_replaced_backend(old, new = None) -> None:+ """Release resources owned by a backend that is no longer published."""+ if old is None or old is new:+ return+ if isinstance(old, _SentenceTransformersBackend):+ # Two ST wrappers share the module-level model. A replacement ST was+ # already warmed against the new name, so clearing it here would discard+ # the model we just selected.+ if not isinstance(new, _SentenceTransformersBackend):+ _release_st_model()+ return+ shutdown = getattr(old, "_shutdown", None)+ if callable(shutdown):+ try:+ shutdown()+ except Exception: # noqa: BLE001 - replacement is already selected+ logger.warning("replaced embedding backend shutdown failed", exc_info = True)+++def _get_backend(model_name: str | None = None):"""The process-wide embedding backend for ``config.EMBED_BACKEND``, built once.- Cached by the raw config value, so ``auto`` detection runs only on a miss and a- config change rebuilds it."""+ Cached by the resolved choice, so ``auto`` detection runs only on a miss and a+ config or saved-model change rebuilds it.++ ``model_name`` is the model the caller is embedding for, defaulting to the live+ setting. A job pins its model once and passes it down, and per-model stored+ backends mean two models can resolve differently: reading the setting here+ instead would let a Settings change mid-job build the NEW model's backend while+ ``encode_with_identity`` goes on labelling the vectors with the pinned one.+ """global _backend, _backend_key- raw = (config.EMBED_BACKEND or "auto").strip().lower()+ raw = _raw_backend()+ old = None+ new = Nonewith _backend_lock:- if _backend is not None and _backend_key == raw:+ model = model_name or config.effective_embedding_model()+ forced = _forced_backends.get(model)+ key = forced or (_resolve_auto_for_model(model) if raw in _AUTO_ALIASES else raw)+ if _backend is not None and _backend_key == _backend_cache_key(raw, key):return _backend- key = _resolve_auto() if raw in _AUTO_ALIASES else raw+ old = _backendif key in _ST_ALIASES:- _backend = _build_st_backend_or_fallback()+ new = _build_st_backend_or_fallback(model)elif key in _LLAMA_ALIASES:# Imported lazily so the ST path never imports llama plumbing.from .embed_llama_server import LlamaServerBackend- _backend = LlamaServerBackend()+ new = LlamaServerBackend()else:raise ValueError(f"Unknown RAG_EMBED_BACKEND={config.EMBED_BACKEND!r}; expected ""'auto', 'sentence-transformers' or 'llama-server'")- _backend_key = raw- return _backend+ _backend = new+ if key in _ST_ALIASES and _is_llama_backend(new):+ # The ST warm probe fell back before producing vectors. Pin that+ # actual backend for this model, but let a different model retry ST.+ key = "llama-server"+ _forced_backends[model] = key+ _backend_key = _backend_cache_key(raw, key)+ # A llama shutdown can wait for an in-flight encode, so keep that wait out+ # of the global publication lock. New callers already see ``new``.+ _dispose_replaced_backend(old, new)+ return newdef _reset_backend() -> None:"""Drop the cached backend (test teardown / re-init)."""global _backend, _backend_keywith _backend_lock:+ _forced_backends.clear()_backend = None_backend_key = None-def active_backend_is_llama() -> bool:+def backend_is_loaded(model_name: str | None = None) -> bool:+ """Whether ``model_name`` is resident, or any embedder when omitted.++ Deliberately lock-free: ``_backend_lock`` and ``_lock`` are both held across a+ whole model load, so taking either here made GET, PUT, reset and unload wait it+ out. Both reads are single attribute loads, and the pre- or post-load value is+ equally true for "is something resident right now".+ """+ backend = _backend+ if backend is None:+ # No published backend does not mean nothing is loaded: an ST wrapper+ # retired by an unload that lands between _get_backend() and its encode+ # reloads the module-level model with nothing to publish. Answering False+ # stranded those weights, since release_backend returns on the same test.+ if model_name is None:+ return _model is not None+ return _model is not None and _name == model_name+ if model_name is None:+ # A llama backend whose process is gone is not resident, whichever model+ # was asked about.+ if _is_llama_backend(backend):+ try:+ return bool(backend._process_alive())+ except Exception: # noqa: BLE001 - a status probe must never block settings+ return False+ return True+ if isinstance(backend, _SentenceTransformersBackend):+ return _model is not None and _name == model_name+ if _is_llama_backend(backend):+ try:+ # The object keeps _model_repo after the subprocess exits or is+ # reaped, so the repo match alone would call a dead server resident.+ if not backend._process_alive():+ return False+ return backend._model_repo == config.effective_gguf_repo_for_embedding_model(model_name)+ except Exception: # noqa: BLE001 - a status probe must never block settings+ return False+ return False+++def release_backend() -> bool:+ """Drop the embedder and stop its llama-server, if one is running. Returns+ whether anything was released.++ Safe mid-ingestion: the next embed rebuilds, and the llama backend's own POST+ retry already covers a server that went away under it."""+ global _backend, _backend_key+ with _backend_lock:+ # Unload is an explicit fresh start, so a past runtime fallback stops pinning+ # the choice and the saved model picks its backend again.+ _forced_backends.clear()+ backend, _backend, _backend_key = _backend, None, None+ if backend is None:+ # Nothing published, but the module-level model can still be there (see+ # backend_is_loaded). Freeing it here is what keeps that leak from being+ # permanent; a no-op when nothing is resident.+ return _release_st_model()+ _dispose_replaced_backend(backend)+ return True+++def active_backend_is_llama(model_name: str | None = None) -> bool:"""True when this process actually embeds via the llama-server (GGUF) backend.Reflects the ACTUAL built backend once one exists: an ``auto`` install that@@ -687,9 +1072,13 @@ def active_backend_is_llama() -> bool:runtime (``_build_st_backend_or_fallback`` on a torch/CUDA load failure, or``_switch_to_llama_fallback`` on an encode failure) loads only inert GGUF, socallers gating on the ST pickle must see llama here. Before any backend is- built, defers to the resolver (``auto`` -> ``_resolve_auto()``, else the raw- key) exactly as a fresh process would. Never raises: a backend probe must not- block saving a model."""+ built, defers to the resolver (``auto`` -> ``_resolve_auto_for_model()``, else+ the raw key) exactly as a fresh process would.++ ``model_name`` names the model to resolve for, defaulting to the live setting.+ A caller embedding under a model pinned for the length of a job passes it, so+ the answer cannot drift when the setting changes underneath that job. Never+ raises: a backend probe must not block saving a model."""try:with _backend_lock:backend = _backend@@ -704,7 +1093,7 @@ def active_backend_is_llama() -> bool:return Falsereturn isinstance(backend, LlamaServerBackend)raw = (config.EMBED_BACKEND or "auto").strip().lower()- key = _resolve_auto() if raw in _AUTO_ALIASES else raw+ key = _resolve_auto_for_model(model_name) if raw in _AUTO_ALIASES else rawreturn key in _LLAMA_ALIASESexcept Exception: # noqa: BLE001 - a backend probe must never block savingreturn False@@ -713,11 +1102,43 @@ def active_backend_is_llama() -> bool:def _identity(is_llama: bool, name: str) -> str:if is_llama:return config.embedding_identity(- "llama-server", name, gguf_repo = config.gguf_repo_for_embedding_model(name)+ "llama-server",+ name,+ gguf_repo = config.effective_gguf_repo_for_embedding_model(name),)return config.embedding_identity("sentence-transformers", name)+def _identity_backend_is_llama(name: str) -> bool:+ """Backend the next encode for ``name`` will use.++ The security-facing active-backend probe deliberately reports a resident+ backend even when Settings has just selected another one. Identity prediction+ is different: ``_get_backend`` will replace a resident backend whose cache key+ no longer matches the stored per-model resolution, so admission/deduplication+ must predict that replacement before the first encode happens.++ ``name`` is threaded into the probe rather than left to default: it may be a+ model pinned for the length of one job (a linked-folder reconcile resolves the+ model once and embeds every file under it), and re-reading the live setting per+ file would let a Settings change mid-job tag two files in one folder with two+ different identities.+ """+ try:+ raw = _raw_backend()+ with _backend_lock:+ backend = _backend+ cached_key = _backend_key+ forced = _forced_backends.get(name)+ resolved = forced or (_resolve_auto_for_model(name) if raw in _AUTO_ALIASES else raw)+ expected_key = _backend_cache_key(raw, resolved)+ if backend is None or cached_key == expected_key:+ return active_backend_is_llama(name)+ return resolved in _LLAMA_ALIASES+ except Exception: # noqa: BLE001 - identity prediction must not block ingestion+ return active_backend_is_llama(name)++def embedding_identity(model_name: str | None = None) -> str:"""Identity of the vectors this process produces right now.@@ -726,7 +1147,8 @@ def embedding_identity(model_name: str | None = None) -> str:companion with its own pooling, and this process can switch to it at runtime. Twospaces under one label is an index that answers with the wrong documents and saysnothing about it."""- return _identity(active_backend_is_llama(), model_name or config.effective_embedding_model())+ name = model_name or config.effective_embedding_model()+ return _identity(_identity_backend_is_llama(name), name)def _is_llama_backend(backend) -> bool:@@ -761,7 +1183,7 @@ def encode_with_identity(def warm(model_name: str | None = None) -> None:"""Eagerly load the embedder so the first real request isn't slow."""- _get_backend().warm(model_name = model_name)+ _get_backend(model_name).warm(model_name = model_name)def encode(@@ -770,17 +1192,66 @@ def encode(model_name: str | None = None,normalize: bool = True,):- """Embed texts into an (N, dim) float32 numpy array."""- backend = _get_backend()+ """Embed texts into an (N, dim) float32 numpy array.++ An explicit unload can retire the llama backend between resolving it and using+ it, so that one lifecycle failure reacquires the newly published backend, the+ same way ``token_counter`` does for a counter held across chunks. Without it+ ``release_backend`` fails the in-flight document rather than rebuilding for it.+ """+ backend = _get_backend(model_name)_served_by.backend = backend- return backend.encode(texts, model_name = model_name, normalize = normalize)+ try:+ return backend.encode(texts, model_name = model_name, normalize = normalize)+ except RuntimeError:+ if not (_is_llama_backend(backend) and getattr(backend, "_closed", False)):+ raise+ replacement = _get_backend(model_name)+ if replacement is backend:+ raise RuntimeError("llama-server embedding backend was unloaded")+ _served_by.backend = replacement+ return replacement.encode(texts, model_name = model_name, normalize = normalize)def dim(model_name: str | None = None) -> int:"""Embedding dimension for the (loaded) model."""- return _get_backend().dim(model_name = model_name)+ return _get_backend(model_name).dim(model_name = model_name)def token_counter(model_name: str | None = None) -> Callable[[str], int]:- """Callable counting tokens with the embedder's own tokenizer."""- return _get_backend().token_counter(model_name = model_name)+ """Callable counting tokens with the embedder's own tokenizer.++ Chunking keeps this callable for the whole document. An explicit unload can+ retire its llama backend between two calls, so lazily reacquire the newly+ published backend only for that precise lifecycle failure. Other tokenizer+ errors still propagate unchanged.+ """+ backend = _get_backend(model_name)+ state = (backend, backend.token_counter(model_name = model_name))+ counter_lock = threading.Lock()++ def _count(text: str) -> int:+ nonlocal state+ served_backend, served_count = state+ try:+ return served_count(text)+ except RuntimeError:+ if not (+ _is_llama_backend(served_backend) and getattr(served_backend, "_closed", False)+ ):+ raise+ with counter_lock:+ # Another counting thread may already have replaced the retired+ # counter while this one was leaving it.+ if state[0] is served_backend:+ replacement = _get_backend(model_name)+ if replacement is served_backend:+ raise RuntimeError("llama-server embedding backend was unloaded")+ state = (+ replacement,+ replacement.token_counter(model_name = model_name),+ )+ retry = state[1]+ return retry(text)++ return _countdiff --git a/studio/backend/hub/utils/hf_cache_state.py b/studio/backend/hub/utils/hf_cache_state.pyindex 145ba1c6fc1..2f3cf101810 100644--- a/studio/backend/hub/utils/hf_cache_state.py+++ b/studio/backend/hub/utils/hf_cache_state.py@@ -521,12 +521,20 @@ def latest_snapshot_from_cache_path(return None-def _repo_dir_has_broken_snapshot_symlinks(repo_dir: Path) -> bool:- latest = latest_snapshot_dir(repo_dir)- if latest is None:- return False+def snapshot_has_broken_symlinks(snapshot: Path) -> bool:+ """Whether ``snapshot`` links to a blob that is not finalized.++ Scoped to one snapshot on purpose. A ``.incomplete`` blob under ``blobs/``+ belongs to whichever revision or scoped file set is fetching it, and the cache+ is shared, so its presence says nothing about the revision being validated.+ What does is a link this snapshot owns whose target is not there yet.++ Windows hydrates the cache with copies rather than links, so there is nothing+ to dangle: a half-fetched file is simply absent, which the payload inventory+ catches instead.+ """try:- for entry in latest.rglob("*"):+ for entry in snapshot.rglob("*"):if entry.is_symlink() and not entry.exists():return Trueexcept OSError:@@ -534,6 +542,13 @@ def _repo_dir_has_broken_snapshot_symlinks(repo_dir: Path) -> bool:return False+def _repo_dir_has_broken_snapshot_symlinks(repo_dir: Path) -> bool:+ latest = latest_snapshot_dir(repo_dir)+ if latest is None:+ return False+ return snapshot_has_broken_symlinks(latest)++def iter_repo_cache_dirs(repo_type: str,repo_id: str,diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 5391c970a65..a7d6d2dc6ff 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -6,10 +6,11 @@ import hashlibimport reimport threadingimport time+from contextvars import ContextVarfrom typing import Any, Literal, Optional, get_argsfrom urllib.parse import unquote, urlsplit-from fastapi import APIRouter, Depends, HTTPException, Request+from fastapi import APIRouter, Depends, Header, HTTPException, Requestfrom pydantic import BaseModel, ConfigDict, Field, StrictBool, ValidationError, field_validatorfrom auth.authentication import (@@ -22,7 +23,10 @@ from auth.storage import rotate_preview_link_secretfrom routes.provider_credentials import current_credential_write, require_ui_sessionfrom storage import credential_secrets-from core.rag.config import default_gguf_repo, effective_gguf_repo+from core.rag.config import (+ default_gguf_repo,+ effective_gguf_repo_for_embedding_model,+)from loggers import get_loggerfrom utils.utils import safe_error_detail, log_and_http_errorfrom utils.personalization_settings import (@@ -1788,6 +1792,10 @@ def update_openai_auto_switch_override(class EmbeddingModelPayload(BaseModel):embedding_model: str = Field(..., min_length = 1, max_length = MAX_EMBEDDING_MODEL_LENGTH)+ # The repo /resolve named, stored so the loader opens what was downloaded.+ gguf_repo: Optional[str] = Field(default = None, max_length = MAX_EMBEDDING_MODEL_LENGTH)+ # And the backend it needs, so a model with no GGUF is not sent to llama-server.+ backend: Optional[Literal["llama", "sentence-transformers"]] = None# Token for gated/private repos during verification (not stored).hf_token: Optional[str] = Field(default = None, max_length = 512)# Skip HF verification (offline installs, local paths HF can't see).@@ -1800,18 +1808,43 @@ class EmbeddingModelResponse(BaseModel):default_embedding_model: strdefault_embedding_gguf_repo: stris_custom: bool+ # Whether THIS model is held in memory right now, for the status line.+ loaded: bool = False+ # Whether ANY embedder is resident, for the Unload action: saving a new model+ # does not release the old one, so the selected model is the wrong question.+ backend_loaded: bool = Falsedef _embedding_model_response() -> EmbeddingModelResponse:+ model = get_rag_embedding_model()return EmbeddingModelResponse(- embedding_model = get_rag_embedding_model(),- embedding_gguf_repo = effective_gguf_repo(),+ embedding_model = model,+ embedding_gguf_repo = effective_gguf_repo_for_embedding_model(model),default_embedding_model = default_embedding_model(),default_embedding_gguf_repo = default_gguf_repo(),is_custom = get_stored_embedding_model() is not None,+ loaded = _embedder_is_loaded(model),+ backend_loaded = _any_embedder_is_loaded(),)+def _embedder_is_loaded(model: str) -> bool:+ from core.rag import embeddings+ try:+ return embeddings.backend_is_loaded(model)+ except Exception: # noqa: BLE001 - probe must never block reading settings+ return False+++def _any_embedder_is_loaded() -> bool:+ """Whether any embedder is resident, whichever model it belongs to."""+ from core.rag import embeddings+ try:+ return embeddings.backend_is_loaded()+ except Exception: # noqa: BLE001 - probe must never block reading settings+ return False++def _ambient_hf_token() -> Optional[str]:"""The HF token the loader would use (HF_TOKEN env or the cached login), so a gatedrepo is scanned rather than failing open. None if unavailable."""@@ -1822,8 +1855,29 @@ def _ambient_hf_token() -> Optional[str]:return None-def _llama_backend_active() -> bool:- """True when this install actually embeds via the llama-server (GGUF) backend.+def _model_names_gguf_repo(model: str) -> bool:+ """Whether ``model`` is a repo id naming GGUF weights, per the embedder's rule."""+ from core.rag import embeddings+ try:+ return embeddings._model_names_gguf_repo(model)+ except Exception: # noqa: BLE001 - a name test that cannot answer blocks nothing+ return False+++def _llama_runtime_available() -> bool:+ """Whether a llama-server binary this install can launch is present.++ Shares the embedder's own probe so the resolver and the loader cannot disagree+ about whether the backend exists."""+ from core.rag import embeddings+ try:+ return embeddings._llama_server_runtime_available()+ except Exception: # noqa: BLE001 - an unanswerable probe must not block saving+ return True+++def _llama_backend_active(model: str | None = None) -> bool:+ """Whether llama serves the active model, or would serve ``model`` if supplied.Delegates to the embeddings module so a runtime fallback fromsentence-transformers to llama-server (after a torch/CUDA load or encode@@ -1832,6 +1886,8 @@ def _llama_backend_active() -> bool:Before any backend is built this still reflects the resolver."""from core.rag import embeddingstry:+ if model is not None:+ return embeddings.resolved_backend_for_model(model) == "llama-server"return embeddings.active_backend_is_llama()except Exception: # noqa: BLE001 - backend probe must never block savingreturn False@@ -1855,11 +1911,16 @@ def _local_gguf_backend_error(model: str) -> str | None:None when not applicable. ``force`` skips this check like HF verification."""from pathlib import Path- if not Path(model).expanduser().is_dir():+ from utils.paths import normalize_path++ # Normalized as _resolve_local_gguf normalizes it, or a WSL drive-letter dir+ # reads as "not a directory" here and the 409 that would have explained it+ # never fires.+ if not Path(normalize_path(model)).expanduser().is_dir():return Nonefrom core.rag.embed_llama_server import LlamaServerBackend- if not _llama_backend_active():+ if not _llama_backend_active(model):return Nonetry:LlamaServerBackend._resolve_local_gguf(model)@@ -1883,27 +1944,28 @@ def _hf_gguf_backend_error(model: str, hf_token: Optional[str]) -> str | None:if Path(model).expanduser().exists():return None # local paths are handled by the local checks- if not _llama_backend_active():+ if not _llama_backend_active(model):return None- from core.rag import config as rag_config-- candidates = [model] if rag_config._names_gguf(model) else [f"{model}-GGUF", model]- try:- from huggingface_hub import list_repo_files- except Exception: # noqa: BLE001 - hub client unavailable: don't block saving+ candidates = _embedding_gguf_candidates(model)+ if _remote_embedding_gguf_plan(candidates, hf_token) is not None:return None- for candidate in candidates:- try:- files = list_repo_files(candidate, token = hf_token)- except Exception: # noqa: BLE001 - missing/gated repo: try next candidate- continue- if any(f.lower().endswith(".gguf") and "mmproj" not in f.lower() for f in files):- return None+ if _search_hub_for_gguf(model, hf_token) is not None:+ return None+ # Safetensors on sentence-transformers is a working answer, not a failure.+ if (+ _sentence_transformers_fallback_allowed(model)+ and _safetensors_plan(model, hf_token) is not None+ ):+ return None+ return _no_embedding_weights_error(candidates)+++def _no_embedding_weights_error(candidates: list[str]) -> str:+ """Error after the caller has already exhausted GGUF and ST resolution."""checked = " or ".join(repr(c) for c in candidates)return (- f"No GGUF weights found in {checked}, but this install embeds with the "- "llama-server backend which requires them. Pick a model with a GGUF "- "companion repo or GGUF files in the repo itself."+ f"No GGUF weights found in {checked}, and no safetensors to fall back to. "+ "Only the model's own publisher is used as a source.")@@ -1914,6 +1976,611 @@ def get_embedding_model(return _embedding_model_response()+class EmbeddingModelResolveResponse(BaseModel):+ embedding_model: str+ backend: Literal["llama", "sentence-transformers"]+ # Repo the picker hands the download manager, and the files to take from it.+ # Split GGUF plans contain every shard in the selected family.+ # Both None when nothing needs fetching, or when ``error`` is set.+ download_repo: Optional[str] = None+ files: Optional[list[str]] = None+ cached: bool = False+ size_bytes: Optional[int] = None+ error: Optional[str] = None+++def _embedding_gguf_candidates(model: str) -> list[str]:+ """Repos the loader would try for ``model``'s GGUF, in its order."""+ from core.rag import config as rag_config++ # An env override is the loader's only source. A stored mirror from an older+ # selection must not outrank it, and discovery must not replace it later.+ if rag_config.gguf_repo_is_explicit():+ return rag_config.gguf_repo_candidates(model)+ try:+ from utils.embedding_model_settings import get_stored_gguf_repo+ stored = get_stored_gguf_repo(model)+ except Exception: # noqa: BLE001 - resolver still has derived candidates+ stored = None+ return list(+ dict.fromkeys([*([stored] if stored else []), *rag_config.gguf_repo_candidates(model)])+ )+++# A GGUF conversion must come from the same owner as the model. Repo names are+# not proof of provenance, so an unsloth/ pick only ever downloads from unsloth.+_GGUF_MIRROR_SEARCH_LIMIT = 25+_GGUF_LIST_DEADLINE_S = 20.0+_EMBEDDING_RESOLVE_DEADLINE: ContextVar[float | None] = ContextVar(+ "embedding-resolve-deadline", default = None+)+++def _call_with_embedding_resolve_budget(fn, *, name: str):+ """Run one remote probe inside the resolution's single time budget."""+ deadline = _EMBEDDING_RESOLVE_DEADLINE.get()+ timeout = (+ _GGUF_LIST_DEADLINE_S+ if deadline is None+ else max(0.0, min(_GGUF_LIST_DEADLINE_S, deadline - time.monotonic()))+ )+ if timeout <= 0:+ raise TimeoutError("embedding model resolution deadline expired")+ from utils.utils import call_with_deadline++ return call_with_deadline(fn, timeout, name = name)+++def _with_embedding_resolve_budget(fn):+ """Give one GET/PUT resolution a deadline shared by every Hub fallback."""++ @functools.wraps(fn)+ def _wrapped(*args, **kwargs):+ if _EMBEDDING_RESOLVE_DEADLINE.get() is not None:+ return fn(*args, **kwargs)+ marker = _EMBEDDING_RESOLVE_DEADLINE.set(time.monotonic() + _GGUF_LIST_DEADLINE_S)+ try:+ return fn(*args, **kwargs)+ finally:+ _EMBEDDING_RESOLVE_DEADLINE.reset(marker)++ return _wrapped+++def _list_repo_files_bounded(repo: str, hf_token: Optional[str]) -> list[str]:+ """List a Hub repo without letting a blackholed route pin Settings forever."""+ from huggingface_hub import list_repo_files+ return _call_with_embedding_resolve_budget(+ lambda: list_repo_files(repo, token = hf_token),+ name = "embed-settings-repo-listing",+ )+++def _gguf_conversion_name_matches(hit_name: str, base: str) -> bool:+ """Whether a search hit names a conversion of exactly ``base``.++ Prefix matching is unsafe (``foo`` must never resolve to ``foo-bar-GGUF``).+ The Hub filter already requires GGUF; this check accepts only the common+ conversion suffix spellings and the exact model name.+ """+ name = hit_name.casefold()+ base = base.casefold()+ return name == base or name in {f"{base}-gguf", f"{base}_gguf", f"{base}.gguf"}+++def _gguf_files_for_pick(names: list[str], picked: str) -> Optional[list[str]]:+ """The complete downloadable file family for a picked GGUF.++ llama-server opens split siblings implicitly, so a single selected shard is+ not a usable plan. Incomplete published families are rejected. Deferred to the+ loader so the plan offered here and the transfer it performs name one set.+ """+ from core.rag.embed_llama_server import LlamaServerBackend+ return LlamaServerBackend._split_family(names, picked)+++def _pick_downloadable_gguf(names: list[str]) -> Optional[list[str]]:+ """Pick the loader's preferred GGUF, skipping torn split families."""+ from core.rag.embed_llama_server import LlamaServerBackend++ _picked, files = LlamaServerBackend._pick_complete_gguf(names)+ return files or None+++def _search_hub_for_gguf(model: str, hf_token: Optional[str]) -> Optional[tuple[str, list[str]]]:+ """``(repo, files)`` for a GGUF conversion of ``model`` published by the same+ owner under a name the -GGUF candidates do not cover.++ Same owner only: a third party's "Qwen3-Embedding-8B-GGUF" is an unverified+ re-upload, and picking unsloth/X must download unsloth's own weights."""+ from core.rag import config as rag_config++ # The loader cannot open a discovered mirror while an explicit repo override+ # is active, so returning one would create a download that can never satisfy it.+ if rag_config.gguf_repo_is_explicit():+ return None+ owner, _, name = model.rpartition("/")+ if not owner:+ return None+ try:+ from huggingface_hub import HfApi+ except Exception: # noqa: BLE001 - hub client unavailable+ return None+ base = rag_config._QUANT_SUFFIX_RE.sub("", name).lower()+ if not base:+ return None+ try:+ hits = _call_with_embedding_resolve_budget(+ lambda: list(+ HfApi().list_models(+ search = base,+ author = owner,+ filter = ["gguf"],+ sort = "downloads",+ limit = _GGUF_MIRROR_SEARCH_LIMIT,+ token = hf_token,+ )+ ),+ name = "embed-settings-model-search",+ )+ except Exception: # noqa: BLE001 - offline or rate limited+ return None+ for hit in hits:+ hit_owner, _, hit_name = hit.id.rpartition("/")+ if hit_owner.casefold() != owner.casefold() or not _gguf_conversion_name_matches(+ hit_name, base+ ):+ continue+ try:+ files = _pick_downloadable_gguf(_list_repo_files_bounded(hit.id, hf_token))+ except Exception: # noqa: BLE001 - unreadable listing: try the next+ continue+ if files:+ return hit.id, files+ return None+++def _cached_embedding_gguf(candidates: list[str], *, require_variant: bool) -> Optional[str]:+ """First candidate already holding a usable GGUF on disk. No network."""+ from core.rag.embed_llama_server import LlamaServerBackend++ for candidate in candidates:+ try:+ if LlamaServerBackend._resolve_cached_gguf(candidate, require_variant = require_variant):+ return candidate+ except Exception: # noqa: BLE001 - a bad cache entry is just a miss+ continue+ return None+++def _cached_embedding_gguf_files(repo: str, files: list[str]) -> bool:+ """Whether the exact resolved GGUF family is complete in ``repo``'s snapshot."""+ from pathlib import Path, PurePosixPath+ from core.rag.embed_llama_server import LlamaServerBackend++ try:+ snapshot = LlamaServerBackend._cached_snapshot_dir(repo)+ if snapshot is None or not files:+ return False+ for name in files:+ path = PurePosixPath(name)+ if (+ path.is_absolute()+ or ".." in path.parts+ or not (snapshot / Path(*path.parts)).is_file()+ ):+ return False+ return True+ except Exception: # noqa: BLE001 - an unreadable cache is a miss+ return False+++def _remote_embedding_gguf_plan(+ candidates: list[str], hf_token: Optional[str]+) -> Optional[tuple[str, list[str]]]:+ """``(repo, files)`` for the first candidate publishing a usable GGUF family."""+ for candidate in candidates:+ try:+ names = _list_repo_files_bounded(candidate, hf_token)+ except Exception: # noqa: BLE001 - missing/gated repo: try the next+ continue+ try:+ files = _pick_downloadable_gguf(names)+ except Exception: # noqa: BLE001 - unreadable listing: try the next+ files = None+ if files:+ return candidate, files+ return None+++# safetensors first: a repo carrying both formats would otherwise be fetched twice.+_ST_WEIGHT_SUFFIXES = (".safetensors", ".bin")+++def _st_backend_available() -> bool:+ """Whether sentence-transformers could actually run here. A GGUF-only install+ has no torch, so the safetensors fallback is not on offer there."""+ try:+ from core.rag import embeddings+ return embeddings.sentence_transformers_runtime_available()+ except Exception: # noqa: BLE001 - a broken import path is a no+ return False+++def _is_st_weight_name(basename: str) -> bool:+ """Whether a filename is a checkpoint, not just something ending in a suffix.++ Shared with the loader so the plan and the cache check cannot disagree."""+ from utils.utils import is_st_weight_name+ return is_st_weight_name(basename)+++def _st_weight_source(model: str, hf_token: Optional[str]) -> Optional[tuple[str, list[str]]]:+ """``(repo, weight files)`` for the repo an ST load of ``model`` would open.++ A slashless name such as ``all-MiniLM-L6-v2`` resolves under the+ ``sentence-transformers/`` namespace, which is what the loader's own+ ``st_repo_id_candidates`` encodes. Probing only the literal id refused the+ alias outright and a forced save then pinned it cache-only.+ """+ from utils.utils import st_repo_id_candidates++ for candidate in st_repo_id_candidates(model) or [model]:+ files = _st_weight_files(candidate, hf_token)+ if files:+ return (candidate, files)+ return None+++def _st_weight_files(model: str, hf_token: Optional[str]) -> Optional[list[str]]:+ """The repo's own weight files, or None when it publishes none we can load."""+ try:+ files = _list_repo_files_bounded(model, hf_token)+ except Exception: # noqa: BLE001 - missing/gated repo or offline+ return None+ for suffix in _ST_WEIGHT_SUFFIXES:+ weights = [+ filename+ for filename in files+ if filename.rsplit("/", 1)[-1].lower().endswith(suffix)+ and _is_st_weight_name(filename.rsplit("/", 1)[-1])+ ]+ if weights:+ return weights+ return None+++def _cached_snapshot_has_st_weights(model: str) -> bool:+ """Whether the cached snapshot holds a checkpoint ST itself can open.++ ``hf_cache_snapshot_is_loadable`` counts ``.gguf``, which is right for the+ llama backend and wrong here: a cached GGUF-only repo would come back ready+ with no checkpoint ST can load. No network."""+ try:+ from utils.utils import snapshot_has_st_weights+ return snapshot_has_st_weights(model)+ except Exception: # noqa: BLE001 - an unreadable cache is not a proof of weights+ return False+++def _cached_st_source(model: str):+ """``(repo id, snapshot dir)`` the cached ST weights for ``model`` came from.++ The same predicate as ``_cached_snapshot_has_st_weights``, keeping the repo it+ matched under rather than reducing it to a yes: for a slashless alias that repo+ is the ``sentence-transformers/`` one, and the PUT verifies and scans it."""+ try:+ from utils.utils import cached_st_source+ return cached_st_source(model)+ except Exception: # noqa: BLE001 - an unreadable cache is not a proof of weights+ return None+++def _cached_st_weight_names(model: str) -> list[str]:+ """Snapshot-relative names of the ST weights already on disk for ``model``."""+ try:+ from utils.utils import hf_cache_snapshot_dir++ snapshot = hf_cache_snapshot_dir(model)+ if snapshot is None:+ return []+ return sorted(+ str(path.relative_to(snapshot))+ for path in snapshot.rglob("*")+ if _is_st_weight_name(path.name) and path.is_file()+ )+ except Exception: # noqa: BLE001 - the plan stands without a file list+ return []+++def _safetensors_plan(model: str, hf_token: Optional[str]) -> Optional[tuple[str, list[str]]]:+ """``(repo, files)`` for running ``model`` on sentence-transformers instead.++ An embedder with no GGUF still works from its own safetensors, for about 1 GB+ more memory, which beats refusing the model or pulling a stranger's conversion."""+ if not _st_backend_available():+ return None+ # A complete local snapshot is the same proof the listing gives, and works+ # offline, where the listing fails and a downloaded model became unselectable.+ from utils.utils import cached_st_repo++ # The repo the snapshot is actually filed under: a slashless name caches under+ # sentence-transformers/, and naming the literal id sends the download manager+ # at a repo that usually does not exist.+ cached_repo = cached_st_repo(model)+ if cached_repo:+ return (cached_repo, _cached_st_weight_names(cached_repo))+ return _st_weight_source(model, hf_token)+++def _sentence_transformers_fallback_allowed(model: str) -> bool:+ """Whether a newly selected model can actually be served by ST in this process."""+ try:+ from core.rag import embeddings+ return embeddings.sentence_transformers_fallback_allowed(model)+ except Exception: # noqa: BLE001 - an unknown backend is not a safe fallback+ return False+++def _hf_files_size(repo: str, files: list[str], hf_token: Optional[str]) -> Optional[int]:+ """Total bytes of ``files`` in ``repo``, for the confirm dialog. None when the+ hub does not say; the dialog has copy for that."""+ try:+ from huggingface_hub import model_info++ info = _call_with_embedding_resolve_budget(+ lambda: model_info(repo, files_metadata = True, token = hf_token),+ name = "embed-settings-file-size",+ )+ wanted = set(files)+ total = sum(+ sibling.size or 0 for sibling in (info.siblings or []) if sibling.rfilename in wanted+ )+ return total or None+ except Exception: # noqa: BLE001 - size is advisory, never a blocker+ return None+++def _hf_snapshot_size(repo: str, hf_token: Optional[str]) -> Optional[int]:+ """Bytes the model download worker will fetch for a full snapshot."""+ try:+ from huggingface_hub import model_info+ from hub.utils.snapshot_filters import snapshot_download_size++ info = _call_with_embedding_resolve_budget(+ lambda: model_info(repo, files_metadata = True, token = hf_token),+ name = "embed-settings-snapshot-size",+ )+ total = snapshot_download_size(info.siblings or [])+ return total or None+ except Exception: # noqa: BLE001 - size is advisory, never a blocker+ return None+++def _local_sentence_transformer_is_present(model: str) -> bool:+ """Whether ``model`` is an existing local path ST can open directly."""+ try:+ from pathlib import Path+ from utils.paths import is_local_path, normalize_path++ if not is_local_path(model):+ return False+ p = Path(normalize_path(model)).expanduser()+ # ST cannot open a .gguf. Falling through reaches the no-loadable-weights+ # error rather than reporting it ready and failing at the first index.+ if p.is_file() and p.suffix.lower() == ".gguf":+ return False+ if not p.exists():+ return False+ # A directory has to hold a checkpoint, not merely exist: modules.json+ # alone also passes is_embedding_model's local-path check.+ if not p.is_dir():+ # SentenceTransformer takes a directory or a repo id, never a bare+ # checkpoint file.+ return False+ if not any(_is_st_weight_name(child.name) and child.is_file() for child in p.rglob("*")):+ return False+ # And a WHOLE one: half a shard family, or a module modules.json declares+ # and the directory lacks, read as ready and failed at the first index.+ # Same completeness test a Hub snapshot gets, so a local copy of a model+ # is judged the way the downloaded one is.+ from utils.utils import checkpoint_directory_is_complete++ return checkpoint_directory_is_complete(p)+ except Exception: # noqa: BLE001 - filesystem oddity is a cache miss+ return False+++@_with_embedding_resolve_budget+def _resolve_embedding_model_plan(+ resolved: str, token: Optional[str]+) -> EmbeddingModelResolveResponse:+ """Server-owned artifact/backend plan shared by GET and PUT.++ The PUT must not persist a client assertion that the GET never validated,+ so both routes use this exact resolver.+ """+ # Resolve for the model being selected, not the backend still serving the+ # previous model. A model-scoped runtime fallback must not force the next+ # selection onto llama-server.+ on_llama = _llama_backend_active(resolved)+ backend: Literal["llama", "sentence-transformers"] = (+ "llama" if on_llama else "sentence-transformers"+ )++ if not on_llama:+ # A valid local SentenceTransformer path is already the artifact; it is+ # not a Hub repo for the download manager to fetch.+ if _local_sentence_transformer_is_present(resolved):+ return EmbeddingModelResolveResponse(+ embedding_model = resolved, backend = backend, cached = True+ )+ # The alias-aware predicate alone: it already pairs the ST file family with+ # the loadable check PER CANDIDATE. Conjoining the generic one asked it+ # about whichever cache directory matched first, so a stale literal entry+ # beside a complete sentence-transformers/ snapshot reported uncached.+ # The repo the cache hit came from, not just whether there was one: the+ # PUT verifies and scans whatever this names, and for a slashless alias+ # that is the sentence-transformers/ candidate. The literal id sent both+ # at a repo that usually does not exist, 409ing a model already on disk.+ cached_source = _cached_st_source(resolved)+ cached = cached_source is not None+ source = None if cached else _st_weight_source(resolved, token)+ if not cached and source is None:+ # is_embedding_model gates on tags, so a feature-extraction repo+ # publishing no loadable checkpoint reaches here and would be offered+ # as a download ST cannot open. The llama-to-ST fallback already+ # proves the weights exist; this path did not.+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ error = (+ f"No sentence-transformers weights found in {resolved!r}. "+ "The repository publishes no checkpoint this backend can load."+ ),+ )+ # The repo that actually publishes the weights, which for a slashless+ # alias is the sentence-transformers/ one, not the literal name. Same+ # question whether the answer came from the cache or from the Hub.+ if cached:+ download_repo = cached_source[0]+ elif source is None:+ download_repo = resolved+ else:+ download_repo = source[0]+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ download_repo = download_repo,+ cached = cached,+ size_bytes = None if cached else _hf_snapshot_size(download_repo, token),+ )++ local_gguf = _resolves_as_local_gguf(resolved)+ # Routing a model here does not make the backend runnable: without a binary+ # the plan is advertised as valid and the transfer persisted, and the first+ # warm fails in _resolve_binary. Scoped to models only llama can serve, since+ # one with safetensors still has the usable ST fallback further down.+ llama_only = (+ local_gguf+ or _model_names_gguf_repo(resolved)+ # An explicit llama policy (or a runtime pin) refuses the safetensors+ # fallback for every model, not only GGUF-named ones, so an ordinary repo+ # id is just as unservable here without a binary.+ or not _sentence_transformers_fallback_allowed(resolved)+ )+ if llama_only and not _llama_runtime_available():+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ error = (+ f"{resolved!r} can only be embedded by the llama-server backend "+ "here, and no llama-server binary was found. Install llama.cpp or "+ "set LLAMA_SERVER_PATH / UNSLOTH_LLAMA_CPP_PATH."+ ),+ )++ # A local .gguf (file or folder) is already the artifact; nothing to fetch.+ if local_gguf:+ return EmbeddingModelResolveResponse(embedding_model = resolved, backend = backend, cached = True)+ local_error = _local_gguf_backend_error(resolved)+ if local_error:+ return EmbeddingModelResolveResponse(+ embedding_model = resolved, backend = backend, error = local_error+ )++ candidates = _embedding_gguf_candidates(resolved)+ # Match the loader's online fast path exactly: only the preferred repo and+ # only the configured variant can suppress the download offer.+ cached_repo = _cached_embedding_gguf(candidates[:1], require_variant = True)+ if cached_repo:+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ download_repo = cached_repo,+ cached = True,+ )+ plan = _remote_embedding_gguf_plan(candidates, token) or _search_hub_for_gguf(resolved, token)+ if plan is None:+ # The loader's offline fallback accepts any complete cached quant from+ # any candidate only after its bounded online listing fails.+ cached_repo = _cached_embedding_gguf(candidates, require_variant = False)+ if cached_repo:+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ download_repo = cached_repo,+ cached = True,+ )+ # No GGUF from this publisher: run it on its own safetensors only when+ # configuration/runtime policy can actually select ST for this model.+ st_plan = (+ _safetensors_plan(resolved, token)+ if _sentence_transformers_fallback_allowed(resolved)+ else None+ )+ if st_plan is None:+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ # Every remote/cache/fallback probe above has already failed;+ # do not repeat the bounded Hub calls merely to format an error.+ error = _no_embedding_weights_error(candidates),+ )+ st_repo, _st_files = st_plan+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = "sentence-transformers",+ download_repo = st_repo,+ # Same alias-aware predicate, asked about the repo the plan named+ # rather than the alias the user typed.+ cached = _cached_snapshot_has_st_weights(st_repo),+ size_bytes = _hf_snapshot_size(st_repo, token),+ )+ repo, files = plan+ if _cached_embedding_gguf_files(repo, files):+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ download_repo = repo,+ files = files,+ cached = True,+ )+ return EmbeddingModelResolveResponse(+ embedding_model = resolved,+ backend = backend,+ download_repo = repo,+ files = files,+ size_bytes = _hf_files_size(repo, files, token),+ )++[email protected]("/embedding-model/resolve", response_model = EmbeddingModelResolveResponse)+def resolve_embedding_model(+ model: str,+ # Header, not a query param: keeps a gated-repo token out of URLs and logs.+ hf_token: Optional[str] = Header(None, alias = "X-Unsloth-HF-Token"),+ current_subject: str = Depends(get_current_subject),+) -> EmbeddingModelResolveResponse:+ """What saving ``model`` would need fetched, and whether it is already here.++ The picker calls this so it can offer the download up front instead of letting+ it happen invisibly at first index. ``error`` is the detail the PUT would+ refuse with, so the two cannot disagree about what is usable."""+ try:+ resolved = validate_embedding_model(model)+ except ValueError as exc:+ raise log_and_http_error(+ exc,+ 400,+ safe_error_detail(exc, fallback = "Invalid embedding model."),+ event = "settings.resolve_embedding_model_failed",+ log = logger,+ ) from exc+ token = (hf_token or "").strip() or None+ return _resolve_embedding_model_plan(resolved, token)++@router.put("/embedding-model", response_model = EmbeddingModelResponse)def update_embedding_model(payload: EmbeddingModelPayload, current_subject: str = Depends(get_current_subject)@@ -1942,17 +2609,40 @@ def update_embedding_model(# Offline, both the Hub malware scan and the is-embedding check are unreachable and degrade# to the local cache below; capture the state once.local_only_load = hf_env_offline()+ # Resolve again server-side. The client fields are only an optimistic echo+ # of GET /resolve; neither a repository nor a backend is trusted on its word.+ plan = _resolve_embedding_model_plan(model, hf_token)+ requested_repo = (payload.gguf_repo or "").strip() or None+ if payload.backend is not None and payload.backend != plan.backend:+ raise HTTPException(+ status_code = 400,+ detail = "The embedding backend no longer matches the server resolution. Resolve it again.",+ )+ if requested_repo is not None and requested_repo != plan.download_repo:+ raise HTTPException(+ status_code = 400,+ detail = "The embedding download repository was not validated for this model.",+ )+ destination_is_llama = plan.backend == "llama"+ # Verify and scan the repo the loader will actually open. A slashless alias+ # resolves under sentence-transformers/, so checking the literal name scanned a+ # repo that usually does not exist (failing open, or a forceable 409) or, worse,+ # a different top-level repo that does. Only the ST path can diverge: a llama+ # download_repo is the GGUF companion, which is not what is scanned here.+ verify_target = model+ if not destination_is_llama and plan.download_repo and plan.download_repo != model:+ verify_target = plan.download_repo# The env/default model needs no verification; saving it is a no-op override.# A local GGUF on the llama-server backend is accepted as-is: it is exactly# what the backend loads, and HF metadata cannot verify a local path.- is_local_gguf = _llama_backend_active() and _resolves_as_local_gguf(model)+ is_local_gguf = destination_is_llama and _resolves_as_local_gguf(model)# The pickle gate only matters for the sentence-transformers backend, which is what# deserializes pickles. On the llama-server backend the embedder loads GGUF files# (inert) from effective_gguf_repo(), so scanning the ST repo's pickle here would# wrongly reject a custom repo whose GGUF companion is clean; the GGUF availability# checks below cover that path instead.scan_st_pickle = (- model != default_embedding_model() and not is_local_gguf and not _llama_backend_active()+ model != default_embedding_model() and not is_local_gguf and not destination_is_llama)if scan_st_pickle:# Malware/pickle gate before we persist a repo the embedder later loads with@@ -1975,13 +2665,13 @@ def update_embedding_model(load_subdirs = tuple(dict.fromkeys((- *security_load_subdirs(model, scan_token),- *_st_module_subdirs(model, scan_token),+ *security_load_subdirs(verify_target, scan_token),+ *_st_module_subdirs(verify_target, scan_token),)))if evaluate_file_security(- model,+ verify_target,hf_token = scan_token,load_subdirs = load_subdirs,local_only_load = local_only_load,@@ -2007,8 +2697,8 @@ def update_embedding_model(# files, which rarely carry sentence-transformers metadata; verify the# GGUF is available (below) rather than the ST embedding-metadata gate,# which would wrongly 409 a valid online GGUF embedder.- gguf_named = _llama_backend_active() and rag_config._names_gguf(model)- if not gguf_named and not is_embedding_model(model, hf_token = hf_token):+ gguf_named = destination_is_llama and rag_config._names_gguf(model)+ if not gguf_named and not is_embedding_model(verify_target, hf_token = hf_token):# Offline, is_embedding_model can only confirm the ST layout (modules.json); a# transformers-native embedder (e.g. gte-modernbert) is unverifiable without Hub# metadata. If already cached and loadable, accept it rather than raising a 409 that@@ -2017,7 +2707,7 @@ def update_embedding_model(# Require a genuinely loadable cache (config + weights), not just a resolved refs/main,# so a metadata-only partial cache still gets the forceable 409.- offline_cached = local_only_load and hf_cache_snapshot_is_loadable(model)+ offline_cached = local_only_load and hf_cache_snapshot_is_loadable(verify_target)if not offline_cached:raise HTTPException(status_code = 409,@@ -2027,13 +2717,44 @@ def update_embedding_model("you may be offline)."),)- # The Hub GGUF probe (list_repo_files) can hang offline; skip it. Local check stays.- gguf_error = _local_gguf_backend_error(model)- if gguf_error is None and not local_only_load:- gguf_error = _hf_gguf_backend_error(model, hf_token)- if gguf_error:- raise HTTPException(status_code = 409, detail = gguf_error)- set_rag_embedding_model(model)+ # The shared resolver already applied the bounded listing and the exact+ # destination backend, so PUT and GET cannot disagree. Any plan error+ # counts, not just llama ones: is_embedding_model gates on tags, so a repo+ # with no loadable checkpoint passes it and would be persisted anyway.+ if plan.error:+ raise HTTPException(status_code = 409, detail = plan.error)+ trusted_backend = None+ trusted_gguf_repo = None+ trusted_gguf_files = None+ trusted_download_pending = False+ if plan.error is None:+ trusted_backend = "llama-server" if destination_is_llama else "sentence-transformers"+ # The exact family this transfer delivers. A repo publishing no+ # RAG_EMBED_GGUF_VARIANT is served another quant on purpose, which the+ # loader's variant lookup cannot recognize as what was downloaded, so+ # without this the model stays cache-only and an eviction reads as+ # "never downloaded" though the transfer finished.+ trusted_gguf_files = plan.files if destination_is_llama else None+ # A sentence-transformers download repo is not a GGUF source. Keeping+ # it out also prevents a later runtime fallback from mislabelling it.+ trusted_gguf_repo = plan.download_repo if destination_is_llama else None+ # The setting may be activated so both mounted settings surfaces stay+ # in sync, but its loader must remain cache-only until this transfer is+ # complete. That prevents a close/cancel from becoming an implicit+ # first-index download.+ trusted_download_pending = bool(plan.download_repo and not plan.cached)+ else:+ # Save anyway, over a failed plan: nothing validated to record, but the+ # marker still has to go on or both loaders take their uncached path and+ # fetch invisibly at the first index, which this picker exists to replace.+ trusted_download_pending = True+ set_rag_embedding_model(+ model,+ gguf_repo = trusted_gguf_repo,+ backend = trusted_backend,+ download_pending = trusted_download_pending,+ gguf_files = trusted_gguf_files,+ )logger.info("settings.embedding_model_updated subject=%s model=%s forced=%s",current_subject,@@ -2043,6 +2764,20 @@ def update_embedding_model(return _embedding_model_response()[email protected]("/embedding-model/unload", response_model = EmbeddingModelResponse)+def unload_embedding_model(+ current_subject: str = Depends(get_current_subject),+) -> EmbeddingModelResponse:+ """Drop the embedder and stop its llama-server. Indexing rebuilds it on demand."""+ from core.rag import embeddings++ released = embeddings.release_backend()+ logger.info(+ "settings.embedding_model_unloaded subject=%s released=%s", current_subject, released+ )+ return _embedding_model_response()++@router.delete("/embedding-model", response_model = EmbeddingModelResponse)def reset_embedding_model(current_subject: str = Depends(get_current_subject),diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 788b0e8b8ac..ca2acbd7f56 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -3921,6 +3921,61 @@ def get_app_setting(key: str, fallback = None):conn.close()+def get_app_settings(keys: list[str]) -> dict[str, Any]:+ """Read a set of settings from one SQLite snapshot.++ Values that form one logical record must not be fetched through separate+ connections: a concurrent multi-key upsert could otherwise leave a reader+ pairing one save's first field with another save's remaining fields.+ Missing keys are omitted from the result.+ """+ unique = list(dict.fromkeys(keys))+ if not unique:+ return {}+ conn = get_connection()+ try:+ placeholders = ",".join("?" for _ in unique)+ rows = conn.execute(+ f"SELECT key, value_json FROM app_settings WHERE key IN ({placeholders})",+ unique,+ ).fetchall()+ return {row["key"]: _json_loads(row["value_json"], None) for row in rows}+ finally:+ conn.close()+++def compare_and_set_app_setting(key: str, expected: Any, value: Any) -> bool:+ """Write ``value`` to ``key`` only while it still holds ``expected``.++ A read-then-upsert cannot express "clear this flag": another save committing+ in the gap is silently reverted by the write that follows it. Comparing inside+ one immediate transaction makes a losing update a no-op instead. Returns+ whether the write happened.+ """+ conn = get_connection()+ try:+ conn.execute("BEGIN IMMEDIATE")+ row = conn.execute("SELECT value_json FROM app_settings WHERE key = ?", (key,)).fetchone()+ current = _json_loads(row["value_json"], None) if row is not None else None+ if current != expected:+ conn.rollback()+ return False+ conn.execute(+ """+ INSERT INTO app_settings (key, value_json, updated_at)+ VALUES (?, ?, ?)+ ON CONFLICT(key) DO UPDATE SET+ value_json = excluded.value_json,+ updated_at = excluded.updated_at+ """,+ (key, json.dumps(value), datetime.now(timezone.utc).isoformat()),+ )+ conn.commit()+ return True+ finally:+ conn.close()++def upsert_app_settings(settings: dict[str, Any]) -> dict[str, Any]:if not settings:return {}diff --git a/studio/backend/tests/test_embedding_model_resolve.py b/studio/backend/tests/test_embedding_model_resolve.pynew file mode 100644index 00000000000..ba504a4670d--- /dev/null+++ b/studio/backend/tests/test_embedding_model_resolve.py@@ -0,0 +1,1109 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The picker asks what saving a model would need fetched before it saves, so the+download can be offered up front instead of happening invisibly at the first index.++The endpoint must agree with the loader about which repo and which file that is,+and with the PUT about what is unusable here."""++from pathlib import Path+import sys+import types as _types+++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import routes.settings as settings+++def client(monkeypatch):+ monkeypatch.setattr(settings, "validate_embedding_model", lambda v: v)+ monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: False)+ monkeypatch.setattr(settings, "_local_gguf_backend_error", lambda m: None)++ app = FastAPI()+ app.include_router(settings.router)+ app.dependency_overrides[settings.get_current_subject] = lambda: "admin"+ return TestClient(app, raise_server_exceptions = False)+++def _resolve(c, model = "unsloth/bge-small-en-v1.5"):+ return c.get("/embedding-model/resolve", params = {"model": model})+++def test_sentence_transformers_backend_points_at_the_model_repo(client, monkeypatch):+ """No GGUF involved: ST loads the model repo itself, and the cache check is the+ ordinary snapshot probe."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ # Cached now also means "holds a checkpoint ST can open", not just "loadable",+ # and names the repo it was filed under: for an exact id, that id.+ monkeypatch.setattr(+ settings, "_cached_st_source", lambda m: ("unsloth/bge-small-en-v1.5", Path("/snap"))+ )++ body = _resolve(client).json()+ assert body["backend"] == "sentence-transformers"+ assert body["download_repo"] == "unsloth/bge-small-en-v1.5"+ assert body["cached"] is True+ assert body["files"] is None+ assert body["error"] is None+++def test_uncached_sentence_transformers_plan_reports_snapshot_size(client, monkeypatch):+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_hf_snapshot_size", lambda repo, token: 987_654)+ # The repo has to publish something loadable before a size means anything.+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: ["model.safetensors"])+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ body = _resolve(client, "org/uncached-st").json()+ assert body["backend"] == "sentence-transformers"+ assert body["cached"] is False+ assert body["size_bytes"] == 987_654+++def test_a_repo_with_no_loadable_checkpoint_is_refused_not_offered(client, monkeypatch):+ """A feature-extraction repo publishing only GGUF passes the tag gate and+ reaches the direct ST branch, where it would be offered as a download ST+ cannot open."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ body = _resolve(client, "org/gguf-only").json()+ assert body["backend"] == "sentence-transformers"+ assert body["download_repo"] is None+ assert body["cached"] is False+ assert "no checkpoint this backend can load" in body["error"]+++def test_resolution_selects_the_backend_for_the_new_model_not_the_old_one(client, monkeypatch):+ seen = []+ monkeypatch.setattr(+ settings,+ "_llama_backend_active",+ lambda model = None: seen.append(model) or False,+ )+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda model: True)+ body = _resolve(client, "org/new-model").json()++ assert seen == ["org/new-model"]+ assert body["backend"] == "sentence-transformers"+++def test_runtime_st_failure_is_planned_as_a_managed_gguf_download(client, monkeypatch):+ from core.rag import embeddings++ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ monkeypatch.setattr(+ embeddings,+ "_resolve_auto_for_model",+ lambda model = None: "sentence-transformers",+ )+ monkeypatch.setattr(embeddings, "sentence_transformers_runtime_available", lambda: False)+ monkeypatch.setattr(embeddings, "_llama_server_runtime_available", lambda: True)+ monkeypatch.setattr(+ settings, "_cached_embedding_gguf", lambda candidates, require_variant: None+ )+ monkeypatch.setattr(+ settings,+ "_remote_embedding_gguf_plan",+ lambda candidates, token: (candidates[0], ["embed-F16.gguf"]),+ )+ monkeypatch.setattr(settings, "_hf_files_size", lambda repo, files, token: 1234)++ body = _resolve(client, "org/embed").json()++ assert body["backend"] == "llama"+ assert body["download_repo"] == "org/embed-GGUF"+ assert body["files"] == ["embed-F16.gguf"]+ assert body["size_bytes"] == 1234+++def test_sentence_transformers_local_path_is_already_present(client, monkeypatch, tmp_path):+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ local = tmp_path / "embedder"+ local.mkdir()+ # "Present" means a checkpoint is there. An empty directory used to pass on+ # existence alone; see test_a_local_dir_without_weights_is_not_already_present.+ (local / "modules.json").write_text("[]")+ (local / "model.safetensors").write_bytes(b"ST")++ body = _resolve(client, str(local)).json()+ assert body["backend"] == "sentence-transformers"+ assert body["cached"] is True+ assert body["download_repo"] is None+++def test_uncached_gguf_names_the_one_file_the_loader_would_open(client, monkeypatch):+ """The companion repo carries every quant; only the variant the embedder opens+ should be fetched, so the picker gets a file list rather than a whole repo."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings, "_cached_embedding_gguf", lambda candidates, require_variant: None+ )+ monkeypatch.setattr(+ settings,+ "_remote_embedding_gguf_plan",+ lambda candidates, token: (candidates[0], ["bge-small-en-v1.5-F16.gguf"]),+ )+ monkeypatch.setattr(settings, "_hf_files_size", lambda repo, files, token: 133_000_000)++ body = _resolve(client).json()+ assert body["backend"] == "llama"+ assert body["download_repo"] == "unsloth/bge-small-en-v1.5-GGUF"+ assert body["files"] == ["bge-small-en-v1.5-F16.gguf"]+ assert body["cached"] is False+ assert body["size_bytes"] == 133_000_000+ assert body["error"] is None+++def test_relaxed_cache_does_not_hide_the_preferred_online_variant(client, monkeypatch):+ """A fallback quant/candidate is only the loader's offline last resort; it+ must not suppress the configured variant's download while Hub listing works."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ seen = []++ def _cached(candidates, require_variant):+ seen.append((tuple(candidates), require_variant))+ return candidates[0] if not require_variant else None++ monkeypatch.setattr(settings, "_cached_embedding_gguf", _cached)+ monkeypatch.setattr(+ settings,+ "_remote_embedding_gguf_plan",+ lambda candidates, token: (candidates[0], ["embed-F16.gguf"]),+ )+ monkeypatch.setattr(settings, "_hf_files_size", lambda *a: 10)++ body = _resolve(client, "acme/embed").json()+ assert seen == [(("acme/embed-GGUF",), True)]+ assert body["cached"] is False+ assert body["files"] == ["embed-F16.gguf"]+++def test_cached_gguf_asks_for_no_download(client, monkeypatch):+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings,+ "_cached_embedding_gguf",+ lambda candidates, require_variant: candidates[0],+ )++ def _unreachable(*args, **kwargs): # pragma: no cover - the point of the test+ raise AssertionError("a cached model must not be listed against the hub")++ monkeypatch.setattr(settings, "_remote_embedding_gguf_plan", _unreachable)++ body = _resolve(client).json()+ assert body["cached"] is True+ assert body["files"] is None+++def test_the_search_fallback_finds_an_off_convention_name(client, monkeypatch):+ """The companion may not be named "<model>-GGUF" at all, so the owner's repos+ are searched before giving up."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings, "_cached_embedding_gguf", lambda candidates, require_variant: None+ )+ monkeypatch.setattr(settings, "_remote_embedding_gguf_plan", lambda candidates, token: None)+ monkeypatch.setattr(+ settings,+ "_search_hub_for_gguf",+ lambda m, token: (+ "unsloth/embeddinggemma-300m-GGUF",+ ["embeddinggemma-300M-F16.gguf"],+ ),+ )+ monkeypatch.setattr(settings, "_hf_files_size", lambda repo, files, token: None)++ body = _resolve(client, "unsloth/embeddinggemma-300m-qat-q8_0-unquantized").json()+ assert body["download_repo"] == "unsloth/embeddinggemma-300m-GGUF"+ assert body["files"] == ["embeddinggemma-300M-F16.gguf"]+ assert body["error"] is None+++def test_the_search_never_leaves_the_model_owner(monkeypatch):+ """Picking unsloth/X must download unsloth's own weights. A repo name is not+ proof of provenance, so a third party's "X-GGUF" is not an acceptable source."""+ seen: dict = {}++ class _Hit:+ def __init__(self, repo_id):+ self.id = repo_id++ class _Api:+ def list_models(self, **kwargs):+ seen.update(kwargs)+ # The Hub can return neighbours; only the owner's own may be taken.+ return [_Hit("someone-else/Qwen3-Embedding-8B-GGUF"), _Hit("unsloth/unrelated")]++ import huggingface_hub++ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", lambda *a, **k: ["x.gguf"])++ assert settings._search_hub_for_gguf("unsloth/Qwen3-Embedding-8B", None) is None+ # And the query itself is scoped to the owner, not filtered only afterwards.+ assert seen["author"] == "unsloth"+++def test_the_search_requires_an_exact_conversion_name(monkeypatch):+ class _Hit:+ def __init__(self, repo_id):+ self.id = repo_id++ class _Api:+ def list_models(self, **kwargs):+ return [_Hit("acme/foo-bar-GGUF"), _Hit("acme/foo-GGUF")]++ import huggingface_hub+ import utils.utils as utils++ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", lambda *a, **k: ["foo-F16.gguf"])+ monkeypatch.setattr(+ utils,+ "call_with_deadline",+ lambda fn, timeout, name: fn(),+ )++ assert settings._search_hub_for_gguf("acme/foo", None) == ("acme/foo-GGUF", ["foo-F16.gguf"])+++def test_split_gguf_plan_contains_every_shard():+ names = [+ "F16/embed-00002-of-00002.gguf",+ "F16/embed-00001-of-00002.gguf",+ "Q8/embed-Q8_0.gguf",+ ]+ assert settings._pick_downloadable_gguf(names) == [+ "F16/embed-00001-of-00002.gguf",+ "F16/embed-00002-of-00002.gguf",+ ]+++def test_repo_file_listing_uses_a_deadline(monkeypatch):+ import huggingface_hub+ import utils.utils as utils++ seen = {}+ monkeypatch.setattr(huggingface_hub, "list_repo_files", lambda repo, token = None: [repo])++ def _bounded(fn, timeout, name):+ seen.update(timeout = timeout, name = name)+ return fn()++ monkeypatch.setattr(utils, "call_with_deadline", _bounded)+ assert settings._list_repo_files_bounded("acme/embed", None) == ["acme/embed"]+ assert seen == {+ "timeout": settings._GGUF_LIST_DEADLINE_S,+ "name": "embed-settings-repo-listing",+ }+++def test_resolution_shares_one_deadline_across_every_remote_fallback(monkeypatch):+ import huggingface_hub+ import utils.utils as utils++ now = [100.0]+ timeouts = []++ class _Api:+ def list_models(self, **kwargs):+ return []++ def _bounded(fn, timeout, name):+ timeouts.append(timeout)+ result = fn()+ now[0] += 6.0+ return result++ monkeypatch.setattr(settings.time, "monotonic", lambda: now[0])+ monkeypatch.setattr(utils, "call_with_deadline", _bounded)+ monkeypatch.setattr(huggingface_hub, "list_repo_files", lambda *a, **k: [])+ monkeypatch.setattr(huggingface_hub, "HfApi", _Api)+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ # An install that embeds with llama-server has the binary; the test host does not.+ monkeypatch.setattr(settings, "_llama_runtime_available", lambda: True)+ monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda model: False)+ monkeypatch.setattr(settings, "_local_gguf_backend_error", lambda model: None)+ monkeypatch.setattr(+ settings,+ "_embedding_gguf_candidates",+ lambda model: ["acme/one", "acme/two", "acme/three"],+ )+ monkeypatch.setattr(+ settings, "_cached_embedding_gguf", lambda candidates, require_variant: None+ )+ monkeypatch.setattr(settings, "_sentence_transformers_fallback_allowed", lambda model: False)++ plan = settings._resolve_embedding_model_plan("acme/embed", None)++ assert plan.error is not None+ assert timeouts == pytest.approx([20.0, 14.0, 8.0, 2.0])+++def _no_gguf_anywhere(monkeypatch):+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings, "_cached_embedding_gguf", lambda candidates, require_variant: None+ )+ monkeypatch.setattr(settings, "_remote_embedding_gguf_plan", lambda candidates, token: None)+ monkeypatch.setattr(settings, "_search_hub_for_gguf", lambda m, token: None)+++def test_no_gguf_falls_back_to_the_models_own_safetensors(client, monkeypatch):+ """Safetensors cost about 1 GB more memory but they load, so they beat both+ refusing the model and pulling a stranger's conversion."""+ _no_gguf_anywhere(monkeypatch)+ monkeypatch.setattr(settings, "_safetensors_plan", lambda m, token: (m, ["model.safetensors"]))+ monkeypatch.setattr(settings, "_hf_snapshot_size", lambda repo, token: 4096)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ body = _resolve(client, "unsloth/Qwen3-Embedding-8B").json()+ assert body["backend"] == "sentence-transformers"+ assert body["download_repo"] == "unsloth/Qwen3-Embedding-8B"+ # No file list: ST needs the config and tokenizer too, not just the weights.+ assert body["files"] is None+ assert body["size_bytes"] == 4096+ assert body["error"] is None+++def test_sentence_transformers_weight_probe_ignores_companion_bins(monkeypatch):+ monkeypatch.setattr(+ settings,+ "_list_repo_files_bounded",+ lambda model, token: ["tokenizer.bin", "assets/vocab.bin"],+ )+ assert settings._st_weight_files("acme/not-a-checkpoint", None) is None++ monkeypatch.setattr(+ settings,+ "_list_repo_files_bounded",+ lambda model, token: ["tokenizer.bin", "weights/pytorch_model-00001-of-00001.bin"],+ )+ assert settings._st_weight_files("acme/checkpoint", None) == [+ "weights/pytorch_model-00001-of-00001.bin"+ ]+++def test_sentence_transformers_size_matches_the_full_snapshot_download(monkeypatch):+ import huggingface_hub++ siblings = [+ _types.SimpleNamespace(rfilename = "config.json", size = 10),+ _types.SimpleNamespace(rfilename = "tokenizer.json", size = 20),+ _types.SimpleNamespace(rfilename = "tokenizer.bin", size = 30),+ _types.SimpleNamespace(rfilename = "model.safetensors", size = 100),+ _types.SimpleNamespace(rfilename = "pytorch_model.bin", size = 110),+ _types.SimpleNamespace(rfilename = "old.gguf", size = 1_000),+ _types.SimpleNamespace(rfilename = "consolidated.00.pth", size = 2_000),+ ]+ monkeypatch.setattr(+ huggingface_hub,+ "model_info",+ lambda repo, files_metadata, token: _types.SimpleNamespace(siblings = siblings),+ )++ # The full-snapshot worker keeps configs/tokenizers and both transformer+ # weight formats, while applying its normal GGUF/consolidated exclusions.+ assert settings._hf_snapshot_size("acme/embedder", None) == 270+++def test_explicit_llama_policy_does_not_offer_safetensors(client, monkeypatch):+ _no_gguf_anywhere(monkeypatch)+ # The policy is what makes this llama-only; the install still has the binary,+ # or the plan is refused for that reason before the GGUF search runs.+ monkeypatch.setattr(settings, "_llama_runtime_available", lambda: True)+ monkeypatch.setattr(settings, "_sentence_transformers_fallback_allowed", lambda model: False)+ monkeypatch.setattr(+ settings,+ "_safetensors_plan",+ lambda *a: (_ for _ in ()).throw(AssertionError("ST fallback must not be probed")),+ )+ body = _resolve(client, "acme/safetensors-only").json()+ assert body["backend"] == "llama"+ assert body["error"].startswith("No GGUF weights found")+++def test_the_fallback_stays_in_the_models_own_repo(monkeypatch):+ """Same rule as the GGUF search: only the publisher is a source."""+ monkeypatch.setattr(settings, "_st_backend_available", lambda: True)+ monkeypatch.setattr(+ settings,+ "_st_weight_files",+ lambda m, token: ["model.safetensors"] if m == "acme/embedder" else None,+ )+ assert settings._safetensors_plan("acme/embedder", None) == (+ "acme/embedder",+ ["model.safetensors"],+ )+ assert settings._safetensors_plan("acme/no-weights", None) is None+++def test_a_gguf_only_install_is_not_offered_safetensors(monkeypatch):+ """No torch here, so ST is not a working answer and the save reason stands."""+ monkeypatch.setattr(settings, "_st_backend_available", lambda: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, token: ["model.safetensors"])+ assert settings._safetensors_plan("acme/embedder", None) is None+++def test_nothing_anywhere_still_reports_the_save_reason(client, monkeypatch):+ """Only when the name candidates, the Hub search AND safetensors come up empty."""+ _no_gguf_anywhere(monkeypatch)+ monkeypatch.setattr(settings, "_safetensors_plan", lambda m, token: None)+ body = _resolve(client, "unsloth/nothing-like-this").json()+ assert body["download_repo"] is None+ assert body["files"] is None+ assert body["cached"] is False+ assert body["error"].startswith("No GGUF weights found")+++def test_a_local_gguf_is_already_the_artifact(client, monkeypatch):+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ # An install that embeds with llama-server has the binary; the test host does not.+ monkeypatch.setattr(settings, "_llama_runtime_available", lambda: True)+ monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: True)++ body = _resolve(client, "/models/my-embedder.gguf").json()+ assert body["cached"] is True+ assert body["download_repo"] is None+ assert body["error"] is None+++def test_candidates_follow_the_loader_order(monkeypatch):+ """One helper builds them, so the picker cannot fetch from a repo the loader+ would not have opened."""+ assert settings._embedding_gguf_candidates("acme/embedder") == [+ "acme/embedder-GGUF",+ "acme/embedder",+ ]+++def test_stored_off_convention_repo_is_the_preferred_candidate(monkeypatch):+ import utils.embedding_model_settings as ems+ monkeypatch.setattr(+ ems,+ "get_stored_gguf_repo",+ lambda model: "acme/special-conversion" if model == "acme/embedder" else None,+ )+ assert settings._embedding_gguf_candidates("acme/embedder") == [+ "acme/special-conversion",+ "acme/embedder-GGUF",+ "acme/embedder",+ ]+++def test_explicit_gguf_repo_disables_stored_and_discovered_mirrors(monkeypatch):+ from core.rag import config as rag_config+ import utils.embedding_model_settings as ems++ monkeypatch.setenv("RAG_EMBED_GGUF_REPO", "deploy/pinned-embedder")+ monkeypatch.setattr(rag_config, "EMBED_GGUF_REPO", "deploy/pinned-embedder")+ monkeypatch.setattr(ems, "get_stored_gguf_repo", lambda model: "acme/old-mirror")++ assert settings._embedding_gguf_candidates("acme/embedder") == ["deploy/pinned-embedder"]+ assert settings._search_hub_for_gguf("acme/embedder", None) is None+++def test_resolved_mirror_reports_its_exact_downloaded_files_as_cached(client, monkeypatch):+ _no_gguf_anywhere(monkeypatch)+ monkeypatch.setattr(+ settings,+ "_search_hub_for_gguf",+ lambda model, token: ("acme/embedder_gguf", ["embed-F16.gguf"]),+ )+ monkeypatch.setattr(+ settings,+ "_cached_embedding_gguf_files",+ lambda repo, files: repo == "acme/embedder_gguf" and files == ["embed-F16.gguf"],+ )++ body = _resolve(client, "acme/embedder").json()+ assert body["download_repo"] == "acme/embedder_gguf"+ assert body["cached"] is True+ assert body["files"] == ["embed-F16.gguf"]+ # A repo that already names GGUF is its own candidate, not "...-GGUF-GGUF".+ assert settings._embedding_gguf_candidates("acme/embedder-GGUF") == ["acme/embedder-GGUF"]+ # unsloth's unquantized re-uploads keep their GGUF on the base name.+ assert settings._embedding_gguf_candidates(+ "unsloth/embeddinggemma-300m-qat-q8_0-unquantized"+ ) == [+ "unsloth/embeddinggemma-300m-qat-q8_0-unquantized-GGUF",+ "unsloth/embeddinggemma-300m-GGUF",+ "unsloth/embeddinggemma-300m-qat-q8_0-unquantized",+ ]+++def test_the_resolved_repo_is_what_the_loader_opens(monkeypatch):+ """A conversion under another owner follows no naming rule, so it is stored and+ read back rather than re-derived."""+ import storage.studio_db as db++ store: dict = {}+ monkeypatch.setattr(+ db, "get_app_settings", lambda keys: {k: store[k] for k in keys if k in store}+ )+ monkeypatch.setattr(db, "upsert_app_settings", lambda s: store.update(s) or store)++ import utils.embedding_model_settings as ems+ from core.rag import config as rag_config++ ems._invalidate_cache()+ ems.set_rag_embedding_model(+ "unsloth/Qwen3-Embedding-4B", gguf_repo = "Qwen/Qwen3-Embedding-4B-GGUF"+ )+ assert rag_config.effective_gguf_repo() == "Qwen/Qwen3-Embedding-4B-GGUF"++ # A pair recorded for another model must never be served for this one.+ store[ems.EMBEDDING_GGUF_SETTING_KEY] = "Qwen/Qwen3-Embedding-4B-GGUF"+ ems._invalidate_cache()+ assert ems.get_stored_gguf_repo("unsloth/bge-m3") is None+ ems._invalidate_cache()+++def test_the_chosen_backend_is_read_back_by_the_loader(monkeypatch):+ """A safetensors-only model must not be handed to llama-server, which would have+ nothing to open. The picker records the backend; ``auto`` honours it."""+ import storage.studio_db as db++ store: dict = {}+ monkeypatch.setattr(+ db, "get_app_settings", lambda keys: {k: store[k] for k in keys if k in store}+ )+ monkeypatch.setattr(db, "upsert_app_settings", lambda s: store.update(s) or store)++ import utils.embedding_model_settings as ems+ from core.rag import embeddings as rag_embeddings++ ems._invalidate_cache()+ ems.set_rag_embedding_model("unsloth/Qwen3-Embedding-8B", backend = "sentence-transformers")+ assert ems.get_stored_backend("unsloth/Qwen3-Embedding-8B") == "sentence-transformers"+ assert rag_embeddings._resolve_auto_for_model() == "sentence-transformers"++ # A backend recorded for another model must not be served for this one.+ store[ems.EMBEDDING_MODEL_SETTING_KEY] = "unsloth/bge-m3"+ store[ems.EMBEDDING_RESOLUTION_SETTING_KEY] = {+ "model": "unsloth/bge-m3",+ "gguf_repo": None,+ "backend": "llama-server",+ }+ ems._invalidate_cache()+ # A model this process never resolved gets nothing, which is the property that+ # matters: the record belongs to bge-m3 and is not lent to anyone else.+ assert ems.get_stored_backend("unsloth/never-resolved") is None+ # Qwen keeps ITS OWN earlier resolution, not bge-m3's. Forgetting it dropped a+ # still-running job for Qwen back onto the hardware default; the memo is keyed+ # per model, so this is Qwen's record, not a stale pair.+ assert ems.get_stored_backend("unsloth/Qwen3-Embedding-8B") == "sentence-transformers"+ ems._resolved_gguf_memo.clear()+ assert ems.get_stored_backend("unsloth/Qwen3-Embedding-8B") is None+ ems._invalidate_cache()+++def test_the_token_is_a_header_not_a_query_parameter(client, monkeypatch):+ """A gated repo's credential must stay out of URLs and access logs."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings, "_cached_embedding_gguf", lambda candidates, require_variant: None+ )+ seen: dict = {}++ def _plan(candidates, token):+ seen["token"] = token+ return candidates[0], ["model-F16.gguf"]++ monkeypatch.setattr(settings, "_remote_embedding_gguf_plan", _plan)+ monkeypatch.setattr(settings, "_hf_files_size", lambda repo, files, token: None)++ client.get(+ "/embedding-model/resolve",+ params = {"model": "acme/gated-embedder"},+ headers = {"X-Unsloth-HF-Token": "hf_secret"},+ )+ assert seen["token"] == "hf_secret"+++def test_a_local_gguf_is_not_reported_as_a_ready_sentence_transformers_model(+ client, monkeypatch, tmp_path+):+ """The presence probe accepted any existing path. `auto` now routes a local+ .gguf to llama-server; this covers an explicit sentence-transformers setting,+ where the no-loadable-weights error is the honest answer."""+ gguf = tmp_path / "embed.gguf"+ gguf.write_bytes(b"GGUF")+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ assert settings._local_sentence_transformer_is_present(str(gguf)) is False+ # A real ST folder on the same filesystem is still recognised.+ folder = tmp_path / "st-model"+ folder.mkdir()+ (folder / "model.safetensors").write_bytes(b"ST")+ assert settings._local_sentence_transformer_is_present(str(folder)) is True++ body = _resolve(client, str(gguf)).json()+ assert body["cached"] is False+ assert "no checkpoint this backend can load" in body["error"]+++def test_a_cached_gguf_only_repo_is_not_reported_as_a_ready_st_model(client, monkeypatch, tmp_path):+ """hf_cache_snapshot_is_loadable counts .gguf, right for llama and wrong here:+ a cached GGUF-only repo came back ready, skipping the Hub weight check."""+ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model-Q8_0.gguf").write_bytes(b"GGUF")+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)++ assert settings._cached_snapshot_has_st_weights("org/gguf-only") is False++ body = _resolve(client, "org/gguf-only").json()+ assert body["cached"] is False+ assert "no checkpoint this backend can load" in body["error"]++ # A real cached ST snapshot on the same path still reports ready.+ (snapshot / "model.safetensors").write_bytes(b"ST")+ assert settings._cached_snapshot_has_st_weights("org/gguf-only") is True+ body = _resolve(client, "org/real-st").json()+ assert body["cached"] is True+ assert body["error"] is None+++def test_a_cached_safetensors_model_is_selectable_offline(client, monkeypatch, tmp_path):+ """The safetensors fallback proved weights only through the remote listing, so+ offline a fully downloaded model could not be selected at all."""+ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model.safetensors").write_bytes(b"ST")+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(settings, "_st_backend_available", lambda: True)+ monkeypatch.setattr(settings, "_sentence_transformers_fallback_allowed", lambda m: True)+ # Offline: every remote probe fails.+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ monkeypatch.setattr(settings, "_remote_embedding_gguf_plan", lambda c, t: None)+ monkeypatch.setattr(settings, "_search_hub_for_gguf", lambda m, t: None)+ monkeypatch.setattr(settings, "_cached_embedding_gguf", lambda c, require_variant = True: None)+ monkeypatch.setattr(settings, "_hf_snapshot_size", lambda repo, token: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)++ assert settings._safetensors_plan("org/st-only", None) == ("org/st-only", ["model.safetensors"])++ body = _resolve(client, "org/st-only").json()+ assert body["backend"] == "sentence-transformers"+ assert body["download_repo"] == "org/st-only"+ assert body["cached"] is True+ assert body["error"] is None+++def test_a_local_dir_without_weights_is_not_already_present(client, monkeypatch, tmp_path):+ """A folder holding modules.json and no checkpoint also passes+ is_embedding_model's local-path check, so it was reported cached and accepted+ without force, then failed at the first index when SentenceTransformer went+ looking for the weights."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ empty = tmp_path / "metadata-only"+ empty.mkdir()+ (empty / "modules.json").write_text("[]")+ (empty / "config.json").write_text("{}")+ assert settings._local_sentence_transformer_is_present(str(empty)) is False++ body = _resolve(client, str(empty)).json()+ assert body["cached"] is False+ assert "no checkpoint this backend can load" in body["error"]++ # A complete module subtree is enough; the weights need not sit at the root.+ # modules.json has to declare it, as a real one does: the directory is judged+ # by the layout it announces, the same way a Hub snapshot is.+ module = empty / "0_Transformer"+ module.mkdir()+ (module / "model.safetensors").write_bytes(b"ST")+ (empty / "modules.json").write_text('[{"idx": 0, "name": "0", "path": "0_Transformer"}]')+ assert settings._local_sentence_transformer_is_present(str(empty)) is True+++def test_a_slashless_alias_resolves_under_the_sentence_transformers_namespace(client, monkeypatch):+ """A slashless name resolves under sentence-transformers/, as the loader's own+ st_repo_id_candidates encodes. Probing only the literal id refused a download+ that worked before this picker existed."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ listed = []++ def _files(repo, token):+ listed.append(repo)+ return ["model.safetensors"] if repo == "sentence-transformers/all-MiniLM-L6-v2" else None++ monkeypatch.setattr(settings, "_st_weight_files", _files)+ monkeypatch.setattr(settings, "_hf_snapshot_size", lambda repo, token: 90_000_000)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ body = _resolve(client, "all-MiniLM-L6-v2").json()+ assert body["error"] is None+ # The setting keeps the alias the user typed; the download names the repo that+ # actually publishes the weights.+ assert body["embedding_model"] == "all-MiniLM-L6-v2"+ assert body["download_repo"] == "sentence-transformers/all-MiniLM-L6-v2"+ assert listed == ["all-MiniLM-L6-v2", "sentence-transformers/all-MiniLM-L6-v2"]+++def test_a_bare_checkpoint_file_is_not_a_local_sentence_transformer(client, monkeypatch, tmp_path):+ """SentenceTransformer takes a directory or a repo id, never a bare file."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ bare = tmp_path / "model.safetensors"+ bare.write_bytes(b"ST")+ assert settings._local_sentence_transformer_is_present(str(bare)) is False++ body = _resolve(client, str(bare)).json()+ assert body["cached"] is False+ assert "no checkpoint this backend can load" in body["error"]+++def test_a_tokenizer_bin_is_not_mistaken_for_a_checkpoint(client, monkeypatch, tmp_path):+ """.bin is the loose suffix: tokenizer.bin shares it with real weights, so a+ directory holding only that beside modules.json resolved as cached."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)++ local = tmp_path / "partial"+ local.mkdir()+ (local / "modules.json").write_text("[]")+ (local / "tokenizer.bin").write_bytes(b"NOT WEIGHTS")+ assert settings._local_sentence_transformer_is_present(str(local)) is False++ body = _resolve(client, str(local)).json()+ assert body["cached"] is False+ assert "no checkpoint this backend can load" in body["error"]++ # A real checkpoint under any of the accepted families still counts.+ (local / "pytorch_model.bin").write_bytes(b"ST")+ assert settings._local_sentence_transformer_is_present(str(local)) is True+++def test_the_cached_snapshot_probe_uses_the_same_filename_family(monkeypatch, tmp_path):+ """The cached-snapshot probe had the same suffix-only test as the local one."""+ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "tokenizer.bin").write_bytes(b"NOT WEIGHTS")+ import utils.utils as utils++ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)+ assert settings._cached_snapshot_has_st_weights("org/partial") is False+ assert settings._cached_st_weight_names("org/partial") == []++ (snapshot / "model.safetensors").write_bytes(b"ST")+ assert settings._cached_snapshot_has_st_weights("org/partial") is True+ assert settings._cached_st_weight_names("org/partial") == ["model.safetensors"]+++def test_a_cached_alias_names_the_namespace_it_is_filed_under(client, monkeypatch, tmp_path):+ """hf_cache_snapshot_dir is alias-aware, so a slashless name finds its snapshot+ under sentence-transformers/. Returning the literal id as the download repo+ sent the manager at a top-level repo that usually does not exist."""+ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model.safetensors").write_bytes(b"ST")+ import utils.utils as utils++ _snapshot_of = (+ lambda repo: snapshot if repo == "sentence-transformers/all-MiniLM-L6-v2" else None+ )+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", _snapshot_of)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", _snapshot_of)+ monkeypatch.setattr(settings, "_st_backend_available", lambda: True)+ # Offline: the remote listing cannot answer, so only the cache can.+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)++ assert utils.cached_st_repo("all-MiniLM-L6-v2") == "sentence-transformers/all-MiniLM-L6-v2"+ assert settings._safetensors_plan("all-MiniLM-L6-v2", None) == (+ "sentence-transformers/all-MiniLM-L6-v2",+ ["model.safetensors"],+ )+ # A name with no cached snapshot anywhere still falls through to the listing.+ assert settings._safetensors_plan("org/uncached", None) is None+++def test_a_stale_literal_cache_does_not_hide_a_complete_alias_snapshot(+ client, monkeypatch, tmp_path+):+ """hf_cache_snapshot_is_loadable stops at the first matching cache directory+ while the ST predicate walks candidates for a complete one. Conjoining them+ let a stale models--all-MiniLM-L6-v2 entry report the model uncached even with+ a complete sentence-transformers/ snapshot beside it; offline the Hub probe+ then failed and /resolve returned an error the loader would have disagreed+ with."""+ literal = tmp_path / "literal"+ literal.mkdir()+ (literal / "config.json").write_text("{}")+ alias = tmp_path / "alias"+ alias.mkdir()+ (alias / "config.json").write_text("{}")+ (alias / "model.safetensors").write_bytes(b"ST")+ import utils.utils as utils++ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ _snapshot_of = (+ lambda repo: alias if repo == "sentence-transformers/all-MiniLM-L6-v2" else literal+ )+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", _snapshot_of)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", _snapshot_of)+ # The generic check answers about the stale literal entry.+ monkeypatch.setattr(+ utils,+ "hf_cache_snapshot_is_loadable",+ lambda repo: repo == "sentence-transformers/all-MiniLM-L6-v2",+ )+ # Offline: the Hub probe cannot rescue it.+ monkeypatch.setattr(settings, "_st_weight_files", lambda m, t: None)++ body = _resolve(client, "all-MiniLM-L6-v2").json()+ assert body["cached"] is True+ assert body["error"] is None+++def test_a_remote_gguf_repo_is_served_by_llama_server_on_an_st_host(monkeypatch):+ """A GPU host resolves ``auto`` to sentence-transformers, which then searches a+ typed or API-selected ``owner/model-GGUF`` for safetensors, finds none and errors.+ Saving over that error sets the pending marker, and the ST loader answers a+ pending model with "not downloaded" before the runtime fallback can reach+ llama-server, so the repo could never load however it was cached."""+ from core.rag import embeddings as rag_embeddings+ import utils.embedding_model_settings as ems++ ems._resolved_gguf_memo.clear()+ ems._invalidate_cache()+ # A GPU is present, so the hardware default is sentence-transformers.+ monkeypatch.setattr(rag_embeddings, "_resolve_auto", lambda: "sentence-transformers")+ # And the forced save recorded no backend, exactly as a failed plan does.+ monkeypatch.setattr(ems, "get_stored_backend", lambda model: None)++ assert rag_embeddings._resolve_auto_for_model("unsloth/bge-m3-GGUF") == "llama-server"+ assert rag_embeddings._resolve_auto_for_model("unsloth/bge-m3") == "sentence-transformers"+++def test_a_local_directory_named_gguf_is_still_a_sentence_transformers_model(monkeypatch, tmp_path):+ """The remote rule is a name test, and a directory may be named anything. Only+ the filesystem can say what ``~/models/my-gguf`` holds, and here it holds+ safetensors."""+ from core.rag import embeddings as rag_embeddings+ import utils.embedding_model_settings as ems++ local = tmp_path / "my-gguf"+ local.mkdir()+ (local / "model.safetensors").write_bytes(b"\x00")+ ems._resolved_gguf_memo.clear()+ ems._invalidate_cache()+ monkeypatch.setattr(rag_embeddings, "_resolve_auto", lambda: "sentence-transformers")+ monkeypatch.setattr(ems, "get_stored_backend", lambda model: None)++ assert rag_embeddings._resolve_auto_for_model(str(local)) == "sentence-transformers"+++def test_a_gguf_only_model_is_refused_when_llama_server_is_missing(client, monkeypatch):+ """A GGUF-named model routes to llama-server because nothing else can open it,+ which says nothing about whether this install can run that backend. Without the+ binary the plan was advertised as valid and the transfer persisted, and the+ first warm failed in _resolve_binary with the download already done."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(settings, "_llama_runtime_available", lambda: False)++ body = _resolve(client, "unsloth/bge-m3-GGUF").json()+ assert body["download_repo"] is None+ assert "no llama-server binary was found" in body["error"]+++def test_a_safetensors_model_still_falls_back_when_llama_server_is_missing(client, monkeypatch):+ """The refusal is scoped to models only llama can serve. One that publishes+ safetensors has a usable plan on the other backend, and turning that into an+ error would strand it too."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(settings, "_llama_runtime_available", lambda: False)+ monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: False)+ monkeypatch.setattr(settings, "_remote_embedding_gguf_plan", lambda *a, **k: None)+ monkeypatch.setattr(settings, "_search_hub_for_gguf", lambda *a, **k: None)+ monkeypatch.setattr(settings, "_cached_embedding_gguf", lambda *a, **k: None)+ monkeypatch.setattr(settings, "_sentence_transformers_fallback_allowed", lambda m: True)+ monkeypatch.setattr(+ settings, "_safetensors_plan", lambda m, t: ("org/st-only", ["model.safetensors"])+ )+ monkeypatch.setattr(settings, "_cached_snapshot_has_st_weights", lambda m: True)++ body = _resolve(client, "org/st-only").json()+ assert body["error"] is None+ assert body["backend"] == "sentence-transformers"+++def test_a_cached_alias_is_verified_under_the_namespace_it_is_filed_under(client, monkeypatch):+ """A slashless model cached only as sentence-transformers/<name> is on disk and+ loadable, but reporting the literal alias as the download repo sent the PUT's+ verification and security scan at a top-level repo that usually does not exist,+ rejecting a valid cached model with a 409 the loader would have ignored."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(+ settings,+ "_cached_st_source",+ lambda m: ("sentence-transformers/all-MiniLM-L6-v2", Path("/snap")),+ )++ body = _resolve(client, "all-MiniLM-L6-v2").json()+ assert body["cached"] is True+ assert body["download_repo"] == "sentence-transformers/all-MiniLM-L6-v2"+ assert body["error"] is None+++def test_a_validated_backend_outranks_the_gguf_name_heuristic(monkeypatch):+ """A repo called <name>-GGUF whose published family is torn or absent falls+ back to its own safetensors, and the resolver persists that plan. Reading the+ name as llama-server anyway sent the first index down the GGUF pending path,+ to fail as "not downloaded" on a model whose weights were validated."""+ from core.rag import embeddings as rag_embeddings+ import utils.embedding_model_settings as ems++ ems._resolved_gguf_memo.clear()+ ems._invalidate_cache()+ monkeypatch.setattr(rag_embeddings, "_resolve_auto", lambda: "llama-server")+ monkeypatch.setattr(ems, "get_stored_backend", lambda model: "sentence-transformers")+ # The name is a guess; a local .gguf is not, and keeps its precedence (see+ # test_a_local_gguf_beats_a_stored_sentence_transformers_record).++ assert rag_embeddings._resolve_auto_for_model("org/torn-GGUF") == "sentence-transformers"+ # With nothing validated, the name still decides, which is what stops a forced+ # save over a failed plan from stranding the model on the wrong backend.+ monkeypatch.setattr(ems, "get_stored_backend", lambda model: None)+ assert rag_embeddings._resolve_auto_for_model("org/torn-GGUF") == "llama-server"+++def test_a_torn_local_checkpoint_is_not_reported_as_present(client, monkeypatch, tmp_path):+ """Any one matching filename used to be enough, so half a shard family read as+ ready and the first index failed when SentenceTransformer opened it. Same+ completeness test a Hub snapshot gets."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ torn = tmp_path / "half-copied"+ torn.mkdir()+ (torn / "config.json").write_text("{}")+ # The index is what says how many shards the family has, as a real sharded+ # checkpoint ships it.+ (torn / "model.safetensors.index.json").write_text(+ '{"weight_map": {"a": "model-00001-of-00002.safetensors",'+ ' "b": "model-00002-of-00002.safetensors"}}'+ )+ (torn / "model-00001-of-00002.safetensors").write_bytes(b"ST")++ assert settings._local_sentence_transformer_is_present(str(torn)) is False++ # The missing shard completes it.+ (torn / "model-00002-of-00002.safetensors").write_bytes(b"ST")+ assert settings._local_sentence_transformer_is_present(str(torn)) is True+++def test_a_declared_module_the_directory_lacks_is_not_present(client, monkeypatch, tmp_path):+ """modules.json announces the layout ST will load. A module it names and the+ directory does not have is a torn copy however complete the rest looks."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ partial = tmp_path / "missing-module"+ partial.mkdir()+ (partial / "config.json").write_text("{}")+ (partial / "model.safetensors").write_bytes(b"ST")+ (partial / "modules.json").write_text(+ '[{"idx": 0, "name": "0", "path": ""}, {"idx": 1, "name": "1", "path": "1_Pooling"}]'+ )++ assert settings._local_sentence_transformer_is_present(str(partial)) is False++ (partial / "1_Pooling").mkdir()+ assert settings._local_sentence_transformer_is_present(str(partial)) is True+++def test_an_explicit_llama_policy_refuses_any_model_without_the_binary(client, monkeypatch):+ """An explicit RAG_EMBED_BACKEND=llama-server refuses the safetensors fallback+ for every model, not only GGUF-named ones, so an ordinary repo id is just as+ unservable without a binary. Scoping the check to the name offered and+ persisted a managed download _resolve_binary would reject at first use."""+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(settings, "_llama_runtime_available", lambda: False)+ monkeypatch.setattr(settings, "_sentence_transformers_fallback_allowed", lambda model: False)+ monkeypatch.setattr(+ settings,+ "_remote_embedding_gguf_plan",+ lambda *a, **k: (_ for _ in ()).throw(AssertionError("no plan may be offered")),+ )++ body = _resolve(client, "org/embedder").json()+ assert body["download_repo"] is None+ assert "no llama-server binary was found" in body["error"]+++def test_a_whole_segment_gguf_name_routes_to_llama_server(monkeypatch):+ """config.gguf_repo_candidates treats "gguf" as a whole name segment, so+ owner/GGUF-model is a direct GGUF repo there. Deciding it by suffix here sent+ those to sentence-transformers, which has nothing to open, and the rejection+ stuck even under a forced selection."""+ from core.rag import embeddings as rag_embeddings+ import utils.embedding_model_settings as ems++ ems._resolved_gguf_memo.clear()+ ems._invalidate_cache()+ monkeypatch.setattr(rag_embeddings, "_resolve_auto", lambda: "sentence-transformers")+ monkeypatch.setattr(ems, "get_stored_backend", lambda model: None)++ for model in ("owner/GGUF-model", "owner/model-GGUF-Q8", "owner/model-GGUF"):+ assert rag_embeddings._resolve_auto_for_model(model) == "llama-server", model+ # A plain substring is still not a GGUF repo, as config's predicate says.+ assert rag_embeddings._resolve_auto_for_model("owner/bigguf") == "sentence-transformers"diff --git a/studio/backend/tests/test_embedding_model_security_gate.py b/studio/backend/tests/test_embedding_model_security_gate.pyindex a6c18bd8dee..1bb5ca09c36 100644--- a/studio/backend/tests/test_embedding_model_security_gate.py+++ b/studio/backend/tests/test_embedding_model_security_gate.py@@ -37,6 +37,14 @@ def _security_stub(blocked):return mod+def _plan(model, backend):+ return settings.EmbeddingModelResolveResponse(+ embedding_model = model,+ backend = backend,+ download_repo = f"{model}-GGUF" if backend == "llama" else model,+ )++@pytest.fixturedef client(monkeypatch):# The settings scan unions in the ST module dirs read from modules.json; keep it@@ -47,15 +55,34 @@ def client(monkeypatch):saved: dict = {}monkeypatch.setattr(settings, "default_embedding_model", lambda: "unsloth/default-embed")monkeypatch.setattr(settings, "validate_embedding_model", lambda v: v)- monkeypatch.setattr(settings, "set_rag_embedding_model", lambda v: saved.setdefault("model", v))- monkeypatch.setattr(settings, "_llama_backend_active", lambda: False)+ monkeypatch.setattr(+ settings,+ "set_rag_embedding_model",+ lambda v, gguf_repo = None, backend = None, download_pending = False, gguf_files = None: (+ saved.update(+ model = v,+ gguf_repo = gguf_repo,+ backend = backend,+ download_pending = download_pending,+ gguf_files = gguf_files,+ )+ ),+ )+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _plan(+ model, "llama" if settings._llama_backend_active() else "sentence-transformers"+ ),+ )monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: False)monkeypatch.setattr(settings, "get_rag_embedding_model", lambda: saved.get("model", ""))monkeypatch.setattr(settings, "get_stored_embedding_model", lambda: saved.get("model"))monkeypatch.setattr(settings,- "effective_gguf_repo",- lambda: f"{saved.get('model', 'unsloth/default-embed')}-GGUF",+ "effective_gguf_repo_for_embedding_model",+ lambda model: f"{model or 'unsloth/default-embed'}-GGUF",)monkeypatch.setattr(settings,@@ -88,6 +115,18 @@ def test_flagged_repo_is_blocked_without_force(client, monkeypatch):assert "model" not in saved+def test_uncached_selection_is_marked_pending_so_loaders_stay_offline(client, monkeypatch):+ c, saved = client+ monkeypatch.setitem(sys.modules, "utils.security", _security_stub(blocked = False))+ import utils.models as models++ monkeypatch.setattr(models, "is_embedding_model", lambda *a, **k: True)+ response = c.put("/embedding-model", json = {"embedding_model": "acme/embedder"})++ assert response.status_code == 200+ assert saved["download_pending"] is True++def test_hard_block_uses_non_forceable_status(client, monkeypatch):# The forceable verification path uses 409; the hard security block must be distinct# (403) so the frontend never routes it into the "save anyway" force flow.@@ -142,7 +181,7 @@ def test_offline_skips_remote_gguf_probe(client, monkeypatch):# dead-DNS session cannot hang.c, _saved = clientmonkeypatch.setenv("HF_HUB_OFFLINE", "1")- monkeypatch.setattr(settings, "_llama_backend_active", lambda: True)+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)monkeypatch.setattr(settings, "_local_gguf_backend_error", lambda model: None)def _boom(*a, **k):@@ -156,14 +195,67 @@ def test_offline_skips_remote_gguf_probe(client, monkeypatch):assert r.status_code == 200+def test_client_cannot_persist_an_unvalidated_gguf_repo(client, monkeypatch):+ c, saved = client+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setitem(sys.modules, "utils.security", _security_stub(blocked = False))++ r = c.put(+ "/embedding-model",+ json = {+ "embedding_model": "acme/embedder",+ "backend": "llama",+ "gguf_repo": "attacker/unrelated-llm-GGUF",+ },+ )+ assert r.status_code == 400+ assert "model" not in saved+++def test_security_scan_uses_the_resolved_destination_backend(client, monkeypatch):+ """The old backend may be llama while the selected model resolves to ST."""+ c, saved = client+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _plan(model, "sentence-transformers"),+ )+ monkeypatch.setitem(sys.modules, "utils.security", _security_stub(blocked = True))++ r = c.put(+ "/embedding-model",+ json = {"embedding_model": "attacker/flagged-st", "backend": "sentence-transformers"},+ )+ assert r.status_code == 403+ assert "model" not in saved++def test_llama_backend_skips_the_st_pickle_scan(monkeypatch):# On the llama-server backend the embedder loads GGUF (inert), not the ST repo's# pickle, so a flagged ST repo with a clean GGUF companion must not be rejected here.saved: dict = {}monkeypatch.setattr(settings, "default_embedding_model", lambda: "unsloth/default-embed")monkeypatch.setattr(settings, "validate_embedding_model", lambda v: v)- monkeypatch.setattr(settings, "set_rag_embedding_model", lambda v: saved.setdefault("model", v))- monkeypatch.setattr(settings, "_llama_backend_active", lambda: True)+ monkeypatch.setattr(+ settings,+ "set_rag_embedding_model",+ lambda v, gguf_repo = None, backend = None, download_pending = False, gguf_files = None: (+ saved.update(+ model = v,+ gguf_repo = gguf_repo,+ backend = backend,+ download_pending = download_pending,+ gguf_files = gguf_files,+ )+ ),+ )+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _plan(model, "llama"),+ )monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: False)monkeypatch.setattr(settings, "get_rag_embedding_model", lambda: saved.get("model", ""))monkeypatch.setattr(settings, "get_stored_embedding_model", lambda: saved.get("model"))@@ -209,12 +301,29 @@ def test_runtime_llama_fallback_skips_the_st_pickle_scan(monkeypatch):saved: dict = {}monkeypatch.setattr(settings, "default_embedding_model", lambda: "unsloth/default-embed")monkeypatch.setattr(settings, "validate_embedding_model", lambda v: v)- monkeypatch.setattr(settings, "set_rag_embedding_model", lambda v: saved.setdefault("model", v))+ monkeypatch.setattr(+ settings,+ "set_rag_embedding_model",+ lambda v, gguf_repo = None, backend = None, download_pending = False, gguf_files = None: (+ saved.update(+ model = v,+ gguf_repo = gguf_repo,+ backend = backend,+ download_pending = download_pending,+ gguf_files = gguf_files,+ )+ ),+ )# Deliberately do NOT monkeypatch settings._llama_backend_active: this test exercises the# real delegation to embeddings.active_backend_is_llama() so the cached fallback is honored.monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: False)monkeypatch.setattr(settings, "get_rag_embedding_model", lambda: saved.get("model", ""))monkeypatch.setattr(settings, "get_stored_embedding_model", lambda: saved.get("model"))+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _plan(model, "llama"),+ )called = {"scanned": False}mod = _types.ModuleType("utils.security")@@ -278,8 +387,25 @@ def test_settings_scan_scopes_module_subdirs(monkeypatch):saved: dict = {}monkeypatch.setattr(settings, "default_embedding_model", lambda: "unsloth/default-embed")monkeypatch.setattr(settings, "validate_embedding_model", lambda v: v)- monkeypatch.setattr(settings, "set_rag_embedding_model", lambda v: saved.setdefault("model", v))- monkeypatch.setattr(settings, "_llama_backend_active", lambda: False)+ monkeypatch.setattr(+ settings,+ "set_rag_embedding_model",+ lambda v, gguf_repo = None, backend = None, download_pending = False, gguf_files = None: (+ saved.update(+ model = v,+ gguf_repo = gguf_repo,+ backend = backend,+ download_pending = download_pending,+ gguf_files = gguf_files,+ )+ ),+ )+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: False)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _plan(model, "sentence-transformers"),+ )monkeypatch.setattr(settings, "_resolves_as_local_gguf", lambda m: False)monkeypatch.setattr(settings, "get_rag_embedding_model", lambda: saved.get("model", ""))monkeypatch.setattr(settings, "get_stored_embedding_model", lambda: saved.get("model"))@@ -323,6 +449,10 @@ def test_clean_repo_saves_under_force(client, monkeypatch):"default_embedding_model": "unsloth/default-embed","default_embedding_gguf_repo": "unsloth/default-embed-GGUF","is_custom": True,+ # Nothing is held in this process, so Unload has nothing to offer.+ "loaded": False,+ # Nor is any other model, so the Unload control stays hidden too.+ "backend_loaded": False,}@@ -344,12 +474,12 @@ def test_sink_threads_ambient_token_into_scan(monkeypatch):# loader's own token to the scan, or it fails open for the repo that still loads.seen = {}mod = _types.ModuleType("utils.security")- mod.security_load_subdirs = (- lambda name, token = None: seen.setdefault("subdirs_token", token) or ()+ mod.security_load_subdirs = lambda name, token = None: (+ seen.setdefault("subdirs_token", token) or ()+ )+ mod.evaluate_file_security = lambda *a, **k: (+ seen.setdefault("scan_token", k.get("hf_token")) or _Decision(False))- mod.evaluate_file_security = lambda *a, **k: seen.setdefault(- "scan_token", k.get("hf_token")- ) or _Decision(False)monkeypatch.setitem(sys.modules, "utils.security", mod)import core.rag.embeddings as embeddings@@ -430,3 +560,153 @@ def test_security_block_is_not_swallowed_by_llama_fallback(monkeypatch):)with pytest.raises(embeddings.UnsafeEmbeddingModelError):embeddings._SentenceTransformersBackend().encode(["hi"])+++def _erroring_plan(model, backend, error):+ return settings.EmbeddingModelResolveResponse(+ embedding_model = model, backend = backend, error = error+ )+++def test_a_sentence_transformers_plan_error_is_refused_not_persisted(client, monkeypatch):+ """The PUT raised on plan.error only for llama destinations, so a repo passing+ the tag gate with no loadable checkpoint was persisted anyway."""+ c, saved = client+ monkeypatch.setitem(sys.modules, "utils.security", _security_stub(blocked = False))+ import utils.models as models++ monkeypatch.setattr(models, "is_embedding_model", lambda *a, **k: True)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _erroring_plan(+ model, "sentence-transformers", "No sentence-transformers weights found."+ ),+ )++ r = c.put("/embedding-model", json = {"embedding_model": "acme/gguf-only"})+ # 409, so the client can still offer "save anyway" as it does for a GGUF error.+ assert r.status_code == 409+ assert "No sentence-transformers weights found." in r.json()["detail"]+ assert "model" not in saved+++def test_forcing_over_a_failed_plan_stays_cache_only(client, monkeypatch):+ """Save anyway over a failed plan recorded no marker, so both loaders took+ their uncached path and fetched invisibly at the first index."""+ c, saved = client+ monkeypatch.setitem(sys.modules, "utils.security", _security_stub(blocked = False))+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: _erroring_plan(model, "sentence-transformers", "cannot resolve"),+ )++ r = c.put("/embedding-model", json = {"embedding_model": "acme/embedder", "force": True})++ assert r.status_code == 200+ assert saved["model"] == "acme/embedder"+ # Nothing was validated, so nothing is claimed...+ assert saved["backend"] is None+ assert saved["gguf_repo"] is None+ # ...but the loader still may not download behind the user's back.+ assert saved["download_pending"] is True+++def test_unload_is_offered_while_another_model_is_still_resident(client, monkeypatch):+ """Saving a new model does not release the old one, and `loaded` answers only+ about the selected one, so the previous model had no control to free it."""+ c, _saved = client+ import core.rag.embeddings as embeddings++ # A is resident; B is what Settings now names.+ monkeypatch.setattr(embeddings, "backend_is_loaded", lambda model_name = None: model_name is None)++ body = c.get("/embedding-model").json()+ assert body["loaded"] is False+ assert body["backend_loaded"] is True++ # Nothing resident at all: neither is claimed.+ monkeypatch.setattr(embeddings, "backend_is_loaded", lambda model_name = None: False)+ body = c.get("/embedding-model").json()+ assert body["loaded"] is False+ assert body["backend_loaded"] is False+++def test_the_resolved_repo_is_what_gets_verified_and_scanned(client, monkeypatch):+ """A slashless alias resolves under sentence-transformers/, but the PUT ran+ is_embedding_model and the malware scan against the literal name: a repo that+ usually does not exist (fail-open, or a forceable 409) or, worse, a different+ top-level repo that does."""+ c, saved = client+ seen = {}++ def _subdirs(name, token = None):+ seen["subdirs"] = name+ return ()++ def _scan(name, **_kwargs):+ seen["scanned"] = name+ return _Decision(False)++ def _is_embedding(name, **_kwargs):+ seen["verified"] = name+ return True++ mod = _types.ModuleType("utils.security")+ mod.security_load_subdirs = _subdirs+ mod.evaluate_file_security = _scan+ monkeypatch.setitem(sys.modules, "utils.security", mod)+ import utils.models as models++ monkeypatch.setattr(models, "is_embedding_model", _is_embedding)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: settings.EmbeddingModelResolveResponse(+ embedding_model = model,+ backend = "sentence-transformers",+ download_repo = "sentence-transformers/all-MiniLM-L6-v2",+ ),+ )++ r = c.put("/embedding-model", json = {"embedding_model": "all-MiniLM-L6-v2"})+ assert r.status_code == 200+ # The setting keeps what the user picked...+ assert saved["model"] == "all-MiniLM-L6-v2"+ # ...but every check ran against the repo the loader will open.+ assert seen["scanned"] == "sentence-transformers/all-MiniLM-L6-v2"+ assert seen["subdirs"] == "sentence-transformers/all-MiniLM-L6-v2"+ assert seen["verified"] == "sentence-transformers/all-MiniLM-L6-v2"+++def test_a_llama_download_repo_is_not_used_as_the_scan_target(client, monkeypatch):+ """Only the ST path may diverge: a llama download_repo is the GGUF companion,+ which is not the repo whose pickles this gate is about."""+ c, _saved = client+ seen = {}++ def _scan(name, **_kwargs):+ seen["scanned"] = name+ return _Decision(False)++ mod = _types.ModuleType("utils.security")+ mod.security_load_subdirs = lambda name, token = None: ()+ mod.evaluate_file_security = _scan+ monkeypatch.setitem(sys.modules, "utils.security", mod)+ import utils.models as models++ monkeypatch.setattr(models, "is_embedding_model", lambda *a, **k: True)+ monkeypatch.setattr(settings, "_llama_backend_active", lambda *_: True)+ monkeypatch.setattr(+ settings,+ "_resolve_embedding_model_plan",+ lambda model, token: settings.EmbeddingModelResolveResponse(+ embedding_model = model, backend = "llama", download_repo = f"{model}-GGUF"+ ),+ )++ r = c.put("/embedding-model", json = {"embedding_model": "acme/embedder"})+ assert r.status_code == 200+ # The llama path does not scan the ST repo at all, so nothing was scanned.+ assert "scanned" not in seendiff --git a/studio/backend/tests/test_embedding_model_settings.py b/studio/backend/tests/test_embedding_model_settings.pyindex bcf3ded71c9..47eea251ce1 100644--- a/studio/backend/tests/test_embedding_model_settings.py+++ b/studio/backend/tests/test_embedding_model_settings.py@@ -29,13 +29,27 @@ def settings_store(monkeypatch):store: dict = {}monkeypatch.setattr(- studio_db, "get_app_setting", lambda key, fallback = None: store.get(key, fallback)+ studio_db,+ "get_app_settings",+ lambda keys: {key: store[key] for key in keys if key in store},)monkeypatch.setattr(studio_db, "upsert_app_settings", lambda settings: store.update(settings) or store)++ def _cas(key, expected, value):+ if store.get(key) != expected:+ return False+ store[key] = value+ return True++ monkeypatch.setattr(studio_db, "compare_and_set_app_setting", _cas)+ # Process-wide and outliving the patched store, so a resolution recorded here+ # would answer for the same model in every later test file.+ ems._resolved_gguf_memo.clear()ems._invalidate_cache()yield store+ ems._resolved_gguf_memo.clear()ems._invalidate_cache()@@ -60,3 +74,328 @@ def test_env_default_derives_its_gguf_companion(monkeypatch):monkeypatch.setattr(rag_config, "EMBEDDING_MODEL", "org/env-default-embedder")assert rag_config.default_gguf_repo() == "org/env-default-embedder-GGUF"+++def test_env_default_keeps_its_resolved_gguf_without_becoming_custom(settings_store, monkeypatch):+ """An env default can resolve to an off-convention repo even though selecting+ it should not turn the default itself into a persisted override."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ monkeypatch.setattr(rag_config, "EMBEDDING_MODEL", "org/env-default-embedder")++ ems.set_rag_embedding_model(+ "org/env-default-embedder",+ gguf_repo = "org/published-conversion",+ backend = "llama-server",+ )++ assert ems.get_stored_embedding_model() is None+ assert ems.get_stored_gguf_repo("org/env-default-embedder") == "org/published-conversion"+ assert rag_config.effective_gguf_repo() == "org/published-conversion"+++def test_resolution_record_keeps_model_repo_and_backend_atomic(settings_store):+ ems.set_rag_embedding_model(+ "org/embedder",+ gguf_repo = "org/embedder-conversion",+ backend = "llama-server",+ )+ assert settings_store[ems.EMBEDDING_RESOLUTION_SETTING_KEY] == {+ "model": "org/embedder",+ "gguf_repo": "org/embedder-conversion",+ "backend": "llama-server",+ "download_pending": False,+ "gguf_files": None,+ }+ assert settings_store[ems.EMBEDDING_GGUF_SETTING_KEY] is None+ assert settings_store[ems.EMBEDDING_BACKEND_SETTING_KEY] is None+++def test_pending_download_is_stored_with_the_same_atomic_resolution(settings_store):+ ems.set_rag_embedding_model(+ "org/embedder",+ gguf_repo = "org/embedder-conversion",+ backend = "llama-server",+ download_pending = True,+ )+ assert ems.get_stored_download_pending("org/embedder") is True+ assert ems.get_stored_download_pending("org/another") is False+ assert settings_store[ems.EMBEDDING_RESOLUTION_SETTING_KEY]["download_pending"] is True+++def test_a_completed_transfer_retires_the_pending_marker(settings_store):+ """Nothing else clears it: the picker re-resolves after a download but does not+ save again, so a marker left behind pins the model cache-only for good and a+ later cache eviction reads as "never downloaded"."""+ ems.set_rag_embedding_model(+ "org/embedder",+ gguf_repo = "org/embedder-conversion",+ backend = "llama-server",+ download_pending = True,+ )++ assert ems.clear_stored_download_pending("org/embedder") is True+ assert ems.get_stored_download_pending("org/embedder") is False+ # The rest of the resolution survives: the loader still opens what was fetched.+ assert ems.get_stored_gguf_repo("org/embedder") == "org/embedder-conversion"+ assert ems.get_stored_backend("org/embedder") == "llama-server"+ # Idempotent, and never touches another model's record.+ assert ems.clear_stored_download_pending("org/embedder") is False+ assert ems.clear_stored_download_pending("org/another") is False+ assert ems.get_stored_gguf_repo("org/embedder") == "org/embedder-conversion"+++def test_a_concurrent_save_is_not_reverted_by_a_late_pending_clear(settings_store):+ """The loader reads model A's pending resolution, the user saves model B, and+ only then does the clear land. A plain upsert would put A's record back beside+ B's override, leaving B to re-derive a backend and a companion it never+ resolved. The write is conditional on the record it read."""+ ems.set_rag_embedding_model(+ "org/a", gguf_repo = "org/a-GGUF", backend = "llama-server", download_pending = True+ )+ stale = ems._get_stored_state() # A's loader has read it+ assert stale[1] == "org/a" and stale[4] is True+ ems.set_rag_embedding_model("org/b", gguf_repo = "org/b-GGUF", backend = "sentence-transformers")+ ems._cached = (0.0, stale) # its 2s snapshot still says A++ assert ems.clear_stored_download_pending("org/a") is False+ ems._invalidate_cache()+ assert ems.get_stored_gguf_repo("org/b") == "org/b-GGUF"+ assert ems.get_stored_backend("org/b") == "sentence-transformers"+ assert ems.get_stored_gguf_repo("org/a") is None+++def test_a_pinned_jobs_resolved_repo_survives_a_save_for_another_model(settings_store, monkeypatch):+ """One stored record, so saving B takes A's repo away while a job pinned to A+ is still ingesting, moving its identity to the derived A-GGUF mid-run."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ ems._resolved_gguf_memo.clear()+ from core.rag import config++ ems.set_rag_embedding_model(+ "org/embedder-a", gguf_repo = "mirror/off-convention-GGUF", backend = "llama-server"+ )+ assert config.effective_gguf_repo_for_embedding_model("org/embedder-a") == (+ "mirror/off-convention-GGUF"+ )++ ems.set_rag_embedding_model("org/embedder-b", gguf_repo = None, backend = None)++ # The stored record is B's now, and the staleness rule still holds.+ assert ems.get_stored_gguf_repo("org/embedder-a") is None+ # But the pinned job keeps embedding through the same mirror.+ assert config.effective_gguf_repo_for_embedding_model("org/embedder-a") == (+ "mirror/off-convention-GGUF"+ )+ # A model this process never resolved is still derived, not invented.+ assert config.effective_gguf_repo_for_embedding_model("org/never-seen") == (+ config.gguf_repo_for_embedding_model("org/never-seen")+ )+++def test_a_reset_keeps_the_repo_a_running_job_still_needs(settings_store, monkeypatch):+ """Reset clears the selection, but a job pinned to the old model is still+ ingesting through the repo that was resolved for it. The memo is per model and+ consulted only when the store has nothing, so dropping it here moved that job+ onto the derived <model>-GGUF mid-run."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ ems._resolved_gguf_memo.clear()+ from core.rag import config++ ems.set_rag_embedding_model(+ "org/embedder-a", gguf_repo = "mirror/off-convention-GGUF", backend = "llama-server"+ )+ assert ems.get_stored_gguf_repo("org/embedder-a") == "mirror/off-convention-GGUF"+ ems.reset_rag_embedding_model()++ # The stored selection is gone...+ assert ems.get_stored_embedding_model() is None+ # ...but the pinned job keeps embedding through the same mirror.+ assert ems.remembered_gguf_repo("org/embedder-a") == "mirror/off-convention-GGUF"+ assert config.effective_gguf_repo_for_embedding_model("org/embedder-a") == (+ "mirror/off-convention-GGUF"+ )+ # A model this process never resolved is still derived, not invented.+ assert config.effective_gguf_repo_for_embedding_model("org/never-seen") == (+ config.gguf_repo_for_embedding_model("org/never-seen")+ )+++def test_a_pinned_jobs_backend_and_pending_survive_a_save_for_another_model(+ settings_store, monkeypatch+):+ """On an auto CPU install a model with no GGUF resolves to+ sentence-transformers; losing that record drops a still-running job onto the+ hardware default, and losing the marker re-enables the implicit download."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ ems._resolved_gguf_memo.clear()++ ems.set_rag_embedding_model(+ "org/st-only",+ gguf_repo = None,+ backend = "sentence-transformers",+ download_pending = True,+ )+ assert ems.get_stored_backend("org/st-only") == "sentence-transformers"+ assert ems.get_stored_download_pending("org/st-only") is True++ ems.set_rag_embedding_model("org/other", gguf_repo = None, backend = "llama-server")++ assert ems.get_stored_backend("org/st-only") == "sentence-transformers"+ assert ems.get_stored_download_pending("org/st-only") is True+ # The newly saved model answers from the record, not the memo.+ assert ems.get_stored_backend("org/other") == "llama-server"+ # A model this process never resolved still has no opinion.+ assert ems.get_stored_backend("org/never-seen") is None+ assert ems.get_stored_download_pending("org/never-seen") is False+++def test_retiring_the_pending_marker_retires_it_in_the_memo_too(settings_store, monkeypatch):+ """Or a pinned job keeps reading pending=True and stays cache-only after the+ download landed."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ ems._resolved_gguf_memo.clear()++ ems.set_rag_embedding_model(+ "org/embedder",+ gguf_repo = None,+ backend = "sentence-transformers",+ download_pending = True,+ )+ assert ems.get_stored_download_pending("org/embedder") is True+ assert ems.clear_stored_download_pending("org/embedder") is True++ ems.set_rag_embedding_model("org/other", gguf_repo = None, backend = None)+ assert ems.get_stored_download_pending("org/embedder") is False+ # The backend it was resolved with is still remembered.+ assert ems.get_stored_backend("org/embedder") == "sentence-transformers"+++def test_a_reset_makes_the_restored_defaults_resolution_durable(settings_store, monkeypatch):+ """The memo survives a reset for jobs still pinned to a model, but the restored+ default is not a running job: new work resolves through it too, and a+ process-only answer would change identity on the next restart, stranding+ whatever was indexed in between."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ ems._resolved_gguf_memo.clear()+ default = ems.default_embedding_model()++ # The default itself was resolved to an off-convention mirror...+ ems.set_rag_embedding_model(+ default, gguf_repo = "mirror/off-convention-GGUF", backend = "llama-server"+ )+ assert ems.get_stored_gguf_repo(default) == "mirror/off-convention-GGUF"+ # ...then another model is selected, taking the single record with it...+ ems.set_rag_embedding_model("org/other", gguf_repo = None, backend = None)+ # ...and the selection is reset.+ assert ems.reset_rag_embedding_model() == default++ # The override is gone, but the default's resolution is durable again, not+ # living only in this process.+ assert ems.get_stored_embedding_model() is None+ ems._resolved_gguf_memo.clear()+ assert ems.get_stored_gguf_repo(default) == "mirror/off-convention-GGUF"+ assert ems.get_stored_backend(default) == "llama-server"+++def test_a_reset_with_nothing_remembered_stays_a_plain_reset(settings_store, monkeypatch):+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ ems._resolved_gguf_memo.clear()++ ems.set_rag_embedding_model("org/other", gguf_repo = None, backend = "sentence-transformers")+ assert ems.reset_rag_embedding_model() == ems.default_embedding_model()++ assert ems.get_stored_embedding_model() is None+ assert settings_store[ems.EMBEDDING_RESOLUTION_SETTING_KEY] is None+++def test_the_planned_gguf_family_is_stored_and_survives_the_clear(settings_store):+ """The loader needs the family to tell the quant the picker actually delivered+ from an unrelated one in the same repo. The clear is conditional on the record+ as read, so carrying an extra field must not make it a permanent no-op."""+ ems._resolved_gguf_memo.clear()+ ems.set_rag_embedding_model(+ "org/a",+ gguf_repo = "org/a-GGUF",+ backend = "llama-server",+ download_pending = True,+ gguf_files = ["a-Q8_0-00001-of-00002.gguf", "a-Q8_0-00002-of-00002.gguf"],+ )++ assert ems.get_stored_gguf_files("org/a") == [+ "a-Q8_0-00001-of-00002.gguf",+ "a-Q8_0-00002-of-00002.gguf",+ ]+ assert ems.clear_stored_download_pending("org/a") is True+ assert ems.get_stored_download_pending("org/a") is False+ # The family outlives the flag: it describes the artifact, not the transfer.+ assert ems.get_stored_gguf_files("org/a") == [+ "a-Q8_0-00001-of-00002.gguf",+ "a-Q8_0-00002-of-00002.gguf",+ ]+++def test_a_record_written_before_the_family_existed_still_clears(settings_store):+ """Upgrade path: an install that saved under the previous build has a record+ with no gguf_files key. Comparing against a rebuilt record would never match+ it, pinning every such model cache-only for good."""+ from storage.studio_db import upsert_app_settings++ ems._resolved_gguf_memo.clear()+ upsert_app_settings(+ {+ ems.EMBEDDING_MODEL_SETTING_KEY: "org/legacy",+ ems.EMBEDDING_RESOLUTION_SETTING_KEY: {+ "model": "org/legacy",+ "gguf_repo": "org/legacy-GGUF",+ "backend": "llama-server",+ "download_pending": True,+ },+ }+ )+ ems._invalidate_cache()++ assert ems.get_stored_gguf_files("org/legacy") is None+ assert ems.clear_stored_download_pending("org/legacy") is True+ assert ems.get_stored_download_pending("org/legacy") is False+++def test_a_reset_keeps_a_pending_only_resolution_for_the_default(settings_store):+ """A default saved over a failed resolution remembers no repo and no backend,+ only the pending flag, and that flag is the one thing keeping the first index+ from starting the implicit download this picker replaces."""+ ems._resolved_gguf_memo.clear()+ default = ems.default_embedding_model()+ ems.set_rag_embedding_model(default, download_pending = True)+ assert ems.get_stored_download_pending(default) is True++ ems.set_rag_embedding_model("org/other", gguf_repo = "org/other-GGUF", backend = "llama-server")+ assert ems.reset_rag_embedding_model() == default++ # Read the store, not the memo: the memo answers for this process either way,+ # and what the reset has to preserve is the record a restart will find.+ ems._resolved_gguf_memo.clear()+ ems._invalidate_cache()+ assert ems.get_stored_download_pending(default) is True+++def test_pinning_a_model_memoizes_what_was_resolved_for_it(settings_store, monkeypatch):+ """A worker pins its model by reading the effective one, then scans for a while+ and embeds afterwards. Only the repo/backend getters used to populate the memo,+ so a save for another model in that gap left the pinned job with nothing to+ fall back to and moved it onto the derived <model>-GGUF mid-run."""+ monkeypatch.delenv("RAG_EMBED_GGUF_REPO", raising = False)+ from core.rag import config++ ems.set_rag_embedding_model(+ "org/embedder-a", gguf_repo = "mirror/off-convention-GGUF", backend = "llama-server"+ )+ # Nothing has read the resolution yet; the pin is the only thing that happens.+ ems._resolved_gguf_memo.clear()+ assert config.effective_embedding_model() == "org/embedder-a"++ ems.set_rag_embedding_model("org/embedder-b", gguf_repo = None, backend = None)++ assert config.effective_gguf_repo_for_embedding_model("org/embedder-a") == (+ "mirror/off-convention-GGUF"+ )+ assert ems.get_stored_backend("org/embedder-a") == "llama-server"diff --git a/studio/backend/tests/test_offline_embedding_minimal.py b/studio/backend/tests/test_offline_embedding_minimal.pyindex ccc6b5f76aa..4162d21440a 100644--- a/studio/backend/tests/test_offline_embedding_minimal.py+++ b/studio/backend/tests/test_offline_embedding_minimal.py@@ -253,6 +253,111 @@ def test_snapshot_is_loadable_with_config_and_weights(hf_cache):assert hf_cache_snapshot_is_loadable("org/emb") is True+def test_snapshot_is_not_loadable_with_only_one_weight_shard(hf_cache):+ _make_cache(+ hf_cache,+ "org/partial-shards",+ {+ "config.json": "{}",+ "model.safetensors.index.json": (+ '{"weight_map":{"a":"model-00001-of-00002.safetensors",'+ '"b":"model-00002-of-00002.safetensors"}}'+ ),+ "model-00001-of-00002.safetensors": "first",+ },+ )+ assert hf_cache_snapshot_is_loadable("org/partial-shards") is False+++def test_snapshot_is_loadable_with_a_complete_indexed_weight_family(hf_cache):+ _make_cache(+ hf_cache,+ "org/complete-shards",+ {+ "config.json": "{}",+ "model.safetensors.index.json": (+ '{"weight_map":{"a":"model-00001-of-00002.safetensors",'+ '"b":"model-00002-of-00002.safetensors"}}'+ ),+ "model-00001-of-00002.safetensors": "first",+ "model-00002-of-00002.safetensors": "second",+ },+ )+ assert hf_cache_snapshot_is_loadable("org/complete-shards") is True+++def test_cancel_marker_keeps_a_snapshot_pending(monkeypatch, hf_cache):+ _make_cache(hf_cache, "org/cancelled", {"config.json": "{}", "model.safetensors": "x"})+ from hub.utils import download_manifest++ monkeypatch.setattr(download_manifest, "has_cancel_marker", lambda *a, **k: True)+ assert hf_cache_snapshot_is_loadable("org/cancelled") is False+++def test_snapshot_manifest_requires_every_expected_file(monkeypatch, hf_cache):+ _make_cache(hf_cache, "org/manifest-partial", {"config.json": "{}", "model.safetensors": "x"})+ from hub.utils import download_manifest++ manifest = download_manifest.Manifest(+ repo_type = "model",+ repo_id = "org/manifest-partial",+ variant = None,+ started_at = "",+ expected_files = (+ download_manifest.ExpectedFile(path = "config.json", size = 2),+ download_manifest.ExpectedFile(path = "model.safetensors", size = 1),+ download_manifest.ExpectedFile(path = "tokenizer.json", size = 10),+ ),+ )+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *a, **k: manifest)++ assert hf_cache_snapshot_is_loadable("org/manifest-partial") is False+++def test_verified_snapshot_manifest_ignores_unrelated_incomplete_blob(monkeypatch, hf_cache):+ _make_cache(+ hf_cache,+ "org/manifest-complete",+ {"config.json": "{}", "model.safetensors": "weights"},+ )+ from hub.utils import download_manifest++ manifest = download_manifest.Manifest(+ repo_type = "model",+ repo_id = "org/manifest-complete",+ variant = None,+ started_at = "",+ expected_files = (+ download_manifest.ExpectedFile(path = "config.json", size = 2),+ download_manifest.ExpectedFile(path = "model.safetensors", size = 7),+ ),+ )+ monkeypatch.setattr(download_manifest, "read_manifest", lambda *a, **k: manifest)+ monkeypatch.setattr(+ "hub.utils.hf_cache_state.repo_cache_dir_has_incomplete_blobs",+ lambda repo_dir: True,+ )++ assert hf_cache_snapshot_is_loadable("org/manifest-complete") is True+++def test_sentence_transformer_module_shards_must_be_complete(hf_cache):+ _make_cache(+ hf_cache,+ "org/st-partial",+ {+ "modules.json": _modules_json("0_Transformer"),+ "0_Transformer/config.json": "{}",+ "0_Transformer/model.safetensors.index.json": (+ '{"weight_map":{"a":"model-00001-of-00002.safetensors",'+ '"b":"model-00002-of-00002.safetensors"}}'+ ),+ "0_Transformer/model-00001-of-00002.safetensors": "first",+ },+ )+ assert hf_cache_snapshot_is_loadable("org/st-partial") is False++def test_snapshot_is_not_loadable_when_metadata_only(hf_cache):# A partial cache (refs/main resolves but no weights) is not loadable._make_cache(hf_cache, "org/partial", {"config.json": "{}", "modules.json": MODULES_JSON})@@ -940,3 +1045,462 @@ def test_get_online_omits_local_files_only(monkeypatch):_install_fake_sentence_transformers(monkeypatch, captured)embeddings._get("org/online")assert captured["local_files_only"] is False+++def test_an_unrelated_incomplete_blob_does_not_condemn_a_complete_snapshot(hf_cache):+ """The blob directory is shared by every revision and every scoped GGUF job in+ the repo, and caches predating managed downloads carry no manifest to appeal to.+ A stray partial from one of those used to make a model that was entirely on disk+ report as not downloaded, which the settings save then persisted as a pending+ transfer and the loader refused to index."""+ snapshot = _make_cache(+ hf_cache, "org/stray-blob", {"config.json": "{}", "model.safetensors": "x"}+ )+ blobs = Path(snapshot).parent.parent / "blobs"+ blobs.mkdir(parents = True, exist_ok = True)+ (blobs / "0badc0ffee.incomplete").write_text("half a file from another revision")++ assert hf_cache_snapshot_is_loadable("org/stray-blob") is True+++def test_a_snapshot_linking_to_an_unfinished_blob_is_still_pending(hf_cache):+ """The narrowing above must not lose the case it was guarding: a link this+ snapshot owns whose blob has not been finalized."""+ snapshot = Path(+ _make_cache(hf_cache, "org/dangling", {"config.json": "{}", "model.safetensors": "x"})+ )+ weights = snapshot / "model.safetensors"+ weights.unlink()+ weights.symlink_to(snapshot.parent.parent / "blobs" / "deadbeef")++ assert hf_cache_snapshot_is_loadable("org/dangling") is False+++def test_get_online_loads_the_snapshot_settings_called_cached(hf_cache, monkeypatch):+ """Settings reports on-device from `hf_cache_snapshot_is_loadable`, so handing+ SentenceTransformer the repo id is what lets it fetch a revision published+ since and change the vectors without changing the identity they carry. The+ picker exists to replace exactly that transfer."""+ from core.rag import embeddings++ snapshot = _make_cache(+ hf_cache, "org/fresh", {"modules.json": MODULES_JSON, "model.safetensors": "x"}+ )+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ monkeypatch.setattr(embeddings, "_model", None, raising = False)+ monkeypatch.setattr(embeddings, "_name", None, raising = False)+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda name, local_only = False: None)+ captured = {}+ _install_fake_sentence_transformers(monkeypatch, captured)++ embeddings._get("org/fresh")++ assert captured["name"] == str(snapshot)+++def test_an_uncached_model_online_still_loads_by_repo_id(monkeypatch):+ """The pin above must not turn a first-ever load into a failure: with nothing+ cached there is no snapshot to prefer, so the repo id still goes to the Hub."""+ from core.rag import embeddings++ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ monkeypatch.delenv("TRANSFORMERS_OFFLINE", raising = False)+ monkeypatch.setattr(embeddings, "_model", None, raising = False)+ monkeypatch.setattr(embeddings, "_name", None, raising = False)+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda name, local_only = False: None)+ captured = {}+ _install_fake_sentence_transformers(monkeypatch, captured)++ embeddings._get("org/never-fetched-xyz")++ assert captured["name"] == "org/never-fetched-xyz"+++def test_a_module_declared_but_absent_makes_the_snapshot_incomplete(monkeypatch, tmp_path):+ """Only module roots already carrying weights were validated, so a snapshot+ missing 0_Transformer entirely passed on a complete 2_Dense."""+ from utils import utils++ snapshot = tmp_path / "snap"+ dense = snapshot / "2_Dense"+ dense.mkdir(parents = True)+ (snapshot / "config.json").write_text("{}")+ (snapshot / "modules.json").write_text(+ '[{"path": "0_Transformer"}, {"path": "1_Pooling"}, {"path": "2_Dense"}]'+ )+ (dense / "model.safetensors").write_bytes(b"ST")+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)++ assert utils.hf_cache_snapshot_is_loadable("org/torn") is False++ # A config-only module needs no weights of its own, so its bare presence is+ # enough; what was missing before is the directory, not the checkpoint.+ (snapshot / "1_Pooling").mkdir()+ (snapshot / "0_Transformer").mkdir()+ (snapshot / "0_Transformer" / "model.safetensors").write_bytes(b"ST")+ assert utils.hf_cache_snapshot_is_loadable("org/torn") is True+++def test_an_eviction_between_the_check_and_the_snapshot_keeps_the_marker(monkeypatch):+ """Retired off the loadable check alone, an eviction landing before+ hf_cache_snapshot_dir cleared the marker AND raised, freeing the next attempt+ to reach the Hub."""+ from core.rag import embeddings+ import utils.embedding_model_settings as ems+ import utils.utils as utils++ cleared = []+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda m: cleared.append(m) or True)+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ # Evicted in the window between the two calls.+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: None)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: None)+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ st_mod = types.ModuleType("sentence_transformers")+ st_mod.SentenceTransformer = lambda *_a, **_k: SimpleNamespace(tokenizer = None)+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ embeddings._model = None+ embeddings._name = None++ try:+ with pytest.raises(embeddings.EmbeddingModelDownloadRequiredError):+ embeddings._get("org/evicted")+ finally:+ embeddings._model = None+ embeddings._name = None++ assert cleared == [], "the marker outlives a load that could not find the snapshot"+++def test_a_gguf_only_cache_does_not_retire_the_pending_st_marker(monkeypatch, tmp_path):+ """hf_cache_snapshot_is_loadable counts .gguf, so a hybrid repo whose GGUF is+ cached while its sentence-transformers snapshot is still downloading retired+ the marker and handed SentenceTransformer a GGUF-only snapshot."""+ from core.rag import embeddings+ import utils.embedding_model_settings as ems+ import utils.utils as utils++ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model-Q8_0.gguf").write_bytes(b"GGUF")++ cleared = []+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda m: cleared.append(m) or True)+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda m: True)+ # The shared predicate says yes; the ST-specific one must not.+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ st_mod = types.ModuleType("sentence_transformers")+ st_mod.SentenceTransformer = lambda *_a, **_k: SimpleNamespace(tokenizer = None)+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ embeddings._model = None+ embeddings._name = None++ assert utils.snapshot_has_st_weights("org/hybrid") is False+ try:+ with pytest.raises(embeddings.EmbeddingModelDownloadRequiredError):+ embeddings._get("org/hybrid")+ finally:+ embeddings._model = None+ embeddings._name = None++ assert cleared == [], "the advertised ST transfer has not landed yet"+++def test_a_partial_st_transfer_keeps_the_pending_marker(monkeypatch, tmp_path):+ """ST weights alone are satisfied by the first finalized shard of a transfer+ still in flight. Clearing the marker there and loading the partial snapshot+ means a later cancel plus eviction leaves the next attempt free to download."""+ from core.rag import embeddings+ import utils.embedding_model_settings as ems+ import utils.utils as utils++ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model-00001-of-00003.safetensors").write_bytes(b"ST")++ cleared = []+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda m: cleared.append(m) or True)+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)+ # The ST family is there; the snapshot as a whole is not complete.+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: False)+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ st_mod = types.ModuleType("sentence_transformers")+ st_mod.SentenceTransformer = lambda *_a, **_k: SimpleNamespace(tokenizer = None)+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ embeddings._model = None+ embeddings._name = None++ assert utils.cached_st_source("org/partial") is None+ try:+ with pytest.raises(embeddings.EmbeddingModelDownloadRequiredError):+ embeddings._get("org/partial")+ finally:+ embeddings._model = None+ embeddings._name = None++ assert cleared == [], "the planned snapshot has not landed in full yet"+++def test_the_alias_snapshot_is_the_one_loaded(monkeypatch, tmp_path):+ """cached_st_source can match under sentence-transformers/ while a separate+ hf_cache_snapshot_dir lookup returns a stale literal entry. Pinning that one+ hands SentenceTransformer the wrong directory while the valid alias snapshot+ sits right there."""+ from core.rag import embeddings+ import utils.utils as utils++ literal = tmp_path / "literal"+ literal.mkdir()+ (literal / "config.json").write_text("{}")+ alias = tmp_path / "alias"+ alias.mkdir()+ (alias / "config.json").write_text("{}")+ (alias / "model.safetensors").write_bytes(b"ST")++ def _dir(repo):+ return alias if repo == "sentence-transformers/all-MiniLM-L6-v2" else literal++ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", _dir)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", _dir)+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)++ assert utils.cached_st_source("all-MiniLM-L6-v2") == (+ "sentence-transformers/all-MiniLM-L6-v2",+ alias,+ )++ loaded = {}+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ st_mod = types.ModuleType("sentence_transformers")++ def _st(target, **_kwargs):+ loaded["target"] = target+ return SimpleNamespace(tokenizer = None)++ st_mod.SentenceTransformer = _st+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ embeddings._model = None+ embeddings._name = None+ try:+ embeddings._get("all-MiniLM-L6-v2")+ finally:+ embeddings._model = None+ embeddings._name = None++ assert loaded["target"] == str(alias)+++def test_a_pending_transfer_does_not_make_the_security_scan_offline(monkeypatch, tmp_path):+ """`local_only` folds two questions together: load from cache, and is the Hub+ reachable. The security gate needs the second. Told offline while online it+ applies the fail-closed cached-pickle rule and rejects a .bin-only repo the+ resolver just accepted and scanned, failing the first index outright."""+ from core.rag import embeddings+ import utils.embedding_model_settings as ems+ import utils.utils as utils++ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "pytorch_model.bin").write_bytes(b"ST")++ seen = {}+ monkeypatch.setattr(+ embeddings,+ "_guard_model_security",+ lambda target, local_only = False: seen.update(target = target, local_only = local_only),+ )+ # Pending, but the Hub is reachable.+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda m: True)+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ st_mod = types.ModuleType("sentence_transformers")+ st_mod.SentenceTransformer = lambda *_a, **_k: SimpleNamespace(tokenizer = None)+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ embeddings._model = None+ embeddings._name = None+ try:+ embeddings._get("org/bin-only")+ finally:+ embeddings._model = None+ embeddings._name = None++ # The load still came from the cache...+ assert seen["target"] == str(snapshot)+ # ...but the gate was told the truth about the network.+ assert seen["local_only"] is False++ # Genuinely offline still scans offline.+ seen.clear()+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ embeddings._model = None+ embeddings._name = None+ try:+ embeddings._get("org/bin-only")+ finally:+ embeddings._model = None+ embeddings._name = None+ assert seen["local_only"] is True+++def test_a_failed_st_constructor_keeps_the_pending_marker(monkeypatch, tmp_path):+ """The snapshot can be complete while the constructor still fails: an+ unsupported architecture, or a device that cannot initialize. Retiring the+ marker before that point let _build_st_backend_or_fallback swap to+ llama-server with nothing left to stop it fetching the GGUF companion during+ the first index."""+ from core.rag import embeddings+ import utils.embedding_model_settings as ems+ import utils.utils as utils++ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model.safetensors").write_bytes(b"ST")++ cleared = []+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda m: cleared.append(m) or True)+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda m: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda m: snapshot)+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)++ def _boom(*_a, **_k):+ raise RuntimeError("unsupported architecture")++ st_mod = types.ModuleType("sentence_transformers")+ st_mod.SentenceTransformer = _boom+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.setenv("HF_HUB_OFFLINE", "1")+ embeddings._model = None+ embeddings._name = None+ try:+ with pytest.raises(RuntimeError, match = "unsupported architecture"):+ embeddings._get("org/unloadable")+ finally:+ embeddings._model = None+ embeddings._name = None++ assert cleared == [], "a llama fallback must not inherit a cleared marker"++ # It does retire once the model actually constructs.+ st_mod.SentenceTransformer = lambda *_a, **_k: SimpleNamespace(tokenizer = None)+ embeddings._model = None+ embeddings._name = None+ try:+ embeddings._get("org/unloadable")+ finally:+ embeddings._model = None+ embeddings._name = None+ assert cleared == ["org/unloadable"]+++def test_a_local_path_is_not_replaced_by_a_hub_cache_of_the_same_name(monkeypatch, tmp_path):+ """The picker takes a slashless relative directory, so a local folder can share+ its name with a cached Hub model. Resolving the cache for it handed+ SentenceTransformer the Hub's weights while the vectors kept the local path's+ identity: a silent swap of the artifact the user selected."""+ from core.rag import embeddings+ import utils.utils as utils++ local = tmp_path / "all-MiniLM-L6-v2"+ local.mkdir()+ (local / "config.json").write_text("{}")+ (local / "model.safetensors").write_bytes(b"LOCAL")+ hub = tmp_path / "hub-snapshot"+ hub.mkdir()+ (hub / "config.json").write_text("{}")+ (hub / "model.safetensors").write_bytes(b"HUB")++ # The same name is cached under the namespace, which is what shadowed it.+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda repo: hub)+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir_for_repo", lambda repo: hub)+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)++ loaded = {}+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ st_mod = types.ModuleType("sentence_transformers")++ def _st(target, **_kwargs):+ loaded["target"] = target+ return SimpleNamespace(tokenizer = None)++ st_mod.SentenceTransformer = _st+ monkeypatch.setitem(sys.modules, "sentence_transformers", st_mod)+ monkeypatch.delenv("HF_HUB_OFFLINE", raising = False)+ embeddings._model = None+ embeddings._name = None+ try:+ embeddings._get(str(local))+ finally:+ embeddings._model = None+ embeddings._name = None++ assert loaded["target"] == str(local)+++def test_an_alias_cache_hit_names_the_namespace_that_supplied_it(monkeypatch, tmp_path):+ """Real cache layout, no stub over the lookup: hf_cache_snapshot_dir tries the+ ST alias itself, so asking it about the literal slashless name returned the+ namespaced snapshot paired with a repo id that had supplied nothing. The+ resolver reports that id, and the PUT verifies and scans it."""+ import utils.utils as utils++ hub = tmp_path / "hub"+ repo_dir = hub / "models--sentence-transformers--all-MiniLM-L6-v2"+ snapshot = repo_dir / "snapshots" / "abc123"+ snapshot.mkdir(parents = True)+ (repo_dir / "refs").mkdir()+ (repo_dir / "refs" / "main").write_text("abc123", encoding = "utf-8")+ (snapshot / "config.json").write_text("{}")+ (snapshot / "model.safetensors").write_bytes(b"ST")+ monkeypatch.setattr(utils, "_hf_cache_roots", lambda: [hub])+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda m: True)++ assert utils.cached_st_source("all-MiniLM-L6-v2") == (+ "sentence-transformers/all-MiniLM-L6-v2",+ snapshot,+ )diff --git a/studio/backend/tests/test_rag_embed_llama_server.py b/studio/backend/tests/test_rag_embed_llama_server.pyindex 1d3a32d053e..e56dc5bc397 100644--- a/studio/backend/tests/test_rag_embed_llama_server.py+++ b/studio/backend/tests/test_rag_embed_llama_server.py@@ -7,6 +7,7 @@ import osimport subprocessimport sysimport textwrap+import threadingimport timeimport typesfrom pathlib import Path@@ -94,6 +95,33 @@ def test_unknown_backend_raises(monkeypatch):embeddings._get_backend()+def test_shutdown_waits_for_an_active_embedding_operation(monkeypatch):+ backend = LlamaServerBackend()+ entered = threading.Event()+ finish = threading.Event()+ shutdown_done = threading.Event()++ def _post(path, payload, **_kwargs):+ entered.set()+ assert finish.wait(timeout = 2)+ return {"data": [{"index": 0, "embedding": [1.0, 0.0]}]}++ monkeypatch.setattr(backend, "_post", _post)+ worker = threading.Thread(target = lambda: backend.encode(["x"]))+ worker.start()+ assert entered.wait(timeout = 2)++ closer = threading.Thread(target = lambda: (backend._shutdown(), shutdown_done.set()))+ closer.start()+ assert shutdown_done.wait(timeout = 0.05) is False+ finish.set()+ worker.join(timeout = 2)+ closer.join(timeout = 2)+ assert shutdown_done.is_set()+ with pytest.raises(RuntimeError, match = "unloaded"):+ backend.encode(["x"])++def test_explicit_backend_overrides_auto(monkeypatch):_stub_st_load(monkeypatch)monkeypatch.setattr(config, "EMBED_BACKEND", "sentence-transformers")@@ -276,7 +304,9 @@ def _patch_spawn_deps(# Force CPU so spawn never depends on a host GPU.monkeypatch.setattr(config, "EMBED_DEVICE", "cpu")monkeypatch.setattr(LlamaServerBackend, "_resolve_binary", lambda self: "/bin/llama-server")- monkeypatch.setattr(LlamaServerBackend, "_resolve_model_path", lambda self: "/m/bge.gguf")+ monkeypatch.setattr(+ LlamaServerBackend, "_resolve_model_path", lambda self, model_name = None: "/m/bge.gguf"+ )monkeypatch.setattr(LlamaServerBackend, "_find_free_port", staticmethod(lambda: free_port))monkeypatch.setattr(mod.subprocess, "Popen", lambda *a, **k: proc)@@ -313,7 +343,7 @@ def test_spawn_auto_falls_back_to_cpu_on_gpu_failure(monkeypatch):b = LlamaServerBackend()calls = []- def fake_spawn_once(use_gpu):+ def fake_spawn_once(use_gpu, model_name = None):calls.append(use_gpu)if use_gpu:raise RuntimeError("CUDA out of memory")@@ -328,7 +358,7 @@ def test_spawn_explicit_gpu_does_not_fall_back(monkeypatch):monkeypatch.setattr(config, "EMBED_DEVICE", "gpu")b = LlamaServerBackend()- def fake_spawn_once(use_gpu):+ def fake_spawn_once(use_gpu, model_name = None):raise RuntimeError("CUDA out of memory")monkeypatch.setattr(b, "_spawn_once", fake_spawn_once)@@ -345,10 +375,10 @@ def _embed_response(vectors):def test_encode_orders_and_returns_float32(monkeypatch):b = LlamaServerBackend()- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)captured = {}- def fake_post(path, payload):+ def fake_post(path, payload, **_kwargs):captured["path"] = pathcaptured["input"] = payload["input"]return _embed_response([[3.0, 4.0], [0.0, 5.0]])@@ -363,8 +393,8 @@ def test_encode_orders_and_returns_float32(monkeypatch):def test_encode_normalizes(monkeypatch):b = LlamaServerBackend()- monkeypatch.setattr(b, "_ensure_ready", lambda: None)- monkeypatch.setattr(b, "_post", lambda p, pl: _embed_response([[3.0, 4.0]]))+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)+ monkeypatch.setattr(b, "_post", lambda p, pl, **_k: _embed_response([[3.0, 4.0]]))out = b.encode(["a"], normalize = True)np.testing.assert_allclose(np.linalg.norm(out, axis = 1), [1.0], rtol = 1e-6)@@ -372,7 +402,7 @@ def test_encode_normalizes(monkeypatch):def test_encode_empty_returns_zero_rows(monkeypatch):b = LlamaServerBackend()b._dim = 384- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)out = b.encode([])assert out.shape == (0, 384)assert out.dtype == np.float32@@ -380,8 +410,10 @@ def test_encode_empty_returns_zero_rows(monkeypatch):def test_encode_rejects_count_mismatch(monkeypatch):b = LlamaServerBackend()- monkeypatch.setattr(b, "_ensure_ready", lambda: None)- monkeypatch.setattr(b, "_post", lambda p, pl: {"data": [{"index": 0, "embedding": [1.0]}]})+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)+ monkeypatch.setattr(+ b, "_post", lambda p, pl, **_k: {"data": [{"index": 0, "embedding": [1.0]}]}+ )with pytest.raises(RuntimeError, match = "vectors for"):b.encode(["a", "b"], normalize = False)@@ -389,10 +421,10 @@ def test_encode_rejects_count_mismatch(monkeypatch):def test_encode_batches(monkeypatch):monkeypatch.setattr(config, "EMBED_BATCH", 2)b = LlamaServerBackend()- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)calls = []- def fake_post(path, payload):+ def fake_post(path, payload, **_kwargs):chunk = payload["input"]calls.append(len(chunk))return _embed_response([[1.0, 0.0]] * len(chunk))@@ -405,10 +437,10 @@ def test_encode_batches(monkeypatch):def test_dim_probes_once_and_caches(monkeypatch):b = LlamaServerBackend()- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)n_calls = {"n": 0}- def fake_post(path, payload):+ def fake_post(path, payload, **_kwargs):n_calls["n"] += 1return _embed_response([[0.1] * 384])@@ -420,10 +452,10 @@ def test_dim_probes_once_and_caches(monkeypatch):def test_token_counter_hits_tokenize(monkeypatch):b = LlamaServerBackend()- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)seen = {}- def fake_post(path, payload):+ def fake_post(path, payload, **_kwargs):seen["path"] = pathseen["content"] = payload["content"]return {"tokens": [1, 2, 3, 4]}@@ -440,7 +472,7 @@ def test_ensure_ready_respawns_dead_process(monkeypatch):b._process = _FakeProc(alive = False, returncode = 0)spawned = {"n": 0}- def fake_spawn():+ def fake_spawn(model_name = None):spawned["n"] += 1b._process = _FakeProc(alive = True)# _current() now also checks the served repo, so mark it current.@@ -471,7 +503,7 @@ def test_path_save_restarts_embedder_with_new_binary(monkeypatch):)spawned = []- def fake_spawn():+ def fake_spawn(model_name = None):spawned.append(backend._binary)backend._process = _FakeProc(alive = True)backend._model_repo = config.effective_gguf_repo()@@ -490,9 +522,11 @@ def test_post_restarts_once_on_connect_error(monkeypatch):b = LlamaServerBackend()b._port = 9000- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)restarts = {"n": 0}- monkeypatch.setattr(b, "_restart", lambda: restarts.__setitem__("n", restarts["n"] + 1))+ monkeypatch.setattr(+ b, "_restart", lambda *_a, **_k: restarts.__setitem__("n", restarts["n"] + 1)+ )attempts = {"n": 0}@@ -523,9 +557,11 @@ def test_post_restarts_once_on_read_timeout(monkeypatch):b = LlamaServerBackend()b._port = 9000- monkeypatch.setattr(b, "_ensure_ready", lambda: None)+ monkeypatch.setattr(b, "_ensure_ready", lambda *_a, **_k: None)restarts = {"n": 0}- monkeypatch.setattr(b, "_restart", lambda: restarts.__setitem__("n", restarts["n"] + 1))+ monkeypatch.setattr(+ b, "_restart", lambda *_a, **_k: restarts.__setitem__("n", restarts["n"] + 1)+ )attempts = {"n": 0}@@ -665,7 +701,11 @@ def test_gpu_opt_in_still_falls_back_to_cpu(monkeypatch):backend = LlamaServerBackend()calls: list[bool] = []- def fake_spawn_once(use_gpu, _calls = calls):+ def fake_spawn_once(+ use_gpu,+ model_name = None,+ _calls = calls,+ ):_calls.append(use_gpu)if use_gpu:raise RuntimeError("GPU start failed")@@ -682,7 +722,9 @@ def test_literal_gpu_remains_a_hard_request(monkeypatch):monkeypatch.setattr(config, "EMBED_DEVICE", requested)backend = LlamaServerBackend()monkeypatch.setattr(- backend, "_spawn_once", lambda use_gpu: (_ for _ in ()).throw(RuntimeError("no cuda"))+ backend,+ "_spawn_once",+ lambda use_gpu, *_a: (_ for _ in ()).throw(RuntimeError("no cuda")),)with pytest.raises(RuntimeError, match = "no cuda"):backend._spawn()@@ -701,7 +743,11 @@ def test_a_soft_gpu_opt_in_keeps_its_own_cpu_fallback(monkeypatch):backend = LlamaServerBackend()calls: list[bool] = []- def fake_spawn_once(use_gpu, _calls = calls):+ def fake_spawn_once(+ use_gpu,+ model_name = None,+ _calls = calls,+ ):_calls.append(use_gpu)if use_gpu:raise RuntimeError("GPU start failed")@@ -934,6 +980,44 @@ def test_an_unreachable_hub_falls_back_to_whatever_variant_is_cached(monkeypatchassert backend._resolve_model_path().endswith("bge-Q8_0.gguf")+def test_a_pending_picker_download_never_falls_through_to_the_hub(monkeypatch, tmp_path):+ import utils.embedding_model_settings as ems++ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: "org/pending-GGUF")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ _use_cache_root(monkeypatch, tmp_path / "empty")+ backend = LlamaServerBackend()+ monkeypatch.setattr(+ backend,+ "_resolve_uncached_model_path",+ lambda *a: (_ for _ in ()).throw(AssertionError("pending model reached the Hub")),+ )++ with pytest.raises(RuntimeError, match = "not downloaded yet"):+ backend._resolve_model_path()+++def test_a_completed_pending_download_uses_its_cached_fallback_quant(monkeypatch, tmp_path):+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ _seed_cache(tmp_path / "hub", repo, ["pending-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()+ monkeypatch.setattr(+ backend,+ "_resolve_uncached_model_path",+ lambda *a: (_ for _ in ()).throw(AssertionError("cached pending model reached Hub")),+ )++ assert backend._resolve_model_path().endswith("pending-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 companionahead of the fallback. Offline that ordering is moot and the fallback repo's cache is@@ -1130,3 +1214,486 @@ def test_the_hub_resolve_runs_inside_the_unreachable_guard(monkeypatch, tmp_pathbackend = LlamaServerBackend()assert backend._resolve_model_path() == "/cache/bge-F16.gguf"assert active == []+++def test_a_split_family_is_downloaded_whole_not_just_its_first_shard(monkeypatch, tmp_path):+ """`-m shard1` makes llama-server open the siblings itself.++ Fetching only the picked file leaves it starting against a repo it just+ downloaded and failing on the shards that were never asked for.+ """+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ names = [+ "bge-F16-00001-of-00003.gguf",+ "bge-F16-00002-of-00003.gguf",+ "bge-F16-00003-of-00003.gguf",+ ]+ fetched = []+ _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: names)+ monkeypatch.setattr(+ huggingface_hub,+ "hf_hub_download",+ lambda **kw: (fetched.append(kw["filename"]), f"/cache/{kw['filename']}")[1],+ )+ backend = LlamaServerBackend()++ assert backend._resolve_model_path() == "/cache/bge-F16-00001-of-00003.gguf"+ assert fetched == names+++def test_a_torn_published_family_is_skipped_rather_than_half_fetched(monkeypatch, tmp_path):+ """Shard 2 missing on the hub is not a repo to adopt; the candidate loop moves on."""+ import contextlib+ import huggingface_hub+ from core.inference import llama_cpp++ _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-00001-of-00003.gguf", "bge-F16-00003-of-00003.gguf"],+ )+ monkeypatch.setattr(+ huggingface_hub,+ "hf_hub_download",+ lambda **kw: pytest.fail("a torn family must not be fetched"),+ )+ backend = LlamaServerBackend()+ with pytest.raises(RuntimeError, match = "no .gguf embedder found"):+ backend._resolve_model_path()+++def test_a_local_dir_of_shards_resolves_to_shard_one_in_any_scan_order(monkeypatch, tmp_path):+ """`iterdir` guarantees no order, and every shard name here is the same length,+ so a length-only sort let the directory decide which shard llama-server opened."""+ names = [+ "bge-F16-00001-of-00003.gguf",+ "bge-F16-00002-of-00003.gguf",+ "bge-F16-00003-of-00003.gguf",+ ]+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ orders = [names, list(reversed(names)), [names[1], names[2], names[0]]]+ real_iterdir = Path.iterdir+ for index, order in enumerate(orders):+ d = tmp_path / f"dir{index}"+ d.mkdir()+ for name in order:+ (d / name).write_bytes(b"")+ monkeypatch.setattr(+ Path,+ "iterdir",+ lambda self, o = order, r = real_iterdir: (+ iter([self / n for n in o]) if self == d else r(self)+ ),+ )+ picked = LlamaServerBackend._resolve_local_gguf(str(d))+ assert Path(picked).name == "bge-F16-00001-of-00003.gguf"+++def test_a_local_dir_with_a_torn_family_is_refused(monkeypatch, tmp_path):+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ d = tmp_path / "torn"+ d.mkdir()+ for n in ("bge-F16-00001-of-00003.gguf", "bge-F16-00003-of-00003.gguf"):+ (d / n).write_bytes(b"")+ with pytest.raises(RuntimeError, match = "no .gguf file found"):+ LlamaServerBackend._resolve_local_gguf(str(d))+++def test_a_local_dir_still_skips_mmproj_and_appledouble_sidecars(tmp_path):+ """macOS copies leave `._name` sidecars beside the real file."""+ d = tmp_path / "local"+ d.mkdir()+ (d / "mmproj-bge.gguf").write_bytes(b"")+ (d / "._bge.gguf").write_bytes(b"\x00\x05\x16\x07")+ (d / "bge.gguf").write_bytes(b"")+ assert Path(LlamaServerBackend._resolve_local_gguf(str(d))).name == "bge.gguf"+++def test_a_wsl_drive_letter_dir_resolves_like_the_other_local_probes(monkeypatch, tmp_path):+ """`normalize_path` maps `C:\\...` onto `/mnt/c/...` under WSL, and the+ sentence-transformers and settings probes already run through it. This one did+ not, so the same folder was a local model on one backend and an unknown Hub repo+ on the other, failing with "No GGUF weights found in 'C:\\models\\...-GGUF'"."""+ from utils.paths import path_utils++ drive = tmp_path / "mnt" / "c" / "models"+ drive.mkdir(parents = True)+ (drive / "bge-F16.gguf").write_bytes(b"")+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(path_utils, "_IS_WSL", True)+ monkeypatch.setattr(+ path_utils,+ "normalize_path",+ lambda p: (+ str(tmp_path / "mnt" / p[0].lower() / p[3:].replace("\\", "/"))+ if len(p) >= 3 and p[1] == ":"+ else p+ ),+ )+ import utils.paths as paths_pkg++ monkeypatch.setattr(paths_pkg, "normalize_path", path_utils.normalize_path)++ picked = LlamaServerBackend._resolve_local_gguf(r"C:\models")+ assert picked is not None and Path(picked).name == "bge-F16.gguf"+++def test_a_posix_path_is_untouched_by_the_normalization(tmp_path):+ """The rewrite must not start mangling ordinary POSIX paths."""+ d = tmp_path / "plain"+ d.mkdir()+ (d / "bge.gguf").write_bytes(b"")+ assert Path(LlamaServerBackend._resolve_local_gguf(str(d))).name == "bge.gguf"+++def test_a_stand_in_quant_does_not_retire_the_pending_marker(monkeypatch, tmp_path):+ """The advertised transfer has not landed: reaching the relaxed pass means the+ configured variant is absent, so what gets served is a leftover from an earlier+ setting. Clearing the marker on it would pin the model to that quant for good."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ cleared = []+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda model: cleared.append(model))+ _seed_cache(tmp_path / "hub", repo, ["pending-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._resolve_model_path().endswith("pending-Q8_0.gguf")+ assert cleared == [], "a stand-in quant is not the transfer that was advertised"+++def test_the_planned_variant_landing_retires_the_pending_marker(monkeypatch, tmp_path):+ """The other half: the configured variant in the preferred repo IS what the+ picker advertised, so the marker has been answered and must not outlive it."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ cleared = []+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda model: cleared.append(model))+ _seed_cache(tmp_path / "hub", repo, ["pending-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._resolve_model_path().endswith("pending-F16.gguf")+ assert cleared == ["org/pending"]+++def test_the_planned_fallback_quant_landing_retires_the_pending_marker(monkeypatch, tmp_path):+ """A repo publishing no F16 is downloaded as whatever quant it does publish, so+ the variant-matching pass never recognizes the finished transfer. Left that way+ the model is cache-only for the life of the install, and a later eviction is+ refused as "not downloaded" though the advertised download completed."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ cleared = []+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ # What the picker planned and the download manager fetched.+ monkeypatch.setattr(ems, "get_stored_gguf_files", lambda model: ["pending-Q8_0.gguf"])+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda model: cleared.append(model))+ _seed_cache(tmp_path / "hub", repo, ["pending-Q8_0.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._resolve_model_path().endswith("pending-Q8_0.gguf")+ assert cleared == ["org/pending"]+++def test_a_pinned_request_serves_the_pinned_models_gguf_not_the_live_setting(monkeypatch):+ """One subprocess serves one GGUF, and the lifecycle read the live setting, so+ a job pinned to A served B's weights while still tagging its vectors A."""+ from core.rag import config++ b = LlamaServerBackend()+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/model-b")+ monkeypatch.setattr(+ config,+ "effective_gguf_repo_for_embedding_model",+ lambda model: f"{model}-GGUF",+ )+ monkeypatch.setattr(b, "_process_alive", lambda: True)+ monkeypatch.setattr(b, "_binary_path_revision", None, raising = False)+ import utils.llama_cpp_path_settings as paths++ monkeypatch.setattr(paths, "custom_llama_cpp_path_revision", lambda: None)++ # A live server on A's weights.+ b._model_repo = "org/model-a-GGUF"++ # The live setting is B, so an unpinned request finds the server stale.+ assert b._current() is False+ # A request pinned to A is served by exactly that server, no respawn.+ assert b._current("org/model-a") is True+ # And a request pinned to B is not.+ assert b._current("org/model-b") is False+++def test_resolution_follows_the_pinned_model(monkeypatch, tmp_path):+ """_resolve_model_path derived the repo and the local-path probe from the live+ setting, so the pinned model reached neither."""+ from core.rag import config++ gguf = tmp_path / "pinned.gguf"+ gguf.write_bytes(b"GGUF")+ b = LlamaServerBackend()+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/model-b")+ monkeypatch.setattr(+ config, "effective_gguf_repo_for_embedding_model", lambda model: f"{model}-GGUF"+ )+ seen = []+ monkeypatch.setattr(+ LlamaServerBackend,+ "_resolve_local_gguf",+ staticmethod(+ lambda model: seen.append(model) or (str(gguf) if "model-a" in model else None)+ ),+ )++ assert b._resolve_model_path("org/model-a") == str(gguf)+ assert seen == ["org/model-a"]+ # Tagged with the repo it was resolved FOR, so a later unpinned request sees+ # it as stale rather than serving A's weights under B's name.+ assert b._model_repo == "org/model-a-GGUF"+++def test_a_swap_cannot_land_between_readiness_and_the_request(monkeypatch):+ """Readiness and the POST were two steps, so a swap in between landed A's+ request on B's server, storing B's vectors under A's identity."""+ import threading++ b = LlamaServerBackend()+ order: list[str] = []+ swapped = threading.Event()++ def fake_ensure_ready(model_name = None):+ order.append(f"ready:{model_name}")++ def fake_post(url, json = None): # noqa: A002 - httpx's parameter name+ order.append("post")+ # A competing swap tries to run right here, where the old code let it.+ swapper = threading.Thread(target = _swap)+ swapper.start()+ swapper.join(timeout = 0.5)+ order.append("post-done")++ class _R:+ @staticmethod+ def raise_for_status():+ return None++ @staticmethod+ def json():+ return {"tokens": [1]}++ return _R()++ def _swap():+ # Blocks until the in-flight request releases the lease.+ with b._serve_lock:+ order.append("swap")+ swapped.set()++ monkeypatch.setattr(b, "_ensure_ready", fake_ensure_ready)+ monkeypatch.setattr(b._client, "post", fake_post)+ monkeypatch.setattr(b, "_port", 1)++ b._post("/tokenize", {"content": "x"}, model_name = "org/model-a")+ swapped.wait(timeout = 2)++ # The swap is after the request completed, never between ready and post.+ assert order[:3] == ["ready:org/model-a", "post", "post-done"]+ assert order[-1] == "swap"+++def test_a_dim_probe_is_serialized_with_a_model_switch(monkeypatch):+ """One subprocess serves one GGUF, so ``_dim`` belongs to whichever model is+ loaded. With two jobs pinned to models of different width, a probe that ran+ outside the request path's lock could ready A, have the other switch to B and+ cache B's width, and then answer A with it."""+ b = LlamaServerBackend()+ monkeypatch.setattr(b, "_ensure_ready", lambda model_name = None: None)+ observed = {}++ def _probe_encode(+ texts,+ normalize = False,+ model_name = None,+ ):+ # A second job trying to take the server while this probe is mid-flight.+ acquired = []+ switcher = threading.Thread(+ target = lambda: acquired.append(b._serve_lock.acquire(timeout = 0.5))+ )+ switcher.start()+ switcher.join()+ if acquired[0]:+ b._serve_lock.release()+ observed["excluded"] = not acquired[0]+ return np.zeros((1, 384), dtype = np.float32)++ monkeypatch.setattr(b, "encode", _probe_encode)++ assert b.dim() == 384+ assert observed["excluded"] is True, "a model switch could land inside the probe"+++def test_the_runtime_probe_does_not_wait_on_a_model_load(monkeypatch):+ """Both the resolve GET and the PUT run this preflight before any+ deadline-bounded Hub call, and ``_get`` holds ``_lock`` across a whole+ SentenceTransformer construction, download included. Sharing that lock made+ opening or saving Settings during a first load block for as long as the load."""+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ finished = threading.Event()++ def _probe():+ embeddings.sentence_transformers_runtime_available()+ finished.set()++ with embeddings._lock: # stands in for a load in progress+ worker = threading.Thread(target = _probe, daemon = True)+ worker.start()+ assert finished.wait(timeout = 60), "the resolve preflight waited on the model-load lock"+++def test_a_stale_quant_in_another_directory_is_not_the_planned_family(monkeypatch, tmp_path):+ """A repo that files each quant in its own directory publishes Q8_0/model.gguf+ beside Q4_K_M/model.gguf. Matching the plan on base names alone let the stale+ one pass for the planned one, retiring the marker and pinning the wrong quant."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ cleared = []+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ # The plan named the Q8_0 copy; only the Q4_K_M one is on disk.+ monkeypatch.setattr(ems, "get_stored_gguf_files", lambda model: ["Q8_0/model.gguf"])+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda model: cleared.append(model))+ _seed_cache(tmp_path / "hub", repo, ["Q4_K_M/model.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._resolve_model_path().endswith("model.gguf")+ assert cleared == [], "a quant from another directory is not the planned family"+++def test_the_planned_family_matches_by_its_directory_too(monkeypatch, tmp_path):+ """The other half: the planned copy in its own directory still retires it."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ cleared = []+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ monkeypatch.setattr(ems, "get_stored_gguf_files", lambda model: ["Q8_0/model.gguf"])+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda model: cleared.append(model))+ _seed_cache(tmp_path / "hub", repo, ["Q8_0/model.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._resolve_model_path().endswith("model.gguf")+ assert cleared == ["org/pending"]+++def test_warming_one_model_cannot_respawn_under_another_models_request(monkeypatch):+ """warm() readied the server itself, outside the serving lock, so warming B+ could kill and respawn between an encode pinned to A passing its own readiness+ check and its POST, landing A's request on B's server under A's identity.+ Readiness belongs to dim(), which holds the lock across it."""+ b = LlamaServerBackend()+ unlocked = []++ def _lock_is_free() -> bool:+ # Ownership is per thread for an RLock, so ask from another one.+ seen = []+ probe = threading.Thread(target = lambda: seen.append(b._serve_lock.acquire(timeout = 0.5)))+ probe.start()+ probe.join()+ if seen[0]:+ b._serve_lock.release()+ return seen[0]++ def _recording_ensure_ready(model_name = None):+ if _lock_is_free():+ unlocked.append(model_name)++ monkeypatch.setattr(b, "_ensure_ready", _recording_ensure_ready)+ monkeypatch.setattr(+ b,+ "encode",+ lambda texts, normalize = False, model_name = None: np.zeros((1, 384), dtype = np.float32),+ )+ b.warm(model_name = "org/model-b")++ assert unlocked == [], "a respawn during warm-up could land outside the serving lock"+++def test_the_planned_family_outranks_a_variant_that_arrives_later(monkeypatch, tmp_path):+ """The record names the artifact this model's vectors were produced with, and+ the stored identity carries the model and the repo but not the file. Once the+ marker retired, a preferred variant arriving later (a full-repo download, a+ republished revision) silently changed the weights under an existing index+ without changing its tag."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ # The transfer completed, so nothing is pending any more.+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: False)+ monkeypatch.setattr(ems, "get_stored_gguf_files", lambda model: ["pending-Q8_0.gguf"])+ monkeypatch.setattr(ems, "clear_stored_download_pending", lambda model: False)+ # And the configured variant has since landed in the same repo.+ _seed_cache(tmp_path / "hub", repo, ["pending-Q8_0.gguf", "pending-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._resolve_model_path().endswith("pending-Q8_0.gguf")+++def test_a_partly_present_planned_family_is_not_served(monkeypatch, tmp_path):+ """Whole family or nothing: entering a torn one at shard 1 gives llama-server a+ model it cannot finish opening."""+ import utils.embedding_model_settings as ems++ repo = "org/pending-GGUF"+ monkeypatch.setattr(config, "effective_embedding_model", lambda: "org/pending")+ monkeypatch.setattr(config, "effective_gguf_repo", lambda: repo)+ monkeypatch.setattr(config, "EMBED_GGUF_VARIANT", "F16")+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: False)+ monkeypatch.setattr(+ ems,+ "get_stored_gguf_files",+ lambda model: ["p-00001-of-00002.gguf", "p-00002-of-00002.gguf"],+ )+ _seed_cache(tmp_path / "hub", repo, ["p-00001-of-00002.gguf", "pending-F16.gguf"])+ _use_cache_root(monkeypatch, tmp_path / "hub")+ backend = LlamaServerBackend()++ assert backend._planned_family_path("org/pending", repo) is None+ assert backend._resolve_model_path().endswith("pending-F16.gguf")diff --git a/studio/backend/tests/test_rag_embedding_identity.py b/studio/backend/tests/test_rag_embedding_identity.pyindex 3a51e94bc80..c26dae13d7a 100644--- a/studio/backend/tests/test_rag_embedding_identity.py+++ b/studio/backend/tests/test_rag_embedding_identity.py@@ -46,11 +46,11 @@ def test_index_written_by_llama_is_stale_for_a_sentence_transformers_query("""The scenario a CPU upgrade produces: documents embedded through the GGUF whilesentence-transformers was failing, then queried by sentence-transformers once itworks. Same model name, different pooling."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)scope = store.kb_scope("K1")_ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)conn = rag_db.get_connection()try:assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL) == []@@ -62,11 +62,11 @@ def test_index_written_by_sentence_transformers_is_stale_for_a_llama_query(rag_home, stub_embeddings, monkeypatch, tmp_path):"""And the other direction, which is what a runtime fallback produces."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)scope = store.kb_scope("K2")_ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)conn = rag_db.get_connection()try:assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL) == []@@ -78,7 +78,7 @@ def test_the_same_backend_still_answers_its_own_index(rag_home, stub_embeddings, monkeypatch, tmp_path):"""The filter must only drop the other backend's rows."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)scope = store.kb_scope("K3")_ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")conn = rag_db.get_connection()@@ -93,11 +93,11 @@ def test_re_uploading_after_a_backend_change_reindexes_instead_of_deduping():"""Identical bytes used to dedupe against a row from the other backend, so therewas no way to repair the index short of renaming the file."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)scope = store.kb_scope("K4")first = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)second = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")assert second != firstconn = rag_db.get_connection()@@ -107,18 +107,56 @@ def test_re_uploading_after_a_backend_change_reindexes_instead_of_deduping(conn.close()+def test_re_resolved_backend_reindexes_before_the_stale_backend_is_rebuilt(+ rag_home, stub_embeddings, monkeypatch, tmp_path+):+ """Saving a new backend changes the next encode before that encode rebuilds+ the resident backend. Admission must predict the replacement or identical+ bytes dedupe against the old vector space and never reach the rebuild."""+ choice = {"backend": "sentence-transformers"}+ monkeypatch.setattr(config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(+ embeddings,+ "_resolve_auto_for_model",+ lambda model_name = None: choice["backend"],+ )+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ monkeypatch.setattr(embeddings, "_backend", embeddings._SentenceTransformersBackend())+ monkeypatch.setattr(+ embeddings,+ "_backend_key",+ embeddings._backend_cache_key("auto", "sentence-transformers"),+ )+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)++ scope = store.kb_scope("K4-resolved")+ first = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")++ # The same model now has a GGUF plan, but the first encode has not yet had a+ # chance to replace the resident ST wrapper.+ choice["backend"] = "llama-server"+ second = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")++ assert second != first+ conn = rag_db.get_connection()+ try:+ assert store.get_document(conn, second)["embedding_model"].startswith("llama-server:")+ finally:+ conn.close()++def test_ingestion_records_the_backend_that_took_over_mid_job(rag_home, stub_embeddings, monkeypatch, tmp_path):"""The row is created before the encode, and an ST encode failure swaps theprocess to llama-server, so the identity is only correct once vectors exist."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)swapped = {"done": False}real_encode = embeddings.encodedef encode_then_swap(texts, **kwargs):swapped["done"] = True- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)return real_encode(texts, **kwargs)monkeypatch.setattr(embeddings, "encode", encode_then_swap)@@ -139,7 +177,7 @@ def test_legacy_rows_keep_answering_and_are_reported("""Rows written before the tag existed could be either backend's. Dropping themwould empty dense search over every corpus indexed so far, and re-embedding oneunasked is not kinder, so they are still served and counted instead."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)scope = store.kb_scope("K6")document_id = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")conn = rag_db.get_connection()@@ -147,14 +185,14 @@ def test_legacy_rows_keep_answering_and_are_reported(store.set_document_embedding_model(conn, document_id, MODEL) # pre-tag spellingassert store.count_untagged_documents(conn) == 1assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL)- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL)finally:conn.close()def test_null_rows_are_still_assumed_current(rag_home, stub_embeddings, monkeypatch, tmp_path):- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)scope = store.kb_scope("K7")document_id = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")conn = rag_db.get_connection()@@ -168,9 +206,9 @@ def test_null_rows_are_still_assumed_current(rag_home, stub_embeddings, monkeypadef test_identity_distinguishes_the_backends_and_the_gguf_repo(monkeypatch):- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)as_st = embeddings.embedding_identity(MODEL)- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)as_llama = embeddings.embedding_identity(MODEL)assert as_st != as_llamaassert config.embedding_identity_model(as_st) == MODEL@@ -180,6 +218,45 @@ def test_identity_distinguishes_the_backends_and_the_gguf_repo(monkeypatch):assert embeddings.embedding_identity(MODEL) != as_llama+def test_llama_identity_uses_the_resolved_stored_repo(monkeypatch):+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)+ monkeypatch.setattr(+ config,+ "effective_gguf_repo_for_embedding_model",+ lambda model: "publisher/off-convention-GGUF",+ )+ assert embeddings.embedding_identity(MODEL) == config.embedding_identity(+ "llama-server",+ MODEL,+ gguf_repo = "publisher/off-convention-GGUF",+ )+++def test_identity_for_a_pinned_model_ignores_the_live_setting(monkeypatch):+ """A job pins its model once and embeds every file under it.++ The backend half of the identity used to be resolved from whatever+ ``effective_embedding_model()`` returned at the moment each file was tagged, so+ changing the model in Settings part way through a linked-folder reconcile split+ one folder across two identities. The pinned name is the only input.+ """+ embeddings._reset_backend()+ reads = []++ def _live_model():+ reads.append(True)+ return "org/whatever-settings-says-now"++ monkeypatch.setattr(config, "effective_embedding_model", _live_model)+ monkeypatch.setattr(embeddings, "_resolve_auto", lambda: "sentence-transformers")++ first = embeddings.embedding_identity(MODEL)+ second = embeddings.embedding_identity(MODEL)++ assert first == second == config.embedding_identity("sentence-transformers", MODEL)+ assert reads == [], "a pinned model must not re-read the live setting"++def test_untagged_values_match_on_the_model_name_alone():tagged = config.embedding_identity("sentence-transformers", MODEL)assert config.embedding_identity_matches(None, tagged) is True@@ -288,13 +365,11 @@ def test_the_identity_comes_from_the_encode_not_from_the_process_after_it(rag_conormalize = True,):vectors = [_vector(t) for t in texts]- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)return vectorsmonkeypatch.setattr(embeddings, "_backend", _SwapsMidEncode())- monkeypatch.setattr(- embeddings, "_backend_key", (config.EMBED_BACKEND or "auto").strip().lower()- )+ monkeypatch.setattr(embeddings, "_backend_key", embeddings._current_backend_key())hits = retrieval.retrieve_dense(rag_conn, "kb_r", "alpha bravo", k = 5, model_name = MODEL)assert [h.chunk_id for h in hits] == ["d1:0"]@@ -304,7 +379,7 @@ def test_a_swap_between_batches_re_embeds_the_document():"""A document whose batches straddle the swap would hold vectors from two spacesunder one identity, so it restarts under the backend that took over."""- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)monkeypatch.setattr(ingestion, "_EMBED_BATCH", 1)monkeypatch.setattr(config, "CHUNK_TOKENS", 3)monkeypatch.setattr(config, "CHUNK_OVERLAP", 0)@@ -321,7 +396,9 @@ def test_a_swap_between_batches_re_embeds_the_document(calls["n"] += 1out = real_encode(batch, **kwargs)if calls["n"] == 1:- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(+ embeddings, "active_backend_is_llama", lambda *_a, **_k: True+ )return outmonkeypatch.setattr(embeddings, "encode_with_identity", swap_after_one_batch)@@ -377,7 +454,7 @@ def test_the_web_ranker_labels_a_page_with_the_backend_that_encoded_it(rag_home,vectors instead of filtering them out."""from core.rag import web_rank- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: False)monkeypatch.setattr(embeddings, "token_counter", lambda model_name = None: lambda t: max(1, len(t.split())))@@ -391,13 +468,11 @@ def test_the_web_ranker_labels_a_page_with_the_backend_that_encoded_it(rag_home,normalize = True,):vectors = [_vector(t) for t in texts]- monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda *_a, **_k: True)return vectorsmonkeypatch.setattr(embeddings, "_backend", _SwapsMidEncode())- monkeypatch.setattr(- embeddings, "_backend_key", (config.EMBED_BACKEND or "auto").strip().lower()- )+ monkeypatch.setattr(embeddings, "_backend_key", embeddings._current_backend_key())labels: list[str | None] = []real_create = store.create_documentdiff --git a/studio/backend/tests/test_rag_embeddings.py b/studio/backend/tests/test_rag_embeddings.pyindex af1c09cde58..e88ee3fdd65 100644--- a/studio/backend/tests/test_rag_embeddings.py+++ b/studio/backend/tests/test_rag_embeddings.py@@ -103,7 +103,7 @@ def test_first_encode_builds_the_selected_backend_once(monkeypatch):def encode(self, texts, **_kwargs):return np.zeros((len(texts), 4), dtype = np.float32)- def _build():+ def _build(model_name = None):builds.append("backend")return _Backend()@@ -169,6 +169,87 @@ def test_token_counter_enables_parallelism_only_during_call(monkeypatch):assert os.environ.get("TOKENIZERS_PARALLELISM") == "false" # restored after+def test_token_counter_reacquires_backend_retired_between_chunk_calls(monkeypatch):+ from core.rag.embed_llama_server import LlamaServerBackend++ retired = LlamaServerBackend()+ replacement = LlamaServerBackend()+ monkeypatch.setattr(embeddings, "_get_backend", lambda *_a, **_k: retired)+ count = embeddings.token_counter("org/embedder")++ retired._closed = True+ monkeypatch.setattr(embeddings, "_get_backend", lambda *_a, **_k: replacement)+ monkeypatch.setattr(+ replacement,+ "_post",+ lambda path, payload, **_k: {"tokens": [1, 2, 3]},+ )++ assert count("the next chunk") == 3+++def test_token_counter_does_not_hide_non_lifecycle_errors(monkeypatch):+ class _BrokenCounterBackend:+ _closed = False++ def token_counter(self, *, model_name = None):+ def _raise(_text):+ raise RuntimeError("invalid tokenizer response")++ return _raise++ monkeypatch.setattr(embeddings, "_get_backend", lambda *_a, **_k: _BrokenCounterBackend())+ with pytest.raises(RuntimeError, match = "invalid tokenizer response"):+ embeddings.token_counter()("chunk")+++def test_st_unload_waits_for_encode_admitted_before_model_lookup(monkeypatch):+ entered_lookup = threading.Event()+ finish_lookup = threading.Event()+ unload_done = threading.Event()+ order = []+ errors = []++ class _Model:+ def encode(self, texts, **kwargs):+ order.append("encode")+ return np.zeros((len(texts), 2), dtype = np.float32)++ def _get(model_name = None):+ entered_lookup.set()+ assert finish_lookup.wait(timeout = 2)+ return _Model()++ def _encode():+ try:+ embeddings._st_encode(["chunk"])+ except Exception as exc: # pragma: no cover - surfaced below+ errors.append(exc)++ monkeypatch.setattr(embeddings, "_get", _get)+ monkeypatch.setattr(embeddings, "_model", object())+ monkeypatch.setattr(embeddings, "_name", "org/embedder")+ worker = threading.Thread(target = _encode)+ worker.start()+ assert entered_lookup.wait(timeout = 2)++ def _unload():+ embeddings._release_st_model()+ order.append("unload")+ unload_done.set()++ closer = threading.Thread(target = _unload)+ closer.start()+ assert unload_done.wait(timeout = 0.05) is False+ finish_lookup.set()+ worker.join(timeout = 2)+ closer.join(timeout = 2)++ assert errors == []+ assert order == ["encode", "unload"]+ assert unload_done.is_set()++def test_sentence_transformer_load_uses_live_cache(monkeypatch, tmp_path):observed = {}@@ -415,6 +496,160 @@ def test_st_success_keeps_sentence_transformers(monkeypatch):assert isinstance(backend, embeddings._SentenceTransformersBackend)+def test_loaded_state_belongs_to_the_resident_sentence_transformer(monkeypatch):+ monkeypatch.setattr(embeddings, "_backend", embeddings._SentenceTransformersBackend())+ monkeypatch.setattr(embeddings, "_model", object())+ monkeypatch.setattr(embeddings, "_name", "org/resident")++ assert embeddings.backend_is_loaded() is True+ assert embeddings.backend_is_loaded("org/resident") is True+ assert embeddings.backend_is_loaded("org/new-selection") is False+++def test_loaded_state_belongs_to_the_resident_gguf_repo(monkeypatch):+ # A live process, since residency now means the subprocess is actually there;+ # see test_a_dead_llama_process_is_not_reported_as_loaded.+ backend = SimpleNamespace(_model_repo = "org/resident-GGUF", _process_alive = lambda: True)+ monkeypatch.setattr(embeddings, "_backend", backend)+ monkeypatch.setattr(embeddings, "_is_llama_backend", lambda value: value is backend)+ monkeypatch.setattr(+ embeddings.config,+ "effective_gguf_repo_for_embedding_model",+ lambda model: f"{model}-GGUF",+ )++ assert embeddings.backend_is_loaded("org/resident") is True+ assert embeddings.backend_is_loaded("org/new-selection") is False+++def test_unload_clears_the_sentence_transformer_weights(monkeypatch):+ embeddings._backend = embeddings._SentenceTransformersBackend()+ embeddings._backend_key = embeddings._current_backend_key()+ embeddings._model = object()+ embeddings._name = "org/embedder"++ assert embeddings.release_backend() is True+ assert embeddings._model is None+ assert embeddings._name is None+++def test_pending_sentence_transformer_refuses_implicit_download_and_llama_fallback(monkeypatch):+ import utils.embedding_model_settings as ems+ import utils.utils as utils++ class _MustNotLoad:+ def __init__(self, *args, **kwargs): # pragma: no cover - failure is the assertion+ raise AssertionError("pending model reached SentenceTransformer")++ monkeypatch.setitem(+ sys.modules,+ "sentence_transformers",+ SimpleNamespace(SentenceTransformer = _MustNotLoad),+ )+ monkeypatch.setattr(ems, "get_stored_download_pending", lambda model: True)+ monkeypatch.setattr(utils, "hf_cache_snapshot_is_loadable", lambda model: False)+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(+ embeddings,+ "_try_make_llama_backend",+ lambda: (_ for _ in ()).throw(AssertionError("pending ST fell back to llama")),+ )+ embeddings._model = None+ embeddings._name = None++ with pytest.raises(embeddings.EmbeddingModelDownloadRequiredError, match = "not downloaded"):+ embeddings._build_st_backend_or_fallback()+++def test_replacing_a_llama_backend_shuts_it_down(monkeypatch):+ calls = []++ class _OldLlama:+ def _shutdown(self):+ calls.append("shutdown")++ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "sentence-transformers")+ monkeypatch.setattr(+ embeddings,+ "_build_st_backend_or_fallback",+ lambda *_a, **_k: embeddings._SentenceTransformersBackend(),+ )+ embeddings._backend = _OldLlama()+ embeddings._backend_key = "stale"++ assert isinstance(embeddings._get_backend(), embeddings._SentenceTransformersBackend)+ assert calls == ["shutdown"]+++def test_explicit_llama_backend_disallows_st_resolution(monkeypatch):+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "llama-server")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ assert embeddings.sentence_transformers_fallback_allowed() is False++ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ assert embeddings.sentence_transformers_fallback_allowed() is True+ monkeypatch.setattr(+ embeddings,+ "_forced_backends",+ {embeddings.config.effective_embedding_model(): "llama-server"},+ )+ assert embeddings.sentence_transformers_fallback_allowed() is False+++def test_forced_llama_fallback_is_scoped_to_the_model_that_failed(monkeypatch):+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {"org/failed": "llama-server"})+ monkeypatch.setattr(+ embeddings,+ "_resolve_auto_for_model",+ lambda model = None: "sentence-transformers",+ )++ assert embeddings.sentence_transformers_fallback_allowed("org/failed") is False+ assert embeddings.sentence_transformers_fallback_allowed("org/new-model") is True+ assert embeddings.resolved_backend_for_model("org/failed") == "llama-server"+ assert embeddings.resolved_backend_for_model("org/new-model") == "sentence-transformers"+++def test_runtime_preflight_predicts_the_supported_llama_fallback(monkeypatch):+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ monkeypatch.setattr(+ embeddings,+ "_resolve_auto_for_model",+ lambda model = None: "sentence-transformers",+ )+ monkeypatch.setattr(embeddings, "sentence_transformers_runtime_available", lambda: False)+ monkeypatch.setattr(embeddings, "_llama_server_runtime_available", lambda: True)++ assert embeddings.resolved_backend_for_model("org/embedder") == "llama-server"+++def test_runtime_preflight_keeps_st_when_no_fallback_exists(monkeypatch):+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ monkeypatch.setattr(+ embeddings,+ "_resolve_auto_for_model",+ lambda model = None: "sentence-transformers",+ )+ monkeypatch.setattr(embeddings, "sentence_transformers_runtime_available", lambda: False)+ monkeypatch.setattr(embeddings, "_llama_server_runtime_available", lambda: False)++ assert embeddings.resolved_backend_for_model("org/embedder") == "sentence-transformers"+++def test_runtime_preflight_catches_a_fatal_torch_device_mismatch(monkeypatch):+ monkeypatch.setattr(+ embeddings,+ "_load_device",+ lambda: (_ for _ in ()).throw(embeddings.TorchDeviceUnusableError("broken torch")),+ )++ assert embeddings.sentence_transformers_runtime_available() is False++class _BoomOnEncodeModel:"""Loads fine (init probe passes) but raises when encoding."""@@ -429,6 +664,8 @@ def test_st_encode_runtime_failure_switches_to_llama(monkeypatch):monkeypatch.setattr(embeddings, "_get", lambda model_name = None: _BoomOnEncodeModel())_patch_llama_backend(monkeypatch, binary = "/fake/llama-server")calls = {}+ embeddings._model = object()+ embeddings._name = "org/embedder"def _sentinel_encode(self,@@ -446,8 +683,20 @@ def test_st_encode_runtime_failure_switches_to_llama(monkeypatch):out = embeddings.encode(["alpha", "beta"])assert calls.get("used") is True # retried on the llama fallbackassert out.shape == (2, 4)+ # The failed ST weights are no longer reachable, including after the+ # published backend became llama rather than an ST wrapper.+ assert embeddings._model is None+ assert embeddings._name is None+ assert embeddings.config.effective_embedding_model() in embeddings._forced_backends# Switch is process-wide: later calls keep using llama, not ST.assert isinstance(embeddings._get_backend(), _SentinelLlamaBackend)+ # It outranks what the saved model would otherwise resolve to, so a model that+ # asks for ST cannot walk the process back into the encoder that just failed.+ monkeypatch.setattr(embeddings, "_resolve_auto_for_model", lambda: "sentence-transformers")+ assert isinstance(embeddings._get_backend(), _SentinelLlamaBackend)+ # An explicit unload is a fresh start, so the pin does not outlive it.+ embeddings._reset_backend()+ assert embeddings._forced_backends == {}def test_st_encode_failure_without_llama_binary_reraises(monkeypatch):@@ -537,3 +786,316 @@ def test_crashing_torch_falls_back_to_llama_server(monkeypatch):embeddings._reset_backend()assert isinstance(embeddings._get_backend(), _SentinelLlamaBackend)+++def test_encode_reacquires_a_backend_retired_between_batches(monkeypatch):+ """`release_backend` promises the next embed rebuilds. Without a reacquire here+ that promise held only for `token_counter`, and pressing Unload mid-ingestion+ failed the document being indexed instead of continuing it."""+ from core.rag.embed_llama_server import LlamaServerBackend++ retired = LlamaServerBackend()+ replacement = LlamaServerBackend()+ retired._closed = True+ served = np.zeros((1, 4), dtype = np.float32)+ monkeypatch.setattr(+ replacement,+ "encode",+ lambda texts, **kwargs: served,+ )+ backends = iter([retired, replacement])+ monkeypatch.setattr(embeddings, "_get_backend", lambda *_a, **_k: next(backends))++ assert embeddings.encode(["chunk"]) is served+ # The identity must name the backend that actually produced the vectors.+ assert embeddings._served_by.backend is replacement+++def test_encode_does_not_hide_a_non_lifecycle_runtime_error(monkeypatch):+ class _BrokenBackend:+ _closed = False++ def encode(self, texts, **kwargs):+ raise RuntimeError("llama-server returned no embedding")++ monkeypatch.setattr(embeddings, "_get_backend", lambda *_a, **_k: _BrokenBackend())+ with pytest.raises(RuntimeError, match = "returned no embedding"):+ embeddings.encode(["chunk"])+++def test_encode_surfaces_the_unload_when_no_replacement_is_published(monkeypatch):+ from core.rag.embed_llama_server import LlamaServerBackend++ retired = LlamaServerBackend()+ retired._closed = True+ monkeypatch.setattr(embeddings, "_get_backend", lambda *_a, **_k: retired)+ with pytest.raises(RuntimeError, match = "was unloaded"):+ embeddings.encode(["chunk"])+++def test_the_token_counter_follows_an_unloaded_sentence_transformer(monkeypatch):+ """The tokenizer used to be captured when the counter was built and held for the+ whole document, so it kept counting through an unload that reported the model+ gone. Reading it per call under the compute lock mirrors `_st_encode`."""+ looked_up = []++ class _Tok:+ def __init__(self, n):+ self.n = n++ def encode(+ self,+ text,+ add_special_tokens = False,+ ):+ return list(range(self.n))++ class _Model:+ def __init__(self, n):+ self.tokenizer = _Tok(n)++ models = [_Model(3), _Model(7)]++ def _get(model_name = None):+ looked_up.append(model_name)+ return models[min(len(looked_up) - 1, 1)]++ monkeypatch.setattr(embeddings, "_get", _get)+ count = embeddings._st_token_counter("org/embedder")++ assert looked_up == [], "the lookup must not happen before the first call"+ assert count("first") == 3+ assert count("second") == 7+ assert looked_up == ["org/embedder", "org/embedder"]+++def test_a_local_gguf_selects_llama_even_on_a_gpu_box(monkeypatch, tmp_path):+ """_resolve_auto answers sentence-transformers whenever a GPU is present, so a+ GPU box pointed at a local .gguf planned an ST load of a GGUF file."""+ gguf = tmp_path / "embed.gguf"+ gguf.write_bytes(b"GGUF")+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ # The hardware default that used to win.+ monkeypatch.setattr(embeddings, "_resolve_auto", lambda: "sentence-transformers")++ assert embeddings._resolve_auto_for_model(str(gguf)) == "llama-server"+ assert embeddings.resolved_backend_for_model(str(gguf)) == "llama-server"+ # A folder holding one counts the same way.+ assert embeddings._resolve_auto_for_model(str(tmp_path)) == "llama-server"+ # An ordinary repo id is untouched, and costs no filesystem walk.+ assert embeddings._resolve_auto_for_model("unsloth/bge-small-en-v1.5") == (+ "sentence-transformers"+ )+++def test_a_local_gguf_beats_a_stored_sentence_transformers_record(monkeypatch, tmp_path):+ """A stored ST record for a .gguf can only come from a force-save that then+ failed; honouring it would reinstate the same broken load."""+ gguf = tmp_path / "embed.gguf"+ gguf.write_bytes(b"GGUF")+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_resolve_auto", lambda: "sentence-transformers")+ import utils.embedding_model_settings as ems++ monkeypatch.setattr(ems, "get_stored_backend", lambda _m: "sentence-transformers")++ assert embeddings._resolve_auto_for_model(str(gguf)) == "llama-server"+++def test_an_explicit_backend_is_not_overridden_by_a_local_gguf(monkeypatch, tmp_path):+ """Only ``auto`` consults the probe; an explicit setting stays verbatim."""+ gguf = tmp_path / "embed.gguf"+ gguf.write_bytes(b"GGUF")+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "sentence-transformers")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ monkeypatch.setattr(embeddings, "sentence_transformers_runtime_available", lambda: True)++ assert embeddings.resolved_backend_for_model(str(gguf)) == "sentence-transformers"+++def test_the_st_probe_warms_the_pinned_model_not_the_live_setting(monkeypatch):+ """_get_backend resolves for the pinned model, but the probe warmed+ model_name=None, reading the live setting: a job pinned to A probed B once+ Settings moved, failing the valid A job before its first encode."""+ warmed = []++ class _Probe:+ def warm(self, model_name = None):+ warmed.append(model_name)++ monkeypatch.setattr(embeddings, "_SentenceTransformersBackend", _Probe)+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "sentence-transformers")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ embeddings._reset_backend()+ try:+ embeddings._get_backend("org/pinned")+ finally:+ embeddings._reset_backend()++ assert warmed == ["org/pinned"]+++def test_the_security_gate_scans_the_snapshot_that_is_actually_loaded(monkeypatch, tmp_path):+ """On the repo id the gate scanned the Hub's current commit while the load+ opened an older cached one, so a pickle present only there passed.+ evaluate_file_security recovers repo and commit from a snapshot path."""+ snapshot = tmp_path / "snap"+ snapshot.mkdir()+ # A real ST checkpoint: the pin is ST-specific now, so a GGUF-only snapshot+ # is deliberately not adopted as the load target.+ (snapshot / "model.safetensors").write_bytes(b"ST")+ scanned = []+ monkeypatch.setattr(+ embeddings, "_guard_model_security", lambda target, local_only = False: scanned.append(target)+ )++ class _ST:+ def __init__(self, target, **_kwargs):+ self.loaded = target+ self.tokenizer = None++ def get_sentence_embedding_dimension(self):+ return 8++ monkeypatch.setattr(embeddings, "_load_device", lambda: "cpu")+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)+ monkeypatch.setattr(embeddings, "_st_accepts_local_files_only", lambda _c: False)+ import utils.utils as utils++ monkeypatch.setattr(utils, "cached_st_source", lambda m: ("org/embedder", snapshot))+ monkeypatch.setattr(utils, "hf_cache_snapshot_dir", lambda m: snapshot)+ import sys as _sys+ import types as _t++ st_mod = _t.ModuleType("sentence_transformers")+ st_mod.SentenceTransformer = _ST+ monkeypatch.setitem(_sys.modules, "sentence_transformers", st_mod)+ embeddings._model = None+ embeddings._name = None+ try:+ model = embeddings._get("org/embedder")+ finally:+ embeddings._model = None+ embeddings._name = None++ # The snapshot was loaded, and it is the same string the gate was handed.+ assert model.loaded == str(snapshot)+ assert scanned == [str(snapshot)]+++def test_the_residency_probe_does_not_wait_on_a_model_load(monkeypatch):+ """Both locks are held across a whole model load, so a probe taking either+ made GET, PUT, reset and unload wait it out."""+ import threading++ embeddings._reset_backend()+ answered = threading.Event()+ result = {}++ # Both locks held, exactly as they are mid-construction.+ with embeddings._backend_lock, embeddings._lock:++ def _probe():+ result["any"] = embeddings.backend_is_loaded()+ result["named"] = embeddings.backend_is_loaded("org/embedder")+ answered.set()++ threading.Thread(target = _probe, daemon = True).start()+ # Answered while the construction locks are still held by this thread.+ assert answered.wait(timeout = 5), "the status probe blocked on the load locks"++ assert result == {"any": False, "named": False}+++def test_a_dead_llama_process_is_not_reported_as_loaded(monkeypatch):+ """The object keeps _model_repo after the subprocess exits, so the repo match+ alone called a dead server resident and offered Unload for it."""+ alive = {"value": True}+ backend = SimpleNamespace(+ _model_repo = "org/resident-GGUF", _process_alive = lambda: alive["value"]+ )+ monkeypatch.setattr(embeddings, "_backend", backend)+ monkeypatch.setattr(embeddings, "_is_llama_backend", lambda value: value is backend)+ monkeypatch.setattr(+ embeddings.config,+ "effective_gguf_repo_for_embedding_model",+ lambda model: f"{model}-GGUF",+ )++ assert embeddings.backend_is_loaded("org/resident") is True+ assert embeddings.backend_is_loaded() is True++ alive["value"] = False+ assert embeddings.backend_is_loaded("org/resident") is False+ # And the unqualified question, which is what gates the Unload control.+ assert embeddings.backend_is_loaded() is False+++def test_two_models_can_each_hold_their_own_llama_fallback_pin(monkeypatch):+ """One (key, model) pair meant a second failing model erased the first one's+ pin, so a job still running under A forgot it had swapped to llama-server and+ retried ST. If the original failure was transient that ingestion splits its+ own results across two vector spaces."""+ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {})+ monkeypatch.setattr(+ embeddings, "_resolve_auto_for_model", lambda model = None: "sentence-transformers"+ )++ embeddings._forced_backends["org/a"] = "llama-server"+ embeddings._forced_backends["org/b"] = "llama-server"++ assert embeddings.resolved_backend_for_model("org/a") == "llama-server"+ assert embeddings.resolved_backend_for_model("org/b") == "llama-server"+ assert embeddings.sentence_transformers_fallback_allowed("org/a") is False+ assert embeddings.sentence_transformers_fallback_allowed("org/b") is False+ # A model that never failed is untouched by either pin.+ assert embeddings.resolved_backend_for_model("org/c") == "sentence-transformers"+ assert embeddings.sentence_transformers_fallback_allowed("org/c") is True+++def test_the_forced_backend_probe_does_not_wait_on_a_model_load(monkeypatch):+ """_get_backend holds _backend_lock across a whole model load, so a resolver+ probe taking it made GET/PUT on this setting hang for the download rather than+ for the 20s Hub budget that is supposed to bound them."""+ import threading++ monkeypatch.setattr(embeddings.config, "EMBED_BACKEND", "auto")+ monkeypatch.setattr(embeddings, "_forced_backends", {"org/pinned": "llama-server"})+ answered = threading.Event()+ result = {}++ with embeddings._backend_lock:++ def _probe():+ result["resolved"] = embeddings.resolved_backend_for_model("org/pinned")+ result["fallback"] = embeddings.sentence_transformers_fallback_allowed("org/pinned")+ answered.set()++ threading.Thread(target = _probe, daemon = True).start()+ assert answered.wait(timeout = 5), "the resolver probe blocked on the construction lock"++ assert result == {"resolved": "llama-server", "fallback": False}+++def test_a_model_reloaded_behind_an_unload_is_still_reported_and_freed(monkeypatch):+ """An ST wrapper descheduled between _get_backend() returning it and its encode+ starting is retired by an unload landing in the gap, and then reloads the+ module-level model with no backend to publish. Answering "nothing is loaded"+ stranded those weights for the life of the process: the next unload saw no+ backend and freed nothing."""+ monkeypatch.setattr(embeddings, "_backend", None, raising = False)+ monkeypatch.setattr(embeddings, "_backend_key", None, raising = False)+ monkeypatch.setattr(embeddings, "_model", object(), raising = False)+ monkeypatch.setattr(embeddings, "_name", "org/embedder", raising = False)++ assert embeddings.backend_is_loaded() is True+ assert embeddings.backend_is_loaded("org/embedder") is True+ assert embeddings.backend_is_loaded("org/other") is False++ assert embeddings.release_backend() is True+ assert embeddings._model is None+ assert embeddings.backend_is_loaded() is False+ # And with nothing resident it stays a no-op.+ assert embeddings.release_backend() is Falsediff --git a/studio/backend/utils/embedding_model_settings.py b/studio/backend/utils/embedding_model_settings.pyindex 798ae6d3647..335b8296e0a 100644--- a/studio/backend/utils/embedding_model_settings.py+++ b/studio/backend/utils/embedding_model_settings.py@@ -13,9 +13,19 @@ from __future__ import annotationsimport threadingimport time-from typing import Any+from typing import Any, OptionalEMBEDDING_MODEL_SETTING_KEY = "rag_embedding_model"+# The GGUF repo the picker resolved for that model. Stored so the loader opens+# what was actually downloaded instead of re-deriving a name that may not exist.+EMBEDDING_GGUF_SETTING_KEY = "rag_embedding_gguf_repo"+# Which backend that model needs. An embedder with no GGUF still runs fine on+# sentence-transformers (safetensors), it just costs about 1 GB more memory.+EMBEDDING_BACKEND_SETTING_KEY = "rag_embedding_backend"+# Atomic association between the selected model and the artifacts/backend the+# resolver validated for it. Unlike the override key, this may name the env+# default: an off-convention GGUF still has to remain attached to that model.+EMBEDDING_RESOLUTION_SETTING_KEY = "rag_embedding_resolution"MAX_EMBEDDING_MODEL_LENGTH = 512# The effective model is consulted on the embedder hot path (once per embed /@@ -23,12 +33,25 @@ MAX_EMBEDDING_MODEL_LENGTH = 512# of hitting sqlite each time. Writes invalidate immediately in-process; other# readers converge within the TTL._CACHE_TTL_S = 2.0-_cached: tuple[float, str | None] | None = None+# typing.Optional, not `str | None`: the future import defers annotations, but a+# type ALIAS is evaluated at import, and PEP 604 needs 3.10 over a 3.9 floor.+_StoredState = tuple[+ Optional[str], Optional[str], Optional[str], Optional[str], bool, Optional[dict]+]+# (override model, resolved model, GGUF repo, backend, download pending, raw record).+# The raw record is carried so a conditional write compares against exactly what+# is stored: a reconstruction never matches a record written by a build with one+# field fewer.+_cached: tuple[float, _StoredState] | None = None# Bumped on every write/invalidate. A reader captures it before the DB read and# only fills the cache if it is unchanged afterward, so a read that overlapped a# save cannot repopulate the cache with the pre-save value for the whole TTL._generation = 0_lock = threading.Lock()+# Per-model, process-local: the last (gguf_repo, backend, download_pending, files)+# seen for each model. The one stored record belongs to whichever model was saved+# last; see remembered_gguf_repo.+_resolved_gguf_memo: dict[str, tuple[Optional[str], Optional[str], bool, Optional[list]]] = {}def _invalidate_cache() -> None:@@ -67,8 +90,152 @@ def validate_embedding_model(value: Any) -> str:return cleaned+def _coerce_gguf_files(value: Any) -> Optional[list]:+ """Repo-relative GGUF names from ``value``, or None when it names no family.++ Same length/control-character rules as every other stored string: this record+ is read back to steer a loader, so it must not carry anything a path join+ would misread."""+ if not isinstance(value, (list, tuple)):+ return None+ named = [f for f in (_coerce_embedding_model(v) for v in value) if f]+ return named or None+++def get_stored_gguf_repo(model: str) -> str | None:+ """The GGUF repo stored alongside ``model``, or None when it was stored for a+ different model (a stale pair must not point the loader at the wrong weights)."""+ stored = _get_stored_state()+ if stored[1] != model:+ return None+ _remember_resolution(model, stored)+ return stored[2]+++def _remember_resolution(model: str, stored: _StoredState) -> None:+ """Keep this process's last resolved repo/backend/pending/files for ``model``."""+ with _lock:+ _resolved_gguf_memo[model] = (stored[2], stored[3], stored[4], _files_of(stored[5]))+++def _remembered(model: str) -> tuple[str | None, str | None, bool, list | None] | None:+ with _lock:+ return _resolved_gguf_memo.get(model)+++def _files_of(resolution: Optional[dict]) -> Optional[list]:+ """The planned GGUF file family recorded in ``resolution``, if it holds one."""+ if not isinstance(resolution, dict):+ return None+ files = resolution.get("gguf_files")+ if not isinstance(files, list):+ return None+ named = [f for f in files if isinstance(f, str) and f.strip()]+ return named or None+++def remembered_gguf_repo(model: str) -> str | None:+ """The repo this process last saw resolved for ``model``, if any.++ One stored record, so saving B makes ``get_stored_gguf_repo(A)`` None while a+ job pinned to A is still ingesting, moving its identity to the derived+ ``A-GGUF`` mid-job and splitting one document set across two tags. The memo is+ process-local and per model, so it lasts as long as the job; a later save for+ A refreshes it, and a reset drops it.+ """+ remembered = _remembered(model)+ return remembered[0] if remembered else None+++def get_stored_backend(model: str) -> str | None:+ """The backend stored for ``model``, or the one this process last saw for it.++ Same staleness rule as the repo, and the same reason to survive it: on an auto+ CPU install a model with no GGUF resolves to sentence-transformers, so losing+ it drops a still-running job onto the hardware default, which has no GGUF.+ """+ stored = _get_stored_state()+ if stored[1] == model:+ _remember_resolution(model, stored)+ return stored[3]+ remembered = _remembered(model)+ return remembered[1] if remembered else None+++def get_stored_gguf_files(model: str) -> list | None:+ """The GGUF file family the picker planned for ``model``, if one was recorded.++ Same staleness-plus-memo rule as the backend. Loaders use it to tell the quant+ the advertised transfer actually delivered from an unrelated one left in the+ same repo by an earlier setting. None on records written before it was stored,+ which is why every consumer has to keep working without it.+ """+ stored = _get_stored_state()+ if stored[1] == model:+ _remember_resolution(model, stored)+ return _files_of(stored[5])+ remembered = _remembered(model)+ return remembered[3] if remembered else None+++def get_stored_download_pending(model: str) -> bool:+ """Whether ``model`` was activated before its required transfer finished.++ Loaders stay cache-only on this marker instead of recreating the invisible+ first-index download. It outlives another model's save for the same reason the+ backend does: forgetting it re-enables that download for a pinned job.+ """+ stored = _get_stored_state()+ if stored[1] == model:+ _remember_resolution(model, stored)+ return stored[4]+ remembered = _remembered(model)+ return remembered[2] if remembered else False+++def clear_stored_download_pending(model: str) -> bool:+ """Retire the pending marker for ``model`` once its weights are on disk.++ Nothing else clears it: the picker re-resolves after a transfer but does not+ save again, so the marker would outlive the download and pin the model+ cache-only forever. Callers are the loaders, once the cache is proven complete.+ """+ stored = _get_stored_state()+ if stored[1] != model or not stored[4]:+ return False+ expected = stored[5]+ if not isinstance(expected, dict):+ # Pre-atomic layout: the flag lives nowhere this can clear.+ return False+ from storage.studio_db import compare_and_set_app_setting++ # Conditional, not a plain upsert: a save for another model committing between+ # the read and this write would otherwise be reverted onto this resolution.+ # Comparing the record as read, rather than a rebuilt one, keeps that guard+ # working across a record whose field set this build does not know about.+ if not compare_and_set_app_setting(+ EMBEDDING_RESOLUTION_SETTING_KEY, expected, {**expected, "download_pending": False}+ ):+ return False+ # Retire the memo with the record, or a pinned job keeps reading pending=True+ # and stays cache-only after the download landed.+ _remember_resolution(model, (stored[0], stored[1], stored[2], stored[3], False, stored[5]))+ _invalidate_cache()+ return True++def get_stored_embedding_model() -> str | None:"""The persisted override, or None when unset/invalid."""+ return _get_stored_state()[0]+++def _get_stored_state() -> _StoredState:+ """Read the override and its resolved artifact association as one snapshot.++ The resolution is one JSON value so its model/repo/backend can never be+ torn. The legacy individual fields are read in the same SQL statement for+ compatibility with builds from before the atomic record existed.+ """global _cachednow = time.monotonic()with _lock:@@ -77,8 +244,15 @@ def get_stored_embedding_model() -> str | None:return cached[1]gen = _generationtry:- from storage.studio_db import get_app_setting- stored = get_app_setting(EMBEDDING_MODEL_SETTING_KEY, None)+ from storage.studio_db import get_app_settings+ settings = get_app_settings(+ [+ EMBEDDING_MODEL_SETTING_KEY,+ EMBEDDING_RESOLUTION_SETTING_KEY,+ EMBEDDING_GGUF_SETTING_KEY,+ EMBEDDING_BACKEND_SETTING_KEY,+ ]+ )except Exception:# Transient store failure: keep the last known value instead of# silently reverting the embed/search hot path to the default model,@@ -87,8 +261,24 @@ def get_stored_embedding_model() -> str | None:if _cached is not None:_cached = (time.monotonic(), _cached[1])return _cached[1]- return None- value = _coerce_embedding_model(stored)+ return (None, None, None, None, False, None)+ override = _coerce_embedding_model(settings.get(EMBEDDING_MODEL_SETTING_KEY))+ resolution = settings.get(EMBEDDING_RESOLUTION_SETTING_KEY)+ resolved_model = repo = backend = None+ download_pending = False+ if isinstance(resolution, dict):+ resolved_model = _coerce_embedding_model(resolution.get("model"))+ repo = _coerce_embedding_model(resolution.get("gguf_repo"))+ backend = _coerce_embedding_model(resolution.get("backend"))+ download_pending = resolution.get("download_pending") is True+ elif override:+ # Legacy PR builds stored the association in separate keys. The one-shot+ # read above still gives this compatibility path a consistent snapshot.+ resolved_model = override+ repo = _coerce_embedding_model(settings.get(EMBEDDING_GGUF_SETTING_KEY))+ backend = _coerce_embedding_model(settings.get(EMBEDDING_BACKEND_SETTING_KEY))+ raw = resolution if isinstance(resolution, dict) else None+ value: _StoredState = (override, resolved_model, repo, backend, download_pending, raw)with _lock:# Only cache when no save landed while we were reading; otherwise this# value may be pre-save, and caching it would mask the new one for the@@ -100,17 +290,53 @@ def get_stored_embedding_model() -> str | None:def get_rag_embedding_model() -> str:"""Effective embedding model: persisted override, else env/default."""- return get_stored_embedding_model() or default_embedding_model()+ stored = _get_stored_state()+ model = stored[0] or default_embedding_model()+ # Reading this is how a job pins its model, so record the resolution here: the+ # memo only protects a pinned job if it was populated before another model's+ # save takes the one stored record, and the repo/backend getters alone left a+ # worker that pinned A, scanned, then embedded with nothing memoized.+ if stored[1] == model:+ _remember_resolution(model, stored)+ return model-def set_rag_embedding_model(value: Any) -> str:+def set_rag_embedding_model(+ value: Any,+ gguf_repo: Any = None,+ backend: Any = None,+ download_pending: bool = False,+ gguf_files: Any = None,+) -> str:parsed = validate_embedding_model(value)from storage.studio_db import upsert_app_settings# Saving the default is not an override; keeps is_custom (and the UI's# reset affordance) honest.stored = parsed if parsed != default_embedding_model() else None- upsert_app_settings({EMBEDDING_MODEL_SETTING_KEY: stored})+ repo = _coerce_embedding_model(gguf_repo)+ chosen = _coerce_embedding_model(backend)+ files = _coerce_gguf_files(gguf_files)+ resolution = (+ {+ "model": parsed,+ "gguf_repo": repo,+ "backend": chosen,+ "download_pending": download_pending is True,+ "gguf_files": files,+ }+ if repo or chosen or download_pending+ else None+ )+ upsert_app_settings(+ {+ EMBEDDING_MODEL_SETTING_KEY: stored,+ EMBEDDING_RESOLUTION_SETTING_KEY: resolution,+ # Retire the pre-atomic spelling on the same commit.+ EMBEDDING_GGUF_SETTING_KEY: None,+ EMBEDDING_BACKEND_SETTING_KEY: None,+ }+ )_invalidate_cache()return parsed@@ -119,6 +345,32 @@ def reset_rag_embedding_model() -> str:"""Clear the override; returns the (env/default) model now in effect."""from storage.studio_db import upsert_app_settings- upsert_app_settings({EMBEDDING_MODEL_SETTING_KEY: None})+ restored = default_embedding_model()+ # The memo survives a reset: it is per model and consulted only when the store+ # has nothing, so it is what a job still pinned to a model reads. The restored+ # default is not a running job, though -- new work resolves through it too, and+ # a process-only answer would change identity on the next restart. So write any+ # remembered resolution for it back durably rather than leave it in memory.+ remembered = _remembered(restored)+ resolution = None+ # The pending flag counts as much as a repo or a backend: a default saved over+ # a failed resolution legitimately remembers (None, None, True), and that flag+ # is what keeps the first index from starting the implicit download.+ if remembered and (remembered[0] or remembered[1] or remembered[2]):+ resolution = {+ "model": restored,+ "gguf_repo": remembered[0],+ "backend": remembered[1],+ "download_pending": remembered[2],+ "gguf_files": remembered[3],+ }+ upsert_app_settings(+ {+ EMBEDDING_MODEL_SETTING_KEY: None,+ EMBEDDING_RESOLUTION_SETTING_KEY: resolution,+ EMBEDDING_GGUF_SETTING_KEY: None,+ EMBEDDING_BACKEND_SETTING_KEY: None,+ }+ )_invalidate_cache()- return default_embedding_model()+ return restoreddiff --git a/studio/backend/utils/utils.py b/studio/backend/utils/utils.pyindex dff484297eb..b9674d4899d 100644--- a/studio/backend/utils/utils.py+++ b/studio/backend/utils/utils.py@@ -536,33 +536,118 @@ def _hf_cache_roots() -> list:return roots-def hf_cache_snapshot_dir(model_name: str) -> Optional[Path]:- """Active local snapshot dir for model_name's main revision, or None if not cached.- Reads refs/main then snapshots/<commit>; no network. Tries the ST alias for slashless names."""+ST_WEIGHT_SUFFIXES = (".safetensors", ".bin")+++def is_st_weight_name(basename: str) -> bool:+ """Whether a filename is a checkpoint SentenceTransformer can load.++ ``.bin`` is the loose one: ``tokenizer.bin`` shares the extension with real+ weights. Shared so the resolver's plan and the loader's cache check cannot+ disagree about what counts as a checkpoint."""+ name = basename.lower()+ for suffix in ST_WEIGHT_SUFFIXES:+ if not name.endswith(suffix):+ continue+ if suffix == ".bin":+ return name.startswith(("pytorch_model", "model", "adapter_model", "consolidated"))+ return True+ return False+++def cached_st_source(model_name: str) -> Optional[tuple]:+ """``(repo id, snapshot dir)`` whose cache holds ST-loadable weights, complete.++ Alias-aware, and it reports WHICH candidate matched: a slashless name caches+ under ``sentence-transformers/``, so the literal id names a repo that usually+ does not exist, and a stale literal cache entry is not the directory that+ supplied the weights. Completeness comes from+ ``hf_cache_snapshot_is_loadable`` on that same candidate: ST weights alone are+ satisfied by the first finalized shard of a transfer still in flight.+ """+ for candidate in st_repo_id_candidates(model_name):+ # Exactly this candidate: the alias-expanding lookup answers a literal+ # slashless name with the namespaced snapshot, pairing a directory with a+ # repo id that supplied nothing.+ snapshot = hf_cache_snapshot_dir_for_repo(candidate)+ if snapshot is None:+ continue+ try:+ if not any(is_st_weight_name(p.name) and p.is_file() for p in snapshot.rglob("*")):+ continue+ except OSError:+ continue+ # This snapshot, not whatever the alias-expanding lookup would find: with+ # several cache roots those differ, and a complete namespaced copy in one+ # would vouch for the partial literal copy in another that gets loaded.+ if snapshot_is_loadable(snapshot, candidate):+ return (candidate, snapshot)+ return None+++def cached_st_repo(model_name: str) -> Optional[str]:+ """Repo id whose cached snapshot holds complete ST-loadable weights."""+ source = cached_st_source(model_name)+ return source[0] if source else None+++def snapshot_has_st_weights(model_name: str) -> bool:+ """Whether ``model_name`` has a complete cached checkpoint ST can open.++ ``hf_cache_snapshot_is_loadable`` counts ``.gguf``, which is right for the+ llama backend and wrong wherever SentenceTransformer is the loader; this pairs+ it with the ST-specific file family so both hold."""+ return cached_st_source(model_name) is not None+++def _snapshot_in_root(cache_root: Path, repo_id: str) -> Optional[Path]:+ """``repo_id``'s main-revision snapshot under exactly ``cache_root``, or None."""try:from huggingface_hub.file_download import repo_folder_nameexcept Exception:repo_folder_name = None+ try:+ if repo_folder_name is not None:+ folder = repo_folder_name(repo_id = repo_id, repo_type = "model")+ else:+ folder = "models--" + repo_id.replace("/", "--")+ repo_dir = cache_root / folder+ ref = repo_dir / "refs" / "main"+ if not ref.is_file():+ return None+ commit = ref.read_text(encoding = "utf-8").strip()+ if not commit:+ return None+ snapshot = repo_dir / "snapshots" / commit+ return snapshot if snapshot.is_dir() else None+ # UnicodeDecodeError is a ValueError, not an OSError: a torn refs file must keep meaning "not cached here".+ except (OSError, UnicodeDecodeError):+ return None+++def hf_cache_snapshot_dir_for_repo(repo_id: str) -> Optional[Path]:+ """Snapshot dir for exactly ``repo_id``, with no alias expansion.++ ``hf_cache_snapshot_dir`` answers "is this model cached anywhere", trying the+ ST alias, so asking it about a literal slashless name can return the+ namespaced snapshot. A caller that has to report WHICH repo supplied the+ weights needs this one instead, or it pairs the alias's directory with the+ literal id and sends verification at a repo that does not exist."""+ for cache_root in _hf_cache_roots():+ snapshot = _snapshot_in_root(cache_root, repo_id)+ if snapshot is not None:+ return snapshot+ return None+++def hf_cache_snapshot_dir(model_name: str) -> Optional[Path]:+ """Active local snapshot dir for model_name's main revision, or None if not cached.+ Reads refs/main then snapshots/<commit>; no network. Tries the ST alias for slashless names."""for cache_root in _hf_cache_roots():for repo_id in st_repo_id_candidates(model_name):- try:- if repo_folder_name is not None:- folder = repo_folder_name(repo_id = repo_id, repo_type = "model")- else:- folder = "models--" + repo_id.replace("/", "--")- repo_dir = cache_root / folder- ref = repo_dir / "refs" / "main"- if not ref.is_file():- continue- commit = ref.read_text(encoding = "utf-8").strip()- if not commit:- continue- snapshot = repo_dir / "snapshots" / commit- if snapshot.is_dir():- return snapshot- # UnicodeDecodeError is a ValueError, not an OSError: a torn refs file must keep meaning "not cached here".- except (OSError, UnicodeDecodeError):- continue+ snapshot = _snapshot_in_root(cache_root, repo_id)+ if snapshot is not None:+ return snapshotreturn None@@ -570,25 +655,136 @@ def hf_cache_snapshot_dir(model_name: str) -> Optional[Path]:_LOADABLE_WEIGHT_SUFFIXES = frozenset({".safetensors", ".bin", ".gguf", ".pt", ".pth", ".ckpt"})+def checkpoint_directory_is_complete(root: Path, weights = None) -> bool:+ """Whether ``root`` holds a whole checkpoint, shards and declared modules alike.++ Shared by the Hub-cache check and the local-path one so a directory is judged+ the same way however it got there: a single shard of a two-shard family, or a+ module ``modules.json`` declares and the directory does not have, is a torn+ checkpoint that SentenceTransformer fails to open at the first index.++ ``weights`` is the already-scanned weight list when the caller has one.+ """+ from hub.utils.inventory_scan import snapshot_holds_a_complete_payload++ if weights is None:+ weights = [+ path+ for path in root.rglob("*")+ if path.suffix.lower() in _LOADABLE_WEIGHT_SUFFIXES+ and path.is_file()+ and not is_appledouble_metadata(path)+ ]+ # SentenceTransformer modules may keep their own transformer checkpoint+ # below 0_Transformer/. Validate every module subtree that carries weights;+ # config-only modules such as Pooling need no weight family of their own.+ if (root / "modules.json").is_file():+ import json+ from pathlib import PurePosixPath++ try:+ modules = json.loads((root / "modules.json").read_text(encoding = "utf-8"))+ except (OSError, UnicodeDecodeError, ValueError):+ return False+ roots = []+ for module in modules if isinstance(modules, list) else []:+ value = module.get("path") if isinstance(module, dict) else None+ if not isinstance(value, str) or "\\" in value:+ continue+ relative = PurePosixPath(value or ".")+ if relative.is_absolute() or ".." in relative.parts:+ continue+ module_root = root.joinpath(*relative.parts)+ # A declared module the directory does not have at all is a torn+ # checkpoint, whatever the others hold: checking only roots that+ # carry weights passed one missing 0_Transformer entirely.+ # Existence is the whole test, since config-only modules such as+ # Pooling have no weight family.+ if module_root != root and not module_root.is_dir():+ return False+ if any(path == module_root or module_root in path.parents for path in weights):+ roots.append(module_root)+ if roots:+ return all(snapshot_holds_a_complete_payload(r, quants = False) for r in roots)+ return snapshot_holds_a_complete_payload(root, quants = False)++def hf_cache_snapshot_is_loadable(model_name: str) -> bool:- """True when model_name's snapshot is cached and loadable: a config (config.json or- modules.json) plus at least one weight file, not a metadata-only partial cache. No network."""+ """True when the cached snapshot can satisfy a cache-only transformer load.++ App-managed downloads are checked against their exact manifest. Imported or+ legacy caches without one fall back to the same weight-family/index scanner+ used by Hub inventory, so one shard of a cancelled checkpoint is not enough.+ No network.+ """snapshot = hf_cache_snapshot_dir(model_name)if snapshot is None:return False+ return snapshot_is_loadable(snapshot, model_name)+++def snapshot_is_loadable(snapshot, model_name: str) -> bool:+ """``hf_cache_snapshot_is_loadable`` for a snapshot the caller already has.++ A caller that picked a specific directory has to have THAT one judged: the+ lookup above expands the ST alias within each cache root while an exact+ per-repo lookup walks the roots for one id, so with several roots configured+ the two can land on different snapshots, and the verdict would then belong to+ a directory nobody is going to load.+ """try:has_config = (snapshot / "config.json").is_file() or (snapshot / "modules.json").is_file()if not has_config:return False+ weights = []for path in snapshot.rglob("*"):if path.suffix.lower() not in _LOADABLE_WEIGHT_SUFFIXES or not path.is_file():continueif not is_appledouble_metadata(path):- return True+ weights.append(path)+ if not weights:+ return False++ # A managed full-snapshot transfer records its exact expected files+ # before downloading. A cancel marker or unfinished blob is conclusive+ # even when config.json and the first finalized shard already exist.+ repo_dir = snapshot.parent.parent+ hub_cache = repo_dir.parent+ repo_id = model_name+ try:+ from huggingface_hub.file_download import repo_folder_name+ for candidate in st_repo_id_candidates(model_name):+ if repo_folder_name(repo_id = candidate, repo_type = "model") == repo_dir.name:+ repo_id = candidate+ break+ except Exception:+ pass+ from hub.utils import download_manifest+ from hub.utils.hf_cache_state import snapshot_has_broken_symlinks++ if download_manifest.has_cancel_marker("model", repo_id, None, hub_cache = hub_cache):+ return False+ manifest = download_manifest.read_manifest("model", repo_id, None, hub_cache = hub_cache)+ if manifest is not None:+ # This exact full-snapshot plan is stronger evidence than an+ # unrelated .incomplete blob left under the repository by another+ # revision or scoped GGUF job.+ return download_manifest.verify_against_disk(manifest, snapshot).ok+ # No manifest: every model on disk before this build is such a cache.+ # Judge THIS snapshot's own links, not every blob in the cache directory it+ # shares, or a stray .incomplete from another revision condemns a model+ # that is fully present.+ if snapshot_has_broken_symlinks(snapshot):+ return False++ return checkpoint_directory_is_complete(snapshot, weights)except OSError:return False- return False+ except Exception:+ # Completeness is a safety property here: an unprovable partial must keep+ # the pending marker so the loader cannot silently reach the network.+ return False# ── Client-safe error helpers ───────────────────────────────────diff --git a/studio/frontend/src/features/settings/api/embedding-model.ts b/studio/frontend/src/features/settings/api/embedding-model.tsindex cc21559f385..0d06a86da4e 100644--- a/studio/frontend/src/features/settings/api/embedding-model.ts+++ b/studio/frontend/src/features/settings/api/embedding-model.ts@@ -3,6 +3,9 @@import { authFetch } from "@/features/auth";import { bumpInventoryVersion } from "@/features/hub";+// Leaf module, not the barrel: the barrel re-exports .tsx panels, and tests stub+// it down to the cache bump alone.+import { hubTokenHeader } from "@/features/hub/lib/hub-token-header";import { readFastApiError } from "@/lib/format-fastapi-error";export type EmbeddingModelSettings = {@@ -11,6 +14,11 @@ export type EmbeddingModelSettings = {defaultEmbeddingModel: string;defaultEmbeddingGgufRepo: string;isCustom: boolean;+ /** THIS model is held in memory right now, for the status line. */+ loaded: boolean;+ /** ANY embedder is resident, so Unload has something to do. Saving a new model+ * does not release the old one, so not the same question as `loaded`. */+ backendLoaded: boolean;};type ApiEmbeddingModelSettings = {@@ -24,6 +32,9 @@ type ApiEmbeddingModelSettings = {default_embedding_gguf_repo: string;// biome-ignore lint/style/useNamingConvention: API schemais_custom: boolean;+ loaded?: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ backend_loaded?: boolean;};/** 409 from the backend: the model could not be verified as an embedding model@@ -41,6 +52,10 @@ function fromApi(settings: ApiEmbeddingModelSettings): EmbeddingModelSettings {defaultEmbeddingModel: settings.default_embedding_model,defaultEmbeddingGgufRepo: settings.default_embedding_gguf_repo,isCustom: settings.is_custom,+ loaded: settings.loaded ?? false,+ // A backend predating this field answers only about the selected model,+ // which is the old behaviour and the right fallback.+ backendLoaded: settings.backend_loaded ?? settings.loaded ?? false,};}@@ -56,7 +71,12 @@ export async function loadEmbeddingModelSettings(): Promise<EmbeddingModelSettinexport async function updateEmbeddingModelSettings(embeddingModel: string,- options?: { hfToken?: string; force?: boolean },+ options?: {+ hfToken?: string;+ force?: boolean;+ ggufRepo?: string | null;+ backend?: EmbeddingModelResolution["backend"] | null;+ },): Promise<EmbeddingModelSettings> {const res = await authFetch("/api/settings/embedding-model", {method: "PUT",@@ -66,6 +86,9 @@ export async function updateEmbeddingModelSettings(embedding_model: embeddingModel,// biome-ignore lint/style/useNamingConvention: API schemahf_token: options?.hfToken || null,+ // biome-ignore lint/style/useNamingConvention: API schema+ gguf_repo: options?.ggufRepo ?? null,+ backend: options?.backend ?? null,force: options?.force ?? false,}),});@@ -89,6 +112,72 @@ export async function updateEmbeddingModelSettings(return settings;}+/** What saving a model would need fetched, and whether it is already on disk. */+export type EmbeddingModelResolution = {+ embeddingModel: string;+ backend: "llama" | "sentence-transformers";+ /** Repo to hand the download manager; null when nothing needs fetching. */+ downloadRepo: string | null;+ /** The selected GGUF family (all shards when split), on llama-server. */+ files: string[] | null;+ cached: boolean;+ sizeBytes: number | null;+ /** Why the model is unusable here; the detail the save would refuse with. */+ error: string | null;+};++type ApiEmbeddingModelResolution = {+ // biome-ignore lint/style/useNamingConvention: API schema+ embedding_model: string;+ backend: "llama" | "sentence-transformers";+ // biome-ignore lint/style/useNamingConvention: API schema+ download_repo: string | null;+ files: string[] | null;+ cached: boolean;+ // biome-ignore lint/style/useNamingConvention: API schema+ size_bytes: number | null;+ error: string | null;+};++export async function resolveEmbeddingModel(+ embeddingModel: string,+ options?: { hfToken?: string },+): Promise<EmbeddingModelResolution> {+ const params = new URLSearchParams({ model: embeddingModel });+ const res = await authFetch(+ `/api/settings/embedding-model/resolve?${params}`,+ // The token rides a header so a gated repo's credential stays out of the URL.+ { headers: hubTokenHeader(options?.hfToken) },+ );+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to check the embedding model"),+ );+ }+ const body = (await res.json()) as ApiEmbeddingModelResolution;+ return {+ embeddingModel: body.embedding_model,+ backend: body.backend,+ downloadRepo: body.download_repo,+ files: body.files,+ cached: body.cached,+ sizeBytes: body.size_bytes,+ error: body.error,+ };+}++export async function unloadEmbeddingModel(): Promise<EmbeddingModelSettings> {+ const res = await authFetch("/api/settings/embedding-model/unload", {+ method: "POST",+ });+ if (!res.ok) {+ throw new Error(+ await readFastApiError(res, "Failed to unload the embedding model"),+ );+ }+ return fromApi(await res.json());+}+export async function resetEmbeddingModelSettings(): Promise<EmbeddingModelSettings> {const res = await authFetch("/api/settings/embedding-model", {method: "DELETE",diff --git a/studio/frontend/src/features/settings/components/documents-rag-section.tsx b/studio/frontend/src/features/settings/components/documents-rag-section.tsxindex d0323bfda12..e3343dcac9d 100644--- a/studio/frontend/src/features/settings/components/documents-rag-section.tsx+++ b/studio/frontend/src/features/settings/components/documents-rag-section.tsx@@ -3,35 +3,59 @@import { Button } from "@/components/ui/button";import { useChatRuntimeStore } from "@/features/chat";+import { formatBytes, listCachedGguf, listCachedModels } from "@/features/hub";+import { Spinner } from "@/components/ui/spinner";+import { cn } from "@/lib/utils";+import {+ DOWNLOAD_KIND,+ downloadManager,+ jobKeyOf,+ scopedVariant,+ useDownloadManagerStore,+} from "@/features/hub/download-manager";import { useT } from "@/i18n";import { toast } from "@/lib/toast";-import { type ReactElement, useEffect, useState } from "react";+import { type ReactElement, useCallback, useEffect, useState } from "react";import {EmbeddingModelBlockedError,+ type EmbeddingModelResolution,EmbeddingModelVerificationError,- resetEmbeddingModelSettings,+ resolveEmbeddingModel,+ unloadEmbeddingModel,updateEmbeddingModelSettings,} from "../api/embedding-model";import { useEmbeddingModelStore } from "../stores/embedding-model-store";-import { EmbeddingModelCombobox } from "./embedding-model-combobox";+import { EmbeddingModelPicker } from "./embedding-model-picker";import { SettingsRow } from "./settings-row";import { SettingsSection } from "./settings-section";+/** One slot per repo for the embedder's GGUF, so re-picking adopts the running+ * transfer and a full-repo Hub download keeps its own. */+const EMBEDDING_DOWNLOAD_SCOPE = "rag-embedding";+/*** Which model indexes uploaded documents. Rendered in both General and Data,* off one shared store, so a save on one is what the other reads.+ *+ * Picking applies immediately, as dictation does; a model that is not on disk+ * is marked pending by the server and offered as a download. Its loader remains+ * cache-only, so closing or cancelling cannot turn into a first-index transfer.*/+// Residency is not a function of anything this component does, so it is polled+// rather than read only on a settings mutation.+const RESIDENCY_POLL_MS = 5000;+export function DocumentsRagSection(): ReactElement {const t = useT();const hfToken = useChatRuntimeStore((s) => s.hfToken);const embeddingModel = useEmbeddingModelStore((s) => s.settings);const loadError = useEmbeddingModelStore((s) => s.loadError);+ const beginSave = useEmbeddingModelStore((s) => s.beginSave);+ const isSaveCurrent = useEmbeddingModelStore((s) => s.isSaveCurrent);const save = useEmbeddingModelStore((s) => s.save);- // Null until the user edits, so the field follows a save made on the other- // surface instead of pinning whatever this mount first read.- const [draftOverride, setDraftOverride] = useState<string | null>(null);- const draftEmbeddingModel =- draftOverride ?? embeddingModel?.embeddingModel ?? "";+ // Unloading releases residency and leaves the selection alone, so it must not+ // take a place in save order and retire an in-flight selection's reservation.+ const applyResidency = useEmbeddingModelStore((s) => s.applyResidency);const [saveError, setSaveError] = useState<string | null>(null);// The store carries the backend's reason; an unreadable failure has none.const loadFailure =@@ -39,67 +63,325 @@ export function DocumentsRagSection(): ReactElement {? null: loadError || t("settings.general.rag.loadError");const embeddingModelError = saveError ?? loadFailure;- // Set after a 409 (unverifiable model); offers "Save anyway".- const [embeddingModelNeedsForce, setEmbeddingModelNeedsForce] =- useState(false);+ // Set after a 409 (unverifiable model); "Save anyway" applies to that pick only.+ const [forceCandidate, setForceCandidate] = useState<string | null>(null);+ /** Bumped when a save leaves the model string unchanged, which the effect+ * below keys on and would otherwise not re-run for. */+ const [resolveNonce, setResolveNonce] = useState(0);const [isSavingEmbeddingModel, setIsSavingEmbeddingModel] = useState(false);+ // What /resolve last said about the saved model: drives the status line and+ // whether the action row offers Download.+ const [resolution, setResolution] = useState<EmbeddingModelResolution | null>(+ null,+ );+ // Repo ids with a complete cache, for the picker's on-device dot.+ const [cachedRepos, setCachedRepos] = useState<ReadonlySet<string>>(+ () => new Set(),+ );useEffect(() => {void useEmbeddingModelStore.getState().load();}, []);- const saveEmbeddingModel = async (force: boolean) => {- const trimmed = draftEmbeddingModel.trim();- if (!trimmed) {- setSaveError(t("settings.general.rag.emptyError"));- return;+ // Residency changes with no settings mutation: a running job reaching its+ // first encode makes a backend resident, and the store loads only on mount.+ // No lifecycle event to subscribe to, so re-read while visible; a hidden tab+ // does not poll and catches up when it returns.+ useEffect(() => {+ const refresh = () => {+ if (document.hidden) return;+ void useEmbeddingModelStore.getState().load();+ };+ const timer = window.setInterval(refresh, RESIDENCY_POLL_MS);+ document.addEventListener("visibilitychange", refresh);+ return () => {+ window.clearInterval(timer);+ document.removeEventListener("visibilitychange", refresh);+ };+ }, []);++ const refreshCachedRepos = useCallback(async () => {+ try {+ const [models, gguf] = await Promise.all([+ listCachedModels(hfToken || undefined),+ listCachedGguf(hfToken || undefined),+ ]);+ setCachedRepos(+ new Set(+ [...models, ...gguf]+ .filter((repo) => !repo.partial)+ .map((repo) => repo.repo_id),+ ),+ );+ } catch {+ // Advisory: without it rows just lose their dot.}- setIsSavingEmbeddingModel(true);+ }, [hfToken]);++ useEffect(() => {+ void refreshCachedRepos();+ }, [refreshCachedRepos]);++ // Resolve the model already saved, so the row reports its state on open+ // rather than only after a pick.+ const savedModel = embeddingModel?.embeddingModel;+ useEffect(() => {+ // Another mounted settings surface may have saved a different model. Its+ // model-scoped actions and errors say nothing about this new selection.+ setResolution(null);+ setForceCandidate(null);setSaveError(null);+ if (!savedModel) return;+ let live = true;+ void resolveEmbeddingModel(savedModel, { hfToken: hfToken || undefined })+ .then((next) => {+ if (live && next.embeddingModel === savedModel) setResolution(next);+ })+ .catch(() => {+ // Offline: the row simply says nothing about disk state.+ });+ return () => {+ live = false;+ };+ }, [savedModel, hfToken, resolveNonce]);++ /** Persist the pick, recording the GGUF repo /resolve named so the loader+ * opens what was downloaded rather than re-deriving a name. */+ const persist = async (+ model: string,+ plan: EmbeddingModelResolution | null,+ force: boolean,+ reservation: number,+ ): Promise<boolean> => {try {- const stood = await save(() =>- updateEmbeddingModelSettings(trimmed, {- hfToken: hfToken || undefined,- force,- }),+ const stood = await save(+ () =>+ updateEmbeddingModelSettings(model, {+ hfToken: hfToken || undefined,+ ggufRepo:+ plan?.backend === "llama" ? (plan.downloadRepo ?? null) : null,+ backend: plan?.backend ?? null,+ force,+ }),+ reservation,);- // A later save owns the field now, so this answer says nothing current.- if (!stood) return;- setDraftOverride(null);- setEmbeddingModelNeedsForce(false);+ // A later save owns the setting now, so this answer says nothing current.+ if (!stood) return false;+ setForceCandidate(null);toast.success(t("settings.general.rag.saved"), {description: t("settings.general.rag.reindexWarning"),});+ return true;} catch (error) {- // A hard security block cannot be forced; keep the "save anyway" action hidden.+ // A hard security block cannot be forced; keep "Save anyway" hidden.if (error instanceof EmbeddingModelBlockedError) {- setEmbeddingModelNeedsForce(false);+ setForceCandidate(null);} else if (error instanceof EmbeddingModelVerificationError) {- setEmbeddingModelNeedsForce(true);+ setForceCandidate(model);}setSaveError(error instanceof Error? error.message: t("settings.general.rag.saveError"),);+ return false;+ }+ };++ /** Resolve first, so a model that needs fetching is offered as a download+ * rather than saved and quietly fetched at the first index. */+ const applyEmbeddingModel = async (model: string, force: boolean) => {+ // A force affordance belongs only to the request that produced its 409.+ setForceCandidate(null);+ const trimmed = model.trim();+ if (!trimmed) {+ setSaveError(t("settings.general.rag.emptyError"));+ return;+ }+ // Claim cross-surface ordering before the resolver await. Otherwise a+ // slower older selection can call save last and overwrite a newer pick.+ const reservation = beginSave();+ setIsSavingEmbeddingModel(true);+ setSaveError(null);+ setResolution(null);+ try {+ if (force) {+ // A force save can leave the model string unchanged, so the savedModel+ // effect does not re-run and nothing restores the plan this call cleared,+ // leaving no Download offered while the loader refuses to index.+ if (await persist(trimmed, null, true, reservation)) {+ setResolveNonce((n) => n + 1);+ }+ return;+ }+ let resolution: EmbeddingModelResolution;+ try {+ resolution = await resolveEmbeddingModel(trimmed, {+ hfToken: hfToken || undefined,+ });+ } catch {+ if (!isSaveCurrent(reservation)) return;+ // Offline or the probe failed: let the save decide, as it did before.+ await persist(trimmed, null, false, reservation);+ return;+ }+ if (!isSaveCurrent(reservation)) return;+ if (resolution.error) {+ // Forceable: the user may know something the probe cannot see.+ setResolution(resolution);+ setForceCandidate(trimmed);+ setSaveError(resolution.error);+ return;+ }+ // Retain the plan only after the server accepted the matching setting.+ // A rejected save must not expose a Download action for an unsaved repo.+ if (await persist(trimmed, resolution, false, reservation)) {+ setResolution(resolution);+ }} finally {setIsSavingEmbeddingModel(false);}};- const resetEmbeddingModel = async () => {+ const startDownload = async (resolution: EmbeddingModelResolution) => {+ const repoId = resolution.downloadRepo;+ if (!repoId) return;+ // Scoped when the backend named a file: the companion repo carries every+ // quant, and the embedder opens one.+ const scoped = resolution.files !== null && resolution.files.length > 0;+ try {+ const outcome = await downloadManager.requestStart({+ kind: DOWNLOAD_KIND.MODEL,+ repoId,+ variant: scoped ? scopedVariant(EMBEDDING_DOWNLOAD_SCOPE) : null,+ scopeId: scoped ? EMBEDDING_DOWNLOAD_SCOPE : null,+ files: scoped ? (resolution.files ?? undefined) : undefined,+ expectedBytes: resolution.sizeBytes ?? 0,+ });+ if (outcome === "started") {+ toast.success(+ t("settings.general.rag.downloading", {+ model: resolution.embeddingModel,+ }),+ { description: t("settings.general.rag.downloadingDescription") },+ );+ } else if (outcome === "conflict") {+ // Not a failure: an earlier partial used a different transport and the+ // Hub's own card is where it resumes. "Couldn't start" would send the+ // user looking for a problem instead of for that row.+ toast.info(t("settings.general.rag.downloadConflict"));+ } else if (outcome === "busy") {+ // The repo is occupied by a sibling transfer, which the downloads panel+ // is already showing. Reselect once it lands.+ toast.info(t("settings.general.rag.downloadBusy"));+ } else {+ // requestStart turns refused starts into outcomes rather than throws, so+ // every remaining non-start still needs feedback from this caller.+ toast.error(t("settings.general.rag.downloadFailed"));+ }+ } catch (error) {+ toast.error(t("settings.general.rag.downloadFailed"), {+ description: error instanceof Error ? error.message : undefined,+ });+ }+ };++ // The live job for the repo this model needs, so the button reflects a+ // transfer started here or from anywhere else.+ const downloadJobKey =+ resolution?.downloadRepo && !resolution.cached+ ? jobKeyOf(+ DOWNLOAD_KIND.MODEL,+ resolution.downloadRepo,+ resolution.files?.length+ ? scopedVariant(EMBEDDING_DOWNLOAD_SCOPE)+ : null,+ )+ : null;+ const fullSnapshotJobKey =+ resolution?.downloadRepo && !resolution.cached+ ? jobKeyOf(DOWNLOAD_KIND.MODEL, resolution.downloadRepo, null)+ : null;+ const downloadState = useDownloadManagerStore((state) =>+ downloadJobKey ? (state.jobs[downloadJobKey]?.state ?? null) : null,+ );+ const fullSnapshotDownloadState = useDownloadManagerStore((state) =>+ fullSnapshotJobKey ? (state.jobs[fullSnapshotJobKey]?.state ?? null) : null,+ );+ const downloading =+ downloadState === "running" ||+ downloadState === "cancelling" ||+ fullSnapshotDownloadState === "running" ||+ fullSnapshotDownloadState === "cancelling";++ // The original resolve correctly said uncached. Once the shared manager+ // completes, ask again so the status/button and picker dots reflect disk.+ useEffect(() => {+ if (+ (downloadState !== "complete" &&+ fullSnapshotDownloadState !== "complete") ||+ !savedModel+ )+ return;+ let live = true;+ void Promise.all([+ resolveEmbeddingModel(savedModel, { hfToken: hfToken || undefined }),+ refreshCachedRepos(),+ ])+ .then(([next]) => {+ if (live && next.embeddingModel === savedModel) setResolution(next);+ })+ .catch(() => {+ // The completed transfer remains in the shared panel; a later open+ // retries the advisory resolve/cache inventory.+ });+ return () => {+ live = false;+ };+ }, [+ downloadState,+ fullSnapshotDownloadState,+ savedModel,+ hfToken,+ refreshCachedRepos,+ ]);+ const canDownload = Boolean(+ resolution && !resolution.cached && resolution.downloadRepo,+ );+ const onDevice = Boolean(resolution?.cached);+ const statusTone: "pending" | "ready" | "error" | null = !embeddingModel+ ? "pending"+ : embeddingModelError+ ? "error"+ : downloading || isSavingEmbeddingModel+ ? "pending"+ : onDevice+ ? "ready"+ : null;+ const statusText = !embeddingModel+ ? t("settings.general.rag.checking")+ : downloading+ ? t("settings.general.rag.downloadingStatus")+ : canDownload+ ? resolution?.sizeBytes+ ? t("settings.general.rag.notDownloadedSized", {+ size: formatBytes(resolution.sizeBytes),+ })+ : t("settings.general.rag.notDownloaded")+ : onDevice+ ? embeddingModel.loaded+ ? t("settings.general.rag.loaded")+ : t("settings.general.rag.onDevice")+ : "";++ const unload = async () => {setIsSavingEmbeddingModel(true);- setSaveError(null);- setEmbeddingModelNeedsForce(false);try {- if (!(await save(resetEmbeddingModelSettings))) return;- setDraftOverride(null);+ await applyResidency(unloadEmbeddingModel);} catch (error) {- setSaveError(- error instanceof Error- ? error.message- : t("settings.general.rag.saveError"),- );+ toast.error(t("settings.general.rag.unloadFailed"), {+ description: error instanceof Error ? error.message : undefined,+ });} finally {setIsSavingEmbeddingModel(false);}@@ -115,57 +397,71 @@ export function DocumentsRagSection(): ReactElement {className="max-[360px]:flex-col max-[360px]:items-stretch max-[360px]:gap-3"><div className="flex flex-col items-end gap-1 max-[360px]:w-full">- <div className="flex items-center gap-2 max-[360px]:w-full">- <EmbeddingModelCombobox- value={draftEmbeddingModel}- onChange={(next) => {- setDraftOverride(next);- setEmbeddingModelNeedsForce(false);- setSaveError(null);- }}- accessToken={hfToken || undefined}- disabled={!embeddingModel}- placeholder={t("settings.general.rag.searchPlaceholder")}- ariaLabel={t("settings.general.rag.embeddingModel")}- className="w-[220px] max-[360px]:min-w-0 max-[360px]:flex-1"- />- <Button- variant="outline"- size="sm"- disabled={- !embeddingModel ||- isSavingEmbeddingModel ||- draftEmbeddingModel.trim() === embeddingModel.embeddingModel- }- onClick={() => void saveEmbeddingModel(false)}- >- {isSavingEmbeddingModel ? t("common.saving") : t("common.save")}- </Button>- </div>+ <EmbeddingModelPicker+ value={embeddingModel?.embeddingModel ?? ""}+ onSelect={(model) => void applyEmbeddingModel(model, false)}+ defaultModel={embeddingModel?.defaultEmbeddingModel}+ cachedModels={cachedRepos}+ accessToken={hfToken || undefined}+ disabled={!embeddingModel}+ busy={isSavingEmbeddingModel}+ className="w-[260px] max-[360px]:w-full"+ />{embeddingModelError ? (<span className="max-w-[300px] text-right text-xs text-destructive">{embeddingModelError}</span>) : null}- <div className="flex items-center gap-2">- {embeddingModelNeedsForce ? (+ <div className="flex min-h-7 w-full items-center justify-between gap-3">+ <span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">+ {statusTone ? (+ <span+ className={cn(+ "size-1.5 shrink-0 rounded-full",+ statusTone === "pending"+ ? "animate-pulse bg-current"+ : statusTone === "ready"+ ? "bg-emerald-500"+ : "bg-destructive",+ )}+ />+ ) : null}+ <span className="truncate">{statusText}</span>+ </span>+ {forceCandidate ? (<Buttonvariant="outline"size="sm"+ className="h-7 shrink-0 px-2.5 text-xs"disabled={isSavingEmbeddingModel}- onClick={() => void saveEmbeddingModel(true)}+ onClick={() => void applyEmbeddingModel(forceCandidate, true)}>{t("settings.general.rag.saveAnyway")}</Button>+ ) : canDownload ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 shrink-0 px-2.5 text-xs"+ disabled={downloading || isSavingEmbeddingModel}+ onClick={() => resolution && void startDownload(resolution)}+ >+ {downloading ? <Spinner className="mr-1.5" /> : null}+ {t("settings.general.rag.download")}+ </Button>) : null}- {embeddingModel?.isCustom ? (+ {/* Outside the chain above: saving a new model does not release the+ old one, so while Download shows for an uncached pick the previous+ model can still be resident. backendLoaded asks about any. */}+ {embeddingModel?.backendLoaded ? (<Button- variant="ghost"+ variant="outline"size="sm"+ className="h-7 shrink-0 px-2.5 text-xs"disabled={isSavingEmbeddingModel}- onClick={() => void resetEmbeddingModel()}+ onClick={() => void unload()}>- {t("settings.general.rag.resetAction")}+ {t("settings.general.rag.unload")}</Button>) : null}</div>diff --git a/studio/frontend/src/features/settings/components/embedding-model-combobox.tsx b/studio/frontend/src/features/settings/components/embedding-model-combobox.tsxdeleted file mode 100644index dd272728ccb..00000000000--- a/studio/frontend/src/features/settings/components/embedding-model-combobox.tsx+++ /dev/null@@ -1,139 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--import {- Combobox,- ComboboxContent,- ComboboxEmpty,- ComboboxInput,- ComboboxItem,- ComboboxList,-} from "@/components/ui/combobox";-import { Spinner } from "@/components/ui/spinner";-import type { PipelineType } from "@huggingface/hub";-import { useHubModelSearch } from "@/features/hub/hooks/use-hub-model-search";-import { useDebouncedValue } from "@/hooks";-import { type ReactElement, useMemo, useRef, useState } from "react";--// HF pipeline filter for embedding models; matches the backend's-// is_embedding_model signals (sentence-similarity / feature-extraction).-const EMBEDDING_TASKS: readonly PipelineType[] = [- "sentence-similarity",- "feature-extraction",-];--type EmbeddingModelComboboxProps = {- value: string;- /** Fires on typing, selection, and Enter with the current text. */- onChange: (value: string) => void;- accessToken?: string;- disabled?: boolean;- placeholder?: string;- ariaLabel?: string;- className?: string;-};--export function EmbeddingModelCombobox({- value,- onChange,- accessToken,- disabled,- placeholder,- ariaLabel,- className,-}: EmbeddingModelComboboxProps): ReactElement {- const anchorRef = useRef<HTMLDivElement>(null);- // Only text the user typed is a query. A saved or selected value searches for- // itself, which leaves the list holding that one model instead of the others.- const [typed, setTyped] = useState<string | null>(null);- // Anything the parent set (selection, reset, reload) clears the query. Saving- // writes the same string back, which this cannot see, so closing clears it too.- const query = typed !== null && typed === value ? typed : "";- const debouncedQuery = useDebouncedValue(query);-- const { results, isLoading } = useHubModelSearch(debouncedQuery, {- task: EMBEDDING_TASKS,- accessToken,- excludeGguf: true,- enabled: !disabled,- // Curated unsloth listing when empty (the global top-downloads page holds- // no unsloth mirrors to float); a typed query searches the whole Hub.- ownerScope: debouncedQuery.trim() ? "all" : "unsloth",- });-- const items = useMemo(() => {- const ids = results.map((item) => item.id);- const selected = value.trim();- if (selected && !ids.includes(selected)) {- ids.push(selected);- }- return ids;- }, [results, value]);-- return (- <div- ref={anchorRef}- className={className}- onKeyDown={(event) => {- if (event.key !== "Enter") return;- if (!(event.target instanceof HTMLInputElement)) return;- event.preventDefault();- const typed = event.target.value.trim();- if (typed) {- onChange(typed);- } else if (items.length > 0) {- onChange(items[0]);- }- }}- >- <Combobox- items={items}- filteredItems={items}- filter={null}- onOpenChange={(open) => {- // The search lasts as long as the list is open, as the model picker- // in Settings -> Agents does.- if (!open) setTyped(null);- }}- value={value.trim() ? value : null}- onValueChange={(next) => onChange(next ?? "")}- onInputValueChange={(next, details) => {- // The settings load and a pick both write the input too, and arrive- // with another reason; only typing is a search.- if (details.reason !== "input-change") {- setTyped(null);- return;- }- setTyped(next);- onChange(next);- }}- itemToStringValue={(item) => item}- autoHighlight={true}- >- <ComboboxInput- className="h-8 w-full font-mono [&_input]:text-ui-11"- placeholder={placeholder}- aria-label={ariaLabel}- disabled={disabled}- />- <ComboboxContent anchor={anchorRef}>- {isLoading ? (- <div className="flex items-center gap-2 px-2 py-3 text-xs text-muted-foreground">- <Spinner className="size-3.5" />- Searching...- </div>- ) : (- <ComboboxEmpty>No embedding models found</ComboboxEmpty>- )}- <ComboboxList>- {(id: string) => (- <ComboboxItem key={id} value={id}>- <span className="truncate font-mono text-ui-11">{id}</span>- </ComboboxItem>- )}- </ComboboxList>- </ComboboxContent>- </Combobox>- </div>- );-}diff --git a/studio/frontend/src/features/settings/components/embedding-model-picker.tsx b/studio/frontend/src/features/settings/components/embedding-model-picker.tsxnew file mode 100644index 00000000000..02ccbf37117--- /dev/null+++ b/studio/frontend/src/features/settings/components/embedding-model-picker.tsx@@ -0,0 +1,249 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Input } from "@/components/ui/input";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/components/ui/popover";+import { Spinner } from "@/components/ui/spinner";+import { formatBytes, useHubModelSearch } from "@/features/hub";+import { useDebouncedValue, useWheelScrollRef } from "@/hooks";+import { useT } from "@/i18n";+import { ChevronDownStandardIcon } from "@/lib/chevron-icons";+import { Search01Icon } from "@hugeicons/core-free-icons";+import { HugeiconsIcon } from "@hugeicons/react";+import type { PipelineType } from "@huggingface/hub";+import { type ReactElement, useMemo, useState } from "react";++// HF pipeline filter for embedding models; matches the backend's+// is_embedding_model signals (sentence-similarity / feature-extraction).+const EMBEDDING_TASKS: readonly PipelineType[] = [+ "sentence-similarity",+ "feature-extraction",+];+type EmbeddingModelPickerProps = {+ value: string;+ /** Fires once, on a pick. Typing is a search, not a selection. */+ onSelect: (model: string) => void;+ /** The env/default model, marked "Recommended" so it is findable again. */+ defaultModel?: string;+ /** Repos already on disk, for the on-device dot. */+ cachedModels?: ReadonlySet<string>;+ accessToken?: string;+ disabled?: boolean;+ /** Held open with a spinner while the pick is resolved and saved. */+ busy?: boolean;+ className?: string;+};++/**+ * Embedding model picker for Settings -> Documents & RAG.+ *+ * Modelled on the dictation picker (voice-tab.tsx `SttModelPicker`): a button+ * trigger, so the saved model never reads as a half-typed query, and one field+ * that reaches the whole Hub. Empty lists unsloth's embedders, which the global+ * top-downloads page would bury.+ */+/** Repo ids an on-device copy of `model` can be filed under.+ *+ * The inventory records what was fetched, not what was picked, and the two differ+ * by the conventions the backend resolves through: llama-server opens the `-GGUF`+ * companion, and a slashless alias resolves under `sentence-transformers/`.+ *+ * An off-convention mirror is not derivable here and still shows no dot; the+ * row's own status line covers the selected model. */+export function cachedRepoCandidates(model: string): string[] {+ const id = model.trim();+ if (!id) return [];+ const candidates = [id, `${id}-GGUF`];+ if (!id.includes("/")) candidates.push(`sentence-transformers/${id}`);+ // Mirrors the backend's _QUANT_SUFFIX_RE: an unquantized re-upload's GGUF sits+ // on the base name, so embeddinggemma-300m-qat-q8_0-unquantized resolves to+ // embeddinggemma-300m-GGUF and would otherwise never light up.+ const slash = id.lastIndexOf("/");+ const owner = slash === -1 ? "" : id.slice(0, slash + 1);+ const name = id.slice(slash + 1);+ const base = name.replace(/(?:-qat)?(?:-q\d+_\d+[a-z]*)?-unquantized$/i, "");+ if (base !== name) candidates.push(`${owner}${base}-GGUF`);+ return candidates;+}++function isOnDevice(+ cached: ReadonlySet<string> | undefined,+ model: string,+): boolean {+ if (!cached) return false;+ return cachedRepoCandidates(model).some((repo) => cached.has(repo));+}++export function EmbeddingModelPicker({+ value,+ onSelect,+ defaultModel,+ cachedModels,+ accessToken,+ disabled,+ busy,+ className,+}: EmbeddingModelPickerProps): ReactElement {+ const t = useT();+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const resultsRef = useWheelScrollRef<HTMLDivElement>();+ const debouncedQuery = useDebouncedValue(query.trim());++ const { results, isLoading } = useHubModelSearch(debouncedQuery, {+ task: EMBEDDING_TASKS,+ accessToken,+ excludeGguf: true,+ enabled: open && !disabled,+ ownerScope: debouncedQuery ? "all" : "unsloth",+ });++ const items = useMemo(() => {+ const rows = results.map((result) => ({+ id: result.id,+ sizeBytes: result.estimatedSizeBytes ?? result.curatedSizeBytes ?? null,+ }));+ // Keep the saved model reachable when the listing drops it: a local path, or+ // a repo the query does not match.+ const selected = value.trim();+ if (selected && !rows.some((row) => row.id === selected)) {+ rows.push({ id: selected, sizeBytes: null });+ }+ // The configured default the same way: the empty search is scoped to+ // `unsloth`, so a private, other-owner or local default had no row, and the+ // old "Reset to default" button is gone.+ const fallback = defaultModel?.trim();+ if (fallback && !rows.some((row) => row.id === fallback)) {+ rows.push({ id: fallback, sizeBytes: null });+ }+ return rows;+ }, [results, value, defaultModel]);++ const pick = (model: string) => {+ setOpen(false);+ setQuery("");+ // Reselecting is a retry: a previous transfer may have been cancelled or+ // its cache evicted while the setting still names this model.+ onSelect(model);+ };++ return (+ <Popover+ open={open}+ onOpenChange={(next) => {+ if (disabled || busy) return;+ setOpen(next);+ if (!next) setQuery("");+ }}+ >+ <PopoverTrigger asChild={true}>+ <button+ type="button"+ data-testid="embedding-model-trigger"+ aria-label={t("settings.general.rag.embeddingModel")}+ disabled={disabled || busy}+ className={`border-border bg-background hover:bg-accent/50 dark:border-transparent dark:bg-white/[0.06] dark:hover:bg-white/10 focus-visible:border-ring flex h-8 w-full cursor-pointer items-center justify-between gap-1.5 rounded-full border px-3.5 font-mono text-ui-11 outline-none transition-colors disabled:cursor-not-allowed disabled:opacity-60 ${className ?? ""}`}+ >+ <span className="truncate">{value}</span>+ {busy ? (+ <Spinner className="size-3.5 shrink-0" />+ ) : (+ <HugeiconsIcon+ icon={ChevronDownStandardIcon}+ strokeWidth={2}+ className="text-muted-foreground pointer-events-none size-4 shrink-0"+ />+ )}+ </button>+ </PopoverTrigger>+ <PopoverContent align="end" sideOffset={4} className="w-80 gap-0 p-0">+ <div className="relative p-1.5 pb-0.5">+ <HugeiconsIcon+ icon={Search01Icon}+ strokeWidth={2}+ className="text-muted-foreground pointer-events-none absolute top-[calc(50%+2px)] left-4 size-3.5 -translate-y-1/2"+ />+ <Input+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ data-testid="embedding-model-search"+ placeholder={t("settings.general.rag.searchPlaceholder")}+ className="h-8 pl-8 text-sm"+ autoFocus={true}+ onKeyDown={(event) => {+ if (event.key !== "Enter") return;+ event.preventDefault();+ // Preserve arbitrary typed submission: the backend can recognize+ // existing relative paths such as "embedder" that have no slash.+ const typed = query.trim();+ if (typed) {+ pick(typed);+ } else if (items.length > 0) {+ pick(items[0].id);+ }+ }}+ />+ </div>+ <div+ ref={resultsRef}+ data-testid="embedding-model-results"+ className="max-h-64 overflow-y-auto p-1"+ >+ {isLoading && debouncedQuery ? (+ <div className="flex items-center gap-2 px-3 py-3 text-xs text-muted-foreground">+ <Spinner className="size-3.5" />+ {t("settings.general.rag.searching")}+ </div>+ ) : items.length === 0 ? (+ <div className="px-3 py-3 text-xs text-muted-foreground">+ {t("settings.general.rag.noResults")}+ </div>+ ) : (+ items.map((item) => (+ <button+ key={item.id}+ type="button"+ onClick={() => pick(item.id)}+ aria-selected={item.id === value}+ className={`flex w-full items-center justify-between gap-3 rounded-full px-2.5 py-1.5 text-left transition-colors hover:bg-muted ${+ item.id === value ? "bg-accent font-medium" : ""+ }`}+ >+ <span className="flex min-w-0 flex-1 items-center gap-1.5">+ {/* Same green dot the Hub marks an on-device row with. */}+ {isOnDevice(cachedModels, item.id) ? (+ <span+ // A bare span is generic, and ARIA-in-HTML forbids naming+ // one, so Safari and Firefox drop the label and the dot goes+ // unannounced. Same role the Hub's own on-device dot carries.+ role="img"+ aria-label={t("settings.general.rag.onDevice")}+ className="size-[5px] shrink-0 rounded-full bg-status-success"+ />+ ) : null}+ <span className="truncate font-mono text-ui-11">+ {item.id}+ </span>+ {item.id === defaultModel ? (+ <span className="shrink-0 rounded-full bg-emerald-500/12 px-1.5 py-px text-ui-9 font-medium text-emerald-600 dark:bg-emerald-400/15 dark:text-emerald-400">+ {t("settings.general.rag.recommended")}+ </span>+ ) : null}+ </span>+ {item.sizeBytes ? (+ <span className="shrink-0 text-ui-10 tabular-nums text-muted-foreground">+ {formatBytes(item.sizeBytes)}+ </span>+ ) : null}+ </button>+ ))+ )}+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/studio/frontend/src/features/settings/stores/embedding-model-store.ts b/studio/frontend/src/features/settings/stores/embedding-model-store.tsindex 48e67a1818e..a495644c469 100644--- a/studio/frontend/src/features/settings/stores/embedding-model-store.ts+++ b/studio/frontend/src/features/settings/stores/embedding-model-store.ts@@ -19,11 +19,26 @@ interface EmbeddingModelState {/** Bumped by every committed mutation, so a slower read cannot undo it. */revision: number;applySettings: (settings: EmbeddingModelSettings) => void;+ /** Reserve mutation order before an async preflight such as model resolution. */+ beginSave: () => number;+ isSaveCurrent: (reservation: number) => boolean;/*** Run a write and commit its answer. Returns false when a later write* started first, so the caller leaves the field to that one.*/- save: (request: () => Promise<EmbeddingModelSettings>) => Promise<boolean>;+ save: (+ request: () => Promise<EmbeddingModelSettings>,+ reservation?: number,+ ) => Promise<boolean>;+ /**+ * Run a write that changes residency rather than the selection, such as+ * unloading. It claims no place in save order: doing so retired the+ * reservation a selection still running its preflight on the other surface+ * was holding, and that selection then returned without ever persisting.+ */+ applyResidency: (+ request: () => Promise<EmbeddingModelSettings>,+ ) => Promise<void>;load: () => Promise<void>;}@@ -53,8 +68,13 @@ export const useEmbeddingModelStore = create<EmbeddingModelState>(loadError: null,revision: state.revision + 1,})),- save: async (request) => {- const save = ++latestSave;+ beginSave: () => ++latestSave,+ isSaveCurrent: (reservation) => reservation === latestSave,+ save: async (request, reservation) => {+ const save = reservation ?? ++latestSave;+ // Resolution belonging to an older cross-surface selection must never+ // become a newer write merely because its preflight finished last.+ if (save !== latestSave) return false;savesInFlight += 1;try {const settings = await request();@@ -67,7 +87,11 @@ export const useEmbeddingModelStore = create<EmbeddingModelState>(} catch (error) {// A failed write leaves the backend on whatever the others wrote, so// an overlap has to be settled by a read, not by request order.- if (save !== latestSave || savesInFlight > 1) saveWasSuperseded = true;+ if (save !== latestSave) {+ saveWasSuperseded = true;+ return false;+ }+ if (savesInFlight > 1) saveWasSuperseded = true;throw error;} finally {savesInFlight -= 1;@@ -77,6 +101,26 @@ export const useEmbeddingModelStore = create<EmbeddingModelState>(}}},+ applyResidency: async (request) => {+ savesInFlight += 1;+ try {+ const settings = await request();+ // A selection is still out, and this answer was formed before whatever+ // it persists. Applying it would show the old model; let the settling+ // re-read below carry the residency change instead.+ if (savesInFlight > 1) {+ saveWasSuperseded = true;+ return;+ }+ get().applySettings(settings);+ } finally {+ savesInFlight -= 1;+ if (savesInFlight === 0 && saveWasSuperseded) {+ saveWasSuperseded = false;+ void get().load();+ }+ }+ },load: async () => {const revision = get().revision;const load = ++latestLoad;diff --git a/studio/frontend/src/features/settings/tabs/voice-tab.tsx b/studio/frontend/src/features/settings/tabs/voice-tab.tsxindex 6583d3f45ea..278ec78d985 100644--- a/studio/frontend/src/features/settings/tabs/voice-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/voice-tab.tsx@@ -22,7 +22,6 @@ import {type SttDownloadStatus,StudioModelDictationAdapter,StudioSpeechSynthesisAdapter,- cancelSttDownload,createConfiguredUtterance,curateSystemVoices,fetchSttStatus,@@ -36,12 +35,6 @@ import {validateSttModel,} from "@/features/chat";import {- type TransferSample,- appendSample,- computeTransferStats,-} from "@/lib/transfer-stats";-import {- DownloadProgressBar,hfApiToken,useHfTokenStore,useHubModelSearch,@@ -507,14 +500,10 @@ export function VoiceTab() {| "ready"| "error";type SttDownloadAvailability =- | "checking"- | "missing"- | "downloaded"- | "error";+ "checking" | "missing" | "downloaded" | "error";const [sttPhase, setSttPhase] = useState<SttPhase>("idle");const [sttDevice, setSttDevice] = useState<string | null>(null);const [statusNonce, setStatusNonce] = useState(0);- const [sttDownloadCancelling, setSttDownloadCancelling] = useState(false);const [sttUnloading, setSttUnloading] = useState(false);const isLocalEngine = dictationEngine === "model";const isCustomEngine = dictationEngine === "custom";@@ -526,11 +515,8 @@ export function VoiceTab() {const [sttDownload, setSttDownload] = useState<SttDownloadStatus | null>(null,);- const [downloadBytesPerSec, setDownloadBytesPerSec] = useState(0);- const [downloadEtaSeconds, setDownloadEtaSeconds] = useState(0);// Was a bare two-sample delta over ~800ms with no window or stability gate,// so one throttled timer or bursty poll set the displayed speed outright.- const downloadSamplesRef = useRef<TransferSample[]>([]);// Model whose download this tab watched; completion auto-loads it.const watchedDownloadRef = useRef<string | null>(null);@@ -600,40 +586,14 @@ export function VoiceTab() {if (download.model && !isTrackingSttDownload(download.model)) {trackSttDownload(download.model);}- const bytes = download.bytes_done ?? 0;- // Compare before adopting: assigning first made this test itself, so- // a straight switch priced the new run over the old one's samples.- if (download.model !== watchedDownloadRef.current) {- // A different model's counter is a different run.- downloadSamplesRef.current.length = 0;- }watchedDownloadRef.current = download.model;- if (typeof document !== "undefined" && document.hidden) {- // A hidden tab's timers are clamped to about once a minute, so- // these gaps time the poller and would read as the burst cadence.- // The hub poll loop drops them the same way.- downloadSamplesRef.current.length = 0;- setDownloadBytesPerSec(0);- setDownloadEtaSeconds(0);- } else {- appendSample(downloadSamplesRef.current, Date.now() / 1000, bytes);- const stats = computeTransferStats(- downloadSamplesRef.current,- download.bytes_total ?? 0,- );- setDownloadBytesPerSec(stats.stable ? stats.rateBytesPerSecond : 0);- setDownloadEtaSeconds(stats.stable ? stats.etaSeconds : 0);- }- // Keep the download progress fresh.+ // Keep the status line fresh.window.setTimeout(() => {if (!cancelled) setStatusNonce((n) => n + 1);}, 800);} else {const finished = watchedDownloadRef.current;watchedDownloadRef.current = null;- downloadSamplesRef.current.length = 0;- setDownloadBytesPerSec(0);- setDownloadEtaSeconds(0);if (finished === sttModel &&engineStatus.downloaded_models.includes(sttModel) &&@@ -765,21 +725,6 @@ export function VoiceTab() {}};- const stopSttDownload = async () => {- setSttDownloadCancelling(true);- try {- await cancelSttDownload(sttDownload?.model ?? sttModel);- setSttDownload(null);- setStatusNonce((nonce) => nonce + 1);- } catch (error) {- toast.error(t("settings.voice.dictation.sttCancelDownloadFailed"), {- description: error instanceof Error ? error.message : undefined,- });- } finally {- setSttDownloadCancelling(false);- }- };-const warmSttModel = async () => {setSttPhase("loading");try {@@ -1081,133 +1026,100 @@ export function VoiceTab() {setSttModel(next);}}/>- {downloadingThisModel ? (- <div className="rounded-md border border-border/60 bg-muted/20 px-2.5 pt-2">- <div className="mb-1.5 flex items-center justify-between gap-3">- <span className="text-xs text-muted-foreground">- {sttModelStatusText}- </span>- <Button- variant="ghost"- size="sm"- className="-mr-1.5 h-7 shrink-0 px-2 text-xs"- disabled={sttDownloadCancelling}- onClick={() => void stopSttDownload()}- >- {sttDownloadCancelling- ? t("settings.voice.dictation.sttCancellingDownload")- : t("settings.voice.dictation.sttCancelDownload")}- </Button>- </div>- <DownloadProgressBar- progress={{- expectedBytes: sttDownload?.bytes_total ?? 0,- downloadedBytes: sttDownload?.bytes_done ?? 0,- fraction:- sttDownload?.bytes_total &&- sttDownload.bytes_total > 0- ? (sttDownload.bytes_done ?? 0) /- sttDownload.bytes_total- : 0,- }}- bytesPerSec={downloadBytesPerSec}- etaSeconds={downloadEtaSeconds}- />- </div>- ) : (- <div className="flex min-h-7 items-center justify-between gap-3">- <span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">- {effectiveSttDownloadAvailability === "checking" ||- sttPhase === "loading" ||- sttPhase === "checking" ? (- <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-current" />- ) : sttPhase === "ready" ||- (effectiveSttDownloadAvailability === "downloaded" &&- sttPhase === "on-demand") ? (- <span className="size-1.5 shrink-0 rounded-full bg-emerald-500" />- ) : effectiveSttDownloadAvailability === "error" ||- sttPhase === "error" ? (- <span className="size-1.5 shrink-0 rounded-full bg-destructive" />+ {/* Progress lives in the shared downloads panel; a second bar+ here said the same thing twice. */}+ <div className="flex min-h-7 items-center justify-between gap-3">+ <span className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">+ {effectiveSttDownloadAvailability === "checking" ||+ sttPhase === "loading" ||+ sttPhase === "checking" ? (+ <span className="size-1.5 shrink-0 animate-pulse rounded-full bg-current" />+ ) : sttPhase === "ready" ||+ (effectiveSttDownloadAvailability === "downloaded" &&+ sttPhase === "on-demand") ? (+ <span className="size-1.5 shrink-0 rounded-full bg-emerald-500" />+ ) : effectiveSttDownloadAvailability === "error" ||+ sttPhase === "error" ? (+ <span className="size-1.5 shrink-0 rounded-full bg-destructive" />+ ) : null}+ <span>{sttModelStatusText}</span>+ </span>+ {sttPhase === "unavailable" ? (+ <Button+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs"+ onClick={() => setStatusNonce((nonce) => nonce + 1)}+ >+ {t("settings.voice.dictation.sttRetry")}+ </Button>+ ) : effectiveSttDownloadAvailability === "error" ? (+ <Button+ variant="ghost"+ size="sm"+ className="h-7 px-2 text-xs"+ disabled={downloadingThisModel || sttDownloadStarting}+ // Restart: the sidecar error is sticky until a new+ // start(), so re-polling alone never clears it.+ onClick={() => void beginSttDownload()}+ >+ {t("settings.voice.dictation.sttRetry")}+ </Button>+ ) : effectiveSttDownloadAvailability === "missing" ? (+ <Button+ variant="outline"+ size="sm"+ className="h-7 px-2.5 text-xs"+ disabled={downloadingThisModel || sttDownloadStarting}+ onClick={() => void beginSttDownload()}+ >+ {downloadingThisModel || sttDownloadStarting ? (+ <Spinner className="mr-1.5" />) : null}- <span>{sttModelStatusText}</span>- </span>- {sttPhase === "unavailable" ? (+ {t("settings.voice.dictation.sttDownload")}+ </Button>+ ) : effectiveSttDownloadAvailability === "downloaded" ? (+ sttPhase === "ready" ? (<Button- variant="ghost"+ variant="outline"size="sm"- className="h-7 px-2 text-xs"- onClick={() => setStatusNonce((nonce) => nonce + 1)}+ className="h-7 px-2.5 text-xs"+ disabled={sttUnloading}+ onClick={releaseSttModel}>- {t("settings.voice.dictation.sttRetry")}+ {sttUnloading ? <Spinner className="mr-1.5" /> : null}+ {sttUnloading+ ? t("settings.voice.dictation.sttUnloading")+ : t("settings.voice.dictation.sttUnload")}</Button>- ) : effectiveSttDownloadAvailability === "error" ? (+ ) : sttPhase === "loading" || sttPhase === "checking" ? (+ // The status line already says "Loading model…"; the+ // button only needs the spinner.<Button- variant="ghost"- size="sm"- className="h-7 px-2 text-xs"- disabled={downloadingThisModel || sttDownloadStarting}- // Restart the download; the sidecar error is sticky until- // a new start(), so re-polling alone never clears it.- onClick={() => void beginSttDownload()}+ variant="outline"+ size="icon-sm"+ className="size-7"+ disabled={true}+ aria-label={t(+ "settings.voice.dictation.sttLoadingModel",+ )}>- {t("settings.voice.dictation.sttRetry")}+ <Spinner /></Button>- ) : effectiveSttDownloadAvailability === "missing" ? (+ ) : (<Buttonvariant="outline"size="sm"className="h-7 px-2.5 text-xs"- disabled={downloadingThisModel || sttDownloadStarting}- onClick={() => void beginSttDownload()}+ onClick={warmSttModel}>- {downloadingThisModel || sttDownloadStarting ? (- <Spinner className="mr-1.5" />- ) : null}- {t("settings.voice.dictation.sttDownload")}+ {sttPhase === "error"+ ? t("settings.voice.dictation.sttRetry")+ : t("settings.voice.dictation.sttLoad")}</Button>- ) : effectiveSttDownloadAvailability === "downloaded" ? (- sttPhase === "ready" ? (- <Button- variant="outline"- size="sm"- className="h-7 px-2.5 text-xs"- disabled={sttUnloading}- onClick={releaseSttModel}- >- {sttUnloading ? <Spinner className="mr-1.5" /> : null}- {sttUnloading- ? t("settings.voice.dictation.sttUnloading")- : t("settings.voice.dictation.sttUnload")}- </Button>- ) : sttPhase === "loading" || sttPhase === "checking" ? (- // The status line already says "Loading model…"; the- // button only needs the spinner.- <Button- variant="outline"- size="icon-sm"- className="size-7"- disabled={true}- aria-label={t(- "settings.voice.dictation.sttLoadingModel",- )}- >- <Spinner />- </Button>- ) : (- <Button- variant="outline"- size="sm"- className="h-7 px-2.5 text-xs"- onClick={warmSttModel}- >- {sttPhase === "error"- ? t("settings.voice.dictation.sttRetry")- : t("settings.voice.dictation.sttLoad")}- </Button>- )- ) : null}- </div>- )}+ )+ ) : null}+ </div></div></SettingsRow>) : (@@ -1351,9 +1263,7 @@ export function VoiceTab() {value={effectiveTtsEngine}onValueChange={(value) =>setTtsEngine(- value === "studio" || value === "custom"- ? value- : "system",+ value === "studio" || value === "custom" ? value : "system",)}>diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.tsindex 17daf9b8087..e854fbcde98 100644--- a/studio/frontend/src/i18n/locales/ar.ts+++ b/studio/frontend/src/i18n/locales/ar.ts@@ -794,7 +794,7 @@ export const ar = {embeddingModel: "نموذج التضمين (Embedding)",embeddingModelDescription:"نموذج Hugging Face أو مسار محلي يُستخدم لفهرسة مستنداتك والبحث فيها. القيمة الافتراضية هي {defaultModel}.",- searchPlaceholder: "ابحث عن نماذج التضمين",+ searchPlaceholder: "ابحث عن أي نموذج على HF",reindexWarning:"يؤثر فقط في المستندات التي تُفهرس حديثًا. أعِد رفع المستندات الحالية بعد تغيير النموذج.",emptyError: "أدخل معرّف نموذج Hugging Face أو مسارًا محليًا.",@@ -802,7 +802,24 @@ export const ar = {saveError: "فشل حفظ نموذج التضمين.",saved: "تم حفظ نموذج التضمين.",saveAnyway: "الحفظ على أي حال",- resetAction: "إعادة التعيين إلى الافتراضي",+ recommended: "موصى به",+ onDevice: "على الجهاز",+ searching: "جارٍ البحث في Hugging Face…",+ checking: "جارٍ التحقق…",+ noResults: "لم يتم العثور على نماذج تضمين",+ download: "تنزيل",+ unload: "إلغاء التحميل",+ unloadFailed: "تعذّر إلغاء تحميل نموذج التضمين",+ downloadingStatus: "جارٍ التنزيل…",+ notDownloaded: "غير مُنزّل",+ notDownloadedSized: "غير مُنزّل · {size}",+ loaded: "مُحمّل",+ downloading: "جارٍ تنزيل {model}",+ downloadingDescription:+ "يظهر التقدم في لوحة التنزيلات. ستستخدمه الفهرسة بمجرد اكتماله.",+ downloadFailed: "تعذّر بدء التنزيل",+ downloadConflict: "استأنف هذا التنزيل من Hub",+ downloadBusy: "التنزيل قيد التقدم بالفعل",},storage: {sectionTitle: "التخزين",diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.tsindex 5c120aed803..6e83153b5a1 100644--- a/studio/frontend/src/i18n/locales/de.ts+++ b/studio/frontend/src/i18n/locales/de.ts@@ -815,7 +815,7 @@ export const de = {embeddingModel: "Embedding-Modell",embeddingModelDescription:"Hugging-Face-Modell oder lokaler Pfad zum Indexieren und Durchsuchen Ihrer Dokumente. Standard ist {defaultModel}.",- searchPlaceholder: "Embedding-Modelle suchen",+ searchPlaceholder: "Beliebiges Modell auf HF suchen",reindexWarning:"Betrifft nur neu indexierte Dokumente. Laden Sie bestehende nach einer Modelländerung erneut hoch.",emptyError:@@ -825,7 +825,24 @@ export const de = {saveError: "Das Embedding-Modell konnte nicht gespeichert werden.",saved: "Embedding-Modell gespeichert.",saveAnyway: "Trotzdem speichern",- resetAction: "Auf Standard zurücksetzen",+ recommended: "Empfohlen",+ onDevice: "Auf dem Gerät",+ searching: "Hugging Face wird durchsucht…",+ checking: "Wird geprüft…",+ noResults: "Keine Embedding-Modelle gefunden",+ download: "Herunterladen",+ unload: "Entladen",+ unloadFailed: "Embedding-Modell konnte nicht entladen werden",+ downloadingStatus: "Wird heruntergeladen…",+ notDownloaded: "Nicht heruntergeladen",+ notDownloadedSized: "Nicht heruntergeladen · {size}",+ loaded: "Geladen",+ downloading: "{model} wird heruntergeladen",+ downloadingDescription:+ "Der Fortschritt steht im Downloads-Bereich. Nach Abschluss wird es für die Indizierung genutzt.",+ downloadFailed: "Download konnte nicht gestartet werden",+ downloadConflict: "Diesen Download im Hub fortsetzen",+ downloadBusy: "Download läuft bereits",},storage: {sectionTitle: "Speicher",diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.tsindex 4684b6e2739..b0ff9af7cec 100644--- a/studio/frontend/src/i18n/locales/en.ts+++ b/studio/frontend/src/i18n/locales/en.ts@@ -795,7 +795,7 @@ export const en = {embeddingModel: "Embedding model",embeddingModelDescription:"Hugging Face model or local path used to index and search your documents. Default is {defaultModel}.",- searchPlaceholder: "Search embedding models",+ searchPlaceholder: "Search any model on HF",reindexWarning:"Only affects newly indexed documents. Re-upload existing ones after changing the model.",emptyError: "Enter a Hugging Face model id or local path.",@@ -803,7 +803,24 @@ export const en = {saveError: "Failed to save the embedding model.",saved: "Embedding model saved.",saveAnyway: "Save anyway",- resetAction: "Reset to default",+ recommended: "Recommended",+ onDevice: "On device",+ searching: "Searching Hugging Face…",+ checking: "Checking…",+ noResults: "No embedding models found",+ download: "Download",+ unload: "Unload",+ unloadFailed: "Couldn't unload the embedding model",+ downloadingStatus: "Downloading…",+ notDownloaded: "Not downloaded",+ notDownloadedSized: "Not downloaded · {size}",+ loaded: "Loaded",+ downloading: "Downloading {model}",+ downloadingDescription:+ "Progress is in the downloads panel. Indexing uses it once it lands.",+ downloadFailed: "Couldn't start the download",+ downloadConflict: "Resume this download from the Hub",+ downloadBusy: "Download already in progress",},storage: {sectionTitle: "Storage",diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.tsindex 02f418e0763..4b8f324157b 100644--- a/studio/frontend/src/i18n/locales/es.ts+++ b/studio/frontend/src/i18n/locales/es.ts@@ -810,7 +810,7 @@ export const es = {embeddingModel: "Modelo de embeddings",embeddingModelDescription:"Modelo de Hugging Face o ruta local usada para indexar y buscar tus documentos. El valor predeterminado es {defaultModel}.",- searchPlaceholder: "Buscar modelos de embedding",+ searchPlaceholder: "Buscar cualquier modelo en HF",reindexWarning:"Solo afecta a los documentos recién indexados. Vuelve a subir los existentes tras cambiar el modelo.",emptyError:@@ -820,7 +820,24 @@ export const es = {saveError: "No se pudo guardar el modelo de embeddings.",saved: "Modelo de embeddings guardado.",saveAnyway: "Guardar de todos modos",- resetAction: "Restablecer al valor predeterminado",+ recommended: "Recomendado",+ onDevice: "En el dispositivo",+ searching: "Buscando en Hugging Face…",+ checking: "Comprobando…",+ noResults: "No se encontraron modelos de embedding",+ download: "Descargar",+ unload: "Descargar de memoria",+ unloadFailed: "No se pudo descargar el modelo de embedding",+ downloadingStatus: "Descargando…",+ notDownloaded: "No descargado",+ notDownloadedSized: "No descargado · {size}",+ loaded: "Cargado",+ downloading: "Descargando {model}",+ downloadingDescription:+ "El progreso está en el panel de descargas. La indexación lo usará cuando termine.",+ downloadFailed: "No se pudo iniciar la descarga",+ downloadConflict: "Reanuda esta descarga desde el Hub",+ downloadBusy: "La descarga ya está en curso",},storage: {sectionTitle: "Almacenamiento",diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.tsindex 07fb5d5400c..615152a42b8 100644--- a/studio/frontend/src/i18n/locales/fr.ts+++ b/studio/frontend/src/i18n/locales/fr.ts@@ -814,7 +814,7 @@ export const fr = {embeddingModel: "Modèle d'embedding",embeddingModelDescription:"Modèle Hugging Face ou chemin local utilisé pour indexer et rechercher vos documents. La valeur par défaut est {defaultModel}.",- searchPlaceholder: "Rechercher des modèles d'embedding",+ searchPlaceholder: "Rechercher n'importe quel modèle sur HF",reindexWarning:"N'affecte que les documents nouvellement indexés. Téléversez à nouveau les documents existants après avoir changé de modèle.",emptyError:@@ -823,7 +823,24 @@ export const fr = {saveError: "Échec de l'enregistrement du modèle d'embedding.",saved: "Modèle d'embedding enregistré.",saveAnyway: "Enregistrer quand même",- resetAction: "Rétablir la valeur par défaut",+ recommended: "Recommandé",+ onDevice: "Sur l'appareil",+ searching: "Recherche sur Hugging Face…",+ checking: "Vérification…",+ noResults: "Aucun modèle d'embedding trouvé",+ download: "Télécharger",+ unload: "Décharger",+ unloadFailed: "Impossible de décharger le modèle d'embedding",+ downloadingStatus: "Téléchargement…",+ notDownloaded: "Non téléchargé",+ notDownloadedSized: "Non téléchargé · {size}",+ loaded: "Chargé",+ downloading: "Téléchargement de {model}",+ downloadingDescription:+ "La progression s'affiche dans le panneau des téléchargements. L'indexation l'utilisera une fois terminé.",+ downloadFailed: "Impossible de démarrer le téléchargement",+ downloadConflict: "Reprenez ce téléchargement depuis le Hub",+ downloadBusy: "Téléchargement déjà en cours",},storage: {sectionTitle: "Stockage",diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.tsindex 5ece1a4b923..609e36cdd67 100644--- a/studio/frontend/src/i18n/locales/hi.ts+++ b/studio/frontend/src/i18n/locales/hi.ts@@ -797,7 +797,7 @@ export const hi = {embeddingModel: "एम्बेडिंग मॉडल",embeddingModelDescription:"आपके दस्तावेज़ों को इंडेक्स और खोजने के लिए उपयोग किया जाने वाला Hugging Face मॉडल या स्थानीय पथ। डिफ़ॉल्ट {defaultModel} है।",- searchPlaceholder: "एम्बेडिंग मॉडल खोजें",+ searchPlaceholder: "HF पर कोई भी मॉडल खोजें",reindexWarning:"केवल नए इंडेक्स किए गए दस्तावेज़ों को प्रभावित करता है। मॉडल बदलने के बाद मौजूदा दस्तावेज़ फिर से अपलोड करें।",emptyError: "एक Hugging Face मॉडल id या स्थानीय पथ दर्ज करें।",@@ -805,7 +805,24 @@ export const hi = {saveError: "एम्बेडिंग मॉडल सहेजने में विफल।",saved: "एम्बेडिंग मॉडल सहेजा गया।",saveAnyway: "फिर भी सहेजें",- resetAction: "डिफ़ॉल्ट पर रीसेट करें",+ recommended: "अनुशंसित",+ onDevice: "डिवाइस पर",+ searching: "Hugging Face पर खोज रहे हैं…",+ checking: "जाँच रहे हैं…",+ noResults: "कोई एम्बेडिंग मॉडल नहीं मिला",+ download: "डाउनलोड करें",+ unload: "अनलोड करें",+ unloadFailed: "एम्बेडिंग मॉडल अनलोड नहीं हो सका",+ downloadingStatus: "डाउनलोड हो रहा है…",+ notDownloaded: "डाउनलोड नहीं हुआ",+ notDownloadedSized: "डाउनलोड नहीं हुआ · {size}",+ loaded: "लोड हो गया",+ downloading: "{model} डाउनलोड हो रहा है",+ downloadingDescription:+ "प्रगति डाउनलोड पैनल में दिखती है। पूरा होने पर इंडेक्सिंग इसका उपयोग करेगी।",+ downloadFailed: "डाउनलोड शुरू नहीं हो सका",+ downloadConflict: "इस डाउनलोड को Hub से फिर से शुरू करें",+ downloadBusy: "डाउनलोड पहले से चल रहा है",},storage: {sectionTitle: "स्टोरेज",diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.tsindex 51dfebcaabf..3af4facb312 100644--- a/studio/frontend/src/i18n/locales/it.ts+++ b/studio/frontend/src/i18n/locales/it.ts@@ -786,7 +786,7 @@ export const it = {embeddingModel: "Modello di embedding",embeddingModelDescription:"Modello Hugging Face o percorso locale usato per indicizzare e cercare nei tuoi documenti. Il valore predefinito è {defaultModel}.",- searchPlaceholder: "Cerca modelli di embedding",+ searchPlaceholder: "Cerca qualsiasi modello su HF",reindexWarning:"Vale solo per i documenti indicizzati da ora in poi. Ricarica quelli esistenti dopo aver cambiato modello.",emptyError:@@ -796,7 +796,24 @@ export const it = {saveError: "Salvataggio del modello di embedding non riuscito.",saved: "Modello di embedding salvato.",saveAnyway: "Salva comunque",- resetAction: "Ripristina il valore predefinito",+ recommended: "Consigliato",+ onDevice: "Sul dispositivo",+ searching: "Ricerca su Hugging Face…",+ checking: "Verifica…",+ noResults: "Nessun modello di embedding trovato",+ download: "Scarica",+ unload: "Scarica dalla memoria",+ unloadFailed: "Impossibile scaricare il modello di embedding",+ downloadingStatus: "Download in corso…",+ notDownloaded: "Non scaricato",+ notDownloadedSized: "Non scaricato · {size}",+ loaded: "Caricato",+ downloading: "Download di {model}",+ downloadingDescription:+ "L'avanzamento è nel pannello dei download. L'indicizzazione lo userà al termine.",+ downloadFailed: "Impossibile avviare il download",+ downloadConflict: "Riprendi questo download dall'Hub",+ downloadBusy: "Download già in corso",},storage: {sectionTitle: "Archiviazione",diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.tsindex 326cc38a1c8..8ee3cff40da 100644--- a/studio/frontend/src/i18n/locales/ja.ts+++ b/studio/frontend/src/i18n/locales/ja.ts@@ -783,14 +783,30 @@ export const ja = {sectionTitle: "ドキュメントと RAG",embeddingModel: "埋め込みモデル",embeddingModelDescription: "ドキュメントのインデックス作成と検索に使用する Hugging Face モデルまたはローカルパス。デフォルトは {defaultModel} です。",- searchPlaceholder: "埋め込みモデルを検索",+ searchPlaceholder: "HF 上の任意のモデルを検索",reindexWarning: "新しくインデックスされるドキュメントにのみ影響します。モデルを変更した後は、既存のドキュメントを再アップロードしてください。",emptyError: "Hugging Face モデル ID またはローカルパスを入力してください。",loadError: "埋め込みモデル設定の読み込みに失敗しました。",saveError: "埋め込みモデルの保存に失敗しました。",saved: "埋め込みモデルを保存しました。",saveAnyway: "そのまま保存",- resetAction: "デフォルトに戻す",+ recommended: "推奨",+ onDevice: "このデバイス",+ searching: "Hugging Face を検索中…",+ checking: "確認中…",+ noResults: "埋め込みモデルが見つかりません",+ download: "ダウンロード",+ unload: "アンロード",+ unloadFailed: "埋め込みモデルをアンロードできませんでした",+ downloadingStatus: "ダウンロード中…",+ notDownloaded: "未ダウンロード",+ notDownloadedSized: "未ダウンロード · {size}",+ loaded: "読み込み済み",+ downloading: "{model} をダウンロード中",+ downloadingDescription: "進捗はダウンロードパネルに表示されます。完了後にインデックス作成で使用されます。",+ downloadFailed: "ダウンロードを開始できませんでした",+ downloadConflict: "このダウンロードは Hub から再開してください",+ downloadBusy: "ダウンロードはすでに進行中です",},storage: {sectionTitle: "ストレージ",diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.tsindex 0d22f6723c7..c18a56dcf9a 100644--- a/studio/frontend/src/i18n/locales/ko.ts+++ b/studio/frontend/src/i18n/locales/ko.ts@@ -791,7 +791,7 @@ export const ko = {embeddingModel: "임베딩 모델",embeddingModelDescription:"문서를 색인하고 검색하는 데 사용되는 Hugging Face 모델 또는 로컬 경로입니다. 기본값은 {defaultModel}입니다.",- searchPlaceholder: "임베딩 모델 검색",+ searchPlaceholder: "HF의 모든 모델 검색",reindexWarning:"새로 색인되는 문서에만 적용됩니다. 모델을 변경한 후 기존 문서를 다시 업로드하세요.",emptyError: "Hugging Face 모델 ID 또는 로컬 경로를 입력하세요.",@@ -799,7 +799,23 @@ export const ko = {saveError: "임베딩 모델을 저장하지 못했습니다.",saved: "임베딩 모델이 저장되었습니다.",saveAnyway: "그래도 저장",- resetAction: "기본값으로 재설정",+ recommended: "추천",+ onDevice: "기기에 있음",+ searching: "Hugging Face 검색 중…",+ checking: "확인 중…",+ noResults: "임베딩 모델을 찾을 수 없습니다",+ download: "다운로드",+ unload: "언로드",+ unloadFailed: "임베딩 모델을 언로드할 수 없습니다",+ downloadingStatus: "다운로드 중…",+ notDownloaded: "다운로드되지 않음",+ notDownloadedSized: "다운로드되지 않음 · {size}",+ loaded: "로드됨",+ downloading: "{model} 다운로드 중",+ downloadingDescription: "진행 상황은 다운로드 패널에 표시됩니다. 완료되면 색인에 사용됩니다.",+ downloadFailed: "다운로드를 시작할 수 없습니다",+ downloadConflict: "Hub에서 이 다운로드를 재개하세요",+ downloadBusy: "이미 다운로드가 진행 중입니다",},storage: {sectionTitle: "저장소",diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.tsindex 79c57b028fe..f86307eea72 100644--- a/studio/frontend/src/i18n/locales/pt-br.ts+++ b/studio/frontend/src/i18n/locales/pt-br.ts@@ -804,7 +804,7 @@ export const ptBR = {embeddingModel: "Modelo de embedding",embeddingModelDescription:"Modelo do Hugging Face ou caminho local usado para indexar e buscar seus documentos. O padrão é {defaultModel}.",- searchPlaceholder: "Buscar modelos de embedding",+ searchPlaceholder: "Buscar qualquer modelo no HF",reindexWarning:"Afeta apenas documentos recém-indexados. Reenvie os documentos existentes após alterar o modelo.",emptyError: "Insira um id de modelo do Hugging Face ou um caminho local.",@@ -812,7 +812,24 @@ export const ptBR = {saveError: "Falha ao salvar o modelo de embedding.",saved: "Modelo de embedding salvo.",saveAnyway: "Salvar mesmo assim",- resetAction: "Redefinir para o padrão",+ recommended: "Recomendado",+ onDevice: "No dispositivo",+ searching: "Buscando no Hugging Face…",+ checking: "Verificando…",+ noResults: "Nenhum modelo de embedding encontrado",+ download: "Baixar",+ unload: "Descarregar",+ unloadFailed: "Não foi possível descarregar o modelo de embedding",+ downloadingStatus: "Baixando…",+ notDownloaded: "Não baixado",+ notDownloadedSized: "Não baixado · {size}",+ loaded: "Carregado",+ downloading: "Baixando {model}",+ downloadingDescription:+ "O progresso aparece no painel de downloads. A indexação vai usá-lo quando terminar.",+ downloadFailed: "Não foi possível iniciar o download",+ downloadConflict: "Retome este download pelo Hub",+ downloadBusy: "Download já em andamento",},storage: {sectionTitle: "Armazenamento",diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.tsindex 3843d277234..de84af69d74 100644--- a/studio/frontend/src/i18n/locales/ru.ts+++ b/studio/frontend/src/i18n/locales/ru.ts@@ -798,7 +798,7 @@ export const ru = {embeddingModel: "Модель эмбеддингов",embeddingModelDescription:"Модель Hugging Face или локальный путь для индексации и поиска по вашим документам. По умолчанию {defaultModel}.",- searchPlaceholder: "Поиск embedding-моделей",+ searchPlaceholder: "Поиск любой модели на HF",reindexWarning:"Влияет только на вновь индексируемые документы. После смены модели загрузите существующие документы заново.",emptyError: "Введите ID модели Hugging Face или локальный путь.",@@ -806,7 +806,24 @@ export const ru = {saveError: "Не удалось сохранить модель эмбеддингов.",saved: "Модель эмбеддингов сохранена.",saveAnyway: "Всё равно сохранить",- resetAction: "Восстановить значение по умолчанию",+ recommended: "Рекомендуется",+ onDevice: "На устройстве",+ searching: "Поиск в Hugging Face…",+ checking: "Проверка…",+ noResults: "Модели эмбеддингов не найдены",+ download: "Скачать",+ unload: "Выгрузить",+ unloadFailed: "Не удалось выгрузить модель эмбеддингов",+ downloadingStatus: "Загрузка…",+ notDownloaded: "Не загружено",+ notDownloadedSized: "Не загружено · {size}",+ loaded: "Загружено",+ downloading: "Загрузка {model}",+ downloadingDescription:+ "Прогресс виден на панели загрузок. После завершения он будет использован для индексации.",+ downloadFailed: "Не удалось начать загрузку",+ downloadConflict: "Возобновите эту загрузку в Hub",+ downloadBusy: "Загрузка уже выполняется",},storage: {sectionTitle: "Хранилище",diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.tsindex a474bf12734..cf593e82dc7 100644--- a/studio/frontend/src/i18n/locales/zh-CN.ts+++ b/studio/frontend/src/i18n/locales/zh-CN.ts@@ -775,7 +775,7 @@ export const zhCN = {embeddingModel: "Embedding 模型",embeddingModelDescription:"用于为文档建立索引和搜索的 Hugging Face 模型或本地路径。默认值为 {defaultModel}。",- searchPlaceholder: "搜索嵌入模型",+ searchPlaceholder: "搜索 HF 上的任意模型",reindexWarning:"仅影响新建立索引的文档。更改模型后请重新上传已有文档。",emptyError: "请输入 Hugging Face 模型 ID 或本地路径。",@@ -783,7 +783,23 @@ export const zhCN = {saveError: "保存 embedding 模型失败。",saved: "Embedding 模型已保存。",saveAnyway: "仍然保存",- resetAction: "重置为默认值",+ recommended: "推荐",+ onDevice: "本机",+ searching: "正在搜索 Hugging Face…",+ checking: "检查中…",+ noResults: "未找到 embedding 模型",+ download: "下载",+ unload: "卸载",+ unloadFailed: "无法卸载 embedding 模型",+ downloadingStatus: "正在下载…",+ notDownloaded: "未下载",+ notDownloadedSized: "未下载 · {size}",+ loaded: "已加载",+ downloading: "正在下载 {model}",+ downloadingDescription: "进度显示在下载面板中。下载完成后即可用于建立索引。",+ downloadFailed: "无法开始下载",+ downloadConflict: "请在 Hub 中继续此下载",+ downloadBusy: "下载已在进行中",},storage: {sectionTitle: "存储",diff --git a/studio/frontend/tests/download-eta-invalidation.test.ts b/studio/frontend/tests/download-eta-invalidation.test.tsindex bf9a039a53a..021faa558d3 100644--- a/studio/frontend/tests/download-eta-invalidation.test.ts+++ b/studio/frontend/tests/download-eta-invalidation.test.ts@@ -6,8 +6,8 @@// GGUF metadata arriving after a job was adopted does exactly that. Hiding the// ETA for one poll beats showing one for a size that is no longer the target.//-// Also pins that the voice poller ignores a hidden tab's throttled callbacks,-// the way the hub poll loop already does.+// Also pins that the poll loop ignores a hidden tab's throttled callbacks: its+// gaps time the poller, not the transfer, and would read as the burst rate.import assert from "node:assert/strict";import { readFileSync } from "node:fs";@@ -59,21 +59,28 @@ test("a total that grows drops the ETA measured against the old one", () => {);});-test("the voice poller drops a hidden tab's throttled samples", () => {- const source = readFileSync(+test("the poll loop drops a hidden tab's throttled samples", () => {+ // Voice used to run a second estimator of its own for a progress bar beside+ // the shared panel. Both are gone, so this is the only one left to guard.+ const voice = readFileSync(new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),"utf8",);- const guard = source.indexOf("document.hidden");- assert.ok(guard > 0, "the voice poller should skip a hidden tab");- const clear = source.indexOf("downloadSamplesRef.current.length = 0", guard);- const sample = source.indexOf(- "appendSample(downloadSamplesRef.current",- guard,+ assert.ok(+ !voice.includes("downloadSamplesRef"),+ "voice no longer estimates a rate of its own",+ );++ const source = readFileSync(+ new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),+ "utf8",);+ const guard = source.indexOf("document.hidden");+ assert.ok(guard > 0, "the poll loop should skip a hidden tab");+ const clear = source.indexOf("rt.speedSamples.length = 0", guard);assert.ok(clear > 0, "a hidden tab should clear the samples");assert.ok(- sample < 0 || clear < sample,+ clear - guard < 120,"the hidden-tab branch must clear rather than sample",);});diff --git a/studio/frontend/tests/embedding-model-combobox-query.test.ts b/studio/frontend/tests/embedding-model-combobox-query.test.tsdeleted file mode 100644index a01dc141899..00000000000--- a/studio/frontend/tests/embedding-model-combobox-query.test.ts+++ /dev/null@@ -1,84 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0--import assert from "node:assert/strict";-import { readFileSync } from "node:fs";-import test from "node:test";-import { fileURLToPath } from "node:url";--import { en } from "../src/i18n/locales/en.ts";--function read(path: string): string {- return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf-8");-}--// These reach the hub and chat barrels and cannot be imported here, so this-// asserts on source, like ~50 sibling tests.-const COMBOBOX = read(- "../src/features/settings/components/embedding-model-combobox.tsx",-);-const SECTION = read(- "../src/features/settings/components/documents-rag-section.tsx",-);-const GENERAL_TAB = read("../src/features/settings/tabs/general-tab.tsx");-const DATA_TAB = read("../src/features/settings/tabs/data-tab.tsx");--test("only typed text searches the Hub", () => {- // Searching for the saved model returns that model, so the list held one row- // and the other embedding models were unreachable without clearing the field.- assert.match(- COMBOBOX,- /const query = typed !== null && typed === value \? typed : ""/,- );- assert.match(COMBOBOX, /useDebouncedValue\(query\)/);- assert.ok(- !COMBOBOX.includes("useDebouncedValue(value)"),- "the controlled value is no longer the query",- );-});--test("only a keystroke counts as typing", () => {- const start = COMBOBOX.indexOf("onInputValueChange");- const handler = COMBOBOX.slice(start, COMBOBOX.indexOf("}}", start));- // base-ui writes the input for the settings load ("none") and for a pick- // ("item-press") too. Treating those as a search collapses the list to the- // model already set, which is what the field did before.- assert.ok(handler.includes('details.reason !== "input-change"'));- assert.ok(handler.includes("setTyped(null)"));- assert.ok(handler.includes("setTyped(next)"));-});--test("closing the list ends the search", () => {- const start = COMBOBOX.indexOf("onOpenChange");- const handler = COMBOBOX.slice(start, COMBOBOX.indexOf("}}", start));- // Saving writes the same string back, so the value never changes and the- // equality guard cannot see it. Without this, reopening the list after a- // save is still filtered by what was typed to enter the model.- assert.ok(handler.includes("if (!open) setTyped(null)"));-});--test("the field says what it does", () => {- assert.match(- SECTION,- /placeholder=\{t\("settings.general.rag.searchPlaceholder"\)\}/,- );- assert.equal(- en.settings.general.rag.searchPlaceholder,- "Search embedding models",- );-});--test("General and Data show the same section, not two copies of it", () => {- assert.ok(SECTION.includes("export function DocumentsRagSection"));- for (const [name, tab] of [- ["general", GENERAL_TAB],- ["data", DATA_TAB],- ] as const) {- assert.ok(tab.includes("<DocumentsRagSection />"), `${name} renders it`);- // A second copy of the load and save logic would let the two tabs disagree.- assert.ok(- !tab.includes("loadEmbeddingModelSettings"),- `${name} has no embedding logic of its own`,- );- }-});diff --git a/studio/frontend/tests/embedding-model-picker.test.ts b/studio/frontend/tests/embedding-model-picker.test.tsnew file mode 100644index 00000000000..82ec1dca8d6--- /dev/null+++ b/studio/frontend/tests/embedding-model-picker.test.ts@@ -0,0 +1,372 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import { fileURLToPath } from "node:url";++import { en } from "../src/i18n/locales/en.ts";++function read(path: string): string {+ return readFileSync(fileURLToPath(new URL(path, import.meta.url)), "utf-8");+}++// These reach the hub and chat barrels and cannot be imported here, so this+// asserts on source, like ~50 sibling tests.+const PICKER = read(+ "../src/features/settings/components/embedding-model-picker.tsx",+);+const SECTION = read(+ "../src/features/settings/components/documents-rag-section.tsx",+);+const API = read("../src/features/settings/api/embedding-model.ts");+const GENERAL_TAB = read("../src/features/settings/tabs/general-tab.tsx");+const DATA_TAB = read("../src/features/settings/tabs/data-tab.tsx");++test("the field says it reaches the whole Hub", () => {+ assert.equal(+ en.settings.general.rag.searchPlaceholder,+ "Search any model on HF",+ );+ assert.match(+ PICKER,+ /placeholder=\{t\("settings.general.rag.searchPlaceholder"\)\}/,+ );+});++test("an empty query lists unsloth, a typed one searches everything", () => {+ // The global top-downloads page holds no unsloth mirrors to float, so an+ // unscoped empty query buries the models this install actually ships with.+ assert.match(PICKER, /ownerScope: debouncedQuery \? "all" : "unsloth"/);+ assert.match(PICKER, /useDebouncedValue\(query\.trim\(\)\)/);+});++test("only the query searches; the saved model never becomes one", () => {+ // The old combobox searched for whatever was in the field, so opening it on a+ // saved model returned that one row and hid every other embedder.+ assert.ok(+ !PICKER.includes("useDebouncedValue(value)"),+ "the controlled value is not the query",+ );+ // It is still reachable as a row, just not as a search term.+ assert.match(PICKER, /rows\.push\(\{ id: selected, sizeBytes: null \}\)/);+});++test("picking applies straight away, with no Save button", () => {+ assert.match(+ SECTION,+ /onSelect=\{\(model\) => void applyEmbeddingModel\(model, false\)\}/,+ );+ assert.ok(+ !SECTION.includes('t("common.save")'),+ "selection is the apply action, as it is for dictation models",+ );+ // "Save anyway" survives: a 409 is still forceable, per model.+ assert.match(SECTION, /applyEmbeddingModel\(forceCandidate, true\)/);+});++test("a model that is not on disk is offered as a real download", () => {+ // The whole point of the change: before this, saving only wrote the setting+ // and the weights arrived invisibly at the first index.+ assert.match(SECTION, /resolveEmbeddingModel\(trimmed, \{/);+ assert.match(SECTION, /setResolution\(resolution\)/);+ // Same manager the Hub cards use, so progress, cancel and transport are shared.+ assert.match(SECTION, /downloadManager\.requestStart\(\{/);+ assert.match(SECTION, /kind: DOWNLOAD_KIND\.MODEL/);+});++test("the resolve runs before the save, not after it", () => {+ // Saving first meant a model with no same-owner GGUF 409'd and the user saw a+ // wall of red text instead of a download.+ const fn = SECTION.slice(+ SECTION.indexOf("const applyEmbeddingModel"),+ SECTION.indexOf("const startDownload"),+ );+ assert.ok(+ fn.indexOf("resolveEmbeddingModel") <+ fn.indexOf("persist(trimmed, resolution"),+ "resolve decides, then the save records what it found",+ );+ // Only the explicit override skips it, and it persists no plan.+ assert.match(+ fn,+ /if \(force\) \{[\s\S]*persist\(trimmed, null, true, reservation\)/,+ );+ const forceBranch = fn.slice(fn.indexOf("if (force) {"), fn.indexOf("let resolution"));+ assert.ok(+ !forceBranch.includes("resolveEmbeddingModel"),+ "the force path must not re-enter the resolver before saving",+ );+});++test("cross-surface save order is claimed before model resolution", () => {+ const fn = SECTION.slice(+ SECTION.indexOf("const applyEmbeddingModel"),+ SECTION.indexOf("const startDownload"),+ );+ assert.ok(+ fn.indexOf("const reservation = beginSave()") <+ fn.indexOf("resolveEmbeddingModel(trimmed"),+ );+ assert.match(fn, /isSaveCurrent\(reservation\)/);+ assert.match(fn, /persist\(trimmed, resolution, false, reservation\)/);+});++test("the repo the resolve picked is what gets stored", () => {+ // A GGUF repo need not follow a naming rule, so the loader has to be told+ // rather than left to re-derive it. The backend rides along: a model with no+ // GGUF runs on safetensors, and llama-server would have nothing to open.+ assert.match(+ SECTION,+ /plan\?\.backend === "llama" \? \(plan\.downloadRepo \?\? null\) : null/,+ );+ assert.match(SECTION, /backend: plan\?\.backend \?\? null/);+ assert.match(API, /gguf_repo: options\?\.ggufRepo \?\? null/);+ assert.match(API, /backend: options\?\.backend \?\? null/);+});++test("a missing model gets a Download button, not a popup", () => {+ // A modal for a one-click action was noise, and voice already had the shape.+ assert.ok(!SECTION.includes("AlertDialog"), "no confirmation modal");+ assert.match(SECTION, /const canDownload = Boolean\(/);+ assert.match(+ SECTION,+ /onClick=\{\(\) => resolution && void startDownload\(resolution\)\}/,+ );+});++test("the action slot offers Download or Unload, not Reset to default", () => {+ assert.ok(+ !SECTION.includes("resetEmbeddingModelSettings"),+ "reset is reachable by picking the default in the list",+ );+ assert.match(SECTION, /settings\.general\.rag\.unload/);+ // Gated on backendLoaded, not loaded, and outside the Download chain: saving a+ // new model does not release the old one, so the control that frees the+ // previous model was unreachable while Download showed.+ assert.match(SECTION, /embeddingModel\?\.backendLoaded \? \(/);+ assert.ok(+ !SECTION.includes("): embeddingModel?.loaded ? ("),+ "Unload is not an alternative to Download",+ );+});++test("the button follows a transfer started anywhere", () => {+ // Keyed off the shared manager, so a download begun from the Hub disables it too.+ assert.match(SECTION, /useDownloadManagerStore\(\(state\) =>/);+ assert.match(SECTION, /jobKeyOf\(/);+ assert.match(SECTION, /const fullSnapshotJobKey =/);+ assert.match(SECTION, /fullSnapshotDownloadState === "running"/);+});++test("download completion refreshes the resolved cache state", () => {+ assert.match(+ SECTION,+ /downloadState !== "complete" &&\s*fullSnapshotDownloadState !== "complete"/,+ );+ assert.match(+ SECTION,+ /Promise\.all\(\[\s*resolveEmbeddingModel\(savedModel,[\s\S]*refreshCachedRepos\(\)/,+ );+});++test("a saved-model change clears every previous model-scoped action", () => {+ const effect = SECTION.slice(+ SECTION.indexOf("const savedModel"),+ SECTION.indexOf("/** Persist the pick"),+ );+ assert.ok(+ effect.indexOf("setResolution(null)") <+ effect.indexOf("resolveEmbeddingModel(savedModel"),+ );+ assert.ok(+ effect.indexOf("setForceCandidate(null)") <+ effect.indexOf("resolveEmbeddingModel(savedModel"),+ );+ assert.ok(+ effect.indexOf("setSaveError(null)") <+ effect.indexOf("resolveEmbeddingModel(savedModel"),+ );+});++test("a new save cannot retain another model's force action", () => {+ const apply = SECTION.slice(+ SECTION.indexOf("const applyEmbeddingModel"),+ SECTION.indexOf("const startDownload"),+ );+ assert.match(apply, /setForceCandidate\(null\);[\s\S]*const trimmed/);+});++test("a rejected save cannot retain its download plan", () => {+ const apply = SECTION.slice(+ SECTION.indexOf("const applyEmbeddingModel"),+ SECTION.indexOf("const startDownload"),+ );+ assert.ok(+ apply.lastIndexOf("setResolution(resolution)") >+ apply.indexOf("await persist(trimmed, resolution"),+ "the accepted persistence result publishes the download plan",+ );+});++test("every download-manager non-start outcome gets feedback", () => {+ // requestStart refuses by returning an outcome rather than throwing, so a+ // non-start is silent unless this caller speaks. Every branch must, and the+ // three do not mean the same thing: "conflict" is resumable from the Hub and+ // "busy" is a sibling transfer already running, so reporting either as+ // "couldn't start the download" sends the user hunting for a fault that the+ // downloads panel is, at that moment, showing them the answer to.+ assert.match(SECTION, /if \(outcome === "started"\)[\s\S]*else \{/);+ assert.match(+ SECTION,+ /outcome === "conflict"[\s\S]*toast\.info\(t\("settings\.general\.rag\.downloadConflict"\)\)/,+ );+ assert.match(+ SECTION,+ /outcome === "busy"[\s\S]*toast\.info\(t\("settings\.general\.rag\.downloadBusy"\)\)/,+ );+ assert.match(+ SECTION,+ /toast\.error\(t\("settings\.general\.rag\.downloadFailed"\)\)/,+ );+});++test("only the embedder's own GGUF is fetched, not every quant", () => {+ assert.match(SECTION, /scopeId: scoped \? EMBEDDING_DOWNLOAD_SCOPE : null/);+ assert.match(+ SECTION,+ /variant: scoped \? scopedVariant\(EMBEDDING_DOWNLOAD_SCOPE\) : null/,+ );+});++test("the current row can be retried and arbitrary relative paths submit", () => {+ assert.match(PICKER, /onSelect\(model\);/);+ assert.ok(!PICKER.includes("if (model !== value.trim())"));+ assert.match(+ PICKER,+ /const typed = query\.trim\(\);\s*if \(typed\) \{\s*pick\(typed\);/,+ );+ assert.ok(!PICKER.includes("isDirectModelReference"));+});++test("a gated-repo token never rides in the URL", () => {+ const start = API.indexOf("export async function resolveEmbeddingModel");+ const fn = API.slice(start, API.indexOf("\n}", start));+ assert.ok(!fn.includes('params.set("hf_token"'), "not a query parameter");+ assert.match(fn, /headers: hubTokenHeader\(options\?\.hfToken\)/);+});++test("on-device rows carry the Hub's green dot", () => {+ assert.match(PICKER, /rounded-full bg-status-success/);+ // The membership test moved off the raw id and onto the resolved repo; see+ // "the on-device dot follows the resolved repo, not the displayed id".+ assert.match(PICKER, /isOnDevice\(cachedModels, item\.id\)/);+ assert.match(PICKER, /cached\.has\(repo\)/);+});++test("General and Data show the same section, not two copies of it", () => {+ assert.ok(SECTION.includes("export function DocumentsRagSection"));+ for (const [name, tab] of [+ ["general", GENERAL_TAB],+ ["data", DATA_TAB],+ ] as const) {+ assert.ok(tab.includes("<DocumentsRagSection />"), `${name} renders it`);+ // A second copy of the load and save logic would let the two tabs disagree.+ assert.ok(+ !tab.includes("loadEmbeddingModelSettings"),+ `${name} has no embedding logic of its own`,+ );+ }+});++const VOICE_TAB = read("../src/features/settings/tabs/voice-tab.tsx");++test("a dictation download is reported once, not twice", () => {+ // Settings drew its own bar and Cancel beside the shared downloads panel,+ // so one transfer showed two identical progress readouts.+ assert.ok(+ !VOICE_TAB.includes("DownloadProgressBar"),+ "no second progress bar",+ );+ assert.ok(+ !VOICE_TAB.includes("sttCancelDownload"),+ "cancelling belongs to the panel",+ );+ // The status line still names the state; only the duplicate readout went.+ assert.match(VOICE_TAB, /\{sttModelStatusText\}/);+ assert.match(VOICE_TAB, /sttDownloading/);+});++test("the rate estimator went with the bar it fed", () => {+ for (const dead of [+ "downloadBytesPerSec",+ "downloadEtaSeconds",+ "computeTransferStats",+ "downloadSamplesRef",+ ]) {+ assert.ok(!VOICE_TAB.includes(dead), `${dead} is unused now`);+ }+});++test("a force save re-resolves even though the model string did not change", () => {+ // Save anyway on the model already saved leaves savedModel identical, so the+ // effect keyed on it never re-runs and nothing restores the plan the apply+ // cleared. The backend still marks an uncached model pending, so the row would+ // sit with no Download while the loader refuses to index.+ assert.match(+ SECTION,+ /if \(await persist\(trimmed, null, true, reservation\)\) \{\s*setResolveNonce\(\(n\) => n \+ 1\);/,+ );+ assert.match(SECTION, /\}, \[savedModel, hfToken, resolveNonce\]\);/);+});++test("the configured default stays reachable when the listing drops it", () => {+ // The empty query is scoped to `unsloth`, so a private, other-owner or local+ // default had no row, and "Reset to default" is gone.+ assert.match(PICKER, /rows\.push\(\{ id: fallback, sizeBytes: null \}\)/);+ assert.match(PICKER, /const fallback = defaultModel\?\.trim\(\)/);+ // A stale memo would pin the row to whatever the default was on first render.+ assert.match(PICKER, /\}, \[results, value, defaultModel\]\)/);+ // And the section still hands the default down for it to be found.+ assert.match(SECTION, /defaultModel=\{embeddingModel\?\.defaultEmbeddingModel\}/);+});++test("backend residency is re-read, not just loaded once on mount", () => {+ // A running job reaching its first encode makes a backend resident with no+ // settings mutation, and the store loads only on mount. No lifecycle event to+ // subscribe to, so this re-reads.+ assert.match(SECTION, /const RESIDENCY_POLL_MS = \d+;/);+ assert.match(SECTION, /window\.setInterval\(refresh, RESIDENCY_POLL_MS\)/);+ // A hidden tab must not poll, and must catch up the moment it is shown.+ assert.match(SECTION, /if \(document\.hidden\) return;/);+ assert.match(SECTION, /addEventListener\("visibilitychange", refresh\)/);+ assert.match(SECTION, /removeEventListener\("visibilitychange", refresh\)/);+ assert.match(SECTION, /window\.clearInterval\(timer\)/);+});++test("the on-device dot follows the resolved repo, not the displayed id", () => {+ // The inventory records what was fetched, not what was picked, so an exact-id+ // lookup left the dot off a fully downloaded model.+ assert.match(PICKER, /export function cachedRepoCandidates\(model: string\): string\[\]/);+ assert.match(PICKER, /`\$\{id\}-GGUF`/);+ assert.match(PICKER, /`sentence-transformers\/\$\{id\}`/);+ assert.match(PICKER, /if \(!id\.includes\("\/"\)\)/);+ assert.match(PICKER, /isOnDevice\(cachedModels, item\.id\)/);+ assert.ok(+ !PICKER.includes("cachedModels?.has(item.id)"),+ "the raw exact-id lookup is gone",+ );+});++test("an unquantized re-upload's GGUF companion counts as on device", () => {+ // The backend strips the quant suffix, so+ // unsloth/embeddinggemma-300m-qat-q8_0-unquantized resolves under+ // unsloth/embeddinggemma-300m-GGUF; checking only <literal>-GGUF left the dot+ // off a fully downloaded companion.+ assert.match(PICKER, /\(\?:-qat\)\?\(\?:-q\\d\+_\\d\+\[a-z\]\*\)\?-unquantized\$/i);+ assert.match(PICKER, /if \(base !== name\) candidates\.push\(`\$\{owner\}\$\{base\}-GGUF`\)/);+ // No lookbehind: this build target ships regex verbatim, so anything Safari 16+ // cannot parse would break the bundle rather than fail a test.+ assert.ok(!PICKER.includes("(?<="), "no lookbehind in shipped regex");+});diff --git a/studio/frontend/tests/embedding-model-store.test.ts b/studio/frontend/tests/embedding-model-store.test.tsindex c044352fd2b..a67a0284001 100644--- a/studio/frontend/tests/embedding-model-store.test.ts+++ b/studio/frontend/tests/embedding-model-store.test.ts@@ -21,6 +21,8 @@ type Settings = {defaultEmbeddingModel: string;defaultEmbeddingGgufRepo: string;isCustom: boolean;+ loaded: boolean;+ backendLoaded: boolean;};function settings(model: string): Settings {@@ -30,6 +32,8 @@ function settings(model: string): Settings {defaultEmbeddingModel: "unsloth/bge-small-en-v1.5",defaultEmbeddingGgufRepo: "",isCustom: model !== "unsloth/bge-small-en-v1.5",+ loaded: false,+ backendLoaded: false,};}@@ -51,6 +55,7 @@ function respondWith(model: string, release?: Promise<void>): void {default_embedding_gguf_repo: "",// biome-ignore lint/style/useNamingConvention: API schemais_custom: model !== "unsloth/bge-small-en-v1.5",+ loaded: false,}),} as unknown as Response;}) as typeof fetch;@@ -180,6 +185,30 @@ test("an older save cannot land on top of a newer one", async () => {);});+test("selection order is reserved before an older preflight finishes", async () => {+ reset();+ const store = useEmbeddingModelStore.getState();+ const olderSelection = store.beginSave();+ const newerSelection = store.beginSave();+ let olderWriteRan = false;++ assert.equal(+ await store.save(async () => {+ olderWriteRan = true;+ return settings("org/older");+ }, olderSelection),+ false,+ );+ assert.equal(olderWriteRan, false, "the superseded preflight cannot write");+ assert.ok(+ await store.save(async () => settings("org/newer"), newerSelection),+ );+ assert.equal(+ useEmbeddingModelStore.getState().settings?.embeddingModel,+ "org/newer",+ );+});+test("a superseded save is reconciled against the backend", async () => {reset();const store = useEmbeddingModelStore.getState();@@ -281,3 +310,26 @@ test("the settle flag does not carry into the next save", async () => {await new Promise((resolve) => setTimeout(resolve, 0));assert.equal(reads, 0, "the earlier overlap was already settled");});++test("unloading does not retire an in-flight selection's reservation", async () => {+ reset();+ const store = useEmbeddingModelStore.getState();+ // The user starts a selection on one surface, switches to the other while its+ // preflight is still running, and unloads. Unloading releases residency and+ // leaves the selection alone, so the selection must still be the current save.+ const selection = store.beginSave();+ await store.applyResidency(async () => settings("org/selected"));++ assert.ok(+ useEmbeddingModelStore.getState().isSaveCurrent(selection),+ "the unload took the selection's place in save order",+ );+ assert.ok(+ await store.save(async () => settings("org/selected"), selection),+ "the selection was dropped without ever persisting",+ );+ assert.equal(+ useEmbeddingModelStore.getState().settings?.embeddingModel,+ "org/selected",+ );+});diff --git a/studio/frontend/tests/voice-download-model-switch.test.ts b/studio/frontend/tests/voice-download-model-switch.test.tsindex 0907abf2bbd..afc18f36d58 100644--- a/studio/frontend/tests/voice-download-model-switch.test.ts+++ b/studio/frontend/tests/voice-download-model-switch.test.ts@@ -2,10 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0// Switching straight from one dictation download to another must restart the-// estimator. The guard once sat AFTER the ref it compares against was assigned,-// so it never fired and the new run was priced over the old one's samples: a-// 5 MB/s download read as 200 MB/s with 20s left. appendSample cannot save it-// either, since a resumed model can start above where the last one stopped.+// estimator, or the new run is priced over the old one's samples: a 5 MB/s+// download reads as 200 MB/s with 20s left. appendSample cannot save it either,+// since a resumed model can start above where the last one stopped.+//+// Voice settings used to keep its own estimator, reset by watching the model+// name. That copy is gone: the shared manager owns the only estimator and gets+// the property structurally, since samples live on the per-job runtime and+// another model is another job. The second test pins what the reset is worth.import assert from "node:assert/strict";import { readFileSync } from "node:fs";@@ -24,19 +28,27 @@ const voiceTabSource = readFileSync("utf8",);-test("the watched model is compared before it is adopted", () => {- const compare = voiceTabSource.indexOf(- "download.model !== watchedDownloadRef.current",+test("each download's samples belong to its own job, not to the tab", () => {+ const pollLoopSource = readFileSync(+ new URL("../src/features/hub/download-manager/poll-loop.ts", import.meta.url),+ "utf8",);- const assign = voiceTabSource.indexOf(- "watchedDownloadRef.current = download.model",- );- assert.ok(compare > 0, "the model-change guard should still exist");- assert.ok(assign > 0, "the watched model should still be recorded");+ // Empty per job, so a second model cannot inherit the first one's samples.assert.ok(- compare < assign,- "comparing after assigning makes the guard unreachable",+ /speedSamples:\s*\[\]/.test(pollLoopSource),+ "each job runtime should start with its own empty sample buffer",+ );+ // And voice settings must not grow a second estimator back.+ const voiceTabSource = readFileSync(+ new URL("../src/features/settings/tabs/voice-tab.tsx", import.meta.url),+ "utf8",);+ for (const gone of ["computeTransferStats", "appendSample", "downloadSamplesRef"]) {+ assert.ok(+ !voiceTabSource.includes(gone),+ `voice-tab should not re-implement the estimator (${gone})`,+ );+ }});// What that guard is worth: the same two downloads, with and without the reset.diff --git a/tests/studio/test_settings_compact_overflow_contract.py b/tests/studio/test_settings_compact_overflow_contract.pyindex 0465b1f54de..53d9d4e0bb5 100644--- a/tests/studio/test_settings_compact_overflow_contract.py+++ b/tests/studio/test_settings_compact_overflow_contract.py@@ -52,12 +52,14 @@ def test_embedding_model_controls_stack_on_the_narrowest_viewports():# pinning the filename turned that move into a red build even though both responsive# classes came along untouched. Follow whichever settings surface renders the picker.# Dropping the classes still fails; relocating them no longer does.+ # The combobox became EmbeddingModelPicker; follow the component, since the+ # contract is that the control stacks and fills the row under 360px.owners = [pathfor path in sorted(SETTINGS.rglob("*.tsx"))- if "<EmbeddingModelCombobox" in path.read_text(encoding = "utf-8")+ if "<EmbeddingModelPicker" in path.read_text(encoding = "utf-8")]- assert owners, "no settings surface renders EmbeddingModelCombobox"+ assert owners, "no settings surface renders EmbeddingModelPicker"missing = [str(path.relative_to(REPO))@@ -65,7 +67,9 @@ def test_embedding_model_controls_stack_on_the_narrowest_viewports():if not ('className="max-[360px]:flex-col max-[360px]:items-stretch max-[360px]:gap-3"'in (source := path.read_text(encoding = "utf-8"))- and 'className="w-[220px] max-[360px]:min-w-0 max-[360px]:flex-1"' in source+ # The fixed width has to give way at the breakpoint: flex-1 for the+ # combobox, a full row for the picker trigger.+ and ("max-[360px]:w-full" in source or "max-[360px]:flex-1" in source))]assert missing == []