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: keep compacted turns searchable when the archive embedder fails (#16718)
Debojyoti Banerjee91935a13e40b
diff --git a/studio/backend/core/rag/conversation_archive.py b/studio/backend/core/rag/conversation_archive.pyindex 44dad7c4d56..b5e5c897277 100644--- a/studio/backend/core/rag/conversation_archive.py+++ b/studio/backend/core/rag/conversation_archive.py@@ -823,6 +823,10 @@ def _archive_turns(positions = _transcript_positions(thread_id, branch or live)live_positions = _live_positions(live)written = 0+ # Only an embedder failure falls back to keyword copies; a failing store would refuse those too.+ dense_failed = False+ embedded = False+ embed_error = Noneconn = Nonetry:if cancel_check is not None and cancel_check():@@ -942,6 +946,7 @@ def _archive_turns()if not vectors:return 0+ embedded = True# Only fully embedded groups; a partial one is left for the next request.complete: list = []@@ -1058,10 +1063,12 @@ def _archive_turns(raise embed_errorexcept embeddings.EmbeddingModelDownloadRequiredError as exc:globals()["_INGEST_FAILED"] = True+ dense_failed = True_log_embedder_pending(model, exc)- except Exception:+ except Exception as exc:# Failing to archive must not raise; what was written before the failure stays searchable.globals()["_INGEST_FAILED"] = True+ dense_failed = not embedded or exc is embed_errorlogger.warning("conversation_archive.ingest_failed thread_id=%s", thread_id, exc_info = True)finally:if conn is not None:@@ -1070,6 +1077,13 @@ def _archive_turns(except Exception:pass+ if dense_failed and not (cancel_check is not None and cancel_check()):+ # Without any copy there is no archive, so search_conversation is never offered (#16706).+ # degraded() stays set: dense recall is still down.+ written += _archive_turns_lexically(+ thread_id, scope, groups, positions, live_positions, cancel_check+ )+# Re-check after commit: a concurrent delete sweep could strand deleted content. Delete drops rows first, sweeps archives last, so either order converges.if written and not can_archive(thread_id):logger.info("conversation_archive.thread_deleted_mid_ingest thread_id=%s", thread_id)@@ -1078,6 +1092,102 @@ def _archive_turns(return written+# Matches no embedder, so `_stale_document` re-embeds the copy in place once one works.+LEXICAL_ONLY_IDENTITY = rag_db.VECTORS_DROPPED + "none"+++def _rough_token_count(text: str) -> int:+ return max(1, len(text or "") // 4)+++@_writes+def _archive_turns_lexically(+ thread_id: str,+ scope: str,+ groups: list,+ positions: Optional[list[list[str]]],+ live_positions: Optional[list[list[str]]],+ cancel_check: Optional[Callable[[], bool]],+) -> int:+ """Keyword-only copies of evicted turns, one per evicted occurrence (``_write_budget``); returns how many were written."""+ written = 0+ conn = None+ try:+ conn = rag_db.get_connection()+ for group, span in groups:+ if cancel_check is not None and cancel_check():+ break+ text = render_turn(group)+ if not text:+ continue+ digest = hashlib.sha256(text.encode("utf-8", "ignore")).hexdigest()+ seats = _occurrences(positions, group)+ budget = _write_budget(positions, seats, live_positions, group)+ if len(store.documents_by_hash(conn, scope, digest)) >= budget:+ # As the dense pre-check: re-seat, retire surplus copies after a rewind, widen the span.+ _restamp(conn, scope, digest, seats[:budget], commit = True)+ _widen_span(conn, scope, digest, span)+ continue+ chunks = _turn_chunks(text, max(1, int(config.CHUNK_TOKENS)), _rough_token_count)+ if not chunks:+ continue+ roles = " + ".join(+ dict.fromkeys(str(message.get("role") or "message") for message in group)+ )+ _write_lock = False+ try:+ conn.execute("BEGIN IMMEDIATE")+ _write_lock = True+ except Exception:+ logger.debug("conversation_archive.no_write_lock", exc_info = True)+ # Re-counted under the lock: a concurrent compaction may have written some.+ have = len(store.documents_by_hash(conn, scope, digest))+ if have >= budget:+ if _write_lock:+ conn.rollback()+ continue+ try:+ for n in range(have, budget):+ document_id = store.create_document(+ conn,+ scope = scope,+ thread_id = thread_id,+ filename = f"earlier turn ({roles})",+ sha256 = digest,+ status = "completed",+ embedding_model = LEXICAL_ONLY_IDENTITY,+ archive_messages = span,+ archive_ordinal = seats[n]+ if n < len(seats)+ else _fallback_ordinal(conn, scope, positions),+ commit = False,+ )+ store.add_lexical_chunks(conn, scope, document_id, chunks)+ except Exception:+ conn.rollback()+ raise+ conn.commit()+ written += budget - have+ if written:+ logger.info(+ "conversation_archive.archived_without_vectors thread_id=%s turns=%s",+ thread_id,+ written,+ )+ return written+ except Exception:+ logger.warning(+ "conversation_archive.lexical_ingest_failed thread_id=%s", thread_id, exc_info = True+ )+ return written+ finally:+ if conn is not None:+ try:+ conn.close()+ except Exception:+ pass++# A Settings pick whose download has not finished is not a fault; logged once, not per compaction._EMBEDDER_PENDING_LOGGED: set = set()diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.pyindex 0a8fcd61af0..564fd6601a3 100644--- a/studio/backend/core/rag/store.py+++ b/studio/backend/core/rag/store.py@@ -392,6 +392,40 @@ def failed_documents_by_hash(conn: sqlite3.Connection, scope: str, sha256: str)return [dict(r) for r in rows]+def _insert_chunk(+ conn: sqlite3.Connection, scope: str, document_id: str, chunk, regions_json+) -> int:+ """Writes one chunks row and its FTS5 row; returns the chunks rowid."""+ chunk_id = f"{document_id}:{chunk.chunk_index}"+ cur = conn.execute(+ "INSERT OR REPLACE INTO chunks("+ "id, document_id, scope, chunk_index, text, page_number, "+ "source_page_index, page_char_start, page_char_end, token_count, "+ "whole_document_token_count, kind, pdf_regions_json) "+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",+ (+ chunk_id,+ document_id,+ scope,+ chunk.chunk_index,+ chunk.text,+ chunk.page_number,+ chunk.source_page_index,+ getattr(chunk, "page_char_start", None),+ getattr(chunk, "page_char_end", None),+ chunk.token_count,+ getattr(chunk, "whole_document_token_count", None),+ getattr(chunk, "kind", "text"),+ regions_json,+ ),+ )+ conn.execute(+ "INSERT INTO chunks_fts(text, chunk_id, scope) VALUES(?,?,?)",+ (chunk.text, chunk_id, scope),+ )+ return cur.lastrowid++def add_chunks(conn: sqlite3.Connection,scope: str,@@ -416,33 +450,14 @@ def add_chunks(for i, (chunk, vector) in enumerate(zip(chunks, vectors)):chunk_id = f"{document_id}:{chunk.chunk_index}"chunk_regions = regions[i] if regions and i < len(regions) else None- regions_json = json.dumps(chunk_regions) if chunk_regions else None- cur = conn.execute(- "INSERT OR REPLACE INTO chunks("- "id, document_id, scope, chunk_index, text, page_number, "- "source_page_index, page_char_start, page_char_end, token_count, "- "whole_document_token_count, kind, pdf_regions_json) "- "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",- (- chunk_id,- document_id,+ chunk_rowids.append(+ _insert_chunk(+ conn,scope,- chunk.chunk_index,- chunk.text,- chunk.page_number,- chunk.source_page_index,- getattr(chunk, "page_char_start", None),- getattr(chunk, "page_char_end", None),- chunk.token_count,- getattr(chunk, "whole_document_token_count", None),- getattr(chunk, "kind", "text"),- regions_json,- ),- )- chunk_rowids.append(cur.lastrowid)- conn.execute(- "INSERT INTO chunks_fts(text, chunk_id, scope) VALUES(?,?,?)",- (chunk.text, chunk_id, scope),+ document_id,+ chunk,+ json.dumps(chunk_regions) if chunk_regions else None,+ ))vec_rowids.append(conn.execute(@@ -474,6 +489,12 @@ def add_chunks()+def add_lexical_chunks(conn: sqlite3.Connection, scope: str, document_id: str, chunks) -> None:+ """chunks + FTS5 rows only, no vec0 row: keyword search finds them, dense search never does. Uncommitted."""+ for chunk in chunks:+ _insert_chunk(conn, scope, document_id, chunk, None)++def replace_document_vectors(conn: sqlite3.Connection,document_id: str,diff --git a/studio/backend/tests/test_conversation_archive.py b/studio/backend/tests/test_conversation_archive.pyindex bd57e5b33ae..0192ef6ab24 100644--- a/studio/backend/tests/test_conversation_archive.py+++ b/studio/backend/tests/test_conversation_archive.py@@ -94,6 +94,17 @@ def conn(rag_home, rag_conn, stub_embeddings):return rag_conn+def _fail_embedder(monkeypatch):+ """Archiving then falls back to keyword-only copies, as with a llama.cpp that cannot load the embedder."""+ from core.rag import embeddings++ def no_embedder(*_args, **_kwargs):+ raise RuntimeError("unknown model architecture")++ monkeypatch.setattr(embeddings, "encode_with_identity", no_embedder)+ monkeypatch.setattr(embeddings, "token_counter", no_embedder)++def _tool_part(*,type = "tool-call",@@ -1225,11 +1236,16 @@ def test_an_embedder_download_still_pending_is_logged_once_without_a_traceback(turn = _turn("what is the deploy code", "the deploy code is 5150")caplog.set_level(logging.INFO, logger = conversation_archive.logger.name)- for _ in range(3):- assert _archive([dict(m) for m in turn]) == 0+ # The first fit keeps a keyword copy of the evicted turn; later fits find it there and add none.+ # Saved once: each saved occurrence gets its own copy.+ _save_thread(THREAD, turn, append = True)+ for expected in (1, 0, 0):+ assert conversation_archive.archive_turns(THREAD, [dict(m) for m in turn]) == expectedassert conversation_archive.degraded() is Truefound = conversation_archive.recall(THREAD, "sourdough")assert found is not None and "sourdough" in found[0]+ found = conversation_archive.recall(THREAD, "deploy code")+ assert found is not None and "5150" in found[0]records = [r for r in caplog.records if r.name == conversation_archive.logger.name]assert not [r for r in records if r.levelno >= logging.WARNING or r.exc_info]@@ -1258,14 +1274,135 @@ def test_a_failed_archive_marks_the_feature_degraded(conn, monkeypatch):raise RuntimeError("no embedding model could be started")monkeypatch.setattr(embeddings, "encode_with_identity", no_embedder)- assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 0+ # Kept for keyword search, but dense recall is still down.+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 1assert conversation_archive.degraded() is Truemonkeypatch.setattr(embeddings, "encode_with_identity", real)+ # The keyword copy is re-embedded in place.assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turn]) == 1assert conversation_archive.degraded() is False+def test_turns_evicted_while_the_embedder_fails_stay_searchable(conn, monkeypatch):+ """#16706: with no archive the chat never gets search_conversation, and recall finds nothing."""+ from core.inference import tools+ from core.rag import embeddings++ thread_id = "no-embedder-thread"+ turns = _turn("what is the deploy code", "the deploy code is 5150") + _turn(+ "which colour did we pick", "we picked teal"+ )+ _save_thread(thread_id, turns + [{"role": "user", "content": "and now?"}])++ real_encode = embeddings.encode_with_identity+ real_counter = embeddings.token_counter++ def no_embedder(*_args, **_kwargs):+ raise RuntimeError("llama-server binary not found")++ monkeypatch.setattr(embeddings, "encode_with_identity", no_embedder)+ monkeypatch.setattr(embeddings, "token_counter", no_embedder)+ assert conversation_archive.has_archive(thread_id) is False+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turns]) == 2+ assert conversation_archive.has_archive(thread_id) is True++ # The model's own search, through the tool it is now offered, answers from keyword matches.+ found = tools._search_conversation({"query": "deploy code"}, {"thread_id": thread_id})+ assert "5150" in found+ found = tools._search_conversation({"query": "colour teal"}, {"thread_id": thread_id})+ assert "teal" in found++ scope = store.conversation_archive_scope(thread_id)+ before = {+ row["sha256"]: row["archive_ordinal"]+ for row in conn.execute(+ "SELECT sha256, archive_ordinal FROM documents WHERE scope = ?", (scope,)+ )+ }+ assert len(before) == 2++ # Once the embedder works, the same eviction re-embeds both turns where they were.+ monkeypatch.setattr(embeddings, "encode_with_identity", real_encode)+ monkeypatch.setattr(embeddings, "token_counter", real_counter)+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turns]) == 2+ rows = conn.execute(+ "SELECT sha256, archive_ordinal, embedding_model FROM documents WHERE scope = ?", (scope,)+ ).fetchall()+ assert {row["sha256"]: row["archive_ordinal"] for row in rows} == before+ assert all(row["embedding_model"] != conversation_archive.LEXICAL_ONLY_IDENTITY for row in rows)+ vectors = conn.execute("SELECT COUNT(*) FROM chunks_vec WHERE scope = ?", (scope,)).fetchone()[+ 0+ ]+ assert vectors > 0+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turns]) == 0+++def test_keyword_copies_keep_every_evicted_occurrence_of_a_repeated_turn(conn, monkeypatch):+ """A turn said twice keeps both seats, or recall shows the value it replaced as the latest."""+ from core.rag import embeddings++ thread_id = "repeat-no-embedder"+ turns = _turn("set X to 1", "ok") + _turn("set X to 2", "ok") + _turn("set X to 1", "ok")+ live = [{"role": "user", "content": "what is X now?"}]+ _save_thread(thread_id, turns + live)++ def no_embedder(*_args, **_kwargs):+ raise RuntimeError("unknown model architecture")++ monkeypatch.setattr(embeddings, "encode_with_identity", no_embedder)+ monkeypatch.setattr(embeddings, "token_counter", no_embedder)+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turns], live = live) == 3+ ordinals = [+ row[0]+ for row in conn.execute(+ "SELECT archive_ordinal FROM documents WHERE scope = ? ORDER BY archive_ordinal",+ (store.conversation_archive_scope(thread_id),),+ )+ ]+ assert ordinals == [0, 1, 2]+ assert conversation_archive.archive_turns(thread_id, [dict(m) for m in turns], live = live) == 0+++def test_chat_stop_interrupts_the_keyword_fallback(conn, monkeypatch):+ from core.rag import embeddings++ thread_id = "stop-no-embedder"+ turns = [m for i in range(5) for m in _turn(f"question {i}", f"answer {i}")]+ _save_thread(thread_id, turns + [{"role": "user", "content": "next"}])++ def no_embedder(*_args, **_kwargs):+ raise RuntimeError("unknown model architecture")++ monkeypatch.setattr(embeddings, "encode_with_identity", no_embedder)+ monkeypatch.setattr(embeddings, "token_counter", no_embedder)+ polls = []++ def stop_after_one_write():+ polls.append(1)+ # Polled once before the dense pass, once before the fallback, then once per turn.+ return len(polls) > 3++ written = conversation_archive.archive_turns(+ thread_id, [dict(m) for m in turns], cancel_check = stop_after_one_write+ )+ assert written == 1+++def test_a_failing_store_does_not_fall_back_to_keyword_copies(conn, monkeypatch):+ """Only the embedder failing falls back: a store that cannot write chunks is left to retry."""+ turns = _turn("what is a wombat", "a burrowing marsupial")+ real_add_chunks = store.add_chunks++ def explode(*args, **kwargs):+ raise RuntimeError("disk full")++ monkeypatch.setattr(store, "add_chunks", explode)+ assert _archive(turns, thread_id = "store-fails") == 0+ assert conversation_archive.has_archive("store-fails") is False+ monkeypatch.setattr(store, "add_chunks", real_add_chunks)++def test_the_late_archive_cleanup_spares_a_recreated_thread(conn):"""The late archive sweep after DELETE must spare a chat recreated under the same id."""from routes import chat_history@@ -2343,12 +2480,24 @@ def test_archive_embed_failure_keeps_completed_batches(conn, monkeypatch):evicted.append({"role": "user", "content": f"fail question {index} unique {index}"})evicted.append({"role": "assistant", "content": f"fail answer {index} unique {index}"})- written = conversation_archive.archive_turns(thread_id, evicted)- assert 0 < written < 8+ scope = store.conversation_archive_scope(thread_id)++ def keyword_only():+ return conn.execute(+ "SELECT COUNT(*) FROM documents WHERE scope = ? AND embedding_model = ?",+ (scope, conversation_archive.LEXICAL_ONLY_IDENTITY),+ ).fetchone()[0]++ # Every turn is kept: the embedded batches with vectors, the rest for keyword search only.+ assert conversation_archive.archive_turns(thread_id, evicted) == 8+ unembedded = keyword_only()+ assert 0 < unembedded < 8assert conversation_archive.degraded()calls.clear()- assert conversation_archive.archive_turns(thread_id, evicted) == 8 - written- assert sum(calls) <= 8 - written+ # Only the keyword-only turns are encoded again.+ assert conversation_archive.archive_turns(thread_id, evicted) == unembedded+ assert sum(calls) <= unembedded+ assert keyword_only() == 0VARIABLE = "ZQXVARA123"@@ -3934,8 +4083,13 @@ def test_a_retried_turn_is_numbered_on_the_branch_the_user_is_on(conn):assert ordinals == [0, 1, 2]-def test_a_rewind_retires_the_copy_the_conversation_no_longer_holds(conn):[email protected]("embedder_fails", [False, True])+def test_a_rewind_retires_the_copy_the_conversation_no_longer_holds(+ conn, monkeypatch, embedder_fails+):"""Identical copies outnumber occurrences after a rewind, so surplus copies must be retired."""+ if embedder_fails:+ _fail_embedder(monkeypatch)first = _turn("set ZQXVARA123 to 1", "ok")second = _turn("set ZQXVARA123 to 2", "ok")repeat = _turn("set ZQXVARA123 to 1", "ok")@@ -4926,8 +5080,13 @@ def test_a_tool_turn_with_a_preamble_still_gets_its_seat():assert conversation_archive._occurrences(positions, live) == [1]-def test_the_same_text_over_a_longer_span_widens_the_stored_window(conn):[email protected]("embedder_fails", [False, True])+def test_the_same_text_over_a_longer_span_widens_the_stored_window(+ conn, monkeypatch, embedder_fails+):"""Same text over a longer span must widen the stored window, or the turn is filtered out of recall."""+ if embedder_fails:+ _fail_embedder(monkeypatch)short = [_assistant_call("terminal", '{"command":"ls"}', id = "c2"),{"role": "tool", "tool_call_id": "c2", "content": "main.py readme.md"},