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.

Release indexing caller scopes and protect transactions (#7087)

LearningCircuit8aa71a28a34b
diff --git a/changelog.d/+rag-batch-session-boundaries.bugfix.md b/changelog.d/+rag-batch-session-boundaries.bugfix.md
new file mode 100644
index 0000000000..ff3a030aa1
--- /dev/null
+++ b/changelog.d/+rag-batch-session-boundaries.bugfix.md
@@ -0,0 +1 @@
+The background collection Index task, both scheduled library sweep batches, and the bulk `index_all_documents` and `index_documents_batch` service helpers now release their database read scopes before indexing and progress callbacks, allowing indexing to own its transactions and reducing connection hold time during long runs.
diff --git a/changelog.d/+rag-transaction-ownership.bugfix.md b/changelog.d/+rag-transaction-ownership.bugfix.md
new file mode 100644
index 0000000000..0d0a3f20c8
--- /dev/null
+++ b/changelog.d/+rag-transaction-ownership.bugfix.md
@@ -0,0 +1 @@
+Preserve caller transactions: document indexing called while the same thread is inside an open `get_user_db_session` block is now rejected with an error result before it can commit or roll back that caller's pending writes. The parallel and bulk indexing entry points reject before they read, embed or run progress callbacks.
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 89d5e25ef1..eca6963168 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
@@ -51,6 +51,7 @@ from ...database.models.library import (
EmbeddingProvider,
)
from ...database.session_context import get_user_db_session, safe_rollback
+from ...database.thread_local_session import thread_session_manager
from ...utilities.type_utils import to_bool
from ..utils import ensure_in_collection
from ...embeddings.splitters import get_text_splitter
@@ -107,6 +108,26 @@ class _PreparedDocument:
_EMBEDDING_CANCEL_BATCH_SIZE = 32
+def _indexing_scope_error() -> Optional[Dict[str, str]]:
+ """Reject borrowed scopes before indexing can commit or roll them back.
+
+ Indexing commits writes and may recover from failures with a full rollback.
+ A nested scope reuses the caller's Session, so it cannot own either action.
+ Check before entering get_user_db_session, whose exception cleanup also
+ rolls back that Session.
+
+ Only an open ``get_user_db_session`` block on the calling thread counts
+ (``thread_session_manager.in_scope``). A Session obtained some other way,
+ such as directly from ``get_metrics_session``, is not detected.
+ """
+ if thread_session_manager.in_scope():
+ return {
+ "status": "error",
+ "error": "Indexing must run outside an existing database session",
+ }
+ return None
+
+
class _LazyEmbeddings(Embeddings):
"""Embeddings proxy that defers backend construction until first use.
@@ -1796,6 +1817,9 @@ class LibraryRAGService:
is_cancelled: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
"""Load, split, and embed without mutating collection state."""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ return scope_error
with get_user_db_session(self.username, self.db_password) as session:
document = session.query(Document).filter_by(id=document_id).first()
if not document:
@@ -1898,6 +1922,9 @@ class LibraryRAGService:
self, prepared: _PreparedDocument
) -> Dict[str, Any]:
"""Serialize chunk rows, FAISS mutation, status updates, and commit."""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ return scope_error
document_id = prepared.document_id
collection_id = prepared.collection_id
chunks = prepared.chunk_inputs
@@ -2134,6 +2161,11 @@ class LibraryRAGService:
def index_document(
self, document_id: str, collection_id: str, force_reindex: bool = False
) -> Dict[str, Any]:
+ # Reject before acquiring the collection lock: a caller holding a DB
+ # write transaction could otherwise deadlock a writer holding this lock.
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ return scope_error
collection_name = f"collection_{collection_id}"
index_hash = self._get_index_hash(
collection_name, self.embedding_model, self.embedding_provider
@@ -2178,6 +2210,10 @@ class LibraryRAGService:
Returns:
Dict with status, chunk_count, and any errors
"""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ return scope_error
+
# Phase 1: Read & chunk doc
with get_user_db_session(self.username, self.db_password) as session:
# Get the document
@@ -2764,8 +2800,23 @@ class LibraryRAGService:
progress_callback: Optional callback function called after each document with (current, total, doc_title, status)
Returns:
- Dict with counts of successful, skipped, and failed documents
+ Dict with counts of successful, skipped, and failed documents.
+ Inside an existing ``get_user_db_session`` block on this thread
+ it indexes nothing and returns ``status`` ``"error"`` with zero
+ counts.
"""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ # Reject before the read scope below: nested in the caller's
+ # scope, its exception cleanup would roll back the caller's
+ # Session.
+ return {
+ **scope_error,
+ "successful": 0,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ }
with get_user_db_session(self.username, self.db_password) as session:
# Get all DocumentCollection entries for this collection
query = session.query(DocumentCollection).filter_by(
@@ -2776,63 +2827,67 @@ class LibraryRAGService:
# Only index documents that haven't been indexed yet
query = query.filter_by(indexed=False)
- doc_collections = query.all()
-
- if not doc_collections:
- return {
- "status": "info",
- "message": "No documents to index",
- "successful": 0,
- "skipped": 0,
- "failed": 0,
- }
-
- results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}
- total = len(doc_collections)
-
- for idx, doc_collection in enumerate(doc_collections, 1):
- # Get the document for title info
+ # Materialize the values needed by the loop before leaving the
+ # read scope. A thread-local session is reused by nested calls;
+ # keeping this scope open during index_document would retain its
+ # connection throughout splitting, embedding, and callbacks.
+ doc_info = []
+ for doc_collection in query.all():
+ document_id = doc_collection.document_id
document = (
- session.query(Document)
- .filter_by(id=doc_collection.document_id)
- .first()
+ session.query(Document).filter_by(id=document_id).first()
)
- title = document.title if document else "Unknown"
-
- result = self.index_document(
- doc_collection.document_id, collection_id, force_reindex
+ doc_info.append(
+ (document_id, document.title if document else "Unknown")
)
- if result["status"] == "success":
- results["successful"] += 1
- elif result["status"] in ("skipped", "cleared"):
- # "cleared" (a previously-indexed doc emptied to no text,
- # its stale vectors purged) is a handled non-failure, not an
- # error — counting it in "failed" would surface a blank-error
- # failure for a correct purge.
- results["skipped"] += 1
- else:
- results["failed"] += 1
- results["errors"].append(
- {
- "doc_id": doc_collection.document_id,
- "title": title,
- "error": result.get("error"),
- }
- )
+ if not doc_info:
+ return {
+ "status": "info",
+ "message": "No documents to index",
+ "successful": 0,
+ "skipped": 0,
+ "failed": 0,
+ }
- # Call progress callback if provided
- if progress_callback:
- progress_callback(idx, total, title, result["status"])
+ results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}
+ total = len(doc_info)
- logger.info(
- f"Indexed collection {collection_id}: "
- f"{results['successful']} successful, "
- f"{results['skipped']} skipped, "
- f"{results['failed']} failed"
+ for idx, (document_id, title) in enumerate(doc_info, 1):
+ result = self.index_document(
+ document_id, collection_id, force_reindex
)
- return results
+ if result["status"] == "success":
+ results["successful"] += 1
+ elif result["status"] in ("skipped", "cleared"):
+ # "cleared" (a previously-indexed doc emptied to no text,
+ # its stale vectors purged) is a handled non-failure, not an
+ # error — counting it in "failed" would surface a blank-error
+ # failure for a correct purge.
+ results["skipped"] += 1
+ else:
+ results["failed"] += 1
+ results["errors"].append(
+ {
+ "doc_id": document_id,
+ "title": title,
+ "error": result.get("error"),
+ }
+ )
+
+ # Call progress callback if provided
+ if progress_callback:
+ progress_callback(idx, total, title, result["status"])
+
+ logger.info(
+ f"Indexed collection {collection_id}: "
+ f"{results['successful']} successful, "
+ f"{results['skipped']} skipped, "
+ f"{results['failed']} failed"
+ )
+
+ return results
def remove_document_from_rag(
self, document_id: str, collection_id: str
@@ -3166,12 +3221,20 @@ class LibraryRAGService:
force_reindex: Whether to force reindexing even if already indexed
Returns:
- Dict mapping doc_id to individual result
+ Dict mapping doc_id to individual result. Inside an existing
+ ``get_user_db_session`` block on this thread every result is the
+ scope error and nothing is read or indexed.
"""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ # Reject before the read scope below, for the same reason as
+ # index_all_documents.
+ return {doc_id: dict(scope_error) for doc_id, _title in doc_info}
results = {}
doc_ids = [doc_id for doc_id, _ in doc_info]
- # Use single database session for querying
+ # Use one short read scope to collect only scalar state. Keep the
+ # potentially slow per-document operations outside this scope.
with get_user_db_session(self.username, self.db_password) as session:
# Pre-load all documents for this batch
documents = (
@@ -3179,7 +3242,7 @@ class LibraryRAGService:
)
# Create lookup for quick access
- doc_lookup = {doc.id: doc for doc in documents}
+ existing_doc_ids = {doc.id for doc in documents}
# Pre-load DocumentCollection entries
doc_collections = (
@@ -3191,57 +3254,50 @@ class LibraryRAGService:
.all()
)
doc_collection_lookup = {
- dc.document_id: dc for dc in doc_collections
+ dc.document_id: (dc.indexed, dc.chunk_count)
+ for dc in doc_collections
}
- # Process each document in the batch
- for doc_id, title in doc_info:
- document = doc_lookup.get(doc_id)
-
- if not document:
- results[doc_id] = {
- "status": "error",
- "error": "Document not found",
- }
- continue
+ # Process each document after the read scope releases its connection.
+ for doc_id, title in doc_info:
+ if doc_id not in existing_doc_ids:
+ results[doc_id] = {
+ "status": "error",
+ "error": "Document not found",
+ }
+ continue
- # Check if already indexed via DocumentCollection
- doc_collection = doc_collection_lookup.get(doc_id)
- if (
- doc_collection
- and doc_collection.indexed
- and not force_reindex
- ):
- results[doc_id] = {
- "status": "skipped",
- "message": "Document already indexed for this collection",
- "chunk_count": doc_collection.chunk_count,
- }
- continue
+ # Check if already indexed via DocumentCollection
+ doc_collection = doc_collection_lookup.get(doc_id)
+ if doc_collection and doc_collection[0] and not force_reindex:
+ results[doc_id] = {
+ "status": "skipped",
+ "message": "Document already indexed for this collection",
+ "chunk_count": doc_collection[1],
+ }
+ continue
- # Do NOT short-circuit empty text_content here: a document/note
- # edited down to empty still has its PRIOR chunks + vectors on
- # disk, and only index_document's empty-content branch purges
- # them (via an empty-replace). Returning an "error" here left
- # that stale (plaintext) content permanently searchable through
- # the bulk "Index All" path — and self-perpetuating, since the
- # doc's indexed flag never flips. Route it through index_document
- # so the batch path gets the same purge-on-clear as the SSE /
- # single-document paths; it returns "cleared" (purged) or the
- # same "error" when there were no prior chunks.
- try:
- result = self.index_document(
- doc_id, collection_id, force_reindex
- )
- results[doc_id] = result
- except Exception as e:
- logger.exception(
- f"Error indexing document {doc_id} in batch"
- )
- results[doc_id] = {
- "status": "error",
- "error": f"Indexing failed: {type(e).__name__}",
- }
+ # Do NOT short-circuit empty text_content here: a document/note
+ # edited down to empty still has its PRIOR chunks + vectors on
+ # disk, and only index_document's empty-content branch purges
+ # them (via an empty-replace). Returning an "error" here left
+ # that stale (plaintext) content permanently searchable through
+ # the bulk "Index All" path — and self-perpetuating, since the
+ # doc's indexed flag never flips. Route it through index_document
+ # so the batch path gets the same purge-on-clear as the SSE /
+ # single-document paths; it returns "cleared" (purged) or the
+ # same "error" when there were no prior chunks.
+ try:
+ result = self.index_document(
+ doc_id, collection_id, force_reindex
+ )
+ results[doc_id] = result
+ except Exception as e:
+ logger.exception(f"Error indexing document {doc_id} in batch")
+ results[doc_id] = {
+ "status": "error",
+ "error": f"Indexing failed: {type(e).__name__}",
+ }
return results
@@ -3341,8 +3397,36 @@ class LibraryRAGService:
Returns:
``{"successful": int, "skipped": int, "failed": int,
"errors": [...], "results": {doc_id: {...}},
- "cancelled": bool, "total": int}``.
+ "cancelled": bool, "total": int}``. Inside an existing
+ ``get_user_db_session`` block on this thread nothing is loaded,
+ embedded or written and no callback runs: every document fails
+ with the scope error.
"""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ # Pool workers run on their own threads, where this caller's
+ # scope is invisible to _prepare_document's guard. Without this
+ # check every document would be loaded and embedded before the
+ # coordinator rejected its write.
+ title_lookup = dict(doc_info)
+ return {
+ "successful": 0,
+ "skipped": 0,
+ "failed": len(title_lookup),
+ "errors": [
+ {
+ "doc_id": doc_id,
+ "title": title,
+ "error": scope_error["error"],
+ }
+ for doc_id, title in title_lookup.items()
+ ],
+ "results": {
+ doc_id: dict(scope_error) for doc_id in title_lookup
+ },
+ "cancelled": False,
+ "total": len(doc_info),
+ }
if max_workers < 1:
max_workers = 1
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index 4bf179817a..7a40ca10eb 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -1533,98 +1533,101 @@ class BackgroundJobScheduler:
.all()
)
- # Group document ids by collection so we build exactly one RAG
- # service per collection (each collection can have its own
- # embedding config).
- docs_by_collection: Dict[str, List[str]] = {}
- for doc_id, coll_id in unindexed:
- docs_by_collection.setdefault(coll_id, []).append(doc_id)
-
- if unindexed:
- logger.info(
- f"[RECONCILER] Found {len(unindexed)} in-collection "
- f"unindexed document(s) across "
- f"{len(docs_by_collection)} collection(s) for {username}"
- )
+ # Group document ids by collection so we build exactly one RAG
+ # service per collection (each collection can have its own
+ # embedding config).
+ docs_by_collection: Dict[str, List[str]] = {}
+ for doc_id, coll_id in unindexed:
+ docs_by_collection.setdefault(coll_id, []).append(doc_id)
+
+ if unindexed:
+ logger.info(
+ f"[RECONCILER] Found {len(unindexed)} in-collection "
+ f"unindexed document(s) across "
+ f"{len(docs_by_collection)} collection(s) for {username}"
+ )
- for coll_id, doc_ids in docs_by_collection.items():
- try:
- # USE THE FACTORY so per-collection embedding settings
- # (model/provider/chunking/etc.) stored on the
- # collection are honored — get_rag_service loads them
- # from the collection row when collection_id is given.
- with get_rag_service(
- username,
- collection_id=coll_id,
- db_password=password,
- ) as rag_service:
- # Fan out across the per-collection batch using
- # the user-configured parallel-worker count
- # resolved above. Clamped to ``[1, 16]`` so a
- # misconfigured value can't blow the pool size
- # past the documented range.
- doc_info = [(doc_id, "") for doc_id in doc_ids]
- aggregate = rag_service.index_documents_parallel(
- doc_info,
- coll_id,
- force_reindex=False,
- max_workers=_max_parallel,
- )
- for doc_id in doc_ids:
- result = aggregate["results"].get(doc_id, {})
- if result.get("status") == "success":
- total_indexed += 1
- logger.debug(
- f"[RECONCILER] Indexed document {doc_id} "
- f"into collection {coll_id} with "
- f"{result.get('chunk_count', 0)} chunks"
- )
- elif result.get("status") == "error":
- # ``password`` is in scope and was
- # passed into ``get_rag_service``.
- # Drop the traceback chain + redact
- # str(e) to avoid leaking the
- # SQLCipher master password.
- safe_msg = redact_secrets(
- str(result.get("error", "")),
- password,
- )
- logger.warning(
- f"[RECONCILER] Failed to index document "
- f"{doc_id} into collection {coll_id}: {safe_msg}"
- )
- except Exception as coll_error:
- # Recover the shared thread-local session before moving
- # on to the next collection so its queries don't run on
- # a poisoned session.
- safe_rollback(db, "RECONCILER collection")
- safe_msg = redact_secrets(str(coll_error), password)
- logger.warning(
- f"[RECONCILER] Failed to index collection {coll_id}: {safe_msg}"
+ for coll_id, doc_ids in docs_by_collection.items():
+ try:
+ # USE THE FACTORY so per-collection embedding settings
+ # (model/provider/chunking/etc.) stored on the
+ # collection are honored — get_rag_service loads them
+ # from the collection row when collection_id is given.
+ with get_rag_service(
+ username,
+ collection_id=coll_id,
+ db_password=password,
+ ) as rag_service:
+ # Fan out across the per-collection batch using
+ # the user-configured parallel-worker count
+ # resolved above. Clamped to ``[1, 16]`` so a
+ # misconfigured value can't blow the pool size
+ # past the documented range.
+ doc_info = [(doc_id, "") for doc_id in doc_ids]
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ coll_id,
+ force_reindex=False,
+ max_workers=_max_parallel,
)
+ for doc_id in doc_ids:
+ result = aggregate["results"].get(doc_id, {})
+ if result.get("status") == "success":
+ total_indexed += 1
+ logger.debug(
+ f"[RECONCILER] Indexed document {doc_id} "
+ f"into collection {coll_id} with "
+ f"{result.get('chunk_count', 0)} chunks"
+ )
+ elif result.get("status") == "error":
+ # ``password`` is in scope and was
+ # passed into ``get_rag_service``.
+ # Drop the traceback chain + redact
+ # str(e) to avoid leaking the
+ # SQLCipher master password.
+ safe_msg = redact_secrets(
+ str(result.get("error", "")),
+ password,
+ )
+ logger.warning(
+ f"[RECONCILER] Failed to index document "
+ f"{doc_id} into collection {coll_id}: {safe_msg}"
+ )
+ except Exception as coll_error:
+ # The read scope has ended, but the coordinator's cached
+ # session may still need recovery after a failed writer.
+ safe_rollback(db, "RECONCILER collection")
+ safe_msg = redact_secrets(str(coll_error), password)
+ logger.warning(
+ f"[RECONCILER] Failed to index collection {coll_id}: {safe_msg}"
+ )
- # ---- Case (b): research orphans -> default library ---------
- # Research downloads land as Document rows (research_id set)
- # with NO DocumentCollection link yet. index_document()
- # ensure_in_collection's the default-library link, so this
- # ingests + indexes in one call.
- #
- # Case (b) gets its OWN independent _LIBRARY_SWEEP_BATCH budget
- # rather than the leftover of case (a). Case (a) only flips a
- # row to indexed=True on SUCCESS, so a block of permanently
- # failing case-(a) rows (empty text, embedding/FAISS errors,
- # PolicyDeniedError under egress denial) would otherwise fill
- # the LIMIT every tick, leave the leftover at 0, and starve the
- # research-orphan path forever — regressing the no-regression
- # promise for generate_rag-only users. Decoupling the budgets
- # caps total work at 2 x _LIBRARY_SWEEP_BATCH per tick, which is
- # acceptable. RANDOMIZED selection (see case (a)) so a block of
- # permanently-failing low-id orphans can't pin the LIMIT slots
- # every tick and starve the rest.
- #
- # Resolve the default library collection once.
- default_library_id = get_default_library_id(username, password)
+ # ---- Case (b): research orphans -> default library ---------
+ # Research downloads land as Document rows (research_id set)
+ # with NO DocumentCollection link yet. index_document()
+ # ensure_in_collection's the default-library link, so this
+ # ingests + indexes in one call.
+ #
+ # Case (b) gets its OWN independent _LIBRARY_SWEEP_BATCH budget
+ # rather than the leftover of case (a). Case (a) only flips a
+ # row to indexed=True on SUCCESS, so a block of permanently
+ # failing case-(a) rows (empty text, embedding/FAISS errors,
+ # PolicyDeniedError under egress denial) would otherwise fill
+ # the LIMIT every tick, leave the leftover at 0, and starve the
+ # research-orphan path forever — regressing the no-regression
+ # promise for generate_rag-only users. Decoupling the budgets
+ # caps total work at 2 x _LIBRARY_SWEEP_BATCH per tick, which is
+ # acceptable. RANDOMIZED selection (see case (a)) so a block of
+ # permanently-failing low-id orphans can't pin the LIMIT slots
+ # every tick and starve the rest.
+ #
+ # Resolve the default library collection once.
+ default_library_id = get_default_library_id(username, password)
+ # The prior indexing calls have finished their own transactions.
+ # Query the second batch in a fresh scope and release it before
+ # invoking the parallel coordinator again.
+ with get_user_db_session(username, password) as db:
orphans = (
db.query(Document.id)
.outerjoin(
@@ -1645,64 +1648,64 @@ class BackgroundJobScheduler:
.all()
)
- if orphans:
- logger.info(
- f"[RECONCILER] Found {len(orphans)} research "
- f"orphan document(s) to ingest into the default "
- f"library for {username}"
- )
- try:
- with get_rag_service(
- username,
- collection_id=default_library_id,
- db_password=password,
- ) as rag_service:
- # Same parallel fan-out as the in-collection
- # branch above; ``_max_parallel`` was resolved
- # from the user's saved
- # ``rag.indexing_max_parallel_docs`` setting at
- # the top of this tick.
- orphan_ids = [doc_id for (doc_id,) in orphans]
- doc_info = [(doc_id, "") for doc_id in orphan_ids]
- aggregate = rag_service.index_documents_parallel(
- doc_info,
- default_library_id,
- force_reindex=False,
- max_workers=_max_parallel,
- )
- for doc_id in orphan_ids:
- result = aggregate["results"].get(doc_id, {})
- if result.get("status") == "success":
- total_indexed += 1
- logger.debug(
- f"[RECONCILER] Ingested + "
- f"indexed research orphan "
- f"{doc_id} into the default "
- f"library with "
- f"{result.get('chunk_count', 0)} chunks"
- )
- elif result.get("status") == "error":
- safe_msg = redact_secrets(
- str(result.get("error", "")),
- password,
- )
- logger.warning(
- f"[RECONCILER] Failed to index "
- f"research orphan {doc_id}: {safe_msg}"
- )
- except Exception as orphan_error:
- safe_rollback(db, "RECONCILER orphans")
- safe_msg = redact_secrets(str(orphan_error), password)
- logger.warning(
- f"[RECONCILER] Failed to index research "
- f"orphans into the default library: {safe_msg}"
- )
-
+ if orphans:
logger.info(
- f"[RECONCILER] Completed reconcile for user {username}: "
- f"{total_indexed} document(s) indexed "
- f"(per-case batch cap {_LIBRARY_SWEEP_BATCH})"
+ f"[RECONCILER] Found {len(orphans)} research "
+ f"orphan document(s) to ingest into the default "
+ f"library for {username}"
)
+ try:
+ with get_rag_service(
+ username,
+ collection_id=default_library_id,
+ db_password=password,
+ ) as rag_service:
+ # Same parallel fan-out as the in-collection
+ # branch above; ``_max_parallel`` was resolved
+ # from the user's saved
+ # ``rag.indexing_max_parallel_docs`` setting at
+ # the top of this tick.
+ orphan_ids = [doc_id for (doc_id,) in orphans]
+ doc_info = [(doc_id, "") for doc_id in orphan_ids]
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ default_library_id,
+ force_reindex=False,
+ max_workers=_max_parallel,
+ )
+ for doc_id in orphan_ids:
+ result = aggregate["results"].get(doc_id, {})
+ if result.get("status") == "success":
+ total_indexed += 1
+ logger.debug(
+ f"[RECONCILER] Ingested + "
+ f"indexed research orphan "
+ f"{doc_id} into the default "
+ f"library with "
+ f"{result.get('chunk_count', 0)} chunks"
+ )
+ elif result.get("status") == "error":
+ safe_msg = redact_secrets(
+ str(result.get("error", "")),
+ password,
+ )
+ logger.warning(
+ f"[RECONCILER] Failed to index "
+ f"research orphan {doc_id}: {safe_msg}"
+ )
+ except Exception as orphan_error:
+ safe_rollback(db, "RECONCILER orphans")
+ safe_msg = redact_secrets(str(orphan_error), password)
+ logger.warning(
+ f"[RECONCILER] Failed to index research "
+ f"orphans into the default library: {safe_msg}"
+ )
+
+ logger.info(
+ f"[RECONCILER] Completed reconcile for user {username}: "
+ f"{total_indexed} document(s) indexed "
+ f"(per-case batch cap {_LIBRARY_SWEEP_BATCH})"
+ )
except Exception as e:
# ``password`` is pre-declared as ``None`` at the top of the
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 8773ee905b..1feda59625 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -4112,103 +4112,97 @@ def _background_index_worker(
db_session.commit()
_unlink_reindex_faiss_files(faiss_reset_paths)
- # Get documents to index
- doc_links = _query_documents_to_index(
- db_session, collection_id, force_reindex
- )
-
- if not doc_links:
- _update_task_status(
- username,
- db_password,
- task_id,
- status="completed",
- progress_message="No documents to index",
+ # Keep only scalar values after the setup scope exits. The
+ # parallel coordinator owns its per-document write scopes.
+ doc_info = [
+ (doc.id, doc.filename or doc.title or "Unknown")
+ for _link, doc in _query_documents_to_index(
+ db_session, collection_id, force_reindex
)
- return
-
- total = len(doc_links)
- results = {"successful": 0, "skipped": 0, "failed": 0}
+ ]
- # Update task with total count
+ if not doc_info:
_update_task_status(
username,
db_password,
task_id,
- progress_total=total,
- progress_message=f"Indexing {total} documents",
+ status="completed",
+ progress_message="No documents to index",
)
+ return
- # The caller (start_background_index, which owns the
- # Flask request context) resolved ``max_workers`` from
- # ``rag.indexing_max_parallel_docs`` and forwarded it
- # here. Workers must NOT call ``get_settings_manager()``
- # themselves — no Flask app context, pre-commit
- # ``check-settings-manager-thread-safety`` would reject,
- # and #3453 documents the data-loss shape that produces.
- _max_workers = max(1, min(int(max_workers), 16))
-
- doc_info = [
- (doc.id, doc.filename or doc.title or "Unknown")
- for _link, doc in doc_links
- ]
+ total = len(doc_info)
+ results = {"successful": 0, "skipped": 0, "failed": 0}
- def _on_progress(
- completed: int,
- total: int,
- title: str,
- status: str,
- ) -> None:
- _update_task_status(
- username,
- db_password,
- task_id,
- progress_current=completed,
- progress_message=(
- f"Indexing {completed}/{total}: {title}"
- ),
- )
+ # Update task with total count
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ progress_total=total,
+ progress_message=f"Indexing {total} documents",
+ )
- def _is_cancelled() -> bool:
- return _is_task_cancelled(username, db_password, task_id)
+ # The caller (start_background_index, which owns the
+ # Flask request context) resolved ``max_workers`` from
+ # ``rag.indexing_max_parallel_docs`` and forwarded it
+ # here. Workers must NOT call ``get_settings_manager()``
+ # themselves — no Flask app context, pre-commit
+ # ``check-settings-manager-thread-safety`` would reject,
+ # and #3453 documents the data-loss shape that produces.
+ _max_workers = max(1, min(int(max_workers), 16))
- aggregate = rag_service.index_documents_parallel(
- doc_info,
- collection_id,
- force_reindex=force_reindex,
- max_workers=_max_workers,
- progress_callback=_on_progress,
- is_cancelled=_is_cancelled,
+ def _on_progress(
+ completed: int,
+ total: int,
+ title: str,
+ status: str,
+ ) -> None:
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ progress_current=completed,
+ progress_message=(f"Indexing {completed}/{total}: {title}"),
)
- results["successful"] = aggregate["successful"]
- results["skipped"] = aggregate["skipped"]
- results["failed"] = aggregate["failed"]
- results["errors"] = aggregate["errors"]
+ def _is_cancelled() -> bool:
+ return _is_task_cancelled(username, db_password, task_id)
- if aggregate["cancelled"]:
- completed = (
- aggregate["successful"]
- + aggregate["skipped"]
- + aggregate["failed"]
- )
- _update_task_status(
- username,
- db_password,
- task_id,
- status="cancelled",
- progress_message=(
- f"Cancelled after {completed}/{total} documents"
- ),
- )
- logger.info(
- f"Indexing task {task_id} was cancelled "
- f"after {completed}/{total} documents"
- )
- db_session.commit()
- return
+ aggregate = rag_service.index_documents_parallel(
+ doc_info,
+ collection_id,
+ force_reindex=force_reindex,
+ max_workers=_max_workers,
+ progress_callback=_on_progress,
+ is_cancelled=_is_cancelled,
+ )
- db_session.commit()
+ results["successful"] = aggregate["successful"]
+ results["skipped"] = aggregate["skipped"]
+ results["failed"] = aggregate["failed"]
+ results["errors"] = aggregate["errors"]
+
+ if aggregate["cancelled"]:
+ completed = (
+ aggregate["successful"]
+ + aggregate["skipped"]
+ + aggregate["failed"]
+ )
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ status="cancelled",
+ progress_message=(
+ f"Cancelled after {completed}/{total} documents"
+ ),
+ )
+ logger.info(
+ f"Indexing task {task_id} was cancelled "
+ f"after {completed}/{total} documents"
+ )
+ return
# Wrap reconciliation so a transient store/DB error does not
# leave the task in "processing" forever (the previous code
diff --git a/tests/news/test_library_sweep.py b/tests/news/test_library_sweep.py
index 0c21b5b62c..8313975ed6 100644
--- a/tests/news/test_library_sweep.py
+++ b/tests/news/test_library_sweep.py
@@ -808,6 +808,94 @@ def real_db_session():
engine.dispose()
[email protected]("fail_collection", [False, True])
+def test_both_sweep_batches_release_their_read_scope(
+ real_db_session, fail_collection
+):
+ """Each batch can own its writes, even after the previous batch fails."""
+ from local_deep_research.database.models.library import DocumentCollection
+ from local_deep_research.database.session_context import get_user_db_session
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ session, source_id, default_id, collection_id = real_db_session
+ _seed_document(session, source_id, doc_id="upload", text_content="upload")
+ _seed_document(
+ session,
+ source_id,
+ doc_id="orphan",
+ text_content="download",
+ research_id="research",
+ )
+ session.add(
+ DocumentCollection(
+ document_id="upload", collection_id=collection_id, indexed=False
+ )
+ )
+ session.commit()
+ scheduler = _fresh_scheduler()
+ service = _rag_service()
+ scopes = []
+
+ def write_batch(doc_info, target_collection, **kwargs):
+ scopes.append(thread_session_manager.in_scope())
+ assert not thread_session_manager.in_scope()
+ assert not session.in_transaction()
+ with get_user_db_session("testuser", "testpass") as writer:
+ for doc_id, _ in doc_info:
+ link = (
+ writer.query(DocumentCollection)
+ .filter_by(
+ document_id=doc_id, collection_id=target_collection
+ )
+ .first()
+ )
+ if link is None:
+ link = DocumentCollection(
+ document_id=doc_id, collection_id=target_collection
+ )
+ writer.add(link)
+ link.indexed = True
+ writer.flush()
+ if fail_collection and target_collection == collection_id:
+ raise RuntimeError("collection write failed")
+ writer.commit()
+ return _default_parallel_side_effect(doc_info, target_collection)
+
+ service.index_documents_parallel.side_effect = write_batch
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=DocumentSchedulerSettings(
+ sweep_library_collections=True
+ ),
+ ),
+ _patched_session(session),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ return_value=session,
+ ),
+ patch(FACTORY, return_value=service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ assert scopes == [False, False]
+ indexed = {
+ (link.document_id, link.collection_id): link.indexed
+ for link in session.query(DocumentCollection).all()
+ }
+ assert indexed == {
+ ("upload", collection_id): not fail_collection,
+ ("orphan", default_id): True,
+ }
+
+
def test_case_a_predicate_selects_only_unindexed_with_text_real_db(
real_db_session,
):
diff --git a/tests/research_library/services/test_batch_index_session_scope.py b/tests/research_library/services/test_batch_index_session_scope.py
new file mode 100644
index 0000000000..3a4acd348e
--- /dev/null
+++ b/tests/research_library/services/test_batch_index_session_scope.py
@@ -0,0 +1,139 @@
+"""Bulk indexing must release its read scope before slow per-doc work."""
+
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentCollection,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+
+
+def _service():
+ service = object.__new__(LibraryRAGService)
+ service.username = "alice"
+ service._db_password = "test-password"
+ return service
+
+
+def _read_scope(session):
+ active = {"value": False}
+
+ @contextmanager
+ def get_session(*args, **kwargs):
+ assert not active["value"]
+ active["value"] = True
+ try:
+ yield session
+ finally:
+ active["value"] = False
+
+ return active, get_session
+
+
+def test_index_all_releases_read_scope_before_index_and_progress():
+ service = _service()
+ session = Mock()
+ links = [
+ SimpleNamespace(document_id="one"),
+ SimpleNamespace(document_id="two"),
+ ]
+ documents = {
+ "one": SimpleNamespace(title="First"),
+ "two": SimpleNamespace(title="Second"),
+ }
+
+ links_query = Mock()
+ links_query.filter_by.return_value = links_query
+ links_query.all.return_value = links
+
+ def query(model):
+ if model is DocumentCollection:
+ return links_query
+ assert model is Document
+ document_query = Mock()
+ document_query.filter_by.side_effect = lambda *, id: SimpleNamespace(
+ first=lambda: documents[id]
+ )
+ return document_query
+
+ session.query.side_effect = query
+ active, get_session = _read_scope(session)
+ indexed = []
+ progressed = []
+
+ def index_document(document_id, collection_id, force_reindex):
+ assert not active["value"]
+ indexed.append((document_id, collection_id, force_reindex))
+ return {"status": "success", "chunk_count": 1}
+
+ def progress(index, total, title, status):
+ assert not active["value"]
+ progressed.append((index, total, title, status))
+
+ service.index_document = index_document
+ with patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
+ side_effect=get_session,
+ ):
+ result = service.index_all_documents(
+ "collection", progress_callback=progress
+ )
+
+ assert indexed == [
+ ("one", "collection", False),
+ ("two", "collection", False),
+ ]
+ assert progressed == [
+ (1, 2, "First", "success"),
+ (2, 2, "Second", "success"),
+ ]
+ assert result["successful"] == 2
+
+
+def test_index_batch_releases_read_scope_before_per_document_work():
+ service = _service()
+ session = Mock()
+ docs_query = Mock()
+ docs_query.filter.return_value = docs_query
+ docs_query.all.return_value = [
+ SimpleNamespace(id="one"),
+ SimpleNamespace(id="two"),
+ ]
+ links_query = Mock()
+ links_query.filter.return_value = links_query
+ links_query.all.return_value = [
+ SimpleNamespace(document_id="one", indexed=False, chunk_count=0),
+ SimpleNamespace(document_id="two", indexed=True, chunk_count=3),
+ ]
+ session.query.side_effect = lambda model: (
+ docs_query if model is Document else links_query
+ )
+ active, get_session = _read_scope(session)
+ indexed = []
+
+ def index_document(document_id, collection_id, force_reindex):
+ assert not active["value"]
+ indexed.append((document_id, collection_id, force_reindex))
+ return {"status": "success", "chunk_count": 1}
+
+ service.index_document = index_document
+ with patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
+ side_effect=get_session,
+ ):
+ result = service.index_documents_batch(
+ [("one", "First"), ("two", "Second")], "collection"
+ )
+
+ assert indexed == [("one", "collection", False)]
+ assert result["one"]["status"] == "success"
+ assert result["two"] == {
+ "status": "skipped",
+ "message": "Document already indexed for this collection",
+ "chunk_count": 3,
+ }
diff --git a/tests/research_library/services/test_rag_transaction_ownership.py b/tests/research_library/services/test_rag_transaction_ownership.py
new file mode 100644
index 0000000000..91ae86e004
--- /dev/null
+++ b/tests/research_library/services/test_rag_transaction_ownership.py
@@ -0,0 +1,557 @@
+"""Indexing rejects borrowed sessions without changing caller transactions.
+
+Production callers must therefore leave their own ``get_user_db_session``
+blocks before they index; the last tests here pin that.
+"""
+
+import ast
+import textwrap
+import threading
+from contextlib import nullcontext
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+import local_deep_research
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentCollection,
+ DocumentStatus,
+ EmbeddingProvider,
+ RAGIndex,
+ SourceType,
+)
+from local_deep_research.database.models.queue import TaskMetadata
+from local_deep_research.database.session_context import get_user_db_session
+from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+)
+from local_deep_research.research_library.services import (
+ library_rag_service as rag_service_module,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+
+SCOPE_ERROR = "Indexing must run outside an existing database session"
+
+
+def rig(tmp_path):
+ engine = create_engine(
+ f"sqlite:///{tmp_path / 'review.sqlite'}", connect_args={"timeout": 0.1}
+ )
+ Base.metadata.create_all(engine)
+ factory = sessionmaker(bind=engine)
+ with factory() as setup:
+ setup.add_all(
+ [
+ SourceType(
+ id="source", name="document", display_name="Document"
+ ),
+ Collection(
+ id="collection",
+ name="Library",
+ collection_type="default_library",
+ ),
+ Document(
+ id="doc",
+ source_type_id="source",
+ document_hash="hash",
+ title="Original",
+ text_content="Text to index",
+ file_size=13,
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ ),
+ RAGIndex(
+ id=1,
+ collection_name="collection_collection",
+ embedding_model="test-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=3,
+ index_path=str(tmp_path / "index"),
+ index_hash="review",
+ chunk_size=500,
+ chunk_overlap=50,
+ ),
+ ]
+ )
+ setup.commit()
+ session = factory()
+ service = LibraryRAGService.__new__(LibraryRAGService)
+ service.username = "local_review"
+ service._db_password = "test-only"
+ service.embedding_model = "test-model"
+ service.embedding_provider = "test-provider"
+ service.rag_index_record = SimpleNamespace(id=1)
+ service.text_splitter = MagicMock()
+ service.text_splitter.split_documents.side_effect = lambda docs: docs
+ service.embedding_manager = MagicMock()
+ observations = []
+
+ def embed(texts):
+ observations.append(
+ {
+ "in_transaction": session.in_transaction(),
+ "checked_out": engine.pool.checkedout(),
+ }
+ )
+ return [[0.1, 0.2, 0.3] for _ in texts]
+
+ service.embedding_manager.embeddings.embed_documents.side_effect = embed
+ vector_index = MagicMock()
+ stats = SimpleNamespace(added=1, removed=0, chunks=1)
+ vector_index.index_prepared.return_value = stats
+
+ def index(**kwargs):
+ service.embedding_manager.embeddings.embed_documents(
+ [c.text for c in kwargs["chunks"]]
+ )
+ return stats
+
+ vector_index.index.side_effect = index
+ service._get_vector_index = MagicMock(return_value=vector_index)
+ service._get_index_hash = MagicMock(return_value="review")
+ service._get_index_path = MagicMock(return_value=tmp_path / "index")
+
+ # Like thread_session_manager, give each thread its own Session. The test
+ # thread gets ``session``; indexing pool threads get their own.
+ local = threading.local()
+ local.session = session
+ sessions = [session]
+ sessions_lock = threading.Lock()
+
+ def thread_session(_username, _password):
+ if getattr(local, "session", None) is None:
+ local.session = factory()
+ with sessions_lock:
+ sessions.append(local.session)
+ return local.session
+
+ with patch(
+ "local_deep_research.database.thread_local_session.get_metrics_session",
+ side_effect=thread_session,
+ ):
+ yield SimpleNamespace(
+ engine=engine,
+ factory=factory,
+ session=session,
+ service=service,
+ observations=observations,
+ )
+ for owned in sessions:
+ owned.close()
+ engine.dispose()
+
+
+def add_membership(rig):
+ with rig.factory() as session:
+ session.add(
+ DocumentCollection(
+ document_id="doc", collection_id="collection", indexed=False
+ )
+ )
+ session.commit()
+
+
+def test_serial_rejects_enclosing_write_without_discarding_it(rig):
+ add_membership(rig)
+ with get_user_db_session("local_review", "test-only") as outer:
+ document = outer.query(Document).filter_by(id="doc").one()
+ document.title = "Caller edit"
+ outer.flush()
+ result = rig.service.index_document("doc", "collection")
+ assert result == {
+ "status": "error",
+ "error": "Indexing must run outside an existing database session",
+ }
+ assert outer.in_transaction()
+ assert document.title == "Caller edit"
+ assert rig.observations == []
+ rig.service._get_index_path.assert_not_called()
+ with rig.factory() as observer:
+ assert (
+ observer.query(Document).filter_by(id="doc").one().title
+ == "Original"
+ )
+ outer.commit()
+ with rig.factory() as check:
+ assert (
+ check.query(Document).filter_by(id="doc").one().title
+ == "Caller edit"
+ )
+ assert (
+ rig.service.index_document("doc", "collection")["status"] == "success"
+ )
+
+
+def test_serial_rejects_staged_membership_without_discarding_it(rig):
+ with get_user_db_session("local_review", "test-only") as outer:
+ outer.add(
+ DocumentCollection(
+ document_id="doc", collection_id="collection", indexed=False
+ )
+ )
+ outer.flush()
+ result = rig.service.index_document("doc", "collection")
+ assert result["status"] == "error", result
+ assert rig.observations == []
+ assert (
+ outer.query(DocumentCollection)
+ .filter_by(document_id="doc", collection_id="collection")
+ .count()
+ == 1
+ )
+ with rig.factory() as observer:
+ assert (
+ observer.query(DocumentCollection)
+ .filter_by(document_id="doc", collection_id="collection")
+ .count()
+ == 0
+ )
+ outer.commit()
+ with rig.factory() as check:
+ assert (
+ check.query(DocumentCollection)
+ .filter_by(document_id="doc", collection_id="collection")
+ .count()
+ == 1
+ )
+ assert (
+ rig.service.index_document("doc", "collection")["status"] == "success"
+ )
+
+
[email protected]("entry", ["locked", "prepare", "persist"])
+def test_internal_indexing_entries_preserve_borrowed_transactions(rig, entry):
+ add_membership(rig)
+ prepared = None
+ if entry == "persist":
+ prepared = rig.service._prepare_document("doc", "collection", False)[
+ "prepared"
+ ]
+ rig.observations.clear()
+ with get_user_db_session("local_review", "test-only") as outer:
+ document = outer.query(Document).filter_by(id="doc").one()
+ document.title = "Caller edit"
+ outer.flush()
+ if entry == "locked":
+ result = rig.service._index_document_locked("doc", "collection")
+ elif entry == "prepare":
+ result = rig.service._prepare_document("doc", "collection", False)
+ else:
+ result = rig.service._write_prepared_document(prepared)
+ assert result["status"] == "error", result
+ assert rig.observations == []
+ assert outer.in_transaction()
+ assert document.title == "Caller edit"
+ with rig.factory() as observer:
+ assert (
+ observer.query(Document).filter_by(id="doc").one().title
+ == "Original"
+ )
+ outer.commit()
+ with rig.factory() as check:
+ assert (
+ check.query(Document).filter_by(id="doc").one().title
+ == "Caller edit"
+ )
+
+
+def test_serial_first_time_membership_succeeds(rig):
+ result = rig.service.index_document("doc", "collection")
+ assert result["status"] == "success", result
+ with rig.factory() as check:
+ membership = (
+ check.query(DocumentCollection)
+ .filter_by(document_id="doc", collection_id="collection")
+ .one()
+ )
+ assert membership.indexed is True
+
+
[email protected]("entry", ["parallel", "all", "batch"])
+def test_bulk_entries_reject_before_reading_or_embedding(rig, entry):
+ """Bulk entry points reject a borrowed scope before doing any work.
+
+ The bulk helpers would read inside a nested scope, whose exception
+ cleanup rolls back the caller's Session. The parallel pool workers run
+ on other threads, where ``_prepare_document``'s guard cannot see this
+ caller's scope, so without an entry check every document would be
+ embedded and only its write rejected.
+ """
+ add_membership(rig)
+ opened = []
+ real_scope = rag_service_module.get_user_db_session
+
+ def counted_scope(*args, **kwargs):
+ opened.append(threading.current_thread().name)
+ return real_scope(*args, **kwargs)
+
+ rejected = {"status": "error", "error": SCOPE_ERROR}
+ with get_user_db_session("local_review", "test-only") as outer:
+ document = outer.query(Document).filter_by(id="doc").one()
+ document.title = "Caller edit"
+ outer.flush()
+ with patch.object(
+ rag_service_module, "get_user_db_session", counted_scope
+ ):
+ if entry == "parallel":
+ result = rig.service.index_documents_parallel(
+ [("doc", "Doc")], "collection", max_workers=1
+ )
+ elif entry == "all":
+ result = rig.service.index_all_documents("collection")
+ else:
+ result = rig.service.index_documents_batch(
+ [("doc", "Doc")], "collection"
+ )
+ assert opened == []
+ assert rig.observations == []
+ if entry == "parallel":
+ assert result == {
+ "successful": 0,
+ "skipped": 0,
+ "failed": 1,
+ "errors": [
+ {"doc_id": "doc", "title": "Doc", "error": SCOPE_ERROR}
+ ],
+ "results": {"doc": rejected},
+ "cancelled": False,
+ "total": 1,
+ }
+ elif entry == "all":
+ assert result == {
+ **rejected,
+ "successful": 0,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ }
+ else:
+ assert result == {"doc": rejected}
+ assert outer.in_transaction()
+ assert document.title == "Caller edit"
+ with rig.factory() as observer:
+ assert (
+ observer.query(Document).filter_by(id="doc").one().title
+ == "Original"
+ )
+ outer.commit()
+ with rig.factory() as check:
+ assert (
+ check.query(Document).filter_by(id="doc").one().title
+ == "Caller edit"
+ )
+
+
+def test_background_index_worker_indexes_outside_its_setup_scope(rig):
+ """The normal collection Index action must not lend its setup scope.
+
+ ``_background_index_worker`` reads the collection inside
+ ``get_user_db_session`` and has to leave that block before it calls
+ ``index_documents_parallel``. The coordinator runs
+ ``_write_prepared_document`` on this same thread, so an open setup scope
+ would make the guard fail every document. Every session here really
+ enters the scope, as in production, so moving the call back inside the
+ block fails this test.
+ """
+ from local_deep_research.web.routers import rag as rag_router
+
+ add_membership(rig)
+ with rig.factory() as setup:
+ # Indexed before, so the worker skips first-index metadata capture.
+ collection = setup.query(Collection).filter_by(id="collection").one()
+ collection.embedding_model = "test-model"
+ setup.add(
+ TaskMetadata(
+ task_id="task",
+ status="processing",
+ task_type="indexing",
+ progress_current=0,
+ progress_total=0,
+ metadata_json={"collection_id": "collection"},
+ )
+ )
+ setup.commit()
+
+ service = rig.service
+ scopes = {"coordinator": [], "write": []}
+ coordinate = service.index_documents_parallel
+ write = service._write_prepared_document
+
+ def observed_coordinate(*args, **kwargs):
+ scopes["coordinator"].append(thread_session_manager.in_scope())
+ return coordinate(*args, **kwargs)
+
+ def observed_write(prepared):
+ scopes["write"].append(thread_session_manager.in_scope())
+ return write(prepared)
+
+ service.index_documents_parallel = observed_coordinate
+ service._write_prepared_document = observed_write
+ service.reconcile_collection_index = MagicMock(
+ return_value={
+ "indexed_documents": 1,
+ "indexed_chunks": 1,
+ "live_vectors": 1,
+ "orphan_vectors": 0,
+ }
+ )
+ with patch.object(
+ rag_router,
+ "_get_rag_service_for_thread",
+ return_value=nullcontext(service),
+ ):
+ rag_router._background_index_worker(
+ "task", "collection", "local_review", "test-only", False, 2
+ )
+
+ with rig.factory() as check:
+ task = check.query(TaskMetadata).filter_by(task_id="task").one()
+ assert task.status == "completed", (
+ task.error_message,
+ task.metadata_json,
+ )
+ result = task.metadata_json["result"]
+ assert (result["successful"], result["failed"], result["errors"]) == (
+ 1,
+ 0,
+ [],
+ )
+ membership = (
+ check.query(DocumentCollection)
+ .filter_by(document_id="doc", collection_id="collection")
+ .one()
+ )
+ assert membership.indexed is True
+ assert scopes == {"coordinator": [False], "write": [False]}
+ service._get_vector_index.return_value.index_prepared.assert_called_once()
+
+
+_INDEXING_METHODS = frozenset(
+ {
+ "index_document",
+ "index_documents_parallel",
+ "index_all_documents",
+ "index_documents_batch",
+ "_index_one",
+ "_index_document_locked",
+ "_prepare_document",
+ "_write_prepared_document",
+ }
+)
+
+
+def _called_name(node):
+ target = node.func if isinstance(node, ast.Call) else node
+ if isinstance(target, ast.Name):
+ return target.id
+ return getattr(target, "attr", None)
+
+
+def indexing_calls_inside_scope(tree):
+ """``(lineno, method)`` for each indexing call made inside a scope.
+
+ A scope is the body of ``with get_user_db_session(...)`` or of a function
+ decorated with ``with_user_database``. A nested function starts outside
+ any scope: it runs when it is called, not where it is defined.
+ """
+ found = []
+
+ def visit(node, scoped):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ scoped = any(
+ _called_name(decorator) == "with_user_database"
+ for decorator in node.decorator_list
+ )
+ elif isinstance(node, ast.Lambda):
+ scoped = False
+ elif isinstance(node, (ast.With, ast.AsyncWith)):
+ for item in node.items:
+ visit(item, scoped)
+ inner = scoped or any(
+ isinstance(item.context_expr, ast.Call)
+ and _called_name(item.context_expr) == "get_user_db_session"
+ for item in node.items
+ )
+ for statement in node.body:
+ visit(statement, inner)
+ return
+ elif (
+ scoped
+ and isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr in _INDEXING_METHODS
+ ):
+ found.append((node.lineno, node.func.attr))
+ for child in ast.iter_child_nodes(node):
+ visit(child, scoped)
+
+ visit(tree, False)
+ return found
+
+
+def test_scope_scanner_flags_only_calls_made_inside_a_scope():
+ tree = ast.parse(
+ textwrap.dedent(
+ """\
+ def worker(service):
+ with get_user_db_session(user, password) as db:
+ doc_info = load(db)
+ service.index_documents_parallel(doc_info, "c")
+ service.index_documents_parallel(doc_info, "c")
+ with get_user_db_session(user, password) as db:
+ def later():
+ service.index_document("d", "c")
+ later()
+
+ @with_user_database
+ def decorated(db, service):
+ service.index_all_documents("c")
+ """
+ )
+ )
+ assert indexing_calls_inside_scope(tree) == [
+ (4, "index_documents_parallel"),
+ (13, "index_all_documents"),
+ ]
+
+
+def test_no_production_caller_indexes_inside_a_session_scope():
+ """A call written inside a scope would fail every document at run time.
+
+ The guard rejects indexing inside a ``get_user_db_session`` block on the
+ calling thread. The background Index worker, both scheduler sweep
+ batches and the bulk helpers had their indexing calls inside their setup
+ scopes and had to move them out; this keeps every call site out.
+ """
+ package = Path(local_deep_research.__file__).resolve().parent
+ violations = []
+ for path in sorted(package.rglob("*.py")):
+ source = path.read_text(encoding="utf-8")
+ if (
+ "get_user_db_session" not in source
+ and "with_user_database" not in source
+ ):
+ continue
+ if not any(method in source for method in _INDEXING_METHODS):
+ continue
+ violations.extend(
+ f"{path.relative_to(package)}:{lineno} {method}()"
+ for lineno, method in indexing_calls_inside_scope(
+ ast.parse(source, filename=str(path))
+ )
+ )
+ assert violations == [], (
+ "Indexing called inside a get_user_db_session block; the guard "
+ "rejects it. Collect plain values inside the block, leave it, then "
+ "index:\n" + "\n".join(violations)
+ )