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: answer dense RAG search from an in-memory numpy matrix kept in sync by SQLite triggers (#15961)
Daniel Hane5d3613c4b62
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.pyindex 429941bc02c..280fc8a9441 100644--- a/studio/backend/core/rag/store.py+++ b/studio/backend/core/rag/store.py@@ -20,7 +20,7 @@ from datetime import datetime, timezonefrom storage import rag_db-from . import config+from . import config, vec_cachedef kb_scope(kb_id: str) -> str:@@ -405,6 +405,7 @@ def add_chunks(per-chunk PDF highlight rects, stored as JSON."""if len(vectors):rag_db.ensure_vec(conn, len(vectors[0]), document_id)+ epoch_before = vec_cache.read_epoch(conn, scope) if vec_cache.enabled() else Nonevec_rowids: list[int] = []for i, (chunk, vector) in enumerate(zip(chunks, vectors)):chunk_id = f"{document_id}:{chunk.chunk_index}"@@ -442,10 +443,27 @@ def add_chunks((scope, chunk_id, _f32(vector)),).lastrowid)+ epoch_after = appended = None+ if epoch_before is not None:+ epoch_after = vec_cache.read_epoch(conn, scope)+ appended = conn.execute(+ "SELECT count(*) FROM chunks WHERE scope=? AND rowid > ?", (scope, epoch_before[2])+ ).fetchone()[0]# Another writer's width change may have marked this document while it was encoding.rag_db.restore_dropped_identity(conn, document_id)conn.commit()_remember_vec_rowids(conn, document_id, vec_rowids)+ if epoch_after is not None:+ vec_cache.note_append(+ _db_file(conn),+ scope,+ epoch_before,+ epoch_after,+ appended,+ vec_rowids,+ [f"{document_id}:{chunk.chunk_index}" for chunk in chunks[: len(vec_rowids)]],+ vectors[: len(vec_rowids)],+ )def replace_document_vectors(@@ -828,30 +846,22 @@ def _search_dense(conn: sqlite3.Connection, scope, vector, k: int, embedding_modfetches = dict.fromkeys(scopes, max(k * 3, k + 10))pending = list(scopes)query = _f32(vector) if pending else b""+ db_file = _db_file(conn) if pending and vec_cache.enabled() else Nonewhile pending:widen: list[str] = []for s in pending:fetch = fetches[s]- # SQLite < 3.41 does not pass LIMIT to vec0's KNN planner; bind k explicitly.- rows = conn.execute(- "SELECT chunk_id, distance FROM chunks_vec "- "WHERE scope=? AND embedding MATCH ? AND k=? ORDER BY distance",- (s, query, fetch),- ).fetchall()+ rows, cap = _knn(conn, db_file, s, vector, query, fetch)kept[s] = _drop_incompatible(conn,# A NaN vector written by an fp16 embedder reads back as a NULL distance: skip it, or the# subtraction raises and the whole retrieval fails.- [- (r["chunk_id"], 1.0 - r["distance"])- for r in rows- if r["distance"] is not None and math.isfinite(r["distance"])- ],+ [(cid, 1.0 - d) for cid, d in rows if d is not None and math.isfinite(d)],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)+ if len(kept[s]) < k and len(rows) >= fetch and fetch < cap:+ fetches[s] = min(fetch * 4, cap)widen.append(s)pending = widenout = [hit for s in scopes for hit in kept[s]]@@ -861,6 +871,23 @@ def _search_dense(conn: sqlite3.Connection, scope, vector, k: int, embedding_mod# 4096 is vec0's own ceiling; raising this errors the query._MAX_DENSE_FETCH = 4096+++def _knn(conn, db_file, scope: str, vector, query: bytes, fetch: int):+ """(chunk_id, distance) rows plus the largest fetch worth asking for: the cache's row count, or vec0's cap."""+ if db_file is not None:+ hit = vec_cache.search(conn, db_file, scope, vector, fetch)+ if hit is not None:+ return hit+ # SQLite < 3.41 does not pass LIMIT to vec0's KNN planner; bind k explicitly.+ rows = conn.execute(+ "SELECT chunk_id, distance FROM chunks_vec "+ "WHERE scope=? AND embedding MATCH ? AND k=? ORDER BY distance",+ (scope, query, min(fetch, _MAX_DENSE_FETCH)),+ ).fetchall()+ return [(r["chunk_id"], r["distance"]) for r in rows], _MAX_DENSE_FETCH++# One id per bound parameter, kept under the oldest SQLITE_MAX_VARIABLE_NUMBER._ID_BATCH = 900diff --git a/studio/backend/core/rag/vec_cache.py b/studio/backend/core/rag/vec_cache.pynew file mode 100644index 00000000000..fecf8da8147--- /dev/null+++ b/studio/backend/core/rag/vec_cache.py@@ -0,0 +1,305 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""In-memory per-scope float32 matrices answering dense KNN exactly, in place of vec0's scalar scan.++SQLite stays authoritative: triggers bump ``rag_vec_epoch`` for a scope in the same transaction as any write that+can change its vectors, and an entry answers only a reader whose snapshot shows the epoch the entry was built at.+Anything else (miss, stale, over budget, no numpy, any error) returns None and the caller scans vec0."""++from __future__ import annotations++import logging+import os+import sqlite3+import threading+from collections import OrderedDict+from dataclasses import dataclass++logger = logging.getLogger(__name__)++GLOBAL_SCOPE = ""+_ID_OVERHEAD = 64+++def _np():+ try:+ import numpy+ except ImportError:+ return None+ return numpy+++def enabled() -> bool:+ return os.environ.get("RAG_VEC_CACHE", "1") != "0" and _budget() > 0+++def _budget() -> int:+ try:+ return int(float(os.environ.get("RAG_VEC_CACHE_MB", "256")) * 1024 * 1024)+ except ValueError:+ return 0+++@dataclass(frozen = True)+class _Entry:+ epoch: tuple+ rowids: object+ chunk_ids: object+ mat: object+ inv: object+ nbytes: int+++_entries: OrderedDict[tuple, _Entry] = OrderedDict()+_too_big: dict[tuple, int] = {}+_bytes = 0+_lock = threading.Lock()+_pending: set[tuple] = set()+_cond = threading.Condition(_lock)+_worker: threading.Thread | None = None+_busy = 0+++def _key(db_file: str, scope: str, dim: int) -> tuple:+ try:+ ino = os.stat(db_file).st_ino+ except OSError:+ ino = None+ return db_file, ino, scope, int(dim)+++def read_epoch(conn: sqlite3.Connection, scope: str) -> tuple | None:+ """(scope epoch, global epoch, newest chunk rowid in the scope): equal tuples mean equal vectors."""+ try:+ return tuple(+ conn.execute(+ "SELECT COALESCE((SELECT n FROM rag_vec_epoch WHERE scope=?), 0), "+ "COALESCE((SELECT n FROM rag_vec_epoch WHERE scope=?), 0), "+ "COALESCE((SELECT max(rowid) FROM chunks WHERE scope=?), 0)",+ (scope, GLOBAL_SCOPE, scope),+ ).fetchone()+ )+ except sqlite3.Error:+ return None+++def _make_entry(np, epoch, rowids, chunk_ids, blob: bytes, dim: int) -> _Entry:+ mat = np.frombuffer(blob, dtype = np.float32).reshape(-1, dim)+ with np.errstate(all = "ignore"):+ norms = np.sqrt(np.einsum("ij,ij->i", mat, mat, dtype = np.float64))+ # vec0 answers NULL for NaN / inf / zero rows, which _search_dense drops.+ valid = np.isfinite(norms) & (norms > 0)+ mat = np.ascontiguousarray(mat[valid])+ inv = (1.0 / norms[valid]).astype(np.float32)+ rowids = np.asarray(rowids, dtype = np.int64)[valid]+ ids = np.empty(len(chunk_ids), dtype = object)+ ids[:] = chunk_ids+ ids = ids[valid]+ for a in (mat, inv, rowids, ids):+ a.setflags(write = False)+ nbytes = mat.nbytes + inv.nbytes + rowids.nbytes + sum(len(c) + _ID_OVERHEAD for c in ids)+ return _Entry(epoch, rowids, ids, mat, inv, nbytes)+++def _publish(+ key: tuple,+ entry: _Entry | None,+ expect: tuple | None = None,+) -> None:+ """Under _lock. ``expect``: replace only while the current entry is still at that epoch."""+ global _bytes+ old = _entries.get(key)+ if expect is not None and (old is None or old.epoch != expect):+ return+ if old is not None:+ _bytes -= old.nbytes+ del _entries[key]+ if entry is None:+ return+ if entry.nbytes > _budget():+ _too_big[key] = entry.epoch+ return+ _entries[key] = entry+ _bytes += entry.nbytes+ while _bytes > _budget() and _entries:+ _, evicted = _entries.popitem(last = False)+ _bytes -= evicted.nbytes+++def search(conn, db_file: str, scope: str, vector, fetch: int):+ """(rows, cap) from the cache at this snapshot's epoch, else None (and a build is queued)."""+ if not enabled():+ return None+ np = _np()+ if np is None:+ return None+ try:+ epoch = read_epoch(conn, scope)+ if epoch is None:+ return None+ key = _key(db_file, scope, len(vector))+ with _lock:+ entry = _entries.get(key)+ if entry is not None and entry.epoch == epoch:+ _entries.move_to_end(key)+ else:+ entry = None+ if _too_big.get(key) != epoch:+ _schedule(key)+ if entry is None:+ return None+ return _search_entry(np, entry, vector, fetch)+ except Exception: # noqa: BLE001 - vec0 answers instead+ logger.debug("vec_cache.search failed", exc_info = True)+ return None+++def _search_entry(np, entry: _Entry, vector, fetch: int):+ q = np.asarray(vector, dtype = np.float32)+ qn = float(np.sqrt(np.dot(q.astype(np.float64), q.astype(np.float64))))+ n = len(entry.rowids)+ if not np.isfinite(qn) or qn == 0.0 or n == 0:+ return [], n+ scores = (entry.mat @ q) * entry.inv+ scores = scores.astype(np.float64) / qn+ f = min(int(fetch), n)+ idx = np.argpartition(-scores, f - 1)[:f] if f < n else np.arange(n)+ order = idx[np.lexsort((entry.rowids[idx], -scores[idx]))]+ return [(entry.chunk_ids[i], 1.0 - float(scores[i])) for i in order], n+++def note_append(+ db_file: str, scope: str, before, after, appended: int, rowids, chunk_ids, vectors+) -> None:+ """After a committed pure append: extend the entry iff this writer's rows are the only change since+ ``before``. ``appended``: chunks rows in the scope newer than before's max rowid, read under the write lock."""+ if not enabled() or before is None or after is None or not rowids:+ return+ np = _np()+ if np is None:+ return+ try:+ dim = len(vectors[0])+ key = _key(db_file, scope, dim)+ with _lock:+ entry = _entries.get(key)+ if entry is None:+ return+ if after[:2] != before[:2] or appended != len(rowids) or entry.epoch != before:+ _publish(key, None)+ return+ rows = np.asarray(vectors, dtype = np.float32).reshape(len(rowids), dim)+ add = _make_entry(np, after, rowids, list(chunk_ids), rows.tobytes(), dim)+ merged = _Entry(+ after,+ np.concatenate([entry.rowids, add.rowids]),+ np.concatenate([entry.chunk_ids, add.chunk_ids]),+ np.concatenate([entry.mat, add.mat]),+ np.concatenate([entry.inv, add.inv]),+ entry.nbytes + add.nbytes,+ )+ for a in (merged.rowids, merged.chunk_ids, merged.mat, merged.inv):+ a.setflags(write = False)+ with _lock:+ _publish(key, merged, expect = before)+ except Exception: # noqa: BLE001+ logger.debug("vec_cache.note_append failed", exc_info = True)+ with _lock:+ _publish(_key(db_file, scope, len(vectors[0])), None)+++def _schedule(key: tuple) -> None:+ """Under _lock."""+ global _worker+ if key in _pending:+ return+ _pending.add(key)+ if _worker is None or not _worker.is_alive():+ _worker = threading.Thread(target = _run, name = "rag-vec-cache", daemon = True)+ _worker.start()+ _cond.notify_all()+++def _run() -> None:+ global _busy+ while True:+ with _lock:+ while not _pending:+ _cond.wait()+ key = _pending.pop()+ _busy += 1+ try:+ _build(key)+ except Exception: # noqa: BLE001+ logger.debug("vec_cache build failed for %s", key[2], exc_info = True)+ finally:+ with _lock:+ _busy -= 1+ _cond.notify_all()+++def _connect(db_file: str) -> sqlite3.Connection:+ from storage import rag_db, sqlite_gate++ conn = sqlite_gate.connect(db_file, timeout = 5)+ try:+ conn.enable_load_extension(True)+ rag_db.sqlite_vec.load(conn)+ conn.enable_load_extension(False)+ except BaseException:+ conn.close()+ raise+ return conn+++def _build(key: tuple) -> None:+ from storage import rag_db++ np = _np()+ if np is None or not enabled():+ return+ db_file, _, scope, dim = key+ conn = _connect(db_file)+ try:+ conn.row_factory = sqlite3.Row+ conn.execute("BEGIN")+ epoch = read_epoch(conn, scope)+ if epoch is None or rag_db.vec_table_dim(conn) != dim:+ return+ count = conn.execute("SELECT count(*) FROM chunks WHERE scope=?", (scope,)).fetchone()[0]+ if count * (dim * 4 + _ID_OVERHEAD) > _budget():+ with _lock:+ _too_big[key] = epoch+ return+ rows = conn.execute(+ "SELECT rowid, chunk_id, embedding FROM chunks_vec WHERE scope=?", (scope,)+ ).fetchall()+ finally:+ conn.close()+ entry = _make_entry(+ np,+ epoch,+ [r[0] for r in rows],+ [r[1] for r in rows],+ b"".join(r[2] for r in rows),+ dim,+ )+ with _lock:+ _too_big.pop(key, None)+ _publish(key, entry)+++def drain(timeout: float = 30.0) -> bool:+ """Wait for queued builds; for tests and benchmarks."""+ with _lock:+ return _cond.wait_for(lambda: not _pending and not _busy, timeout)+++def clear() -> None:+ global _bytes+ with _lock:+ _entries.clear()+ _too_big.clear()+ _pending.clear()+ _bytes = 0diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex c89fec38cd9..506bbc32513 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -217,6 +217,26 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:ON linked_folder_sync_jobs(folder_id)WHERE status IN ('pending','running');+ -- No INSERT trigger: any row trigger on chunks costs ~20 us per insert. Inserts show up as a new+ -- max(rowid) per scope instead; a reused rowid only follows a delete, which bumps the epoch.+ CREATE TABLE IF NOT EXISTS rag_vec_epoch (+ scope TEXT NOT NULL PRIMARY KEY,+ n INTEGER NOT NULL+ ) WITHOUT ROWID;+ CREATE TRIGGER IF NOT EXISTS rag_vec_epoch_chunk_delete AFTER DELETE ON chunks BEGIN+ INSERT INTO rag_vec_epoch(scope, n) VALUES (OLD.scope, 1)+ ON CONFLICT(scope) DO UPDATE SET n = n + 1;+ END;+ CREATE TRIGGER IF NOT EXISTS rag_vec_epoch_document_model+ AFTER UPDATE OF embedding_model ON documents BEGIN+ INSERT INTO rag_vec_epoch(scope, n) VALUES (NEW.scope, 1)+ ON CONFLICT(scope) DO UPDATE SET n = n + 1;+ END;+ CREATE TRIGGER IF NOT EXISTS rag_vec_epoch_document_delete AFTER DELETE ON documents BEGIN+ INSERT INTO rag_vec_epoch(scope, n) VALUES (OLD.scope, 1)+ ON CONFLICT(scope) DO UPDATE SET n = n + 1;+ END;+CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(text,chunk_id UNINDEXED,@@ -460,6 +480,11 @@ def ensure_vec(int(dim),)conn.execute("DROP TABLE chunks_vec")+ # The drop moves no chunks row; the global epoch invalidates every cached scope.+ conn.execute(+ "INSERT INTO rag_vec_epoch(scope, n) VALUES ('', 1) "+ "ON CONFLICT(scope) DO UPDATE SET n = n + 1"+ )conn.execute("UPDATE documents SET embedding_model=? || COALESCE(embedding_model, '') ""WHERE id IS NOT ? AND COALESCE(embedding_model, '') NOT LIKE ?",diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.pyindex 47b62bd78af..2a0ab4d851a 100644--- a/studio/backend/tests/conftest.py+++ b/studio/backend/tests/conftest.py@@ -1042,7 +1042,12 @@ def rag_home(tmp_path, monkeypatch, linkable_temp_base):root.mkdir(parents = True, exist_ok = True)monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(root))monkeypatch.setattr(rag_db, "_schema_ready", set())- return root+ yield root+ from core.rag import vec_cache++ # A background build still holding the db would block its removal on Windows.+ vec_cache.drain()+ vec_cache.clear()@pytest.fixturediff --git a/studio/backend/tests/test_rag_vec_cache.py b/studio/backend/tests/test_rag_vec_cache.pynew file mode 100644index 00000000000..8c7ed31ac93--- /dev/null+++ b/studio/backend/tests/test_rag_vec_cache.py@@ -0,0 +1,293 @@+# 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 dense cache answers exactly what vec0 answers, and never from a snapshot it was not built at."""++import math++import pytest++np = pytest.importorskip("numpy")++from core.rag import config, store, vec_cache+from core.rag.chunking import Chunk+from storage import rag_db++DIM = 16+++def _chunk(i):+ return Chunk(+ text = f"t{i}",+ token_count = 1,+ page_number = None,+ source_page_index = 0,+ chunk_index = i,+ page_char_start = 0,+ page_char_end = 2,+ )+++def _add(+ conn,+ scope,+ doc,+ vectors,+ dim = DIM,+):+ store.create_document(conn, scope = scope, filename = "f", sha256 = doc, document_id = doc)+ store.add_chunks(conn, scope, doc, [_chunk(i) for i in range(len(vectors))], vectors)+++def _vectors(+ n,+ seed = 0,+ dim = DIM,+):+ rng = np.random.default_rng(seed)+ out = rng.standard_normal((n, dim)).astype(np.float32)+ out[::7] *= 9.0 # unnormalised rows+ return out+++def _vec0_matches(conn):+ seen = []+ conn.set_trace_callback(seen.append)+ return seen+++def _search(conn, scope, q, k, monkeypatch, cache):+ monkeypatch.setenv("RAG_VEC_CACHE", "1" if cache else "0")+ return store.search_dense(conn, scope, q, k)+++def _warm(conn, scope, q, monkeypatch):+ _search(conn, scope, q, 5, monkeypatch, True)+ assert vec_cache.drain()+++def _same(a, b):+ assert len(a) == len(b)+ for (ca, sa), (cb, sb) in zip(a, b):+ assert abs(sa - sb) < 1e-5, (ca, sa, cb, sb)+ if not a:+ return+ # Rows tied with the last kept score may be swapped for one another; everything above it must agree.+ edge = a[-1][1] + 1e-5+ assert {c for c, s in a if s > edge} == {c for c, s in b if s > edge}+++def _hit(conn, scope, q, k, monkeypatch):+ seen = _vec0_matches(conn)+ try:+ got = _search(conn, scope, q, k, monkeypatch, True)+ finally:+ conn.set_trace_callback(None)+ assert not [s for s in seen if "MATCH" in s.upper()], "expected a cache hit"+ return got+++def test_cache_matches_vec0_on_unnormalised_nan_zero_and_tied_rows(rag_conn, monkeypatch):+ rows = _vectors(300)+ rows[5] = np.nan+ rows[9] = 0.0+ rows[11] = rows[12] = rows[13] # ties+ _add(rag_conn, "kb_a", "d", rows)+ q = rows[13] * 3 + 0.01+ _warm(rag_conn, "kb_a", q, monkeypatch)+ for k in (1, 5, 30, 200, 400):+ want = _search(rag_conn, "kb_a", q, k, monkeypatch, False)+ got = _hit(rag_conn, "kb_a", q, k, monkeypatch)+ _same(got, want)+ assert "d:5" not in {c for c, _ in got} and "d:9" not in {c for c, _ in got}+++def test_zero_query_returns_nothing_on_both_paths(rag_conn, monkeypatch):+ _add(rag_conn, "kb_a", "d", _vectors(20))+ _warm(rag_conn, "kb_a", _vectors(1)[0], monkeypatch)+ zero = [0.0] * DIM+ assert _hit(rag_conn, "kb_a", zero, 5, monkeypatch) == []+ assert _search(rag_conn, "kb_a", zero, 5, monkeypatch, False) == []+++def test_every_writer_moves_the_epoch(rag_conn, monkeypatch):+ def epoch(scope = "kb_a"):+ return vec_cache.read_epoch(rag_conn, scope)++ e0 = epoch()+ _add(rag_conn, "kb_a", "d1", _vectors(3))+ e1 = epoch()+ assert e1[:2] == e0[:2] and e1[2] > e0[2]+ monkeypatch.setattr(config, "effective_embedding_model", lambda fresh = False: "m")+ assert store.replace_document_vectors(+ rag_conn, "d1", None, ["d1:0", "d1:1", "d1:2"], _vectors(3, seed = 1), "m2", "m"+ )+ e2 = epoch()+ assert e2[0] > e1[0]+ source = dict(rag_conn.execute("SELECT * FROM documents WHERE id='d1'").fetchone())+ store.copy_documents(rag_conn, [(source, None)], "kb_b", thread_id = "t")+ rag_conn.commit()+ assert epoch("kb_b")[2] > 0+ store.delete_document(rag_conn, "d1")+ assert epoch()[0] > e2[0]+ # Width change: no chunks row moves, the global epoch does.+ g = epoch()[1]+ _add(rag_conn, "kb_c", "w", _vectors(2, dim = DIM * 2), dim = DIM * 2)+ assert epoch()[1] == g + 1+++def test_append_extends_the_entry_without_a_rebuild(rag_conn, monkeypatch):+ _add(rag_conn, "kb_a", "d1", _vectors(50))+ q = _vectors(1, seed = 3)[0]+ _warm(rag_conn, "kb_a", q, monkeypatch)+ _add(rag_conn, "kb_a", "d2", [q * 2])+ got = _hit(rag_conn, "kb_a", q, 3, monkeypatch)+ assert got[0][0] == "d2:0"+ _same(got, _search(rag_conn, "kb_a", q, 3, monkeypatch, False))+++ "writer", ["reembed", "copy_into", "delete_doc", "delete_scope", "raw_sql", "raw_sql_insert"]+)+def test_no_stale_answer_after_any_write(rag_conn, monkeypatch, writer):+ _add(rag_conn, "kb_a", "d1", _vectors(40))+ _add(rag_conn, "kb_a", "d2", _vectors(40, seed = 2))+ q = _vectors(1, seed = 4)[0]+ _warm(rag_conn, "kb_a", q, monkeypatch)+ _hit(rag_conn, "kb_a", q, 10, monkeypatch)+ if writer == "reembed":+ monkeypatch.setattr(config, "effective_embedding_model", lambda fresh = False: "m")+ flipped = _vectors(40, seed = 9)+ flipped[17] = q+ ids = [f"d1:{i}" for i in range(40)]+ assert store.replace_document_vectors(rag_conn, "d1", None, ids, flipped, "m", "m")+ elif writer == "copy_into":+ _add(rag_conn, "kb_src", "s", [q])+ source = dict(rag_conn.execute("SELECT * FROM documents WHERE id='s'").fetchone())+ store.copy_documents(rag_conn, [(source, None)], "kb_a", thread_id = "t")+ rag_conn.commit()+ elif writer == "delete_doc":+ store.delete_document(rag_conn, "d2")+ elif writer == "delete_scope":+ for doc in ("d1", "d2"):+ store.delete_document(rag_conn, doc)+ elif writer == "raw_sql_insert":+ # An older build appending rows never calls note_append; the scope's newest rowid still moves.+ other = rag_db.get_connection()+ try:+ other.execute(+ "INSERT INTO chunks(id, document_id, scope, chunk_index, text) "+ "VALUES('d2:99', 'd2', 'kb_a', 99, 'x')"+ )+ other.execute(+ "INSERT INTO chunks_vec(scope, chunk_id, embedding) VALUES('kb_a', 'd2:99', ?)",+ (np.asarray(q, dtype = np.float32).tobytes(),),+ )+ other.commit()+ finally:+ other.close()+ else:+ # An older build deleting rows knows nothing of the cache; the triggers still fire.+ other = rag_db.get_connection()+ try:+ other.execute(+ "DELETE FROM chunks_vec WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id='d1')"+ )+ other.execute("DELETE FROM chunks WHERE document_id='d1'")+ other.commit()+ finally:+ other.close()+ for _ in range(2):+ want = _search(rag_conn, "kb_a", q, 10, monkeypatch, False)+ got = _search(rag_conn, "kb_a", q, 10, monkeypatch, True)+ _same(got, want)+ vec_cache.drain()+ _same(_hit(rag_conn, "kb_a", q, 10, monkeypatch), want)+++def test_a_reader_snapshot_never_sees_a_later_commit(rag_conn, monkeypatch):+ _add(rag_conn, "kb_a", "d1", _vectors(30))+ q = _vectors(1, seed = 5)[0]+ _warm(rag_conn, "kb_a", q, monkeypatch)+ rag_conn.execute("BEGIN")+ try:+ before = _search(rag_conn, "kb_a", q, 5, monkeypatch, True)+ writer = rag_db.get_connection()+ try:+ _add(writer, "kb_a", "late", [q])+ # Same chunk ids, new vectors: only the epoch tells the old snapshot these are not its rows.+ monkeypatch.setattr(config, "effective_embedding_model", lambda fresh = False: "m")+ moved = _vectors(30, seed = 8)+ moved[3] = q+ ids = [f"d1:{i}" for i in range(30)]+ assert store.replace_document_vectors(writer, "d1", None, ids, moved, "m", "m")+ finally:+ writer.close()+ vec_cache.drain()+ _search(rag_conn, "kb_a", q, 5, monkeypatch, True)+ vec_cache.drain()+ during = _search(rag_conn, "kb_a", q, 5, monkeypatch, True)+ finally:+ rag_conn.commit()+ _same(during, before)+ assert "late:0" not in {c for c, _ in during} and during[0][0] != "d1:3"+ after = _search(rag_conn, "kb_a", q, 5, monkeypatch, True)+ assert {after[0][0], after[1][0]} == {"late:0", "d1:3"}++[email protected]("mode", ["off", "no_numpy", "over_budget", "raises"])+def test_fallbacks_answer_like_vec0(rag_conn, monkeypatch, mode):+ _add(rag_conn, "kb_a", "d1", _vectors(60))+ q = _vectors(1, seed = 6)[0]+ want = _search(rag_conn, "kb_a", q, 10, monkeypatch, False)+ if mode == "off":+ monkeypatch.setenv("RAG_VEC_CACHE", "0")+ elif mode == "no_numpy":+ monkeypatch.setattr(vec_cache, "_np", lambda: None)+ elif mode == "over_budget":+ monkeypatch.setenv("RAG_VEC_CACHE_MB", "0.001")+ else:+ _warm(rag_conn, "kb_a", q, monkeypatch)++ def boom(*_a, **_k):+ raise RuntimeError("injected")++ monkeypatch.setattr(vec_cache, "_search_entry", boom)+ if mode != "off":+ monkeypatch.setenv("RAG_VEC_CACHE", "1")+ for _ in range(2):+ assert store.search_dense(rag_conn, "kb_a", q, 10) == want+ vec_cache.drain()+ if mode == "over_budget":+ assert not vec_cache._entries+++def test_a_database_without_the_epoch_table_still_serves(rag_conn, monkeypatch):+ for name in (+ "rag_vec_epoch_chunk_delete",+ "rag_vec_epoch_document_model",+ "rag_vec_epoch_document_delete",+ ):+ rag_conn.execute(f"DROP TRIGGER {name}")+ rag_conn.execute("DROP TABLE rag_vec_epoch")+ rag_conn.commit()+ _add(rag_conn, "kb_a", "d1", _vectors(20))+ q = _vectors(1, seed = 7)[0]+ for _ in range(2):+ got = _search(rag_conn, "kb_a", q, 5, monkeypatch, True)+ vec_cache.drain()+ assert got == _search(rag_conn, "kb_a", q, 5, monkeypatch, False)+ assert not vec_cache._entries+ assert math.isfinite(got[0][1])+++def test_the_builder_opens_and_closes_through_the_connection_gate(monkeypatch, tmp_path):+ from core.rag import vec_cache+ from storage import sqlite_gate++ opened = []+ real = sqlite_gate.connect+ monkeypatch.setattr(sqlite_gate, "connect", lambda *a, **kw: opened.append(a) or real(*a, **kw))+ conn = vec_cache._connect(str(tmp_path / "x.db"))+ assert isinstance(conn, sqlite_gate.GatedConnection) and len(opened) == 1+ conn.close()