Skip to content

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

Studio: keep the RAG embedder off the GPU unless asked (#8654)

Daniel Han34a119764806
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.py
index 76bfabfee1b..cd713c1c047 100644
--- a/studio/backend/core/rag/config.py
+++ b/studio/backend/core/rag/config.py
@@ -76,6 +76,62 @@ OCR_MAX_TOKENS = int(os.environ.get("RAG_OCR_MAX_TOKENS", "2048"))
# the vectors, so the index must be rebuilt.
EMBED_BACKEND = os.environ.get("RAG_EMBED_BACKEND", "auto")
+# ``documents.embedding_model`` records the embedder that produced a document's
+# vectors, not just the configured model name. The name alone is not the embedding
+# space: llama-server ignores it and embeds through the GGUF companion, which pools
+# its own way, so one name can mean two spaces on the same machine.
+EMBEDDING_IDENTITY_TAGS = ("sentence-transformers", "llama-server")
+
+
+def _escape_identity_segment(value: str) -> str:
+ """Colons separate the segments, and a model can be a local path that contains one
+ (``C:\\models\\bge``), which would otherwise read back as ``C``. A repo id contains
+ neither character, so the identity of a normal model is unchanged."""
+ return value.replace("%", "%25").replace(":", "%3A")
+
+
+def _unescape_identity_segment(value: str) -> str:
+ return value.replace("%3A", ":").replace("%25", "%")
+
+
+def embedding_identity(
+ backend: str,
+ model: str,
+ *,
+ gguf_repo: str | None = None,
+) -> str:
+ """Tagged identity for ``documents.embedding_model``.
+
+ The configured model comes first so a row written before identities carried a tag
+ still compares equal on it. llama-server appends the GGUF repo it actually embeds
+ through, which is the part that can differ from the model's ST form."""
+ model = _escape_identity_segment(model)
+ if gguf_repo is None:
+ return f"{backend}:{model}"
+ return f"{backend}:{model}:{_escape_identity_segment(gguf_repo)}"
+
+
+def embedding_identity_model(identity: str | None) -> str | None:
+ """The configured model inside a tagged identity, or None when untagged."""
+ for tag in EMBEDDING_IDENTITY_TAGS:
+ if identity and identity.startswith(f"{tag}:"):
+ return _unescape_identity_segment(identity[len(tag) + 1 :].split(":", 1)[0])
+ return None
+
+
+def embedding_identity_matches(stored: str | None, current: str) -> bool:
+ """Whether ``stored``'s vectors can answer a query embedded under ``current``.
+
+ NULL is still assumed current. An untagged row predates the tag and we cannot know
+ which backend wrote it, so it matches on the model name alone, exactly as it did
+ before: dropping those would empty dense search over every corpus indexed so far.
+ They are reported instead (``store.count_untagged_documents``)."""
+ if stored is None:
+ return True
+ if embedding_identity_model(stored) is not None:
+ return stored == current
+ return stored == (embedding_identity_model(current) or current)
+
def effective_embedding_model() -> str:
"""The embedding model actually in use: the persisted Settings override when
@@ -125,7 +181,44 @@ def effective_gguf_repo() -> str:
# tiny model) and exact vs fp32, for ~30MB more on disk.
EMBED_GGUF_REPO = os.environ.get("RAG_EMBED_GGUF_REPO", "unsloth/bge-small-en-v1.5-GGUF")
EMBED_GGUF_VARIANT = os.environ.get("RAG_EMBED_GGUF_VARIANT", "F16")
+# Read by BOTH backends, and "auto" means something different to each, because the
+# cost of a GPU is different. llama-server offloads inside its own subprocess, so
+# "auto" there means GPU when there is room. sentence-transformers loads inside the
+# backend process, where the first CUDA allocation pins a primary context for the life
+# of the process (712 MiB on a B200, against 74 MiB of weights), so "auto" there means
+# CPU. Set "gpu" to offload either one; "cpu" keeps both off the GPU.
EMBED_DEVICE = os.environ.get("RAG_EMBED_DEVICE", "auto") # "auto" | "gpu" | "cpu"
+
+
+def embed_device_preference() -> str:
+ """``EMBED_DEVICE`` normalized to exactly ``gpu``, ``cpu`` or ``auto``.
+
+ One reader for both backends, because they used to disagree about the same
+ string: the llama path compared a bare ``.lower()``, so ``" gpu "`` fell through
+ to auto, and an Intel user writing the accelerator's own name (``xpu``) got CPU
+ from a setting that named their device. Anything that is not recognizably a
+ request for CPU or for an accelerator is ``auto``, so a typo degrades to each
+ backend's default rather than to silence.
+ """
+ value = (EMBED_DEVICE or "").strip().lower()
+ if value in ("gpu", "cuda", "rocm", "hip", "xpu", "mps", "metal"):
+ return "gpu"
+ if value == "cpu":
+ return "cpu"
+ return "auto"
+
+
+def embed_device_requires_gpu() -> bool:
+ """True when a failed GPU start must raise instead of retrying on CPU.
+
+ Only the literal documented value is that hard a request, which is what it has
+ always meant. The spellings we newly began honoring above -- padding, or the
+ accelerator's own name -- used to fall through to ``auto``, and ``auto`` falls
+ back, so reading them as fatal would take RAG away from hosts it worked on. They
+ still opt into the GPU; they just do not insist on it."""
+ return (EMBED_DEVICE or "").lower() == "gpu"
+
+
EMBED_HOST = os.environ.get("RAG_EMBED_HOST", "127.0.0.1")
EMBED_PORT = int(os.environ.get("RAG_EMBED_PORT", "0")) # 0 = auto-pick a free port
EMBED_BATCH = int(os.environ.get("RAG_EMBED_BATCH", "64"))
diff --git a/studio/backend/core/rag/embed_llama_server.py b/studio/backend/core/rag/embed_llama_server.py
index 63c92a9c281..dc06ac15472 100644
--- a/studio/backend/core/rag/embed_llama_server.py
+++ b/studio/backend/core/rag/embed_llama_server.py
@@ -271,9 +271,12 @@ class LlamaServerBackend:
def _use_gpu(self) -> bool:
"""``RAG_EMBED_DEVICE``: ``gpu``/``cpu`` force it; ``auto`` uses a GPU when
- present. A sticky CPU fallback (after an auto GPU start fails) wins."""
- dev = config.EMBED_DEVICE.lower()
- if dev == "gpu":
+ present. A sticky CPU fallback (after a GPU start we were allowed to give up
+ on) wins, so the reaper's next restart does not pay the startup timeout again
+ on a path already known not to start. Only the literal ``gpu`` outranks it,
+ and that spelling never sets the flag."""
+ dev = config.embed_device_preference()
+ if dev == "gpu" and not self._force_cpu:
return True
if dev == "cpu" or self._force_cpu:
return False
@@ -418,14 +421,13 @@ class LlamaServerBackend:
pass
def _spawn(self) -> None:
- """Start the embed server (caller holds the lock). On ``auto``, a failed
- GPU start falls back to CPU once; explicit ``gpu``/``cpu`` do not."""
+ """Start the embed server (caller holds the lock). A failed GPU start falls
+ back to CPU once, unless ``RAG_EMBED_DEVICE`` is the literal ``gpu``."""
use_gpu = self._use_gpu()
try:
self._spawn_once(use_gpu)
except RuntimeError:
- auto = config.EMBED_DEVICE.lower() not in ("gpu", "cpu")
- if use_gpu and auto:
+ 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)
diff --git a/studio/backend/core/rag/embeddings.py b/studio/backend/core/rag/embeddings.py
index 10fd9301b6a..25a65d79eaf 100644
--- a/studio/backend/core/rag/embeddings.py
+++ b/studio/backend/core/rag/embeddings.py
@@ -5,6 +5,10 @@
``config.EMBED_BACKEND`` (``auto`` picks by hardware): ``sentence-transformers``
(torch) or ``llama-server`` (GGUF, no torch).
+Either way the embedder stays off the GPU unless asked: this one runs in the backend
+process, where a CUDA context outlives every unload, and the other runs in a child.
+See ``_device``.
+
Backends produce different vectors, so switching requires rebuilding the index. We
degrade to llama.cpp rather than crash when ST breaks on a machine: an init-time
probe falls back before any vector is produced (so spaces can't mix), and a
@@ -43,6 +47,11 @@ _lock = threading.Lock()
_compute_lock = threading.Lock()
_model = None
_name: str | None = None
+# The backend that served this thread's most recent encode. The process embedder can
+# swap between an encode returning and the caller asking what produced the vectors,
+# and the answer has to be the backend that was actually used. See
+# ``encode_with_identity``.
+_served_by = threading.local()
# Unsloth device -> torch device string. Apple has no torch device -> CPU.
@@ -50,6 +59,31 @@ _TORCH_DEVICE = {DeviceType.CUDA: "cuda", DeviceType.XPU: "xpu"}
def _device() -> str:
+ """Torch device for the in-process embedder. CPU unless asked otherwise.
+
+ Defaulting a GPU machine to CPU is deliberate. This embedder runs inside the
+ backend process, and the first CUDA allocation there creates a primary context
+ that is never returned while the process lives: measured at 712 MiB on a B200,
+ against 74 MiB for bge-small's own weights. So ingesting one document used to
+ cost most of a gigabyte of VRAM for the rest of the session, on a machine where
+ the user had loaded no model at all, and no amount of unloading gets it back --
+ ``del model; torch.cuda.empty_cache()`` returns none of it.
+
+ The trade is real but small at the sizes this runs at. bge-small is a 33M parameter
+ BERT: on the same host, one 128-token chunk takes 18.7ms on CPU against 5.2ms on
+ CUDA, which is noise next to parsing and chunking the document it came from. Bulk
+ indexing is where it shows, at batch 64: 445 chunks/s on CPU against 3174/s on CUDA.
+ ``RAG_EMBED_DEVICE=gpu`` opts back in for a large corpus.
+
+ This reads the same setting as the llama-server backend but resolves ``auto``
+ differently, which is intended: that backend offloads inside its own subprocess,
+ where the context dies with the child and costs the backend nothing.
+ """
+ if config.embed_device_preference() != "gpu":
+ return "cpu"
+ # Still a table lookup, so asking for a GPU on a host without one, or on Apple
+ # where this backend has no torch device, lands on CPU rather than on a device
+ # string torch cannot open.
return _TORCH_DEVICE.get(get_device(), "cpu")
@@ -375,8 +409,8 @@ def _st_accepts_local_files_only(st_cls) -> bool:
def _get(model_name: str | None = None):
- """Cached SentenceTransformer, (re)loading on a name change. Loaded in fp16
- for a ~1.5x speedup at negligible accuracy loss."""
+ """Cached SentenceTransformer, (re)loading on a name change. Loaded in fp16 on an
+ accelerator for a ~1.5x speedup at negligible accuracy loss, fp32 on CPU."""
global _model, _name
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
@@ -386,7 +420,6 @@ def _get(model_name: str | None = None):
if _model is None or _name != name:
# Probe before loading sentence-transformers on the selected device.
device = _load_device()
- degraded_to_cpu = device == "cpu" and _device() != "cpu"
_install_torchao_stub_once()
from sentence_transformers import SentenceTransformer
from utils.hf_cache_settings import active_hf_hub_cache
@@ -396,7 +429,13 @@ def _get(model_name: str | None = None):
st_kwargs = dict(
device = device,
cache_folder = active_hf_hub_cache(),
- model_kwargs = dtype_kwargs("float32" if degraded_to_cpu else "float16"),
+ # Keyed on the device we actually load on, not on whether we degraded
+ # onto it. fp16 BERT on CPU is slow where it works at all, and several
+ # ops raise "not implemented for 'Half'" -- which _SentenceTransformers
+ # Backend.encode() catches and answers by swapping the whole process to
+ # llama-server, so getting this wrong fails as a silent backend change
+ # rather than as an error.
+ model_kwargs = dtype_kwargs("float32" if device == "cpu" else "float16"),
)
load_target = name
if local_only:
@@ -506,6 +545,7 @@ class _SentenceTransformersBackend:
fallback = _switch_to_llama_fallback(st_err)
if fallback is None:
raise
+ _served_by.backend = fallback
return fallback.encode(texts, model_name = model_name, normalize = normalize)
def token_counter(self, *, model_name = None):
@@ -668,6 +708,55 @@ def active_backend_is_llama() -> bool:
return False
+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)
+ )
+ return config.embedding_identity("sentence-transformers", name)
+
+
+def embedding_identity(model_name: str | None = None) -> str:
+ """Identity of the vectors this process produces right now.
+
+ Recorded on every document, because the model name alone does not name the
+ embedding space: llama-server ignores the name and embeds through the GGUF
+ companion with its own pooling, and this process can switch to it at runtime. Two
+ spaces under one label is an index that answers with the wrong documents and says
+ nothing about it."""
+ return _identity(active_backend_is_llama(), model_name or config.effective_embedding_model())
+
+
+def _is_llama_backend(backend) -> bool:
+ """Whether a concrete backend object embeds through llama-server."""
+ try:
+ from .embed_llama_server import LlamaServerBackend
+ except Exception: # noqa: BLE001 - llama plumbing import must never block
+ return False
+ return isinstance(backend, LlamaServerBackend)
+
+
+def encode_with_identity(
+ texts: list[str],
+ *,
+ model_name: str | None = None,
+ normalize: bool = True,
+):
+ """``(vectors, identity)``, the identity taken from the encode that produced them.
+
+ Not from the process embedder read afterwards: a concurrent ST encode failure
+ swaps that between the two, so the vectors would be labelled with a space they
+ were never in, and a query then searches (or a document is stored against) the
+ wrong half of the index."""
+ _served_by.backend = None
+ vectors = encode(texts, model_name = model_name, normalize = normalize)
+ served = getattr(_served_by, "backend", None)
+ name = model_name or config.effective_embedding_model()
+ if served is None: # a stubbed encode never reached a backend
+ return vectors, embedding_identity(name)
+ return vectors, _identity(_is_llama_backend(served), name)
+
+
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)
@@ -680,7 +769,9 @@ def encode(
normalize: bool = True,
):
"""Embed texts into an (N, dim) float32 numpy array."""
- return _get_backend().encode(texts, model_name = model_name, normalize = normalize)
+ backend = _get_backend()
+ _served_by.backend = backend
+ return backend.encode(texts, model_name = model_name, normalize = normalize)
def dim(model_name: str | None = None) -> int:
diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.py
index 5c2a11f00fa..d34cadacbd1 100644
--- a/studio/backend/core/rag/ingestion.py
+++ b/studio/backend/core/rag/ingestion.py
@@ -109,14 +109,35 @@ def _abort_if_document_deleted(conn, job_id: str, document_id: str) -> bool:
return True
-def _embed_all(texts: list[str], model_name: str | None):
- """Embed texts in batches into a flat vector list."""
+def _embed_pass(texts: list[str], model_name: str | None):
+ """One batched pass. Returns ``(vectors, identity, changed)``, ``changed`` when the
+ embedder swapped part way and the vectors therefore span two spaces."""
vectors: list = []
+ identity: str | None = None
+ changed = False
for i in range(0, len(texts), _EMBED_BATCH):
batch = texts[i : i + _EMBED_BATCH]
- out = embeddings.encode(batch, model_name = model_name, normalize = True)
+ out, batch_identity = embeddings.encode_with_identity(
+ batch, model_name = model_name, normalize = True
+ )
+ changed = changed or (identity is not None and batch_identity != identity)
+ identity = batch_identity
vectors.extend(out)
- return vectors
+ return vectors, identity or embeddings.embedding_identity(model_name), changed
+
+
+def _embed_all(texts: list[str], model_name: str | None):
+ """Embed texts in batches. Returns ``(vectors, identity)`` of the embedder that
+ produced them. An ST encode failure swaps the process to llama-server, and a swap
+ between batches would leave one document holding vectors from two spaces, so the
+ document restarts under the backend that took over. That swap is one-way, so the
+ second pass is uniform."""
+ for _ in range(2):
+ vectors, identity, changed = _embed_pass(texts, model_name)
+ if not changed:
+ return vectors, identity
+ logger.warning("embedder changed mid-document; re-embedding under the new one")
+ return vectors, identity
def _ocr_scanned_pages(
@@ -272,7 +293,10 @@ def _run(
return
_progress(conn, job_id, "embedding", 0.5)
- vectors = _embed_all([c.text for c in chunks], model_name)
+ # An ST encode failure swaps the process to llama-server, so the embedder that
+ # produced these vectors is only known once they exist.
+ vectors, identity = _embed_all([c.text for c in chunks], model_name)
+ store.set_document_embedding_model(conn, document_id, identity)
# Locate each chunk's highlight regions (non-PDFs/failures yield none).
regions = None
@@ -347,6 +371,15 @@ def start_ingestion(
sha = _sha256_file(stored_path)
conn = rag_db.get_connection()
try:
+ # Named before the transaction opens, because naming the embedder on a fresh
+ # process is slow work that touches no database: it searches for the
+ # llama-server binary, runs nvidia-smi under a ten second timeout, and on a
+ # host without it imports torch. Under BEGIN IMMEDIATE that is a RESERVED
+ # lock held for all of it, and connections wait only busy_timeout (5s) for
+ # one, so a concurrent ingest or job heartbeat fails with "database is
+ # locked" instead of queueing.
+ effective_model = model_name or config.effective_embedding_model()
+ effective_identity = embeddings.embedding_identity(effective_model)
# Serialize admission with durable scope retirement across backend
# processes. The job lease is committed in the same transaction as the
# document, so cleanup never observes an unowned in-flight document.
@@ -356,7 +389,6 @@ def start_ingestion(
).fetchone():
conn.rollback()
raise RuntimeError("Owning scope is being deleted")
- effective_model = model_name or config.effective_embedding_model()
# (old_document_id, old_stored_path) replaced by this upload; deleted by
# the worker only after the replacement completes, so a failed re-index
# never destroys the still-searchable original.
@@ -374,8 +406,9 @@ def start_ingestion(
stale_model = (
doc is not None
and doc.get("status") == "completed"
- and doc.get("embedding_model") is not None
- and doc.get("embedding_model") != effective_model
+ and not config.embedding_identity_matches(
+ doc.get("embedding_model"), effective_identity
+ )
)
if empty_completed or stale_model:
# A prior ingest of identical bytes yielded zero chunks (e.g. a scanned
@@ -408,7 +441,7 @@ def start_ingestion(
project_id = project_id,
status = "pending",
stored_path = stored_path,
- embedding_model = effective_model,
+ embedding_model = effective_identity,
linked_folder_id = linked_folder_id,
linked_relative_path = linked_relative_path,
commit = False,
diff --git a/studio/backend/core/rag/retrieval.py b/studio/backend/core/rag/retrieval.py
index 6f933e089e0..920c717aa63 100644
--- a/studio/backend/core/rag/retrieval.py
+++ b/studio/backend/core/rag/retrieval.py
@@ -6,11 +6,14 @@ Fusion. ``dense_score`` is carried so callers can apply a similarity floor."""
from __future__ import annotations
+import logging
import sqlite3
from dataclasses import dataclass
from . import config, embeddings, store
+logger = logging.getLogger(__name__)
+
@dataclass
class Hit:
@@ -40,13 +43,42 @@ def retrieve_dense(
) -> list[Hit]:
k = k or config.TOP_K_DENSE
effective = model_name or config.effective_embedding_model()
- vec = embeddings.encode([query], model_name = effective, normalize = True)[0]
+ # The identity comes from the encode, so it names the backend that actually served
+ # this query even if a concurrent ST failure swapped the process meanwhile.
+ vectors, identity = embeddings.encode_with_identity(
+ [query], model_name = effective, normalize = True
+ )
+ vec = vectors[0]
+ _warn_once_on_untagged(conn)
return [
Hit(cid, s, dense_score = s)
- for cid, s in store.search_dense(conn, scope, vec, k, embedding_model = effective)
+ for cid, s in store.search_dense(conn, scope, vec, k, embedding_model = identity)
]
+_untagged_warned = False
+
+
+def _warn_once_on_untagged(conn: sqlite3.Connection) -> None:
+ """Say once that some documents predate embedder identities, so their vectors are
+ served as if current. We cannot tell which backend wrote them, and re-embedding a
+ corpus unasked is not obviously kinder than leaving it, so we report instead."""
+ global _untagged_warned
+ if _untagged_warned:
+ return
+ _untagged_warned = True
+ try:
+ stale = store.count_untagged_documents(conn)
+ except Exception: # noqa: BLE001 - a diagnostic must never break retrieval
+ return
+ if stale:
+ logger.warning(
+ "%d document(s) were indexed before the embedder was recorded; they are "
+ "searched as if current. Re-upload them if dense results look wrong.",
+ stale,
+ )
+
+
def _rrf(rankings: list[list[Hit]], rrf_k: int, top_k: int) -> list[Hit]:
fused: dict[str, float] = {}
best: dict[str, Hit] = {}
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.py
index ef49f80fade..60cc5f389ba 100644
--- a/studio/backend/core/rag/store.py
+++ b/studio/backend/core/rag/store.py
@@ -20,6 +20,8 @@ from datetime import datetime, timezone
from storage import rag_db
+from . import config
+
def kb_scope(kb_id: str) -> str:
return f"kb_{kb_id}"
@@ -171,6 +173,17 @@ def set_document_status(
conn.commit()
+def set_document_embedding_model(
+ conn: sqlite3.Connection, document_id: str, embedding_model: str
+) -> None:
+ """Record which embedder actually produced this document's vectors. Written after
+ the encode, because the process can swap backends part way through a job."""
+ conn.execute(
+ "UPDATE documents SET embedding_model=? WHERE id=?", (embedding_model, document_id)
+ )
+ conn.commit()
+
+
def list_documents(conn: sqlite3.Connection, scope: str) -> list[dict]:
rows = conn.execute(
"SELECT id, scope, kb_id, thread_id, project_id, filename, sha256, status, error, "
@@ -377,9 +390,12 @@ def search_dense(
"""Cosine KNN over vec0 for one scope or several. Returns
[(chunk_id, 1 - distance)]. vec0 KNN constrains its partition key by
equality, so multi-scope runs one query per scope and merges by score.
- ``embedding_model`` drops hits from documents indexed under a different
- (same-width) model, whose vectors live in another space; NULL-model legacy
- documents are assumed current, matching the ingestion dedupe rule."""
+ ``embedding_model`` is the querying embedder's identity (backend plus model, see
+ ``embeddings.embedding_identity``); it drops hits from documents indexed by a
+ different embedder of the same width, whose vectors live in another space. Rows
+ written before identities carried a backend match on the model name alone, and
+ NULL-model legacy documents are assumed current, matching the ingestion dedupe
+ rule."""
if not rag_db.vec_table_exists(conn):
return []
dim = rag_db.vec_table_dim(conn)
@@ -387,24 +403,79 @@ def search_dense(
# Embedding model switched widths and nothing re-indexed yet; the stale
# table cannot answer new-model queries (vec0 errors on the MATCH).
return []
- # Over-fetch when filtering so stale-model hits don't starve the top-k.
- fetch = max(k * 3, k + 10)
- out: list[tuple[str, float]] = []
- for s in _scopes(scope):
- if conn.execute(
- "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?", (s,)
- ).fetchone():
- continue
- rows = conn.execute(
- "SELECT chunk_id, distance FROM chunks_vec "
- "WHERE scope=? AND embedding MATCH ? ORDER BY distance LIMIT ?",
- (s, _f32(vector), fetch),
- ).fetchall()
- out.extend((r["chunk_id"], 1.0 - r["distance"]) for r in rows)
- if out:
- ids = [cid for cid, _ in out]
- placeholders = ",".join("?" * len(ids))
- valid = {
+ # The pre-tag spelling of the same request, kept acceptable so an existing index
+ # keeps answering after an upgrade.
+ untagged = config.embedding_identity_model(embedding_model) or embedding_model
+ # dict.fromkeys keeps the caller's order and collapses a scope named twice, which
+ # is now load-bearing: widening carries per-scope state, and a repeat would both
+ # multiply that scope's fetch twice per round and emit its hits twice into the merge.
+ scopes = list(
+ dict.fromkeys(
+ s
+ for s in _scopes(scope)
+ if not conn.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?", (s,)
+ ).fetchone()
+ )
+ )
+ # Over-fetch when filtering so stale-model hits don't starve the top-k. Their
+ # distances come from another space, so they can fill every fetched slot while
+ # compatible chunks sit further down the KNN list: widen until k of them survive
+ # the filter or the scope has nothing left to give.
+ #
+ # Per scope, not across the merge. vec0 constrains its partition key by equality,
+ # so each scope is its own KNN list with its own stale prefix; a project scope
+ # buried under another embedder's vectors would otherwise stop widening the
+ # moment the thread scope handed over k weak hits, and the merge would then rank
+ # a stronger project chunk it never fetched.
+ kept: dict[str, list[tuple[str, float]]] = {}
+ fetches = dict.fromkeys(scopes, max(k * 3, k + 10))
+ pending = list(scopes)
+ while pending:
+ widen: list[str] = []
+ for s in pending:
+ fetch = fetches[s]
+ rows = conn.execute(
+ "SELECT chunk_id, distance FROM chunks_vec "
+ "WHERE scope=? AND embedding MATCH ? ORDER BY distance LIMIT ?",
+ (s, _f32(vector), fetch),
+ ).fetchall()
+ kept[s] = _drop_incompatible(
+ conn,
+ [(r["chunk_id"], 1.0 - r["distance"]) for r in rows],
+ embedding_model,
+ untagged,
+ )
+ if len(kept[s]) < k and len(rows) >= fetch and fetch < _MAX_DENSE_FETCH:
+ fetches[s] = min(fetch * 4, _MAX_DENSE_FETCH)
+ widen.append(s)
+ pending = widen
+ out = [hit for s in scopes for hit in kept[s]]
+ out.sort(key = lambda t: t[1], reverse = True)
+ return out[:k]
+
+
+# Widening is bounded: past this many nearest neighbours per scope the scope is
+# effectively another embedder's, and a re-upload is the answer, not a longer scan.
+_MAX_DENSE_FETCH = 4096
+# One id per bound parameter, kept under the oldest SQLITE_MAX_VARIABLE_NUMBER.
+_ID_BATCH = 900
+
+
+def _drop_incompatible(
+ conn: sqlite3.Connection,
+ candidates: list[tuple[str, float]],
+ embedding_model: str | None,
+ untagged: str | None,
+) -> list[tuple[str, float]]:
+ """Keep the KNN candidates whose document is still live and whose vectors this
+ query can be compared against."""
+ valid: set[str] = set()
+ ids = [cid for cid, _ in candidates]
+ for start in range(0, len(ids), _ID_BATCH):
+ batch = ids[start : start + _ID_BATCH]
+ placeholders = ",".join("?" * len(batch))
+ valid.update(
r["id"]
for r in conn.execute(
f"SELECT c.id FROM chunks c JOIN documents d ON d.id=c.document_id "
@@ -412,13 +483,26 @@ def search_dense(
f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
f"AND (d.linked_folder_id IS NULL OR EXISTS "
f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id)) "
- f"AND (? IS NULL OR d.embedding_model IS NULL OR d.embedding_model=?)",
- (*ids, embedding_model, embedding_model),
+ f"AND (? IS NULL OR d.embedding_model IS NULL OR d.embedding_model=? "
+ f"OR d.embedding_model=?)",
+ (*batch, embedding_model, embedding_model, untagged),
).fetchall()
- }
- out = [t for t in out if t[0] in valid]
- out.sort(key = lambda t: t[1], reverse = True)
- return out[:k]
+ )
+ return [t for t in candidates if t[0] in valid]
+
+
+def count_untagged_documents(conn: sqlite3.Connection) -> int:
+ """Documents whose ``embedding_model`` predates backend tagging.
+
+ Either backend could have written them, because the llama-server fallback never
+ recorded that it had taken over, and nothing in the row says which pooling the
+ vectors came from. We keep serving them rather than drop a corpus or re-embed one
+ behind the user's back, so this exists to say how many are in that state."""
+ tags = " ".join(f"AND embedding_model NOT LIKE '{t}:%'" for t in config.EMBEDDING_IDENTITY_TAGS)
+ row = conn.execute(
+ f"SELECT COUNT(*) AS n FROM documents WHERE embedding_model IS NOT NULL {tags}"
+ ).fetchone()
+ return int(row["n"]) if row else 0
def chunks_by_id(conn: sqlite3.Connection, ids) -> dict:
diff --git a/studio/backend/core/rag/web_rank.py b/studio/backend/core/rag/web_rank.py
index aac3bdedbff..3fd1bf97e99 100644
--- a/studio/backend/core/rag/web_rank.py
+++ b/studio/backend/core/rag/web_rank.py
@@ -95,7 +95,11 @@ def retrieve_web_chunks(
)
if not chunks:
continue
- vectors = embeddings.encode(
+ # The identity has to come from the encode that produced these vectors: a
+ # concurrent ST failure swaps the process embedder, and reading it after
+ # the fact would label this page with a space its vectors were never in,
+ # which the hybrid query below then searches instead of filtering out.
+ vectors, identity = embeddings.encode_with_identity(
[chunk.text for chunk in chunks], model_name = model, normalize = True
)
doc_id = store.create_document(
@@ -104,7 +108,7 @@ def retrieve_web_chunks(
filename = source,
sha256 = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest(),
status = "ready",
- embedding_model = model,
+ embedding_model = identity,
)
doc_ids.append(doc_id)
store.add_chunks(conn, scope, doc_id, chunks, vectors)
diff --git a/studio/backend/tests/test_rag_embed_llama_server.py b/studio/backend/tests/test_rag_embed_llama_server.py
index cf9fd4a07f4..cc0466ca520 100644
--- a/studio/backend/tests/test_rag_embed_llama_server.py
+++ b/studio/backend/tests/test_rag_embed_llama_server.py
@@ -571,3 +571,112 @@ class TestTheEmbeddingLoaderChangesAreMacOsOnly:
)
mod.LlamaServerBackend()._build_env(str(wrapper), use_gpu = True)
assert seen["dir"] == str(wrapper.parent)
+
+
+def test_device_preference_is_shared_between_both_backends(monkeypatch):
+ """One reader, so the two backends cannot disagree about the same string.
+
+ They did: this one compared a bare .lower() with no strip, so " gpu " forced the
+ GPU for sentence-transformers and fell through to auto here, and an Intel user
+ writing their own accelerator's name (xpu) got neither.
+ """
+ for requested, expected in (
+ ("gpu", "gpu"),
+ ("GPU", "gpu"),
+ (" gpu ", "gpu"),
+ ("cuda", "gpu"),
+ ("rocm", "gpu"),
+ ("hip", "gpu"),
+ ("xpu", "gpu"),
+ ("mps", "gpu"),
+ ("metal", "gpu"),
+ ("cpu", "cpu"),
+ ("CPU", "cpu"),
+ (" cpu ", "cpu"),
+ ("auto", "auto"),
+ ("", "auto"),
+ (" ", "auto"),
+ ("banana", "auto"),
+ ):
+ monkeypatch.setattr(config, "EMBED_DEVICE", requested)
+ assert config.embed_device_preference() == expected, requested
+
+
+def test_use_gpu_honours_the_normalized_preference(monkeypatch):
+ """A whitespace-padded or device-named setting reaches this backend too."""
+ backend = LlamaServerBackend()
+ for requested in (" gpu ", "GPU", "xpu", "cuda"):
+ monkeypatch.setattr(config, "EMBED_DEVICE", requested)
+ monkeypatch.setattr(
+ LlamaServerBackend,
+ "_gpu_available",
+ staticmethod(lambda: False),
+ )
+ assert backend._use_gpu() is True, requested
+ for requested in (" cpu ", "CPU"):
+ monkeypatch.setattr(config, "EMBED_DEVICE", requested)
+ monkeypatch.setattr(
+ LlamaServerBackend,
+ "_gpu_available",
+ staticmethod(lambda: True),
+ )
+ assert backend._use_gpu() is False, requested
+
+
+def test_gpu_opt_in_still_falls_back_to_cpu(monkeypatch):
+ """Opting into the GPU by naming it must not turn a failed GPU start fatal.
+
+ These spellings all fell through to ``auto`` before the normalizer read them,
+ so they fell back; making them fatal would stop RAG on hosts it worked on."""
+ for requested in ("cuda", "rocm", "hip", "xpu", "mps", "metal", " gpu ", " CUDA "):
+ monkeypatch.setattr(config, "EMBED_DEVICE", requested)
+ backend = LlamaServerBackend()
+ calls: list[bool] = []
+
+ def fake_spawn_once(use_gpu, _calls = calls):
+ _calls.append(use_gpu)
+ if use_gpu:
+ raise RuntimeError("GPU start failed")
+
+ monkeypatch.setattr(backend, "_spawn_once", fake_spawn_once)
+ backend._spawn()
+ assert calls == [True, False], requested
+ assert backend._force_cpu is True, requested
+
+
+def test_literal_gpu_remains_a_hard_request(monkeypatch):
+ """The documented value keeps forcing the GPU, as it always has."""
+ for requested in ("gpu", "GPU"):
+ monkeypatch.setattr(config, "EMBED_DEVICE", requested)
+ backend = LlamaServerBackend()
+ monkeypatch.setattr(
+ backend, "_spawn_once", lambda use_gpu: (_ for _ in ()).throw(RuntimeError("no cuda"))
+ )
+ with pytest.raises(RuntimeError, match = "no cuda"):
+ backend._spawn()
+ assert backend._force_cpu is False, requested
+
+
+def test_a_soft_gpu_opt_in_keeps_its_own_cpu_fallback(monkeypatch):
+ """The chat reaper kills this server routinely, so respawns are the common case.
+
+ A GPU start we were already allowed to give up on must not be retried on every
+ one of them: each retry pays the full startup timeout before landing back on the
+ CPU it had already fallen back to. Only the literal ``gpu`` outranks the flag,
+ and that spelling never sets it."""
+ for requested in ("cuda", "xpu", " gpu "):
+ monkeypatch.setattr(config, "EMBED_DEVICE", requested)
+ backend = LlamaServerBackend()
+ calls: list[bool] = []
+
+ def fake_spawn_once(use_gpu, _calls = calls):
+ _calls.append(use_gpu)
+ if use_gpu:
+ raise RuntimeError("GPU start failed")
+
+ monkeypatch.setattr(backend, "_spawn_once", fake_spawn_once)
+ backend._spawn()
+ assert calls == [True, False], requested
+ backend._spawn() # the reaper killed it; the respawn stays where we landed
+ assert calls == [True, False, False], requested
+ assert backend._use_gpu() is False, requested
diff --git a/studio/backend/tests/test_rag_embedding_identity.py b/studio/backend/tests/test_rag_embedding_identity.py
new file mode 100644
index 00000000000..3a51e94bc80
--- /dev/null
+++ b/studio/backend/tests/test_rag_embedding_identity.py
@@ -0,0 +1,453 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""``documents.embedding_model`` names the embedder, not just the model.
+
+llama-server ignores the configured model name and embeds through its GGUF companion
+with its own pooling, so the same name can mean two vector spaces on one machine. An
+index written by one backend must not silently answer the other's queries.
+"""
+
+import math
+
+from core.rag import config, embeddings, ingestion, retrieval, store
+from core.rag.chunking import Chunk
+from storage import rag_db
+
+MODEL = "sentence-transformers/all-MiniLM-L6-v2"
+# A model may also be a local path, and on Windows that carries the separator.
+WINDOWS_MODEL = r"C:\models\bge-small-en-v1.5"
+
+_VOCAB = ["alpha", "bravo", "charlie", "delta"]
+
+
+def _write(tmp_path, name, text):
+ path = tmp_path / name
+ path.write_text(text, encoding = "utf-8")
+ return str(path)
+
+
+def _ingest(tmp_path, scope, name, text):
+ document_id, _ = ingestion.start_ingestion(
+ scope = scope,
+ kb_id = None,
+ thread_id = None,
+ filename = name,
+ stored_path = _write(tmp_path, name, text),
+ model_name = MODEL,
+ background = False,
+ )
+ return document_id
+
+
+def test_index_written_by_llama_is_stale_for_a_sentence_transformers_query(
+ rag_home, stub_embeddings, monkeypatch, tmp_path
+):
+ """The scenario a CPU upgrade produces: documents embedded through the GGUF while
+ sentence-transformers was failing, then queried by sentence-transformers once it
+ works. Same model name, different pooling."""
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ scope = store.kb_scope("K1")
+ _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)
+ conn = rag_db.get_connection()
+ try:
+ assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL) == []
+ finally:
+ conn.close()
+
+
+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)
+ scope = store.kb_scope("K2")
+ _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ conn = rag_db.get_connection()
+ try:
+ assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL) == []
+ finally:
+ conn.close()
+
+
+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)
+ scope = store.kb_scope("K3")
+ _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+ conn = rag_db.get_connection()
+ try:
+ assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL)
+ finally:
+ conn.close()
+
+
+def test_re_uploading_after_a_backend_change_reindexes_instead_of_deduping(
+ rag_home, stub_embeddings, monkeypatch, tmp_path
+):
+ """Identical bytes used to dedupe against a row from the other backend, so there
+ was no way to repair the index short of renaming the file."""
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: 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)
+ second = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+ assert second != first
+ conn = rag_db.get_connection()
+ try:
+ assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL)
+ 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 the
+ process to llama-server, so the identity is only correct once vectors exist."""
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)
+ swapped = {"done": False}
+ real_encode = embeddings.encode
+
+ def encode_then_swap(texts, **kwargs):
+ swapped["done"] = True
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ return real_encode(texts, **kwargs)
+
+ monkeypatch.setattr(embeddings, "encode", encode_then_swap)
+ scope = store.kb_scope("K5")
+ document_id = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+ assert swapped["done"]
+ conn = rag_db.get_connection()
+ try:
+ stored = store.get_document(conn, document_id)["embedding_model"]
+ finally:
+ conn.close()
+ assert stored.startswith("llama-server:")
+
+
+def test_legacy_rows_keep_answering_and_are_reported(
+ rag_home, stub_embeddings, monkeypatch, tmp_path
+):
+ """Rows written before the tag existed could be either backend's. Dropping them
+ would empty dense search over every corpus indexed so far, and re-embedding one
+ unasked is not kinder, so they are still served and counted instead."""
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)
+ scope = store.kb_scope("K6")
+ document_id = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+ conn = rag_db.get_connection()
+ try:
+ store.set_document_embedding_model(conn, document_id, MODEL) # pre-tag spelling
+ assert store.count_untagged_documents(conn) == 1
+ assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL)
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: 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)
+ scope = store.kb_scope("K7")
+ document_id = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie")
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("UPDATE documents SET embedding_model=NULL WHERE id=?", (document_id,))
+ conn.commit()
+ assert store.count_untagged_documents(conn) == 0
+ assert retrieval.retrieve_dense(conn, scope, "alpha bravo", k = 5, model_name = MODEL)
+ finally:
+ conn.close()
+
+
+def test_identity_distinguishes_the_backends_and_the_gguf_repo(monkeypatch):
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)
+ as_st = embeddings.embedding_identity(MODEL)
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ as_llama = embeddings.embedding_identity(MODEL)
+ assert as_st != as_llama
+ assert config.embedding_identity_model(as_st) == MODEL
+ assert config.embedding_identity_model(as_llama) == MODEL
+ monkeypatch.setattr(config, "EMBED_GGUF_REPO", "LLukas22/all-MiniLM-L6-v2-GGUF")
+ monkeypatch.setenv("RAG_EMBED_GGUF_REPO", "LLukas22/all-MiniLM-L6-v2-GGUF")
+ assert embeddings.embedding_identity(MODEL) != as_llama
+
+
+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
+ assert config.embedding_identity_matches(MODEL, tagged) is True
+ assert config.embedding_identity_matches("other/model", tagged) is False
+ assert config.embedding_identity_matches(tagged, tagged) is True
+ assert (
+ config.embedding_identity_matches(
+ config.embedding_identity("llama-server", MODEL, gguf_repo = "r"), tagged
+ )
+ is False
+ )
+
+
+def _vector(text):
+ v = [float(text.lower().count(w)) for w in _VOCAB]
+ n = math.sqrt(sum(x * x for x in v)) or 1.0
+ return [x / n for x in v]
+
+
+def _put(conn, scope, document_id, texts, embedding_model):
+ """Index one document's chunks directly, under a chosen identity."""
+ chunks = [
+ Chunk(
+ text = t,
+ token_count = len(t.split()),
+ page_number = None,
+ source_page_index = 0,
+ chunk_index = i,
+ page_char_start = 0,
+ page_char_end = len(t),
+ )
+ for i, t in enumerate(texts)
+ ]
+ store.create_document(
+ conn,
+ scope = scope,
+ filename = f"{document_id}.txt",
+ sha256 = document_id,
+ status = "completed",
+ document_id = document_id,
+ embedding_model = embedding_model,
+ )
+ store.add_chunks(conn, scope, document_id, chunks, [_vector(t) for t in texts])
+
+
+def test_a_local_model_path_survives_the_identity_round_trip():
+ """Colons separate the identity's segments and a Windows path carries one, so the
+ model used to read back as ``C``."""
+ st = config.embedding_identity("sentence-transformers", WINDOWS_MODEL)
+ llama = config.embedding_identity(
+ "llama-server", WINDOWS_MODEL, gguf_repo = WINDOWS_MODEL + "-GGUF"
+ )
+ assert st != llama
+ assert config.embedding_identity_model(st) == WINDOWS_MODEL
+ assert config.embedding_identity_model(llama) == WINDOWS_MODEL
+ # The pre-tag spelling of such a row is the bare path, and it still has to match.
+ assert config.embedding_identity_matches(WINDOWS_MODEL, st) is True
+ assert config.embedding_identity_matches(r"C:\models\other", st) is False
+
+
+def test_a_local_path_model_keeps_answering_its_legacy_rows(rag_conn):
+ """The upgrade must not empty dense search for a corpus indexed under a path."""
+ _put(rag_conn, "kb_w", "d1", ["alpha bravo"], WINDOWS_MODEL)
+ hits = store.search_dense(
+ rag_conn,
+ "kb_w",
+ _vector("alpha bravo"),
+ 5,
+ embedding_model = config.embedding_identity("sentence-transformers", WINDOWS_MODEL),
+ )
+ assert [cid for cid, _ in hits] == ["d1:0"]
+
+
+def test_stale_backend_chunks_do_not_starve_the_current_backend(rag_conn):
+ """What a partial reindex leaves: both backends in one scope. The other one's
+ distances come from another space, so they can fill every fetched candidate slot
+ while the compatible chunks sit further down the KNN list."""
+ stale = config.embedding_identity("llama-server", MODEL, gguf_repo = "r")
+ current = config.embedding_identity("sentence-transformers", MODEL)
+ for i in range(40):
+ _put(rag_conn, "kb_s", f"old{i}", ["alpha"], stale)
+ _put(rag_conn, "kb_s", "new", ["alpha bravo"], current)
+ hits = store.search_dense(rag_conn, "kb_s", _vector("alpha"), 5, embedding_model = current)
+ assert [cid for cid, _ in hits] == ["new:0"]
+
+
+def test_the_identity_comes_from_the_encode_not_from_the_process_after_it(rag_conn, monkeypatch):
+ """A concurrent ST failure swaps the process embedder for the rest of its life. A
+ query sentence-transformers had already encoded must still be answered by the
+ sentence-transformers half of the index, not by the backend that took over."""
+ _put(
+ rag_conn,
+ "kb_r",
+ "d1",
+ ["alpha bravo"],
+ config.embedding_identity("sentence-transformers", MODEL),
+ )
+
+ class _SwapsMidEncode:
+ def encode(
+ self,
+ texts,
+ *,
+ model_name = None,
+ normalize = True,
+ ):
+ vectors = [_vector(t) for t in texts]
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ return vectors
+
+ monkeypatch.setattr(embeddings, "_backend", _SwapsMidEncode())
+ monkeypatch.setattr(
+ embeddings, "_backend_key", (config.EMBED_BACKEND or "auto").strip().lower()
+ )
+ 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"]
+
+
+def test_a_swap_between_batches_re_embeds_the_document(
+ rag_home, stub_embeddings, monkeypatch, tmp_path
+):
+ """A document whose batches straddle the swap would hold vectors from two spaces
+ under one identity, so it restarts under the backend that took over."""
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)
+ monkeypatch.setattr(ingestion, "_EMBED_BATCH", 1)
+ monkeypatch.setattr(config, "CHUNK_TOKENS", 3)
+ monkeypatch.setattr(config, "CHUNK_OVERLAP", 0)
+ passes = {"n": 0}
+ real_pass = ingestion._embed_pass
+
+ def swap_during_the_first_pass(texts, model_name):
+ passes["n"] += 1
+ if passes["n"] == 1:
+ calls = {"n": 0}
+ real_encode = embeddings.encode_with_identity
+
+ def swap_after_one_batch(batch, **kwargs):
+ calls["n"] += 1
+ out = real_encode(batch, **kwargs)
+ if calls["n"] == 1:
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ return out
+
+ monkeypatch.setattr(embeddings, "encode_with_identity", swap_after_one_batch)
+ return real_pass(texts, model_name)
+
+ monkeypatch.setattr(ingestion, "_embed_pass", swap_during_the_first_pass)
+ scope = store.kb_scope("K8")
+ document_id = _ingest(tmp_path, scope, "doc.txt", "alpha bravo charlie delta echo foxtrot")
+ assert passes["n"] == 2
+ conn = rag_db.get_connection()
+ try:
+ assert store.get_document(conn, document_id)["embedding_model"].startswith("llama-server:")
+ finally:
+ conn.close()
+
+
+def test_widening_survives_a_scope_larger_than_one_parameter_batch(rag_conn):
+ """The widened candidate set outgrows a single bound-parameter batch."""
+ stale = config.embedding_identity("llama-server", MODEL, gguf_repo = "r")
+ current = config.embedding_identity("sentence-transformers", MODEL)
+ _put(rag_conn, "kb_b", "old", ["alpha"] * 2000, stale)
+ _put(rag_conn, "kb_b", "new", ["alpha bravo"], current)
+ hits = store.search_dense(rag_conn, "kb_b", _vector("alpha"), 5, embedding_model = current)
+ assert [cid for cid, _ in hits] == ["new:0"]
+
+
+def test_a_saturated_scope_keeps_widening_after_another_scope_is_full(rag_conn):
+ """A project-and-thread search, which is the shape retrieval actually asks for.
+
+ vec0 constrains its partition key by equality, so each scope is its own KNN list
+ with its own stale prefix. A thread scope that hands over k compatible but weak
+ hits must not stop the project scope widening past the other embedder's vectors
+ burying a stronger chunk, or the merge ranks a top-k it never fetched."""
+ stale = config.embedding_identity("llama-server", MODEL, gguf_repo = "r")
+ current = config.embedding_identity("sentence-transformers", MODEL)
+ # The thread scope answers on the first fetch, with the weakest hits in the corpus.
+ _put(rag_conn, "thread_t", "weak", ["alpha bravo charlie delta"] * 5, current)
+ # The project scope's whole first fetch is another embedder's, and the compatible
+ # chunk that outranks every thread hit sits just behind it.
+ _put(rag_conn, "kb_p", "old", ["alpha"] * 20, stale)
+ _put(rag_conn, "kb_p", "new", ["alpha bravo"], current)
+ hits = store.search_dense(
+ rag_conn, ["kb_p", "thread_t"], _vector("alpha"), 5, embedding_model = current
+ )
+ assert hits[0][0] == "new:0"
+
+
+def test_the_web_ranker_labels_a_page_with_the_backend_that_encoded_it(rag_home, monkeypatch):
+ """A concurrent ST failure swaps the process embedder for the rest of its life.
+
+ A page sentence-transformers had already encoded must not be stored as
+ llama-server: the hybrid query right below it then searches those mislabeled
+ vectors instead of filtering them out."""
+ from core.rag import web_rank
+
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: False)
+ monkeypatch.setattr(
+ embeddings, "token_counter", lambda model_name = None: lambda t: max(1, len(t.split()))
+ )
+
+ class _SwapsMidEncode:
+ def encode(
+ self,
+ texts,
+ *,
+ model_name = None,
+ normalize = True,
+ ):
+ vectors = [_vector(t) for t in texts]
+ monkeypatch.setattr(embeddings, "active_backend_is_llama", lambda: True)
+ return vectors
+
+ monkeypatch.setattr(embeddings, "_backend", _SwapsMidEncode())
+ monkeypatch.setattr(
+ embeddings, "_backend_key", (config.EMBED_BACKEND or "auto").strip().lower()
+ )
+
+ labels: list[str | None] = []
+ real_create = store.create_document
+
+ def record(conn, **kwargs):
+ labels.append(kwargs.get("embedding_model"))
+ return real_create(conn, **kwargs)
+
+ monkeypatch.setattr(web_rank.store, "create_document", record)
+ web_rank.retrieve_web_chunks(
+ [{"text": "alpha bravo charlie", "title": "page", "url": "https://a"}],
+ "alpha",
+ top_n = 3,
+ min_score = 0.0,
+ model_name = MODEL,
+ )
+ assert labels == [config.embedding_identity("sentence-transformers", MODEL)]
+
+
+def test_resolving_the_embedder_does_not_hold_the_write_lock(
+ rag_home, stub_embeddings, monkeypatch, tmp_path
+):
+ """Naming the embedder can take seconds on a fresh process: it searches for the
+ llama-server binary, runs nvidia-smi with a ten second timeout, and on a host
+ without it imports torch. Inside the admission transaction that is a RESERVED
+ lock held for all of it, and rag.db opens every connection with a five second
+ busy_timeout, so an unrelated ingest or a job heartbeat fails outright with
+ "database is locked" rather than waiting."""
+ import sqlite3
+
+ from utils.paths import rag_db_path
+
+ probes: list[tuple[bool, str]] = []
+ real_identity = embeddings.embedding_identity
+
+ def probing_identity(model_name = None):
+ other = sqlite3.connect(str(rag_db_path()))
+ try:
+ other.execute("PRAGMA busy_timeout = 100")
+ other.execute("BEGIN IMMEDIATE")
+ other.rollback()
+ probes.append((True, ""))
+ except sqlite3.OperationalError as exc:
+ probes.append((False, str(exc)))
+ finally:
+ other.close()
+ return real_identity(model_name)
+
+ monkeypatch.setattr(embeddings, "embedding_identity", probing_identity)
+ _ingest(tmp_path, store.kb_scope("K1"), "doc.txt", "alpha bravo charlie")
+
+ assert probes, "embedding_identity was never called"
+ assert all(ok for ok, _ in probes), [err for ok, err in probes if not ok]
diff --git a/studio/backend/tests/test_rag_embeddings.py b/studio/backend/tests/test_rag_embeddings.py
index 113c17a3b09..a3a6405886f 100644
--- a/studio/backend/tests/test_rag_embeddings.py
+++ b/studio/backend/tests/test_rag_embeddings.py
@@ -180,6 +180,145 @@ def test_sentence_transformer_load_uses_live_cache(monkeypatch, tmp_path):
assert observed["name"] == "Org/Embedder"
assert observed["cache_folder"] == str(tmp_path / "selected-hub")
+ # fp32, because the load lands on CPU. The dtype follows the device we actually
+ # load on rather than how we got there, so the default CPU placement and a
+ # degraded-onto-CPU load agree.
+ assert list(observed["model_kwargs"].values()) == ["float32"]
+
+
+def test_device_defaults_to_cpu_on_an_accelerator_host(monkeypatch):
+ """A GPU must not be used just because it is there.
+
+ This embedder loads in the backend process, where the first CUDA allocation pins a
+ primary context nothing can hand back, so an idle Studio that indexed one document
+ would carry it for the rest of the session.
+ """
+ monkeypatch.setattr(embeddings.config, "EMBED_DEVICE", "auto")
+ monkeypatch.setattr(
+ embeddings,
+ "get_device",
+ lambda: embeddings.DeviceType.CUDA,
+ )
+ assert embeddings._device() == "cpu"
+
+
+def test_device_opts_in_to_the_accelerator(monkeypatch):
+ """Every spelling of "use the accelerator" opts in, including the device's own name.
+
+ An Intel user reaches for ``xpu`` and a ROCm user for ``rocm`` before either reaches
+ for the generic ``gpu``; matching only ``gpu`` handed both of them CPU from a setting
+ that named their hardware.
+ """
+ monkeypatch.setattr(
+ embeddings,
+ "get_device",
+ lambda: embeddings.DeviceType.CUDA,
+ )
+ for requested in ("gpu", "GPU", " cuda ", "rocm", "hip", "xpu", "mps", "metal"):
+ monkeypatch.setattr(embeddings.config, "EMBED_DEVICE", requested)
+ assert embeddings._device() == "cuda", requested
+
+
+def test_device_opt_in_still_yields_cpu_without_an_accelerator(monkeypatch):
+ monkeypatch.setattr(embeddings.config, "EMBED_DEVICE", "gpu")
+ monkeypatch.setattr(embeddings, "get_device", lambda: embeddings.DeviceType.CPU)
+ assert embeddings._device() == "cpu"
+
+
+def test_device_opt_in_on_apple_stays_on_cpu(monkeypatch):
+ """MLX is not a torch device. Asking for a GPU must not produce a device string
+ torch cannot open, which is why this stays a lookup in _TORCH_DEVICE."""
+ monkeypatch.setattr(embeddings.config, "EMBED_DEVICE", "gpu")
+ monkeypatch.setattr(embeddings, "get_device", lambda: embeddings.DeviceType.MLX)
+ assert embeddings._device() == "cpu"
+
+
+def test_unrecognized_device_setting_falls_back_without_raising(monkeypatch):
+ monkeypatch.setattr(
+ embeddings,
+ "get_device",
+ lambda: embeddings.DeviceType.CUDA,
+ )
+ for requested in ("", " ", "banana", "auto", None):
+ monkeypatch.setattr(embeddings.config, "EMBED_DEVICE", requested)
+ assert embeddings._device() == "cpu", requested
+
+
+def test_cpu_never_loads_float16(monkeypatch, tmp_path):
+ """fp16 on CPU is not merely slow on older torch, it raises.
+
+ torch 2.2 has no CPU Half kernel for LayerNorm, which every BERT runs, so an
+ fp16 CPU load dies with ``"LayerNormKernelImpl" not implemented for 'Half'``.
+ _SentenceTransformersBackend.encode() answers that by swapping the process to
+ llama-server, so the failure would surface as a silent change of embedding space
+ against an index nobody reindexed rather than as an error.
+ """
+ observed = {}
+
+ class FakeSentenceTransformer:
+ def __init__(self, name, **kwargs):
+ observed.update(kwargs)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "sentence_transformers",
+ SimpleNamespace(SentenceTransformer = FakeSentenceTransformer),
+ )
+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)
+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache",
+ lambda: str(tmp_path / "hub"),
+ )
+ # Every way of arriving on CPU: the default, an explicit request, a host with no
+ # accelerator, and a degrade from a probe that condemned the accelerator.
+ for embed_device, hardware, load_device in (
+ ("auto", embeddings.DeviceType.CUDA, None),
+ ("cpu", embeddings.DeviceType.CUDA, None),
+ ("gpu", embeddings.DeviceType.CPU, None),
+ ("gpu", embeddings.DeviceType.CUDA, "cpu"),
+ ):
+ monkeypatch.setattr(embeddings.config, "EMBED_DEVICE", embed_device)
+ monkeypatch.setattr(embeddings, "get_device", lambda hw = hardware: hw)
+ if load_device is not None:
+ monkeypatch.setattr(embeddings, "_load_device", lambda d = load_device: d)
+ embeddings._model = None
+ embeddings._name = None
+ observed.clear()
+
+ embeddings._get("Org/Embedder")
+
+ assert observed["device"] == "cpu", (embed_device, hardware)
+ assert list(observed["model_kwargs"].values()) == ["float32"], (embed_device, hardware)
+ embeddings._model = None
+ embeddings._name = None
+
+
+def test_opted_in_accelerator_loads_float16(monkeypatch, tmp_path):
+ observed = {}
+
+ class FakeSentenceTransformer:
+ def __init__(self, name, **kwargs):
+ observed.update(kwargs)
+
+ monkeypatch.setitem(
+ sys.modules,
+ "sentence_transformers",
+ SimpleNamespace(SentenceTransformer = FakeSentenceTransformer),
+ )
+ monkeypatch.setattr(embeddings, "_install_torchao_stub_once", lambda: None)
+ monkeypatch.setattr(embeddings, "_guard_model_security", lambda *_a, **_k: None)
+ monkeypatch.setattr(embeddings, "_load_device", lambda: "cuda")
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.active_hf_hub_cache",
+ lambda: str(tmp_path / "selected-hub"),
+ )
+ embeddings._model = None
+ embeddings._name = None
+
+ embeddings._get("Org/Embedder")
+
+ assert observed["device"] == "cuda"
assert list(observed["model_kwargs"].values()) == ["float16"]