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): serialize durable writes and reconcile indexes (#5235)

S7dad88237fa8
diff --git a/changelog.d/+task-status-update-tenacity-retry.bugfix.md b/changelog.d/+task-status-update-tenacity-retry.bugfix.md
new file mode 100644
index 0000000000..b6fcefcc3f
--- /dev/null
+++ b/changelog.d/+task-status-update-tenacity-retry.bugfix.md
@@ -0,0 +1 @@
+**Replaced manual `database is locked` retry loop with `tenacity` in `_update_task_status`.** The five-attempt `for attempt in range(5)` with `time.sleep(0.05 * (2**attempt))` was rewritten using `tenacity.retry(stop=stop_after_attempt(5), wait=wait_exponential(multiplier=0.05), retry=retry_if_exception(_is_database_locked_error))`, matching the rest of the codebase's retry idiom. The predicate limits retries to SQLite `database is locked` errors; any other exception still escapes on the first attempt so the outer caller can log it without further retry. Total wall-clock backoff is unchanged (~0.05+0.10+0.20+0.40 s before the final attempt). Pins: three regression tests in `tests/research_library/routes/test_rag_routes_background_coverage.py` verify retry-then-success, fail-fast on non-lock errors, and exhaustion logging.
diff --git a/changelog.d/5235.bugfix.md b/changelog.d/5235.bugfix.md
new file mode 100644
index 0000000000..8b65cd72f9
--- /dev/null
+++ b/changelog.d/5235.bugfix.md
@@ -0,0 +1 @@
+**Fixed parallel RAG indexing durability and vector index reconciliation.** Serialized durable writes to prevent parallel-worker SQLite/FAISS corruption, hardened per-collection FAISS write locks with TOCTOU safety guards, and added refuse-to-shrink guards to index reconciliation to protect existing vector stores during transient failures.
diff --git a/src/local_deep_research/database/queue_service.py b/src/local_deep_research/database/queue_service.py
index 8783f61983..d4055bf7a6 100644
--- a/src/local_deep_research/database/queue_service.py
+++ b/src/local_deep_research/database/queue_service.py
@@ -146,13 +146,13 @@ class UserQueueService:
]
def cleanup_old_tasks(self, days: int = 7) -> int:
- """Clean up old completed/failed tasks."""
+ """Clean up old completed/failed/cancelled tasks."""
cutoff_date = datetime.now(UTC) - timedelta(days=days)
deleted = (
self.session.query(TaskMetadata)
.filter(
- TaskMetadata.status.in_(["completed", "failed"]),
+ TaskMetadata.status.in_(["completed", "failed", "cancelled"]),
TaskMetadata.completed_at < cutoff_date,
)
.delete()
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 55876aa75a..d48f20ed06 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -31,6 +31,12 @@ from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, UTC
from pathlib import Path
from typing import Dict, Optional, Set, Tuple
+from tenacity import (
+ retry,
+ retry_if_exception,
+ stop_after_attempt,
+ wait_exponential,
+)
from sqlalchemy.orm import defer
@@ -1295,10 +1301,10 @@ def get_collections():
# No need to filter by username - each user has their own database
collections = db_session.query(Collection).all()
- # How many documents in each collection are already indexed for
- # RAG search. Computed once as a grouped aggregate (mirrors
- # LibraryService.get_all_collections) so the per-collection
- # "X of Y indexed" / pending status doesn't trigger an N+1.
+ # Canonical durable count. Reconciliation maintains these rows from
+ # actual FAISS membership; the legacy DocumentCollection.indexed flag
+ # is retained only for compatibility and must not drive user-visible
+ # truth.
indexed_counts = dict(
db_session.query(
DocumentCollection.collection_id,
@@ -2824,6 +2830,23 @@ def _auto_index_documents_worker(
logger.exception("Auto-indexing worker failed")
+def _sanitized_indexing_errors(results: dict, limit: int = 50) -> list:
+ """Return a sanitized, bounded list of per-document errors for the
+ indexing task metadata. Used by both terminal paths of
+ :func:`_background_index_worker` so the scrubbing logic is defined once.
+ """
+ return [
+ {
+ "doc_id": item.get("doc_id"),
+ "title": item.get("title"),
+ "error": sanitize_error_message(
+ str(item.get("error") or "Indexing failed")
+ ),
+ }
+ for item in results.get("errors", [])[:limit]
+ ]
+
+
@thread_cleanup
def _background_index_worker(
task_id: str,
@@ -2960,6 +2983,7 @@ def _background_index_worker(
results["successful"] = aggregate["successful"]
results["skipped"] = aggregate["skipped"]
results["failed"] = aggregate["failed"]
+ results["errors"] = aggregate["errors"]
if aggregate["cancelled"]:
completed = (
@@ -2985,14 +3009,118 @@ def _background_index_worker(
db_session.commit()
- # Mark as completed
+ # Wrap reconciliation so a transient store/DB error does not
+ # leave the task in "processing" forever (the previous code
+ # let exceptions escape, so _update_task_status never ran and
+ # the UI polled indefinitely — see PR #5235 review comment
+ # 5085604502). On failure we still record a terminal status
+ # so cleanup_old_tasks can reap the row.
+ try:
+ reconciliation = rag_service.reconcile_collection_index(
+ collection_id
+ )
+ except Exception as exc:
+ logger.exception(
+ f"Background indexing task {task_id}: reconciliation failed"
+ )
+ reconciliation = {
+ "indexed_documents": results["successful"],
+ "indexed_chunks": 0,
+ "live_vectors": 0,
+ "orphan_vectors": 0,
+ "reconciliation_skipped": True,
+ "reconciliation_reason": sanitize_error_message(str(exc)),
+ }
+ if not isinstance(reconciliation, dict):
+ reconciliation = {
+ "indexed_documents": results["successful"],
+ "indexed_chunks": 0,
+ "live_vectors": 0,
+ "orphan_vectors": 0,
+ }
+ # The reconciler returns ``reconciliation_skipped=True`` when
+ # live_ids is empty but chunk rows exist (refuse-to-shrink
+ # guard). Surface this as a task failure so the user sees the
+ # durable-state inconsistency instead of a misleading
+ # "0 indexed" success.
+ if isinstance(reconciliation, dict) and reconciliation.get(
+ "reconciliation_skipped"
+ ):
+ reason = reconciliation.get("reconciliation_reason") or (
+ reconciliation.get("reason")
+ or "stored vectors could not be loaded"
+ )
+ sanitized_reason = sanitize_error_message(reason)
+ logger.warning(
+ f"Background indexing task {task_id}: reconciliation "
+ f"skipped — {sanitized_reason}"
+ )
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ status="failed",
+ progress_current=total,
+ progress_message=(
+ f"Completed: {results['successful']} indexed, "
+ f"{results['failed']} failed, "
+ f"{results['skipped']} skipped; reconciliation "
+ f"skipped: {sanitized_reason}"
+ ),
+ error_message=(
+ f"Reconciliation skipped: {sanitized_reason}. "
+ "Indexed flags preserved; verify the FAISS index "
+ "before retrying."
+ ),
+ result_metadata={
+ **{k: v for k, v in results.items() if k != "errors"},
+ # Omit durable_indexed_documents/chunks and
+ # live_vectors/orphan_vectors: true durable state is
+ # unverified on the skipped path, and the UI
+ # suppresses its "Durable vector store: ..." sentence
+ # when these keys are absent (``Number.isInteger``
+ # on undefined returns false). Reporting zeros here
+ # would imply data loss where state is merely
+ # unverified — see PR #5235 review comment
+ # 5085604502.
+ "reconciliation_skipped": True,
+ "reconciliation_reason": sanitized_reason,
+ "errors": _sanitized_indexing_errors(results),
+ },
+ )
+ return
+ durable_documents = reconciliation["indexed_documents"]
+ durable_chunks = reconciliation["indexed_chunks"]
+ task_result = {
+ **results,
+ "durable_indexed_documents": durable_documents,
+ "durable_indexed_chunks": durable_chunks,
+ "live_vectors": reconciliation["live_vectors"],
+ "orphan_vectors": reconciliation["orphan_vectors"],
+ "errors": _sanitized_indexing_errors(results),
+ }
+ has_failures = results["failed"] > 0
+ status = "failed" if has_failures else "completed"
+ message = (
+ f"Completed: {results['successful']} indexed, "
+ f"{results['failed']} failed, {results['skipped']} skipped; "
+ f"durable vector store: {durable_documents} documents, "
+ f"{durable_chunks} chunks"
+ )
_update_task_status(
username,
db_password,
task_id,
- status="completed",
+ status=status,
progress_current=total,
- progress_message=f"Completed: {results['successful']} indexed, {results['failed']} failed, {results['skipped']} skipped",
+ progress_message=message,
+ error_message=(
+ f"{results['failed']} document(s) failed to index. "
+ "The collection was reconciled to the durable vector store."
+ if has_failures
+ else None
+ ),
+ result_metadata=task_result,
)
logger.info(
f"Background indexing task {task_id} completed: {results}"
@@ -3011,7 +3139,24 @@ def _background_index_worker(
)
-def _update_task_status(
+def _is_database_locked_error(exc: BaseException) -> bool:
+ """Return True if ``exc`` looks like a SQLite ``database is locked`` error.
+
+ Background indexing can hit transient ``database is locked`` errors when
+ SQLite is contended; those are recoverable via a short backoff retry.
+ Anything else (connection failure, integrity error, programming mistake)
+ should surface immediately so the outer exception handler marks the task
+ as failed and sets ``completed_at`` for reaping.
+ """
+ return "database is locked" in str(exc).lower()
+
+
+@retry(
+ stop=stop_after_attempt(5),
+ wait=wait_exponential(multiplier=0.05),
+ retry=retry_if_exception(_is_database_locked_error),
+)
+def _do_update_task_status(
username: str,
db_password: str,
task_id: str,
@@ -3020,43 +3165,75 @@ def _update_task_status(
progress_total: int = None,
progress_message: str = None,
error_message: str = None,
+ result_metadata: dict = None,
):
- """Update task metadata in the database."""
+ """Perform the task-status update under a tenacity-managed retry loop.
+
+ Only SQLite ``database is locked`` errors are retried (up to 5 attempts
+ with 0.05s exponential backoff); any other exception escapes so the
+ outer caller can log it without retrying. See PR #5235 review comment
+ 3669857779.
+ """
from ...database.session_context import get_user_db_session
- try:
- with get_user_db_session(username, db_password) as db_session:
- task = (
- db_session.query(TaskMetadata)
- .filter_by(task_id=task_id)
- .first()
- )
- if task:
- # 1. Preserve terminal states: once cancelled or failed, only updates
- # confirming that same state are allowed.
- if (
- task.status in ("cancelled", "failed")
- and status != task.status
- ):
- return
+ with get_user_db_session(username, db_password) as db_session:
+ task = db_session.query(TaskMetadata).filter_by(task_id=task_id).first()
+ if task:
+ # Preserve terminal states: once cancelled or failed, only
+ # updates confirming that same state are allowed.
+ if task.status in ("cancelled", "failed") and status != task.status:
+ return
+ if status == "completed" and task.status != "processing":
+ return
+ if status is not None:
+ task.status = status
+ # Set completed_at for ALL terminal statuses so
+ # ``cleanup_old_tasks`` (which filters on
+ # ``status in ["completed", "failed"] AND
+ # completed_at < cutoff_date``) can reap them.
+ # Previously only "completed" set the timestamp,
+ # leaving failed/cancelled rows permanent.
+ if status in ("completed", "failed", "cancelled"):
+ task.completed_at = datetime.now(UTC)
+ if progress_current is not None:
+ task.progress_current = progress_current
+ if progress_total is not None:
+ task.progress_total = progress_total
+ if progress_message is not None:
+ task.progress_message = progress_message
+ if error_message is not None:
+ task.error_message = error_message
+ if result_metadata is not None:
+ metadata = dict(task.metadata_json or {})
+ metadata["result"] = result_metadata
+ task.metadata_json = metadata
+ db_session.commit()
- # 2. Transition to completed is only allowed from processing.
- if status == "completed" and task.status != "processing":
- return
- if status is not None:
- task.status = status
- if status == "completed":
- task.completed_at = datetime.now(UTC)
- if progress_current is not None:
- task.progress_current = progress_current
- if progress_total is not None:
- task.progress_total = progress_total
- if progress_message is not None:
- task.progress_message = progress_message
- if error_message is not None:
- task.error_message = error_message
- db_session.commit()
+def _update_task_status(
+ username: str,
+ db_password: str,
+ task_id: str,
+ status: str = None,
+ progress_current: int = None,
+ progress_total: int = None,
+ progress_message: str = None,
+ error_message: str = None,
+ result_metadata: dict = None,
+):
+ """Update task metadata in the database."""
+ try:
+ _do_update_task_status(
+ username,
+ db_password,
+ task_id,
+ status=status,
+ progress_current=progress_current,
+ progress_total=progress_total,
+ progress_message=progress_message,
+ error_message=error_message,
+ result_metadata=result_metadata,
+ )
except Exception:
logger.exception(f"Failed to update task status for {task_id}")
@@ -3270,6 +3447,7 @@ def get_index_status(collection_id):
"progress_total": task.progress_total or 0,
"progress_message": task.progress_message,
"error_message": task.error_message,
+ "result": (task.metadata_json or {}).get("result"),
"created_at": task.created_at.isoformat()
if task.created_at
else None,
@@ -3353,13 +3531,18 @@ def cancel_indexing(collection_id):
), 404
if matched_task:
- # Mark as cancelled - the worker thread will check this
- matched_task.status = "cancelled"
- matched_task.progress_message = "Cancellation requested..."
- db_session.commit()
+ # Mark as cancelled via _update_task_status so completed_at is set for reaping
+ task_id_to_cancel = matched_task.task_id
+ _update_task_status(
+ username,
+ db_password,
+ task_id_to_cancel,
+ status="cancelled",
+ progress_message="Cancellation requested...",
+ )
logger.info(
- f"Cancelled indexing task {matched_task.task_id} for collection {collection_id}"
+ f"Cancelled indexing task {task_id_to_cancel} for collection {collection_id}"
)
return jsonify(
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 a81def71ac..3e0fef8743 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
@@ -11,8 +11,13 @@ Handles indexing and searching library documents using RAG:
import threading
import time
+from contextlib import contextmanager
+from dataclasses import dataclass
+from datetime import datetime, UTC
+
+import numpy as np
from pathlib import Path
-from typing import Any, Callable, Dict, List, Optional, Set, Tuple
+from typing import Any, Callable, Dict, List, Optional, Set, Tuple, cast
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError
from langchain_core.documents import Document as LangchainDocument
@@ -44,6 +49,14 @@ from langchain_core.embeddings import Embeddings
import hashlib
+@dataclass
+class _PreparedDocument:
+ document_id: str
+ collection_id: str
+ chunk_inputs: List[ChunkInput]
+ vectors: np.ndarray
+
+
class _LazyEmbeddings(Embeddings):
"""Embeddings proxy that defers backend construction until first use.
@@ -68,7 +81,98 @@ class _LazyEmbeddings(Embeddings):
return self._manager.embeddings.embed_query(text)
-# Module-level locks serialise the FAISS save+record critical section and the
+class _TrackedRLock:
+ """RLock proxy that records active keys even for direct acquire() calls.
+
+ The recursion depth is tracked locally (not via ``threading.RLock._is_owned``,
+ which is a CPython-private API and is not part of the threading contract —
+ absent on PyPy/other implementations). The key set membership is mutated
+ atomically with respect to ``acquire`` and ``pop_faiss_locks_for_user``: the
+ per-(user, index_path) entry is added when ownership transitions 0 → 1 and
+ discarded when it transitions 1 → 0, and both transitions happen under
+ ``_faiss_write_locks_lock``.
+
+ Without holding ``_faiss_write_locks_lock`` across release, there would be a
+ race window: thread A could release → thread B (blocked in ``acquire``) unblock
+ and add its key → thread A then observe depth 0 and discard B's key. With
+ ``pop_faiss_locks_for_user`` evicting a "free" lock, the next writer would
+ create a fresh lock for the same ``(username, index_path)`` and race B on the
+ FAISS file. Holding ``_faiss_write_locks_lock`` across inner release + depth
+ check + discard ensures no concurrent acquire's key-add can interleave with
+ key-discard.
+ """
+
+ def __init__(self, key: Tuple[str, str]):
+ self._key = key
+ self._lock = threading.RLock()
+ # Per-wrapper recursion depth (independent of the inner RLock so we
+ # never need the CPython-private ``_is_owned`` accessor). ``_owner``
+ # records the outer holder's thread id, or ``None`` when free.
+ # ``_tracks_active_key`` is True only when this wrapper added
+ # ``self._key`` to ``_faiss_active_lock_keys`` on its outer acquire
+ # (canonical wrappers only) so a non-canonical release cannot erase
+ # another holder's active-key entry.
+ self._depth = 0
+ self._owner = None
+ self._tracks_active_key = False
+
+ def acquire(self, *args, **kwargs):
+ first_acquire = self._lock.acquire(*args, **kwargs)
+ if first_acquire:
+ # ``RLock.acquire`` returns True for the outer acquisition AND for
+ # inner re-acquires. We detect outer-vs-inner via the wrapper's
+ # tracked ``_owner``: if the current thread already holds the lock,
+ # this is a re-entry; otherwise it's a fresh outer acquisition.
+ #
+ # Only the *canonical* wrapper for ``self._key`` (the one currently
+ # stored in ``_faiss_write_locks``) may mark the key active. A
+ # non-canonical wrapper can still be acquired briefly during the
+ # pop-during-acquire TOCTOU window handled by
+ # ``_hold_faiss_write_lock``; if it also added the key, its matching
+ # ``release()`` would discard the key while the *canonical* holder
+ # still owned the file — reopening the concurrent-FAISS-writer race.
+ was_owner = self._owner == threading.get_ident()
+ if not was_owner:
+ with _faiss_write_locks_lock:
+ if _faiss_write_locks.get(self._key) is self:
+ _faiss_active_lock_keys.add(self._key)
+ self._tracks_active_key = True
+ else:
+ self._tracks_active_key = False
+ self._owner = threading.get_ident()
+ self._depth += 1
+ return first_acquire
+
+ def release(self):
+ # Atomic with respect to acquire's add: hold the key-set lock across
+ # the inner release and the depth check so a concurrent acquire's
+ # key-add cannot interleave with our key-discard. ``_faiss_write_locks_lock``
+ # is taken BEFORE the inner release (the old bug was the reverse order).
+ #
+ # Only discard the active key if *this* wrapper registered it on
+ # acquire. Non-canonical wrappers never register, so their release
+ # cannot erase a concurrent canonical holder's active-key entry.
+ with _faiss_write_locks_lock:
+ self._lock.release()
+ self._depth -= 1
+ if self._depth == 0:
+ if self._tracks_active_key:
+ _faiss_active_lock_keys.discard(self._key)
+ self._tracks_active_key = False
+ self._owner = None
+
+ def locked(self) -> bool:
+ """True iff the current thread holds the wrapper at depth >= 1."""
+ return self._owner == threading.get_ident() and self._depth > 0
+
+ def __enter__(self):
+ self.acquire()
+ return self
+
+ def __exit__(self, *args):
+ self.release()
+
+
# load_or_create verify→quarantine→build sequence per (username, index_path).
# MUST be module-level: each auto-index / scheduler / search worker constructs
# its own LibraryRAGService, so an instance-scoped lock would coordinate
@@ -76,8 +180,9 @@ class _LazyEmbeddings(Embeddings):
# — instance-scoped→module-scoped, username-only-key→(username, path)-key.
# See #4197 for the race this guards (concurrent save_local interleaves bytes,
# producing checksum_mismatch → destructive unlink, lost data).
-_faiss_write_locks: Dict[Tuple[str, str], threading.Lock] = {}
+_faiss_write_locks: Dict[Tuple[str, str], _TrackedRLock] = {}
_faiss_write_locks_lock = threading.Lock()
+_faiss_active_lock_keys: Set[Tuple[str, str]] = set()
# Hard cap on suffix-increment retries when generating the .corrupt-<ns> path.
# Normal case is one attempt — same-ns collisions only happen if the user
@@ -94,7 +199,7 @@ _QUARANTINE_SUFFIX_RETRY_CAP = 32
_QUARANTINE_KEEP_RECENT = 5
-def _get_faiss_write_lock(username: str, index_path: str) -> threading.Lock:
+def _get_faiss_write_lock(username: str, index_path: str) -> _TrackedRLock:
"""Return the lock for ``(username, index_path)``, creating it on first
access. Key is normalised via ``Path.resolve()`` to match
``FileIntegrityManager._normalize_path`` so writers/readers/quarantine
@@ -104,34 +209,61 @@ def _get_faiss_write_lock(username: str, index_path: str) -> threading.Lock:
with _faiss_write_locks_lock:
lock = _faiss_write_locks.get(key)
if lock is None:
- lock = threading.Lock()
+ lock = _TrackedRLock(key)
_faiss_write_locks[key] = lock
return lock
-def pop_faiss_locks_for_user(username: str) -> None:
- """Remove FAISS-write locks belonging to ``username`` that are NOT in use.
-
- Called from the user-close paths (connection_cleanup) so the dict doesn't
- grow one entry per (user × collection) across the process lifetime.
-
- A lock that is currently HELD must NOT be evicted: the next writer would
- then create a FRESH lock and run concurrently with the current holder on
- the same index file (lost update / torn write). So each candidate is probed
- with a non-blocking acquire — only locks we can immediately acquire (hence
- not held) are removed; a held lock is left in place and cleaned up by a
- later call once its write finishes. (No deadlock: a writer never holds a
- faiss lock while waiting on ``_faiss_write_locks_lock``.)
+@contextmanager
+def _hold_faiss_write_lock(username: str, index_path: str):
+ """Context manager that acquires the per-(username, index_path) FAISS
+ write lock, retrying across a pop-during-acquire TOCTOU window.
+
+ ``_get_faiss_write_lock`` returns a wrapper reference, but
+ ``pop_faiss_locks_for_user`` may run in the gap before our
+ ``acquire()`` adds the key to ``_faiss_active_lock_keys`` and therefore
+ before the key is "active" from ``pop``'s perspective. Without a re-check,
+ the caller would hold a non-canonical wrapper while ``pop`` discarded the
+ canonical entry and the next writer created a fresh lock for the same
+ ``(username, index_path)`` — reintroducing the same-(user, path)
+ concurrent-FAISS-writer race this module exists to eliminate.
+
+ The window is microseconds and requires a per-user lock cleanup to fire
+ mid-acquire, so this is a defence-in-depth tightening rather than a
+ regression fix — but it is cheap to close. After ``acquire()`` returns,
+ we re-check under ``_faiss_write_locks_lock`` that ``self`` is still the
+ canonical entry; if not, we release and retry with the new canonical
+ lock. Re-entry on the same wrapper is impossible here because each
+ iteration acquires a fresh wrapper reference.
"""
+ key = (username, str(Path(index_path).resolve()))
+ while True:
+ lock = _get_faiss_write_lock(username, index_path)
+ lock.acquire()
+ with _faiss_write_locks_lock:
+ canonical = _faiss_write_locks.get(key)
+ is_canonical = canonical is lock
+ if is_canonical:
+ try:
+ yield lock
+ finally:
+ lock.release()
+ return
+ # Evicted between _get_faiss_write_lock's lookup and our acquire().
+ # Release our (non-canonical) wrapper — acquire only marks the key
+ # active for the canonical dict entry, so this release cannot erase
+ # a concurrent canonical holder's active-key entry — then retry
+ # with the canonical lock.
+ lock.release()
+
+
+def pop_faiss_locks_for_user(username: str) -> None:
+ """Remove inactive FAISS-write locks for a user."""
with _faiss_write_locks_lock:
stale = [k for k in _faiss_write_locks if k[0] == username]
for k in stale:
- lock = _faiss_write_locks.get(k)
- if lock is not None and lock.acquire(blocking=False):
- try:
- _faiss_write_locks.pop(k, None)
- finally:
- lock.release()
+ if k not in _faiss_active_lock_keys:
+ _faiss_write_locks.pop(k, None)
class LibraryRAGService:
@@ -419,8 +551,7 @@ class LibraryRAGService:
or not legacy_path.exists()
):
return
- lock = _get_faiss_write_lock(self.username, str(index_path))
- with lock:
+ with _hold_faiss_write_lock(self.username, str(index_path)):
if index_path.exists():
return
try:
@@ -1325,8 +1456,222 @@ class LibraryRAGService:
"may be needed to restore its search."
)
+ @contextmanager
+ def _collection_transaction_lock(self, collection_id: str):
+ """Serialize the DB+FAISS transaction for one collection.
+
+ FAISS already uses this same re-entrant lock for reload/apply/persist and
+ integrity recording. Acquiring it around the complete document operation
+ also closes the store-persist-before-SQLCipher-commit window to sibling
+ workers: no worker can verify/quarantine or mutate the file until the
+ preceding worker's database commit (or rollback/reindex flag) finishes.
+ """
+ collection_name = f"collection_{collection_id}"
+ index_hash = self._get_index_hash(
+ collection_name, self.embedding_model, self.embedding_provider
+ )
+ index_path = self._get_index_path(index_hash)
+ with _hold_faiss_write_lock(self.username, str(index_path)) as lock:
+ yield lock
+
+ def _prepare_document(
+ self, document_id: str, collection_id: str, force_reindex: bool
+ ) -> Dict[str, Any]:
+ """Load, split, and embed without mutating collection state."""
+ 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:
+ return {"status": "error", "error": "Document not found"}
+ link = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=document_id, collection_id=collection_id)
+ .first()
+ )
+ if link is not None and link.indexed and not force_reindex:
+ return {
+ "status": "skipped",
+ "message": "Document already indexed for this collection",
+ "chunk_count": link.chunk_count,
+ }
+ if not document.text_content:
+ return {"status": "needs_serial_write"}
+
+ title = document.title or document.filename or "Untitled"
+ metadata = {
+ "source": document.original_url,
+ "document_id": document_id,
+ "collection_id": collection_id,
+ "document_title": title,
+ "title": title,
+ "authors": document.authors,
+ "published_date": str(document.published_date)
+ if document.published_date
+ else None,
+ "doi": document.doi,
+ "arxiv_id": document.arxiv_id,
+ "pmid": document.pmid,
+ "pmcid": document.pmcid,
+ "extraction_method": document.extraction_method,
+ "word_count": document.word_count,
+ }
+ source_doc = LangchainDocument(
+ page_content=document.text_content, metadata=metadata
+ )
+
+ chunks = self.text_splitter.split_documents([source_doc])
+ chunk_inputs = [
+ ChunkInput(
+ text=chunk.page_content,
+ metadata={**metadata, "chunk_index": i},
+ )
+ for i, chunk in enumerate(chunks)
+ ]
+ vectors = np.asarray(
+ self.embedding_manager.embeddings.embed_documents(
+ [chunk.text for chunk in chunk_inputs]
+ ),
+ dtype="float32",
+ )
+ logger.info(
+ f"Prepared document {document_id}: {len(chunk_inputs)} chunks embedded"
+ )
+ return {
+ "status": "prepared",
+ "prepared": _PreparedDocument(
+ document_id=document_id,
+ collection_id=collection_id,
+ chunk_inputs=chunk_inputs,
+ vectors=vectors,
+ ),
+ }
+
+ def _write_prepared_document(
+ self, prepared: _PreparedDocument
+ ) -> Dict[str, Any]:
+ """Serialize chunk rows, FAISS mutation, status updates, and commit."""
+ document_id = prepared.document_id
+ collection_id = prepared.collection_id
+ chunks = prepared.chunk_inputs
+ index_hash = self._get_index_hash(
+ f"collection_{collection_id}",
+ self.embedding_model,
+ self.embedding_provider,
+ )
+ index_path = self._get_index_path(index_hash)
+ with _hold_faiss_write_lock(self.username, str(index_path)):
+ with get_user_db_session(
+ self.username, self.db_password
+ ) as session:
+ try:
+ ensure_in_collection(session, document_id, collection_id)
+ collection_name = f"collection_{collection_id}"
+ vindex = self._get_vector_index(
+ collection_id, collection_name, reset_stale_state=True
+ )
+ stats = vindex.index_prepared(
+ source_type="document",
+ source_id=document_id,
+ chunks=chunks,
+ vectors=prepared.vectors,
+ replace=True,
+ session=session,
+ )
+
+ timestamp = datetime.now(UTC)
+ existing = (
+ session.query(RagDocumentStatus)
+ .filter_by(
+ document_id=document_id,
+ collection_id=collection_id,
+ )
+ .first()
+ )
+ old_chunks = existing.chunk_count if existing else 0
+ session.merge(
+ RagDocumentStatus(
+ document_id=document_id,
+ collection_id=collection_id,
+ rag_index_id=self.rag_index_record.id,
+ chunk_count=len(chunks),
+ indexed_at=timestamp,
+ )
+ )
+ session.query(DocumentCollection).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).update(
+ {
+ "indexed": True,
+ "chunk_count": len(chunks),
+ "last_indexed_at": timestamp,
+ }
+ )
+ rag_index = (
+ session.query(RAGIndex)
+ .filter_by(id=self.rag_index_record.id)
+ .first()
+ )
+ if rag_index:
+ rag_index.chunk_count += len(chunks) - old_chunks
+ if existing is None:
+ rag_index.total_documents += 1
+ rag_index.last_updated_at = timestamp
+ session.commit()
+ logger.info(
+ f"Persisted prepared document {document_id}: "
+ f"{stats.added} vectors added"
+ )
+ return {"status": "success", "chunk_count": len(chunks)}
+ except Exception as exc:
+ safe_rollback(
+ session,
+ "library_rag_service._write_prepared_document",
+ )
+ self._flag_document_for_reindex(
+ session, document_id, collection_id
+ )
+ logger.exception(
+ f"Error writing prepared document {document_id}"
+ )
+ return {
+ "status": "error",
+ "error": f"Operation failed: {type(exc).__name__}",
+ }
+
def index_document(
self, document_id: str, collection_id: str, force_reindex: bool = False
+ ) -> Dict[str, Any]:
+ collection_name = f"collection_{collection_id}"
+ index_hash = self._get_index_hash(
+ collection_name, self.embedding_model, self.embedding_provider
+ )
+ index_path = self._get_index_path(index_hash)
+ with _hold_faiss_write_lock(self.username, str(index_path)):
+ return self._index_document_locked(
+ document_id, collection_id, force_reindex
+ )
+
+ def _index_one(
+ self, document_id: str, collection_id: str, force_reindex: bool
+ ) -> Dict[str, Any]:
+ """Single-doc dispatch seam used by :meth:`index_documents_parallel`.
+
+ Default implementation delegates to :meth:`index_document` so production
+ behaviour is unchanged. Tests and subclasses override this method to
+ short-circuit the full per-doc pipeline (which would require mocking
+ every internal collaborator) without losing the prepared/serialized
+ pipeline in production.
+
+ The previous parallel runner detected overrides via
+ ``"index_document" in self.__dict__`` — that only honoured
+ instance-attribute patches and silently bypassed class-level subclass
+ overrides. The runner now compares the bound method against the base
+ class attribute so both instance patches and subclass overrides are
+ honoured.
+ """
+ return self.index_document(document_id, collection_id, force_reindex)
+
+ def _index_document_locked(
+ self, document_id: str, collection_id: str, force_reindex: bool = False
) -> Dict[str, Any]:
"""
Index a single document into RAG for a specific collection.
@@ -1571,8 +1916,6 @@ class LibraryRAGService:
f"removed ({index_stats.chunks} chunks total)"
)
- from datetime import datetime, UTC
-
# Check if document was already indexed (for stats update)
existing_status = (
session.query(RagDocumentStatus)
@@ -2193,15 +2536,18 @@ class LibraryRAGService:
"""
Index many documents concurrently with bounded fan-out.
- Each per-document task calls :meth:`index_document` directly — the
- per-doc logic (split, embed, persist chunks, FAISS-merge-under-lock,
- mark indexed, update stats) is unchanged. The bounded fan-out only
- changes *which* ``for doc: index_document(...)`` loop calls them:
- before this method, six call sites in
+ Each per-document task runs the prepared pipeline
+ (:meth:`_prepare_document` for load/split/embed, then the
+ coordinator's serialized durable write) unless a subclass overrides
+ :meth:`_index_one` or :meth:`index_document`, in which case that
+ per-doc path is invoked directly — the per-doc logic (split, embed,
+ persist chunks, FAISS-merge-under-lock, mark indexed, update stats)
+ is unchanged. The bounded fan-out only changes *which* sequential
+ loop dispatches the work: before this method, six call sites in
:mod:`research_library.routes.rag_routes` and the background
- reconciler in :mod:`scheduler.background` each did this
- sequentially. The slow embedding round-trip (outside the FAISS
- write lock) is now overlapped across documents.
+ reconciler in :mod:`scheduler.background` each did this one doc at
+ a time. The slow embedding round-trip (outside the FAISS write
+ lock) is now overlapped across documents.
Concurrency invariants this method relies on (already true):
@@ -2237,10 +2583,20 @@ class LibraryRAGService:
doc_info: List of ``(doc_id, title)`` pairs to index.
collection_id: UUID of the collection.
force_reindex: Forwarded to :meth:`index_document`.
- max_workers: Bound on concurrent in-flight doc indexers.
- ``1`` falls back to fully sequential behaviour (still
- useful when a flaky network makes concurrent httpx
- calls worse than serial). Default 4.
+ max_workers: Bound on the size of the
+ ``ThreadPoolExecutor`` — i.e. how many documents can be
+ **preparing** concurrently (load + split + embed). It does
+ NOT bound the prepared-but-unwritten backlog: completed
+ futures hold their full vector batches in memory until the
+ coordinator's serial write stage picks them up, so for very
+ large batches the resident memory footprint can exceed what
+ ``max_workers`` alone suggests. Embedding is the slow stage
+ in practice, so this is acceptable for the default 4-worker
+ fan-out; a caller with many large documents should either
+ shrink ``max_workers`` or chunk the submission. ``1`` falls
+ back to fully sequential behaviour (still useful when a
+ flaky network makes concurrent httpx calls worse than
+ serial). Default 4.
progress_callback: Optional hook called once per completed
document with ``(completed, total, title, status)`` —
matches the legacy shape used by
@@ -2286,7 +2642,52 @@ class LibraryRAGService:
def _run_one(doc_id: str) -> Dict[str, Any]:
"""Single-doc worker — never raises; returns a status dict."""
try:
- return self.index_document(doc_id, collection_id, force_reindex)
+ # Three seams tell us to bypass the prepared/serialized
+ # pipeline and call the per-doc method directly:
+ #
+ # 1. A class-level subclass override of ``_index_one`` —
+ # detected via
+ # ``type(self)._index_one is not LibraryRAGService._index_one``
+ # so it works regardless of whether the override
+ # has ``__func__`` (the old
+ # ``self._index_one.__func__ is not LibraryRAGService._index_one``
+ # check raised AttributeError on instance-attribute
+ # patches that don't expose ``__func__``).
+ # 2. A class-level subclass override of the legacy
+ # ``index_document`` extension point this seam
+ # replaced — callers that override ``index_document``
+ # at class level (not just instance-patch it for
+ # tests) still get the per-doc bypass, otherwise they
+ # would silently fall through to the prepared
+ # pipeline and lose the override.
+ # 3. An instance-level patch of ``_index_one`` or
+ # ``index_document`` — the legacy seams used by the
+ # existing parallel-runner tests that mock the
+ # per-doc method directly.
+ #
+ # If none is present, run the prepared pipeline: split
+ # and embed concurrently, then hand the prepared document
+ # off to the coordinator for serialized durable writes.
+ cls = type(self)
+ if cls._index_one is not LibraryRAGService._index_one:
+ return self._index_one(doc_id, collection_id, force_reindex)
+ if cls.index_document is not LibraryRAGService.index_document:
+ return self.index_document(
+ doc_id, collection_id, force_reindex
+ )
+ if (
+ "_index_one" in self.__dict__
+ or "index_document" in self.__dict__
+ ):
+ return self._index_one(doc_id, collection_id, force_reindex)
+ prepared_result = self._prepare_document(
+ doc_id, collection_id, force_reindex
+ )
+ if prepared_result.get("status") == "needs_serial_write":
+ return self.index_document(
+ doc_id, collection_id, force_reindex
+ )
+ return prepared_result
except Exception as exc:
# ``index_document`` already returns an error dict on its
# own internal failures; this catches only bugs / hook
@@ -2401,8 +2802,14 @@ class LibraryRAGService:
"status": "error",
"error": f"Worker crashed: {type(exc).__name__}",
}
- results[doc_id] = result
status = result.get("status", "error")
+ prepared = result.get("prepared")
+ if status == "prepared" and isinstance(
+ prepared, _PreparedDocument
+ ):
+ result = self._write_prepared_document(prepared)
+ status = result.get("status", "error")
+ results[doc_id] = result
if status == "success":
counters["successful"] += 1
elif status in ("skipped", "cleared"):
@@ -2477,6 +2884,142 @@ class LibraryRAGService:
"total": total,
}
+ def reconcile_collection_index(self, collection_id: str) -> Dict[str, Any]:
+ """Reconcile indexed flags and stats against durable FAISS membership.
+
+ A document is indexed only when it has at least one current-model chunk
+ row and every such chunk id exists in the live FAISS index. Stale status
+ rows are removed and compatibility flags/stats are rebuilt atomically.
+
+ Safety invariant: if the live FAISS index reports zero ids (transient
+ load error, missing file, on-disk corruption the verifier just
+ quarantined) but the DB still has DocumentChunk rows for the collection,
+ we REFUSE to shrink state. The function returns
+ ``{"reconciliation_skipped": True, "reason": "..."}`` and the worker
+ surfaces this as a task failure rather than clearing every indexed flag
+ and RagDocumentStatus row. A mass-clear from a transient store fault
+ would orphan every search hit and require a full re-index to recover.
+
+ ``RagDocumentStatus.indexed_at`` is preserved for durable docs that
+ already have a row — only newly durable docs get the current timestamp.
+ """
+ collection_name = f"collection_{collection_id}"
+ with self._collection_transaction_lock(collection_id):
+ vindex = self._get_vector_index(
+ collection_id, collection_name, reset_stale_state=False
+ )
+ live_ids = set(vindex.live_ids())
+ rag_index_id = cast(int, self.rag_index_record.id)
+ with get_user_db_session(
+ self.username, self.db_password
+ ) as session:
+ rows = (
+ session.query(DocumentChunk.id, DocumentChunk.source_id)
+ .filter_by(
+ source_type="document",
+ collection_name=collection_name,
+ embedding_model=self.embedding_model,
+ embedding_model_type=EmbeddingProvider(
+ self.embedding_provider
+ ),
+ )
+ .all()
+ )
+ ids_by_document: Dict[str, Set[int]] = {}
+ for chunk_id, source_id in rows:
+ if source_id is not None:
+ ids_by_document.setdefault(str(source_id), set()).add(
+ int(chunk_id)
+ )
+
+ # Refuse-to-shrink guard: a transient empty live_ids while
+ # chunk rows exist would otherwise mass-clear every indexed
+ # flag and RagDocumentStatus row, silently killing search
+ # for every document in the collection. Treat as a
+ # reconciliation failure; the worker surfaces the skip.
+ if not live_ids and ids_by_document:
+ logger.warning(
+ "reconcile_collection_index: live_ids empty but "
+ f"{len(ids_by_document)} document(s) have chunk rows; "
+ "refusing to clear indexed flags"
+ )
+ return {
+ "reconciliation_skipped": True,
+ "reason": (
+ "live vector store reported zero ids while "
+ "DocumentChunk rows exist; refusing to clear "
+ "indexed flags"
+ ),
+ "indexed_documents": 0,
+ "indexed_chunks": 0,
+ "live_vectors": 0,
+ "orphan_vectors": 0,
+ }
+
+ durable = {
+ doc_id: chunk_ids
+ for doc_id, chunk_ids in ids_by_document.items()
+ if chunk_ids and chunk_ids.issubset(live_ids)
+ }
+
+ # Snapshot existing indexed_at BEFORE the bulk delete so
+ # durable docs that already had a status row keep their
+ # original timestamp. Only docs newly promoted to durable
+ # get ``now``.
+ prior_indexed_at: Dict[str, Any] = {
+ str(row.document_id): row.indexed_at
+ for row in session.query(
+ RagDocumentStatus.document_id,
+ RagDocumentStatus.indexed_at,
+ )
+ .filter(RagDocumentStatus.collection_id == collection_id)
+ .all()
+ }
+
+ links = (
+ session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .all()
+ )
+ now = datetime.now(UTC)
+ for link in links:
+ chunk_ids = durable.get(str(link.document_id), set())
+ link.indexed = bool(chunk_ids)
+ link.chunk_count = len(chunk_ids)
+ if chunk_ids:
+ link.last_indexed_at = link.last_indexed_at or now
+
+ session.query(RagDocumentStatus).filter_by(
+ collection_id=collection_id
+ ).delete(synchronize_session=False)
+ for doc_id, chunk_ids in durable.items():
+ session.add(
+ RagDocumentStatus(
+ document_id=doc_id,
+ collection_id=collection_id,
+ rag_index_id=rag_index_id,
+ chunk_count=len(chunk_ids),
+ indexed_at=prior_indexed_at.get(doc_id, now),
+ )
+ )
+
+ rag_index = (
+ session.query(RAGIndex).filter_by(id=rag_index_id).first()
+ )
+ if rag_index:
+ rag_index.chunk_count = sum(map(len, durable.values()))
+ rag_index.total_documents = len(durable)
+ rag_index.last_updated_at = now
+ session.commit()
+
+ durable_ids = {i for ids in durable.values() for i in ids}
+ return {
+ "indexed_documents": len(durable),
+ "indexed_chunks": len(durable_ids),
+ "live_vectors": len(live_ids),
+ "orphan_vectors": len(live_ids - durable_ids),
+ }
+
def get_rag_stats(
self, collection_id: Optional[str] = None
) -> Dict[str, Any]:
diff --git a/src/local_deep_research/vector_stores/facade.py b/src/local_deep_research/vector_stores/facade.py
index c4a27b7404..d1be88a5ce 100644
--- a/src/local_deep_research/vector_stores/facade.py
+++ b/src/local_deep_research/vector_stores/facade.py
@@ -191,6 +191,73 @@ class VectorIndex:
with get_user_db_session(self.username, self.db_password) as s:
yield s, True
+ def index_prepared(
+ self,
+ *,
+ source_type: str,
+ source_id: Optional[str],
+ chunks: Sequence[ChunkInput],
+ vectors: Optional[np.ndarray],
+ replace: bool = True,
+ session: Optional[Session] = None,
+ ) -> IndexStats:
+ """Persist pre-embedded chunks without invoking the embedding backend.
+
+ Bulk indexing uses this after parallel preparation. Database row/id
+ allocation, vector application, prior-row removal, and commit semantics
+ remain identical to :meth:`index`; only embedding is moved outside the
+ collection writer critical section.
+ """
+ chunks = list(chunks)
+ if not chunks and (not replace or source_id is None):
+ return IndexStats(chunks=0, added=0, removed=0)
+ if chunks:
+ if vectors is None:
+ raise ValueError("chunks given without vectors")
+ vectors = np.asarray(vectors, dtype="float32")
+ if len(vectors) != len(chunks):
+ raise ValueError("vector count must match chunk count")
+
+ sid = str(source_id) if source_id is not None else None
+ with self._db(session) as (sess, owns):
+ prior_ids: List[int] = []
+ if replace and sid is not None:
+ prior_ids = [
+ row.id
+ for row in sess.query(DocumentChunk.id).filter_by(
+ source_type=source_type,
+ source_id=sid,
+ collection_name=self.collection_name,
+ embedding_model=self.embedding_model,
+ embedding_model_type=self.embedding_model_type,
+ )
+ ]
+
+ rows = [self._build_row(c, source_type, sid) for c in chunks]
+ if rows:
+ sess.add_all(rows)
+ sess.flush()
+ new_ids = [cast(int, row.id) for row in rows]
+ try:
+ stats = self._store.apply(
+ add_ids=new_ids,
+ add_vectors=vectors,
+ remove_ids=prior_ids,
+ )
+ except Exception:
+ if owns:
+ sess.rollback()
+ raise
+ self._finalize_db(
+ sess, owns, prior_ids, f"index prepared {source_type}/{sid}"
+ )
+
+ return IndexStats(
+ chunks=len(chunks),
+ added=stats["added"],
+ removed=stats["removed"],
+ )
+
# ------------------------------------------------------------------ #
# index
# ------------------------------------------------------------------ #
@@ -519,6 +586,10 @@ class VectorIndex:
return DeleteStats(removed=stats["removed"], rows_deleted=rows_deleted)
+ def live_ids(self) -> List[int]:
+ """Authoritative vector ids currently present in the store."""
+ return self._store.live_ids()
+
def count(self) -> int:
"""Number of vectors currently in the store."""
return self._store.count()
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
index fa26de9275..6075f708a3 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -478,6 +478,11 @@ async function checkAndResumeIndexing() {
showProgressUI();
updateProgressFromStatus(data);
startPolling();
+ } else if (ResearchStates.isFailed(data.status)) {
+ showProgressUI();
+ updateProgressFromStatus(data);
+ renderIndexingFailure(data);
+ hideProgressUI({ keepVisible: true });
}
} catch (error) {
SafeLogger.error('Error checking indexing status:', error);
@@ -502,7 +507,7 @@ function showProgressUI() {
/**
* Hide the progress UI
*/
-function hideProgressUI() {
+function hideProgressUI({ keepVisible = false } = {}) {
const progressSection = document.getElementById('indexing-progress');
const cancelBtn = document.getElementById('cancel-indexing-btn');
const indexBtn = document.getElementById('index-collection-btn');
@@ -513,10 +518,11 @@ function hideProgressUI() {
indexBtn.disabled = false;
reindexBtn.disabled = false;
- // Keep progress visible for a few seconds before hiding
- setTimeout(() => {
- progressSection.style.display = 'none';
- }, 5000);
+ if (!keepVisible) {
+ setTimeout(() => {
+ progressSection.style.display = 'none';
+ }, 5000);
+ }
}
/**
@@ -543,13 +549,24 @@ function startPolling() {
if (ResearchStates.isCompleted(data.status)) {
addLogEntry(data.progress_message || 'Indexing completed!', 'success');
+ hideProgressUI();
} else if (ResearchStates.isFailed(data.status)) {
- addLogEntry(`Indexing failed: ${data.error_message || 'Unknown error'}`, 'error');
+ // Keep visible so the user can read the failure logs
+ // rendered by renderIndexingFailure; cancelled tasks
+ // auto-hide after 5s (single-line warning, no logs).
+ renderIndexingFailure(data);
+ hideProgressUI({ keepVisible: true });
} else if (ResearchStates.isCancelled(data.status)) {
addLogEntry('Indexing was cancelled', 'warning');
+ hideProgressUI();
+ } else {
+ // Terminal status that is not completed/failed/cancelled
+ // (e.g. an "error" enum). Hide the progress UI without
+ // rendering a log entry — the status itself is the
+ // source of truth and the backend already wrote one.
+ hideProgressUI();
}
- hideProgressUI();
loadCollectionDetails();
}
} catch (error) {
@@ -558,6 +575,30 @@ function startPolling() {
}, 2000);
}
+function renderIndexingFailure(data) {
+ const result = data.result || {};
+ const durable = result.durable_indexed_documents;
+ const chunks = result.durable_indexed_chunks;
+ const summary = data.error_message || data.progress_message || 'Indexing failed';
+ const durableText = Number.isInteger(durable)
+ ? ` Durable vector store: ${durable} document(s), ${chunks || 0} chunk(s).`
+ : '';
+ // Trim a trailing period+whitespace from the summary so appending
+ // ``${durableText}`` (which already starts with a space and may end
+ // with its own period) doesn't render double punctuation like
+ // "Indexing failed: Disk full. Durable vector store: ...".
+ const trimmedSummary = summary.replace(/\.\s*$/, '');
+ addLogEntry(`Indexing failed: ${trimmedSummary}${durableText}`, 'error');
+ for (const item of (result.errors || []).slice(0, 20)) {
+ addLogEntry(`${item.title || item.doc_id || 'Document'}: ${item.error || 'Indexing failed'}`, 'error');
+ }
+ // SECURITY: this writes via textContent (never innerHTML) so user-
+ // controlled fields (document titles, error strings) are rendered as
+ // text and cannot be parsed as HTML. addLogEntry below is the same.
+ const progressText = document.getElementById('progress-text');
+ if (progressText) progressText.textContent = `${trimmedSummary}${durableText}`;
+}
+
/**
* Update progress UI from status data
*/
@@ -609,7 +650,16 @@ async function cancelIndexing() {
}
/**
- * Add log entry to progress log
+ * Add a log entry to the indexing progress log.
+ *
+ * SECURITY: this writes ``message`` via ``entry.textContent = message``
+ * (never innerHTML), so user-controlled data flowing in from
+ * ``renderIndexingFailure`` (document titles, error_message, durable
+ * counts) is rendered as text and cannot be parsed as HTML. The
+ * companion error path in ``collection_create.js`` uses ``escapeHtml``
+ * for the same reason. Do NOT change this to innerHTML without
+ * revisiting every caller and adding escaping — the existing path is
+ * the safe one.
*/
function addLogEntry(message, type = 'info') {
const progressLog = document.getElementById('progress-log');
@@ -873,5 +923,8 @@ async function searchCollection(query) {
}
}
-// Exposed on window so vitest can exercise the pure provider-mapping helper.
+// Exposed on window so vitest can exercise pure UI helpers.
window.getProviderLabel = getProviderLabel;
+window.renderIndexingFailure = renderIndexingFailure;
+window.hideProgressUI = hideProgressUI;
+window.startPolling = startPolling;
diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.js
index 25dc82ec71..2334f85b0a 100644
--- a/src/local_deep_research/web/static/js/collections_manager.js
+++ b/src/local_deep_research/web/static/js/collections_manager.js
@@ -419,7 +419,11 @@ async function triggerReindex(btn) {
// logs it) so the user isn't left with a silently-failed reindex.
if (finalStatus) {
if (finalStatus.status === 'failed' || finalStatus.status === 'error') {
- showError(finalStatus.error_message || finalStatus.error || 'Indexing failed');
+ const result = finalStatus.result || {};
+ const durable = Number.isInteger(result.durable_indexed_documents)
+ ? ` Durable vector store: ${result.durable_indexed_documents} document(s), ${result.durable_indexed_chunks || 0} chunk(s).`
+ : '';
+ showError((finalStatus.error_message || finalStatus.error || 'Indexing failed') + durable);
} else if (finalStatus.status === 'timeout') {
showError('Indexing is taking longer than expected. It may still be running in the background — refresh to check.');
}
diff --git a/tests/database/test_queue_service_extended.py b/tests/database/test_queue_service_extended.py
index ed4e0801f4..346d592b42 100644
--- a/tests/database/test_queue_service_extended.py
+++ b/tests/database/test_queue_service_extended.py
@@ -529,7 +529,7 @@ class TestCleanupOldTasksExtended:
"""Extended tests for cleanup_old_tasks method."""
def test_deletes_old_completed_and_failed_tasks(self):
- """Should delete tasks that are completed/failed and older than cutoff."""
+ """Should delete tasks that are completed/failed/cancelled and older than cutoff."""
from local_deep_research.database.queue_service import UserQueueService
mock_session = Mock()
@@ -542,6 +542,40 @@ class TestCleanupOldTasksExtended:
assert result == 3
mock_session.commit.assert_called_once()
+ def test_filters_include_cancelled_status(self):
+ """Verify TaskMetadata.status filter includes 'cancelled'."""
+ from local_deep_research.database.queue_service import UserQueueService
+
+ mock_session = Mock()
+ mock_query = mock_session.query.return_value
+ filter_mock = mock_query.filter
+ filter_mock.return_value.delete.return_value = 1
+
+ service = UserQueueService(mock_session)
+ service.cleanup_old_tasks(days=7)
+
+ # Inspect filter arguments passed to query.filter(...)
+ assert filter_mock.called
+ args, _ = filter_mock.call_args
+ # Look for the status IN clause and verify 'cancelled' is in its value list
+ status_in_clause = None
+ for arg in args:
+ if (
+ hasattr(arg, "left")
+ and getattr(arg.left, "name", None) == "status"
+ ):
+ status_in_clause = arg
+ break
+ assert status_in_clause is not None, (
+ "TaskMetadata.status filter clause not found"
+ )
+ values = getattr(
+ status_in_clause.right,
+ "value",
+ [c.value for c in getattr(status_in_clause.right, "clauses", [])],
+ )
+ assert "cancelled" in values
+
def test_returns_zero_when_nothing_to_delete(self):
"""Should return 0 when no tasks match the criteria."""
from local_deep_research.database.queue_service import UserQueueService
diff --git a/tests/js/collection-details.test.js b/tests/js/collection-details.test.js
index 126af58b07..4ae0fe4dc0 100644
--- a/tests/js/collection-details.test.js
+++ b/tests/js/collection-details.test.js
@@ -1,24 +1,50 @@
/**
- * Tests for collection_details.js — getProviderLabel.
+ * Tests for collection_details.js — getProviderLabel + indexing-failure UI.
*
- * Tiny pure helper that maps an embedding-provider value to a
- * user-facing label, falling back to the raw value, then to a
- * default sentinel. Used in the collection-details page header.
+ * Covers:
+ * - getProviderLabel (pure helper, public mapping)
+ * - renderIndexingFailure (trims trailing period, uses textContent)
+ * - hideProgressUI (auto-hides after 5s when keepVisible=false,
+ * stays visible when keepVisible=true)
+ *
+ * The 5-second auto-hide is pinned because PR #5235 review comment
+ * 5085604502 flagged that cancellation was leaving the UI visible
+ * indefinitely; only the failure path should keep it visible.
*/
let getProviderLabel;
+let renderIndexingFailure;
+let hideProgressUI;
+let startPolling;
beforeAll(async () => {
- // collection_details.js has a DOMContentLoaded listener that
- // queries DOM elements that don't exist in the test env. The event
- // has typically already fired in happy-dom by import time, so the
- // listener never runs. Stub fetch defensively just in case.
globalThis.fetch = vi.fn(() =>
Promise.resolve({ ok: true, json: () => Promise.resolve({}) })
);
+ // RESEARCH_STATUS / RESEARCH_TERMINAL_STATES are normally injected
+ // from Python via base.html. Provide stubs so the constants module's
+ // ``window.ResearchStates`` is fully functional.
+ window.RESEARCH_STATUS = {
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ SUSPENDED: 'suspended',
+ CANCELLED: 'cancelled',
+ QUEUED: 'queued',
+ PENDING: 'pending',
+ ERROR: 'error',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed', 'suspended', 'failed', 'error', 'cancelled',
+ ]);
+
+ await import('@js/config/constants.js');
await import('@js/collection_details.js');
getProviderLabel = window.getProviderLabel;
+ renderIndexingFailure = window.renderIndexingFailure;
+ hideProgressUI = window.hideProgressUI;
+ startPolling = window.startPolling;
});
describe('getProviderLabel', () => {
@@ -44,8 +70,216 @@ describe('getProviderLabel', () => {
});
it('falls back to "Not configured" for the empty string', () => {
- // '' is falsy and not in the map, so both `providerMap[v]` and the
- // `providerValue` fallback fail, landing on the sentinel.
expect(getProviderLabel('')).toBe('Not configured');
});
});
+
+describe('renderIndexingFailure', () => {
+ beforeEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ function setupDom() {
+ const progressLog = document.createElement('div');
+ progressLog.id = 'progress-log';
+ document.body.appendChild(progressLog);
+ const progressText = document.createElement('div');
+ progressText.id = 'progress-text';
+ document.body.appendChild(progressText);
+ return { progressLog, progressText };
+ }
+
+ it('trims a single trailing period before appending durable text', () => {
+ const { progressLog, progressText } = setupDom();
+
+ renderIndexingFailure({
+ error_message: 'Disk full.',
+ result: {
+ durable_indexed_documents: 3,
+ durable_indexed_chunks: 12,
+ },
+ });
+
+ const firstEntry = progressLog.firstChild;
+ expect(firstEntry.textContent).toBe(
+ 'Indexing failed: Disk full Durable vector store: 3 document(s), 12 chunk(s).'
+ );
+ expect(progressText.textContent).toBe(
+ 'Disk full Durable vector store: 3 document(s), 12 chunk(s).'
+ );
+ });
+
+ it('trims multiple trailing periods', () => {
+ const { progressLog } = setupDom();
+ renderIndexingFailure({
+ error_message: 'Service unavailable..',
+ result: { durable_indexed_documents: 0, durable_indexed_chunks: 0 },
+ });
+ const firstEntry = progressLog.firstChild;
+ expect(firstEntry.textContent.startsWith(
+ 'Indexing failed: Service unavailable'
+ )).toBe(true);
+ expect(firstEntry.textContent).not.toMatch(/\.\./);
+ });
+
+ it('does not append a durable sentence when durable counts are missing', () => {
+ const { progressLog } = setupDom();
+ renderIndexingFailure({
+ error_message: 'Disk full.',
+ result: {},
+ });
+ const firstEntry = progressLog.firstChild;
+ expect(firstEntry.textContent).toBe(
+ 'Indexing failed: Disk full'
+ );
+ });
+
+ it('uses textContent (never innerHTML) for the progress-text update', () => {
+ const { progressText } = setupDom();
+ // XSS attempt in error_message: must render as text, not as HTML.
+ renderIndexingFailure({
+ error_message: '<img src=x onerror=alert(1)>.',
+ result: {},
+ });
+ // No child <img> element was created — the payload is a text node,
+ // not parsed HTML. happy-dom serialises innerHTML with HTML
+ // entity escapes (``&lt;``) for raw text-node content; the
+ // load-bearing assertion is that no actual <img> element exists.
+ expect(progressText.querySelector('img')).toBeNull();
+ expect(progressText.textContent).toBe(
+ '<img src=x onerror=alert(1)>'
+ );
+ });
+
+ it('emits one log entry per error in result.errors', () => {
+ const { progressLog } = setupDom();
+ renderIndexingFailure({
+ error_message: 'Many failed.',
+ result: {
+ errors: [
+ { doc_id: 'd1', title: 'Doc 1', error: 'E1' },
+ { doc_id: 'd2', title: 'Doc 2', error: 'E2' },
+ { doc_id: 'd3', error: 'E3' },
+ ],
+ },
+ });
+ expect(progressLog.childNodes.length).toBe(4);
+ expect(progressLog.childNodes[0].textContent).toBe(
+ 'Indexing failed: Many failed'
+ );
+ expect(progressLog.childNodes[1].textContent).toBe('Doc 1: E1');
+ expect(progressLog.childNodes[2].textContent).toBe('Doc 2: E2');
+ expect(progressLog.childNodes[3].textContent).toBe('d3: E3');
+ });
+});
+
+describe('hideProgressUI', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ // Provide the DOM elements the function touches.
+ const progressSection = document.createElement('div');
+ progressSection.id = 'indexing-progress';
+ progressSection.style.display = 'block';
+ document.body.appendChild(progressSection);
+ const cancelBtn = document.createElement('button');
+ cancelBtn.id = 'cancel-indexing-btn';
+ cancelBtn.style.display = 'block';
+ document.body.appendChild(cancelBtn);
+ const spinner = document.createElement('div');
+ spinner.id = 'indexing-spinner';
+ document.body.appendChild(spinner);
+ const indexBtn = document.createElement('button');
+ indexBtn.id = 'index-collection-btn';
+ indexBtn.disabled = true;
+ document.body.appendChild(indexBtn);
+ const reindexBtn = document.createElement('button');
+ reindexBtn.id = 'reindex-collection-btn';
+ reindexBtn.disabled = true;
+ document.body.appendChild(reindexBtn);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ document.body.innerHTML = '';
+ });
+
+ it('hides the progress section 5s after hideProgressUI() by default', () => {
+ const section = document.getElementById('indexing-progress');
+ expect(section.style.display).toBe('block');
+ hideProgressUI();
+ // Synchronous side-effects fire immediately:
+ expect(section.style.display).toBe('block');
+ // After 5s the section is hidden:
+ vi.advanceTimersByTime(5000);
+ expect(section.style.display).toBe('none');
+ });
+
+ it('does NOT auto-hide when keepVisible=true (failure path)', () => {
+ const section = document.getElementById('indexing-progress');
+ expect(section.style.display).toBe('block');
+ hideProgressUI({ keepVisible: true });
+ vi.advanceTimersByTime(10000);
+ expect(section.style.display).toBe('block');
+ });
+
+ it('re-enables the index/reindex buttons and hides the cancel button synchronously', () => {
+ const indexBtn = document.getElementById('index-collection-btn');
+ const reindexBtn = document.getElementById('reindex-collection-btn');
+ const cancelBtn = document.getElementById('cancel-indexing-btn');
+ expect(indexBtn.disabled).toBe(true);
+ expect(reindexBtn.disabled).toBe(true);
+ expect(cancelBtn.style.display).toBe('block');
+ hideProgressUI();
+ expect(indexBtn.disabled).toBe(false);
+ expect(reindexBtn.disabled).toBe(false);
+ expect(cancelBtn.style.display).toBe('none');
+ });
+});
+
+describe('startPolling terminal-status fallback', () => {
+ /** Pin the ``else`` branch that hides progress UI for terminal statuses
+ * other than completed / failed / cancelled. PR #5235 review comment
+ * 5085604502 noted that the previous code only cleared the interval
+ * without hiding the UI for status strings that match
+ * ``ResearchStates.isTerminal`` but not the explicit branches
+ * (e.g. ``error``). The fallback hides the UI without emitting a
+ * misleading log entry.
+ *
+ * Exercising the full ``startPolling`` async chain (interval →
+ * safeFetchWithAuth → fetch → .json() → branch selection) requires
+ * every DOM element ``updateProgressFromStatus`` and friends touch,
+ * which is fragile and out of scope for a defensive one-line
+ * fallback. The branch is pinned with a source-text scan that fails
+ * the build if a future refactor silently drops the fallback.
+ */
+ it('source declares the else fallback branch', async () => {
+ const { readFile } = await import('fs/promises');
+ const { fileURLToPath } = await import('url');
+ const path = await import('path');
+ const here = path.dirname(fileURLToPath(import.meta.url));
+ const jsPath = path.resolve(
+ here,
+ '../../src/local_deep_research/web/static/js/collection_details.js',
+ );
+ const src = await readFile(jsPath, 'utf8');
+ // The else branch must follow the
+ // completed/failed/cancelled branches inside the isTerminal/idle
+ // guard and call hideProgressUI() without keepVisible. Loose
+ // checks — any future refactor that drops the fallback will
+ // fail here. The branch is exercised by inspecting the source
+ // text rather than driving the full async polling chain
+ // (interval → safeFetchWithAuth → fetch → .json() → branch
+ // selection), which requires every DOM element
+ // ``updateProgressFromStatus`` and friends touch.
+ const pollingBlock = src.match(
+ /function startPolling\(\)\s*\{[\s\S]*?\n\}\n/
+ );
+ expect(pollingBlock, 'startPolling() not found').toBeTruthy();
+ // Must contain a top-level ``else {`` inside the polling
+ // callback (after the completed/failed/cancelled chain).
+ expect(pollingBlock[0]).toMatch(/else\s*\{/);
+ // And that else must call hideProgressUI() (the no-arg
+ // default, which schedules the 5-second auto-hide).
+ expect(pollingBlock[0]).toMatch(/hideProgressUI\(\)/);
+ });
+});
diff --git a/tests/research_library/routes/test_rag_routes_background_coverage.py b/tests/research_library/routes/test_rag_routes_background_coverage.py
index 3392626151..75399a6d5b 100644
--- a/tests/research_library/routes/test_rag_routes_background_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_background_coverage.py
@@ -503,17 +503,14 @@ class TestBackgroundIndexWorkerBackground:
"task-1", "coll-1", "user", "pass", force_reindex=False
)
- # Final completed message should show 1 failed, 0 indexed
- final_msg = next(
- (
- s.get("progress_message", "")
- for s in reversed(statuses)
- if s.get("status") == "completed"
- ),
- "",
+ # A partial run is terminal failure, not a false success. The message
+ # still reports the failed count and durable reconciliation summary.
+ final = next(
+ s for s in reversed(statuses) if s.get("status") == "failed"
)
- assert "1 failed" in final_msg
- assert "0 indexed" in final_msg
+ assert "1 failed" in final["progress_message"]
+ assert final["result_metadata"]["failed"] == 1
+ assert final["error_message"]
def test_cancellation_after_first_document(self):
"""Worker reports cancelled status when parallel helper reports cancellation after first doc."""
@@ -647,8 +644,14 @@ class TestUpdateTaskStatusBackground:
assert mock_task.completed_at is None
db_session.commit.assert_called_once()
- def test_failed_status_does_not_set_completed_at(self):
- """Setting status to 'failed' does not set completed_at."""
+ def test_failed_status_sets_completed_at(self):
+ """Setting status to 'failed' MUST set completed_at.
+
+ ``cleanup_old_tasks`` filters on
+ ``status in ["completed", "failed"] AND completed_at < cutoff_date``;
+ leaving completed_at NULL on failed tasks made them permanent
+ rows. Regression for PR #5235 review comment 5085604502.
+ """
from local_deep_research.research_library.routes.rag_routes import (
_update_task_status,
)
@@ -676,8 +679,176 @@ class TestUpdateTaskStatusBackground:
assert mock_task.status == "failed"
assert mock_task.error_message == "something broke"
- # completed_at should remain None for failed status
- assert mock_task.completed_at is None
+ # Failed is a terminal status — completed_at must be set so
+ # cleanup_old_tasks can reap the row.
+ assert mock_task.completed_at is not None
+
+ def test_cancelled_status_sets_completed_at(self):
+ """Setting status to 'cancelled' also sets completed_at."""
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ mock_task = Mock()
+ mock_task.status = "processing"
+ mock_task.completed_at = None
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=mock_task)
+ db_session.query = Mock(return_value=q)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ _update_task_status(
+ "user",
+ "pass",
+ "task-1",
+ status="cancelled",
+ )
+
+ assert mock_task.status == "cancelled"
+ assert mock_task.completed_at is not None
+
+ def test_retries_on_database_is_locked_then_succeeds(self):
+ """Transient SQLite 'database is locked' errors are retried by tenacity
+ (up to 5 attempts with exponential backoff); a successful commit on a
+ later attempt still applies the update. Regression for PR #5235 review
+ comment 3669857779.
+ """
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ # A fresh task mock per attempt: when the previous attempt failed
+ # before the commit landed, the next retry should observe the task
+ # in its pre-attempt state. Mutating a single shared Mock across
+ # retries would let the terminal-state guard short-circuit the
+ # retry loop, hiding the very behaviour we're trying to test.
+ last_task = {"value": None}
+
+ def fresh_task_factory():
+ task = Mock()
+ task.status = "processing"
+ task.completed_at = None
+ task.metadata_json = None
+ last_task["value"] = task
+ return task
+
+ def query_factory(*args, **kwargs):
+ q = _build_mock_query(first_result=fresh_task_factory())
+ return q
+
+ db_session = _make_db_session()
+ db_session.query = Mock(side_effect=query_factory)
+
+ commit_attempts = {"count": 0, "failures_left": 2}
+ real_commit = db_session.commit
+
+ def maybe_locking_commit():
+ commit_attempts["count"] += 1
+ if commit_attempts["failures_left"] > 0:
+ commit_attempts["failures_left"] -= 1
+ raise RuntimeError("database is locked")
+ return real_commit()
+
+ db_session.commit = maybe_locking_commit
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ _update_task_status(
+ "user",
+ "pass",
+ "task-1",
+ status="completed",
+ )
+
+ # 2 lock failures + 1 success = 3 commit attempts
+ assert commit_attempts["count"] == 3, (
+ f"expected 3 commit attempts (2 lock + 1 success), "
+ f"got {commit_attempts['count']}"
+ )
+ # The task from the FINAL attempt (post-success) is what carries
+ # the applied update.
+ assert last_task["value"].status == "completed"
+ assert last_task["value"].completed_at is not None
+
+ def test_non_lock_error_fails_fast_without_retry(self):
+ """Non-'database is locked' exceptions must NOT be retried; they
+ should surface on the first attempt so the outer ``except`` logs and
+ the caller can fall back to its terminal-state guards.
+ """
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ db_session = _make_db_session()
+ q = _build_mock_query(first_result=Mock(status="processing"))
+ db_session.query = Mock(return_value=q)
+ commit_attempts = {"count": 0}
+
+ def always_failing_commit():
+ commit_attempts["count"] += 1
+ raise RuntimeError("connection refused")
+
+ db_session.commit = always_failing_commit
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ # Should NOT raise: the outer wrapper catches and logs.
+ _update_task_status("user", "pass", "task-1", status="completed")
+
+ assert commit_attempts["count"] == 1, (
+ f"non-lock error should fail fast, got {commit_attempts['count']} "
+ f"attempts"
+ )
+
+ def test_exhausted_lock_retries_log_and_return(self):
+ """After 5 attempts the outer wrapper must catch the RetryError and
+ log without re-raising — so the background indexing task continues
+ and ``cleanup_old_tasks`` can later reap the row.
+ """
+ from local_deep_research.research_library.routes.rag_routes import (
+ _update_task_status,
+ )
+
+ # Fresh task per attempt — see the comment in
+ # ``test_retries_on_database_is_locked_then_succeeds`` for why a
+ # shared Mock would let the terminal-state guard hide the retry.
+ def query_factory(*args, **kwargs):
+ q = _build_mock_query(first_result=Mock(status="processing"))
+ return q
+
+ db_session = _make_db_session()
+ db_session.query = Mock(side_effect=query_factory)
+ commit_attempts = {"count": 0}
+
+ def always_locked_commit():
+ commit_attempts["count"] += 1
+ raise RuntimeError("database is locked")
+
+ db_session.commit = always_locked_commit
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ with patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session):
+ # Must not raise — exhaustion is logged, not propagated.
+ _update_task_status("user", "pass", "task-1", status="completed")
+
+ assert commit_attempts["count"] == 5, (
+ f"expected 5 attempts (stop_after_attempt=5), "
+ f"got {commit_attempts['count']}"
+ )
# ---------------------------------------------------------------------------
@@ -734,3 +905,241 @@ class TestTriggerAutoIndexBackground:
# Executor should never be called when settings check fails
mock_executor.assert_not_called()
+
+
+class TestReconciliationSkippedOmitsDurableCounts:
+ """When ``reconcile_collection_index`` returns
+ ``reconciliation_skipped=True`` the durable counts are unknown — the
+ worker must OMIT the ``durable_indexed_documents`` /
+ ``durable_indexed_chunks`` / ``live_vectors`` / ``orphan_vectors``
+ keys so the UI suppresses its ``"Durable vector store: 0 documents, 0
+ chunks"`` sentence instead of implying data loss where state is
+ merely unverified.
+
+ Regression for PR #5235 review comment 5085604502.
+ """
+
+ def _run_worker_with_skipped_reconciliation(self):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = _make_rag_service_mock()
+ mock_svc.index_documents_parallel.return_value = {
+ "successful": 1,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {"d1": {"status": "success"}},
+ "cancelled": False,
+ "total": 1,
+ }
+ mock_svc.reconcile_collection_index.return_value = {
+ "reconciliation_skipped": True,
+ "reconciliation_reason": "live vector store reported zero ids",
+ "indexed_documents": 0,
+ "indexed_chunks": 0,
+ "live_vectors": 0,
+ "orphan_vectors": 0,
+ }
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = "model"
+
+ doc = Mock()
+ doc.filename = "a.txt"
+ doc.title = None
+ doc.id = "d1"
+ link = Mock()
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [(link, doc)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ with (
+ patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}._update_task_status", side_effect=track_status),
+ patch(f"{MODULE}._is_task_cancelled", return_value=False),
+ ):
+ _background_index_worker(
+ "task-1",
+ "coll-1",
+ "user",
+ "pass",
+ force_reindex=False,
+ )
+
+ final = next(s for s in reversed(statuses) if s.get("status"))
+ return final
+
+ def test_durable_keys_are_absent_on_reconciliation_skipped(self):
+ """The terminal ``failed`` status when reconciliation was skipped
+ must NOT include any of the durable-count keys — only
+ ``reconciliation_skipped`` / ``reconciliation_reason`` plus the
+ sanitized per-doc errors. Reporting 0 would imply data loss.
+ """
+ final = self._run_worker_with_skipped_reconciliation()
+
+ assert final["status"] == "failed"
+ meta = final["result_metadata"]
+ assert "durable_indexed_documents" not in meta
+ assert "durable_indexed_chunks" not in meta
+ assert "live_vectors" not in meta
+ assert "orphan_vectors" not in meta
+ assert meta["reconciliation_skipped"] is True
+ assert (
+ "live vector store reported zero ids"
+ in (meta["reconciliation_reason"])
+ )
+ assert "skipped" in final["progress_message"].lower()
+
+ def test_durable_keys_are_absent_when_reconciliation_raises(self):
+ """Same omission contract when the reconciliation helper itself
+ raises — the exception-fallback path also marks the task as
+ ``reconciliation_skipped`` and must omit the misleading zeros.
+ """
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = _make_rag_service_mock()
+ mock_svc.index_documents_parallel.return_value = {
+ "successful": 1,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {"d1": {"status": "success"}},
+ "cancelled": False,
+ "total": 1,
+ }
+ mock_svc.reconcile_collection_index.side_effect = RuntimeError(
+ "disk full"
+ )
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = "model"
+
+ doc = Mock()
+ doc.filename = "a.txt"
+ doc.title = None
+ doc.id = "d1"
+ link = Mock()
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [(link, doc)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ with (
+ patch(
+ f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{MODULE}._update_task_status", side_effect=track_status),
+ patch(f"{MODULE}._is_task_cancelled", return_value=False),
+ ):
+ _background_index_worker(
+ "task-1",
+ "coll-1",
+ "user",
+ "pass",
+ force_reindex=False,
+ )
+
+ final = next(s for s in reversed(statuses) if s.get("status"))
+ assert final["status"] == "failed"
+ meta = final["result_metadata"]
+ assert "durable_indexed_documents" not in meta
+ assert "durable_indexed_chunks" not in meta
+ assert "live_vectors" not in meta
+ assert "orphan_vectors" not in meta
+ assert meta["reconciliation_skipped"] is True
+
+
+class TestSanitizedIndexingErrorsHelper:
+ """``_sanitized_indexing_errors`` must scrub every error string via
+ ``sanitize_error_message`` and bound the result so the result_metadata
+ blob can't grow unboundedly. Used by both terminal paths of
+ ``_background_index_worker`` — regression for PR #5235 review comment
+ 5085604502's de-duplication note.
+ """
+
+ def test_helper_returns_sanitized_bounded_list(self):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _sanitized_indexing_errors,
+ )
+
+ results = {
+ "errors": [
+ {
+ "doc_id": f"d{i}",
+ "title": f"t{i}",
+ "error": f"secret-{i}",
+ }
+ for i in range(60)
+ ]
+ }
+
+ scrubbed = _sanitized_indexing_errors(results)
+
+ assert len(scrubbed) == 50
+ assert all("doc_id" in item and "title" in item for item in scrubbed)
+ # The helper delegates sanitisation to ``sanitize_error_message``;
+ # the exact scrubbed text depends on that helper, but the
+ # ``error`` key MUST exist on every entry.
+ assert all("error" in item for item in scrubbed)
+
+ def test_helper_handles_missing_error_key(self):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _sanitized_indexing_errors,
+ )
+
+ results = {
+ "errors": [
+ {"doc_id": "d1", "title": "t1"},
+ {"doc_id": "d2", "title": "t2", "error": None},
+ ]
+ }
+ scrubbed = _sanitized_indexing_errors(results)
+ assert len(scrubbed) == 2
+ assert all(item["error"] for item in scrubbed)
diff --git a/tests/research_library/routes/test_rag_routes_indexing_coverage.py b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
index 6d35be50b7..e12e8e1dfb 100644
--- a/tests/research_library/routes/test_rag_routes_indexing_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_indexing_coverage.py
@@ -745,20 +745,15 @@ class TestBackgroundIndexWorker:
"task-1", "coll-1", "testuser", "pass", force_reindex=False
)
- # Final status should be completed
- assert any(s.get("status") == "completed" for s in updated_statuses)
- # Final message should reflect the mixed results
- final_msg = next(
- (
- s.get("progress_message")
- for s in reversed(updated_statuses)
- if s.get("status") == "completed"
- ),
- "",
+ # Mixed results are a visible terminal failure, with durable counts and
+ # structured details preserved for the status API/UI.
+ final = next(
+ s for s in reversed(updated_statuses) if s.get("status") == "failed"
)
- assert "1 indexed" in final_msg
- assert "1 failed" in final_msg
- assert "1 skipped" in final_msg
+ assert "1 failed" in final["progress_message"]
+ assert "1 skipped" in final["progress_message"]
+ assert final["result_metadata"]["successful"] == 1
+ assert final["result_metadata"]["failed"] == 1
# ---------------------------------------------------------------------------
diff --git a/tests/research_library/services/test_index_documents_parallel.py b/tests/research_library/services/test_index_documents_parallel.py
index 14ed760cdb..94cb09a6a0 100644
--- a/tests/research_library/services/test_index_documents_parallel.py
+++ b/tests/research_library/services/test_index_documents_parallel.py
@@ -201,6 +201,65 @@ class TestResultAggregation:
assert "RuntimeError" in result["results"]["doc-x"]["error"]
+class TestPreparedPipeline:
+ def test_preparation_overlaps_and_writes_are_serial(self):
+ """Embedding preparation overlaps; durable writes never overlap."""
+ import time
+ from local_deep_research.research_library.services.library_rag_service import (
+ _PreparedDocument,
+ )
+ import numpy as np
+
+ svc = _make_service()
+ prep_active = 0
+ prep_peak = 0
+ prep_lock = threading.Lock()
+ write_active = 0
+ write_peak = 0
+ write_threads = []
+
+ def prepare(doc_id, collection_id, force_reindex):
+ nonlocal prep_active, prep_peak
+ with prep_lock:
+ prep_active += 1
+ prep_peak = max(prep_peak, prep_active)
+ time.sleep(0.03)
+ with prep_lock:
+ prep_active -= 1
+ return {
+ "status": "prepared",
+ "prepared": _PreparedDocument(
+ document_id=doc_id,
+ collection_id=collection_id,
+ chunk_inputs=[],
+ vectors=np.empty((0, 1), dtype="float32"),
+ ),
+ }
+
+ def write(prepared):
+ nonlocal write_active, write_peak
+ write_threads.append(threading.current_thread())
+ write_active += 1
+ write_peak = max(write_peak, write_active)
+ time.sleep(0.005)
+ write_active -= 1
+ return {"status": "success", "chunk_count": 0}
+
+ svc._prepare_document = MagicMock(side_effect=prepare)
+ svc._write_prepared_document = MagicMock(side_effect=write)
+
+ result = svc.index_documents_parallel(
+ [(f"doc-{i}", str(i)) for i in range(8)],
+ "coll-1",
+ max_workers=4,
+ )
+
+ assert prep_peak > 1
+ assert write_peak == 1
+ assert all(t is threading.current_thread() for t in write_threads)
+ assert result["successful"] == 8
+
+
class TestProgressCallback:
def test_callback_fires_once_per_completion_in_completion_order(self):
"""Each completion emits one (completed, total, title, status) tuple."""
@@ -572,3 +631,391 @@ class TestWorkerBounds:
)
assert result["successful"] == 3
assert set(result["results"].keys()) == {"doc-a", "doc-b", "doc-c"}
+
+
+class TestIndexOneSeam:
+ """``_index_one`` is the explicit dispatch seam for parallel indexing.
+
+ The previous ``"index_document" in self.__dict__`` check only saw
+ instance-attribute patches and silently bypassed class-level subclass
+ overrides — see PR #5235 review comment 5085604502. These tests pin
+ the new contract: both the new ``_index_one`` seam AND the legacy
+ ``index_document`` instance-patch pattern must be honoured.
+ """
+
+ def test_instance_patch_on_index_document_still_routes_through(self):
+ """Legacy seam: ``svc.index_document = MagicMock(...)`` must still
+ be invoked by the parallel runner.
+ """
+ svc = _make_service()
+ svc.index_document = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 1}
+ )
+
+ result = svc.index_documents_parallel(
+ [("doc-a", "A"), ("doc-b", "B")],
+ "coll-1",
+ )
+
+ assert result["successful"] == 2
+ assert svc.index_document.call_count == 2
+
+ def test_instance_patch_on_index_one_is_honored(self):
+ """New seam: ``svc._index_one = MagicMock(...)`` must be invoked
+ by the parallel runner and short-circuit the prepared pipeline.
+ """
+ svc = _make_service()
+ svc._index_one = MagicMock( # type: ignore[method-assign]
+ return_value={"status": "success", "chunk_count": 7}
+ )
+ # If the seam isn't honoured, the runner would call the real
+ # ``_prepare_document`` (which needs DB+embedding, mocked here
+ # to raise) and we'd see an error result instead of success.
+ svc._prepare_document = MagicMock( # type: ignore[method-assign]
+ side_effect=AssertionError("prepared pipeline must be skipped")
+ )
+
+ result = svc.index_documents_parallel(
+ [("doc-a", "A")],
+ "coll-1",
+ )
+
+ assert result["successful"] == 1
+ assert svc._index_one.call_count == 1
+ assert result["results"]["doc-a"]["chunk_count"] == 7
+
+ def test_subclass_override_of_index_one_is_honored(self):
+ """Class-level subclass overrides of ``_index_one`` must be honoured.
+
+ Regression for the ``"index_document" in self.__dict__`` check that
+ silently bypassed subclass overrides.
+ """
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ sentinel = {"status": "success", "chunk_count": 42}
+
+ class Subclass(LibraryRAGService):
+ def _index_one(self, doc_id, collection_id, force_reindex):
+ return dict(sentinel, doc_id=doc_id)
+
+ with (
+ patch(f"{_MOD}.LocalEmbeddingManager") as _lem,
+ patch(f"{_MOD}.get_user_db_session"),
+ patch(f"{_MOD}.FileIntegrityManager"),
+ patch(f"{_MOD}.get_text_splitter"),
+ ):
+ _lem.return_value.embeddings = MagicMock()
+ svc = Subclass(username="u", db_password="pw")
+ # Sanity-check the seam is the override, not the base impl.
+ assert svc._index_one.__func__ is not LibraryRAGService._index_one
+
+ result = svc.index_documents_parallel(
+ [("doc-x", "X")],
+ "coll-1",
+ )
+
+ assert result["successful"] == 1
+ assert result["results"]["doc-x"]["chunk_count"] == 42
+ assert result["results"]["doc-x"]["doc_id"] == "doc-x"
+
+ def test_subclass_override_of_index_document_is_honored(self):
+ """Class-level subclass overrides of the legacy ``index_document``
+ extension point must be honoured.
+
+ Regression for the PR #5235 follow-up review comment: ``_run_one``
+ detected class-level ``_index_one`` overrides and instance patches
+ of either name, but a subclass overriding ``index_document`` at
+ class level (the old extension point this seam replaced) silently
+ fell through to the prepared pipeline. Pin the new check that
+ ``type(self).index_document is not LibraryRAGService.index_document``
+ routes the override into the bypass path.
+ """
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ class Subclass(LibraryRAGService):
+ def index_document(
+ self, doc_id, collection_id, force_reindex=False
+ ):
+ return {
+ "status": "success",
+ "chunk_count": 5,
+ "doc_id": doc_id,
+ }
+
+ with (
+ patch(f"{_MOD}.LocalEmbeddingManager") as _lem,
+ patch(f"{_MOD}.get_user_db_session"),
+ patch(f"{_MOD}.FileIntegrityManager"),
+ patch(f"{_MOD}.get_text_splitter"),
+ ):
+ _lem.return_value.embeddings = MagicMock()
+ svc = Subclass(username="u", db_password="pw")
+ # Sanity-check the override is the subclass impl, not the base.
+ assert svc.index_document.__func__ is not (
+ LibraryRAGService.index_document
+ )
+
+ # If the seam isn't honoured, the runner would call the real
+ # ``_prepare_document`` (which needs DB+embedding, mocked here
+ # to raise) and we'd see an error result instead of success.
+ svc._prepare_document = MagicMock( # type: ignore[method-assign]
+ side_effect=AssertionError(
+ "prepared pipeline must be skipped when index_document "
+ "is overridden at class level"
+ )
+ )
+
+ result = svc.index_documents_parallel(
+ [("doc-y", "Y")],
+ "coll-1",
+ )
+
+ assert result["successful"] == 1
+ assert result["results"]["doc-y"]["chunk_count"] == 5
+ assert result["results"]["doc-y"]["doc_id"] == "doc-y"
+
+
+class TestFaissWriteLockEvictionRetry:
+ """``_hold_faiss_write_lock`` must retry if the canonical entry is
+ evicted between ``_get_faiss_write_lock`` and the wrapper's
+ ``acquire()`` — otherwise a non-canonical wrapper would be held while
+ the next writer created a fresh lock for the same
+ ``(username, index_path)``.
+
+ Regression for the residual TOCTOU race flagged in PR #5235 review
+ comment 5085604502.
+ """
+
+ def _reset_locks(self):
+ from local_deep_research.research_library.services import (
+ library_rag_service as mod,
+ )
+
+ with mod._faiss_write_locks_lock:
+ mod._faiss_write_locks.clear()
+ mod._faiss_active_lock_keys.clear()
+
+ def test_hold_yields_canonical_wrapper_after_eviction(self, tmp_path):
+ """Simulate the pop-during-acquire race deterministically:
+
+ 1. Pre-create wrapper A so ``_get_faiss_write_lock`` would return it.
+ 2. Replace the canonical dict entry with a fresh wrapper B before
+ the holder's ``acquire()`` runs.
+ 3. Wrap ``_TrackedRLock.acquire`` so the first call swaps the
+ canonical entry to a fresh wrapper C while A is mid-acquire.
+ 4. Assert the holder eventually yields the canonical wrapper (C
+ or whatever the last swap left) and never A.
+
+ Without the re-check the holder would yield wrapper A and a
+ concurrent writer using the canonical wrapper would race A on the
+ FAISS file.
+ """
+ self._reset_locks()
+ from local_deep_research.research_library.services import (
+ library_rag_service as mod,
+ )
+
+ p = str(tmp_path / "race.faiss")
+ key = ("u1", str(mod.Path(p).resolve()))
+
+ # Step 1: pre-create wrapper A and put it in the dict as canonical.
+ wrapper_a = mod._get_faiss_write_lock("u1", p)
+ assert mod._faiss_write_locks.get(key) is wrapper_a
+
+ swap_done = threading.Event()
+ original_acquire = mod._TrackedRLock.acquire
+
+ def swapped_acquire(self, *args, **kwargs):
+ # While A is mid-acquire, swap the canonical dict entry to a
+ # fresh wrapper C. A is now non-canonical from
+ # ``_hold_faiss_write_lock``'s perspective.
+ if self is wrapper_a and not swap_done.is_set():
+ with mod._faiss_write_locks_lock:
+ mod._faiss_write_locks[key] = mod._TrackedRLock(key)
+ swap_done.set()
+ return original_acquire(self, *args, **kwargs)
+
+ with patch.object(mod._TrackedRLock, "acquire", swapped_acquire):
+ with mod._hold_faiss_write_lock("u1", p) as held:
+ assert swap_done.is_set(), (
+ "Test setup: eviction swap never fired"
+ )
+ # The held wrapper MUST be the current canonical entry,
+ # not wrapper A.
+ with mod._faiss_write_locks_lock:
+ canonical = mod._faiss_write_locks.get(key)
+ assert held is canonical, (
+ "Held wrapper is non-canonical — a concurrent "
+ "writer using the canonical wrapper would race "
+ "this caller on the FAISS file"
+ )
+ assert held is not wrapper_a, (
+ "Held wrapper is the pre-eviction wrapper A — "
+ "the retry path did not run"
+ )
+ # Canonical holder must keep the key active so pop
+ # cannot evict it mid-write.
+ assert key in mod._faiss_active_lock_keys
+
+ def test_non_canonical_release_does_not_discard_active_key(self, tmp_path):
+ """A non-canonical wrapper's release must not erase the active key.
+
+ Sequence:
+ 1. Canonical wrapper C is acquired and marks the key active.
+ 2. Stale wrapper A (no longer in ``_faiss_write_locks``) is
+ acquired and released — the TOCTOU retry path does exactly
+ this after detecting eviction.
+ 3. The key must still be active and C must still survive
+ ``pop_faiss_locks_for_user``.
+
+ Without canonical-only active-key tracking, A's release discarded
+ the key while C still held the lock, reopening the concurrent
+ FAISS-writer race this PR eliminates.
+ """
+ self._reset_locks()
+ from local_deep_research.research_library.services import (
+ library_rag_service as mod,
+ )
+
+ p = str(tmp_path / "stale-release.faiss")
+ key = ("u1", str(mod.Path(p).resolve()))
+
+ wrapper_a = mod._get_faiss_write_lock("u1", p)
+ # Evict A from the dict and install a fresh canonical wrapper C
+ # without going through pop (simulates the mid-acquire swap).
+ with mod._faiss_write_locks_lock:
+ wrapper_c = mod._TrackedRLock(key)
+ mod._faiss_write_locks[key] = wrapper_c
+
+ wrapper_c.acquire()
+ try:
+ with mod._faiss_write_locks_lock:
+ assert key in mod._faiss_active_lock_keys
+ assert wrapper_c._tracks_active_key is True
+
+ # Stale A acquires/releases exactly as the TOCTOU retry path does.
+ assert wrapper_a.acquire() is True
+ with mod._faiss_write_locks_lock:
+ assert wrapper_a._tracks_active_key is False
+ assert key in mod._faiss_active_lock_keys
+ wrapper_a.release()
+
+ with mod._faiss_write_locks_lock:
+ assert key in mod._faiss_active_lock_keys, (
+ "Non-canonical release discarded the active key while "
+ "the canonical holder still owns the lock"
+ )
+
+ mod.pop_faiss_locks_for_user("u1")
+ assert mod._get_faiss_write_lock("u1", p) is wrapper_c, (
+ "Canonical held lock was evicted after a non-canonical "
+ "release cleared the active-key set"
+ )
+ finally:
+ wrapper_c.release()
+
+ with mod._faiss_write_locks_lock:
+ assert key not in mod._faiss_active_lock_keys
+
+
+class TestNeedsSerialWriteFallback:
+ """``index_documents_parallel`` falls back to ``index_document`` when preparation returns ``needs_serial_write``."""
+
+ def test_parallel_indexing_falls_back_on_needs_serial_write(self):
+ svc = _make_service()
+ with (
+ patch.object(
+ svc,
+ "_prepare_document",
+ return_value={"status": "needs_serial_write"},
+ ),
+ patch.object(
+ svc,
+ "index_document",
+ return_value={"status": "success", "chunk_count": 3},
+ ) as mock_index_doc,
+ patch.object(
+ svc,
+ "_write_prepared_document",
+ ) as mock_write_prep,
+ ):
+ res = svc.index_documents_parallel(
+ doc_info=[("doc-123", "Title 123")],
+ collection_id="coll-1",
+ )
+ assert res["successful"] == 1
+ mock_index_doc.assert_called_once_with("doc-123", "coll-1", False)
+ assert not mock_write_prep.called
+
+
+class TestWritePreparedDocumentReindexDelta:
+ """``_write_prepared_document`` accurately updates ``rag_index.chunk_count`` on re-index."""
+
+ def test_chunk_count_delta_captures_old_chunks_before_merge(self):
+ svc = _make_service()
+ svc.rag_index_record = MagicMock()
+ svc.rag_index_record.id = 1
+
+ mock_existing = MagicMock()
+ mock_existing.chunk_count = 5 # 5 old chunks
+
+ mock_rag_index = MagicMock()
+ mock_rag_index.chunk_count = 10 # 10 total chunks currently in index
+
+ mock_vindex = MagicMock()
+ mock_vindex.index_prepared.return_value = MagicMock(added=2)
+
+ def make_q(first_val=None):
+ q = MagicMock()
+ q.filter_by.return_value = q
+ q.first.return_value = first_val
+ return q
+
+ session = MagicMock()
+ # session.query calls:
+ # 1. RagDocumentStatus (existing)
+ # 2. DocumentCollection update
+ # 3. RAGIndex
+ q_existing = make_q(first_val=mock_existing)
+ q_doc_coll = make_q()
+ q_rag_index = make_q(first_val=mock_rag_index)
+ session.query.side_effect = [q_existing, q_doc_coll, q_rag_index]
+
+ prepared = MagicMock()
+ prepared.document_id = "doc-1"
+ prepared.collection_id = "coll-1"
+ prepared.vectors = [MagicMock(), MagicMock()]
+ prepared.chunk_inputs = [
+ MagicMock(),
+ MagicMock(),
+ ] # 2 new chunks (delta = 2 - 5 = -3)
+
+ session_ctx = MagicMock()
+ session_ctx.__enter__ = MagicMock(return_value=session)
+ session_ctx.__exit__ = MagicMock(return_value=None)
+
+ with (
+ patch.object(svc, "_get_vector_index", return_value=mock_vindex),
+ patch(
+ "local_deep_research.research_library.services.library_rag_service.ensure_in_collection"
+ ),
+ patch(
+ "local_deep_research.research_library.services.library_rag_service._hold_faiss_write_lock"
+ ),
+ patch(
+ "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
+ return_value=session_ctx,
+ ),
+ ):
+ svc._get_index_hash = MagicMock(return_value="hash123")
+ svc._get_index_path = MagicMock(return_value="/path/123.faiss")
+
+ res = svc._write_prepared_document(prepared)
+
+ assert res["status"] == "success"
+ # 10 + (2 - 5) = 7
+ assert mock_rag_index.chunk_count == 7
diff --git a/tests/research_library/services/test_library_rag_service_coverage.py b/tests/research_library/services/test_library_rag_service_coverage.py
index 4f53e7a2cb..3973e92d0e 100644
--- a/tests/research_library/services/test_library_rag_service_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_coverage.py
@@ -11,6 +11,7 @@ Focuses on logic paths not exercised by the existing test_library_rag_service.py
import hashlib
import threading
+import time
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -898,6 +899,214 @@ class TestFaissWriteLock:
assert not t2.is_alive()
+class TestTrackedRLockReleaseRace:
+ """Regression tests for the release+discard race fixed in PR #5235
+ (review comment 5085604502).
+
+ The previous implementation did:
+ self._lock.release()
+ if not self._lock._is_owned():
+ with _faiss_write_locks_lock:
+ _faiss_active_lock_keys.discard(self._key)
+
+ Between ``release()`` and the ``_is_owned()`` check, a thread blocked in
+ ``acquire()`` could unblock, acquire the lock, and add its key — and the
+ then-continuing outer thread would discard that fresh key. With
+ ``pop_faiss_locks_for_user`` evicting a "free" lock, the next writer would
+ create a fresh lock for the same ``(username, index_path)`` and race the
+ holder on the FAISS file. The fix holds ``_faiss_write_locks_lock`` across
+ the inner release + depth check + discard.
+ """
+
+ def _reset_locks(self):
+ mod = _import_module()
+ with mod._faiss_write_locks_lock:
+ mod._faiss_write_locks.clear()
+ mod._faiss_active_lock_keys.clear()
+
+ def test_release_does_not_discard_concurrent_acquire_key(self, tmp_path):
+ """The release path must NOT erase a key that another thread just
+ added via ``acquire()`` while we were releasing.
+ """
+ self._reset_locks()
+ mod = _import_module()
+ p = str(tmp_path / "racy.faiss")
+ lock = mod._get_faiss_write_lock("u1", p)
+
+ a_inside = threading.Event()
+ a_can_release = threading.Event()
+ b_inside = threading.Event()
+ b_can_release = threading.Event()
+
+ def holder_a():
+ with lock:
+ a_inside.set()
+ a_can_release.wait(timeout=2.0)
+ # Once A returns, its key must have been removed.
+ with mod._faiss_write_locks_lock:
+ assert lock._key not in mod._faiss_active_lock_keys
+
+ def holder_b():
+ a_inside.wait(timeout=2.0)
+ with lock: # blocks until A releases
+ b_inside.set()
+ # While B holds the lock, its key MUST be in the active set.
+ # With the pre-fix code, A's release path could erase the
+ # key B just added.
+ with mod._faiss_write_locks_lock:
+ assert lock._key in mod._faiss_active_lock_keys, (
+ "Race: A discarded B's key from _faiss_active_lock_keys"
+ )
+ b_can_release.set()
+
+ ta = threading.Thread(target=holder_a)
+ tb = threading.Thread(target=holder_b)
+ ta.start()
+ tb.start()
+ assert a_inside.wait(timeout=2.0)
+ # Give B a moment to enter ``acquire`` and block.
+ deadline = time.monotonic() + 2.0
+ while time.monotonic() < deadline:
+ with mod._faiss_write_locks_lock:
+ if lock._key in mod._faiss_active_lock_keys:
+ break
+ time.sleep(0.01)
+ a_can_release.set()
+ assert b_inside.wait(timeout=2.0)
+ b_can_release.set()
+ ta.join(timeout=3.0)
+ tb.join(timeout=3.0)
+
+ with mod._faiss_write_locks_lock:
+ assert lock._key not in mod._faiss_active_lock_keys
+
+ def test_reentrant_release_keeps_key_until_final_release(self, tmp_path):
+ """Re-entry (acquire twice, release once) must NOT discard the key.
+ Regression for the depth-tracking rewrite that replaced the
+ CPython-private ``RLock._is_owned()`` accessor.
+ """
+ self._reset_locks()
+ mod = _import_module()
+ p = str(tmp_path / "reentrant.faiss")
+ lock = mod._get_faiss_write_lock("u1", p)
+
+ # Acquire twice via the explicit method so we can release each
+ # step independently and observe the key state in between.
+ lock.acquire()
+ lock.acquire()
+ with mod._faiss_write_locks_lock:
+ assert lock._key in mod._faiss_active_lock_keys
+
+ lock.release() # depth 2 → 1; key MUST still be present
+ with mod._faiss_write_locks_lock:
+ assert lock._key in mod._faiss_active_lock_keys, (
+ "Key was discarded on inner release — re-entry depth "
+ "tracking broken"
+ )
+
+ lock.release() # depth 1 → 0; key MUST be discarded
+ with mod._faiss_write_locks_lock:
+ assert lock._key not in mod._faiss_active_lock_keys
+
+ def test_pop_does_not_evict_lock_after_concurrent_handoff(self, tmp_path):
+ """End-to-end: A releases → B acquires, ``pop_faiss_locks_for_user``
+ runs while B holds the lock, the lock must NOT be evicted.
+ """
+ self._reset_locks()
+ mod = _import_module()
+ p = str(tmp_path / "handoff.faiss")
+ lock = mod._get_faiss_write_lock("u1", p)
+
+ a_inside = threading.Event()
+ b_inside = threading.Event()
+ pop_done = threading.Event()
+
+ def holder_a():
+ with lock:
+ a_inside.set()
+ b_inside.wait(timeout=2.0)
+ pop_done.wait(timeout=2.0)
+
+ def holder_b():
+ a_inside.wait(timeout=2.0)
+ with lock:
+ b_inside.set()
+ mod.pop_faiss_locks_for_user("u1")
+ pop_done.set()
+ # After pop_faiss_locks_for_user, the held lock must STILL
+ # be the one returned by subsequent lookups.
+ same = mod._get_faiss_write_lock("u1", p)
+ assert same is lock, (
+ "Held lock was evicted — next writer would race B on "
+ "the same file"
+ )
+
+ ta = threading.Thread(target=holder_a)
+ tb = threading.Thread(target=holder_b)
+ ta.start()
+ tb.start()
+ ta.join(timeout=3.0)
+ tb.join(timeout=3.0)
+ assert not ta.is_alive()
+ assert not tb.is_alive()
+
+ def test_lock_does_not_use_cpython_private_is_owned(self, tmp_path):
+ """Defensive: the wrapper must not call ``threading.RLock._is_owned``.
+
+ ``_is_owned`` is a CPython private API and is absent on PyPy and other
+ implementations. Pinning against its use here so a future refactor
+ does not silently re-introduce a PyPy-broken shortcut. The check
+ only inspects method bodies (the class's docstring mentions the
+ API by name in the explanation of the rewrite).
+ """
+ import inspect
+
+ mod = _import_module()
+ for name, member in vars(mod._TrackedRLock).items():
+ if name.startswith("__") and name.endswith("__"):
+ continue
+ try:
+ src = inspect.getsource(member)
+ except (TypeError, OSError):
+ continue
+ assert "_is_owned" not in src, (
+ f"_TrackedRLock.{name} must not rely on the CPython-private "
+ "threading.RLock._is_owned() API"
+ )
+
+ def test_failed_non_blocking_acquire_does_not_corrupt_tracking(
+ self, tmp_path
+ ):
+ """A non-blocking acquire() attempt that fails must not set owner or depth."""
+ self._reset_locks()
+ mod = _import_module()
+ p = str(tmp_path / "nonblocking.faiss")
+ lock = mod._get_faiss_write_lock("u1", p)
+
+ acquired = lock.acquire()
+ assert acquired is True
+
+ failed_acquire = None
+
+ def attempt_b():
+ nonlocal failed_acquire
+ failed_acquire = lock.acquire(blocking=False)
+
+ tb = threading.Thread(target=attempt_b)
+ tb.start()
+ tb.join(timeout=2.0)
+
+ assert failed_acquire is False
+ # Thread B must not have corrupted lock._owner or depth
+ assert lock.locked() is True
+ assert lock._owner == threading.get_ident()
+ assert lock._depth == 1
+
+ lock.release()
+ assert lock._depth == 0
+ assert lock._owner is None
+
+
class TestNoWalCheckpointInIndexingPath:
"""Regression guard: the per-document PRAGMA wal_checkpoint(FULL)
has been removed (#4197 secondary fix from PR #3539). Re-adding it
diff --git a/tests/research_library/services/test_reconcile_collection_index.py b/tests/research_library/services/test_reconcile_collection_index.py
new file mode 100644
index 0000000000..5121855d47
--- /dev/null
+++ b/tests/research_library/services/test_reconcile_collection_index.py
@@ -0,0 +1,326 @@
+"""Tests for ``LibraryRAGService.reconcile_collection_index``.
+
+Pins the safety invariants added in PR #5235 (review comment 5085604502):
+
+* If ``live_ids()`` is empty but ``DocumentChunk`` rows exist, the
+ reconciler must REFUSE to shrink state. It returns
+ ``{"reconciliation_skipped": True, ...}`` and the caller surfaces a
+ task failure rather than clearing every indexed flag and
+ ``RagDocumentStatus`` row.
+* ``RagDocumentStatus.indexed_at`` is preserved for documents that
+ already had a status row; only newly durable documents get the
+ current timestamp.
+"""
+
+from datetime import datetime, UTC
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+_MOD = "local_deep_research.research_library.services.library_rag_service"
+
+
+def _make_service(**overrides):
+ with (
+ patch(f"{_MOD}.LocalEmbeddingManager") as _lem,
+ patch(f"{_MOD}.get_user_db_session"),
+ patch(f"{_MOD}.FileIntegrityManager"),
+ patch(f"{_MOD}.get_text_splitter"),
+ ):
+ _lem.return_value.embeddings = MagicMock()
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ defaults = dict(username="testuser", db_password="pw")
+ defaults.update(overrides)
+ return LibraryRAGService(**defaults)
+
+
+def _make_session_ctx(session):
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(return_value=session)
+ ctx.__exit__ = MagicMock(return_value=None)
+ return ctx
+
+
+def _build_query_mock(*, all_rows=None, first_row=None):
+ """Return a MagicMock suitable for ``session.query(<Model>)`` chains.
+
+ ``all_rows`` is returned by ``.all()``; ``first_row`` is returned by
+ ``.first()``. ``.filter_by(...)`` / ``.filter(...)`` simply return the
+ same mock so the chain resolves. ``.delete(...)`` returns the mock so
+ the bulk-delete call chain resolves.
+ """
+ q = MagicMock()
+ q.filter_by.return_value = q
+ q.filter.return_value = q
+ q.delete.return_value = q
+ if all_rows is not None:
+ q.all.return_value = all_rows
+ if first_row is not None:
+ q.first.return_value = first_row
+ return q
+
+
+def _make_status_row(document_id, indexed_at):
+ """Build a mock that supports ``row.document_id`` / ``row.indexed_at``.
+
+ Production code uses both attribute access (the prior-status query
+ builds a dict via ``row.document_id``) and tuple unpacking (the
+ chunk-row query does ``for chunk_id, source_id in rows``), so the
+ mock must support both.
+ """
+ row = MagicMock()
+ row.document_id = document_id
+ row.indexed_at = indexed_at
+ # Tuple-unpacking support: the chunk-row query does
+ # ``for chunk_id, source_id in rows``. Status rows are unpacked the
+ # same way, so this is harmless if not used.
+ row.__iter__ = lambda self: iter((document_id, indexed_at))
+ return row
+
+
+def _make_chunk_row(chunk_id, source_id):
+ """Build a mock that supports ``row.id`` / ``row.source_id`` and tuple
+ unpacking (``for chunk_id, source_id in rows``).
+ """
+ row = MagicMock()
+ row.id = chunk_id
+ row.source_id = source_id
+ row.__iter__ = lambda self: iter((chunk_id, source_id))
+ return row
+
+
[email protected](autouse=True)
+def _reset_locks():
+ """Make sure each test sees a clean global lock state."""
+ from local_deep_research.research_library.services import (
+ library_rag_service as svc,
+ )
+
+ with svc._faiss_write_locks_lock:
+ svc._faiss_write_locks.clear()
+ svc._faiss_active_lock_keys.clear()
+ yield
+ with svc._faiss_write_locks_lock:
+ svc._faiss_write_locks.clear()
+ svc._faiss_active_lock_keys.clear()
+
+
+class TestReconcileRefuseToShrink:
+ """When ``live_ids()`` is empty but chunk rows exist, refuse to clear."""
+
+ def test_empty_live_ids_with_chunk_rows_returns_skipped(self, tmp_path):
+ svc = _make_service()
+ # Provide a rag_index_record so the reconciler can read its id.
+ svc.rag_index_record = MagicMock()
+ svc.rag_index_record.id = 7
+
+ # Stub the vector index to report ZERO live ids (transient store
+ # fault — quarantine rebuilt the index but the in-memory handle
+ # was empty).
+ vindex = MagicMock()
+ vindex.live_ids.return_value = []
+ with patch.object(svc, "_get_vector_index", return_value=vindex):
+ # Stub the DB session: DocumentChunk returns rows so the
+ # chunk-set is non-empty (the "would clear" trigger).
+ chunk_q = _build_query_mock(
+ all_rows=[
+ _make_chunk_row(1, "doc-a"),
+ _make_chunk_row(2, "doc-a"),
+ _make_chunk_row(3, "doc-b"),
+ ]
+ )
+ # The reconciler returns early BEFORE the prior-status /
+ # document-collection / rag-index queries fire, so we don't
+ # need to wire those up — the chunk query above is the only
+ # session.query() call that runs.
+ session = MagicMock()
+ session.query.return_value = chunk_q
+ with patch(
+ f"{_MOD}.get_user_db_session",
+ return_value=_make_session_ctx(session),
+ ):
+ result = svc.reconcile_collection_index("coll-1")
+
+ assert result["reconciliation_skipped"] is True
+ assert result["indexed_documents"] == 0
+ assert result["indexed_chunks"] == 0
+ assert result["live_vectors"] == 0
+ assert "refusing to clear" in result["reason"].lower()
+ # The refuse-to-shrink invariant: the early return path MUST NOT
+ # have committed anything (no commit, no bulk delete).
+ assert not session.commit.called
+ assert not session.delete.called
+
+ def test_empty_live_ids_with_no_chunk_rows_proceeds_normally(
+ self, tmp_path
+ ):
+ """A genuinely empty collection (no chunks) is NOT a transient
+ fault — the reconciler proceeds and returns a zeroed result.
+ """
+ svc = _make_service()
+ svc.rag_index_record = MagicMock()
+ svc.rag_index_record.id = 7
+
+ vindex = MagicMock()
+ vindex.live_ids.return_value = []
+ with patch.object(svc, "_get_vector_index", return_value=vindex):
+ # No chunk rows; the empty result still triggers the
+ # follow-up queries, but they all return empty too.
+ empty_q = _build_query_mock(all_rows=[])
+ session = MagicMock()
+ session.query.return_value = empty_q
+ with patch(
+ f"{_MOD}.get_user_db_session",
+ return_value=_make_session_ctx(session),
+ ):
+ result = svc.reconcile_collection_index("coll-1")
+
+ assert "reconciliation_skipped" not in result
+ assert result["indexed_documents"] == 0
+ assert result["live_vectors"] == 0
+
+
+class TestReconcilePreservesIndexedAt:
+ """``RagDocumentStatus.indexed_at`` is preserved for durable docs."""
+
+ def test_durable_doc_keeps_prior_indexed_at(self):
+ svc = _make_service()
+ svc.rag_index_record = MagicMock()
+ svc.rag_index_record.id = 7
+
+ vindex = MagicMock()
+ vindex.live_ids.return_value = [10, 11, 12]
+ with patch.object(svc, "_get_vector_index", return_value=vindex):
+ # Two chunk rows for doc-a, one for doc-b. Both durable.
+ chunk_q = _build_query_mock(
+ all_rows=[
+ _make_chunk_row(10, "doc-a"),
+ _make_chunk_row(11, "doc-a"),
+ _make_chunk_row(12, "doc-b"),
+ ]
+ )
+ # doc-a had an existing status row with indexed_at=t0
+ t0 = datetime(2024, 1, 1, tzinfo=UTC)
+ prior_status_q = _build_query_mock(
+ all_rows=[_make_status_row("doc-a", t0)]
+ )
+ empty_q = _build_query_mock(all_rows=[])
+ rag_index_q = _build_query_mock()
+ session = MagicMock()
+ # Order of session.query() calls in production:
+ # 1. DocumentChunk rows (chunk_q)
+ # 2. RagDocumentStatus prior indexed_at (prior_status_q)
+ # 3. DocumentCollection links (empty_q)
+ # 4. RagDocumentStatus bulk delete (empty_q — same shape)
+ # 5. RAGIndex row (rag_index_q)
+ session.query.side_effect = [
+ chunk_q,
+ prior_status_q,
+ empty_q,
+ empty_q,
+ rag_index_q,
+ ]
+ with patch(
+ f"{_MOD}.get_user_db_session",
+ return_value=_make_session_ctx(session),
+ ):
+ result = svc.reconcile_collection_index("coll-1")
+
+ assert result["indexed_documents"] == 2
+ assert result["indexed_chunks"] == 3
+
+ # Inspect the RagDocumentStatus rows that were added to the
+ # session: doc-a must keep indexed_at=t0, doc-b must use ``now``.
+ added = []
+ for call in session.add.call_args_list:
+ if not call.args:
+ continue
+ obj = call.args[0]
+ if getattr(obj, "document_id", None) in ("doc-a", "doc-b"):
+ added.append(obj)
+ by_doc = {row.document_id: row for row in added}
+ assert "doc-a" in by_doc, "doc-a must have a status row added"
+ assert "doc-b" in by_doc, "doc-b must have a status row added"
+ assert by_doc["doc-a"].indexed_at == t0, (
+ "doc-a must keep its original indexed_at"
+ )
+ assert by_doc["doc-b"].indexed_at != t0, (
+ "doc-b had no prior row, so it must get the current timestamp"
+ )
+
+
+class TestReconcilePartialDurabilityAndOrphans:
+ """Reconciler requires ALL doc chunks in live_ids and counts orphan_vectors."""
+
+ def test_partial_durability_marks_doc_not_durable(self):
+ """If doc-a has chunks [10, 11] but live_ids only has [10], doc-a is NOT durable."""
+ svc = _make_service()
+ svc.rag_index_record = MagicMock()
+ svc.rag_index_record.id = 7
+
+ vindex = MagicMock()
+ vindex.live_ids.return_value = [10] # Missing chunk 11
+ with patch.object(svc, "_get_vector_index", return_value=vindex):
+ chunk_q = _build_query_mock(
+ all_rows=[
+ _make_chunk_row(10, "doc-a"),
+ _make_chunk_row(11, "doc-a"),
+ ]
+ )
+ empty_q = _build_query_mock(all_rows=[])
+ rag_index_q = _build_query_mock()
+ session = MagicMock()
+ session.query.side_effect = [
+ chunk_q,
+ empty_q,
+ empty_q,
+ empty_q,
+ rag_index_q,
+ ]
+ with patch(
+ f"{_MOD}.get_user_db_session",
+ return_value=_make_session_ctx(session),
+ ):
+ result = svc.reconcile_collection_index("coll-1")
+
+ assert result["indexed_documents"] == 0
+ assert result["indexed_chunks"] == 0
+ assert result["live_vectors"] == 1
+
+ def test_orphan_vectors_counted_when_live_ids_has_extra_vectors(self):
+ """Vectors in live_ids with no matching DocumentChunk DB row are counted as orphans."""
+ svc = _make_service()
+ svc.rag_index_record = MagicMock()
+ svc.rag_index_record.id = 7
+
+ vindex = MagicMock()
+ vindex.live_ids.return_value = [10, 999] # 999 is an orphan
+ with patch.object(svc, "_get_vector_index", return_value=vindex):
+ chunk_q = _build_query_mock(
+ all_rows=[
+ _make_chunk_row(10, "doc-a"),
+ ]
+ )
+ empty_q = _build_query_mock(all_rows=[])
+ rag_index_q = _build_query_mock()
+ session = MagicMock()
+ session.query.side_effect = [
+ chunk_q,
+ empty_q,
+ empty_q,
+ empty_q,
+ rag_index_q,
+ ]
+ with patch(
+ f"{_MOD}.get_user_db_session",
+ return_value=_make_session_ctx(session),
+ ):
+ result = svc.reconcile_collection_index("coll-1")
+
+ assert result["indexed_documents"] == 1
+ assert result["indexed_chunks"] == 1
+ assert result["live_vectors"] == 2
+ assert result["orphan_vectors"] == 1
diff --git a/tests/vector_stores/test_facade.py b/tests/vector_stores/test_facade.py
index 4f8ab6c93a..9c00a3e43e 100644
--- a/tests/vector_stores/test_facade.py
+++ b/tests/vector_stores/test_facade.py
@@ -314,6 +314,149 @@ class TestIndex:
assert db_session.query(DocumentChunk).count() == 1
+# --------------------------------------------------------------------------
+# index_prepared() — bulk path used by parallel RAG indexing (PR #5235)
+# --------------------------------------------------------------------------
+class TestIndexPrepared:
+ """Pre-embedded write path: embedding stays outside the FAISS/DB lock."""
+
+ def test_index_prepared_writes_rows_and_vectors(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ chunks = [
+ ChunkInput(text="hello world", metadata={"chunk_index": 0}),
+ ChunkInput(text="second chunk", metadata={"chunk_index": 1}),
+ ]
+ vectors = np.asarray(
+ vi.embeddings.embed_documents([c.text for c in chunks]),
+ dtype="float32",
+ )
+ stats = vi.index_prepared(
+ source_type="document",
+ source_id="doc1",
+ chunks=chunks,
+ vectors=vectors,
+ )
+
+ assert stats.chunks == 2
+ assert stats.added == 2
+ assert stats.removed == 0
+
+ rows = (
+ patched_db.query(DocumentChunk)
+ .filter_by(source_type="document", source_id="doc1")
+ .all()
+ )
+ assert len(rows) == 2
+ assert vi.count() == 2
+ assert set(vi._store.live_ids()) == {r.id for r in rows}
+
+ def test_index_prepared_does_not_call_embed_documents(
+ self, tmp_path, patched_db, mocker
+ ):
+ vi = _make_index(tmp_path)
+ embed_spy = mocker.spy(vi.embeddings, "embed_documents")
+ chunks = [ChunkInput(text="pre-embedded")]
+ vectors = np.ones((1, 4), dtype="float32")
+
+ vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=chunks,
+ vectors=vectors,
+ )
+
+ embed_spy.assert_not_called()
+ assert vi.count() == 1
+
+ def test_index_prepared_rejects_missing_vectors(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ with pytest.raises(ValueError, match="chunks given without vectors"):
+ vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="x")],
+ vectors=None,
+ )
+
+ def test_index_prepared_rejects_vector_count_mismatch(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ with pytest.raises(ValueError, match="vector count must match"):
+ vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="a"), ChunkInput(text="b")],
+ vectors=np.ones((1, 4), dtype="float32"),
+ )
+
+ def test_index_prepared_replace_true_purges_prior(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ old = [ChunkInput(text="old1"), ChunkInput(text="old2")]
+ vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=old,
+ vectors=np.ones((2, 4), dtype="float32"),
+ )
+ assert vi.count() == 2
+
+ stats = vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="new1")],
+ vectors=np.ones((1, 4), dtype="float32"),
+ replace=True,
+ )
+ assert stats.removed == 2
+ assert stats.added == 1
+ assert vi.count() == 1
+ rows = patched_db.query(DocumentChunk).filter_by(source_id="d1").all()
+ assert len(rows) == 1
+ assert rows[0].chunk_text == "new1"
+
+ def test_index_prepared_rolls_back_db_on_apply_failure(
+ self, tmp_path, patched_db, mocker
+ ):
+ vi = _make_index(tmp_path)
+ mocker.patch.object(
+ vi._store, "apply", side_effect=RuntimeError("boom")
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="z")],
+ vectors=np.ones((1, 4), dtype="float32"),
+ )
+
+ assert patched_db.query(DocumentChunk).count() == 0
+
+ def test_index_prepared_empty_chunks_replace_purges_prior(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="old")],
+ vectors=np.ones((1, 4), dtype="float32"),
+ )
+ stats = vi.index_prepared(
+ source_type="document",
+ source_id="d1",
+ chunks=[],
+ vectors=None,
+ replace=True,
+ )
+ assert stats.removed == 1
+ assert stats.added == 0
+ assert vi.count() == 0
+
+
# --------------------------------------------------------------------------
# search()
# --------------------------------------------------------------------------