~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): preserve completed index across overlapping runs (#7888)
creed0c8821d5382d
diff --git a/changelog.d/7523.bugfix.md b/changelog.d/7523.bugfix.mdnew file mode 100644index 0000000000..a6fce96f42--- /dev/null+++ b/changelog.d/7523.bugfix.md@@ -0,0 +1 @@+Preserve a completed document index when overlapping indexing runs finish out of order, and keep RAG index counts in sync when a document is marked for retry.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 36b4b7247c..9bcfcb80fe 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@@ -1977,9 +1977,28 @@ class LibraryRAGService:so without this flag the document stays permanently, silentlyunsearchable. Best-effort + committed in its own statement;index_document owns per-document commits (see index_all_documents), so- this clobbers no caller.+ this clobbers no caller. Remove the status row's contribution from its+ RAGIndex counters in the same transaction; later retries add it back."""try:+ status = (+ session.query(RagDocumentStatus)+ .filter_by(document_id=document_id, collection_id=collection_id)+ .first()+ )+ if status is not None:+ rag_index = (+ session.query(RAGIndex)+ .filter_by(id=status.rag_index_id)+ .first()+ )+ if rag_index is not None:+ rag_index.chunk_count = max(+ 0, (rag_index.chunk_count or 0) - status.chunk_count+ )+ rag_index.total_documents = max(+ 0, (rag_index.total_documents or 0) - 1+ )session.query(DocumentCollection).filter_by(document_id=document_id, collection_id=collection_id).update(@@ -2343,6 +2362,43 @@ class LibraryRAGService:isinstance(prepared.status_exists, bool)and current_status_exists != prepared.status_exists):+ peer_status_exists = current_status_exists+ if (+ prepared.initial_indexed is False+ and prepared.status_exists is False+ and link.indexed is True+ and not peer_status_exists+ and prepared.status_index_id is None+ ):+ # No matching index existed during preparation.+ # A peer may have created its first index and+ # completed this document since then; the saved+ # None identity cannot observe that new row.+ peer_index = self._resolve_index_for_config(+ session, collection_id+ )+ if peer_index is not None:+ peer_status_exists = self._status_row_exists(+ session,+ document_id,+ collection_id,+ peer_index.id,+ )+ if (+ prepared.initial_indexed is False+ and prepared.status_exists is False+ and link.indexed is True+ and peer_status_exists+ ):+ # Another writer finished this same document while+ # we embedded it. The content hash matched above;+ # clearing its committed status would lose a valid+ # index and make the next sweep count it twice.+ return {+ "status": "skipped",+ "message": "Document indexed by another run during embedding",+ "chunk_count": link.chunk_count,+ }logger.info(f"Document {document_id} indexing status modified during embedding; ""aborting persist and flagging for reindex."diff --git a/tests/research_library/services/test_library_rag_service_index_failure.py b/tests/research_library/services/test_library_rag_service_index_failure.pyindex 554f3054af..9f20cc5dff 100644--- a/tests/research_library/services/test_library_rag_service_index_failure.py+++ b/tests/research_library/services/test_library_rag_service_index_failure.py@@ -15,6 +15,8 @@ all occurs.from unittest.mock import MagicMock, patch+from local_deep_research.database.models.library import RagDocumentStatus+_MOD = "local_deep_research.research_library.services.library_rag_service"@@ -80,6 +82,14 @@ def test_index_document_not_marked_indexed_when_store_persists_no_embeddings(session.query.return_value.filter_by.return_value.first.return_value = (_make_doc())+ # A first indexing failure has no persisted status row. The broad default+ # query double above represents the document, not a RagDocumentStatus.+ status_query = MagicMock()+ status_query.filter_by.return_value.first.return_value = None+ default_query = session.query.return_value+ session.query.side_effect = lambda model, *args: (+ status_query if model is RagDocumentStatus else default_query+ )mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)# The splitter produces a real (non-empty) chunk set...diff --git a/tests/research_library/services/test_library_rag_service_rollback.py b/tests/research_library/services/test_library_rag_service_rollback.pyindex d2140d4a7b..88f8313d77 100644--- a/tests/research_library/services/test_library_rag_service_rollback.py+++ b/tests/research_library/services/test_library_rag_service_rollback.py@@ -14,6 +14,8 @@ dict.from unittest.mock import MagicMock, patch+from local_deep_research.database.models.library import RagDocumentStatus+_MOD = "local_deep_research.research_library.services.library_rag_service"@@ -84,6 +86,14 @@ def test_index_document_rolls_back_session_on_exception(session.query.return_value.filter_by.return_value.first.return_value = (_make_doc())+ # This fixture represents a document, but has no persisted RAG status.+ # Keep the new status lookup from returning the document MagicMock.+ status_query = MagicMock()+ status_query.filter_by.return_value.first.return_value = None+ default_query = session.query.return_value+ session.query.side_effect = lambda model, *args: (+ status_query if model is RagDocumentStatus else default_query+ )mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)# Force the inner work to raise — text_splitter is patched indiff --git a/tests/research_library/services/test_rag_overlapping_index_7523.py b/tests/research_library/services/test_rag_overlapping_index_7523.pynew file mode 100644index 0000000000..07b730793a--- /dev/null+++ b/tests/research_library/services/test_rag_overlapping_index_7523.py@@ -0,0 +1,222 @@+"""A second prepared writer must not erase a document indexed by its peer."""++import hashlib+from contextlib import contextmanager++import numpy as np+import pytest+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,+ EmbeddingProvider,+ RAGIndex,+ RagDocumentStatus,+ SourceType,+)+from local_deep_research.research_library.services import (+ library_rag_service as rag_module,+)+from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ _PreparedDocument,+)+++def indexed_peer(tmp_path, monkeypatch):+ engine = create_engine(f"sqlite:///{tmp_path / 'overlap.db'}")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()++ @contextmanager+ def db_session(*_args, **_kwargs):+ yield session++ monkeypatch.setattr(rag_module, "get_user_db_session", db_session)+ source_type = SourceType(+ id="source-type", name="document", display_name="Document"+ )+ collection = Collection(id="collection", name="Collection")+ body = "A document indexed by overlapping runs."+ document = Document(+ id="document",+ source_type_id=source_type.id,+ title="Document",+ text_content=body,+ document_hash=hashlib.sha256(body.encode()).hexdigest(),+ file_size=len(body),+ file_type="txt",+ status=DocumentStatus.COMPLETED,+ )+ link = DocumentCollection(+ document_id=document.id, collection_id=collection.id, indexed=False+ )+ index = RAGIndex(+ collection_name="collection_collection",+ embedding_model="test-model",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ embedding_dimension=2,+ index_path=str(tmp_path / "index.faiss"),+ index_hash="test-index",+ chunk_size=100,+ chunk_overlap=10,+ chunk_count=0,+ total_documents=0,+ )+ session.add_all([source_type, collection, document, link, index])+ session.commit()++ service = object.__new__(LibraryRAGService)+ service.username = "test-user"+ service._db_password = "test-password" # gitleaks:allow+ service.embedding_model = "test-model"+ service.embedding_provider = "sentence_transformers"+ service.chunk_size = 100+ service.chunk_overlap = 10+ service.splitter_type = "recursive"+ service.text_separators = ["\n\n", "\n", ". ", " ", ""]+ service.distance_metric = "cosine"+ service.normalize_vectors = True+ service.index_type = "flat"+ service.rag_index_record = index+ yield session, service, body++ session.close()+ engine.dispose()+++def _peer_finishes(session, service):+ link = session.query(DocumentCollection).one()+ link.indexed = True+ link.chunk_count = 2+ session.add(+ RagDocumentStatus(+ document_id="document",+ collection_id="collection",+ rag_index_id=service.rag_index_record.id,+ chunk_count=2,+ )+ )+ service.rag_index_record.chunk_count = 2+ service.rag_index_record.total_documents = 1+ session.commit()+++def test_late_prepared_writer_keeps_peers_completed_index(indexed_peer):+ session, service, body = indexed_peer+ prepared = _PreparedDocument(+ document_id="document",+ collection_id="collection",+ chunk_inputs=[],+ vectors=np.empty((0, 2), dtype="float32"),+ content_hash=hashlib.sha256(body.encode()).hexdigest(),+ initial_indexed=False,+ status_exists=False,+ status_index_id=service.rag_index_record.id,+ had_collection_link=True,+ )+ _peer_finishes(session, service)++ result = service._write_prepared_document_once(prepared)++ session.expire_all()+ assert result["status"] == "skipped"+ assert session.query(DocumentCollection).one().indexed is True+ assert session.query(DocumentCollection).one().chunk_count == 2+ assert session.query(RagDocumentStatus).one().chunk_count == 2+ index = session.query(RAGIndex).one()+ assert (index.chunk_count, index.total_documents) == (2, 1)+++def test_late_writer_keeps_peer_when_first_index_appears_after_prepare(+ indexed_peer,+):+ session, service, body = indexed_peer+ session.delete(service.rag_index_record)+ session.commit()+ service.rag_index_record = None+ prepared = _PreparedDocument(+ document_id="document",+ collection_id="collection",+ chunk_inputs=[],+ vectors=np.empty((0, 2), dtype="float32"),+ content_hash=hashlib.sha256(body.encode()).hexdigest(),+ initial_indexed=False,+ status_exists=False,+ status_index_id=None,+ had_collection_link=True,+ )++ # The peer creates the first index and finishes while this writer embeds.+ new_index = RAGIndex(+ collection_name="collection_collection",+ embedding_model=service.embedding_model,+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ embedding_dimension=2,+ index_path="/new.faiss",+ index_hash=service._get_index_hash(+ "collection_collection",+ service.embedding_model,+ service.embedding_provider,+ ),+ chunk_size=service.chunk_size,+ chunk_overlap=service.chunk_overlap,+ chunk_count=0,+ total_documents=0,+ )+ session.add(new_index)+ session.commit()+ service.rag_index_record = new_index+ _peer_finishes(session, service)++ result = service._write_prepared_document_once(prepared)++ session.expire_all()+ assert result["status"] == "skipped"+ assert session.query(DocumentCollection).one().indexed is True+ assert session.query(RagDocumentStatus).one().rag_index_id == new_index.id+ assert session.query(RagDocumentStatus).one().chunk_count == 2+ assert (new_index.chunk_count, new_index.total_documents) == (2, 1)+++def test_reindex_flag_removes_deleted_status_from_index_counters(indexed_peer):+ session, service, _body = indexed_peer+ _peer_finishes(session, service)+ session.add(+ Document(+ id="other-document",+ source_type_id="source-type",+ title="Other document",+ text_content="Other content",+ document_hash=hashlib.sha256(b"Other content").hexdigest(),+ file_size=13,+ file_type="txt",+ status=DocumentStatus.COMPLETED,+ )+ )+ session.add(+ RagDocumentStatus(+ document_id="other-document",+ collection_id="collection",+ rag_index_id=service.rag_index_record.id,+ chunk_count=3,+ )+ )+ service.rag_index_record.chunk_count = 5+ service.rag_index_record.total_documents = 2+ session.commit()++ service._flag_document_for_reindex(session, "document", "collection")+ service._flag_document_for_reindex(session, "document", "collection")++ session.expire_all()+ assert session.query(RagDocumentStatus).count() == 1+ assert session.query(DocumentCollection).one().indexed is False+ index = session.query(RAGIndex).one()+ assert (index.chunk_count, index.total_documents) == (3, 1)