~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: remaining chunk dedup and ID consistency issues in library_rag_service (#2201)
LearningCircuit3d4dd0e74679
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 20d636e673..6efc41c08f 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@@ -10,7 +10,7 @@ Handles indexing and searching library documents using RAG:"""from pathlib import Path-from typing import Any, Dict, List, Optional+from typing import Any, Dict, List, Optional, Tuplefrom langchain_core.documents import Document as LangchainDocumentfrom loguru import logger@@ -219,7 +219,7 @@ class LibraryRAGService:chunks: List[LangchainDocument],chunk_ids: List[str],existing_ids: Optional[set] = None,- ) -> tuple:+ ) -> Tuple[List[LangchainDocument], List[str]]:"""Deduplicate chunks by ID within a batch, optionally excluding existing IDs."""seen_ids: set = set()new_chunks: List[LangchainDocument] = []@@ -637,9 +637,9 @@ class LibraryRAGService:if hasattr(self.faiss_index, "docstore")else set())- old_chunk_ids = [- eid for eid in embedding_ids if eid in existing_ids- ]+ old_chunk_ids = list(+ {eid for eid in embedding_ids if eid in existing_ids}+ )if old_chunk_ids:logger.info(f"Force re-index: removing {len(old_chunk_ids)} existing chunks from FAISS"@@ -655,6 +655,10 @@ class LibraryRAGService:)else:existing_ids = None++ unique_count = len(set(embedding_ids))+ batch_dups = len(chunks) - unique_count+new_chunks, new_ids = self._deduplicate_chunks(chunks, embedding_ids, existing_ids)@@ -666,8 +670,10 @@ class LibraryRAGService:f"Force re-index: adding {len(new_chunks)} chunks with updated metadata to FAISS index")else:+ already_exist = unique_count - len(new_chunks)logger.info(- f"Adding {len(new_chunks)} new embeddings to FAISS index ({len(chunks) - len(new_chunks)} already exist)"+ f"Adding {len(new_chunks)} new embeddings to FAISS index "+ f"({already_exist} already exist, {batch_dups} batch duplicates removed)")self.faiss_index.add_documents(new_chunks, ids=new_ids)else:@@ -1177,16 +1183,8 @@ class LibraryRAGService:f"Split local file {file_path} into {len(chunks)} chunks")- # Generate unique IDs for chunks- import hashlib-- file_hash = hashlib.sha256(str(file_path).encode()).hexdigest()[:8]- embedding_ids = [- f"local_{file_hash}_{i}" for i in range(len(chunks))- ]-- # Store chunks in database- self.embedding_manager._store_chunks_to_db(+ # Store chunks in database (returns UUID-based IDs)+ embedding_ids = self.embedding_manager._store_chunks_to_db(chunks=chunks,collection_name="local_library",source_type="local_file",@@ -1197,8 +1195,22 @@ class LibraryRAGService:if self.faiss_index is None:self.faiss_index = self.load_or_create_faiss_index()+ # Filter out chunks that already exist in FAISS and deduplicate+ if self.faiss_index is not None:+ existing_ids = (+ set(self.faiss_index.docstore._dict.keys())+ if hasattr(self.faiss_index, "docstore")+ else set()+ )+ else:+ existing_ids = None+ new_chunks, new_ids = self._deduplicate_chunks(+ chunks, embedding_ids, existing_ids+ )+# Add embeddings to FAISS index- self.faiss_index.add_documents(chunks, ids=embedding_ids)+ if new_chunks:+ self.faiss_index.add_documents(new_chunks, ids=new_ids)# Save FAISS indexindex_path = (@@ -1221,13 +1233,14 @@ class LibraryRAGService:)logger.info(- f"Successfully indexed local file {file_path} with {len(chunks)} chunks"+ f"Successfully indexed local file {file_path} with {len(new_chunks)} new chunks "+ f"({len(chunks) - len(new_chunks)} skipped)")return {"status": "success",- "chunk_count": len(chunks),- "embedding_ids": embedding_ids,+ "chunk_count": len(new_chunks),+ "embedding_ids": new_ids,}except Exception as e:@@ -1301,9 +1314,9 @@ class LibraryRAGService:if hasattr(self.faiss_index, "docstore")else set())- old_chunk_ids = [- eid for eid in embedding_ids if eid in existing_ids- ]+ old_chunk_ids = list(+ {eid for eid in embedding_ids if eid in existing_ids}+ )if old_chunk_ids:logger.info(f"Force re-index: removing {len(old_chunk_ids)} existing chunks from FAISS"@@ -1319,6 +1332,10 @@ class LibraryRAGService:)else:existing_ids = None++ unique_count = len(set(embedding_ids))+ batch_dups = len(chunks) - unique_count+new_chunks, new_ids = self._deduplicate_chunks(chunks, embedding_ids, existing_ids)@@ -1330,8 +1347,10 @@ class LibraryRAGService:f"Force re-index: adding {len(new_chunks)} chunks with updated metadata to FAISS index")else:+ already_exist = unique_count - len(new_chunks)logger.info(- f"Adding {len(new_chunks)} new chunks to FAISS index ({len(chunks) - len(new_chunks)} already exist)"+ f"Adding {len(new_chunks)} new chunks to FAISS index "+ f"({already_exist} already exist, {batch_dups} batch duplicates removed)")self.faiss_index.add_documents(new_chunks, ids=new_ids)else:diff --git a/tests/research_library/services/test_library_rag_service.py b/tests/research_library/services/test_library_rag_service.pyindex 994cf30612..23d6961084 100644--- a/tests/research_library/services/test_library_rag_service.py+++ b/tests/research_library/services/test_library_rag_service.py@@ -5,6 +5,7 @@ Tests for LibraryRAGService.import pytestfrom unittest.mock import Mock, MagicMockfrom pathlib import Path+from langchain_core.documents import Document as LangchainDocumentclass TestLibraryRAGServiceInit:@@ -1237,3 +1238,289 @@ class TestDeduplicateChunks:assert len(result_chunks) == 2assert result_ids == ["id-1", "id-2"]+++def _create_rag_service(mocker):+ """Helper to create a minimally-mocked LibraryRAGService."""+ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)++ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session",+ return_value=mock_session,+ )++ mock_embedding_manager = Mock()+ mock_embedding_manager.embeddings = Mock()+ mock_embedding_manager.embeddings.embed_query.return_value = [0.1] * 384++ mock_splitter = Mock()+ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service.get_text_splitter",+ return_value=mock_splitter,+ )++ mock_integrity = Mock()+ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",+ return_value=mock_integrity,+ )++ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ service = LibraryRAGService(+ username="test_user",+ embedding_manager=mock_embedding_manager,+ )+ return service+++class TestForceReindexDedup:+ """Tests for force_reindex old_chunk_ids deduplication."""++ def test_force_reindex_old_chunk_ids_deduplicated_index_document(+ self, mocker+ ):+ """Verify deletion path in index_document uses unique IDs."""+ service = _create_rag_service(mocker)++ # Mock document lookup+ mock_doc = Mock()+ mock_doc.id = "doc-1"+ mock_doc.text_content = "Hello world test content"+ mock_doc.title = "Test"+ mock_doc.filename = "test.txt"+ mock_doc.original_url = "http://example.com"+ mock_doc.authors = None+ mock_doc.published_date = None+ mock_doc.doi = None+ mock_doc.arxiv_id = None++ mock_doc_collection = Mock()+ mock_doc_collection.indexed = True+ mock_doc_collection.chunk_count = 2++ mock_session = MagicMock()+ mock_session.__enter__ = Mock(return_value=mock_session)+ mock_session.__exit__ = Mock(return_value=False)+ # First query: Document lookup, second: DocumentCollection+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc+ mock_session.query.return_value.filter_by.return_value.all.return_value = [+ mock_doc_collection+ ]++ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session",+ return_value=mock_session,+ )++ # Chunks with duplicate IDs (the root cause of #2182)+ chunks = [+ LangchainDocument(page_content="chunk A"),+ LangchainDocument(page_content="chunk B"),+ LangchainDocument(page_content="chunk A dup"),+ ]+ service.text_splitter.split_documents.return_value = chunks++ # _store_chunks_to_db returns IDs with duplicates+ duplicate_ids = ["id-1", "id-2", "id-1"]+ service.embedding_manager._store_chunks_to_db.return_value = (+ duplicate_ids+ )++ # Setup FAISS mock with existing IDs+ mock_faiss = Mock()+ mock_docstore = Mock()+ mock_docstore._dict = {"id-1": "doc", "id-2": "doc"}+ mock_faiss.docstore = mock_docstore+ service.faiss_index = mock_faiss++ mock_rag_index = Mock()+ mock_rag_index.index_path = "/tmp/test.faiss"+ mock_rag_index.id = "rag-1"+ service.rag_index_record = mock_rag_index++ service.index_document("doc-1", "coll-1", force_reindex=True)++ # Verify delete was called with deduplicated IDs+ delete_call = mock_faiss.delete.call_args[0][0]+ assert len(delete_call) == len(set(delete_call)), (+ "old_chunk_ids passed to FAISS.delete() must not contain duplicates"+ )++ def test_force_reindex_old_chunk_ids_deduplicated_index_user_document(+ self, mocker+ ):+ """Verify deletion path in index_user_document uses unique IDs."""+ service = _create_rag_service(mocker)++ # Mock user document+ mock_user_doc = Mock()+ mock_user_doc.id = "udoc-1"+ mock_user_doc.filename = "test.txt"+ mock_user_doc.text_content = "Some content here for testing"+ mock_user_doc.file_type = "txt"+ mock_user_doc.file_size = 100++ chunks = [+ LangchainDocument(page_content="chunk A"),+ LangchainDocument(page_content="chunk B"),+ LangchainDocument(page_content="chunk A dup"),+ ]+ service.text_splitter.split_documents.return_value = chunks++ # _store_chunks_to_db returns IDs with duplicates+ duplicate_ids = ["id-1", "id-2", "id-1"]+ service.embedding_manager._store_chunks_to_db.return_value = (+ duplicate_ids+ )++ # Setup FAISS mock+ mock_faiss = Mock()+ mock_docstore = Mock()+ mock_docstore._dict = {"id-1": "doc", "id-2": "doc"}+ mock_faiss.docstore = mock_docstore+ service.faiss_index = mock_faiss++ mock_rag_index = Mock()+ mock_rag_index.index_path = "/tmp/test.faiss"+ mock_rag_index.id = "rag-1"+ service.rag_index_record = mock_rag_index++ service.index_user_document(+ mock_user_doc, "collection_123", force_reindex=True+ )++ # Verify delete was called with deduplicated IDs+ delete_call = mock_faiss.delete.call_args[0][0]+ assert len(delete_call) == len(set(delete_call)), (+ "old_chunk_ids passed to FAISS.delete() must not contain duplicates"+ )+++class TestIndexLocalFileDedup:+ """Tests for index_local_file deduplication and ID consistency."""++ def test_index_local_file_uses_db_embedding_ids(self, mocker, tmp_path):+ """Verify IDs come from _store_chunks_to_db, not manual generation."""+ service = _create_rag_service(mocker)++ # Create a real temp file+ test_file = tmp_path / "test.txt"+ test_file.write_text(+ "This is a test file with enough content to pass validation."+ )++ chunks = [+ LangchainDocument(page_content="chunk 1"),+ LangchainDocument(page_content="chunk 2"),+ ]+ service.text_splitter.split_documents.return_value = chunks++ db_ids = ["db-uuid-1", "db-uuid-2"]+ service.embedding_manager._store_chunks_to_db.return_value = db_ids++ # Setup FAISS mock+ mock_faiss = Mock()+ mock_docstore = Mock()+ mock_docstore._dict = {} # Empty index+ mock_faiss.docstore = mock_docstore+ service.faiss_index = mock_faiss++ mock_rag_index = Mock()+ mock_rag_index.index_path = "/tmp/test.faiss"+ mock_rag_index.id = "rag-1"+ service.rag_index_record = mock_rag_index++ result = service.index_local_file(str(test_file))++ assert result["status"] == "success"+ # The IDs in the result should come from DB, not manual local_* generation+ assert result["embedding_ids"] == db_ids+ # Verify add_documents was called with DB-based IDs+ add_call = mock_faiss.add_documents.call_args+ assert add_call[1]["ids"] == db_ids++ def test_index_local_file_deduplicates_before_faiss(self, mocker, tmp_path):+ """Verify dedup is applied before adding to FAISS."""+ service = _create_rag_service(mocker)++ test_file = tmp_path / "test.txt"+ test_file.write_text(+ "This is a test file with enough content to pass validation."+ )++ chunks = [+ LangchainDocument(page_content="chunk 1"),+ LangchainDocument(page_content="chunk 2"),+ LangchainDocument(page_content="chunk 1 dup"),+ ]+ service.text_splitter.split_documents.return_value = chunks++ # Return IDs with a duplicate+ db_ids = ["db-uuid-1", "db-uuid-2", "db-uuid-1"]+ service.embedding_manager._store_chunks_to_db.return_value = db_ids++ # Setup FAISS mock+ mock_faiss = Mock()+ mock_docstore = Mock()+ mock_docstore._dict = {}+ mock_faiss.docstore = mock_docstore+ service.faiss_index = mock_faiss++ mock_rag_index = Mock()+ mock_rag_index.index_path = "/tmp/test.faiss"+ mock_rag_index.id = "rag-1"+ service.rag_index_record = mock_rag_index++ result = service.index_local_file(str(test_file))++ assert result["status"] == "success"+ # Only 2 unique chunks should be added+ assert result["chunk_count"] == 2+ add_call = mock_faiss.add_documents.call_args+ added_ids = add_call[1]["ids"]+ assert len(added_ids) == 2+ assert len(added_ids) == len(set(added_ids))++ def test_index_local_file_skips_existing_chunks(self, mocker, tmp_path):+ """Verify existing_ids filtering works — chunks already in FAISS are skipped."""+ service = _create_rag_service(mocker)++ test_file = tmp_path / "test.txt"+ test_file.write_text(+ "This is a test file with enough content to pass validation."+ )++ chunks = [+ LangchainDocument(page_content="already in index"),+ LangchainDocument(page_content="new chunk"),+ ]+ service.text_splitter.split_documents.return_value = chunks++ db_ids = ["existing-id", "new-id"]+ service.embedding_manager._store_chunks_to_db.return_value = db_ids++ # Setup FAISS mock with one existing ID+ mock_faiss = Mock()+ mock_docstore = Mock()+ mock_docstore._dict = {"existing-id": "some_doc"}+ mock_faiss.docstore = mock_docstore+ service.faiss_index = mock_faiss++ mock_rag_index = Mock()+ mock_rag_index.index_path = "/tmp/test.faiss"+ mock_rag_index.id = "rag-1"+ service.rag_index_record = mock_rag_index++ result = service.index_local_file(str(test_file))++ assert result["status"] == "success"+ assert result["chunk_count"] == 1+ assert result["embedding_ids"] == ["new-id"]+ # Verify only the new chunk was added+ add_call = mock_faiss.add_documents.call_args+ assert add_call[1]["ids"] == ["new-id"]