Skip to content

~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.

fix(rag): use worker-owned sessions during preparation (#7759)

LearningCircuit3cd3789cb0f2
diff --git a/changelog.d/7557.bugfix.md b/changelog.d/7557.bugfix.md
new file mode 100644
index 0000000000..6945141ea4
--- /dev/null
+++ b/changelog.d/7557.bugfix.md
@@ -0,0 +1 @@
+Document preparation for parallel collection indexing now reads index metadata through each worker's own database session, preventing intermittent document failures after a coordinator commit on the prepared indexing path. Documents that still require a serial write keep the previous shared-record access.
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.py
index 6380442754..36b4b7247c 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
@@ -113,6 +113,14 @@ class _PreparedDocument:
content_hash: Optional[str] = None
initial_indexed: Optional[bool] = None
status_exists: Optional[bool] = None
+ # The RAGIndex identity ``status_exists`` was measured against — the
+ # row selected by ``_resolve_index_for_config`` at prepare time. The
+ # write-side staleness re-check must measure its status-row query
+ # against this same identity (see ``_status_row_exists``); deriving it
+ # from ``self.rag_index_record`` there breaks the paired predicate.
+ # None means no index matching this service's configuration existed at
+ # prepare time.
+ status_index_id: Optional[int] = None
# True iff a DocumentCollection row existed at prepare time. False
# means first-time ingest: Phase 3 may create the link. Distinguishes
# that from a concurrent unlink of a row that was present then.
@@ -824,6 +832,42 @@ class LibraryRAGService:
),
)
+ def _status_row_exists(
+ self,
+ session,
+ document_id: str,
+ collection_id: str,
+ rag_index_id: Optional[int],
+ ) -> bool:
+ """Whether the document's status row exists for one index identity.
+
+ Both sides of the prepare/write staleness comparison must measure
+ through this function AND against the same ``rag_index_id``: the
+ identity :meth:`_resolve_index_for_config` selected when the
+ prepared document was snapshotted
+ (``_PreparedDocument.status_index_id``). Deriving the write side's
+ identity from ``self.rag_index_record`` breaks the pairing whenever
+ that attribute lags the resolution: on a fresh per-request/per-sweep
+ service it is still ``None`` when the staleness gate runs
+ (``_get_vector_index`` only sets it afterwards), so every document
+ whose status row survived a chunk purge compares True against
+ False, aborts a healthy write as "stale", and
+ ``_flag_document_for_reindex`` deletes the surviving row. A ``None``
+ identity means no index existed at prepare time; the NOT NULL
+ column can hold no row for it, so the predicate is False — the same
+ value preparation snapshotted.
+ """
+ return (
+ session.query(RagDocumentStatus)
+ .filter_by(
+ document_id=document_id,
+ collection_id=collection_id,
+ rag_index_id=rag_index_id,
+ )
+ .first()
+ is not None
+ )
+
def _get_index_path(self, index_hash: str) -> Path:
"""Get path for FAISS index file.
@@ -2084,17 +2128,18 @@ class LibraryRAGService:
).hexdigest()
prep_initial_indexed = link.indexed if link is not None else False
prep_had_collection_link = link is not None
- prep_status_exists = (
- session.query(RagDocumentStatus)
- .filter_by(
- document_id=document_id,
- collection_id=collection_id,
- rag_index_id=self.rag_index_record.id,
- )
- .first()
- is not None
- if self.rag_index_record
- else False
+ # The coordinator's ORM record may be expired by a commit while
+ # this worker prepares another document. Resolve the index through
+ # this worker's session so no attribute refresh shares a session
+ # with the coordinator or another worker, and snapshot the
+ # identity the status row is keyed to so the write-side re-check
+ # measures the same predicate (see _status_row_exists).
+ rag_index = self._resolve_index_for_config(session, collection_id)
+ prep_status_index_id = (
+ rag_index.id if rag_index is not None else None
+ )
+ prep_status_exists = self._status_row_exists(
+ session, document_id, collection_id, prep_status_index_id
)
chunks = self.text_splitter.split_documents([source_doc])
@@ -2136,6 +2181,7 @@ class LibraryRAGService:
content_hash=prep_content_hash,
initial_indexed=prep_initial_indexed,
status_exists=prep_status_exists,
+ status_index_id=prep_status_index_id,
had_collection_link=prep_had_collection_link,
),
}
@@ -2274,17 +2320,20 @@ class LibraryRAGService:
"message": "Document modified during indexing, flagged for reindex",
}
- current_status_exists = (
- session.query(RagDocumentStatus)
- .filter_by(
- document_id=document_id,
- collection_id=collection_id,
- rag_index_id=self.rag_index_record.id,
- )
- .first()
- is not None
- if self.rag_index_record
- else False
+ # Same predicate AND the same index identity as
+ # preparation's snapshot (see _status_row_exists and
+ # _PreparedDocument.status_index_id). Deriving the
+ # identity from self.rag_index_record here would
+ # disagree with preparation whenever that attribute
+ # lags the resolution — None on a fresh service until
+ # _get_vector_index sets it below — aborting healthy
+ # writes as "stale" and deleting surviving status
+ # rows via _flag_document_for_reindex.
+ current_status_exists = self._status_row_exists(
+ session,
+ document_id,
+ collection_id,
+ prepared.status_index_id,
)
if (
isinstance(prepared.initial_indexed, bool)
diff --git a/tests/research_library/services/test_rag_transaction_ownership.py b/tests/research_library/services/test_rag_transaction_ownership.py
index a58ff4fa25..622cee552b 100644
--- a/tests/research_library/services/test_rag_transaction_ownership.py
+++ b/tests/research_library/services/test_rag_transaction_ownership.py
@@ -8,12 +8,14 @@ import ast
import textwrap
import threading
from contextlib import nullcontext
+from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
-from sqlalchemy import create_engine
+from sqlalchemy import create_engine, event, inspect
+from sqlalchemy.exc import InvalidRequestError
from sqlalchemy.orm import sessionmaker
import local_deep_research
@@ -25,6 +27,7 @@ from local_deep_research.database.models.library import (
DocumentStatus,
EmbeddingProvider,
RAGIndex,
+ RagDocumentStatus,
SourceType,
)
from local_deep_research.database.models.queue import TaskMetadata
@@ -170,6 +173,168 @@ def add_membership(rig):
session.commit()
+def add_second_document(rig):
+ with rig.factory() as setup:
+ setup.add_all(
+ [
+ Document(
+ id="doc-2",
+ source_type_id="source",
+ document_hash="hash-2",
+ title="Second",
+ text_content="More text to index",
+ file_size=18,
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ ),
+ DocumentCollection(
+ document_id="doc-2",
+ collection_id="collection",
+ indexed=False,
+ ),
+ ]
+ )
+ setup.commit()
+
+
+def test_parallel_preparation_uses_worker_owned_index_records(rig):
+ """An expired coordinator record must never refresh in a pool worker."""
+ add_membership(rig)
+ add_second_document(rig)
+
+ shared_record = rig.session.get(RAGIndex, 1)
+ control_record = rig.session.get(Collection, "collection")
+ rig.session.commit()
+ rig.service.rag_index_record = shared_record
+ coordinator = threading.current_thread()
+ worker_refreshes = []
+ coordinator_loads = []
+
+ def reject_worker_refresh(state):
+ if threading.current_thread() is not coordinator:
+ worker_refreshes.append(state)
+ raise InvalidRequestError("Coordinator session used by worker")
+ coordinator_loads.append(state.is_column_load)
+
+ event.listen(rig.session, "do_orm_execute", reject_worker_refresh)
+ preparing = threading.Barrier(2)
+
+ def embed(texts):
+ preparing.wait(timeout=5)
+ return [[0.1, 0.2, 0.3] for _ in texts]
+
+ rig.service.embedding_manager.embeddings.embed_documents.side_effect = embed
+ try:
+ # Positive control: the hook observes a refresh of a commit-expired
+ # attribute on this session, so worker_refreshes == [] below cannot
+ # pass merely because refreshes stopped reaching the listener.
+ assert control_record.name == "Library"
+ assert coordinator_loads == [True]
+ # End the control's read transaction; shared_record stays expired.
+ rig.session.commit()
+ assert "id" in inspect(shared_record).expired_attributes
+ result = rig.service.index_documents_parallel(
+ [("doc", "Original"), ("doc-2", "Second")],
+ "collection",
+ max_workers=2,
+ )
+ finally:
+ event.remove(rig.session, "do_orm_execute", reject_worker_refresh)
+
+ assert result["failed"] == 0, result["errors"]
+ assert result["successful"] == 2
+ assert worker_refreshes == []
+ with rig.factory() as check:
+ assert (
+ check.query(DocumentCollection).filter_by(indexed=True).count() == 2
+ )
+
+
+def test_prep_write_status_parity_survives_prior_status_rows(rig):
+ """A fresh service must not abort docs whose status row outlived a purge.
+
+ Production shape the worker-ownership test above cannot see: an in-place
+ text change (Zotero ``_purge_collection_chunks``) deletes the docs'
+ chunks and clears ``link.indexed`` but leaves their
+ ``RagDocumentStatus`` rows behind, and the reconciler sweep later picks
+ the docs up via ``index_documents_parallel(force_reindex=False)`` on a
+ FRESH service whose ``rag_index_record`` stays ``None`` until the first
+ write's ``_get_vector_index`` sets it — after that write's Phase-3
+ staleness gate, and after any document already in flight took its
+ prepare-time snapshot. Both documents here are prepared before either
+ is written, so preparation and the write-side re-check must measure the
+ status row against the same index identity, or a healthy write aborts
+ as "stale" and ``_flag_document_for_reindex`` deletes its surviving
+ status row:
+
+ * re-checked against ``rag_index_record`` (still ``None``) after
+ preparation resolved the index itself, the FIRST write compares
+ True with False — and so does every write after it;
+ * measured against ``rag_index_record`` on both sides, the SECOND
+ document was snapshotted while it was ``None`` (False) but is
+ re-checked after the first write set it (True).
+ """
+ add_membership(rig)
+ add_second_document(rig)
+ with rig.factory() as setup:
+ setup.add_all(
+ [
+ RagDocumentStatus(
+ document_id=document_id,
+ collection_id="collection",
+ rag_index_id=1,
+ chunk_count=1,
+ indexed_at=datetime(2026, 10, 1, tzinfo=UTC),
+ )
+ for document_id in ("doc", "doc-2")
+ ]
+ )
+ setup.commit()
+
+ # The real _get_vector_index sets rag_index_record before the persist
+ # writes — but only AFTER the staleness gate above them. Model that so
+ # the test cannot accidentally arm the gate's guard itself.
+ vector_index = rig.service._get_vector_index.return_value
+
+ def fresh_service_vector_index(*args, **kwargs):
+ rig.service.rag_index_record = SimpleNamespace(id=1)
+ return vector_index
+
+ rig.service._get_vector_index.side_effect = fresh_service_vector_index
+ rig.service.rag_index_record = None
+ # Neither document finishes preparing until both took their status
+ # snapshot, so both snapshots precede the first write.
+ preparing = threading.Barrier(2)
+
+ def embed(texts):
+ preparing.wait(timeout=5)
+ return [[0.1, 0.2, 0.3] for _ in texts]
+
+ rig.service.embedding_manager.embeddings.embed_documents.side_effect = embed
+ result = rig.service.index_documents_parallel(
+ [("doc", "Original"), ("doc-2", "Second")],
+ "collection",
+ force_reindex=False,
+ max_workers=2,
+ )
+ assert result["failed"] == 0, result["errors"]
+ assert {
+ document_id: outcome["status"]
+ for document_id, outcome in result["results"].items()
+ } == {"doc": "success", "doc-2": "success"}
+ with rig.factory() as check:
+ statuses = {
+ status.document_id: (status.rag_index_id, status.chunk_count)
+ for status in check.query(RagDocumentStatus).filter_by(
+ collection_id="collection"
+ )
+ }
+ assert statuses == {"doc": (1, 1), "doc-2": (1, 1)}
+ assert (
+ check.query(DocumentCollection).filter_by(indexed=True).count() == 2
+ )
+
+
def test_serial_rejects_enclosing_write_without_discarding_it(rig):
add_membership(rig)
with get_user_db_session("local_review", "test-only") as outer:
diff --git a/tests/research_library/services/test_text_index_invalidation.py b/tests/research_library/services/test_text_index_invalidation.py
index 8a83d35a53..74be8955ba 100644
--- a/tests/research_library/services/test_text_index_invalidation.py
+++ b/tests/research_library/services/test_text_index_invalidation.py
@@ -52,6 +52,36 @@ class MemoryVectors:
def indexer_for(case, collection="library"):
+ """Build the fake indexer double used by the serialization tests.
+
+ The double is a ``LibraryRAGService`` built with ``__new__`` (no
+ ``__init__``): only the collaborators set in ``__dict__`` below are
+ faked, and every other method is the production one.
+
+ Premise change (#7557, PR 7759): ``_prepare_document`` used to
+ snapshot ``status_exists`` against the coordinator's
+ ``rag_index_record``. It now resolves the index through its OWN
+ session (the coordinator's ORM record may expire mid-run and a pool
+ worker must not refresh it), via the real
+ ``_resolve_index_for_config`` -> ``_find_matching_rag_index``, and
+ both sides of the prepare/write status comparison measure through the
+ real ``_status_row_exists`` against that resolved identity.
+ ``_get_index_hash`` maps ``collection_<id>`` to the ``index_hash``
+ extraction_case seeds (the collection id), so
+ ``_find_matching_rag_index`` returns at its hash lookup and its
+ configuration-matching fallback (``_matches_current_index_configuration``)
+ never runs. ``_matches_collection_configuration`` is never called
+ either: its caller skips it because the seeded collections store no
+ ``embedding_model``. So the
+ double sets none of the configuration attributes (``chunk_size``,
+ ``chunk_overlap``, ``splitter_type``, ``text_separators``,
+ ``distance_metric``, ``normalize_vectors``, ``index_type``) that
+ ``__init__`` would. ``rag_index_record`` stands in for the record the
+ real ``_get_vector_index`` (faked here) assigns. The prepared write's
+ persist step reads it after that call. The serial path
+ (``_index_document_locked``) also reads it for its own status snapshot
+ and gate. The tests' staleness and invalidation premises are unchanged.
+ """
with case.sessions() as session:
index_id, index_key = (
session.query(RAGIndex.id, RAGIndex.index_hash)
@@ -81,7 +111,7 @@ def indexer_for(case, collection="library"):
embedding_provider="sentence_transformers",
_collection_transaction_lock=lambda coll: nullcontext(),
_get_vector_index=lambda *a, **kw: backend,
- _get_index_hash=lambda coll, *args: coll,
+ _get_index_hash=lambda coll, *args: coll.removeprefix("collection_"),
_get_index_path=lambda h: case.service.library_root / h,
text_splitter=SimpleNamespace(split_documents=lambda docs: docs),
_embed_texts_cancellable=lambda texts, cancelled: [
@@ -137,6 +167,16 @@ def assert_pending(case, collection="library"):
def test_reconciliation_preserves_invalidation_until_replacement(
extraction_case, mode
):
+ """Old vectors stay invalidated until the replacement is indexed.
+
+ Premise note (#7557, PR 7759): mode="prepared" used to snapshot status
+ existence against the coordinator's ``rag_index_record``; preparation
+ now resolves the index through its own worker-owned session (the
+ coordinator's ORM record may expire mid-run and must not be refreshed
+ by a worker), so the ``indexer_for`` double provides that seam. The
+ premise tested here — a text replacement keeps the old chunks
+ invalidated until the replacement commit lands — is unchanged.
+ """
case = extraction_case(quality="low", incoming=LONGER)
indexer, backend = indexer_for(case)
old_ids = backend._store.ids.copy()
@@ -186,6 +226,15 @@ def test_reconciliation_preserves_invalidation_until_replacement(
def test_text_change_after_validation_is_detected_before_vector_writes(
extraction_case, mode
):
+ """A text change between validation and vector writes aborts as stale.
+
+ Premise note (#7557, PR 7759): the prepared path's status snapshot now
+ goes through worker-session index resolution instead of the
+ coordinator's ``rag_index_record`` (see ``indexer_for``) because
+ preparation must use worker-owned sessions. Staleness detection
+ itself — what this test forces into the validation-to-write window —
+ is unchanged.
+ """
case = extraction_case(quality="low")
indexer, backend = indexer_for(case)
before = backend._store.ids.copy()
@@ -205,10 +254,118 @@ def test_text_change_after_validation_is_detected_before_vector_writes(
assert not backend._store.removed
+ "flip", ["membership", "status_row", "status_row_rekeyed"]
+)
+def test_status_flip_between_prepare_and_write_aborts_as_stale(
+ extraction_case, flip
+):
+ """A concurrent status flip during embedding must abort the write.
+
+ The Phase-3 staleness gate snapshots the document's indexed state at
+ prepare (``initial_indexed`` / ``status_exists``) and re-measures it at
+ write time: when a concurrent commit flips that state mid-embed, the
+ write must abort as ``stale`` and flag the document for reindex
+ instead of silently overwriting the other writer's outcome. Each flip
+ shape exercises one arm of the gate: a membership ``indexed`` flip, a
+ ``RagDocumentStatus`` row appearing for the prepared index identity,
+ and a row that existed throughout but keyed to another index of the
+ same collection (an older embedding model's) being re-keyed to the
+ prepared index, as a concurrent writer's ``session.merge`` does. Only a
+ status predicate that measures the index identity sees that last flip.
+ """
+ case = extraction_case(quality="low", incoming=LONGER)
+ indexer, backend = indexer_for(case)
+ assert case.service.download_resource(case.resource_id) == (True, None)
+ assert_pending(case)
+ before = backend._store.ids.copy()
+ with case.sessions() as session:
+ # Derived from the seeded rows, not from preparation: extraction_case
+ # also seeds the "selected" collection's index, a wrong but valid
+ # identity for preparation to resolve.
+ library_index_id = (
+ session.query(RAGIndex.id)
+ .filter_by(collection_name="collection_library")
+ .scalar()
+ )
+ if flip == "status_row_rekeyed":
+ old_index = RAGIndex(
+ collection_name="collection_library",
+ embedding_model="old-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ index_path=str(case.service.library_root / "old-model"),
+ index_hash="library-old-model",
+ chunk_size=100,
+ chunk_overlap=0,
+ is_current=False,
+ )
+ session.add(old_index)
+ session.flush()
+ session.add(
+ RagDocumentStatus(
+ document_id="canonical",
+ collection_id="library",
+ rag_index_id=old_index.id,
+ chunk_count=1,
+ )
+ )
+ session.commit()
+ # A lagging coordinator record pointing at the old index: the
+ # gate must still measure against prepared.status_index_id.
+ indexer.rag_index_record = SimpleNamespace(id=old_index.id)
+
+ prep = LibraryRAGService._prepare_document(
+ indexer, "canonical", "library", True
+ )
+ assert prep["status"] == "prepared", prep
+ assert prep["prepared"].status_index_id == library_index_id
+ with case.sessions() as session:
+ if flip == "membership":
+ session.query(DocumentCollection).filter_by(
+ document_id="canonical", collection_id="library"
+ ).one().indexed = True
+ elif flip == "status_row":
+ session.add(
+ RagDocumentStatus(
+ document_id="canonical",
+ collection_id="library",
+ rag_index_id=library_index_id,
+ chunk_count=1,
+ )
+ )
+ else:
+ session.get(
+ RagDocumentStatus, ("canonical", "library")
+ ).rag_index_id = library_index_id
+ session.commit()
+
+ result = LibraryRAGService._write_prepared_document(
+ indexer, prep["prepared"]
+ )
+ assert result == {
+ "status": "stale",
+ "message": "Document indexed state changed during indexing, "
+ "flagged for reindex",
+ }
+ # The abort's _flag_document_for_reindex undid the flip again.
+ assert_pending(case)
+ assert backend._store.ids == before
+ assert not backend._store.removed
+
+
@pytest.mark.parametrize("mode", ["prepared", "serial"])
def test_text_writer_cannot_commit_between_claim_and_index_commit(
extraction_case, mode
):
+ """The claim fence blocks a competing writer until the index commit.
+
+ Premise note (#7557, PR 7759): the prepared path's status snapshot now
+ goes through worker-session index resolution instead of the
+ coordinator's ``rag_index_record`` (see ``indexer_for``) because
+ preparation must use worker-owned sessions. The claim fence this test
+ exercises is unchanged.
+ """
case = extraction_case(quality="low")
indexer, backend = indexer_for(case)
real_persist = backend.index_prepared
@@ -324,6 +481,15 @@ def test_chunk_invalidation_rolls_back_with_text_and_preserves_metadata(
@pytest.mark.parametrize("mode", ["prepared", "serial"])
def test_failed_reindex_keeps_old_chunks_invalidated(extraction_case, mode):
+ """A failed vector write leaves the old chunks invalidated and pending.
+
+ Premise note (#7557, PR 7759): the prepared path's status snapshot now
+ goes through worker-session index resolution instead of the
+ coordinator's ``rag_index_record`` (see ``indexer_for``) because
+ preparation must use worker-owned sessions. The failure-recovery
+ premise — old chunks stay invalidated when the vector write raises —
+ is unchanged.
+ """
case = extraction_case(quality="low")
indexer, backend = indexer_for(case)
replace_text(case)
diff --git a/tests/research_library/test_library_sync_integration.py b/tests/research_library/test_library_sync_integration.py
index 44163bddff..426b6f5de4 100644
--- a/tests/research_library/test_library_sync_integration.py
+++ b/tests/research_library/test_library_sync_integration.py
@@ -187,6 +187,16 @@ def test_regenerated_refill_keeps_old_vectors_invalid_until_reindexed(
tmp_path,
mode,
):
+ """Refilled docs keep old vectors invalidated until a reindex replaces them.
+
+ Premise note (#7557, PR 7759): mode="prepared" used to snapshot status
+ existence against the coordinator's ``rag_index_record``; preparation
+ now resolves the index through its own worker-owned session (the
+ coordinator's ORM record may expire mid-run and must not be refreshed
+ by a worker), so the ``indexer_for`` double provides that seam. The
+ premise tested here — a regenerated refill never resurrects old
+ vectors before the reindex — is unchanged.
+ """
case = extraction_case(quality="low", incoming=LONGER, storage="database")
base = tmp_path / "library"
case.service.library_root = base / case.service.username