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
perf(studio): reuse embeddings for identical files in linked folders (#11972)
Tom Mathews7bfd700beca0
diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.pyindex 984d78cfe57..c761c99cf06 100644--- a/studio/backend/core/rag/folder_sync.py+++ b/studio/backend/core/rag/folder_sync.py@@ -1485,6 +1485,7 @@ def _reconcile_folder(job_id: str) -> None:model_name = embedding_model,background = False,content_hash = content_hash,+ reuse_identical = not rebuild,)result = ingestion.get_job_status(ingestion_job)if result is None:diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.pyindex fcf0c03927d..bc71b0ed681 100644--- a/studio/backend/core/rag/ingestion.py+++ b/studio/backend/core/rag/ingestion.py@@ -487,6 +487,7 @@ def start_ingestion(linked_relative_path: str | None = None,background: bool = True,content_hash: str | None = None,+ reuse_identical: bool = False,) -> tuple[str, str]:"""Create the document + job rows and spawn the worker, returning``(document_id, job_id)``. A duplicate content hash in this scope returns the@@ -497,7 +498,10 @@ def start_ingestion(reconciliation hashes it to detect content-identical renames) pass that digestthrough instead of paying for a second full read of the file. Must be the lowercasehex sha256 of ``stored_path``; a mismatched value would misfile the document under- the wrong hash, so it is trusted as given and never reverified here."""+ the wrong hash, so it is trusted as given and never reverified here.++ ``reuse_identical`` (dedupe=False only) copies a completed same-hash document's index+ onto a new row instead of re-embedding, keeping per-path ownership for linked folders."""account_path(stored_path)if account_is_retired():raise RuntimeError("Account is retired")@@ -517,6 +521,12 @@ def start_ingestion(# RESERVED lock that long fails concurrent writers with "database is locked".effective_model = model_name or config.effective_embedding_model()effective_identity = embeddings.embedding_identity(effective_model)+ # Prefetch before BEGIN IMMEDIATE: a cold read scans the vec0 partition and would starve other writers.+ prefetched = None+ if reuse_identical and not dedupe:+ candidate = store.reusable_document_by_hash(conn, scope, sha, ext, effective_identity)+ if candidate is not None:+ prefetched = (candidate["id"], store.prefetch_donor_vectors(conn, candidate))# The job lease is committed in the same transaction as the document, so cleanup never observes an# unowned in-flight document.conn.execute("BEGIN IMMEDIATE")@@ -574,6 +584,59 @@ def start_ingestion(store.delete_document(conn, failed["id"], commit = False)_remove_upload(failed.get("stored_path"), keep_path = stored_path)+ if reuse_identical and not dedupe:+ donor = store.reusable_document_by_hash(conn, scope, sha, ext, effective_identity)+ if donor is not None:+ conn.execute("SAVEPOINT reuse_identical")+ reused_id = store.create_document(+ conn,+ scope = scope,+ filename = filename,+ sha256 = sha,+ kb_id = kb_id,+ thread_id = thread_id,+ project_id = project_id,+ status = "completed",+ stored_path = stored_path,+ embedding_model = donor["embedding_model"],+ linked_folder_id = linked_folder_id,+ linked_relative_path = linked_relative_path,+ commit = False,+ )+ donor_chunks = donor["num_chunks"] or 0+ copied = store.copy_document_index(+ conn,+ donor,+ reused_id,+ scope,+ prefetched[1] if prefetched and prefetched[0] == donor["id"] else None,+ )+ if rag_db.vec_table_exists(conn) and copied != donor_chunks:+ # Donor lost vectors: ingest normally rather than copy a dense-search-invisible doc.+ conn.execute("ROLLBACK TO reuse_identical")+ conn.execute("RELEASE reuse_identical")+ logger.info(+ "linked-folder reuse donor %s in scope %s is missing vectors; "+ "falling back to a normal ingest",+ donor["id"],+ scope,+ )+ else:+ conn.execute("RELEASE reuse_identical")+ conn.execute(+ "UPDATE documents SET num_chunks=? WHERE id=?",+ (donor_chunks, reused_id),+ )+ job_id = _new_job(conn, reused_id, scope, status = "completed", progress = 1.0)+ with _jobs_lock:+ _jobs[account_key(job_id)] = queue.Queue()+ _emit(+ job_id,+ {"type": "complete", "num_chunks": donor_chunks, "reused": True},+ )+ _emit(job_id, None)+ return reused_id, job_id+document_id = store.create_document(conn,scope = scope,diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.pyindex 596cb2057dd..969ca2ed87f 100644--- a/studio/backend/core/rag/store.py+++ b/studio/backend/core/rag/store.py@@ -12,10 +12,13 @@ partition key.from __future__ import annotationsimport json+import osimport reimport sqlite3import struct+import threadingimport uuid+from collections import OrderedDictfrom datetime import datetime, timezonefrom storage import rag_db@@ -414,6 +417,28 @@ def document_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> str |return row["id"] if row else None+def reusable_document_by_hash(+ conn: sqlite3.Connection, scope: str, sha256: str, ext: str, identity: str+) -> dict | None:+ """Newest completed, non-empty same-hash document in a live ``scope`` whose index can be+ copied. Extension must match (parsers branch on it) and so must the embedding identity."""+ # rowid DESC is served by idx_documents_hash (no sort over every copy) and is newest-first.+ for row in conn.execute(+ "SELECT * FROM documents WHERE scope=? AND sha256=? AND status='completed' "+ "AND num_chunks > 0 AND NOT EXISTS "+ "(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=documents.scope) "+ "ORDER BY rowid DESC",+ (scope, sha256),+ ):+ doc = dict(row)+ if os.path.splitext(doc["filename"])[1].lower() != ext:+ continue+ if not config.embedding_identity_matches(doc.get("embedding_model"), identity):+ continue+ return doc+ return None++def documents_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> list[dict]:"""Every live copy of this text in the scope, oldest first.@@ -457,6 +482,7 @@ def add_chunks(per-chunk PDF highlight rects, stored as JSON."""if len(vectors):rag_db.ensure_vec(conn, len(vectors[0]))+ vec_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 None@@ -483,11 +509,14 @@ def add_chunks("INSERT INTO chunks_fts(text, chunk_id, scope) VALUES(?,?,?)",(chunk.text, chunk_id, scope),)- conn.execute(- "INSERT INTO chunks_vec(scope, chunk_id, embedding) VALUES(?,?,?)",- (scope, chunk_id, _f32(vector)),+ vec_rowids.append(+ conn.execute(+ "INSERT INTO chunks_vec(scope, chunk_id, embedding) VALUES(?,?,?)",+ (scope, chunk_id, _f32(vector)),+ ).lastrowid)conn.commit()+ _remember_vec_rowids(conn, document_id, vec_rowids)def delete_document(@@ -514,6 +543,124 @@ def delete_document(conn.commit()+def _copy_chunk_rows(+ conn: sqlite3.Connection, source_id: str, target_id: str, scope: str+) -> dict[str, str]:+ """Uncommitted chunk + FTS copy; returns source -> target ids (chunks_vec has no FK)."""+ chunk_ids: dict[str, str] = {}+ for r in conn.execute(+ "SELECT id, chunk_index FROM chunks WHERE document_id=?", (source_id,)+ ).fetchall():+ chunk_ids[r["id"]] = f"{target_id}:{r['chunk_index']}"+ conn.execute(+ "INSERT INTO chunks("+ "id, document_id, scope, chunk_index, text, page_number, "+ "source_page_index, token_count, kind, pdf_regions_json) "+ "SELECT ? || ':' || chunk_index, ?, ?, chunk_index, text, page_number, "+ "source_page_index, token_count, kind, pdf_regions_json "+ "FROM chunks WHERE document_id=?",+ (target_id, target_id, scope, source_id),+ )+ conn.execute(+ "INSERT INTO chunks_fts(text, chunk_id, scope) "+ "SELECT text, id, scope FROM chunks WHERE document_id=?",+ (target_id,),+ )+ return chunk_ids+++# chunks_vec rowids this process wrote, per (db, document): chunk_id is unindexed in vec0, and the next+# copy's donor is usually the one just written. Verified on read.+_VEC_ROWIDS_MAX = 256+_vec_rowids: OrderedDict[tuple[str, str], list[int]] = OrderedDict()+_vec_rowids_lock = threading.Lock()+++def _db_file(conn: sqlite3.Connection) -> str:+ return conn.execute("PRAGMA database_list").fetchone()[2]+++def _remember_vec_rowids(conn: sqlite3.Connection, document_id: str, rowids: list[int]) -> None:+ key = (_db_file(conn), document_id)+ with _vec_rowids_lock:+ _vec_rowids[key] = rowids+ _vec_rowids.move_to_end(key)+ while len(_vec_rowids) > _VEC_ROWIDS_MAX:+ _vec_rowids.popitem(last = False)+++def _donor_vectors_by_rowid(conn: sqlite3.Connection, source: dict, chunk_ids) -> list | None:+ with _vec_rowids_lock:+ rowids = _vec_rowids.get((_db_file(conn), source["id"]))+ if not rowids or len(rowids) != len(chunk_ids):+ return None+ rows = []+ for start in range(0, len(rowids), 500):+ batch = rowids[start : start + 500]+ rows += conn.execute(+ f"SELECT scope, chunk_id, embedding FROM chunks_vec "+ f"WHERE rowid IN ({','.join('?' * len(batch))})",+ batch,+ ).fetchall()+ found = {r["chunk_id"] for r in rows if r["scope"] == source["scope"]}+ return rows if len(rows) == len(found) and found == set(chunk_ids) else None+++def _donor_vectors(conn: sqlite3.Connection, source: dict, chunk_ids) -> list:+ rows = _donor_vectors_by_rowid(conn, source, chunk_ids)+ if rows is not None:+ return rows+ # One pass over the partition: chunk ids are "<document id>:<index>" and ';' sorts right after ':'.+ rows = conn.execute(+ "SELECT scope, chunk_id, embedding FROM chunks_vec "+ "WHERE scope=? AND chunk_id > ? AND chunk_id < ?",+ (source["scope"], f"{source['id']}:", f"{source['id']};"),+ ).fetchall()+ return [r for r in rows if r["chunk_id"] in chunk_ids]+++def prefetch_donor_vectors(conn: sqlite3.Connection, source: dict) -> list | None:+ """Read ``source``'s vector rows outside any write transaction, for copy_document_index."""+ if not rag_db.vec_table_exists(conn):+ return None+ ids = [+ r["id"] for r in conn.execute("SELECT id FROM chunks WHERE document_id=?", (source["id"],))+ ]+ return _donor_vectors(conn, source, ids)+++def copy_document_index(+ conn: sqlite3.Connection,+ source: dict,+ target_id: str,+ scope: str,+ prefetched: list | None = None,+) -> int:+ """Uncommitted chunk + FTS + vector copy; returns vector rows copied (0 without chunks_vec).+ ``prefetched`` (prefetch_donor_vectors) is used only if it still covers exactly the donor's chunks."""+ chunk_ids = _copy_chunk_rows(conn, source["id"], target_id, scope)+ if not rag_db.vec_table_exists(conn):+ return 0+ rows = prefetched+ if (+ rows is None+ or len(rows) != len(chunk_ids)+ or {r["chunk_id"] for r in rows} != chunk_ids.keys()+ # chunks_vec may have been recreated at another width since the prefetch.+ or (rows and len(rows[0]["embedding"]) != 4 * (rag_db.vec_table_dim(conn) or 0))+ ):+ rows = _donor_vectors(conn, source, chunk_ids)+ rowids = [+ conn.execute(+ "INSERT INTO chunks_vec(scope, chunk_id, embedding) VALUES(?,?,?)",+ (scope, chunk_ids[r["chunk_id"]], r["embedding"]),+ ).lastrowid+ for r in rows+ ]+ _remember_vec_rowids(conn, target_id, rowids)+ return len(rows)++def copy_documents(conn: sqlite3.Connection,documents: list[tuple[dict, str | None]],@@ -542,24 +689,7 @@ def copy_documents(conn.execute("UPDATE documents SET num_chunks=? WHERE id=?", (source["num_chunks"], document_id))- for r in conn.execute(- "SELECT id, chunk_index FROM chunks WHERE document_id=?", (source["id"],)- ).fetchall():- chunk_ids[r["id"]] = f"{document_id}:{r['chunk_index']}"- conn.execute(- "INSERT INTO chunks("- "id, document_id, scope, chunk_index, text, page_number, "- "source_page_index, token_count, kind, pdf_regions_json) "- "SELECT ? || ':' || chunk_index, ?, ?, chunk_index, text, page_number, "- "source_page_index, token_count, kind, pdf_regions_json "- "FROM chunks WHERE document_id=?",- (document_id, document_id, scope, source["id"]),- )- conn.execute(- "INSERT INTO chunks_fts(text, chunk_id, scope) "- "SELECT text, id, scope FROM chunks WHERE document_id=?",- (document_id,),- )+ chunk_ids.update(_copy_chunk_rows(conn, source["id"], document_id, scope))if chunk_ids and rag_db.vec_table_exists(conn):# vec0 scans the whole partition for any chunk filter, so read each source scope once.for source_scope in {source["scope"] for source, _ in documents}:diff --git a/studio/backend/tests/test_rag_linked_folders.py b/studio/backend/tests/test_rag_linked_folders.pyindex 96a424e8e58..e32264a6fb6 100644--- a/studio/backend/tests/test_rag_linked_folders.py+++ b/studio/backend/tests/test_rag_linked_folders.py@@ -2547,3 +2547,334 @@ def test_the_ownership_snapshot_survives_an_unloadable_vector_extension(rag_homeassert owned == [folder["id"]]assert folder_sync.get_folder(folder["id"])["status"] == "retired"+++def _spy_on_encode(monkeypatch) -> list[list[str]]:+ from core.rag import embeddings++ calls: list[list[str]] = []+ original = embeddings.encode++ def spy(texts, **kwargs):+ calls.append(list(texts))+ return original(texts, **kwargs)++ monkeypatch.setattr(embeddings, "encode", spy)+ return calls+++def _chunk_texts(document_id: str) -> list[str]:+ with _connection() as conn:+ rows = conn.execute(+ "SELECT text FROM chunks WHERE document_id=? ORDER BY chunk_index", (document_id,)+ ).fetchall()+ return [r["text"] for r in rows]+++def _vectors(document_id: str) -> dict[str, bytes]:+ with _connection() as conn:+ rows = conn.execute(+ "SELECT chunk_id, embedding FROM chunks_vec WHERE chunk_id LIKE ?",+ (f"{document_id}:%",),+ ).fetchall()+ return {row["chunk_id"].rsplit(":", 1)[1]: bytes(row["embedding"]) for row in rows}+++@requires_sqlite_vec+def test_identical_linked_files_copy_one_embedding_instead_of_reembedding(+ rag_home, stub_embeddings, monkeypatch+):+ calls = _spy_on_encode(monkeypatch)+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "c.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "d.txt").write_text("a distinct different body", encoding = "utf-8")++ result = _run(folder["id"])+ assert result["status"] == "completed"+ assert result["added"] == 4++ embedded_texts = [text for call in calls for text in call]+ assert embedded_texts.count("shared duplicate content") == 1+ assert embedded_texts.count("a distinct different body") == 1++ with _connection() as conn:+ rows = conn.execute(+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)+ ).fetchall()+ assert len(rows) == 4+ by_rel = {row["relative_path"]: dict(row) for row in rows}+ documents = {+ rel: store.get_document(conn, row["document_id"]) for rel, row in by_rel.items()+ }+ assert len({d["id"] for d in documents.values()}) == 4+ for rel, doc in documents.items():+ assert doc["linked_relative_path"] == rel+ assert len({d["stored_path"] for d in documents.values()}) == 4++ donor = documents["a.txt"]+ assert donor["num_chunks"] > 0+ for rel in ("b.txt", "c.txt"):+ copy = documents[rel]+ assert copy["num_chunks"] == donor["num_chunks"]+ assert _chunk_texts(copy["id"]) == _chunk_texts(donor["id"])+ assert _vectors(copy["id"]) == _vectors(donor["id"])++ hits = store.search_lexical(conn, folder["scope"], "shared", 10)+ hit_doc_ids = {chunk_id.rsplit(":", 1)[0] for chunk_id, _ in hits}+ assert hit_doc_ids == {+ documents["a.txt"]["id"],+ documents["b.txt"]["id"],+ documents["c.txt"]["id"],+ }+++@requires_sqlite_vec+def test_deleting_a_reused_copy_leaves_its_siblings_intact(rag_home, stub_embeddings):+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "c.txt").write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ with _connection() as conn:+ before = {+ row["relative_path"]: row["document_id"]+ for row in conn.execute(+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)+ ).fetchall()+ }+ survivors = {"a.txt": before["a.txt"], "c.txt": before["c.txt"]}+ deleted_id = before["b.txt"]++ (source / "b.txt").unlink()+ result = _run(folder["id"])+ assert result["status"] == "completed"+ assert result["deleted"] == 1++ with _connection() as conn:+ remaining = {+ row["relative_path"]+ for row in conn.execute(+ "SELECT relative_path FROM linked_folder_files WHERE folder_id=?", (folder["id"],)+ ).fetchall()+ }+ assert remaining == {"a.txt", "c.txt"}+ assert store.get_document(conn, deleted_id) is None+ assert (+ conn.execute(+ "SELECT COUNT(*) AS n FROM chunks WHERE document_id=?", (deleted_id,)+ ).fetchone()["n"]+ == 0+ )+ assert (+ conn.execute(+ "SELECT COUNT(*) AS n FROM chunks_vec WHERE chunk_id LIKE ?", (f"{deleted_id}:%",)+ ).fetchone()["n"]+ == 0+ )+ for doc_id in survivors.values():+ doc = store.get_document(conn, doc_id)+ assert doc is not None and doc["num_chunks"] > 0+ assert _chunk_texts(doc_id)+ assert _vectors(doc_id)+ assert store.search_lexical(conn, folder["scope"], "shared", 10)+++@requires_sqlite_vec+def test_rebuild_reembeds_every_file_even_content_identical_ones(+ rag_home, stub_embeddings, monkeypatch+):+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "c.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "d.txt").write_text("a distinct different body", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ calls = _spy_on_encode(monkeypatch)+ result = _run(folder["id"], rebuild = True)+ assert result["status"] == "completed"++ embedded_texts = [text for call in calls for text in call]+ assert embedded_texts.count("shared duplicate content") == 3+ assert embedded_texts.count("a distinct different body") == 1+++@requires_sqlite_vec+def test_reuse_skips_a_donor_whose_embedding_model_no_longer_matches(+ rag_home, stub_embeddings, monkeypatch+):+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ with _connection() as conn:+ donor_row = _mapping(folder)+ donor = store.get_document(conn, donor_row["document_id"])+ stale_identity = donor["embedding_model"] + "-stale"+ conn.execute(+ "UPDATE documents SET embedding_model=? WHERE id=?", (stale_identity, donor["id"])+ )+ conn.commit()++ calls = _spy_on_encode(monkeypatch)+ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ result = _run(folder["id"])+ assert result["status"] == "completed"+ assert result["added"] == 1++ embedded_texts = [text for call in calls for text in call]+ assert "shared duplicate content" in embedded_texts++ with _connection() as conn:+ new_row = conn.execute(+ "SELECT document_id FROM linked_folder_files WHERE folder_id=? AND relative_path='b.txt'",+ (folder["id"],),+ ).fetchone()+ new_doc = store.get_document(conn, new_row["document_id"])+ assert new_doc["id"] != donor["id"]+ assert new_doc["embedding_model"] == donor["embedding_model"]+ assert _vectors(new_doc["id"])+++@requires_sqlite_vec+def test_reuse_falls_back_to_a_normal_ingest_when_the_donor_lost_its_vectors(+ rag_home, stub_embeddings, monkeypatch+):+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ with _connection() as conn:+ donor_id = _mapping(folder)["document_id"]+ conn.execute("DELETE FROM chunks_vec WHERE chunk_id LIKE ?", (f"{donor_id}:%",))+ conn.commit()++ calls = _spy_on_encode(monkeypatch)+ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ result = _run(folder["id"])+ assert result["status"] == "completed"+ assert result["added"] == 1++ embedded_texts = [text for call in calls for text in call]+ assert "shared duplicate content" in embedded_texts++ with _connection() as conn:+ new_row = conn.execute(+ "SELECT document_id FROM linked_folder_files WHERE folder_id=? AND relative_path='b.txt'",+ (folder["id"],),+ ).fetchone()+ new_doc = store.get_document(conn, new_row["document_id"])+ vecs = _vectors(new_doc["id"])+ assert len(vecs) == new_doc["num_chunks"] > 0+++@requires_sqlite_vec+def test_identical_copies_read_the_donor_vectors_by_rowid(rag_home, stub_embeddings, monkeypatch):+ hits = []+ original = store._donor_vectors_by_rowid++ def spy(conn, source, chunk_ids):+ rows = original(conn, source, chunk_ids)+ hits.append(rows is not None)+ return rows++ monkeypatch.setattr(store, "_donor_vectors_by_rowid", spy)+ source, folder = _folder(rag_home)+ for name in ("a.txt", "b.txt", "c.txt"):+ (source / name).write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ assert hits == [True, True]+ with _connection() as conn:+ ids = [+ r["document_id"]+ for r in conn.execute(+ "SELECT document_id FROM linked_folder_files WHERE folder_id=? ORDER BY relative_path",+ (folder["id"],),+ ).fetchall()+ ]+ assert _vectors(ids[1]) == _vectors(ids[0]) == _vectors(ids[2])+++@requires_sqlite_vec+def test_a_stale_rowid_entry_falls_back_to_the_partition_scan(rag_home, stub_embeddings):+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ (source / "d.txt").write_text("a distinct different body", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ with _connection() as conn:+ by_rel = {+ r["relative_path"]: r["document_id"]+ for r in conn.execute(+ "SELECT relative_path, document_id FROM linked_folder_files WHERE folder_id=?",+ (folder["id"],),+ ).fetchall()+ }+ other = [+ r["rowid"]+ for r in conn.execute(+ "SELECT rowid FROM chunks_vec WHERE chunk_id LIKE ?", (f"{by_rel['d.txt']}:%",)+ ).fetchall()+ ]+ store._remember_vec_rowids(conn, by_rel["a.txt"], other)++ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"+ with _connection() as conn:+ b_id = conn.execute(+ "SELECT document_id FROM linked_folder_files WHERE folder_id=? AND relative_path='b.txt'",+ (folder["id"],),+ ).fetchone()["document_id"]+ assert _vectors(b_id) == _vectors(by_rel["a.txt"])+++@requires_sqlite_vec+def test_donor_vectors_are_read_before_the_write_lock(rag_home, stub_embeddings, monkeypatch):+ in_transaction = []+ original = store._donor_vectors++ def spy(conn, source, chunk_ids):+ in_transaction.append(conn.in_transaction)+ return original(conn, source, chunk_ids)++ monkeypatch.setattr(store, "_donor_vectors", spy)+ source, folder = _folder(rag_home)+ for name in ("a.txt", "b.txt", "c.txt"):+ (source / name).write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"+ assert in_transaction == [False, False]+++@requires_sqlite_vec+def test_a_vec_table_resized_after_the_prefetch_falls_back_to_a_normal_ingest(+ rag_home, stub_embeddings, monkeypatch+):+ source, folder = _folder(rag_home)+ (source / "a.txt").write_text("shared duplicate content", encoding = "utf-8")+ assert _run(folder["id"])["status"] == "completed"++ original = store.prefetch_donor_vectors++ def resize_after_prefetch(conn, donor):+ rows = original(conn, donor)+ with _connection() as other:+ dim = rag_db.vec_table_dim(other)+ rag_db.ensure_vec(other, dim + 1)+ other.commit()+ return rows++ monkeypatch.setattr(store, "prefetch_donor_vectors", resize_after_prefetch)+ (source / "b.txt").write_text("shared duplicate content", encoding = "utf-8")+ result = _run(folder["id"])+ assert result["status"] == "completed"+ assert result["failed"] == 0+ with _connection() as conn:+ b_id = conn.execute(+ "SELECT document_id FROM linked_folder_files WHERE folder_id=? AND relative_path='b.txt'",+ (folder["id"],),+ ).fetchone()["document_id"]+ assert _vectors(b_id)