Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: keep RAG lexical search off the linked-folder filters when nothing is linked (#8394)

Daniel Han3c77be4463fb
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.py
index 1e31bef1f8d..ef49f80fade 100644
--- a/studio/backend/core/rag/store.py
+++ b/studio/backend/core/rag/store.py
@@ -299,6 +299,26 @@ def delete_document(
conn.commit()
+def linked_folder_rows_exist(conn: sqlite3.Connection) -> bool:
+ """Whether anything here can be hidden by the linked-folder filters.
+
+ One EXISTS per thing they hide, so with all three empty the plain query returns the
+ same rows straight out of the FTS index.
+
+ A purged tombstone does not count: every knowledge base delete leaves one for good
+ and its scope keeps no documents, so counting it would end the fast path on the first
+ delete. Folder-owned documents are counted directly, not via `linked_folders`: a
+ crash before `_install_mapping` leaves one that outlives its folder row.
+ """
+ return bool(
+ conn.execute(
+ "SELECT EXISTS(SELECT 1 FROM linked_folders) "
+ "OR EXISTS(SELECT 1 FROM linked_folder_retired_scopes WHERE purged_at IS NULL) "
+ "OR EXISTS(SELECT 1 FROM documents WHERE linked_folder_id IS NOT NULL)"
+ ).fetchone()[0]
+ )
+
+
def search_lexical(conn: sqlite3.Connection, scope, query: str, k: int):
"""BM25 lexical search over one scope or several. Returns
[(chunk_id, score)], higher = better."""
@@ -309,18 +329,39 @@ def search_lexical(conn: sqlite3.Connection, scope, query: str, k: int):
if not scopes:
return []
placeholders = ",".join("?" * len(scopes))
- rows = conn.execute(
- f"SELECT chunks_fts.chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "
- f"JOIN chunks c ON c.id=chunks_fts.chunk_id "
- f"JOIN documents d ON d.id=c.document_id "
- f"WHERE chunks_fts MATCH ? AND chunks_fts.scope IN ({placeholders}) "
- f"AND NOT EXISTS "
- f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
- f"AND (d.linked_folder_id IS NULL OR EXISTS "
- f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id)) "
- f"ORDER BY s LIMIT ?",
- (mq, *scopes, k),
- ).fetchall()
+ # One snapshot for the gate and the read: WAL pins it at the transaction's first
+ # read, so a scope retired in between cannot land rows in a result the gate already
+ # decided to run unfiltered. A caller's own transaction is used instead.
+ own_read_txn = not conn.in_transaction
+ if own_read_txn:
+ conn.execute("BEGIN")
+ try:
+ # The filtered form joins chunks and documents and runs both subqueries for every
+ # matched row BEFORE the LIMIT, so it costs more the commoner the query terms are.
+ # With nothing linked that work is provably wasted (linked_folder_rows_exist).
+ if linked_folder_rows_exist(conn):
+ sql = (
+ f"SELECT chunks_fts.chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "
+ f"JOIN chunks c ON c.id=chunks_fts.chunk_id "
+ f"JOIN documents d ON d.id=c.document_id "
+ f"WHERE chunks_fts MATCH ? AND chunks_fts.scope IN ({placeholders}) "
+ f"AND NOT EXISTS "
+ f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ f"AND (d.linked_folder_id IS NULL OR EXISTS "
+ f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id)) "
+ f"ORDER BY s LIMIT ?"
+ )
+ else:
+ sql = (
+ f"SELECT chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "
+ f"WHERE chunks_fts MATCH ? AND scope IN ({placeholders}) "
+ f"ORDER BY s LIMIT ?"
+ )
+ rows = conn.execute(sql, (mq, *scopes, k)).fetchall()
+ finally:
+ # Read-only, but it has to end: an open snapshot blocks WAL checkpointing.
+ if own_read_txn:
+ conn.commit()
# bm25() is negative (more negative = better); flip to higher-is-better.
return [(r["chunk_id"], -r["s"]) for r in rows]
diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.py
index 1a4b77b7a20..b7cbcad93dd 100644
--- a/studio/backend/routes/rag.py
+++ b/studio/backend/routes/rag.py
@@ -326,13 +326,25 @@ def _scope_for_owner(scope_type: str, scope_id: str) -> str:
)
-def _require_scope_owner(scope_type: str, scope_id: str) -> None:
+def _require_scope_owner(
+ scope_type: str,
+ scope_id: str,
+ conn: sqlite3.Connection | None = None,
+) -> None:
+ """404 unless the scope's owner still exists.
+
+ ``conn`` reuses a connection the caller already holds: sqlite-vec loads per
+ connection, so opening a second one to read a single row pays that twice.
+ """
if scope_type == "knowledge_base":
- conn = _rag_connection()
- try:
+ if conn is not None:
exists = store.get_kb(conn, scope_id) is not None
- finally:
- conn.close()
+ else:
+ owner_conn = _rag_connection()
+ try:
+ exists = store.get_kb(owner_conn, scope_id) is not None
+ finally:
+ owner_conn.close()
detail = "Knowledge base not found"
else:
from storage.studio_db import get_chat_project
@@ -887,22 +899,25 @@ def folder_job_events(
@router.post("/search")
def search(payload: SearchRequest, subject: str = Depends(get_current_subject)) -> dict:
_require_rag()
- if payload.kb_id:
- _require_scope_owner("knowledge_base", payload.kb_id)
- scope = store.kb_scope(payload.kb_id)
- else:
- scopes = []
- if payload.project_id:
- _require_scope_owner("project", payload.project_id)
- scopes.append(store.project_scope(payload.project_id))
- if payload.thread_id:
- scopes.append(store.thread_scope(payload.thread_id))
- if not scopes:
- raise HTTPException(status_code = 400, detail = "Provide kb_id, project_id, or thread_id")
- scope = scopes[0] if len(scopes) == 1 else scopes
-
+ # One connection for the whole request; the ownership check reads a single row.
conn = _rag_connection()
try:
+ if payload.kb_id:
+ _require_scope_owner("knowledge_base", payload.kb_id, conn)
+ scope = store.kb_scope(payload.kb_id)
+ else:
+ scopes = []
+ if payload.project_id:
+ _require_scope_owner("project", payload.project_id, conn)
+ scopes.append(store.project_scope(payload.project_id))
+ if payload.thread_id:
+ scopes.append(store.thread_scope(payload.thread_id))
+ if not scopes:
+ raise HTTPException(
+ status_code = 400, detail = "Provide kb_id, project_id, or thread_id"
+ )
+ scope = scopes[0] if len(scopes) == 1 else scopes
+
if payload.mode == "lexical":
hits = retrieval.retrieve_lexical(conn, scope, payload.query, payload.top_k)
elif payload.mode == "dense":
diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.py
index bdebd311e93..f82ea9c0973 100644
--- a/studio/backend/storage/rag_db.py
+++ b/studio/backend/storage/rag_db.py
@@ -255,6 +255,13 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
conn.execute("ALTER TABLE documents ADD COLUMN linked_folder_id TEXT")
if "linked_relative_path" not in cols:
conn.execute("ALTER TABLE documents ADD COLUMN linked_relative_path TEXT")
+ # After the ALTER that adds the column on an older database. Partial, so it holds only
+ # folder-owned rows and is empty with nothing linked, which keeps the lexical fast-path
+ # gate an index probe rather than a scan of documents.
+ conn.execute(
+ "CREATE INDEX IF NOT EXISTS idx_documents_linked_folder "
+ "ON documents(linked_folder_id) WHERE linked_folder_id IS NOT NULL"
+ )
ensure_linked_folder_columns(conn)
conn.commit()
diff --git a/studio/backend/tests/test_rag_store.py b/studio/backend/tests/test_rag_store.py
index 14df7b44697..07abfb835ec 100644
--- a/studio/backend/tests/test_rag_store.py
+++ b/studio/backend/tests/test_rag_store.py
@@ -156,3 +156,171 @@ def test_kb_delete_rolls_back_when_document_cleanup_fails(rag_conn, monkeypatch)
"doc1",
"doc2",
]
+
+
+def _link_folder(
+ conn,
+ folder_id,
+ scope,
+ path = "/tmp/linked",
+):
+ conn.execute(
+ "INSERT INTO linked_folders(id, scope_type, scope_id, scope, path, name, "
+ "auto_sync, status, created_at, updated_at) "
+ "VALUES(?,?,?,?,?,?,1,'idle','2026-01-01T00:00:00+00:00','2026-01-01T00:00:00+00:00')",
+ (folder_id, "knowledge_base", scope.removeprefix("kb_"), scope, path, "linked"),
+ )
+ conn.commit()
+
+
+def test_lexical_fast_path_only_while_no_folder_rows_exist(rag_conn):
+ """The plain FTS query is used exactly when the filters could not exclude anything."""
+ _add_doc(rag_conn, "kb_a", "d1", "d1.txt", "h1", ["alpha bravo charlie"])
+ assert store.linked_folder_rows_exist(rag_conn) is False
+
+ _link_folder(rag_conn, "f1", "kb_a")
+ assert store.linked_folder_rows_exist(rag_conn) is True
+
+ rag_conn.execute("DELETE FROM linked_folders")
+ rag_conn.execute(
+ "INSERT INTO linked_folder_retired_scopes(scope, retired_at) "
+ "VALUES('kb_a', '2026-01-01T00:00:00+00:00')"
+ )
+ rag_conn.commit()
+ assert store.linked_folder_rows_exist(rag_conn) is True
+
+
+def test_lexical_hides_retired_scope_and_unmapped_linked_document(rag_conn):
+ """The filters still apply once a folder row exists, fast path or not."""
+ _add_doc(rag_conn, "kb_a", "d1", "d1.txt", "h1", ["alpha bravo charlie"])
+ _add_doc(rag_conn, "kb_a", "d2", "d2.txt", "h2", ["alpha delta echo"])
+ _link_folder(rag_conn, "f1", "kb_a")
+ # d2 belongs to a folder but has no mapping row yet, so it is not searchable.
+ rag_conn.execute("UPDATE documents SET linked_folder_id='f1' WHERE id='d2'")
+ rag_conn.commit()
+ assert [cid for cid, _ in store.search_lexical(rag_conn, "kb_a", "alpha", 10)] == ["d1:0"]
+
+ rag_conn.execute(
+ "INSERT INTO linked_folder_files(folder_id, relative_path, size_bytes, mtime_ns, "
+ "document_id, synced_at) VALUES('f1', 'd2.txt', 1, 1, 'd2', "
+ "'2026-01-01T00:00:00+00:00')"
+ )
+ rag_conn.commit()
+ assert sorted(cid for cid, _ in store.search_lexical(rag_conn, "kb_a", "alpha", 10)) == [
+ "d1:0",
+ "d2:0",
+ ]
+
+ rag_conn.execute(
+ "INSERT INTO linked_folder_retired_scopes(scope, retired_at) "
+ "VALUES('kb_a', '2026-01-01T00:00:00+00:00')"
+ )
+ rag_conn.commit()
+ assert store.search_lexical(rag_conn, "kb_a", "alpha", 10) == []
+
+
+def test_lexical_results_match_across_both_query_forms(rag_conn):
+ """The fast path is a shortcut in work, not in behaviour."""
+ for i in range(12):
+ _add_doc(
+ rag_conn, "kb_a", f"d{i}", f"d{i}.txt", f"h{i}", [f"alpha bravo {'charlie ' * (i % 4)}"]
+ )
+ fast = store.search_lexical(rag_conn, "kb_a", "alpha bravo", 5)
+ _link_folder(rag_conn, "f1", "kb_b") # another scope, so nothing is excluded
+ filtered = store.search_lexical(rag_conn, "kb_a", "alpha bravo", 5)
+ assert fast == filtered
+
+
+def test_lexical_gate_and_read_share_one_snapshot(rag_conn, monkeypatch):
+ """A scope retired between the gate and the FTS read must not reach the read.
+
+ Otherwise the gate decides against a state the read no longer sees, and rows from the
+ retired scope take slots the caller loses at hydration.
+ """
+ from storage import rag_db
+
+ _add_doc(rag_conn, "kb_a", "d1", "d1.txt", "h1", ["alpha bravo charlie"])
+ observed = {}
+ real = store.linked_folder_rows_exist
+
+ def retire_midway(conn):
+ observed["gate"] = real(conn)
+ writer = rag_db.get_connection()
+ try:
+ writer.execute(
+ "INSERT INTO linked_folder_retired_scopes(scope, retired_at) "
+ "VALUES('kb_a', '2026-01-01T00:00:00+00:00')"
+ )
+ writer.commit()
+ finally:
+ writer.close()
+ observed["after_commit"] = real(conn)
+ return observed["gate"]
+
+ monkeypatch.setattr(store, "linked_folder_rows_exist", retire_midway)
+ hits = store.search_lexical(rag_conn, "kb_a", "alpha", 10)
+
+ assert observed["gate"] is False
+ # Same connection, same call, after another connection committed the retirement.
+ assert observed["after_commit"] is False
+ assert [cid for cid, _ in hits] == ["d1:0"]
+ # The snapshot is released, so the next call sees the retirement and hides the row.
+ monkeypatch.setattr(store, "linked_folder_rows_exist", real)
+ assert store.search_lexical(rag_conn, "kb_a", "alpha", 10) == []
+
+
+def test_lexical_reuses_a_transaction_the_caller_already_opened(rag_conn):
+ """A caller holding a transaction keeps its own snapshot, and keeps it open."""
+ _add_doc(rag_conn, "kb_a", "d1", "d1.txt", "h1", ["alpha bravo charlie"])
+ rag_conn.execute("BEGIN")
+ assert [cid for cid, _ in store.search_lexical(rag_conn, "kb_a", "alpha", 10)] == ["d1:0"]
+ assert rag_conn.in_transaction
+ rag_conn.commit()
+
+
+def test_gate_ignores_a_purged_tombstone(rag_conn):
+ """Deleting a knowledge base must not disable the fast path for good.
+
+ delete_retired_scope keeps the tombstone and only stamps purged_at, so a gate that
+ counted it would take the filtered query forever after the first ordinary delete.
+ """
+ _add_doc(rag_conn, "kb_a", "d1", "d1.txt", "h1", ["alpha bravo charlie"])
+ rag_conn.execute(
+ "INSERT INTO linked_folder_retired_scopes(scope, retired_at) "
+ "VALUES('kb_gone', '2026-01-01T00:00:00+00:00')"
+ )
+ rag_conn.commit()
+ assert store.linked_folder_rows_exist(rag_conn) is True
+
+ rag_conn.execute(
+ "UPDATE linked_folder_retired_scopes SET purged_at='2026-01-01T00:00:01+00:00'"
+ )
+ rag_conn.commit()
+ assert store.linked_folder_rows_exist(rag_conn) is False
+ assert [cid for cid, _ in store.search_lexical(rag_conn, "kb_a", "alpha", 10)] == ["d1:0"]
+
+
+def test_gate_counts_a_folder_document_that_outlived_its_folder(rag_conn):
+ """An orphan left by a crash before _install_mapping stays hidden after unlink.
+
+ Unlink collects only mapped documents, so the folder row goes and this one does not;
+ the gate has to see the document itself or unlinked content becomes searchable.
+ """
+ _link_folder(rag_conn, "f1", "kb_a")
+ store.create_document(
+ rag_conn,
+ scope = "kb_a",
+ filename = "secret.md",
+ sha256 = "h1",
+ document_id = "orphan",
+ linked_folder_id = "f1",
+ )
+ store.add_chunks(
+ rag_conn, "kb_a", "orphan", [_chunk("alpha bravo secret")], [embed("alpha bravo")]
+ )
+ assert store.search_lexical(rag_conn, "kb_a", "alpha", 10) == []
+
+ rag_conn.execute("DELETE FROM linked_folders WHERE id='f1'")
+ rag_conn.commit()
+ assert store.linked_folder_rows_exist(rag_conn) is True
+ assert store.search_lexical(rag_conn, "kb_a", "alpha", 10) == []