~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
perf(rag): reduce collection search database queries (#5285)
LearningCircuit542d4d3a8f6f
diff --git a/changelog.d/5285.misc.md b/changelog.d/5285.misc.mdnew file mode 100644index 0000000000..3fdaeaf6f1--- /dev/null+++ b/changelog.d/5285.misc.md@@ -0,0 +1 @@+Collection search now checks eligibility with an index-scoped existence query instead of the full RAG statistics query it used before -- 3 statements instead of 5 on an exact index match. The "indexed under other configurations" diagnostic that explains an unexpectedly empty collection is still logged.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 857f047bf4..396d5b6f6d 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@@ -24,7 +24,7 @@ from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledErrorfrom langchain_core.documents import Document as LangchainDocumentfrom loguru import logger-from sqlalchemy import func+from sqlalchemy import exists, funcfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.orm import Session@@ -1545,12 +1545,13 @@ class LibraryRAGService:full re-embed.Callers are expected to have already confirmed the collection has- indexed documents (e.g. via ``get_rag_stats``) before calling this- — for an ORDINARY query, this method will otherwise create an empty- RAGIndex/store for a never-indexed (collection, embedding model)- pair and return no results, rather than raising. A DEGENERATE query- embedding (see above) is refused even on that never-indexed store —- it is never swallowed into an empty result either.+ indexed documents (e.g. via ``has_indexed_documents``) before+ calling this — for an ORDINARY query, this method will otherwise+ create an empty RAGIndex/store for a never-indexed (collection,+ embedding model) pair and return no results, rather than raising.+ A DEGENERATE query embedding (see above) is refused even on that+ never-indexed store — it is never swallowed into an empty result+ either."""collection_name = f"collection_{collection_id}"vindex = self._get_vector_index(collection_id, collection_name)@@ -3290,6 +3291,44 @@ class LibraryRAGService:"orphan_vectors": len(live_ids - durable_ids),}+ def has_indexed_documents(self, collection_id: str) -> bool:+ """Check search eligibility without collecting unrelated RAG statistics.++ Use the same exact-hash and legacy-configuration resolution as search+ and stats. Rows belonging to other indexes cannot make this one eligible.+ Resolving an index is read-only and never probes the embedding provider.+ """+ with get_user_db_session(self.username, self.db_password) as session:+ rag_index = self._resolve_index_for_config(session, collection_id)+ if rag_index is None:+ # Ineligible path only, so the extra query here doesn't+ # touch the hot (eligible) path. Mirrors the same+ # foreign-rows diagnostic get_rag_stats logs, so "I indexed+ # this and search returns nothing" is still explained.+ 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."+ )+ return False+ return bool(+ session.query(+ exists().where(+ RagDocumentStatus.collection_id == collection_id,+ RagDocumentStatus.rag_index_id == rag_index.id,+ )+ ).scalar()+ )+def get_rag_stats(self, collection_id: Optional[str] = None) -> Dict[str, Any]:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.pyindex a8fc69fd8b..9a177564a6 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py@@ -278,8 +278,7 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):index_type=index_type,) as rag_service:# Check if there are indexed documents- stats = rag_service.get_rag_stats(self.collection_id)- if stats.get("indexed_documents", 0) == 0:+ if not rag_service.has_indexed_documents(self.collection_id):logger.info(f"No documents indexed in collection '{self.collection_name}'")diff --git a/tests/research_library/search/services/test_collection_search_normalize_vectors.py b/tests/research_library/search/services/test_collection_search_normalize_vectors.pyindex 40d6efd1c7..0b0a173a20 100644--- a/tests/research_library/search/services/test_collection_search_normalize_vectors.py+++ b/tests/research_library/search/services/test_collection_search_normalize_vectors.py@@ -6,7 +6,7 @@ without passing normalize_vectors, so LibraryRAGService defaulted it to True.A collection BUILT with normalize_vectors=False was then LOADED/queried withL2 normalization on at search time, corrupting similarity rankings.-The stored value lives on the RAGIndex row (rag_indices.normalize_vectors).+The stored value lives on the Collection row (collections.normalize_vectors).These tests assert the search path threads that stored value through into theLibraryRAGService(...) constructor, with NULL -> True preserved."""@@ -15,20 +15,27 @@ from unittest.mock import Mock, patchimport pytest--def _make_rag_index(normalize_vectors):- """Build a mock RAGIndex row with the embedding fields search() reads."""- rag_index = Mock()- rag_index.embedding_model = "all-MiniLM-L6-v2"- rag_index.embedding_model_type = Mock(value="sentence_transformers")- rag_index.chunk_size = 1000- rag_index.chunk_overlap = 200- rag_index.normalize_vectors = normalize_vectors- return rag_index+from local_deep_research.database.models.library import (+ Collection,+ EmbeddingProvider,+)+++def _make_collection(normalize_vectors):+ """Build a mock Collection row with the embedding fields search() reads."""+ return Collection(+ id="abc123",+ name="Test collection",+ embedding_model="all-MiniLM-L6-v2",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ chunk_size=1000,+ chunk_overlap=200,+ normalize_vectors=normalize_vectors,+ )def _run_search_capturing_rag_service(normalize_vectors):- """Run CollectionSearchEngine.search with a stored RAGIndex carrying the+ """Run CollectionSearchEngine.search with a stored Collection carrying thegiven normalize_vectors value, returning the patched LibraryRAGService mockso callers can inspect the constructor call kwargs."""@@ -37,7 +44,7 @@ def _run_search_capturing_rag_service(normalize_vectors):)settings = {"_username": "testuser"}- rag_index = _make_rag_index(normalize_vectors)+ collection = _make_collection(normalize_vectors)with patch("local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",@@ -50,7 +57,7 @@ def _run_search_capturing_rag_service(normalize_vectors):with patch("local_deep_research.web_search_engines.engines.search_engine_collection.get_user_db_session") as mock_session:- mock_session.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = rag_index+ mock_session.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = collectionwith patch("local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService"@@ -59,9 +66,7 @@ def _run_search_capturing_rag_service(normalize_vectors):# LibraryRAGService(...) constructor has already been# called with the (mis)configured kwargs we want to inspect.mock_instance = Mock()- mock_instance.get_rag_stats.return_value = {- "indexed_documents": 0- }+ mock_instance.has_indexed_documents.return_value = Falsemock_rag_service.return_value.__enter__.return_value = (mock_instance)@@ -83,7 +88,7 @@ def _run_search_capturing_rag_service(normalize_vectors):class TestNormalizeVectorsThreadedThrough:- """Search must pass the stored RAGIndex.normalize_vectors to the service."""+ """Search must pass the stored Collection.normalize_vectors to the service."""def test_stored_false_is_passed_through(self):"""normalize_vectors=False on the index -> service built with False.diff --git a/tests/research_library/search/services/test_collection_search_query_count.py b/tests/research_library/search/services/test_collection_search_query_count.pynew file mode 100644index 0000000000..be7d32e8fe--- /dev/null+++ b/tests/research_library/search/services/test_collection_search_query_count.py@@ -0,0 +1,290 @@+"""Real SQL-count and index-scope regressions for collection search eligibility."""++from contextlib import contextmanager+from unittest.mock import Mock, patch++import pytest+from sqlalchemy import create_engine, event+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.models import Base+from local_deep_research.database.models.library import (+ Collection,+ EmbeddingProvider,+ RAGIndex,+ RagDocumentStatus,+)+from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+)+from local_deep_research.web_search_engines.engines.search_engine_collection import (+ CollectionSearchEngine,+)++_ENGINE = "local_deep_research.web_search_engines.engines"+_SERVICE = "local_deep_research.research_library.services.library_rag_service"+_COLLECTION_ID = "collection-query-count"+_CONFIG = {+ "embedding_model": "test-model",+ "embedding_provider": "sentence_transformers",+ "chunk_size": 700,+ "chunk_overlap": 0,+ "splitter_type": "recursive",+ "text_separators": ["\n", ""],+ "distance_metric": "dot_product",+ "normalize_vectors": False,+ "index_type": "flat",+}+++class _NoEmbeddingIO:+ @property+ def embeddings(self):+ raise AssertionError(+ "Eligibility must not initialize or probe embeddings"+ )+++def search_world():+ """Real collection, configuration resolution and EXISTS; no embedding IO."""+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine, expire_on_commit=False)()+ collection_config = dict(_CONFIG)+ collection_config["embedding_model_type"] = EmbeddingProvider(+ collection_config.pop("embedding_provider")+ )+ session.add(+ Collection(+ id=_COLLECTION_ID,+ name="Query count collection",+ **collection_config,+ )+ )+ session.commit()++ @contextmanager+ def get_session(*_args, **_kwargs):+ yield session++ services = []++ def make_service(**kwargs):+ service = LibraryRAGService(+ **kwargs, embedding_manager=_NoEmbeddingIO()+ )+ service.get_rag_stats = Mock(wraps=service.get_rag_stats)+ service.search = Mock(return_value=[])+ services.append(service)+ return service++ with (+ patch(+ f"{_ENGINE}.search_engine_library.get_setting_from_snapshot",+ return_value=None,+ ),+ patch(+ f"{_ENGINE}.search_engine_library.get_server_url",+ return_value="http://localhost:5000",+ ),+ patch(+ f"{_ENGINE}.search_engine_collection.get_user_db_session",+ get_session,+ ),+ patch(f"{_SERVICE}.get_user_db_session", get_session),+ patch(f"{_SERVICE}.FileIntegrityManager"),+ patch(+ f"{_ENGINE}.search_engine_collection.LibraryRAGService",+ side_effect=make_service,+ ),+ ):++ def add_index(collection_id=_COLLECTION_ID, legacy=False, **overrides):+ config = {**_CONFIG, **overrides}+ with LibraryRAGService(+ username="query-count-user",+ embedding_manager=_NoEmbeddingIO(),+ **config,+ ) as service:+ index_hash = service._get_index_hash(+ f"collection_{collection_id}",+ service.embedding_model,+ service.embedding_provider,+ )+ if legacy:+ index_hash = "legacy-" + index_hash+ config["embedding_model_type"] = EmbeddingProvider(+ config.pop("embedding_provider")+ )+ index = RAGIndex(+ collection_name=f"collection_{collection_id}",+ embedding_dimension=4,+ index_path=f"/unused/{index_hash}.faiss",+ index_hash=index_hash,+ is_current=True,+ **config,+ )+ session.add(index)+ session.commit()+ return index++ def add_status(index, collection_id=_COLLECTION_ID):+ session.add(+ RagDocumentStatus(+ document_id=f"document-for-index-{index.id}",+ collection_id=collection_id,+ rag_index_id=index.id,+ chunk_count=1,+ )+ )+ session.commit()++ def search(collection_id=_COLLECTION_ID):+ collection_engine = CollectionSearchEngine(+ collection_id=collection_id,+ collection_name="Query count collection",+ settings_snapshot={"_username": "query-count-user"},+ )+ statements = []++ def capture(_conn, _cursor, statement, _params, _context, _many):+ statements.append(statement)++ event.listen(engine, "before_cursor_execute", capture)+ try:+ assert collection_engine.search("test query") == []+ finally:+ event.remove(engine, "before_cursor_execute", capture)+ return statements++ yield session, add_index, add_status, search, services++ session.close()+ engine.dispose()++[email protected]("indexed", [False, True])[email protected]("legacy", [False, True])+def test_search_eligibility_uses_only_configuration_and_exists_queries(+ search_world, indexed, legacy+):+ _session, add_index, add_status, search, services = search_world+ index = add_index(legacy=legacy)+ if indexed:+ add_status(index)++ statements = search()++ service = services[-1]+ assert len(statements) == 3 + int(legacy), statements+ service.get_rag_stats.assert_not_called()+ assert sum("FROM collections" in sql for sql in statements) == 1+ assert sum("FROM rag_indices" in sql for sql in statements) == 1 + int(+ legacy+ )+ assert (+ sum(+ "SELECT EXISTS" in sql and "FROM rag_document_status" in sql+ for sql in statements+ )+ == 1+ )+ assert not any(+ "count(" in sql.lower() or "sum(" in sql.lower() for sql in statements+ )+ if indexed:+ service.search.assert_called_once_with("test query", _COLLECTION_ID, 10)+ else:+ service.search.assert_not_called()++[email protected]("active_index_exists", [False, True])+ "foreign_config",+ [+ {"collection_id": "other-collection"},+ {"embedding_model": "other-model"},+ {"chunk_overlap": 20},+ {"normalize_vectors": True},+ {"distance_metric": "cosine"},+ {"text_separators": ["\n\n", "\n", ""]},+ ],+)+def test_foreign_status_rows_do_not_make_this_configuration_searchable(+ search_world, active_index_exists, foreign_config+):+ session, add_index, add_status, search, services = search_world+ if active_index_exists:+ add_index()+ foreign_index = add_index(**foreign_config)+ add_status(+ foreign_index, foreign_config.get("collection_id", _COLLECTION_ID)+ )+ original_indices = session.query(RAGIndex).count()++ search()++ services[-1].get_rag_stats.assert_not_called()+ services[-1].search.assert_not_called()+ assert session.query(RAGIndex).count() == original_indices+++def test_missing_collection_does_not_fall_back_to_another_collection(+ search_world,+):+ """Locks the premise this change relies on -- a missing collection_id+ never falls back to another collection (e.g. the default library) --+ rather than detecting a regression of this change itself. ``search()``+ returns at the Collection lookup before ``LibraryRAGService`` (and so+ ``has_indexed_documents``) is ever constructed, so ``services == []``+ and this passes byte-identically under a full revert of #5285. See+ ``test_has_indexed_documents_scopes_status_rows_to_the_resolved_index``+ below for a test that actually exercises ``has_indexed_documents``.+ """+ _session, add_index, add_status, search, services = search_world+ add_status(add_index())++ statements = search(collection_id=None)++ assert len(statements) == 1, statements+ assert services == []+++def test_has_indexed_documents_scopes_status_rows_to_the_resolved_index(+ search_world,+):+ """Direct test of ``has_indexed_documents`` itself, since ``search()``+ only reaches it indirectly through ``CollectionSearchEngine`` and no+ test in this tree calls it directly otherwise.++ Fails if the ``RagDocumentStatus.rag_index_id`` scoping is dropped in+ favor of a ``collection_id``-only ``EXISTS`` -- as it briefly was in+ this branch's own history (commit 3df8c2c7f, reverted by 6770ae75e):+ the second assertion below would then see the status row (moved to a+ foreign index but still in the same collection) as making this+ configuration eligible, and return True instead of False.+ """+ session, add_index, add_status, _search, _services = search_world+ index = add_index()+ add_status(index)++ with LibraryRAGService(+ username="query-count-user",+ embedding_manager=_NoEmbeddingIO(),+ **_CONFIG,+ ) as service:+ assert service.has_indexed_documents(_COLLECTION_ID) is True++ # Re-point the same status row at a foreign-configuration index+ # without changing its collection_id.+ status_row = (+ session.query(RagDocumentStatus)+ .filter_by(collection_id=_COLLECTION_ID)+ .one()+ )+ foreign_index = add_index(embedding_model="other-model")+ status_row.rag_index_id = foreign_index.id+ session.commit()++ assert service.has_indexed_documents(_COLLECTION_ID) is Falsediff --git a/tests/research_library/services/test_rag_stats_index_scope.py b/tests/research_library/services/test_rag_stats_index_scope.pyindex 98e2b2a798..0b15a805d6 100644--- a/tests/research_library/services/test_rag_stats_index_scope.py+++ b/tests/research_library/services/test_rag_stats_index_scope.py@@ -7,9 +7,13 @@ 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.+``search_engine_library`` still gates directly on this result+(``get_rag_stats(...)["indexed_documents"] == 0`` skips a collection);+``search_engine_collection`` now uses the cheaper, index-scoped+``has_indexed_documents`` instead (see+``test_collection_search_query_count.py``) and never calls+``get_rag_stats``. So the count below decides whether a search runs at+all only for the library engine.Uses the real-components harness from ``test_multi_model_switch_revert.py``:network-free fake embeddings, one in-memory sqlite session shared by every@@ -286,3 +290,48 @@ class TestRagStatsIndexScope:.count()== 0), "reading stats must not create an index row"++ def test_has_indexed_documents_warns_on_foreign_rows_but_not_when_eligible(+ self, shared_world, seeded_collection, loguru_caplog_full+ ):+ """``has_indexed_documents`` keeps the same "indexed under other+ configurations" diagnostic ``get_rag_stats`` logs (see+ ``test_stats_are_zero_for_a_configuration_with_no_index`` above),+ emitted from its own ``rag_index is None`` branch so the eligible+ (hot) path pays nothing for it.++ Fails under a revert that drops that branch's foreign-rows count+ and ``logger.warning(...)`` call: the miss-path assertions below+ would find an empty ``loguru_caplog_full.text``.+ """+ 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_full.at_level("WARNING"):+ assert svc_c.has_indexed_documents(collection_id) is False++ assert collection_id in loguru_caplog_full.text+ assert "model-C" in loguru_caplog_full.text+ assert (+ "1 document(s) are indexed under other configurations"+ in loguru_caplog_full.text+ )++ # The eligible path must stay silent -- resolving svc_a's own+ # index and finding its own status row takes the early ``return+ # bool(...)`` above the foreign-rows count and warning.+ loguru_caplog_full.clear()+ with loguru_caplog_full.at_level("WARNING"):+ assert svc_a.has_indexed_documents(collection_id) is True+ assert loguru_caplog_full.text == ""diff --git a/tests/web/routers/test_rag_indexing_pipeline.py b/tests/web/routers/test_rag_indexing_pipeline.pyindex 1fc48a4f1e..a336c4d7a5 100644--- a/tests/web/routers/test_rag_indexing_pipeline.py+++ b/tests/web/routers/test_rag_indexing_pipeline.py@@ -596,8 +596,10 @@ class TestChunkingSettingsAtQueryTime:query_svc = _make_service(**_query_time_kwargs(row))- # The engine's own pre-search guard passes, so an empty result is- # not the guard short-circuiting.+ # search_engine_collection's own guard now checks+ # has_indexed_documents, not this -- this just confirms the+ # document really is indexed, so an empty result below is not+ # "nothing indexed yet" wearing a different explanation.assert query_svc.get_rag_stats(collection_id)["indexed_documents"] > 0hits = query_svc.search(QUERY, collection_id, 5)assert any(SECRET in h.text for h in hits), (diff --git a/tests/web_search_engines/engines/test_search_engine_collection.py b/tests/web_search_engines/engines/test_search_engine_collection.pyindex 671c3890b1..2b22303666 100644--- a/tests/web_search_engines/engines/test_search_engine_collection.py+++ b/tests/web_search_engines/engines/test_search_engine_collection.py@@ -411,9 +411,9 @@ class TestSearch:) as mock_rag_service:# Set up mock RAG service instance for context managermock_rag_instance = Mock()- mock_rag_instance.get_rag_stats.return_value = {- "indexed_documents": 0- }+ mock_rag_instance.has_indexed_documents.return_value = (+ False+ )mock_rag_service.return_value.__enter__.return_value = (mock_rag_instance)@@ -476,9 +476,9 @@ class TestSearch:) as mock_rag_service:# Set up mock RAG service instance for context managermock_rag_instance = Mock()- mock_rag_instance.get_rag_stats.return_value = {- "indexed_documents": 1- }+ mock_rag_instance.has_indexed_documents.return_value = (+ True+ )mock_rag_instance.search.return_value = [SearchResult(chunk_id=1,@@ -552,9 +552,9 @@ class TestSearch:"local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService") as mock_rag_service:mock_rag_instance = Mock()- mock_rag_instance.get_rag_stats.return_value = {- "indexed_documents": 1- }+ mock_rag_instance.has_indexed_documents.return_value = (+ True+ )mock_rag_instance.search.return_value = [SearchResult(chunk_id=1,@@ -633,9 +633,9 @@ class TestSearch:"local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService") as mock_rag_service:mock_rag_instance = Mock()- mock_rag_instance.get_rag_stats.return_value = {- "indexed_documents": 2- }+ mock_rag_instance.has_indexed_documents.return_value = (+ True+ )mock_rag_instance.search.return_value = [SearchResult(chunk_id=1,@@ -719,9 +719,9 @@ class TestSearch:) as mock_rag_service:# Set up mock RAG service instance for context managermock_rag_instance = Mock()- mock_rag_instance.get_rag_stats.return_value = {- "indexed_documents": 1- }+ mock_rag_instance.has_indexed_documents.return_value = (+ True+ )mock_rag_instance.search.return_value = []mock_rag_service.return_value.__enter__.return_value = (mock_rag_instance@@ -827,9 +827,9 @@ class TestSearch:"local_deep_research.web_search_engines.engines.search_engine_collection.LibraryRAGService") as mock_rag_service:mock_rag_instance = Mock()- mock_rag_instance.get_rag_stats.return_value = {- "indexed_documents": 0- }+ mock_rag_instance.has_indexed_documents.return_value = (+ False+ )mock_rag_service.return_value.__enter__.return_value = (mock_rag_instance)diff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.pyindex 2964a3d20e..4d7313bad2 100644--- a/tests/web_search_engines/test_engine_success_path.py+++ b/tests/web_search_engines/test_engine_success_path.py@@ -1451,7 +1451,15 @@ def _fake_rag_hit():def _fake_rag_service(module):- """Context-manager stub for ``LibraryRAGService``."""+ """Context-manager stub for ``LibraryRAGService``.++ ``get_rag_stats`` is still load-bearing for ``_drive_library``+ (``search_engine_library`` gates on it). It is dead configuration for+ ``_drive_collection``: ``search_engine_collection`` gates on+ ``has_indexed_documents`` instead, which this unconfigured MagicMock+ attribute already answers truthily, so the stub is kept as-is rather+ than split per engine.+ """service = MagicMock()service.get_rag_stats.return_value = {"indexed_documents": 5}service.search.return_value = [_fake_rag_hit()]