~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(rag): scope get_rag_stats counts to the configured index (#5798)
Ehsan78bd52ab2fa2
diff --git a/changelog.d/5798.bugfix.md b/changelog.d/5798.bugfix.mdnew file mode 100644index 0000000000..000bf2e634--- /dev/null+++ b/changelog.d/5798.bugfix.md@@ -0,0 +1,12 @@+RAG statistics for a collection now count only the documents and chunks of the+index that the active embedding configuration resolves to. A collection that+was indexed under one embedding model and then indexed again under another+keeps status rows from both indexes, so the previous per-collection count+reported documents the current index cannot search, disagreed with that index's+own document and chunk totals, and let a library or collection search proceed+against an index that holds nothing. A configuration with no index for the+collection now reports zero indexed documents rather than another index's rows,+and logs a warning naming the configuration when documents are indexed under a+different one, so that case is distinguishable from an empty collection. The+reported embedding model, provider and dimension now come from the resolved+index instead of an arbitrary chunk of the collection.diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.pyindex 4777dd357b..273164a822 100644--- a/src/local_deep_research/research_library/services/library_rag_service.py+++ b/src/local_deep_research/research_library/services/library_rag_service.py@@ -587,6 +587,23 @@ class LibraryRAGService:return candidatereturn None+ def _resolve_index_for_config(+ self, db_session: Session, collection_id: str+ ) -> RAGIndex | None:+ """The collection's index for this service's configuration, or None.++ Read-only: unlike ``_get_or_create_rag_index`` it never creates a+ row or probes the embedding provider.+ """+ collection_name = f"collection_{collection_id}"+ return self._find_matching_rag_index(+ db_session,+ collection_name,+ self._get_index_hash(+ collection_name, self.embedding_model, self.embedding_provider+ ),+ )+def _get_index_path(self, index_hash: str) -> Path:"""Get path for FAISS index file.@@ -3182,43 +3199,61 @@ class LibraryRAGService:# Count indexed documents from rag_document_status tablefrom ...database.models.library import RagDocumentStatus- indexed_docs = (- session.query(RagDocumentStatus)- .filter_by(collection_id=collection_id)- .count()- )-- # Count total chunks from rag_document_status table- total_chunks = (- session.query(func.sum(RagDocumentStatus.chunk_count))- .filter_by(collection_id=collection_id)- .scalar()- or 0- )+ # One collection can hold status rows from several indexes at+ # once, so scope the counts to the index this configuration+ # resolves to. No such index means nothing is indexed for it.+ rag_index = self._resolve_index_for_config(session, collection_id)- # Get collection name in the format stored in DocumentChunk (collection_<uuid>)- collection = (- session.query(Collection).filter_by(id=collection_id).first()- )- collection_name = (- f"collection_{collection_id}" if collection else "library"- )+ if rag_index is None:+ indexed_docs = 0+ total_chunks = 0+ foreign_rows = (+ session.query(RagDocumentStatus)+ .filter_by(collection_id=collection_id)+ .count()+ )+ if foreign_rows:+ logger.warning(+ f"Collection {collection_id} has no index for the "+ f"active embedding configuration "+ f"({self.embedding_provider}/{self.embedding_model}), "+ f"so it reports zero indexed documents. "+ f"{foreign_rows} document(s) are indexed under other "+ f"configurations and are not searchable from this one."+ )+ else:+ indexed_docs = (+ session.query(RagDocumentStatus)+ .filter_by(+ collection_id=collection_id,+ rag_index_id=rag_index.id,+ )+ .count()+ )- # Get embedding model info from chunks- chunk_sample = (- session.query(DocumentChunk)- .filter_by(collection_name=collection_name)- .first()- )+ # Count total chunks from rag_document_status table+ total_chunks = (+ session.query(func.sum(RagDocumentStatus.chunk_count))+ .filter_by(+ collection_id=collection_id,+ rag_index_id=rag_index.id,+ )+ .scalar()+ or 0+ )+ # Describe the index the counts above came from. Sampling any+ # chunk of the collection would describe whichever index wrote+ # first, which is the same mismatch as the counts.embedding_info = {}- if chunk_sample:+ if rag_index is not None:+ stored_provider = rag_index.embedding_model_type+ if isinstance(stored_provider, EmbeddingProvider):+ stored_provider = stored_provider.valueembedding_info = {- "model": chunk_sample.embedding_model,- "model_type": chunk_sample.embedding_model_type.value- if chunk_sample.embedding_model_type- else None,- "dimension": chunk_sample.embedding_dimension,+ "model": rag_index.embedding_model,+ "model_type": stored_provider,+ "dimension": rag_index.embedding_dimension,}return {diff --git a/tests/research_library/services/test_library_rag_service_deep_coverage.py b/tests/research_library/services/test_library_rag_service_deep_coverage.pyindex 1a556f74e6..e5589eeb00 100644--- a/tests/research_library/services/test_library_rag_service_deep_coverage.py+++ b/tests/research_library/services/test_library_rag_service_deep_coverage.py@@ -5,19 +5,34 @@ Targets ~146 missing statements not covered by existing test files:- get_current_index_info (collection_id present/absent, no RAG index, embedding_model_type None)- remove_document_from_rag (success, not-in-collection error, exception path)- index_documents_batch (not found, already indexed skip, no text, batch exception)-- get_rag_stats (default collection id, with collection, chunk_sample present/absent)+- get_rag_stats (default collection id, with collection, matching index present/absent)- close (idempotent second call, clears resources)- index_document exception path (embedding fails mid-way)"""from unittest.mock import MagicMock, patch+from local_deep_research.database.models.library import EmbeddingProvider+# ---------------------------------------------------------------------------# Module-level patch path prefix# ---------------------------------------------------------------------------_MOD = "local_deep_research.research_library.services.library_rag_service"+def _make_rag_index(model, model_type, dimension):+ """Stand-in for the RAGIndex row get_rag_stats describes.++ embedding_info is read off the index the configuration resolves to,+ not off a sampled chunk, so these tests configure the RAGIndex query.+ """+ index = MagicMock()+ index.embedding_model = model+ index.embedding_model_type = model_type+ index.embedding_dimension = dimension+ return index++def _make_service(**overrides):"""Create a LibraryRAGService with all external deps mocked out."""with (@@ -467,11 +482,9 @@ class TestGetRagStats:mock_session_ctx.return_value = _make_session_ctx(mock_session)mock_collection = MagicMock()- mock_chunk_sample = MagicMock()- mock_chunk_sample.embedding_model = "model-a"- mock_chunk_sample.embedding_model_type = MagicMock()- mock_chunk_sample.embedding_model_type.value = "sentence_transformers"- mock_chunk_sample.embedding_dimension = 384+ mock_rag_index = _make_rag_index(+ "model-a", EmbeddingProvider.SENTENCE_TRANSFORMERS, 384+ )def query_side(model_or_expr):q = MagicMock()@@ -483,8 +496,9 @@ class TestGetRagStats:q.filter_by.return_value.scalar.return_value = 30elif "Collection" in model_name:q.filter_by.return_value.first.return_value = mock_collection- elif "DocumentChunk" in model_name:- q.filter_by.return_value.first.return_value = mock_chunk_sample+ elif "RAGIndex" in model_name:+ q.filter_by.return_value.first.return_value = mock_rag_index+ q.filter_by.return_value.all.return_value = []else:q.filter_by.return_value.scalar.return_value = 30return q@@ -498,7 +512,7 @@ class TestGetRagStats:assert result["embedding_info"]["model"] == "model-a"@patch(f"{_MOD}.get_user_db_session")- def test_stats_without_chunk_sample(self, mock_session_ctx):+ def test_stats_without_matching_index(self, mock_session_ctx):svc = _make_service()mock_session = MagicMock()mock_session_ctx.return_value = _make_session_ctx(mock_session)@@ -513,8 +527,9 @@ class TestGetRagStats:q.filter_by.return_value.scalar.return_value = Noneelif "Collection" in model_name:q.filter_by.return_value.first.return_value = None- elif "DocumentChunk" in model_name:+ elif "RAGIndex" in model_name:q.filter_by.return_value.first.return_value = None+ q.filter_by.return_value.all.return_value = []else:q.filter_by.return_value.scalar.return_value = Nonereturn q@@ -526,15 +541,14 @@ class TestGetRagStats:assert result["embedding_info"] == {}@patch(f"{_MOD}.get_user_db_session")- def test_chunk_sample_embedding_model_type_none(self, mock_session_ctx):+ def test_index_embedding_model_type_none(self, mock_session_ctx):svc = _make_service()mock_session = MagicMock()mock_session_ctx.return_value = _make_session_ctx(mock_session)- mock_chunk_sample = MagicMock()- mock_chunk_sample.embedding_model = "model-b"- mock_chunk_sample.embedding_model_type = None # <-- None branch- mock_chunk_sample.embedding_dimension = 768+ mock_rag_index = _make_rag_index(+ "model-b", None, 768+ ) # <-- None branchdef query_side(model_or_expr):q = MagicMock()@@ -546,8 +560,9 @@ class TestGetRagStats:q.filter_by.return_value.scalar.return_value = 10elif "Collection" in model_name:q.filter_by.return_value.first.return_value = MagicMock()- elif "DocumentChunk" in model_name:- q.filter_by.return_value.first.return_value = mock_chunk_sample+ elif "RAGIndex" in model_name:+ q.filter_by.return_value.first.return_value = mock_rag_index+ q.filter_by.return_value.all.return_value = []else:q.filter_by.return_value.scalar.return_value = 10return qdiff --git a/tests/research_library/services/test_library_rag_service_index_coverage.py b/tests/research_library/services/test_library_rag_service_index_coverage.pyindex af78f05604..bab1b8eeb2 100644--- a/tests/research_library/services/test_library_rag_service_index_coverage.py+++ b/tests/research_library/services/test_library_rag_service_index_coverage.py@@ -4,15 +4,30 @@ Targets uncovered lines in library_rag_service.py:- index_document: no text_content (error), force_reindex (delete old chunks first)- index_documents_batch: batch processing (not found, skip, no text, success)- get_current_index_info: no index found → returns None-- get_rag_stats: stats calculation with and without chunk sample+- get_rag_stats: stats calculation with and without a matching RAG index- remove_document_from_rag: success deletion path"""from unittest.mock import MagicMock, patch+from local_deep_research.database.models.library import EmbeddingProvider+_MOD = "local_deep_research.research_library.services.library_rag_service"+def _make_rag_index(model, model_type, dimension):+ """Stand-in for the RAGIndex row get_rag_stats describes.++ embedding_info is read off the index the configuration resolves to,+ not off a sampled chunk, so these tests configure the RAGIndex query.+ """+ index = MagicMock()+ index.embedding_model = model+ index.embedding_model_type = model_type+ index.embedding_dimension = dimension+ return index++# ---------------------------------------------------------------------------# Shared helpers# ---------------------------------------------------------------------------@@ -619,11 +634,9 @@ class TestGetRagStats:mock_session_ctx.return_value = _make_session_ctx(mock_session)mock_collection = MagicMock()- mock_chunk_sample = MagicMock()- mock_chunk_sample.embedding_model = "bge-small"- mock_chunk_sample.embedding_model_type = MagicMock()- mock_chunk_sample.embedding_model_type.value = "sentence_transformers"- mock_chunk_sample.embedding_dimension = 512+ mock_rag_index = _make_rag_index(+ "bge-small", EmbeddingProvider.SENTENCE_TRANSFORMERS, 512+ )def query_side(model_or_expr):q = MagicMock()@@ -635,8 +648,9 @@ class TestGetRagStats:q.filter_by.return_value.scalar.return_value = 70elif "Collection" == name:q.filter_by.return_value.first.return_value = mock_collection- elif "DocumentChunk" in name:- q.filter_by.return_value.first.return_value = mock_chunk_sample+ elif "RAGIndex" in name:+ q.filter_by.return_value.first.return_value = mock_rag_index+ q.filter_by.return_value.all.return_value = []else:q.filter_by.return_value.scalar.return_value = 70return q@@ -654,8 +668,10 @@ class TestGetRagStats:assert result["embedding_info"]["dimension"] == 512@patch(f"{_MOD}.get_user_db_session")- def test_stats_no_chunk_sample_embedding_info_empty(self, mock_session_ctx):- """When no DocumentChunk exists, embedding_info is an empty dict."""+ def test_stats_no_matching_index_embedding_info_empty(+ self, mock_session_ctx+ ):+ """With no index for this configuration, embedding_info is empty."""svc = _make_service()mock_session = MagicMock()mock_session_ctx.return_value = _make_session_ctx(mock_session)@@ -670,8 +686,9 @@ class TestGetRagStats:q.filter_by.return_value.scalar.return_value = Noneelif "Collection" == name:q.filter_by.return_value.first.return_value = None- elif "DocumentChunk" in name:+ elif "RAGIndex" in name:q.filter_by.return_value.first.return_value = None+ q.filter_by.return_value.all.return_value = []else:q.filter_by.return_value.scalar.return_value = Nonereturn q@@ -685,18 +702,13 @@ class TestGetRagStats:assert result["unindexed_documents"] == 3@patch(f"{_MOD}.get_user_db_session")- def test_stats_chunk_sample_embedding_model_type_none(- self, mock_session_ctx- ):- """embedding_model_type = None on chunk_sample yields None in embedding_info."""+ def test_stats_index_embedding_model_type_none(self, mock_session_ctx):+ """embedding_model_type = None on the index yields None in embedding_info."""svc = _make_service()mock_session = MagicMock()mock_session_ctx.return_value = _make_session_ctx(mock_session)- mock_chunk_sample = MagicMock()- mock_chunk_sample.embedding_model = "custom"- mock_chunk_sample.embedding_model_type = None- mock_chunk_sample.embedding_dimension = 256+ mock_rag_index = _make_rag_index("custom", None, 256)def query_side(model_or_expr):q = MagicMock()@@ -708,8 +720,9 @@ class TestGetRagStats:q.filter_by.return_value.scalar.return_value = 20elif "Collection" == name:q.filter_by.return_value.first.return_value = MagicMock()- elif "DocumentChunk" in name:- q.filter_by.return_value.first.return_value = mock_chunk_sample+ elif "RAGIndex" in name:+ q.filter_by.return_value.first.return_value = mock_rag_index+ q.filter_by.return_value.all.return_value = []else:q.filter_by.return_value.scalar.return_value = 20return qdiff --git a/tests/research_library/services/test_rag_stats_index_scope.py b/tests/research_library/services/test_rag_stats_index_scope.pynew file mode 100644index 0000000000..98e2b2a798--- /dev/null+++ b/tests/research_library/services/test_rag_stats_index_scope.py@@ -0,0 +1,288 @@+"""``get_rag_stats`` must describe ONE index, not every index in the collection.++A collection accumulates ``RagDocumentStatus`` rows from more than one+``RAGIndex`` whenever the embedding configuration changes between indexing+runs: documents indexed under model A keep their rows, and documents indexed+afterwards under model B get rows pointing at B's index. Counting those rows by+``collection_id`` alone reports documents that the current index cannot search,+and disagrees with the ``RAGIndex`` row's own aggregate for the same index.++Both search engines gate on the result (``search_engine_collection`` and+``search_engine_library`` skip a collection when ``indexed_documents == 0``), so+the count decides whether a search runs at all.++Uses the real-components harness from ``test_multi_model_switch_revert.py``:+network-free fake embeddings, one in-memory sqlite session shared by every+``get_user_db_session`` call site, ``LDR_DATA_DIR`` under ``tmp_path``, and a+real ``LibraryRAGService`` with only the embedding backend faked.+"""++import hashlib+import uuid+from contextlib import contextmanager++import numpy as np+import pytest+from langchain_core.embeddings import Embeddings+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.models import Base+from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentCollection,+ DocumentStatus,+ RAGIndex,+ RagDocumentStatus,+ SourceType,+)++_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"++USERNAME = "statsuser"+DB_PASSWORD = "pw" # gitleaks:allow+++class _FakeEmbeddings(Embeddings):+ """Deterministic, network-free embeddings keyed by model name and+ dimension, so two configurations produce two distinct indexes."""++ def __init__(self, name: str, dim: int):+ self.name = name+ self.dim = dim++ def _vec(self, text: str):+ # sha256, not hash(): str hashing is salted per process.+ seed = hashlib.sha256(f"{self.name}\x00{text}".encode()).digest()[:4]+ rng = np.random.default_rng(int.from_bytes(seed, "big"))+ return rng.random(self.dim).tolist()++ def embed_documents(self, texts):+ return [self._vec(t) for t in texts]++ def embed_query(self, text):+ return self._vec(text)+++def shared_world(tmp_path, monkeypatch, mocker):+ """One in-memory DB shared by every ``get_user_db_session`` call site, and+ a real on-disk cache tree under ``tmp_path``."""+ from unittest.mock import MagicMock++ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()++ @contextmanager+ def _shared_session(*_a, **_k):+ yield session++ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _shared_session)+ mocker.patch(+ "local_deep_research.vector_stores.facade.get_user_db_session",+ _shared_session,+ )++ fim = MagicMock()+ fim.verify_file.return_value = (True, None)+ fim.record_file.return_value = None+ mocker.patch(f"{_RAG_MOD}.FileIntegrityManager", return_value=fim)++ yield session++ session.close()+ engine.dispose()+++def seeded_collection(shared_world):+ """A collection holding two real documents, both linked but unindexed."""+ session = shared_world+ collection_id = uuid.uuid4().hex++ source_type = SourceType(+ id=uuid.uuid4().hex, name="document", display_name="Document"+ )+ session.add(source_type)+ session.add(Collection(id=collection_id, name="Stats scope collection"))++ document_ids = []+ for label in ("first", "second"):+ document_id = uuid.uuid4().hex+ body = f"The {label} document says something about vector indexes. " * 5+ session.add(+ Document(+ id=document_id,+ source_type_id=source_type.id,+ document_hash=hashlib.sha256(body.encode()).hexdigest(),+ title=f"Stats scope {label} document",+ text_content=body,+ original_url=f"http://example.com/stats-scope-{label}",+ file_size=len(body),+ file_type="txt",+ status=DocumentStatus.COMPLETED,+ )+ )+ session.add(+ DocumentCollection(+ document_id=document_id,+ collection_id=collection_id,+ indexed=False,+ chunk_count=0,+ )+ )+ document_ids.append(document_id)++ session.commit()+ return collection_id, document_ids[0], document_ids[1]+++def _make_service(model, dim, **overrides):+ """A real LibraryRAGService with only the embedding backend faked."""+ from unittest.mock import MagicMock++ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ emb_mgr = MagicMock()+ emb_mgr.embeddings = _FakeEmbeddings(name=model, dim=dim)++ kwargs = dict(+ username=USERNAME,+ db_password=DB_PASSWORD,+ embedding_model=model,+ embedding_provider="sentence_transformers",+ embedding_manager=emb_mgr,+ index_type="flat",+ distance_metric="cosine",+ normalize_vectors=True,+ )+ kwargs.update(overrides)+ return LibraryRAGService(**kwargs)+++class TestRagStatsIndexScope:+ def test_stats_count_only_the_configured_index(+ self, shared_world, seeded_collection+ ):+ """Indexing one document under model A and the other under model B+ leaves status rows from both indexes in the collection. Each service+ must report its own index's documents and chunks."""+ session = shared_world+ collection_id, doc_a, doc_b = seeded_collection++ svc_a = _make_service("model-A", dim=8)+ result_a = svc_a.index_document(doc_a, collection_id)+ assert result_a["status"] == "success", result_a++ svc_b = _make_service("model-B", dim=4)+ result_b = svc_b.index_document(doc_b, collection_id)+ assert result_b["status"] == "success", result_b++ rows = (+ session.query(RagDocumentStatus)+ .filter_by(collection_id=collection_id)+ .all()+ )+ assert len(rows) == 2+ assert len({row.rag_index_id for row in rows}) == 2, (+ "the two documents must sit under two different indexes for this "+ "test to exercise anything"+ )++ index_b = (+ session.query(RAGIndex)+ .filter_by(+ collection_name=f"collection_{collection_id}",+ embedding_model="model-B",+ )+ .one()+ )+ index_a = (+ session.query(RAGIndex)+ .filter_by(+ collection_name=f"collection_{collection_id}",+ embedding_model="model-A",+ )+ .one()+ )++ stats_b = svc_b.get_rag_stats(collection_id)+ assert stats_b["total_documents"] == 2+ assert stats_b["indexed_documents"] == 1+ assert stats_b["unindexed_documents"] == 1+ assert stats_b["total_chunks"] == result_b["chunk_count"]++ # The counts must agree with the index's own aggregate, which+ # index_document maintains per index.+ assert stats_b["indexed_documents"] == index_b.total_documents+ assert stats_b["total_chunks"] == index_b.chunk_count++ # The other index is unchanged and reports its own document, so the+ # scoping is per configuration rather than "only the current index".+ stats_a = svc_a.get_rag_stats(collection_id)+ assert stats_a["indexed_documents"] == 1+ assert stats_a["total_chunks"] == result_a["chunk_count"]+ assert stats_a["indexed_documents"] == index_a.total_documents+ assert stats_a["total_chunks"] == index_a.chunk_count++ # embedding_info describes the index the counts came from. Sampling+ # a chunk of the collection would answer "model-A" for both services,+ # since model-A indexed first.+ assert stats_b["embedding_info"]["model"] == "model-B"+ assert stats_b["embedding_info"]["dimension"] == 4+ assert stats_a["embedding_info"]["model"] == "model-A"+ assert stats_a["embedding_info"]["dimension"] == 8++ def test_stats_are_zero_for_a_configuration_with_no_index(+ self, shared_world, seeded_collection, loguru_caplog+ ):+ """A configuration that has never indexed this collection has no+ index row, so nothing is indexed for it, however many rows other+ indexes left behind."""+ session = shared_world+ collection_id, doc_a, _doc_b = seeded_collection++ svc_a = _make_service("model-A", dim=8)+ assert svc_a.index_document(doc_a, collection_id)["status"] == "success"+ assert (+ session.query(RagDocumentStatus)+ .filter_by(collection_id=collection_id)+ .count()+ == 1+ )++ svc_c = _make_service("model-C", dim=6)++ with loguru_caplog.at_level("WARNING"):+ stats_c = svc_c.get_rag_stats(collection_id)++ assert stats_c["total_documents"] == 2+ assert stats_c["indexed_documents"] == 0+ assert stats_c["unindexed_documents"] == 2+ assert stats_c["total_chunks"] == 0++ # Zero here means "not indexed under THIS configuration", which reads+ # identically to "not indexed at all" unless the log says otherwise.+ assert stats_c["embedding_info"] == {}+ assert collection_id in loguru_caplog.text+ assert "model-C" in loguru_caplog.text+ assert (+ "1 document(s) are indexed under other configurations"+ in loguru_caplog.text+ )++ assert (+ session.query(RAGIndex)+ .filter_by(+ collection_name=f"collection_{collection_id}",+ embedding_model="model-C",+ )+ .count()+ == 0+ ), "reading stats must not create an index row"