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: HNSW (usearch) tier for gigantic RAG scopes, kept consistent with SQLite (#16145)
Daniel Han5c1dc912ac94
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.pyindex 280fc8a9441..577e3c0f987 100644--- a/studio/backend/core/rag/store.py+++ b/studio/backend/core/rag/store.py@@ -407,11 +407,12 @@ def add_chunks(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] = []+ chunk_rowids: list[int] = []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 Noneregions_json = json.dumps(chunk_regions) if chunk_regions else None- conn.execute(+ 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, "@@ -433,6 +434,7 @@ def add_chunks(regions_json,),)+ chunk_rowids.append(cur.lastrowid)conn.execute("INSERT INTO chunks_fts(text, chunk_id, scope) VALUES(?,?,?)",(chunk.text, chunk_id, scope),@@ -463,6 +465,7 @@ def add_chunks(vec_rowids,[f"{document_id}:{chunk.chunk_index}" for chunk in chunks[: len(vec_rowids)]],vectors[: len(vec_rowids)],+ chunk_rowids = chunk_rowids,)diff --git a/studio/backend/core/rag/vec_ann.py b/studio/backend/core/rag/vec_ann.pynew file mode 100644index 00000000000..193b6bf5127--- /dev/null+++ b/studio/backend/core/rag/vec_ann.py@@ -0,0 +1,155 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""HNSW (usearch) over a scope's unit rows, keyed by ``chunks.rowid``, plus an exact delta for rows added after the+build. Pure numpy + usearch: no SQLite here; ``vec_cache`` decides when an index may answer."""++from __future__ import annotations++import json+import logging+import os+from dataclasses import dataclass, field++logger = logging.getLogger(__name__)++DTYPE = "f16"+CONNECTIVITY = 16+EXPANSION_ADD = 128+# Fixed at load, not per query: the index is shared across threads. usearch still returns k > expansion.+EXPANSION_SEARCH = 256+FORMAT = 1+++def usearch():+ """The usearch.index module, or None when the wheel is missing or does not load on this machine."""+ try:+ from usearch import index+ except Exception: # noqa: BLE001 - any load failure leaves the exact / vec0 paths+ return None+ return index+++@dataclass(frozen = True)+class Ann:+ """One published generation: a (usually memory-mapped) index plus the exact rows newer than it."""++ index: object+ n: int+ path: str | None+ delta_keys: object+ delta_mat: object+ meta: dict = field(default_factory = dict)++ @property+ def size(self) -> int:+ return self.n + len(self.delta_keys)+++def new_index(dim: int):+ return usearch().Index(+ ndim = int(dim),+ metric = "cos",+ dtype = DTYPE,+ connectivity = CONNECTIVITY,+ expansion_add = EXPANSION_ADD,+ )+++def add(np, index, keys, rows, threads: int) -> int:+ """Add float32 rows; NaN / inf / zero rows (vec0 scores them NULL) are skipped. Returns rows added."""+ rows = np.asarray(rows, dtype = np.float32)+ with np.errstate(all = "ignore"):+ norms = np.sqrt(np.einsum("ij,ij->i", rows, rows))+ valid = np.isfinite(norms) & (norms > 0)+ if not valid.all():+ rows, keys = rows[valid], np.asarray(keys)[valid]+ if len(rows):+ index.add(np.asarray(keys, dtype = np.uint64), rows, threads = threads)+ return len(rows)+++def unit_rows(np, keys, rows):+ """(keys, unit float32 rows) with unscorable rows dropped: the exact delta's form."""+ rows = np.array(rows, dtype = np.float32)+ with np.errstate(all = "ignore"):+ norms = np.sqrt(np.einsum("ij,ij->i", rows, rows))+ valid = np.isfinite(norms) & (norms > 0)+ rows /= norms[:, None]+ return np.asarray(keys, dtype = np.int64)[valid], rows[valid]+++def with_delta(np, ann: Ann, keys, rows) -> Ann:+ """A new generation sharing the index, with ``rows`` (already unit) appended to the delta."""+ return Ann(+ ann.index,+ ann.n,+ ann.path,+ np.concatenate([ann.delta_keys, keys]),+ np.concatenate([ann.delta_mat, rows]) if len(ann.delta_mat) else rows,+ ann.meta,+ )+++def search(np, ann: Ann, q, fetch: int):+ """(keys int64, cosine distances float64) of the ``fetch`` nearest, ascending, ties by key. ``q`` is unit."""+ f = min(int(fetch), ann.size)+ keys, dist = [], []+ if ann.n and f:+ # Near-full fetches (widening) brute-force the stored rows: no graph reachability limit.+ m = ann.index.search(q, min(f, ann.n), exact = 2 * f >= ann.n)+ keys.append(np.asarray(m.keys, dtype = np.int64))+ dist.append(np.asarray(m.distances, dtype = np.float64))+ if len(ann.delta_keys) and f:+ d = 1.0 - (ann.delta_mat @ q).astype(np.float64)+ keys.append(ann.delta_keys)+ dist.append(d)+ if not keys:+ return np.empty(0, np.int64), np.empty(0, np.float64)+ keys, dist = np.concatenate(keys), np.concatenate(dist)+ order = np.lexsort((keys, dist))[:f]+ return keys[order], dist[order]+++def save(index, base: str, meta: dict) -> str:+ """Write ``base``.usearch + ``base``.json via temp names and ``os.replace``; returns the index path."""+ path, meta_path = base + ".usearch", base + ".json"+ index.save(path + ".tmp")+ os.replace(path + ".tmp", path)+ with open(meta_path + ".tmp", "w", encoding = "utf-8") as fh:+ json.dump({**meta, "format": FORMAT}, fh)+ os.replace(meta_path + ".tmp", meta_path)+ return path+++def load(base: str, dim: int):+ """(view index, meta) for a saved generation, or None if missing, mismatched or unreadable."""+ mod = usearch()+ if mod is None:+ return None+ try:+ with open(base + ".json", encoding = "utf-8") as fh:+ meta = json.load(fh)+ if meta.get("format") != FORMAT or int(meta.get("dim", -1)) != int(dim):+ return None+ index = mod.Index.restore(base + ".usearch", view = True)+ if index is None or index.ndim != int(dim) or len(index) != int(meta.get("n", -1)):+ return None+ index.expansion_search = EXPANSION_SEARCH+ return index, meta+ except Exception: # noqa: BLE001 - a corrupt or foreign file is rebuilt+ logger.debug("vec_ann.load failed for %s", base, exc_info = True)+ return None+++def remove_files(base: str) -> bool:+ """Delete a generation's files; False when one is still mapped (Windows) and must be retried later."""+ ok = True+ for suffix in (".usearch", ".json", ".usearch.tmp", ".json.tmp"):+ try:+ os.remove(base + suffix)+ except FileNotFoundError:+ pass+ except OSError:+ ok = False+ return okdiff --git a/studio/backend/core/rag/vec_cache.py b/studio/backend/core/rag/vec_cache.pyindex d649b74794e..4e13a03a862 100644--- a/studio/backend/core/rag/vec_cache.py+++ b/studio/backend/core/rag/vec_cache.py@@ -1,14 +1,16 @@# 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.+"""In-memory per-scope float32 matrices answering dense KNN exactly, in place of vec0's scalar scan; scopes of+``RAG_VEC_ANN_MIN_ROWS`` or more get a saved, memory-mapped HNSW index (``vec_ann``) instead.SQLite stays authoritative: triggers bump ``rag_vec_epoch`` for a scope in the same transaction as any write thatcan 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."""+Anything else (miss, stale, over budget, no numpy / usearch, any error) returns None and the caller scans vec0."""from __future__ import annotations+import hashlibimport loggingimport osimport sqlite3@@ -16,6 +18,8 @@ import threadingfrom collections import OrderedDictfrom dataclasses import dataclass+from . import vec_ann+logger = logging.getLogger(__name__)GLOBAL_SCOPE = ""@@ -105,11 +109,23 @@ class _Entry:nbytes: int+@dataclass(frozen = True)+class _AnnEntry:+ """``epoch`` = (scope epoch, global epoch, newest chunks.rowid covered by index + delta)."""++ epoch: tuple+ ann: object+ base: str | None++_entries: OrderedDict[tuple, _Entry] = OrderedDict()+_ann: OrderedDict[tuple, _AnnEntry] = OrderedDict()+_stale_files: set[str] = set()_too_big: dict[tuple, int] = {}_bytes = 0_lock = threading.Lock()_pending: set[tuple] = set()+_building: set[tuple] = set()_cond = threading.Condition(_lock)_worker: threading.Thread | None = None_busy = 0@@ -154,7 +170,11 @@ def _publish(if entry is None:returnif entry.nbytes > _budget():- _too_big[key] = entry.epoch+ # A scope that outgrew the exact cache through appends moves to HNSW now, not at its next write.+ if entry.n >= _ann_min_rows() and ann_enabled():+ _schedule(key)+ else:+ _too_big[key] = entry.epochreturn_entries[key] = entry_bytes += entry.nbytes@@ -177,15 +197,23 @@ def search(conn, db_file: str, scope: str, vector, fetch: int):key = _key(db_file, scope, len(vector))with _lock:entry = _entries.get(key)+ ann = _ann.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)+ # ANN answers only at the reader's exact epoch: rows added elsewhere are not in its delta yet.+ if ann is None or ann.epoch != epoch:+ ann = None+ if _too_big.get(key) != epoch:+ _schedule(key)+ else:+ _ann.move_to_end(key)+ if entry is not None:+ return _search_entry(np, entry, vector, fetch)+ if ann is not None:+ return _search_ann(conn, np, ann, vector, fetch)+ return Noneexcept Exception: # noqa: BLE001 - vec0 answers insteadlogger.debug("vec_cache.search failed", exc_info = True)return None@@ -230,8 +258,84 @@ def _search_entry(np, entry: _Entry, vector, fetch: int):return [(ids[i], 1.0 - float(s)) for i, s in zip(idx[order], best[order])], n+_ANN_MAX_FETCH = 16384+++def ann_enabled() -> bool:+ return os.environ.get("RAG_VEC_ANN", "1") != "0" and vec_ann.usearch() is not None+++def _ann_min_rows() -> int:+ try:+ return int(os.environ.get("RAG_VEC_ANN_MIN_ROWS", "100000"))+ except ValueError:+ return 100000+++def _ann_threads() -> int:+ # usearch 2.26 strands a few nodes (unreachable at any k) when inserting in parallel: build on one thread.+ return 1+++def _search_ann(conn, np, entry: _AnnEntry, vector, fetch: int):+ """HNSW candidates (+ exact delta), keys resolved to chunk ids in the reader's own snapshot."""+ ann = entry.ann+ cap = min(ann.size, _ANN_MAX_FETCH)+ q = np.array(vector, dtype = np.float32)+ qn = float(np.sqrt(np.dot(q, q)))+ if not np.isfinite(qn) or qn == 0.0 or not ann.size:+ return [], cap+ q /= qn+ keys, dist = vec_ann.search(np, ann, q, min(int(fetch), cap))+ ids: dict[int, str] = {}+ flat = keys.tolist()+ for s0 in range(0, len(flat), _ID_BATCH):+ batch = flat[s0 : s0 + _ID_BATCH]+ for rowid, cid in conn.execute(+ f"SELECT rowid, id FROM chunks WHERE rowid IN ({','.join('?' * len(batch))})", batch+ ):+ ids[rowid] = cid+ return [(ids[k], float(d)) for k, d in zip(flat, dist.tolist()) if k in ids], cap+++_ID_BATCH = 900+++def _note_ann_append(np, key, before, after, appended, chunk_rowids, rows) -> None:+ """Under _lock. Rows a committed pure append added join the exact delta; anything else drops the entry."""+ entry = _ann.get(key)+ if entry is None:+ return+ if (+ chunk_rowids is None+ or after[:2] != before[:2]+ or appended != len(chunk_rowids)+ or entry.epoch != before+ ):+ _ann.pop(key, None)+ return+ keys, unit = vec_ann.unit_rows(np, chunk_rowids, rows)+ ann = vec_ann.with_delta(np, entry.ann, keys, unit)+ _ann[key] = _AnnEntry(after, ann, entry.base)+ if len(ann.delta_keys) > _delta_limit(ann.n):+ _schedule(key)+++def _delta_limit(n: int) -> int:+ """Most exact delta rows kept beside an index of ``n`` rows before it is rebuilt."""+ return max(20000, n // 20)++def note_append(- db_file: str, scope: str, before, after, appended: int, rowids, chunk_ids, vectors+ db_file: str,+ scope: str,+ before,+ after,+ appended: int,+ rowids,+ chunk_ids,+ vectors,+ chunk_rowids = None,) -> 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."""@@ -245,6 +349,7 @@ def note_append(key = _key(db_file, scope, dim)rows = np.array(vectors, dtype = np.float32).reshape(len(rowids), dim)with _lock:+ _note_ann_append(np, key, before, after, appended, chunk_rowids, rows)entry = _entries.get(key)if entry is None:return@@ -264,7 +369,7 @@ def note_append(def _schedule(key: tuple) -> None:"""Under _lock."""global _worker- if key in _pending:+ if key in _pending or key in _building:return_pending.add(key)if _worker is None or not _worker.is_alive():@@ -280,6 +385,7 @@ def _run() -> None:while not _pending:_cond.wait()key = _pending.pop()+ _building.add(key)_busy += 1try:_build(key)@@ -287,6 +393,7 @@ def _run() -> None:logger.debug("vec_cache build failed for %s", key[2], exc_info = True)finally:with _lock:+ _building.discard(key)_busy -= 1_cond.notify_all()@@ -320,6 +427,15 @@ def _build(key: tuple) -> None:if epoch is None or rag_db.vec_table_dim(conn) != dim:returncount = conn.execute("SELECT count(*) FROM chunks WHERE scope=?", (scope,)).fetchone()[0]+ if count >= _ann_min_rows() and ann_enabled():+ try:+ _build_ann(np, conn, key, epoch)+ except Exception:+ # A build takes minutes: never retry it at the same epoch.+ with _lock:+ _too_big[key] = epoch+ raise+ returnif count * (dim * 4 + 8 + _ID_OVERHEAD) > _budget():with _lock:_too_big[key] = epoch@@ -343,6 +459,152 @@ def _build(key: tuple) -> None:_publish(key, entry)+def _ann_dir(db_file: str) -> str:+ return os.path.join(os.path.dirname(os.path.abspath(db_file)), "rag_ann")+++def _ann_prefix(key: tuple) -> str:+ db_file, ino, scope, dim = key+ return hashlib.sha1(f"{db_file}|{ino}|{scope}|{dim}".encode()).hexdigest()[:20]+++def _saved_generations(key: tuple) -> list[tuple[tuple, str]]:+ """[((scope epoch, global epoch, max rowid), base)] of this scope's generations on disk."""+ d, prefix = _ann_dir(key[0]), _ann_prefix(key)+ out = []+ try:+ names = os.listdir(d)+ except OSError:+ return out+ for name in names:+ if name.startswith(prefix + "-") and name.endswith(".json"):+ try:+ epoch = tuple(int(p) for p in name[len(prefix) + 1 : -5].split("-"))+ except ValueError:+ continue+ if len(epoch) == 3:+ out.append((epoch, os.path.join(d, name[:-5])))+ return out+++def _delta_since(np, conn, scope: str, dim: int, after_rowid: int):+ """(keys, unit rows) of the scope's chunks newer than ``after_rowid``: one vec0 partition scan."""+ wanted = dict(+ conn.execute(+ "SELECT id, rowid FROM chunks WHERE scope=? AND rowid > ?", (scope, after_rowid)+ ).fetchall()+ )+ keys, rows = [], []+ if wanted:+ for cid, emb in conn.execute(+ "SELECT chunk_id, embedding FROM chunks_vec WHERE scope=?", (scope,)+ ):+ if cid in wanted:+ keys.append(wanted[cid])+ rows.append(np.frombuffer(emb, dtype = np.float32))+ if not rows:+ return np.empty(0, np.int64), np.empty((0, dim), np.float32)+ return vec_ann.unit_rows(np, keys, np.stack(rows))+++def _build_ann(np, conn, key: tuple, epoch: tuple) -> None:+ """In ``conn``'s read snapshot: reuse a saved generation at this epoch (catching up appends) or build one."""+ _, _, scope, dim = key+ saved = [(e, b) for e, b in _saved_generations(key) if e[:2] == epoch[:2] and e[2] <= epoch[2]]+ loaded = None+ for e, base in sorted(saved, reverse = True):+ loaded = vec_ann.load(base, dim)+ if loaded is not None:+ break+ if loaded is not None:+ index, meta = loaded+ # Counted before any vector is read: a large catch-up goes straight to the streamed rebuild.+ newer = conn.execute(+ "SELECT count(*) FROM chunks WHERE scope=? AND rowid > ?", (scope, e[2])+ ).fetchone()[0]+ if newer <= _delta_limit(len(index)):+ keys, unit = _delta_since(np, conn, scope, dim, e[2])+ ann = vec_ann.Ann(index, len(index), base + ".usearch", keys, unit, meta)+ _publish_ann(key, _AnnEntry(epoch, ann, base))+ return+ loaded = index = None+ index = vec_ann.new_index(dim)+ cur = conn.execute(+ # CROSS JOIN keeps vec0 as the outer scan; chunks is probed by its primary key.+ "SELECT c.rowid, v.embedding FROM chunks_vec v CROSS JOIN chunks c ON c.id = v.chunk_id "+ "WHERE v.scope=? AND c.rowid <= ?",+ (scope, epoch[2]),+ )+ while rows := cur.fetchmany(_FETCH):+ blk = np.frombuffer(b"".join(r[1] for r in rows), dtype = np.float32).reshape(len(rows), dim)+ vec_ann.add(np, index, [r[0] for r in rows], blk, _ann_threads())+ conn.rollback()+ os.makedirs(_ann_dir(key[0]), exist_ok = True)+ base = os.path.join(_ann_dir(key[0]), f"{_ann_prefix(key)}-{epoch[0]}-{epoch[1]}-{epoch[2]}")+ meta = {"dim": dim, "n": len(index), "epoch": list(epoch), "scope": scope}+ vec_ann.save(index, base, meta)+ del index+ loaded = vec_ann.load(base, dim)+ if loaded is None:+ return+ view, meta = loaded+ empty = np.empty(0, np.int64), np.empty((0, dim), np.float32)+ _publish_ann(+ key, _AnnEntry(epoch, vec_ann.Ann(view, len(view), base + ".usearch", *empty, meta), base)+ )+++def _publish_ann(key: tuple, entry: _AnnEntry) -> None:+ with _lock:+ _ann[key] = entry+ _ann.move_to_end(key)+ for _, base in _saved_generations(key):+ if base != entry.base:+ _stale_files.add(base)+ _stale_files.update(_enforce_disk_cap(_ann_dir(key[0]), key))+ with _lock:+ keep = {e.base for e in _ann.values()}+ # Windows refuses to delete a file still mapped by a reader: retried at the next publish.+ for base in list(_stale_files):+ if base not in keep and vec_ann.remove_files(base):+ _stale_files.discard(base)+++def _enforce_disk_cap(d: str, newest: tuple) -> list[str]:+ """Bases to delete so ``d`` fits ``RAG_VEC_ANN_DISK_MB`` (default 4096): unpublished files oldest first, then+ least recently used published scopes (evicted from ``_ann``), never ``newest``."""+ try:+ cap = float(os.environ.get("RAG_VEC_ANN_DISK_MB", "4096")) * 2**20+ sizes = {+ os.path.join(d, n[: -len(".usearch")]): os.path.getsize(os.path.join(d, n))+ for n in os.listdir(d)+ if n.endswith(".usearch")+ }+ except (OSError, ValueError):+ return []+ total = sum(sizes.values())+ out = []+ with _lock:+ published = [(k, e.base) for k, e in _ann.items()]+ for base in sorted(+ set(sizes) - {b for _, b in published}, key = lambda b: os.path.getmtime(b + ".usearch")+ ):+ if total <= cap:+ return out+ total -= sizes[base]+ out.append(base)+ for k, base in published:+ if total <= cap:+ break+ if k == newest:+ continue+ with _lock:+ _ann.pop(k, None)+ total -= sizes.get(base, 0)+ out.append(base)+ return out++def _avg_id(store: _Store, n: int) -> int:sample = store.ids[: min(n, 64)]return int(sum(len(c) for c in sample) / len(sample)) if len(sample) else 0@@ -358,6 +620,8 @@ def clear() -> None:global _byteswith _lock:_entries.clear()+ _ann.clear()_too_big.clear()_pending.clear()+ _stale_files.clear()_bytes = 0diff --git a/studio/backend/requirements/no-torch-runtime.txt b/studio/backend/requirements/no-torch-runtime.txtindex b1cd985e4ab..02d42669bfd 100644--- a/studio/backend/requirements/no-torch-runtime.txt+++ b/studio/backend/requirements/no-torch-runtime.txt@@ -112,6 +112,9 @@ pillow==11.3.0; python_version < "3.10"# sqlite-vec publishes win_amd64 only and no sdist; the RAG store treats a missing sqlite_vec as# "RAG unavailable". Same marker as studio.txt: this file is installed directly on an update.sqlite-vec==0.1.9; sys_platform != "win32" or platform_machine != "ARM64"+# HNSW for gigantic scopes, as in studio.txt; --no-deps here, so its native dependency is pinned too.+usearch==2.26.6+numkong==7.8.6# pymupdf publishes a win_arm64 wheel only for 1.28.2 (2.0 has none, so ">=" builds MuPDF from source).pymupdf==1.27.2.3; sys_platform != "win32" or platform_machine != "ARM64"pymupdf==1.28.2; sys_platform == "win32" and platform_machine == "ARM64"diff --git a/studio/backend/requirements/studio.txt b/studio/backend/requirements/studio.txtindex a1ebc3979f5..9097b90ab5c 100644--- a/studio/backend/requirements/studio.txt+++ b/studio/backend/requirements/studio.txt@@ -66,6 +66,9 @@ av>=12.3.0# sqlite-vec publishes win_amd64 only and no sdist, so there is nothing to floor to. The RAG# store treats a missing sqlite_vec as "RAG unavailable".sqlite-vec==0.1.9; sys_platform != "win32" or platform_machine != "ARM64"+# HNSW for gigantic scopes (vec_cache); wheels for every target incl. win_arm64 and macOS 11+. A missing or+# unloadable wheel keeps the exact / vec0 paths.+usearch==2.26.6# pymupdf publishes a win_arm64 wheel only for 1.28.2 (2.0 has none, so ">=" builds MuPDF from source).pymupdf==1.27.2.3; sys_platform != "win32" or platform_machine != "ARM64"pymupdf==1.28.2; sys_platform == "win32" and platform_machine == "ARM64"diff --git a/studio/backend/tests/test_rag_vec_ann.py b/studio/backend/tests/test_rag_vec_ann.pynew file mode 100644index 00000000000..f642e68168b--- /dev/null+++ b/studio/backend/tests/test_rag_vec_ann.py@@ -0,0 +1,131 @@+# 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 HNSW tier's index, delta and files, without SQLite: this file runs on every platform the wheels cover."""++import os++import pytest++np = pytest.importorskip("numpy")+if os.environ.get("CI"):+ # CI installs studio.txt: a missing or unloadable usearch wheel there is a packaging failure, not a skip.+ import usearch # noqa: F401+else:+ pytest.importorskip("usearch")++from core.rag import vec_ann+++def _clustered(+ n,+ dim,+ seed = 0,+):+ rng = np.random.default_rng(seed)+ centers = rng.standard_normal((max(8, n // 200), dim)).astype(np.float32)+ x = centers[rng.integers(0, len(centers), n)] + 0.5 * rng.standard_normal((n, dim)).astype(+ np.float32+ )+ return x * rng.uniform(0.5, 3.0, (n, 1)).astype(np.float32)+++def _exact(rows, keys, q, k):+ unit = rows / np.linalg.norm(rows, axis = 1, keepdims = True)+ order = np.argsort(-(unit @ (q / np.linalg.norm(q))), kind = "stable")[:k]+ return [int(keys[i]) for i in order]+++def _built(rows, keys):+ index = vec_ann.new_index(rows.shape[1])+ vec_ann.add(np, index, keys, rows, threads = 2)+ index.expansion_search = vec_ann.EXPANSION_SEARCH+ empty = np.empty(0, np.int64), np.empty((0, rows.shape[1]), np.float32)+ return vec_ann.Ann(index, len(index), None, *empty)+++def test_search_recalls_the_exact_neighbours():+ rows = _clustered(5000, 32)+ keys = np.arange(5000) * 3 + 7+ ann = _built(rows, keys)+ rng = np.random.default_rng(1)+ hits = 0+ for q in rows[rng.integers(0, 5000, 20)] + 0.01:+ got, dist = vec_ann.search(np, ann, q / np.linalg.norm(q), 30)+ assert list(dist) == sorted(dist)+ hits += len(set(got.tolist()) & set(_exact(rows, keys, q, 30)))+ assert hits / (20 * 30) >= 0.99+++def test_unscorable_rows_are_never_indexed():+ rows = _clustered(200, 16)+ rows[3] = np.nan+ rows[4] = 0.0+ rows[5, 0] = np.inf+ ann = _built(rows, np.arange(200))+ assert ann.n == 197+ got, _ = vec_ann.search(np, ann, rows[6] / np.linalg.norm(rows[6]), 200)+ assert not {3, 4, 5} & set(got.tolist())+++def test_the_delta_is_searched_exactly_with_the_index():+ rows = _clustered(2000, 16)+ ann = _built(rows, np.arange(2000))+ new = _clustered(50, 16, seed = 9)+ keys, unit = vec_ann.unit_rows(np, np.arange(5000, 5050), new)+ merged = vec_ann.with_delta(np, ann, keys, unit)+ assert merged.size == 2050 and ann.size == 2000+ q = new[17] / np.linalg.norm(new[17])+ got, dist = vec_ann.search(np, merged, q, 10)+ assert got[0] == 5017 and abs(dist[0]) < 1e-6+ want = _exact(np.concatenate([rows, new]), list(range(2000)) + list(range(5000, 5050)), q, 10)+ assert len(set(got.tolist()) & set(want)) >= 9+++def test_saved_generation_reloads_mapped_with_the_same_answers(tmp_path):+ rows = _clustered(3000, 24)+ ann = _built(rows, np.arange(3000))+ base = str(tmp_path / "g-1-0-3000")+ vec_ann.save(ann.index, base, {"dim": 24, "n": ann.n})+ view, meta = vec_ann.load(base, 24)+ assert meta["n"] == 3000 and len(view) == 3000+ q = rows[11] / np.linalg.norm(rows[11])+ reloaded = vec_ann.Ann(view, len(view), base + ".usearch", ann.delta_keys, ann.delta_mat)+ assert (+ vec_ann.search(np, reloaded, q, 20)[0].tolist()+ == vec_ann.search(np, ann, q, 20)[0].tolist()+ )+ del view, reloaded+++def test_mismatched_or_corrupt_generations_are_rejected(tmp_path):+ rows = _clustered(300, 8)+ ann = _built(rows, np.arange(300))+ base = str(tmp_path / "g-1-0-300")+ vec_ann.save(ann.index, base, {"dim": 8, "n": ann.n})+ assert vec_ann.load(base, 16) is None+ with open(base + ".usearch", "wb") as fh:+ fh.write(b"junk" * 16)+ assert vec_ann.load(base, 8) is None+ assert vec_ann.load(str(tmp_path / "missing"), 8) is None+++def test_remove_files_deletes_every_part(tmp_path):+ rows = _clustered(100, 8)+ base = str(tmp_path / "g-1-0-100")+ vec_ann.save(_built(rows, np.arange(100)).index, base, {"dim": 8, "n": 100})+ assert vec_ann.remove_files(base)+ assert not list(tmp_path.iterdir())+++def test_rows_added_with_the_build_threads_stay_reachable():+ from core.rag import vec_cache++ # Parallel inserts strand nodes in usearch 2.26; the build's thread count must not.+ rows = _clustered(6000, 16, seed = 5)+ index = vec_ann.new_index(16)+ vec_ann.add(np, index, np.arange(6000), rows, threads = vec_cache._ann_threads())+ index.expansion_search = vec_ann.EXPANSION_SEARCH+ unit = rows / np.linalg.norm(rows, axis = 1, keepdims = True)+ sample = np.random.default_rng(2).choice(6000, 300, replace = False)+ assert all(int(index.search(unit[i], 1).keys[0]) == i for i in sample)diff --git a/studio/backend/tests/test_rag_vec_cache_ann.py b/studio/backend/tests/test_rag_vec_cache_ann.pynew file mode 100644index 00000000000..a28247ea833--- /dev/null+++ b/studio/backend/tests/test_rag_vec_cache_ann.py@@ -0,0 +1,245 @@+# 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 HNSW tier answers only at the reader's epoch, keeps appends in its exact delta, and falls back to vec0 on+deletes, re-embeds and a missing wheel."""++import os++import pytest++np = pytest.importorskip("numpy")+if os.environ.get("CI"):+ import usearch # noqa: F401+else:+ pytest.importorskip("usearch")++from core.rag import store, vec_ann, vec_cache++DIM = 16++[email protected](autouse = True)+def _small_ann(monkeypatch):+ monkeypatch.setenv("RAG_VEC_ANN_MIN_ROWS", "50")+ monkeypatch.setenv("RAG_VEC_CACHE", "1")+ vec_cache.clear()+ yield+ vec_cache.drain()+ vec_cache.clear()+++def _chunk(i):+ from core.rag.chunking import Chunk+ 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):+ 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):+ return np.random.default_rng(seed).standard_normal((n, DIM)).astype(np.float32)+++def _dense(+ conn,+ q,+ k = 10,+):+ seen = []+ conn.set_trace_callback(seen.append)+ try:+ hits = store.search_dense(conn, "kb", q, k)+ finally:+ conn.set_trace_callback(None)+ return hits, any("MATCH" in s.upper() for s in seen)+++def _warm(conn, q):+ _dense(conn, q)+ assert vec_cache.drain(60)+ (entry,) = vec_cache._ann.values()+ return entry+++def test_a_gigantic_scope_is_answered_by_hnsw_not_vec0(rag_conn, monkeypatch):+ rows = _vectors(400)+ _add(rag_conn, "kb", "d", rows)+ _warm(rag_conn, rows[7])+ assert not vec_cache._entries+ hits, scanned = _dense(rag_conn, rows[7], 10)+ assert not scanned and hits[0][0] == "d:7" and hits[0][1] > 0.999+ monkeypatch.setenv("RAG_VEC_CACHE", "0")+ want = store.search_dense(rag_conn, "kb", rows[7], 10)+ assert len({c for c, _ in hits} & {c for c, _ in want}) >= 9+ assert all(abs(a - b) < 2e-3 for (_, a), (_, b) in zip(hits, want))+++def test_appends_join_the_delta_without_a_rebuild(rag_conn):+ _add(rag_conn, "kb", "d", _vectors(300))+ before = _warm(rag_conn, _vectors(1)[0])+ new = _vectors(5, seed = 7)+ _add(rag_conn, "kb", "e", new)+ (after,) = vec_cache._ann.values()+ assert after.base == before.base and len(after.ann.delta_keys) == 5+ hits, scanned = _dense(rag_conn, new[2], 3)+ assert not scanned and hits[0][0] == "e:2"+++def test_a_delete_falls_back_to_vec0_until_the_rebuild(rag_conn):+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ _add(rag_conn, "kb", "x", _vectors(60, seed = 3))+ _warm(rag_conn, rows[1])+ store.delete_document(rag_conn, "x")+ hits, scanned = _dense(rag_conn, rows[1], 20)+ assert scanned and not any(c.startswith("x:") for c, _ in hits)+ assert vec_cache.drain(60)+ hits, scanned = _dense(rag_conn, rows[1], 20)+ assert not scanned and not any(c.startswith("x:") for c, _ in hits)+++def test_a_re_embed_is_never_answered_from_the_old_vectors(rag_conn):+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ _warm(rag_conn, rows[0])+ flipped = -rows+ ids = [f"d:{i}" for i in range(300)]+ doc = rag_conn.execute("SELECT embedding_model FROM documents WHERE id='d'").fetchone()[0]+ from core.rag import config++ model = config.effective_embedding_model(fresh = True)+ assert store.replace_document_vectors(rag_conn, "d", doc, ids, flipped, model, model)+ hits, scanned = _dense(rag_conn, rows[0], 5)+ assert scanned+ assert vec_cache.drain(60)+ hits, scanned = _dense(rag_conn, -rows[0], 5)+ assert not scanned and hits[0][0] == "d:0"+++def test_a_restart_maps_the_saved_generation_instead_of_rebuilding(rag_conn, monkeypatch):+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ first = _warm(rag_conn, rows[4])+ vec_cache.clear()+ monkeypatch.setattr(vec_ann, "new_index", lambda dim: pytest.fail("rebuilt instead of loading"))+ again = _warm(rag_conn, rows[4])+ assert again.base == first.base+ hits, scanned = _dense(rag_conn, rows[4], 3)+ assert not scanned and hits[0][0] == "d:4"+++def test_a_restart_catches_up_appends_made_while_it_was_down(rag_conn, monkeypatch):+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ _warm(rag_conn, rows[4])+ vec_cache.clear()+ monkeypatch.setenv("RAG_VEC_CACHE", "0")+ new = _vectors(4, seed = 11)+ _add(rag_conn, "kb", "e", new)+ monkeypatch.setenv("RAG_VEC_CACHE", "1")+ monkeypatch.setattr(+ vec_ann, "new_index", lambda dim: pytest.fail("rebuilt instead of catching up")+ )+ entry = _warm(rag_conn, new[1])+ assert len(entry.ann.delta_keys) == 4+ hits, scanned = _dense(rag_conn, new[1], 3)+ assert not scanned and hits[0][0] == "e:1"+++def test_superseded_generations_are_deleted(rag_conn):+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ _add(rag_conn, "kb", "x", _vectors(60, seed = 3))+ # Only the path: a held entry keeps its index mapped, and Windows cannot delete a mapped file.+ first = _warm(rag_conn, rows[0]).base+ store.delete_document(rag_conn, "x")+ _dense(rag_conn, rows[0])+ assert vec_cache.drain(60)+ (second,) = vec_cache._ann.values()+ assert second.base != first+ assert not os.path.exists(first + ".usearch")++[email protected]("mode", ["off", "no_wheel"])+def test_without_the_tier_the_exact_and_vec0_paths_answer(rag_conn, monkeypatch, mode):+ if mode == "off":+ monkeypatch.setenv("RAG_VEC_ANN", "0")+ else:+ monkeypatch.setattr(vec_ann, "usearch", lambda: None)+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ _dense(rag_conn, rows[3])+ assert vec_cache.drain(60)+ assert not vec_cache._ann and vec_cache._entries+ hits, scanned = _dense(rag_conn, rows[3], 3)+ assert not scanned and hits[0][0] == "d:3"+++def test_rows_another_writer_added_are_never_missed(rag_conn, monkeypatch):+ # With the cache off for the write, note_append sees nothing: as with a second process or an older build.+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ _warm(rag_conn, rows[0])+ monkeypatch.setenv("RAG_VEC_CACHE", "0")+ new = _vectors(3, seed = 21)+ _add(rag_conn, "kb", "e", new)+ monkeypatch.setenv("RAG_VEC_CACHE", "1")+ hits, scanned = _dense(rag_conn, new[0], 3)+ assert scanned and hits[0][0] == "e:0"+++def test_the_disk_cap_evicts_the_least_recently_used_scope(rag_conn, monkeypatch):+ monkeypatch.setenv("RAG_VEC_ANN_DISK_MB", "0.001")+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ first = _warm(rag_conn, rows[0]).base+ store.create_document(rag_conn, scope = "kb2", filename = "f", sha256 = "e", document_id = "e")+ store.add_chunks(rag_conn, "kb2", "e", [_chunk(i) for i in range(300)], _vectors(300, seed = 4))+ store.search_dense(rag_conn, "kb2", rows[0], 5)+ assert vec_cache.drain(60)+ (only,) = vec_cache._ann.values()+ assert only.base != first and os.path.exists(only.base + ".usearch")+ assert not os.path.exists(first + ".usearch")+ hits, scanned = _dense(rag_conn, rows[0], 3)+ assert scanned and hits[0][0] == "d:0"+++def test_an_exact_entry_that_outgrows_the_budget_moves_to_hnsw(rag_conn, monkeypatch):+ _add(rag_conn, "kb", "d", _vectors(30))+ _dense(rag_conn, _vectors(1)[0])+ assert vec_cache.drain(60)+ (small,) = vec_cache._entries.values()+ monkeypatch.setenv("RAG_VEC_CACHE_MB", str(3 * small.nbytes / 2**20))+ new = _vectors(300, seed = 5)+ _add(rag_conn, "kb", "e", new)+ assert vec_cache.drain(60)+ assert not vec_cache._entries and vec_cache._ann+ hits, scanned = _dense(rag_conn, new[9], 3)+ assert not scanned and hits[0][0] == "e:9"+++def test_a_large_catch_up_rebuilds_without_loading_the_delta(rag_conn, monkeypatch):+ rows = _vectors(300)+ _add(rag_conn, "kb", "d", rows)+ first = _warm(rag_conn, rows[0]).base+ vec_cache.clear()+ monkeypatch.setenv("RAG_VEC_CACHE", "0")+ _add(rag_conn, "kb", "e", _vectors(4, seed = 13))+ monkeypatch.setenv("RAG_VEC_CACHE", "1")+ monkeypatch.setattr(vec_cache, "_delta_limit", lambda n: 2)+ monkeypatch.setattr(+ vec_cache, "_delta_since", lambda *a: pytest.fail("loaded the delta before rebuilding")+ )+ entry = _warm(rag_conn, rows[0])+ assert entry.base != first and entry.ann.n == 304 and not len(entry.ann.delta_keys)