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 documents searchable after upgrading a Chat only install (#15443)

Nilay8e1fb9aa9678
diff --git a/studio/backend/core/rag/reembed.py b/studio/backend/core/rag/reembed.py
index e93c79b1f16..8780a90366a 100644
--- a/studio/backend/core/rag/reembed.py
+++ b/studio/backend/core/rag/reembed.py
@@ -28,6 +28,7 @@ _MAX_CONSECUTIVE_FAILURES = 3
_RETIRE_JOIN_SECONDS = 10.0
_jobs: dict = {}
+_checked: set = set()
_lock = threading.Lock()
@@ -36,8 +37,10 @@ class _Stopped(Exception):
class _Job:
- def __init__(self) -> None:
+ def __init__(self, identity: str | None = None) -> None:
self.id = str(uuid.uuid4())
+ # Set on automatic jobs: they write this vector space only and stop on a model switch or fallback.
+ self.identity = identity
self.status = "running"
self.done = 0
self.failed = 0
@@ -121,6 +124,8 @@ def _reembed_document(job: _Job, doc: dict, model: str) -> bool:
job.current = done / total
vectors, identity = ingestion._embed_all(texts, model, on_progress)
+ if job.identity is not None and identity != job.identity:
+ raise _Stopped
conn = rag_db.get_connection()
try:
swapped = store.replace_document_vectors(
@@ -160,6 +165,8 @@ def _run(job: _Job) -> None:
raise _Stopped
model = config.effective_embedding_model()
identity = embeddings.embedding_identity(model)
+ if job.identity is not None and identity != job.identity:
+ raise _Stopped
conn = rag_db.get_connection()
try:
pending = [
@@ -170,6 +177,8 @@ def _run(job: _Job) -> None:
]
finally:
conn.close()
+ if job.identity is not None and not _upgraded_from_llama(pending, job.identity):
+ raise _Stopped
job.remaining = len(pending)
if not pending:
job.status = "completed"
@@ -207,7 +216,7 @@ def _run(job: _Job) -> None:
job.current = 0.0
-def start() -> dict:
+def start(identity: str | None = None) -> dict:
"""Start re-embedding this account's stale documents, or return the job already running."""
if account_is_retired():
raise RuntimeError("Account is retired")
@@ -215,8 +224,11 @@ def start() -> dict:
with _lock:
job = _jobs.get(key)
if job is not None and job.status == "running":
+ if identity is None:
+ # A Re-embed click adopts an automatic job, which then follows the current model.
+ job.identity = None
return job.snapshot()
- job = _Job()
+ job = _Job(identity)
job.remaining = sum(stale_counts().values())
job.thread = account_thread(target = _run, args = (job,), daemon = True)
_jobs[key] = job
@@ -227,6 +239,38 @@ def start() -> dict:
return started
+def _upgraded_from_llama(stale: list[dict], identity: str) -> bool:
+ """Every stale document is this identity's model written by llama-server."""
+ model = config.embedding_identity_model(identity)
+ return all(
+ d["embedding_model"].startswith("llama-server:")
+ and config.embedding_identity_model(d["embedding_model"]) == model
+ for d in stale
+ )
+
+
+def start_after_backend_change(identity: str) -> None:
+ """Re-embed on its own only after an upgrade moved the same model from llama-server to
+ sentence-transformers; a runtime fallback the other way must not overwrite the ST vectors."""
+ if not identity.startswith("sentence-transformers:"):
+ return
+ key = account_key("reembed")
+ with _lock:
+ if (key, identity) in _checked or key in _jobs:
+ return
+ _checked.add((key, identity))
+ model = config.embedding_identity_model(identity)
+ if model != config.effective_embedding_model():
+ return
+ conn = rag_db.get_connection()
+ try:
+ stale = _stale_documents(conn, identity)
+ finally:
+ conn.close()
+ if stale and _upgraded_from_llama(stale, identity):
+ start(identity)
+
+
def status() -> dict | None:
with _lock:
job = _jobs.get(account_key("reembed"))
diff --git a/studio/backend/core/rag/retrieval.py b/studio/backend/core/rag/retrieval.py
index ebf942b75b8..b39d2558acd 100644
--- a/studio/backend/core/rag/retrieval.py
+++ b/studio/backend/core/rag/retrieval.py
@@ -10,7 +10,7 @@ import logging
import sqlite3
from dataclasses import dataclass
-from . import config, embeddings, store
+from . import config, embeddings, reembed, store
logger = logging.getLogger(__name__)
@@ -64,6 +64,10 @@ def retrieve_dense(
)
vec = vectors[0]
_warn_once_on_untagged(conn)
+ try:
+ reembed.start_after_backend_change(identity)
+ except Exception: # noqa: BLE001 - re-embedding must never break retrieval
+ logger.warning("could not start re-embedding after an embedder change", exc_info = True)
return [
Hit(cid, s, dense_score = s)
for cid, s in store.search_dense(conn, scope, vec, k, embedding_model = identity)
diff --git a/studio/backend/tests/test_rag_reembed.py b/studio/backend/tests/test_rag_reembed.py
index 985aacdd67b..36a4fbeb307 100644
--- a/studio/backend/tests/test_rag_reembed.py
+++ b/studio/backend/tests/test_rag_reembed.py
@@ -28,6 +28,7 @@ def models(rag_home, stub_embeddings, monkeypatch):
monkeypatch.setattr(embeddings, "encode", encode)
monkeypatch.setattr(embeddings, "max_tokens", lambda model_name = None: None)
monkeypatch.setattr(reembed, "_jobs", {})
+ monkeypatch.setattr(reembed, "_checked", set(), raising = False)
monkeypatch.setattr(reembed, "_RETIRE_JOIN_SECONDS", 0.2)
current = lambda fresh = False: state["model"] if fresh else state.get("cached", state["model"])
monkeypatch.setattr(config, "effective_embedding_model", current)
@@ -77,6 +78,166 @@ def test_stale_documents_regain_dense_search_under_the_same_ids(models, tmp_path
assert hits[0].chunk_id == chunks[1][1][0]
+def test_documents_the_same_model_wrote_through_another_backend_re_embed_on_search(
+ models, tmp_path, monkeypatch
+):
+ scope = store.kb_scope("K10")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: True)
+ doc = _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ llama = _row(doc)[0]
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: False)
+ assert reembed.stale_counts() == {"documents": 1, "archived": 0}
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha bravo", k = 1, model_name = OLD)
+ assert reembed.status() is not None
+ reembed._jobs["reembed"].thread.join(timeout = 10)
+ assert reembed.status()["status"] == "completed"
+ assert _row(doc)[0] == embeddings.embedding_identity(OLD) != llama
+ with _connect() as c:
+ hits = retrieval.retrieve_dense(c, scope, "alpha bravo", k = 1, model_name = OLD)
+ assert hits[0].chunk_id == f"{doc}:0"
+
+
+def test_a_model_switch_leaves_re_embedding_to_the_user(models, tmp_path):
+ scope = store.kb_scope("K11")
+ _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ models["model"] = NEW
+ with _connect() as c:
+ assert retrieval.retrieve_dense(c, scope, "alpha bravo", k = 1, model_name = NEW) == []
+ assert reembed.status() is None
+
+
+def test_documents_left_from_a_model_switch_keep_re_embedding_with_the_user(
+ models, tmp_path, monkeypatch
+):
+ other = "org/other-embedder"
+ monkeypatch.setitem(WIDTHS, other, WIDTHS[OLD])
+ scope = store.kb_scope("K12")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: True)
+ _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: False)
+ (tmp_path / "b.txt").write_text("charlie delta", encoding = "utf-8")
+ ingestion.start_ingestion(
+ scope, None, None, "b.txt", str(tmp_path / "b.txt"), model_name = other, background = False
+ )
+ assert reembed.stale_counts() == {"documents": 2, "archived": 0}
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha bravo", k = 1, model_name = OLD)
+ assert reembed.status() is None
+
+
+def test_a_runtime_fallback_to_llama_server_leaves_the_st_vectors_alone(
+ models, tmp_path, monkeypatch
+):
+ scope = store.kb_scope("K13")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: False)
+ doc = _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ st = _row(doc)[0]
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: True)
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha bravo", k = 1, model_name = OLD)
+ assert reembed.status() is None and _row(doc)[0] == st
+
+
+def test_a_model_switch_stops_an_automatic_re_embed(models, tmp_path, monkeypatch):
+ scope = store.kb_scope("K14")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: True)
+ _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: False)
+ healthy = _ingest(tmp_path, scope, "b.txt", "charlie delta")
+ encode = embeddings.encode
+
+ def switch_while_a_encodes(texts, model_name, **kw):
+ if texts == ["alpha bravo"]:
+ models["model"] = NEW
+ return encode(texts, model_name, **kw)
+
+ monkeypatch.setattr(embeddings, "encode", switch_while_a_encodes)
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha", k = 1, model_name = OLD)
+ reembed._jobs["reembed"].thread.join(timeout = 10)
+ assert reembed.status()["status"] == "cancelled"
+ assert _row(healthy)[0] == embeddings.embedding_identity(OLD)
+ assert all(m != NEW for m, _ in models["encoded"])
+
+
+def test_a_fallback_during_an_automatic_re_embed_stops_it(models, tmp_path, monkeypatch):
+ scope = store.kb_scope("K15")
+ llama = {"on": True}
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: llama["on"])
+ _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ llama["on"] = False
+ healthy = _ingest(tmp_path, scope, "b.txt", "charlie delta")
+ st = _row(healthy)[0]
+ encode = embeddings.encode
+
+ def fall_back_while_a_encodes(texts, model_name, **kw):
+ if texts == ["alpha bravo"]:
+ llama["on"] = True
+ return encode(texts, model_name, **kw)
+
+ monkeypatch.setattr(embeddings, "encode", fall_back_while_a_encodes)
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha", k = 1, model_name = OLD)
+ reembed._jobs["reembed"].thread.join(timeout = 10)
+ assert reembed.status()["status"] == "cancelled"
+ assert _row(healthy)[0] == st
+
+
+def test_a_re_embed_click_during_an_automatic_job_follows_a_model_switch(
+ models, tmp_path, monkeypatch
+):
+ scope = store.kb_scope("K16")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: True)
+ doc = _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: False)
+ encode = embeddings.encode
+
+ def switch_and_click_while_a_encodes(texts, model_name, **kw):
+ if texts == ["alpha bravo"] and model_name == OLD:
+ models["model"] = NEW
+ reembed.start()
+ return encode(texts, model_name, **kw)
+
+ monkeypatch.setattr(embeddings, "encode", switch_and_click_while_a_encodes)
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha", k = 1, model_name = OLD)
+ reembed._jobs["reembed"].thread.join(timeout = 10)
+ assert reembed.status()["status"] == "completed"
+ assert _row(doc)[0] == embeddings.embedding_identity(NEW)
+
+
+def test_an_automatic_job_leaves_a_document_another_model_finished_meanwhile(
+ models, tmp_path, monkeypatch
+):
+ other = "org/other-embedder"
+ monkeypatch.setitem(WIDTHS, other, WIDTHS[OLD])
+ scope = store.kb_scope("K17")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: True)
+ _ingest(tmp_path, scope, "a.txt", "alpha bravo")
+ monkeypatch.setattr(embeddings, "_identity_backend_is_llama", lambda name: False)
+ (tmp_path / "b.txt").write_text("charlie delta", encoding = "utf-8")
+ encode = embeddings.encode
+ late = []
+
+ def finish_an_upload_while_a_encodes(texts, model_name, **kw):
+ if texts == ["alpha bravo"] and not late:
+ late.append(
+ ingestion.start_ingestion(
+ scope, None, None, "b.txt", str(tmp_path / "b.txt"),
+ model_name = other, background = False,
+ )[0]
+ ) # fmt: skip
+ return encode(texts, model_name, **kw)
+
+ monkeypatch.setattr(embeddings, "encode", finish_an_upload_while_a_encodes)
+ with _connect() as c:
+ retrieval.retrieve_dense(c, scope, "alpha", k = 1, model_name = OLD)
+ reembed._jobs["reembed"].thread.join(timeout = 10)
+ assert reembed.status()["status"] == "cancelled"
+ assert _row(late[0])[0] == embeddings.embedding_identity(other)
+
+
def test_failures_keep_the_old_index_and_only_a_streak_ends_the_job(models, tmp_path, monkeypatch):
monkeypatch.setattr(reembed, "_MAX_CONSECUTIVE_FAILURES", 2)
scope = store.kb_scope("K1")