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): preserve the index until a rebuild succeeds (#6917)

LearningCircuit19ba1a505c75
diff --git a/changelog.d/+preserve-collection-during-rebuild.bugfix.md b/changelog.d/+preserve-collection-during-rebuild.bugfix.md
new file mode 100644
index 0000000000..d04bb67e4e
--- /dev/null
+++ b/changelog.d/+preserve-collection-during-rebuild.bugfix.md
@@ -0,0 +1,5 @@
+Keep a collection's working search index available while a forced rebuild prepares its replacement. A rebuild that fails, or is cancelled before it starts publishing, keeps the previous index and configuration. If a cancel arrives after publishing has started, the rebuild finishes and its task reports the published result instead of a cancellation. A successful rebuild publishes the complete replacement in one database transaction and only then deletes the retired files.
+
+The rebuild holds the collection's indexing lock until it has deleted those files, so re-indexing after the index is cleared cannot lose a new file that reuses a retired path. Clearing an index and deleting a collection remove their own files without taking this lock. They also remove the staging data an interrupted rebuild left behind, unless a rebuild of that collection is still running.
+
+Show rebuild progress, explain the effect of cancelling, and retain a collection warning when a rebuild does not finish. The notice survives later incremental indexing and task-history cleanup. Automatic indexing can add unindexed documents but does not retry a cancelled full rebuild. Keep polling until cancellation finishes so a late successful publication is reported correctly.
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index 0b3c84e950..38b5e86194 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -168,6 +168,24 @@ Document → Split into Chunks → Generate Embeddings → Store in Vector Index
3. Click **Index for Search** (or **Rebuild Index**)
4. Wait for indexing to complete (progress shown)
+**Re-Index All Documents** builds a complete replacement while searches use
+the published index. Keep the rebuild running until it completes. Cancelling
+before publication discards the replacement and keeps the previous index and
+embedding settings, even if that index is old. Once publication begins,
+cancellation no longer interrupts its transaction. If publication succeeds,
+a late cancellation then reports that the new index is in use.
+
+An incomplete rebuild leaves a warning on the collection, including the
+published index's last update time when available. This timestamp can also
+change during incremental indexing; it is not the date of the last full
+rebuild. The warning survives reloads and later incremental jobs, until a full
+rebuild succeeds or the index is explicitly cleared.
+
+Automatic indexing, when enabled, can add missing or unindexed documents using
+the collection's existing settings. It does not resume or retry a cancelled
+full rebuild, and it does not apply the replacement embedding settings. Run
+**Re-Index All Documents** again to finish that change.
+
### Index Status
| Status | Meaning |
diff --git a/src/local_deep_research/database/migrations/versions/0033_collection_rebuild_notice.py b/src/local_deep_research/database/migrations/versions/0033_collection_rebuild_notice.py
new file mode 100644
index 0000000000..098356d1a4
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0033_collection_rebuild_notice.py
@@ -0,0 +1,36 @@
+"""Keep incomplete collection rebuilds visible after task history expires.
+
+Revision ID: 0033
+Revises: 0032
+"""
+
+import sqlalchemy as sa
+from alembic import op
+from sqlalchemy import inspect
+from sqlalchemy_utc import UtcDateTime
+
+revision = "0033"
+down_revision = "0032"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ inspector = inspect(op.get_bind())
+ if inspector.has_table("collections") and "rebuild_pending_since" not in {
+ column["name"] for column in inspector.get_columns("collections")
+ }:
+ op.add_column(
+ "collections",
+ sa.Column("rebuild_pending_since", UtcDateTime(), nullable=True),
+ )
+
+
+def downgrade():
+ inspector = inspect(op.get_bind())
+ if inspector.has_table("collections") and "rebuild_pending_since" in {
+ column["name"] for column in inspector.get_columns("collections")
+ }:
+ # Native DROP COLUMN preserves dependent rows even with foreign keys
+ # enabled. Recreating collections in batch mode can cascade deletes.
+ op.drop_column("collections", "rebuild_pending_since")
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index 8480ce1ef1..53fe182c46 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -447,6 +447,12 @@ class Collection(Base):
# a security control.
agent_enabled: Mapped[bool | None] = mapped_column(Boolean, default=True)
+ # A requested full rebuild has not published yet. Kept independently of
+ # short-lived task history; incremental indexing does not finish a rebuild.
+ rebuild_pending_since: Mapped[datetime | None] = mapped_column(
+ UtcDateTime, nullable=True
+ )
+
# Embedding model used for this collection (stored when first indexed)
embedding_model: Mapped[str | None] = mapped_column(
String(100), nullable=True
diff --git a/src/local_deep_research/research_library/deletion/services/collection_deletion.py b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
index 01994cadb9..8d55b1eb37 100644
--- a/src/local_deep_research/research_library/deletion/services/collection_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/collection_deletion.py
@@ -68,6 +68,25 @@ def _user_settings_snapshot(session) -> Dict[str, Any]:
)
+def _remove_unfinished_rebuilds(username: str, collection_id: str) -> None:
+ """Remove interrupted rebuild stages; the deletion has already committed.
+
+ A failure only leaves those stages behind, so it is logged without a
+ traceback rather than reported as a failed deletion.
+ """
+ from ...services.collection_rebuild import remove_unfinished_rebuilds
+
+ try:
+ remove_unfinished_rebuilds(
+ username, collection_id, lambda: get_user_db_session(username)
+ )
+ except Exception:
+ logger.warning(
+ "Could not remove unfinished rebuilds of collection {}",
+ short_id(collection_id),
+ )
+
+
def _remote_drop_failure_result(
collection_id: str, exc: RemoteVectorStoreDropError, outcome: str
) -> Dict[str, Any]:
@@ -359,6 +378,9 @@ class CollectionDeletionService:
faiss_path, allowed_root=rag_indices_root
)
+ # Before the orphan purge below, so it never sees staging chunk rows.
+ _remove_unfinished_rebuilds(self.username, collection_id)
+
# Purge each hard-deleted orphan's vectors + chunk rows in its OTHER
# collections (this collection's chunks were removed in step 2). Reuses
# DocumentDeletionService's per-collection vector purge + chunk backstop.
@@ -468,6 +490,7 @@ class CollectionDeletionService:
collection.embedding_dimension = None
collection.chunk_size = None
collection.chunk_overlap = None
+ collection.rebuild_pending_since = None
session.commit()
@@ -494,8 +517,6 @@ class CollectionDeletionService:
f"{result['documents_reset']} documents reset"
)
- return result
-
except RemoteVectorStoreDropError as exc:
# See delete_collection: keep the RAGIndex rows so the remote
# collection stays addressable, and report failure. Logged
@@ -520,6 +541,10 @@ class CollectionDeletionService:
"error": "Failed to delete collection index",
}
+ # After the commit and outside its scope, as in delete_collection.
+ _remove_unfinished_rebuilds(self.username, collection_id)
+ return result
+
def get_deletion_preview(self, collection_id: str) -> Dict[str, Any]:
"""
Get a preview of what will be deleted.
diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
index 6f16df10ed..e6cffbb03a 100644
--- a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
+++ b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
@@ -784,9 +784,9 @@ class CascadeHelper:
transaction). If the caller has already written in that transaction,
the user's database write lock is held across those network calls, so
call this before the transaction's first write where possible: the
- collection-deletion service does; the force-reindex reset
- (``web/routers/rag.py``) runs after its embedding-metadata write and
- chunk delete, so there the lock is held for the drops. Only
+ collection-deletion service does. Collection rebuilds
+ (``collection_rebuild.py``) run only while every registered provider
+ stores local files, so their calls make no network call. Only
server-backed stores make network calls here (FAISS never does), and
their ``drop_collection`` is expected to bound each call with a
client timeout.
@@ -852,10 +852,10 @@ class CascadeHelper:
index_paths: List[str] = []
# Only needed on the unlink_files=True path (below) -- computed
- # lazily so the unlink_files=False path (all 3 current external
- # callers) doesn't pay for it. Same containment root those callers
+ # lazily so the unlink_files=False path (every current external
+ # caller) doesn't pay for it. Same containment root those callers
# pass to their own post-commit delete_faiss_index_files() call
- # (see collection_deletion.py, web/routers/rag.py), computed here too so
+ # (see collection_deletion.py, collection_rebuild.py), computed here too so
# unlink_files=True gets the same symlinked-ancestor defense --
# currently unreachable (all callers pass unlink_files=False) but
# kept in sync to avoid a latent gap if that changes.
diff --git a/src/local_deep_research/research_library/services/collection_rebuild.py b/src/local_deep_research/research_library/services/collection_rebuild.py
new file mode 100644
index 0000000000..46ce66fe2d
--- /dev/null
+++ b/src/local_deep_research/research_library/services/collection_rebuild.py
@@ -0,0 +1,568 @@
+"""Build a replacement collection index without changing its published state."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import uuid
+from collections.abc import Callable
+from contextlib import AbstractContextManager
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+import numpy as np
+from loguru import logger
+from sqlalchemy.orm import Session
+
+from ...config.paths import get_cache_directory
+from ...database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ EmbeddingProvider,
+ RagDocumentStatus,
+ RAGIndex,
+ RAGIndexStatus,
+)
+from ...database.session_context import safe_rollback
+from ...vector_stores.config import only_local_file_providers_registered
+
+if TYPE_CHECKING:
+ from .library_rag_service import LibraryRAGService, _PreparedDocument
+
+
+_CONFIG_FIELDS = (
+ "embedding_model",
+ "embedding_model_type",
+ "embedding_dimension",
+ "chunk_size",
+ "chunk_overlap",
+ "splitter_type",
+ "text_separators",
+ "distance_metric",
+ "normalize_vectors",
+ "index_type",
+)
+
+
+def document_fingerprint(document: Document) -> str:
+ """Identify the source text and metadata used to prepare a document."""
+ payload = {
+ key: getattr(document, key)
+ for key in (
+ "text_content",
+ "title",
+ "filename",
+ "original_url",
+ "authors",
+ "published_date",
+ "doi",
+ "arxiv_id",
+ "pmid",
+ "pmcid",
+ "extraction_method",
+ "word_count",
+ )
+ }
+ return hashlib.sha256(
+ json.dumps(payload, sort_keys=True, default=str).encode("utf-8")
+ ).hexdigest()
+
+
+def collection_configuration(collection: Collection) -> str:
+ """Snapshot the stored settings that must survive an unfinished rebuild."""
+ return json.dumps(
+ {key: getattr(collection, key) for key in _CONFIG_FIELDS},
+ sort_keys=True,
+ default=str,
+ )
+
+
+def _index_state(session: Session, collection_name: str) -> list[tuple]:
+ return sorted(
+ (
+ row.id,
+ row.index_hash,
+ row.is_current,
+ row.chunk_count,
+ row.total_documents,
+ row.last_updated_at,
+ )
+ for row in session.query(RAGIndex).filter_by(
+ collection_name=collection_name
+ )
+ )
+
+
+def _membership_state(session: Session, collection_id: str) -> list[tuple]:
+ return sorted(
+ (
+ row.document_id,
+ row.id,
+ row.indexed,
+ row.chunk_count,
+ row.last_indexed_at,
+ )
+ for row in session.query(DocumentCollection).filter_by(
+ collection_id=collection_id
+ )
+ )
+
+
+def rebuild_stage_prefix(collection_id: str) -> str:
+ """Return the name prefix shared by every rebuild stage of a collection."""
+ scope = hashlib.sha256(collection_id.encode()).hexdigest()[:16]
+ return f"collection_rebuild_{scope}_"
+
+
+class RebuildCancelled(RuntimeError):
+ """Cancellation observed before publishing a replacement."""
+
+
+class CollectionRebuild:
+ """A private generation whose only publication point is a DB commit.
+
+ Chunk rows and text-free vector files use a unique staging identity.
+ Publishing changes their collection identity, the current-index pointer,
+ collection configuration and document status in one transaction. Files
+ retain their generation paths, so no filesystem rename can race that
+ transaction. A process interruption can leave an unpublished generation,
+ but cannot remove the previously published one.
+
+ The caller holds the per-collection rebuild lock through preparation and
+ cleanup. Ordinary indexing/search need only the shorter collection lock
+ around publication. Document embedding never holds that lock or a DB
+ transaction. Interrupted stages stay unselected until the collection is
+ deleted or its index cleared (``remove_unfinished_rebuilds``); another
+ process's unfinished generation must not be removed speculatively.
+ """
+
+ def __init__(
+ self,
+ service: LibraryRAGService,
+ collection_id: str,
+ doc_info: list[tuple[str, str]],
+ *,
+ session_factory: Callable[[], AbstractContextManager[Session]],
+ ):
+ # The generation switch and post-commit retirement below are atomic
+ # only for local files. A remote drop cannot be rolled back, and the
+ # current RAGIndex rows do not record which backend owns their data.
+ # Refuse rebuilding if any remote provider is registered until those
+ # providers have a separate publication protocol.
+ if not only_local_file_providers_registered():
+ raise RuntimeError(
+ "Staged collection rebuild requires local-file vector stores"
+ )
+ self.service = service
+ self.collection_id = collection_id
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Collection identifier passed as an ORM value; never SQL statement text
+ self.collection_name = f"collection_{collection_id}"
+ prefix = rebuild_stage_prefix(collection_id)
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: Collection identifier passed as an ORM value; never SQL statement text
+ self.stage_name = f"{prefix}{uuid.uuid4().hex}"
+ self.stage_id = self.stage_name.removeprefix("collection_")
+ self.vector_index = None
+ self.index_id = None
+ self.prepared = {}
+ self.published = False
+ self.target_configuration = None
+ self._session = session_factory
+
+ with self._session() as session:
+ collection = session.get(Collection, collection_id)
+ if collection is None:
+ raise ValueError("Collection not found")
+ self.configuration = collection_configuration(collection)
+ self.original_indices = _index_state(session, self.collection_name)
+ self.original_memberships = _membership_state(
+ session, collection_id
+ )
+ self.document_ids = {row[0] for row in self.original_memberships}
+ if self.document_ids != {doc_id for doc_id, _title in doc_info}:
+ raise ValueError("Collection changed before rebuilding; retry")
+ # Persist before preparation so cancellation or a process exit
+ # cannot silently erase the unfinished request. The user DB is
+ # encrypted; no document content is copied into this marker.
+ collection.rebuild_pending_since = datetime.now(UTC)
+ session.commit()
+ logger.info(
+ "Rebuilding collection index; the published index, if any, "
+ "remains in use until the replacement is complete. "
+ "Cancelling before publication keeps that index and does not "
+ "retry the rebuild."
+ )
+
+ def prepare(
+ self,
+ document_id: str,
+ is_cancelled: Callable[[], bool] | None = None,
+ ) -> dict[str, Any]:
+ from .library_rag_service import _PreparedDocument
+
+ result = self.service._prepare_document(
+ document_id, self.collection_id, True, is_cancelled
+ )
+ if result.get("status") == "needs_serial_write":
+ # Empty documents have no replacement chunks. Never dispatch the
+ # ordinary empty-document purge against the published generation.
+ return {
+ "status": "prepared",
+ "prepared": _PreparedDocument(
+ document_id=document_id,
+ collection_id=self.collection_id,
+ chunk_inputs=[],
+ vectors=np.empty((0, 0), dtype="float32"),
+ source_fingerprint=result["source_fingerprint"],
+ ),
+ }
+ return result
+
+ def write(self, prepared: _PreparedDocument) -> dict[str, Any]:
+ """Persist only private chunks; leave published flags and files alone."""
+ if prepared.document_id not in self.document_ids:
+ raise ValueError("Document does not belong to this rebuild")
+ if prepared.chunk_inputs:
+ if self.vector_index is None:
+ self.vector_index = self.service._get_vector_index(
+ self.stage_id, self.stage_name
+ )
+ self.index_id = self.service.rag_index_record.id
+ with self._session() as session:
+ try:
+ self.vector_index.index_prepared(
+ source_type="document",
+ source_id=prepared.document_id,
+ chunks=prepared.chunk_inputs,
+ vectors=prepared.vectors,
+ replace=True,
+ session=session,
+ )
+ index = session.get(RAGIndex, self.index_id)
+ index.status = RAGIndexStatus.REBUILDING
+ session.commit()
+ except Exception:
+ safe_rollback(session, "collection_rebuild.write")
+ raise
+ self.prepared[prepared.document_id] = (
+ prepared.source_fingerprint,
+ len(prepared.chunk_inputs),
+ )
+ return {
+ "status": "success" if prepared.chunk_inputs else "cleared",
+ "chunk_count": len(prepared.chunk_inputs),
+ }
+
+ def _validate_sources(self, session, collection):
+ if collection_configuration(collection) != self.configuration:
+ raise ValueError("Collection configuration changed; retry rebuild")
+ if _index_state(session, self.collection_name) != self.original_indices:
+ raise ValueError("Collection index changed; retry rebuild")
+ # Removing a document from search changes its membership's indexing
+ # state without changing the collection's RAGIndex counters. Preserve
+ # that successful removal instead of restoring its staged vectors.
+ if (
+ _membership_state(session, self.collection_id)
+ != self.original_memberships
+ ):
+ raise ValueError("Collection indexing state changed; retry rebuild")
+ seen = set()
+ # Bound retained source text during the final validation. A writer
+ # transaction prevents edits between validation and publication.
+ documents = (
+ session.query(Document)
+ .join(DocumentCollection)
+ .filter(DocumentCollection.collection_id == self.collection_id)
+ .yield_per(1)
+ )
+ for document in documents:
+ seen.add(document.id)
+ expected = self.prepared.get(document.id)
+ if (
+ expected is None
+ or document_fingerprint(document) != expected[0]
+ ):
+ raise ValueError("Collection documents changed; retry rebuild")
+ if seen != self.document_ids or set(self.prepared) != self.document_ids:
+ raise ValueError("Collection documents changed; retry rebuild")
+
+ def _validate_vectors(self):
+ with self._session() as session:
+ chunk_ids = {
+ row.id
+ for row in session.query(DocumentChunk.id).filter_by(
+ collection_name=self.stage_name
+ )
+ }
+ # Reopen the durable generation: the in-memory facade can
+ # still contain every vector after a file was lost or a
+ # persist failed. Publication requires the bytes on disk.
+ durable_index = (
+ self.service._get_vector_index(self.stage_id, self.stage_name)
+ if self.vector_index is not None
+ else None
+ )
+ live_ids = set(durable_index.live_ids()) if durable_index else set()
+ expected_chunks = sum(
+ n for _fingerprint, n in self.prepared.values()
+ )
+ if chunk_ids != live_ids or len(chunk_ids) != expected_chunks:
+ raise RuntimeError("Replacement index is incomplete")
+
+ return expected_chunks
+
+ def _publish_rows(self, session, expected_chunks):
+ from ..deletion.utils.cascade_helper import CascadeHelper
+
+ # Acquire SQLite's writer lock before reading the state
+ # that must remain unchanged through the publication.
+ found = (
+ session.query(Collection)
+ .filter_by(id=self.collection_id)
+ .update({Collection.id: Collection.id})
+ )
+ if not found:
+ raise ValueError("Collection was deleted during rebuild")
+ # Validation, every publication write and the commit must share the
+ # transaction that took the lock. No callback runs before the commit:
+ # a callback that opened get_user_db_session on this thread would
+ # share this session, and its error handler would roll it back.
+ transaction = session.get_transaction()
+ session.expire_all()
+ collection = session.get(Collection, self.collection_id)
+ self._validate_sources(session, collection)
+
+ CascadeHelper.delete_collection_chunks(session, self.collection_name)
+ retired = CascadeHelper.delete_rag_indices_for_collection(
+ session, self.collection_name, unlink_files=False
+ )
+
+ # Explicit deletion also works with SQLite connections
+ # whose foreign-key enforcement was not configured.
+ session.query(RagDocumentStatus).filter_by(
+ collection_id=self.collection_id
+ ).delete(synchronize_session=False)
+ session.query(DocumentCollection).filter_by(
+ collection_id=self.collection_id
+ ).update({"indexed": False, "chunk_count": 0})
+ session.query(DocumentChunk).filter_by(
+ collection_name=self.stage_name
+ ).update({"collection_name": self.collection_name})
+
+ timestamp = datetime.now(UTC)
+ index = (
+ session.get(RAGIndex, self.index_id)
+ if self.index_id is not None
+ else None
+ )
+ if index is not None:
+ index.collection_name = self.collection_name
+ index.is_current = True
+ index.status = RAGIndexStatus.ACTIVE
+ index.chunk_count = expected_chunks
+ index.total_documents = sum(
+ n > 0 for _fingerprint, n in self.prepared.values()
+ )
+ index.last_updated_at = timestamp
+ for document_id, (
+ _fingerprint,
+ count,
+ ) in self.prepared.items():
+ if count:
+ session.add(
+ RagDocumentStatus(
+ document_id=document_id,
+ collection_id=self.collection_id,
+ rag_index_id=self.index_id,
+ chunk_count=count,
+ indexed_at=timestamp,
+ )
+ )
+ session.query(DocumentCollection).filter_by(
+ document_id=document_id,
+ collection_id=self.collection_id,
+ ).update(
+ {
+ "indexed": True,
+ "chunk_count": count,
+ "last_indexed_at": timestamp,
+ }
+ )
+ for field in _CONFIG_FIELDS:
+ if field == "embedding_model_type":
+ value = EmbeddingProvider(self.service.embedding_provider)
+ elif field == "embedding_dimension":
+ value = index.embedding_dimension if index else None
+ else:
+ value = getattr(self.service, field)
+ setattr(collection, field, value)
+
+ # Clear only with the generation switch, including an empty rebuild.
+ collection.rebuild_pending_since = None
+
+ # A rollback since the lock was taken means the writes above run in a
+ # newer transaction that validation never checked, and may hold only
+ # part of the publication. Refuse to commit them, before recording
+ # the target that _is_published() compares after a failure.
+ if session.get_transaction() is not transaction:
+ raise RuntimeError(
+ "Collection publication lost its transaction; retry rebuild"
+ )
+ self.target_configuration = collection_configuration(collection)
+ return retired["index_paths"]
+
+ def publish(self, is_cancelled: Callable[[], bool] | None = None) -> None:
+ """Publish a complete generation, then remove retired vector files.
+
+ Cancellation is decided once, before the publication transaction
+ opens. After that the publication commits or rolls back as a whole.
+ """
+ expected_chunks = self._validate_vectors()
+ old_paths = []
+ with self.service._collection_transaction_lock(self.collection_id):
+ # The background task's check reads the task row through
+ # get_user_db_session. On this thread it gets the session that
+ # publishes below. Run it while no scope is open, so its
+ # autoflush and its error rollback cannot reach the publication.
+ self._check_cancelled(is_cancelled)
+ try:
+ with self._session() as session:
+ try:
+ old_paths = self._publish_rows(session, expected_chunks)
+ session.commit()
+ self.published = True
+ except Exception:
+ safe_rollback(session, "collection_rebuild.publish")
+ raise
+ except Exception:
+ # A post-commit callback can raise after publication. Use a
+ # fresh session: the failed one may still be in COMMITTED
+ # state, where even rollback and SELECT are unavailable.
+ with self._session() as session:
+ self.published = self._is_published(session)
+ if not self.published:
+ raise
+ logger.warning(
+ "Collection replacement committed despite a commit callback failure"
+ )
+
+ # Clearing an index and indexing again can reuse a retired path.
+ # Keep collection ownership through removal so retirement cannot
+ # delete the new writer's file. The DB commit has already finished.
+ self._unlink(old_paths)
+ from ...web_search_engines.search_engines_config import (
+ invalidate_collection_engines_cache,
+ )
+
+ invalidate_collection_engines_cache(self.service.username)
+
+ @staticmethod
+ def _check_cancelled(is_cancelled):
+ if is_cancelled is not None and is_cancelled():
+ raise RebuildCancelled("Collection rebuild was cancelled")
+
+ def _is_published(self, session):
+ if self.index_id is None:
+ collection = session.get(Collection, self.collection_id)
+ return bool(
+ self.target_configuration is not None
+ and collection is not None
+ and collection.rebuild_pending_since is None
+ and collection_configuration(collection)
+ == self.target_configuration
+ and not _index_state(session, self.collection_name)
+ )
+ index = session.get(RAGIndex, self.index_id)
+ return bool(index and index.collection_name == self.collection_name)
+
+ @staticmethod
+ def _unlink(paths):
+ from ..deletion.utils.cascade_helper import CascadeHelper
+
+ for path in paths:
+ CascadeHelper.delete_faiss_index_files(
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Deletion helper enforces containment beneath the explicit rag_indices root
+ Path(path),
+ allowed_root=get_cache_directory() / "rag_indices",
+ )
+
+ def close(self):
+ """Remove this unpublished generation after its workers have drained."""
+ from ..deletion.utils.cascade_helper import CascadeHelper
+
+ if self.published:
+ return
+ try:
+ with self._session() as session:
+ if self._is_published(session):
+ self.published = True
+ return
+ logger.warning(
+ "Collection rebuild did not publish a replacement. The "
+ "previous index, if any, remains in use and may be "
+ "outdated. Automatic indexing does not retry full "
+ "rebuilds; run Re-Index All again."
+ )
+ CascadeHelper.delete_collection_chunks(session, self.stage_name)
+ retired = CascadeHelper.delete_rag_indices_for_collection(
+ session, self.stage_name, unlink_files=False
+ )
+ session.commit()
+ self._unlink(retired["index_paths"])
+ except Exception:
+ logger.exception(
+ "Could not remove an unpublished collection rebuild"
+ )
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.close()
+ return False
+
+
+def remove_unfinished_rebuilds(
+ username: str,
+ collection_id: str,
+ session_factory: Callable[[], AbstractContextManager[Session]],
+) -> int:
+ """Remove the stages that interrupted rebuilds of a collection left.
+
+ Collection deletion and index clearing call this after their commit.
+ Nothing selects a stage again, and its chunk rows hold document text.
+ Each stage is removed the way ``CollectionRebuild.close`` removes its
+ own. A rebuild of the collection running in this process holds the
+ rebuild lock and removes its stage when it cannot publish, so while that
+ lock is held every stage is left alone. Returns the number removed.
+ """
+ from ..deletion.utils.cascade_helper import CascadeHelper
+ from .library_rag_service import _hold_collection_lock
+
+ with _hold_collection_lock(
+ username, collection_id, purpose="rebuild", blocking=False
+ ) as held:
+ if not held:
+ return 0
+ prefix = rebuild_stage_prefix(collection_id)
+ paths = []
+ with session_factory() as session:
+ names = {
+ name
+ for model in (DocumentChunk, RAGIndex)
+ for (name,) in session.query(model.collection_name)
+ .filter(
+ model.collection_name.startswith(prefix, autoescape=True)
+ )
+ .distinct()
+ }
+ for name in sorted(names):
+ CascadeHelper.delete_collection_chunks(session, name)
+ paths += CascadeHelper.delete_rag_indices_for_collection(
+ session, name, unlink_files=False
+ )["index_paths"]
+ session.commit()
+ CollectionRebuild._unlink(paths)
+ return len(names)
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 e58ad45ca2..635f6fe72c 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
@@ -19,7 +19,17 @@ 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,
+ Literal,
+ Optional,
+ Set,
+ Tuple,
+ Union,
+)
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError
from langchain_core.documents import Document as LangchainDocument
@@ -62,6 +72,12 @@ from ...security.directory_creation import create_directory
from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifier
from ...security.file_integrity.integrity_manager import NO_INTEGRITY_RECORD
from ...vector_stores.facade import VectorIndex, ChunkInput, SearchResult
+from .collection_rebuild import (
+ CollectionRebuild,
+ RebuildCancelled,
+ collection_configuration,
+ document_fingerprint,
+)
from langchain_core.embeddings import Embeddings
import hashlib
@@ -91,6 +107,8 @@ class _PreparedDocument:
collection_id: str
chunk_inputs: List[ChunkInput]
vectors: np.ndarray
+ source_fingerprint: str | None = None
+ collection_configuration: str | None = None
content_hash: Optional[str] = None
initial_indexed: Optional[bool] = None
status_exists: Optional[bool] = None
@@ -128,6 +146,48 @@ def _indexing_scope_error() -> Optional[Dict[str, str]]:
return None
+# Service settings a Collection stores besides embedding_model, named as
+# LibraryRAGService attributes.
+_COLLECTION_INDEX_SETTINGS = (
+ "embedding_provider",
+ "chunk_size",
+ "chunk_overlap",
+ "splitter_type",
+ "text_separators",
+ "distance_metric",
+ "normalize_vectors",
+ "index_type",
+)
+
+
+def resolve_collection_index_settings(
+ collection: Collection, defaults: Dict[str, Any]
+) -> Dict[str, Any]:
+ """Return the settings a service indexing ``collection`` uses.
+
+ A stored value wins and a NULL column takes ``defaults``. Collections
+ indexed before #1054 never stored the five advanced settings, and
+ migration 0032 adds those columns without a backfill. ``get_rag_service``
+ passes the user's current settings as ``defaults``.
+ """
+ provider = collection.embedding_model_type
+ normalize = collection.normalize_vectors
+ stored = {
+ "embedding_provider": provider.value if provider else None,
+ "chunk_size": collection.chunk_size,
+ "chunk_overlap": collection.chunk_overlap,
+ "splitter_type": collection.splitter_type,
+ "text_separators": collection.text_separators,
+ "distance_metric": collection.distance_metric,
+ "normalize_vectors": None if normalize is None else to_bool(normalize),
+ "index_type": collection.index_type,
+ }
+ return {
+ name: defaults[name] if value is None else value
+ for name, value in stored.items()
+ }
+
+
class _LazyEmbeddings(Embeddings):
"""Embeddings proxy that defers backend construction until first use.
@@ -152,6 +212,10 @@ class _LazyEmbeddings(Embeddings):
return self._manager.embeddings.embed_query(text)
+_CollectionLockPurpose = Literal["transaction", "rebuild"]
+_IndexLockKey = Tuple[str, Union[str, Tuple[_CollectionLockPurpose, str]]]
+
+
class _TrackedRLock:
"""RLock proxy that records active keys even for direct acquire() calls.
@@ -173,7 +237,7 @@ class _TrackedRLock:
key-discard.
"""
- def __init__(self, key: Tuple[str, str]):
+ def __init__(self, key: _IndexLockKey):
self._key = key
self._lock = threading.RLock()
# Per-wrapper recursion depth (independent of the inner RLock so we
@@ -251,9 +315,11 @@ class _TrackedRLock:
# — 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], _TrackedRLock] = {}
+# Logical collection operations share tracked ownership and user cleanup,
+# but use tuple identities distinct from every physical path string.
+_faiss_write_locks: Dict[_IndexLockKey, _TrackedRLock] = {}
_faiss_write_locks_lock = threading.Lock()
-_faiss_active_lock_keys: Set[Tuple[str, str]] = set()
+_faiss_active_lock_keys: Set[_IndexLockKey] = 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
@@ -352,8 +418,57 @@ def _hold_faiss_write_lock(username: str, index_path: str):
lock.release()
+def _get_collection_lock(
+ username: str, collection_id: str, *, purpose: _CollectionLockPurpose
+) -> _TrackedRLock:
+ """Identify a collection operation without interpreting its ID as a path.
+
+ The tuple namespace cannot collide with physical FAISS path keys. Share
+ tracked-lock cleanup with those locks so closing a user still releases
+ inactive entries while preserving locks held by background workers.
+ """
+ key = (username, (purpose, str(collection_id)))
+ with _faiss_write_locks_lock:
+ lock = _faiss_write_locks.get(key)
+ if lock is None:
+ lock = _TrackedRLock(key)
+ _faiss_write_locks[key] = lock
+ return lock
+
+
+@contextmanager
+def _hold_collection_lock(
+ username: str,
+ collection_id: str,
+ *,
+ purpose: _CollectionLockPurpose,
+ blocking: bool = True,
+):
+ """Hold a canonical logical lock, or yield None on nonblocking contention.
+
+ Retry eviction between lookup and acquisition just as physical FAISS
+ locks do. Collection IDs remain opaque and never reach filesystem APIs.
+ """
+ key = (username, (purpose, str(collection_id)))
+ while True:
+ lock = _get_collection_lock(username, collection_id, purpose=purpose)
+ if not lock.acquire(blocking=blocking):
+ yield None
+ return
+ with _faiss_write_locks_lock:
+ is_canonical = _faiss_write_locks.get(key) is lock
+ if is_canonical:
+ try:
+ yield lock
+ finally:
+ lock.release()
+ return
+ # Evicted before acquire; a stale wrapper cannot protect this key.
+ lock.release()
+
+
def pop_faiss_locks_for_user(username: str) -> None:
- """Remove inactive FAISS-write locks for a user."""
+ """Remove inactive physical and logical index 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:
@@ -626,6 +741,20 @@ class LibraryRAGService:
)
return hashlib.sha256(hash_input.encode()).hexdigest()
+ def _matches_collection_configuration(self, collection: Collection) -> bool:
+ """Whether ``collection`` still stores this service's configuration.
+
+ NULL columns resolve as in ``get_rag_service``, which filled them from
+ the user's settings when it built this service, so they resolve to
+ this service's own values. Only a stored value can differ, such as one
+ a complete rebuild published.
+ """
+ own = {name: getattr(self, name) for name in _COLLECTION_INDEX_SETTINGS}
+ return (
+ collection.embedding_model == self.embedding_model
+ and resolve_collection_index_settings(collection, own) == own
+ )
+
def _matches_current_index_configuration(self, rag_index: RAGIndex) -> bool:
stored_provider = rag_index.embedding_model_type
if isinstance(stored_provider, EmbeddingProvider):
@@ -1584,6 +1713,15 @@ class LibraryRAGService:
def search(
self, query: str, collection_id: str, top_k: int
+ ) -> List[SearchResult]:
+ """Search one published generation through the metadata switch."""
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ return self._search_published(query, collection_id, top_k)
+
+ def _search_published(
+ self, query: str, collection_id: str, top_k: int
) -> List[SearchResult]:
"""Semantic search within ``collection_id`` via the vector store.
@@ -1770,13 +1908,27 @@ class LibraryRAGService:
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
+ # This identity survives model/configuration changes and publication
+ # of a new generation. Acquire it before resolving the physical path.
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ with get_user_db_session(
+ self.username, self.db_password
+ ) as session:
+ index = self._resolve_index_for_config(session, collection_id)
+ index_hash = (
+ index.index_hash
+ if index is not None
+ else 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)) as lock:
+ yield lock
def _embed_texts_cancellable(
self,
@@ -1837,8 +1989,16 @@ class LibraryRAGService:
"message": "Document already indexed for this collection",
"chunk_count": link.chunk_count,
}
+ source_fingerprint = document_fingerprint(document)
+ collection = session.get(Collection, collection_id)
+ configuration = (
+ collection_configuration(collection) if collection else None
+ )
if not document.text_content:
- return {"status": "needs_serial_write"}
+ return {
+ "status": "needs_serial_write",
+ "source_fingerprint": source_fingerprint,
+ }
title = document.title or document.filename or "Untitled"
metadata = {
@@ -1913,6 +2073,8 @@ class LibraryRAGService:
collection_id=collection_id,
chunk_inputs=chunk_inputs,
vectors=vectors,
+ source_fingerprint=source_fingerprint,
+ collection_configuration=configuration,
content_hash=prep_content_hash,
initial_indexed=prep_initial_indexed,
status_exists=prep_status_exists,
@@ -1930,16 +2092,42 @@ class LibraryRAGService:
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 self._collection_transaction_lock(collection_id):
with get_user_db_session(
self.username, self.db_password
) as session:
+ # Embedding runs outside the collection lock. A complete
+ # rebuild may have published a different configuration while
+ # this document was being prepared. Reject that stale work
+ # before any write or recovery flag can touch the new index.
+ if prepared.source_fingerprint is not None:
+ document = session.get(Document, document_id)
+ if (
+ document is None
+ or document_fingerprint(document)
+ != prepared.source_fingerprint
+ ):
+ return {
+ "status": "error",
+ "error": "Document changed; retry indexing",
+ }
+ if prepared.collection_configuration is not None:
+ collection = session.get(Collection, collection_id)
+ if (
+ collection is None
+ or collection_configuration(collection)
+ != prepared.collection_configuration
+ or (
+ collection.embedding_model is not None
+ and not self._matches_collection_configuration(
+ collection
+ )
+ )
+ ):
+ return {
+ "status": "error",
+ "error": "Collection configuration changed; retry indexing",
+ }
try:
# Phase 3 Revalidation Gate: verify collection link, content, and indexed status.
# The membership check runs unconditionally so legacy
@@ -2168,12 +2356,7 @@ class LibraryRAGService:
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
- collection_name = f"collection_{collection_id}"
- index_hash = self._get_index_hash(
- collection_name, self.embedding_model, self.embedding_provider
- )
- index_path = self._get_index_path(index_hash)
- with _hold_faiss_write_lock(self.username, str(index_path)):
+ with self._collection_transaction_lock(collection_id):
return self._index_document_locked(
document_id, collection_id, force_reindex
)
@@ -2224,6 +2407,20 @@ class LibraryRAGService:
if not document:
return {"status": "error", "error": "Document not found"}
+ # A service may have been constructed before a complete rebuild
+ # published a different model. Check under the collection lock,
+ # before membership changes, empty-document purges or embedding.
+ collection = session.get(Collection, collection_id)
+ if (
+ collection is not None
+ and collection.embedding_model is not None
+ and not self._matches_collection_configuration(collection)
+ ):
+ return {
+ "status": "error",
+ "error": "Collection configuration changed; retry indexing",
+ }
+
# Get or create DocumentCollection entry
doc_collection = ensure_in_collection(
session, document_id, collection_id
@@ -2893,6 +3090,16 @@ class LibraryRAGService:
def remove_document_from_rag(
self, document_id: str, collection_id: str
+ ) -> Dict[str, Any]:
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ return self._remove_document_from_rag_locked(
+ document_id, collection_id
+ )
+
+ def _remove_document_from_rag_locked(
+ self, document_id: str, collection_id: str
) -> Dict[str, Any]:
"""
Remove a document's chunks from RAG for a specific collection.
@@ -3048,6 +3255,16 @@ class LibraryRAGService:
def purge_document_chunks(
self, document_id: str, collection_id: str
+ ) -> int:
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ return self._purge_document_chunks_locked(
+ document_id, collection_id
+ )
+
+ def _purge_document_chunks_locked(
+ self, document_id: str, collection_id: str
) -> int:
"""Delete a document's chunk rows from a collection's RAG store
WITHOUT requiring the ``DocumentCollection`` join row to still exist.
@@ -3074,6 +3291,16 @@ class LibraryRAGService:
def purge_document_vectors(
self, document_id: str, collection_id: str
+ ) -> int:
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ return self._purge_document_vectors_locked(
+ document_id, collection_id
+ )
+
+ def _purge_document_vectors_locked(
+ self, document_id: str, collection_id: str
) -> int:
"""Remove a deleted document's chunk vectors from the collection's
vector store.
@@ -3303,6 +3530,52 @@ class LibraryRAGService:
return results
+ def rebuild_collection(
+ self,
+ doc_info,
+ collection_id,
+ *,
+ max_workers=4,
+ progress_callback=None,
+ is_cancelled=None,
+ ):
+ """Replace the complete collection only after every document is ready."""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ raise RuntimeError(scope_error["error"])
+
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="rebuild"
+ ):
+ with CollectionRebuild(
+ self,
+ collection_id,
+ doc_info,
+ session_factory=lambda: get_user_db_session(
+ self.username, self.db_password
+ ),
+ ) as rebuild:
+ aggregate = self.index_documents_parallel(
+ doc_info,
+ collection_id,
+ force_reindex=True,
+ max_workers=max_workers,
+ progress_callback=progress_callback,
+ is_cancelled=is_cancelled,
+ _rebuild=rebuild,
+ )
+ if aggregate["cancelled"]:
+ return aggregate
+ if aggregate["failed"]:
+ raise RuntimeError(
+ "Collection rebuild failed; the previous index was preserved"
+ )
+ try:
+ rebuild.publish(is_cancelled)
+ except RebuildCancelled:
+ aggregate["cancelled"] = True
+ return aggregate
+
def index_documents_parallel(
self,
doc_info: List[Tuple[str, str]],
@@ -3313,6 +3586,8 @@ class LibraryRAGService:
Callable[[int, int, str, str], None]
] = None,
is_cancelled: Optional[Callable[[], bool]] = None,
+ *,
+ _rebuild: CollectionRebuild | None = None,
) -> Dict[str, Any]:
"""
Index many documents concurrently with bounded fan-out.
@@ -3457,6 +3732,8 @@ class LibraryRAGService:
def _run_one(doc_id: str) -> Dict[str, Any]:
"""Single-doc worker — never raises; returns a status dict."""
try:
+ if _rebuild is not None:
+ return _rebuild.prepare(doc_id, is_cancelled)
# Three seams tell us to bypass the prepared/serialized
# pipeline and call the per-doc method directly:
#
@@ -3622,7 +3899,11 @@ class LibraryRAGService:
if status == "prepared" and isinstance(
prepared, _PreparedDocument
):
- result = self._write_prepared_document(prepared)
+ result = (
+ _rebuild.write(prepared)
+ if _rebuild is not None
+ else self._write_prepared_document(prepared)
+ )
status = result.get("status", "error")
results[doc_id] = result
if status == "success":
@@ -4021,6 +4302,22 @@ class LibraryRAGService:
collection_id: str,
*,
chunk_ids_by_document: Optional[Dict[str, List[int]]] = None,
+ ) -> int:
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ return self._remove_documents_from_index_locked(
+ document_ids,
+ collection_id,
+ chunk_ids_by_document=chunk_ids_by_document,
+ )
+
+ def _remove_documents_from_index_locked(
+ self,
+ document_ids: List[str],
+ collection_id: str,
+ *,
+ chunk_ids_by_document: Optional[Dict[str, List[int]]] = None,
) -> int:
"""Delete given documents' vectors from a collection's vector store.
diff --git a/src/local_deep_research/research_library/services/rag_service_factory.py b/src/local_deep_research/research_library/services/rag_service_factory.py
index dc7fba2913..904e35a03c 100644
--- a/src/local_deep_research/research_library/services/rag_service_factory.py
+++ b/src/local_deep_research/research_library/services/rag_service_factory.py
@@ -27,7 +27,10 @@ from ...database.models.library import Collection
from ...database.session_context import get_user_db_session
from ...utilities.db_utils import get_settings_manager
from ...utilities.type_utils import to_bool
-from ..services.library_rag_service import LibraryRAGService
+from ..services.library_rag_service import (
+ LibraryRAGService,
+ resolve_collection_index_settings,
+)
def _get_default_text_separators(settings):
@@ -236,52 +239,34 @@ def get_rag_service(
f"Using stored settings for collection {collection_id}: "
f"{collection.embedding_model_type.value if collection.embedding_model_type else 'unknown'}/{collection.embedding_model}"
)
+ # Stored values win; NULL columns (normalize_vectors may also
+ # be stored as a string) take the current settings. The
+ # service's configuration check resolves them the same way.
+ stored_settings = resolve_collection_index_settings(
+ collection,
+ {
+ "embedding_provider": default_embedding_provider,
+ "chunk_size": default_chunk_size,
+ "chunk_overlap": default_chunk_overlap,
+ "splitter_type": default_splitter_type,
+ "text_separators": default_text_separators,
+ "distance_metric": default_distance_metric,
+ "normalize_vectors": default_normalize_vectors,
+ "index_type": default_index_type,
+ },
+ )
# Egress policy pre-flight (R9-07 / plan landmine #3):
# block before any chunk is generated when the stored
# provider conflicts with require_local. Critical for
# collections indexed pre-policy-rollout with OpenAI.
- effective_provider = (
- collection.embedding_model_type.value
- if collection.embedding_model_type
- else default_embedding_provider
- )
_enforce_embeddings_policy(
- effective_provider, settings, username
+ stored_settings["embedding_provider"], settings, username
)
- # Handle normalize_vectors - may be stored as string in some
- # cases
- coll_normalize = collection.normalize_vectors
- if coll_normalize is not None:
- coll_normalize = to_bool(coll_normalize)
- else:
- coll_normalize = default_normalize_vectors
-
- def _col(stored, default):
- """Use stored collection value if not None, else default."""
- return stored if stored is not None else default
-
return LibraryRAGService(
username=username,
embedding_model=collection.embedding_model,
- embedding_provider=collection.embedding_model_type.value
- if collection.embedding_model_type
- else default_embedding_provider,
- chunk_size=_col(collection.chunk_size, default_chunk_size),
- chunk_overlap=_col(
- collection.chunk_overlap, default_chunk_overlap
- ),
- splitter_type=_col(
- collection.splitter_type, default_splitter_type
- ),
- text_separators=_col(
- collection.text_separators, default_text_separators
- ),
- distance_metric=_col(
- collection.distance_metric, default_distance_metric
- ),
- normalize_vectors=coll_normalize,
- index_type=_col(collection.index_type, default_index_type),
+ **stored_settings,
db_password=db_password,
)
if collection:
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 43b63cae0c..cceb64de47 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -1264,7 +1264,7 @@ def index_all(
POST, not GET, because it mutates: it resolves the caller's collection,
writes embedding metadata, and runs the embedding/index pipeline over
- every document in it (``?force_reindex=true`` discards and rebuilds
+ every document in it (``?force_reindex=true`` stages and replaces
vectors that already exist). CSRFMiddleware keys enforcement on the
method, so declaring it here is what puts it behind the token check —
a GET would be outside the middleware entirely and startable from
@@ -1290,6 +1290,11 @@ def index_all(
if not collection_id:
collection_id = get_default_library_id(username)
+ if force_reindex:
+ # A replacement is one transaction for the complete collection. Use
+ # the heartbeat-capable stream instead of publishing batch by batch.
+ return index_collection(request, collection_id, username)
+
logger.info(
f"Starting index-all for collection_id: {_log_value_preview(collection_id)}, force_reindex: {force_reindex}"
)
@@ -1301,15 +1306,11 @@ def index_all(
request, username, collection_id, use_defaults=force_reindex
)
- # Imported here, before the settings snapshot is read and the SSE
- # generator is built, rather than inside its try: if the import itself
- # failed there, evaluating the ``except RemoteVectorStoreDropError``
- # clause would raise UnboundLocalError and skip the catch-all error
- # frame. Kept out of the module's top-level imports because it pulls in
- # the deletion package.
+ # Import before building the SSE generator. Importing inside its try
+ # would leave the exception handler unbound if this import failed.
+ # Keep it below module scope because it pulls in the deletion package.
from ...research_library.deletion.utils.cascade_helper import (
RemoteVectorStoreDropError,
- read_vector_cleanup_settings_snapshot,
remote_drop_failure_message,
)
@@ -1317,16 +1318,6 @@ def index_all(
with get_user_db_session(username) as db_session:
settings = get_settings_manager(db_session, username)
batch_size = int(settings.get_setting("rag.indexing_batch_size", 15))
- # The force-reindex reset needs the user's settings snapshot to
- # resolve their vector-store provider and its connection config
- # (#5765); captured here, not inside the generator's worker threads.
- # Read strictly: a defaults-only fallback would silently resolve the
- # global default provider (see read_vector_cleanup_settings_snapshot).
- reset_settings_snapshot = (
- read_vector_cleanup_settings_snapshot(settings)
- if force_reindex
- else None
- )
try:
_max_workers = int(
settings.get_setting("rag.indexing_max_parallel_docs", 4)
@@ -1372,30 +1363,13 @@ def index_all(
if not collection:
collection_found = False
else:
- # Persist the new embedding config AND reset the old
- # chunks/RAGIndex in ONE transaction. Two separate commits
- # would leave a crash window where the Collection carries
- # the NEW embedding config while the OLD RAGIndex row +
- # FAISS file (built with the old config) still exist — a
- # config/index mismatch.
- changed = False
- faiss_reset_paths = []
- if collection.embedding_model is None or force_reindex:
+ # Ordinary indexing records its initial configuration.
+ # Forced rebuilds publish metadata with the new generation.
+ if collection.embedding_model is None and not force_reindex:
_store_collection_embedding_metadata(
collection, rag_service
)
- changed = True
- if force_reindex:
- faiss_reset_paths = _reset_collection_for_reindex(
- db_session,
- collection_id,
- username,
- settings_snapshot=reset_settings_snapshot,
- )
- changed = True
- if changed:
db_session.commit()
- _unlink_reindex_faiss_files(faiss_reset_paths)
doc_info = [
(doc.id, doc.title)
@@ -3016,6 +2990,21 @@ def _upload_to_collection_sync(
# web/routers/library_search.py
+def _collection_rebuild_info(collection, index):
+ """Report durable rebuild state, independently of expiring task rows."""
+ pending = collection.rebuild_pending_since if collection else None
+ updated = index.last_updated_at if index else None
+ return {
+ "rebuild_pending_since": pending.isoformat()
+ if isinstance(pending, datetime)
+ else None,
+ "has_published_index": index is not None,
+ "index_last_updated_at": updated.isoformat()
+ if isinstance(updated, datetime)
+ else None,
+ }
+
+
@router.get("/api/collections/{collection_id}/documents")
def get_collection_documents(
request: Request,
@@ -3158,7 +3147,7 @@ def get_collection_documents(
collection_name = f"collection_{collection_id}"
rag_index = (
db_session.query(RAGIndex)
- .filter_by(collection_name=collection_name)
+ .filter_by(collection_name=collection_name, is_current=True)
.first()
)
if rag_index and rag_index.index_path:
@@ -3179,6 +3168,7 @@ def get_collection_documents(
return {
"success": True,
"collection": {
+ **_collection_rebuild_info(collection, rag_index),
"id": collection.id,
"name": collection.name,
"description": collection.description,
@@ -3290,7 +3280,8 @@ def _unregister_background_indexer(username, collection_id, task_id):
def _store_collection_embedding_metadata(collection, rag_service):
"""Persist the embedding/index configuration used to index a collection.
- Run on first index or force-reindex. Includes the embedding dimension,
+ Run on first incremental index. Forced rebuilds publish their metadata
+ together with the replacement index. Includes the embedding dimension,
probed by embedding a test string (the same way LibraryRAGService derives
it for the RAGIndex row). Previously this read
``embedding_manager.provider.embedding_dimension``, an attribute the real
@@ -3329,103 +3320,6 @@ def _store_collection_embedding_metadata(collection, rag_service):
)
-def _reset_collection_for_reindex(
- db_session, collection_id, username=None, settings_snapshot=None
-):
- """Clear old chunks, vector indices, and indexed-state before a force rebuild.
-
- Prevents mixed-model vectors / stale chunks when re-indexing (e.g. if a
- previous run was cancelled midway). Shared so a force-reindex behaves the
- same whether started via the SSE route or the background worker. Does not
- commit — the caller owns the transaction.
-
- Returns the list of on-disk FAISS index paths to unlink AFTER the caller
- commits. The RAGIndex ROWS are deleted in this transaction, but the files
- must NOT be removed before the commit that could still roll back — a
- rollback would restore the rows while the files were already gone, leaving
- the collection pointing at missing indices (mirrors collection deletion).
-
- ``username`` is required when the configured vector store is server-backed:
- the helper drops that collection remotely (before the RAGIndex rows are
- deleted, while ``index_hash`` still exists — see #5765) and derives its name
- from the username. Empty for local-file stores, which is why it defaults to
- None. A failed remote drop raises RemoteVectorStoreDropError, aborting the
- reindex rather than rebuilding on top of stale vectors.
-
- ``settings_snapshot`` is the user's settings snapshot, captured by the
- caller on the request thread (the background worker must not build one
- itself). Production callers MUST pass it: it selects the user's
- vector-store provider and carries its connection config; without it the
- helper falls back to the global default provider (FAISS).
- """
- # Import stays function-local: hoisting it would pull in the whole
- # deletion package (deletion/__init__ imports its services) at
- # route-module import time for a path only exercised on force-reindex.
- from ...research_library.deletion.utils.cascade_helper import (
- CascadeHelper,
- )
-
- collection_name = f"collection_{collection_id}"
-
- # Delete all old document chunks from DB
- deleted_chunks = CascadeHelper.delete_collection_chunks(
- db_session, collection_name
- )
- logger.info(
- f"Cleared {deleted_chunks} old chunks for collection {collection_id}"
- )
-
- # Delete old RAGIndex records (DB only). Files unlinked by the caller after
- # commit (see docstring). RagDocumentStatus cascade-deletes via FK.
- rag_result = CascadeHelper.delete_rag_indices_for_collection(
- db_session,
- collection_name,
- unlink_files=False,
- username=username,
- settings_snapshot=settings_snapshot,
- )
- logger.info(
- f"Cleared old RAG indices for collection {collection_id}: {rag_result}"
- )
-
- # Mark all documents as unindexed
- db_session.query(DocumentCollection).filter_by(
- collection_id=collection_id
- ).update(
- {
- DocumentCollection.indexed: False,
- DocumentCollection.chunk_count: 0,
- }
- )
- logger.info(f"Reset indexing state for collection {collection_id}")
- return rag_result["index_paths"]
-
-
-def _unlink_reindex_faiss_files(index_paths):
- """Unlink FAISS index files returned by _reset_collection_for_reindex, AFTER
- the caller's DB commit. Best-effort: the DB delete is already durable."""
- if not index_paths:
- return
- from ...research_library.deletion.utils.cascade_helper import (
- CascadeHelper,
- )
- from ...config.paths import get_cache_directory
-
- # NOTE: allowed_root is the COARSE shared rag_indices/ root, not the
- # tighter per-user rag_indices/<sha256(user)>/ subdir. It cannot be
- # narrowed to the per-user subdir without risking refused deletes:
- # pre-per-user-scoping (legacy) indexes live DIRECTLY in this shared
- # root (see library_rag_service._migrate_legacy_index_files), so a
- # per-user allowed_root would reject a legacy-layout RAGIndex.index_path
- # and orphan its files. The containment check still blocks symlink /
- # ancestor escapes outside rag_indices/ entirely.
- rag_indices_root = get_cache_directory() / "rag_indices"
- for path in index_paths:
- CascadeHelper.delete_faiss_index_files(
- path, allowed_root=rag_indices_root
- )
-
-
def _query_documents_to_index(db_session, collection_id, force_reindex):
"""Return the ``(DocumentCollection, Document)`` pairs to index.
@@ -3463,9 +3357,10 @@ def index_collection(
"""Index all documents in a collection with Server-Sent Events progress.
POST, not GET, because it mutates — same reasoning as index-all:
- it writes embedding metadata and runs the embedding/index pipeline
- over every document in the collection (``?force_reindex=true``
- discards and rebuilds vectors that already exist), and
+ a first index writes embedding metadata, and it runs the
+ embedding/index pipeline over every document in the collection
+ (``?force_reindex=true`` stages a complete replacement and publishes
+ it in one transaction, keeping the existing vectors until then), and
CSRFMiddleware keys enforcement on the method, so the verb is what
puts it behind the token check. A GET would sit outside the
middleware entirely and be startable from same-site markup riding
@@ -3501,15 +3396,11 @@ def index_collection(
f"RAG service created: provider={rag_service.embedding_provider}"
)
- # Imported here, before the settings snapshot is read and the SSE
- # generator is built, rather than inside its try: if the import itself
- # failed there, evaluating the ``except RemoteVectorStoreDropError``
- # clause would raise UnboundLocalError and skip the catch-all error
- # frame. Kept out of the module's top-level imports because it pulls in
- # the deletion package.
+ # Import before building the SSE generator. Importing inside its try
+ # would leave the exception handler unbound if this import failed.
+ # Keep it below module scope because it pulls in the deletion package.
from ...research_library.deletion.utils.cascade_helper import (
RemoteVectorStoreDropError,
- read_vector_cleanup_settings_snapshot,
remote_drop_failure_message,
)
@@ -3525,13 +3416,6 @@ def index_collection(
raise
except Exception:
_max_workers = 4
- # See index_all: the force-reindex reset needs the user's settings
- # snapshot to resolve their vector-store provider (#5765).
- reset_settings_snapshot = (
- read_vector_cleanup_settings_snapshot(_settings)
- if force_reindex
- else None
- )
_max_workers = max(1, min(_max_workers, 16))
def generate():
@@ -3568,29 +3452,13 @@ def index_collection(
collection_found = False
else:
collection_name = collection.name
- # Store embedding metadata AND reset the old index in ONE
- # commit (prevents stale / mixed-model vectors). Committing
- # the config write separately from the reset leaves a window
- # where a crash keeps the new config but the old vectors
- # survive.
- changed = False
- faiss_reset_paths = []
- if collection.embedding_model is None or force_reindex:
+ # Keep the published configuration during a rebuild.
+ # Its replacement is committed with the complete new index.
+ if collection.embedding_model is None and not force_reindex:
_store_collection_embedding_metadata(
collection, rag_service
)
- changed = True
- if force_reindex:
- faiss_reset_paths = _reset_collection_for_reindex(
- db_session,
- collection_id,
- username,
- settings_snapshot=reset_settings_snapshot,
- )
- changed = True
- if changed:
db_session.commit()
- _unlink_reindex_faiss_files(faiss_reset_paths)
# Snapshot (id, display name) for each document to index.
doc_info = [
@@ -3604,7 +3472,7 @@ def index_collection(
yield f"data: {json.dumps({'type': 'error', 'error': 'Collection not found'})}\n\n"
return
- if not doc_info:
+ if not doc_info and not force_reindex:
logger.info("No documents to index in collection")
yield f"data: {json.dumps({'type': 'complete', 'results': {'successful': 0, 'skipped': 0, 'failed': 0, 'message': 'No documents to index'}})}\n\n"
return
@@ -3660,10 +3528,14 @@ def index_collection(
# in-flight workers before returning so no worker
# outlives the helper return — see ``index_documents_parallel`` for the
# rationale.
- aggregate = rag_service.index_documents_parallel(
+ index_documents = (
+ rag_service.rebuild_collection
+ if force_reindex
+ else rag_service.index_documents_parallel
+ )
+ aggregate = index_documents(
doc_info,
collection_id,
- force_reindex=force_reindex,
max_workers=_max_workers,
progress_callback=_on_progress,
is_cancelled=_sse_cancel.is_set,
@@ -4072,6 +3944,8 @@ _SAFE_INDEXING_ERRORS = frozenset(
"Document not found in collection",
"Document has no text content",
"Document deleted during indexing",
+ "Document changed; retry indexing",
+ "Collection configuration changed; retry indexing",
}
)
_EMPTY_VECTOR_STORE_REASON = (
@@ -4080,6 +3954,11 @@ _EMPTY_VECTOR_STORE_REASON = (
)
_COLLECTION_NOT_FOUND = "Collection not found"
_REMOTE_DROP_OUTCOME = "indexing was aborted"
+# Appended when a cancel arrived after a rebuild began publishing.
+_LATE_CANCEL_NOTE = (
+ "The cancel request arrived after the rebuild began publishing, "
+ "so the new index is in use."
+)
# Codes for ``metadata_json["failure"]``. The indexing worker records one next
# to an ``error_message`` it built only from fixed phrases and counts, and the
# status endpoint rebuilds that message from the record instead of serving the
@@ -4295,9 +4174,9 @@ def _background_index_worker(
:func:`get_settings_manager` safely (#3453, pre-commit hook
``check-settings-manager-thread-safety``).
- ``settings_snapshot`` is likewise captured by the route before the thread
- starts; a force-reindex hands it to the reset so the user's vector-store
- provider (and its connection config) is resolved (#5765).
+ ``settings_snapshot`` remains accepted for caller compatibility. Staged
+ rebuilds currently require exclusively local-file vector-store providers;
+ remote providers need a separate atomic publication protocol.
"""
from ...database.session_context import get_user_db_session
from ...research_library.deletion.utils.cascade_helper import (
@@ -4329,27 +4208,13 @@ def _background_index_worker(
)
return
- # Store embedding metadata AND reset the old index in ONE commit,
- # so a crash between them can't leave the new config committed
- # while the old (stale/mixed-model) vectors survive.
- changed = False
- faiss_reset_paths = []
- if collection.embedding_model is None or force_reindex:
+ # A rebuild retains the published configuration until its
+ # complete replacement can be committed atomically.
+ if collection.embedding_model is None and not force_reindex:
_store_collection_embedding_metadata(
collection, rag_service
)
- changed = True
- if force_reindex:
- faiss_reset_paths = _reset_collection_for_reindex(
- db_session,
- collection_id,
- username,
- settings_snapshot=settings_snapshot,
- )
- changed = True
- if changed:
db_session.commit()
- _unlink_reindex_faiss_files(faiss_reset_paths)
# Keep only scalar values after the setup scope exits. The
# parallel coordinator owns its per-document write scopes.
@@ -4360,7 +4225,7 @@ def _background_index_worker(
)
]
- if not doc_info:
+ if not doc_info and not force_reindex:
_update_task_status(
username,
db_password,
@@ -4408,10 +4273,14 @@ def _background_index_worker(
def _is_cancelled() -> bool:
return _is_task_cancelled(username, db_password, task_id)
- aggregate = rag_service.index_documents_parallel(
+ index_documents = (
+ rag_service.rebuild_collection
+ if force_reindex
+ else rag_service.index_documents_parallel
+ )
+ aggregate = index_documents(
doc_info,
collection_id,
- force_reindex=force_reindex,
max_workers=_max_workers,
progress_callback=_on_progress,
is_cancelled=_is_cancelled,
@@ -4519,6 +4388,7 @@ def _background_index_worker(
"reconciliation_reason": sanitized_reason,
"errors": _sanitized_indexing_errors(results),
},
+ published_rebuild=force_reindex,
)
return
durable_documents = reconciliation["indexed_documents"]
@@ -4552,6 +4422,8 @@ def _background_index_worker(
else None
),
result_metadata=task_result,
+ # A forced rebuild only gets here after it has published.
+ published_rebuild=force_reindex,
)
logger.info(
f"Background indexing task {task_id} completed: {results}"
@@ -4620,6 +4492,7 @@ def _do_update_task_status(
error_message: str = None,
result_metadata: dict = None,
failure: Optional[dict] = None,
+ published_rebuild: bool = False,
):
"""Perform the task-status update under a tenacity-managed retry loop.
@@ -4631,17 +4504,43 @@ def _do_update_task_status(
``result_metadata`` is stored as ``metadata_json["result"]`` and
``failure`` as ``metadata_json["failure"]`` (see
``_client_task_failure_message``).
+
+ ``published_rebuild`` marks the final update of a forced rebuild whose
+ replacement index has been committed. Only that update may replace
+ ``cancelled``: a cancel that arrives after publication starts cannot
+ stop it, and ``cancelled`` would report the previous index as kept.
"""
from ...database.session_context import get_user_db_session
with get_user_db_session(username, db_password) as db_session:
- task = db_session.query(TaskMetadata).filter_by(task_id=task_id).first()
+ task_query = db_session.query(TaskMetadata).filter_by(task_id=task_id)
+ # Serialize the guard and update across cancellation and worker
+ # connections. A SELECT alone does not start SQLite's deferred write
+ # transaction, and a nested cancellation scope may cache an old row.
+ task_query.update(
+ {TaskMetadata.task_id: TaskMetadata.task_id},
+ synchronize_session=False,
+ )
+ task = task_query.first()
if task:
- # Preserve terminal states: once cancelled or failed, only
+ db_session.refresh(task)
+ if (
+ published_rebuild
+ and task.status == "cancelled"
+ and status in ("completed", "failed")
+ ):
+ progress_message = " ".join(
+ filter(None, (progress_message, _LATE_CANCEL_NOTE))
+ )
+ # Preserve terminal states: once completed, cancelled or failed, only
# updates confirming that same state are allowed.
- if task.status in ("cancelled", "failed") and status != task.status:
+ elif task.status in ("completed", "cancelled", "failed") and (
+ status != task.status
+ ):
+ db_session.commit()
return
- if status == "completed" and task.status != "processing":
+ elif status == "completed" and task.status != "processing":
+ db_session.commit()
return
if status is not None:
task.status = status
@@ -4668,7 +4567,7 @@ def _do_update_task_status(
if failure is not None:
metadata["failure"] = failure
task.metadata_json = metadata
- db_session.commit()
+ db_session.commit()
def _update_task_status(
@@ -4682,6 +4581,7 @@ def _update_task_status(
error_message: str = None,
result_metadata: dict = None,
failure: Optional[dict] = None,
+ published_rebuild: bool = False,
):
"""Update task metadata in the database."""
try:
@@ -4696,6 +4596,7 @@ def _update_task_status(
error_message=error_message,
result_metadata=result_metadata,
failure=failure,
+ published_rebuild=published_rebuild,
)
except Exception:
logger.exception(f"Failed to update task status for {task_id}")
@@ -4791,14 +4692,15 @@ def _start_background_index_sync(
if conflict:
return JSONResponse(conflict, status_code=409)
- # A force-reindex drops the old vector collections, which needs
- # the user's settings snapshot (provider + connection config,
- # #5765). Captured here, on the request-scoped session, because
+ # Preserve the caller's provider snapshot for force-reindex.
+ # Staged rebuilds currently refuse remote providers, but the
+ # background-worker interface still accepts this context.
+ # Captured here, on the request-scoped session, because
# the worker thread must not build one -- and BEFORE the task row
# is committed, so a failure cannot leave a stuck 'processing'
# task behind. Read strictly and not swallowed: a defaults-only
# snapshot (or None) would silently resolve the global default
- # provider and skip a server-backed store's drop (see
+ # provider instead of the configured backend (see
# read_vector_cleanup_settings_snapshot).
from ...research_library.deletion.utils.cascade_helper import (
read_vector_cleanup_settings_snapshot,
@@ -4839,7 +4741,9 @@ def _start_background_index_sync(
started_at=datetime.now(UTC),
progress_current=0,
progress_total=0,
- progress_message="Starting indexing...",
+ progress_message="Starting collection rebuild..."
+ if force_reindex
+ else "Starting indexing...",
metadata_json={
"collection_id": collection_id,
"force_reindex": force_reindex,
@@ -4922,6 +4826,14 @@ def get_index_status(
username, session_id
)
+ # Observe admission before opening the read transaction. If the worker
+ # finishes between these reads, report active for one extra poll rather
+ # than combine an old cancelled task snapshot with a now-inactive worker.
+ with _active_sse_indexers_lock:
+ active_task_id = _active_background_indexers.get(
+ (username, str(collection_id))
+ )
+
try:
with get_user_db_session(username, db_password) as db_session:
# Find the most recent indexing task FOR THIS COLLECTION.
@@ -4959,8 +4871,20 @@ def get_index_status(
task = candidate
break
+ collection = db_session.get(Collection, collection_id)
+ index = (
+ db_session.query(RAGIndex)
+ .filter_by(
+ collection_name=f"collection_{collection_id}",
+ is_current=True,
+ )
+ .first()
+ )
+ rebuild_info = _collection_rebuild_info(collection, index)
+
if not task:
return {
+ **rebuild_info,
"status": "idle",
"collection_id": collection_id,
"message": "No indexing task for this collection",
@@ -4968,8 +4892,14 @@ def get_index_status(
task_metadata = task.metadata_json or {}
safe_result = _client_indexing_result(task_metadata.get("result"))
+ worker_active = active_task_id == task.task_id
return {
+ **rebuild_info,
"task_id": task.task_id,
+ "force_reindex": task_metadata.get("force_reindex") is True,
+ # A cancellation request can precede drain or an indivisible
+ # publication. Clients must observe the worker's final result.
+ "worker_active": worker_active,
"collection_id": collection_id,
"status": task.status,
"progress_current": task.progress_current or 0,
@@ -5090,7 +5020,7 @@ def cancel_indexing(
)
logger.info(
- f"Cancelled indexing task {task_id_to_cancel} for collection {collection_id}"
+ f"Requested cancellation of indexing task {task_id_to_cancel} for collection {collection_id}"
)
return {
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 6c9dfffed6..50c25c15f1 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -12,6 +12,10 @@ let activeIndexingPoll = null;
let progressHideTimer = null;
let progressUiGeneration = 0;
let collectionDetailsLoadId = 0;
+let latestIndexingStatus = null;
+const collectionRebuildInfo = {};
+let collectionRebuildRequestId = 0;
+let appliedCollectionRebuildRequestId = 0;
const collectionBooleanWriteStates = new WeakMap();
const confirmedCollectionBooleanState = new Map();
const collectionBooleanToggleIds = {
@@ -180,6 +184,7 @@ function updateCollectionAgentEnabled(agentEnabled) {
*/
async function loadCollectionDetails() {
const currentLoadId = ++collectionDetailsLoadId;
+ const rebuildRequestId = ++collectionRebuildRequestId;
const booleanGenerationsAtRequest = new Map(
['is_public', 'agent_enabled'].map(field => [
field,
@@ -229,6 +234,8 @@ async function loadCollectionDetails() {
// Update header
document.getElementById('collection-name').textContent = collectionData.name;
document.getElementById('collection-description').textContent = collectionData.description || '';
+ updateCollectionRebuildInfo(collectionData, rebuildRequestId);
+ renderCollectionRebuildNotice();
// Reflect the public/private (egress) flag
const publicToggle = document.getElementById('collection-is-public');
@@ -545,7 +552,10 @@ async function indexCollection(forceReindex) {
SafeLogger.log('Index Collection button clicked, force_reindex:', forceReindex);
const action = forceReindex ? 're-index' : 'index';
- if (!confirm(`${action.charAt(0).toUpperCase() + action.slice(1)} all documents in this collection?`)) {
+ const confirmation = forceReindex
+ ? 'Rebuild the index for all documents? Keep the rebuild running until it completes. Cancelling before publication keeps the previous index, if any, and its settings. Automatic indexing does not retry a cancelled rebuild.'
+ : `${action.charAt(0).toUpperCase() + action.slice(1)} all documents in this collection?`;
+ if (!confirm(confirmation)) {
return;
}
@@ -568,6 +578,7 @@ async function indexCollection(forceReindex) {
if (response.status === 409) {
// Already indexing
showCollectionError(data.error || 'Indexing is already in progress');
+ latestIndexingStatus = null;
showProgressUI();
startPolling();
} else {
@@ -579,8 +590,13 @@ async function indexCollection(forceReindex) {
SafeLogger.log('Background indexing started, task_id:', data.task_id);
// Show progress UI and start polling
+ latestIndexingStatus = { status: 'processing', force_reindex: forceReindex };
+ document.getElementById('progress-fill').style.width = '0%';
showProgressUI();
- addLogEntry('Indexing started in background...', 'info');
+ updateProgressFromStatus(latestIndexingStatus);
+ addLogEntry(forceReindex
+ ? 'Rebuilding the collection index. Cancelling before publication keeps the previous index and settings; automatic indexing does not retry this rebuild.'
+ : 'Indexing started in background...', 'info');
startPolling();
} catch (error) {
@@ -594,6 +610,7 @@ async function indexCollection(forceReindex) {
*/
async function checkAndResumeIndexing() {
const resumeUiGeneration = progressUiGeneration;
+ const rebuildRequestId = ++collectionRebuildRequestId;
try {
const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/status`);
if (resumeUiGeneration !== progressUiGeneration) return;
@@ -603,14 +620,13 @@ async function checkAndResumeIndexing() {
const data = await response.json();
if (resumeUiGeneration !== progressUiGeneration) return;
- if (data.status === 'processing') {
+ updateProgressFromStatus(data, rebuildRequestId);
+ if (data.status === 'processing' || data.worker_active === true) {
SafeLogger.log('Active indexing task found, resuming UI');
showProgressUI();
- updateProgressFromStatus(data);
startPolling();
} else if (ResearchStates.isFailed(data.status)) {
showProgressUI();
- updateProgressFromStatus(data);
renderIndexingFailure(data);
hideProgressUI({ keepVisible: true });
}
@@ -638,6 +654,56 @@ function showProgressUI() {
cancelBtn.style.display = 'inline-block';
indexBtn.disabled = true;
reindexBtn.disabled = true;
+ renderCollectionRebuildNotice();
+}
+
+/** A durable collection notice must outlive the transient progress panel. */
+function updateCollectionRebuildInfo(data, requestId) {
+ if (requestId < appliedCollectionRebuildRequestId) return;
+ const keys = ['rebuild_pending_since', 'has_published_index', 'index_last_updated_at'];
+ if (!keys.some(key => Object.hasOwn(data, key))) return;
+ appliedCollectionRebuildRequestId = requestId;
+ for (const key of keys) {
+ if (Object.hasOwn(data, key)) collectionRebuildInfo[key] = data[key];
+ }
+}
+
+function renderCollectionRebuildNotice() {
+ const notice = document.getElementById('collection-rebuild-notice');
+ if (!notice) return;
+ const state = { ...(latestIndexingStatus || {}), ...collectionRebuildInfo };
+ const rebuilding = state.force_reindex === true && (
+ state.status === 'processing' || state.worker_active === true
+ );
+ if (!rebuilding && !state.rebuild_pending_since) {
+ notice.style.display = 'none';
+ notice.textContent = '';
+ return;
+ }
+ const cancelling = rebuilding && state.status === 'cancelled';
+ const operation = cancelling
+ ? 'Cancellation requested; waiting for the rebuild to stop. If publication has started, it finishes and the new index becomes active.'
+ : rebuilding
+ ? 'Rebuilding the collection index. Keep this operation running until it completes.'
+ : 'The last collection rebuild did not complete. Run Re-Index All again to replace the index.';
+ const retained = state.has_published_index === false
+ ? ' No index has been published for this collection.'
+ : rebuilding
+ ? ' Search uses the currently published index, if any. The final result will show whether the replacement was published.'
+ : state.has_published_index === true
+ ? ' The previous index remains in use and may be outdated.'
+ : ' The published index, if any, may be outdated.';
+ const date = state.index_last_updated_at && new Date(state.index_last_updated_at);
+ const updated = date && !Number.isNaN(date.getTime())
+ ? ` Index last updated: ${date.toLocaleString()}.`
+ : '';
+ const cancellation = rebuilding && !cancelling
+ ? ' Cancelling before publication keeps the previous index, if any, and its settings.'
+ : '';
+ const message = operation + retained + updated + cancellation
+ + ' Automatic indexing can add unindexed documents, but does not retry this full rebuild.';
+ if (notice.textContent !== message) notice.textContent = message;
+ notice.style.display = 'block';
}
/**
@@ -703,6 +769,7 @@ function startPolling() {
poll.interval = setInterval(async () => {
if (activeIndexingPoll !== poll || poll.requestInFlight) return;
poll.requestInFlight = true;
+ const rebuildRequestId = ++collectionRebuildRequestId;
try {
const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/status`);
@@ -716,7 +783,7 @@ function startPolling() {
const isTerminal = (
ResearchStates.isTerminal(data.status) ||
data.status === 'idle'
- );
+ ) && data.worker_active !== true;
if (isTerminal) {
clearInterval(poll.interval);
poll.interval = null;
@@ -724,7 +791,7 @@ function startPolling() {
indexingPollInterval = null;
}
- updateProgressFromStatus(data);
+ updateProgressFromStatus(data, rebuildRequestId);
// Stop polling if indexing is done
if (isTerminal) {
@@ -733,12 +800,14 @@ function startPolling() {
hideProgressUI();
} else if (ResearchStates.isFailed(data.status)) {
// Keep visible so the user can read the failure logs
- // rendered by renderIndexingFailure; cancelled tasks
- // auto-hide after 5s (single-line warning, no logs).
+ // rendered by renderIndexingFailure. The separate
+ // collection notice survives this progress panel.
renderIndexingFailure(data);
hideProgressUI({ keepVisible: true });
} else if (ResearchStates.isCancelled(data.status)) {
- addLogEntry('Indexing was cancelled', 'warning');
+ addLogEntry(data.force_reindex === true
+ ? 'Rebuild cancelled. The previous index, if any, remains in use. Run Re-Index All again; automatic indexing does not retry it.'
+ : 'Indexing was cancelled', 'warning');
hideProgressUI();
} else {
// Terminal status that is not completed/failed/cancelled
@@ -787,17 +856,29 @@ function renderIndexingFailure(data) {
/**
* Update progress UI from status data
*/
-function updateProgressFromStatus(data) {
+function updateProgressFromStatus(data, requestId = ++collectionRebuildRequestId) {
+ latestIndexingStatus = data;
+ updateCollectionRebuildInfo(data, requestId);
+ renderCollectionRebuildNotice();
const progressFill = document.getElementById('progress-fill');
const progressText = document.getElementById('progress-text');
+ const title = document.getElementById('indexing-progress-title');
+ if (title) title.textContent = data.force_reindex === true
+ ? 'Rebuilding Collection Index' : 'Indexing Progress';
if (data.progress_total > 0) {
const percent = Math.round((data.progress_current / data.progress_total) * 100);
progressFill.style.width = percent + '%';
}
- if (data.progress_message) {
+ if (data.status === 'cancelled' && data.worker_active === true) {
+ progressText.textContent = data.force_reindex === true
+ ? 'Cancelling rebuild; waiting for active work to finish...'
+ : 'Cancelling indexing; waiting for active work to finish...';
+ } else if (data.progress_message) {
progressText.textContent = data.progress_message;
+ } else if (data.status === 'processing' && data.force_reindex === true) {
+ progressText.textContent = 'Rebuilding the collection index...';
}
}
@@ -805,7 +886,10 @@ function updateProgressFromStatus(data) {
* Cancel indexing
*/
async function cancelIndexing() {
- if (!confirm('Cancel the current indexing operation?')) {
+ const confirmation = latestIndexingStatus?.force_reindex === true
+ ? 'Cancel this rebuild? Before publication, cancelling leaves the previous index, if any, and its settings working; it may be outdated. Automatic indexing does not retry this rebuild. If publication has already started, it finishes and the new index becomes active.'
+ : 'Cancel the current indexing operation?';
+ if (!confirm(confirmation)) {
return;
}
diff --git a/src/local_deep_research/web/templates/pages/collection_details.html b/src/local_deep_research/web/templates/pages/collection_details.html
index cfe0cdff87..2c008f263c 100644
--- a/src/local_deep_research/web/templates/pages/collection_details.html
+++ b/src/local_deep_research/web/templates/pages/collection_details.html
@@ -19,6 +19,8 @@
</div>
<h1 id="collection-title"><i aria-hidden="true" class="fas fa-folder-open"></i> <span id="collection-name">Loading...</span></h1>
<p class="ldr-subtitle" id="collection-description"></p>
+ <p id="collection-rebuild-notice" class="ldr-alert ldr-alert-warning"
+ role="status" aria-live="polite" style="display: none;"></p>
</div>
<!-- Collection Actions -->
@@ -148,7 +150,7 @@
<!-- Indexing Progress -->
<div id="indexing-progress" class="ldr-rag-section" style="display: none;">
<div class="ldr-section-header">
- <h2><i aria-hidden="true" class="fas fa-spinner fa-spin" id="indexing-spinner"></i> Indexing Progress</h2>
+ <h2><i aria-hidden="true" class="fas fa-spinner fa-spin" id="indexing-spinner"></i> <span id="indexing-progress-title">Indexing Progress</span></h2>
<button id="cancel-indexing-btn" class="ldr-btn-collections ldr-btn-collections-danger" style="display: none;">
<i aria-hidden="true" class="fas fa-times"></i> Cancel Indexing
</button>
diff --git a/tests/database/test_migration_0033_collection_rebuild_notice.py b/tests/database/test_migration_0033_collection_rebuild_notice.py
new file mode 100644
index 0000000000..e830568585
--- /dev/null
+++ b/tests/database/test_migration_0033_collection_rebuild_notice.py
@@ -0,0 +1,270 @@
+"""Upgrade existing collections without inventing an unfinished rebuild."""
+
+import shutil
+from datetime import UTC, datetime
+from importlib import import_module
+
+import pytest
+from alembic import command
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from alembic.script import ScriptDirectory
+from sqlalchemy import (
+ Column,
+ ForeignKey,
+ MetaData,
+ String,
+ Table,
+ create_engine,
+ event,
+ inspect,
+ select,
+ text,
+)
+from sqlalchemy.orm import Session
+from sqlalchemy_utc import UtcDateTime
+
+from local_deep_research.database.alembic_runner import get_alembic_config
+from local_deep_research.database.models.library import Collection
+
+
+MIGRATION = import_module(
+ "local_deep_research.database.migrations.versions."
+ "0033_collection_rebuild_notice"
+)
+
+
+def _migrate(engine, revision, *, downgrade=False):
+ config = get_alembic_config(engine)
+ with engine.begin() as connection:
+ config.attributes["connection"] = connection
+ migrate = command.downgrade if downgrade else command.upgrade
+ migrate(config, revision)
+
+
+def _run_upgrade_body(engine):
+ """Exercise the revision even when the version already says 0033."""
+ with engine.begin() as connection:
+ with Operations.context(MigrationContext.configure(connection)):
+ MIGRATION.upgrade()
+
+
[email protected](scope="module")
+def database_at_0032(tmp_path_factory):
+ database = tmp_path_factory.mktemp("migration_0033") / "before.db"
+ engine = create_engine(f"sqlite:///{database}")
+ try:
+ _migrate(engine, "0032")
+ # 0001 creates tables from today's ORM. Remove only the new column
+ # to reproduce the collections table an existing 0032 DB has.
+ with engine.begin() as connection:
+ operations = Operations(MigrationContext.configure(connection))
+ with operations.batch_alter_table("collections") as batch:
+ batch.drop_column("rebuild_pending_since")
+ connection.execute(
+ text(
+ "INSERT INTO collections "
+ "(id, name, description, embedding_model, created_at, "
+ "updated_at) VALUES (:id, :name, :description, :model, "
+ ":created, :created)"
+ ),
+ {
+ "id": "existing",
+ "name": "Existing collection",
+ "description": "Retain this description",
+ "model": "previous-model",
+ "created": "2026-09-01 12:00:00",
+ },
+ )
+ assert "rebuild_pending_since" not in {
+ column["name"]
+ for column in inspect(engine).get_columns("collections")
+ }
+ finally:
+ engine.dispose()
+ return database
+
+
+def engine_at_0032(database_at_0032, tmp_path):
+ database = tmp_path / "test.db"
+ shutil.copyfile(database_at_0032, database)
+ engine = create_engine(f"sqlite:///{database}")
+ try:
+ yield engine
+ finally:
+ engine.dispose()
+
+
+def test_upgrade_existing_collection_preserves_data_without_a_warning(
+ engine_at_0032,
+):
+ engine = engine_at_0032
+ _migrate(engine, "0033")
+
+ with Session(engine) as session:
+ collection = session.get(Collection, "existing")
+ assert collection.name == "Existing collection"
+ assert collection.description == "Retain this description"
+ assert collection.embedding_model == "previous-model"
+ assert collection.rebuild_pending_since is None
+ assert collection.created_at == datetime(2026, 9, 1, 12, tzinfo=UTC)
+ pending_since = datetime(2026, 10, 18, 12, 30, tzinfo=UTC)
+ collection.rebuild_pending_since = pending_since
+ session.commit()
+
+ # Retrying both the runner and the actual migration body preserves a
+ # live notice instead of clearing it or attempting a duplicate column.
+ _migrate(engine, "0033")
+ _run_upgrade_body(engine)
+ with Session(engine) as session:
+ assert (
+ session.get(Collection, "existing").rebuild_pending_since
+ == pending_since
+ )
+
+
+def test_fresh_database_upgrade_accepts_the_orm_column_and_one_chain():
+ engine = create_engine("sqlite:///:memory:")
+ try:
+ script = ScriptDirectory.from_config(get_alembic_config(engine))
+ assert script.get_revision("0033").down_revision == "0032"
+ assert len(script.get_heads()) == 1
+ _migrate(engine, "0033")
+ _run_upgrade_body(engine)
+ with Session(engine) as session:
+ session.add(Collection(id="fresh", name="Fresh collection"))
+ session.commit()
+ assert (
+ session.get(Collection, "fresh").rebuild_pending_since is None
+ )
+ finally:
+ engine.dispose()
+
+
+def test_downgrade_preserves_collection_data_and_can_upgrade_again(
+ engine_at_0032,
+):
+ engine = engine_at_0032
+ _migrate(engine, "0033")
+ with Session(engine) as session:
+ session.get(Collection, "existing").rebuild_pending_since = datetime(
+ 2026, 10, 18, tzinfo=UTC
+ )
+ session.commit()
+
+ _migrate(engine, "0032", downgrade=True)
+ assert "rebuild_pending_since" not in {
+ column["name"] for column in inspect(engine).get_columns("collections")
+ }
+ with engine.connect() as connection:
+ assert connection.execute(
+ text(
+ "SELECT id, name, description, embedding_model FROM collections"
+ )
+ ).one() == (
+ "existing",
+ "Existing collection",
+ "Retain this description",
+ "previous-model",
+ )
+ _migrate(engine, "0033")
+ with Session(engine) as session:
+ assert session.get(Collection, "existing").rebuild_pending_since is None
+
+
+ "encrypted", [False, True], ids=["sqlite", "sqlcipher"]
+)
+def test_downgrade_preserves_dependent_rows_with_foreign_keys_enabled(
+ tmp_path, encrypted
+):
+ """Dropping the notice must not recreate and cascade-delete collections."""
+ engine_kwargs = {}
+ if encrypted:
+ from local_deep_research.database.sqlcipher_compat import (
+ get_sqlcipher_module,
+ )
+
+ engine_kwargs["module"] = get_sqlcipher_module().dbapi2
+ database = tmp_path / "foreign_keys.db"
+ engine = create_engine(f"sqlite:///{database}", **engine_kwargs)
+
+ @event.listens_for(engine, "connect")
+ def configure_connection(connection, _record):
+ cursor = connection.cursor()
+ try:
+ if encrypted:
+ cursor.execute(
+ "PRAGMA key = 'migration-test-password'"
+ ) # gitleaks:allow
+ cursor.execute("PRAGMA kdf_iter = 1000")
+ cursor.execute("PRAGMA foreign_keys=ON")
+ finally:
+ cursor.close()
+
+ metadata = MetaData()
+ collections = Table(
+ "collections",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("name", String, nullable=False),
+ Column("rebuild_pending_since", UtcDateTime(), nullable=True),
+ )
+ document_collections = Table(
+ "document_collections",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column(
+ "collection_id",
+ String,
+ ForeignKey("collections.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ )
+ try:
+ with engine.begin() as connection:
+ assert (
+ connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1
+ )
+ metadata.create_all(connection)
+ connection.execute(
+ collections.insert(),
+ {
+ "id": "existing",
+ "name": "Existing collection",
+ "rebuild_pending_since": datetime(2026, 10, 18, tzinfo=UTC),
+ },
+ )
+ connection.execute(
+ document_collections.insert(),
+ {"id": "membership", "collection_id": "existing"},
+ )
+
+ with Operations.context(MigrationContext.configure(connection)):
+ MIGRATION.downgrade()
+
+ assert "rebuild_pending_since" not in {
+ column["name"]
+ for column in inspect(connection).get_columns("collections")
+ }
+ assert connection.execute(
+ select(collections.c.id, collections.c.name)
+ ).one() == ("existing", "Existing collection")
+ assert connection.execute(
+ select(
+ document_collections.c.id,
+ document_collections.c.collection_id,
+ )
+ ).one() == ("membership", "existing")
+ assert (
+ connection.exec_driver_sql("PRAGMA foreign_keys").scalar() == 1
+ )
+ assert not connection.exec_driver_sql(
+ "PRAGMA foreign_key_check"
+ ).all()
+
+ if encrypted:
+ assert not database.read_bytes().startswith(b"SQLite format 3")
+ finally:
+ engine.dispose()
diff --git a/tests/js/collection-details-direct-runtime.test.js b/tests/js/collection-details-direct-runtime.test.js
index 7527d5c8c5..5d25826c27 100644
--- a/tests/js/collection-details-direct-runtime.test.js
+++ b/tests/js/collection-details-direct-runtime.test.js
@@ -18,6 +18,7 @@ function renderCollectionPage() {
<input id="collection-agent-enabled" type="checkbox">
<h1 id="collection-name"></h1>
<p id="collection-description"></p>
+ <p id="collection-rebuild-notice" style="display:none"></p>
<span id="stat-total-docs"></span>
<span id="stat-indexed-docs"></span>
<span id="stat-unindexed-docs"></span>
@@ -32,6 +33,7 @@ function renderCollectionPage() {
<div id="no-documents-message"></div>
<section id="notes-section"><div id="notes-list"></div></section>
<section id="indexing-progress" style="display:none">
+ <span id="indexing-progress-title"></span>
<div id="indexing-spinner"></div>
<div id="progress-fill"></div>
<div id="progress-text"></div>
@@ -64,6 +66,7 @@ function collectionPayload({ isProtected = false } = {}) {
index_type: 'flat',
normalize_vectors: false,
index_file_size: 4096,
+ has_published_index: true,
},
documents: [
{
@@ -685,6 +688,7 @@ it('starts indexing and refreshes after the terminal polling response', async ()
expect(document.getElementById('collection-name').textContent)
.toBe('Direct collection');
+ document.getElementById('progress-fill').style.width = '100%';
document.getElementById('reindex-collection-btn').click();
await vi.advanceTimersByTimeAsync(0);
const startCall = safeFetch.mock.calls.find(([url]) =>
@@ -704,7 +708,12 @@ it('starts indexing and refreshes after the terminal polling response', async ()
expect(document.getElementById('indexing-progress').style.display)
.toBe('block');
expect(document.getElementById('progress-log').textContent)
- .toContain('Indexing started in background');
+ .toContain('Rebuilding the collection index');
+ expect(document.getElementById('indexing-progress-title').textContent)
+ .toBe('Rebuilding Collection Index');
+ expect(document.getElementById('progress-fill').style.width).toBe('0%');
+ expect(document.getElementById('collection-rebuild-notice').textContent)
+ .toContain('Cancelling before publication keeps the previous index');
await vi.advanceTimersByTimeAsync(2000);
expect(statusRequests).toBe(2);
@@ -1072,3 +1081,132 @@ it('keeps document IDs out of inline handlers and delegates both action clicks',
);
expect(window.__collectionActionXss).toBeUndefined();
});
+
+it.each(['cancelled', 'completed'])('waits for cancellation to finish and renders the actual %s rebuild outcome', async outcome => {
+ vi.useFakeTimers();
+ const payload = collectionPayload();
+ const pending = '2026-10-18T08:00:00Z';
+ payload.collection.rebuild_pending_since = pending;
+ payload.collection.index_last_updated_at = '2025-01-01T00:00:00Z';
+ let statusRequests = 0;
+ const safeFetch = vi.fn(async (url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) return response(payload);
+ if (url.endsWith('/index/cancel') && options.method === 'POST') {
+ return response({ success: true });
+ }
+ if (url === INDEX_STATUS_URL) {
+ statusRequests += 1;
+ if (statusRequests < 3) return response({
+ status: 'cancelled', force_reindex: true, worker_active: true,
+ has_published_index: true, rebuild_pending_since: pending,
+ });
+ payload.collection.rebuild_pending_since = outcome === 'cancelled' ? pending : null;
+ return response({
+ status: outcome, force_reindex: true, worker_active: false,
+ has_published_index: true,
+ rebuild_pending_since: payload.collection.rebuild_pending_since,
+ progress_message: outcome === 'completed'
+ ? 'The cancel request arrived after the rebuild began publishing, so the new index is in use.'
+ : 'Cancelled before publication',
+ });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('reindex-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('collection-rebuild-notice').textContent)
+ .toContain('Cancellation requested; waiting');
+ document.getElementById('cancel-indexing-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(confirm).toHaveBeenLastCalledWith(expect.stringContaining('Automatic indexing does not retry this rebuild'));
+ expect(confirm).toHaveBeenLastCalledWith(expect.stringContaining('If publication has already started'));
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusRequests).toBe(2);
+ expect(document.getElementById('reindex-collection-btn').disabled).toBe(true);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusRequests).toBe(3);
+ expect(document.getElementById('reindex-collection-btn').disabled).toBe(false);
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(statusRequests).toBe(3);
+ expect(document.getElementById('indexing-progress').style.display).toBe('none');
+ const notice = document.getElementById('collection-rebuild-notice');
+ if (outcome === 'completed') {
+ expect(notice.style.display).toBe('none');
+ expect(document.getElementById('progress-log').textContent).toContain('new index is in use');
+ } else {
+ expect(notice.style.display).toBe('block');
+ expect(notice.textContent).toContain('previous index remains in use and may be outdated');
+ expect(notice.textContent).toContain('Index last updated:');
+ expect(notice.textContent).toContain('does not retry this full rebuild');
+ }
+});
+
+it.each([true, false])('restores an incomplete rebuild notice after reload and incremental completion (published=%s)', async published => {
+ vi.useFakeTimers();
+ const payload = collectionPayload();
+ payload.collection.rebuild_pending_since = '2026-10-18T08:00:00Z';
+ payload.collection.has_published_index = published;
+ payload.collection.index_last_updated_at = '<img src=x onerror=alert(1)>';
+ let statusRequests = 0;
+ const safeFetch = vi.fn(async (url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) return response(payload);
+ if (url === INDEX_STATUS_URL) {
+ statusRequests += 1;
+ return response({
+ status: statusRequests === 1 ? 'idle' : 'completed',
+ force_reindex: false,
+ ...payload.collection,
+ });
+ }
+ if (url.endsWith('/index/start') && options.method === 'POST') {
+ return response({ success: true, task_id: 'incremental' });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ const notice = document.getElementById('collection-rebuild-notice');
+ expect(notice.style.display).toBe('block');
+ expect(notice.textContent).toContain(published
+ ? 'previous index remains in use'
+ : 'No index has been published');
+ expect(notice.querySelector('img')).toBeNull();
+ expect(notice.textContent).not.toContain('Index last updated:');
+ document.getElementById('index-collection-btn').click();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusRequests).toBe(2);
+ expect(notice.style.display).toBe('block');
+ expect(notice.textContent).toContain('last collection rebuild did not complete');
+});
+
+it('accepts newer collection rebuild metadata after an older terminal status response', async () => {
+ vi.useFakeTimers();
+ let documentRequests = 0;
+ let statusRequests = 0;
+ const safeFetch = vi.fn(async url => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ const payload = collectionPayload();
+ documentRequests += 1;
+ payload.collection.rebuild_pending_since = documentRequests === 1
+ ? null : '2026-10-18T09:00:00Z';
+ return response(payload);
+ }
+ if (url === INDEX_STATUS_URL) {
+ statusRequests += 1;
+ return response({
+ status: statusRequests === 1 ? 'processing' : 'completed',
+ force_reindex: false, rebuild_pending_since: null,
+ has_published_index: true,
+ });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(documentRequests).toBe(2);
+ expect(document.getElementById('collection-rebuild-notice').style.display).toBe('block');
+ expect(document.getElementById('collection-rebuild-notice').textContent)
+ .toContain('last collection rebuild did not complete');
+});
diff --git a/tests/research_library/deletion/test_provider_aware_vector_cleanup.py b/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
index da298c60bb..3c5effb757 100644
--- a/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
+++ b/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
@@ -673,33 +673,22 @@ class TestProductionCallersForwardTheSettingsSnapshot:
assert [e for e in events if e[0] == "drop"] == []
- def test_force_reindex_reset_drops_the_configured_providers_collection(
- self,
- ):
- """``_reset_collection_for_reindex`` serves index_all,
- index_collection and the background worker; each passes the
- snapshot it captured on the request thread (pinned in
- tests/web/routers/test_rag_reindex_commit_then_unlink.py)."""
- from local_deep_research.web.routers.rag import (
- _reset_collection_for_reindex,
+ def test_staged_rebuild_refuses_remote_provider_before_opening_db(self):
+ """A remote drop cannot preserve the old index across rollback."""
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
)
- events, snapshots = [], []
- snapshot = _snapshot_selecting("stub_remote")
- session = _session_returning([_fake_index("hash-one")], events)
- stub = _make_remote_stub(events, snapshots=snapshots)
-
- with _registered_behind_a_setting(stub):
- paths = _reset_collection_for_reindex(
- session, "abc", "alice", settings_snapshot=snapshot
- )
+ events = []
+ session_factory = Mock(side_effect=AssertionError("DB opened"))
+ with _registered_behind_a_setting(_make_remote_stub(events)):
+ with pytest.raises(RuntimeError, match="local-file vector stores"):
+ CollectionRebuild(
+ Mock(), "abc", [], session_factory=session_factory
+ )
- assert events[:2] == [
- ("drop", "alice", "hash-one"),
- ("delete_row", "hash-one"),
- ]
- assert snapshots == [snapshot]
- assert paths == []
+ session_factory.assert_not_called()
+ assert events == []
# --------------------------------------------------------------------------- #
diff --git a/tests/research_library/routes/test_rag_indexing_helpers.py b/tests/research_library/routes/test_rag_indexing_helpers.py
index 5414791f9f..6bc9bde13f 100644
--- a/tests/research_library/routes/test_rag_indexing_helpers.py
+++ b/tests/research_library/routes/test_rag_indexing_helpers.py
@@ -8,7 +8,7 @@ collections indexed that way lost it.
"""
from types import SimpleNamespace
-from unittest.mock import Mock, patch
+from unittest.mock import Mock
from local_deep_research.database.models.library import (
DocumentCollection,
@@ -16,7 +16,6 @@ from local_deep_research.database.models.library import (
)
from local_deep_research.web.routers.rag import (
_store_collection_embedding_metadata,
- _reset_collection_for_reindex,
_query_documents_to_index,
)
@@ -159,48 +158,3 @@ class TestQueryDocumentsToIndex:
# text_content is deferred (not loaded); id is available.
assert "text_content" in sa_inspect(doc).unloaded
assert doc.id is not None
-
-
-class TestResetCollectionForReindex:
- def test_clears_chunks_indices_and_marks_unindexed(self):
- db = Mock()
- with patch(
- "local_deep_research.research_library.deletion.utils."
- "cascade_helper.CascadeHelper"
- ) as cascade:
- cascade.delete_collection_chunks.return_value = 12
- cascade.delete_rag_indices_for_collection.return_value = {
- "deleted_indices": 1,
- "deleted_files": 0,
- "index_paths": ["/idx/a", "/idx/b"],
- }
-
- paths = _reset_collection_for_reindex(db, "cid", "alice")
-
- cascade.delete_collection_chunks.assert_called_once_with(
- db, "collection_cid"
- )
- # RAGIndex ROWS are deleted in this transaction, but the on-disk
- # files are unlinked by the caller AFTER the commit — so a rollback
- # can't orphan already-deleted files. delete_rag_indices_for_collection
- # is therefore called with unlink_files=False and its index_paths
- # are returned for the post-commit unlink.
- cascade.delete_rag_indices_for_collection.assert_called_once_with(
- db,
- "collection_cid",
- unlink_files=False,
- username="alice",
- settings_snapshot=None,
- )
- assert paths == ["/idx/a", "/idx/b"]
- # Marks documents unindexed
- db.query.return_value.filter_by.return_value.update.assert_called_once()
-
- def test_does_not_commit(self):
- db = Mock()
- with patch(
- "local_deep_research.research_library.deletion.utils."
- "cascade_helper.CascadeHelper"
- ):
- _reset_collection_for_reindex(db, "cid")
- db.commit.assert_not_called()
diff --git a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
index 9a002ba071..4632d44002 100644
--- a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
+++ b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
@@ -1149,77 +1149,48 @@ class TestBackgroundIndexWorker:
for s in updated_statuses
)
- def test_background_worker_force_reindex_cleanup(self):
- """force_reindex=True triggers cascade deletion of old chunks."""
- from local_deep_research.web.routers.rag import (
- _background_index_worker,
- )
-
- mock_svc = self._make_rag_service_mock()
-
- mock_coll = Mock()
- mock_coll.embedding_model = None # Will be set during force reindex
-
- # First query() call is the Collection lookup; every subsequent call
- # (the DocumentCollection.update() inside _reset_collection_for_reindex,
- # then the DocumentCollection+Document join in
- # _query_documents_to_index) gets an empty-results query — there are
- # no docs to index, so the worker should reach a terminal state
- # without needing a real CascadeHelper.
- query_counter = {"n": 0}
-
- def query_side_effect(*models):
- query_counter["n"] += 1
- if query_counter["n"] == 1:
- return _build_mock_query(first_result=mock_coll)
- return _build_mock_query(all_result=[])
-
- db_session = _make_db_session(query_side_effect=query_side_effect)
+ def test_background_worker_delegates_even_an_empty_forced_rebuild(self):
+ from local_deep_research.web.routers.rag import _background_index_worker
- mock_cascade = Mock()
- mock_cascade.delete_collection_chunks.return_value = 5
- # index_paths is read by _reset_collection_for_reindex to return the
- # FAISS paths to unlink after commit; must be present or the route
- # raises KeyError.
- mock_cascade.delete_rag_indices_for_collection.return_value = {
- "deleted": 2,
- "index_paths": [],
+ service = self._make_rag_service_mock()
+ service.rebuild_collection.return_value = {
+ "successful": 0,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "cancelled": False,
}
-
- updated_statuses = []
-
- def fake_update(username, db_password, task_id, **kwargs):
- updated_statuses.append(kwargs)
-
+ service.reconcile_collection_index.return_value = {
+ "indexed_documents": 0,
+ "indexed_chunks": 0,
+ "live_vectors": 0,
+ "orphan_vectors": 0,
+ }
+ collection = Mock(embedding_model="old-model")
+ db = _make_db_session(
+ query_side_effect=lambda *a: _build_mock_query(
+ first_result=collection
+ )
+ )
with (
patch(
- f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
- ),
- patch(f"{_DB_CTX}.get_user_db_session") as mock_get_session,
- patch(f"{MODULE}._update_task_status", side_effect=fake_update),
- patch(
- "local_deep_research.research_library.deletion.utils"
- ".cascade_helper.CascadeHelper",
- mock_cascade,
+ f"{MODULE}._get_rag_service_for_thread", return_value=service
),
+ patch(f"{_DB_CTX}.get_user_db_session") as get_session,
+ patch(f"{MODULE}._query_documents_to_index", return_value=[]),
+ patch(f"{MODULE}._store_collection_embedding_metadata") as store,
+ patch(f"{MODULE}._update_task_status") as update,
):
- mock_get_session.return_value.__enter__ = Mock(
- return_value=db_session
- )
- mock_get_session.return_value.__exit__ = Mock(return_value=False)
+ get_session.return_value.__enter__.return_value = db
_background_index_worker(
- "task-1", "coll-1", "testuser", "pass", force_reindex=True
+ "task-1", "coll-1", "testuser", "pass", True
)
-
- # CascadeHelper methods were invoked (verifying force_reindex actually
- # ran the cleanup path) and the task reached a terminal/expected state.
- mock_cascade.delete_collection_chunks.assert_called_once()
- mock_cascade.delete_rag_indices_for_collection.assert_called_once()
- assert any(
- s.get("status") in ("completed", "failed")
- or "No documents" in (s.get("progress_message") or "")
- for s in updated_statuses
- )
+ service.rebuild_collection.assert_called_once()
+ assert service.rebuild_collection.call_args.args == ([], "coll-1")
+ service.index_documents_parallel.assert_not_called()
+ store.assert_not_called()
+ db.commit.assert_not_called()
+ assert update.call_args.kwargs["status"] == "completed"
def test_background_worker_cancellation(self):
"""Worker reports cancelled when the parallel helper reports
diff --git a/tests/research_library/routes/test_rag_routes_coverage_main_port.py b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
index 00576f6a10..0b9e3fb6e2 100644
--- a/tests/research_library/routes/test_rag_routes_coverage_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_coverage_main_port.py
@@ -2851,8 +2851,7 @@ class TestUpdateTaskStatus:
db_session.commit.assert_called_once()
def test_task_not_found(self):
- """No matching row -> nothing is committed (a commit here would be a
- write with no target and would mask the missing task)."""
+ """A missing task releases the writer claim without creating a row."""
from local_deep_research.web.routers.rag import _update_task_status
db_session = Mock()
@@ -2863,7 +2862,9 @@ class TestUpdateTaskStatus:
with _helper_session(db_session):
_update_task_status("user", "pass", "task-1", status="completed")
- db_session.commit.assert_not_called()
+ db_session.commit.assert_called_once()
+ db_session.refresh.assert_not_called()
+ db_session.add.assert_not_called()
def test_updates_error_message(self):
from local_deep_research.web.routers.rag import _update_task_status
diff --git a/tests/research_library/routes/test_rag_routes_gaps_main_port.py b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
index 75b7a7fddb..fe8a6b4a74 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
@@ -68,7 +68,7 @@ import json
import re
from contextlib import contextmanager
from types import SimpleNamespace
-from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch
+from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
@@ -1014,48 +1014,24 @@ class TestIndexCollection:
assert mock_coll.chunk_overlap == 50
db_session.commit.assert_called()
- def test_force_reindex_param(self):
- """``force_reindex=true`` re-stores embedding metadata even though a
- model was already recorded.
-
- ``_reset_collection_for_reindex`` is stubbed out here (it is covered
- directly by ``test_rag_indexing_helpers.py::
- TestResetCollectionForReindex``) so this test isolates the
- force-reindex branch of the metadata write.
- """
- mock_coll = Mock()
- mock_coll.id = "coll-1"
+ def test_force_reindex_preserves_metadata_when_replacement_fails(self):
+ mock_coll = Mock(id="coll-1", embedding_model="old-model")
mock_coll.name = "Test"
- mock_coll.embedding_model = "old-model" # Already set
-
db_session = _make_db_session(
query_side_effect=_collection_then_docs(mock_coll, docs=[])
)
- mock_rag = self._metadata_rag_service(
- embedding_model="new-model",
- embedding_provider="openai",
- chunk_size=800,
- chunk_overlap=100,
- text_separators="[]",
- distance_metric="l2",
- normalize_vectors=False,
- index_type="ivf",
- )
-
- _drive_index_collection(
+ mock_rag = self._metadata_rag_service(embedding_model="new-model")
+ mock_rag.rebuild_collection.side_effect = RuntimeError("Rebuild failed")
+ events, _ = _drive_index_collection(
db_session=db_session,
rag_service=mock_rag,
query_params={"force_reindex": "true"},
- extra_patches=[
- patch(
- f"{MODULE}._reset_collection_for_reindex", return_value=[]
- ),
- patch(f"{MODULE}._unlink_reindex_faiss_files"),
- ],
)
-
- assert mock_coll.embedding_model == "new-model"
- assert mock_coll.chunk_size == 800
+ assert events[-1]["type"] == "error"
+ mock_rag.rebuild_collection.assert_called_once()
+ mock_rag.index_documents_parallel.assert_not_called()
+ assert mock_coll.embedding_model == "old-model"
+ db_session.commit.assert_not_called()
def test_sse_response_headers(self):
"""SSE response has correct headers for streaming.
@@ -1100,44 +1076,20 @@ class TestIndexAll:
everywhere).
"""
- def test_force_reindex_stores_metadata_and_resets(self):
- mock_coll = Mock()
- mock_coll.id = "coll-1"
- mock_coll.embedding_model = None
- db_session = _make_db_session(
- query_side_effect=lambda *a: _build_mock_query(
- first_result=mock_coll
- )
- )
- mock_rag = Mock()
+ def test_force_reindex_delegates_to_the_complete_collection_stream(self):
+ from local_deep_research.web.routers.rag import index_all
+ request = _fake_request(
+ query_params={"collection_id": "coll-1", "force_reindex": "true"}
+ )
with (
- patch(
- f"{MODULE}._store_collection_embedding_metadata"
- ) as mock_store,
- patch(
- f"{MODULE}._reset_collection_for_reindex", return_value=[]
- ) as mock_reset,
- patch(f"{MODULE}._query_documents_to_index", return_value=[]),
+ patch(f"{MODULE}.index_collection") as rebuild,
+ patch(f"{MODULE}.get_rag_service") as construct,
):
- _drive_index_all(
- db_session=db_session,
- rag_service=mock_rag,
- query_params={
- "collection_id": "coll-1",
- "force_reindex": "true",
- },
- )
-
- mock_store.assert_called_once_with(mock_coll, mock_rag)
- # The reset is fed the handler's own authenticated `username`
- # parameter directly, not read back off the RAG service object.
- # The route's settings snapshot is forwarded too (it resolves the
- # vector-store provider, #5765); its exact value is pinned in
- # tests/web/routers/test_rag_reindex_commit_then_unlink.py.
- mock_reset.assert_called_once_with(
- db_session, "coll-1", USERNAME, settings_snapshot=ANY
- )
+ result = index_all(request, username=USERNAME)
+ rebuild.assert_called_once_with(request, "coll-1", USERNAME)
+ assert result is rebuild.return_value
+ construct.assert_not_called()
def test_incremental_does_not_reset(self):
"""A non-force index-all must NOT wipe existing chunks/indices."""
@@ -1150,18 +1102,17 @@ class TestIndexAll:
)
)
+ service = Mock()
with (
patch(f"{MODULE}._store_collection_embedding_metadata"),
- patch(f"{MODULE}._reset_collection_for_reindex") as mock_reset,
patch(f"{MODULE}._query_documents_to_index", return_value=[]),
):
_drive_index_all(
db_session=db_session,
- rag_service=Mock(),
+ rag_service=service,
query_params={"collection_id": "coll-1"},
)
-
- mock_reset.assert_not_called()
+ service.rebuild_collection.assert_not_called()
@pytest.mark.parametrize(
("service_error", "client_error"),
@@ -1270,7 +1221,6 @@ class TestIndexAll:
patch(
f"{MODULE}._store_collection_embedding_metadata"
) as mock_store,
- patch(f"{MODULE}._reset_collection_for_reindex") as mock_reset,
):
events, _ = _drive_index_all(
db_session=db_session,
@@ -1284,175 +1234,11 @@ class TestIndexAll:
assert not any(e.get("type") == "complete" for e in events)
mock_query_docs.assert_not_called()
mock_store.assert_not_called()
- mock_reset.assert_not_called()
-
-
-class TestCommitOnceThenUnlinkAfterCommit:
- """Ported from ``origin/main:.../test_rag_routes_gaps_coverage.py``
- ``::TestCommitOnceThenUnlinkAfterCommit``.
-
- Regression guard for the crash-window fix at all three hand-copied
- call sites that persist embedding metadata + a force-reindex reset in
- ONE commit, then unlink the returned FAISS files only AFTER that commit
- lands: index_all, index_collection, and the background worker.
-
- Unlinking before the commit would orphan the FAISS files (referenced by
- a RAGIndex row the reset already deleted) if the transaction then rolled
- back. Parametrized per-site — bundling the 3 sites into one test body
- would let a first failed assert mask failures at the other two sites.
-
- All three call sites are still hand-copied on this branch
- (``rag.py`` index_all / index_collection / ``_background_index_worker``),
- so all three parametrizations remain load-bearing.
- """
-
- _FAISS_PATHS = ["/tmp/coll-1.faiss", "/tmp/coll-1.faiss.ids"]
-
- def _crash_window_patches(self, call_order):
- def record_unlink(paths):
- call_order.append("unlink")
-
- return (
- patch(f"{MODULE}._store_collection_embedding_metadata"),
- patch(
- f"{MODULE}._reset_collection_for_reindex",
- return_value=self._FAISS_PATHS,
- ),
- patch(
- f"{MODULE}._unlink_reindex_faiss_files",
- side_effect=record_unlink,
- ),
- patch(f"{MODULE}._query_documents_to_index", return_value=[]),
- )
-
- def _run_index_all(self):
- mock_coll = Mock()
- mock_coll.id = "coll-1"
- mock_coll.embedding_model = "already-set"
- db_session = _make_db_session(
- query_side_effect=lambda *a: _build_mock_query(
- first_result=mock_coll
- )
- )
-
- call_order = []
- db_session.commit.side_effect = lambda: call_order.append("commit")
- _store, mock_reset, mock_unlink, _query = self._crash_window_patches(
- call_order
- )
- mock_rag = Mock()
- with _store, mock_reset as reset, mock_unlink as unlink, _query:
- _drive_index_all(
- db_session=db_session,
- rag_service=mock_rag,
- query_params={
- "collection_id": "coll-1",
- "force_reindex": "true",
- },
- )
- # The reset is fed the handler's own authenticated `username`
- # parameter directly, not read back off the RAG service object.
- reset.assert_called_once_with(
- db_session, "coll-1", USERNAME, settings_snapshot=ANY
- )
- unlink.assert_called_once_with(self._FAISS_PATHS)
-
- return call_order, db_session.commit.call_count
-
- def _run_index_collection(self):
- mock_coll = Mock()
- mock_coll.id = "coll-1"
- mock_coll.name = "Test"
- mock_coll.embedding_model = "already-set"
- db_session = _make_db_session(
- query_side_effect=lambda *a: _build_mock_query(
- first_result=mock_coll
- )
- )
-
- call_order = []
- db_session.commit.side_effect = lambda: call_order.append("commit")
- _store, mock_reset, mock_unlink, _query = self._crash_window_patches(
- call_order
- )
-
- mock_rag = Mock()
- with _store, mock_reset as reset, mock_unlink as unlink, _query:
- _drive_index_collection(
- db_session=db_session,
- rag_service=mock_rag,
- query_params={"force_reindex": "true"},
- )
- # See _run_index_all: the reset is fed the authenticated
- # `username` parameter directly.
- reset.assert_called_once_with(
- db_session, "coll-1", USERNAME, settings_snapshot=ANY
- )
- unlink.assert_called_once_with(self._FAISS_PATHS)
-
- return call_order, db_session.commit.call_count
-
- def _run_background_worker(self):
- from local_deep_research.web.routers.rag import (
- _background_index_worker,
- )
- mock_svc = Mock()
- mock_svc.__enter__ = Mock(return_value=mock_svc)
- mock_svc.__exit__ = Mock(return_value=False)
-
- mock_coll = Mock()
- mock_coll.id = "coll-1"
- mock_coll.embedding_model = "already-set"
-
- db_session = _make_db_session(
- query_side_effect=lambda *a: _build_mock_query(
- first_result=mock_coll
- )
- )
-
- call_order = []
- db_session.commit.side_effect = lambda: call_order.append("commit")
- _store, mock_reset, mock_unlink, _query = self._crash_window_patches(
- call_order
- )
-
- with (
- _user_db_session(db_session),
- patch(
- f"{MODULE}._get_rag_service_for_thread", return_value=mock_svc
- ),
- patch(f"{MODULE}._update_task_status"),
- _store,
- mock_reset as reset,
- mock_unlink as unlink,
- _query,
- ):
- _background_index_worker(
- "task-1", "coll-1", USERNAME, "pass", force_reindex=True
- )
- # See _run_index_all: the reset is fed the authenticated
- # `username` parameter directly.
- # Called without a snapshot, the worker forwards None.
- reset.assert_called_once_with(
- db_session, "coll-1", USERNAME, settings_snapshot=None
- )
- unlink.assert_called_once_with(self._FAISS_PATHS)
-
- return call_order, db_session.commit.call_count
-
- @pytest.mark.parametrize(
- "runner_name",
- ["_run_index_all", "_run_index_collection", "_run_background_worker"],
- ids=["index_all", "index_collection", "background_worker"],
- )
- def test_commit_once_then_unlink_after_commit(self, runner_name):
- call_order, commit_call_count = getattr(self, runner_name)()
- # The commit must precede the unlink — never the reverse — and must
- # happen exactly once (not once per helper call).
- assert call_order == ["commit", "unlink"]
- assert commit_call_count == 1
+# Publication commit/unlink ordering is checked against real SQLite and FAISS
+# in services/test_collection_rebuild.py. Route delegation is covered in
+# web/routers/test_rag_reindex_commit_then_unlink.py.
class TestClearedStatusIsSkippedNotFailed:
@@ -1504,7 +1290,6 @@ class TestClearedStatusIsSkippedNotFailed:
with (
patch(f"{MODULE}._store_collection_embedding_metadata"),
- patch(f"{MODULE}._reset_collection_for_reindex", return_value=[]),
patch(
f"{MODULE}._query_documents_to_index",
return_value=[(Mock(), Mock(id="doc-1", title="t"))],
diff --git a/tests/research_library/services/test_collection_lock_identity.py b/tests/research_library/services/test_collection_lock_identity.py
new file mode 100644
index 0000000000..e83a4fba63
--- /dev/null
+++ b/tests/research_library/services/test_collection_lock_identity.py
@@ -0,0 +1,266 @@
+"""Logical collection locks stay independent of filesystem path semantics."""
+
+import os
+import threading
+from uuid import uuid4
+
+import pytest
+
+from local_deep_research.research_library.services import (
+ library_rag_service as rag,
+)
+
+
+def lock_users():
+ # Do not clear the shared registry: unrelated workers may own its locks.
+ prefix = f"collection-lock-test-{uuid4().hex}"
+ users = (f"{prefix}-owner", f"{prefix}-other")
+ try:
+ yield users
+ finally:
+ for username in users:
+ rag.pop_faiss_locks_for_user(username)
+
+
[email protected]("purpose", ["transaction", "rebuild"])
+def test_collection_locks_never_resolve_ids_as_filesystem_paths(
+ monkeypatch, lock_users, purpose
+):
+ def refuse_filesystem_resolution(*_args, **_kwargs):
+ raise AssertionError("Collection IDs must not reach Path.resolve")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(rag.Path, "resolve", refuse_filesystem_resolution)
+ lock = rag._get_collection_lock(
+ lock_users[0], "C:\\collection:opaque/../id", purpose=purpose
+ )
+ with rag._hold_collection_lock(
+ lock_users[0], "C:\\collection:opaque/../id", purpose=purpose
+ ) as held:
+ assert held is lock
+ assert held.locked()
+ assert not lock.locked()
+
+
+def test_pathlike_collection_ids_stay_distinct_and_ignore_working_directory(
+ tmp_path, monkeypatch, lock_users
+):
+ identifiers = (
+ "collection",
+ "./collection",
+ "folder/../collection",
+ "collection/",
+ "/collection",
+ "C:\\folder\\..\\collection",
+ )
+ first_directory = tmp_path / "first"
+ second_directory = tmp_path / "second"
+ first_directory.mkdir()
+ second_directory.mkdir()
+ monkeypatch.chdir(first_directory)
+ locks = [
+ rag._get_collection_lock(lock_users[0], name, purpose="transaction")
+ for name in identifiers
+ ]
+ assert len({id(lock) for lock in locks}) == len(identifiers)
+
+ monkeypatch.chdir(second_directory)
+ for name, expected in zip(identifiers, locks, strict=True):
+ assert (
+ rag._get_collection_lock(lock_users[0], name, purpose="transaction")
+ is expected
+ )
+
+
+def test_collection_locks_separate_users_purposes_and_physical_paths(
+ tmp_path, lock_users
+):
+ identifier = str(tmp_path / "collection")
+ locks = (
+ rag._get_collection_lock(
+ lock_users[0], identifier, purpose="transaction"
+ ),
+ rag._get_collection_lock(lock_users[0], identifier, purpose="rebuild"),
+ rag._get_collection_lock(
+ lock_users[1], identifier, purpose="transaction"
+ ),
+ rag._get_faiss_write_lock(lock_users[0], identifier),
+ )
+ assert len({id(lock) for lock in locks}) == len(locks)
+
+
[email protected]("purpose", ["transaction", "rebuild"])
+def test_other_thread_is_excluded_until_collection_lock_is_released(
+ monkeypatch, lock_users, purpose
+):
+ attempted = threading.Event()
+ blocking_attempted = threading.Event()
+ entered = threading.Event()
+ release_worker = threading.Event()
+ nonblocking_results = []
+ errors = []
+
+ def contender():
+ try:
+ with rag._hold_collection_lock(
+ lock_users[0], "collection", purpose=purpose, blocking=False
+ ) as available:
+ nonblocking_results.append(available)
+ attempted.set()
+ with rag._hold_collection_lock(
+ lock_users[0], "collection", purpose=purpose
+ ) as held:
+ assert held is not None and held.locked()
+ entered.set()
+ assert release_worker.wait(10), "Worker was not released"
+ except BaseException as exc:
+ errors.append(exc)
+ attempted.set()
+
+ worker = threading.Thread(target=contender, daemon=True)
+ try:
+ with rag._hold_collection_lock(
+ lock_users[0], "collection", purpose=purpose
+ ) as owner_lock:
+ acquire = owner_lock.acquire
+
+ def observe_acquire(*args, **kwargs):
+ if kwargs.get("blocking", True):
+ blocking_attempted.set()
+ return acquire(*args, **kwargs)
+
+ monkeypatch.setattr(owner_lock, "acquire", observe_acquire)
+ worker.start()
+ assert attempted.wait(10), "Contender did not attempt acquisition"
+ assert not errors, errors
+ assert nonblocking_results == [None]
+ assert blocking_attempted.wait(10), (
+ "Blocking acquisition was not attempted"
+ )
+ assert not entered.is_set()
+ assert entered.wait(10), (
+ "Blocking contender did not acquire after release"
+ )
+ finally:
+ release_worker.set()
+ if worker.ident is not None:
+ worker.join(10)
+ assert not worker.is_alive(), "Contender did not finish"
+ assert not errors, errors
+
+
+def test_user_cleanup_preserves_nested_active_collection_locks(lock_users):
+ username, other_user = lock_users
+ inactive = rag._get_collection_lock(username, "idle", purpose="rebuild")
+ other = rag._get_collection_lock(other_user, "idle", purpose="rebuild")
+
+ with rag._hold_collection_lock(
+ username, "collection", purpose="transaction"
+ ) as outer:
+ with rag._hold_collection_lock(
+ username, "collection", purpose="transaction", blocking=False
+ ) as inner:
+ assert inner is outer
+ rag.pop_faiss_locks_for_user(username)
+ assert (
+ rag._get_collection_lock(
+ username, "collection", purpose="transaction"
+ )
+ is outer
+ )
+ # The inner release must not make the outer holder evictable.
+ rag.pop_faiss_locks_for_user(username)
+ assert (
+ rag._get_collection_lock(
+ username, "collection", purpose="transaction"
+ )
+ is outer
+ )
+ assert rag._get_collection_lock(
+ username, "idle", purpose="rebuild"
+ ) is not (inactive)
+ assert rag._get_collection_lock(
+ other_user, "idle", purpose="rebuild"
+ ) is (other)
+
+ assert not outer.locked()
+ rag.pop_faiss_locks_for_user(username)
+ assert (
+ rag._get_collection_lock(username, "collection", purpose="transaction")
+ is not outer
+ )
+
+
+ "blocking", [True, False], ids=["blocking", "nonblocking"]
+)
+def test_collection_holder_retries_eviction_before_acquire(
+ monkeypatch, lock_users, blocking
+):
+ username = lock_users[0]
+ stale = rag._get_collection_lock(username, "collection", purpose="rebuild")
+ original_acquire = rag._TrackedRLock.acquire
+ replacements = []
+
+ def evict_before_acquire(lock, *args, **kwargs):
+ if lock is stale and not replacements:
+ rag.pop_faiss_locks_for_user(username)
+ replacements.append(
+ rag._get_collection_lock(
+ username, "collection", purpose="rebuild"
+ )
+ )
+ return original_acquire(lock, *args, **kwargs)
+
+ monkeypatch.setattr(rag._TrackedRLock, "acquire", evict_before_acquire)
+ with rag._hold_collection_lock(
+ username, "collection", purpose="rebuild", blocking=blocking
+ ) as held:
+ assert len(replacements) == 1
+ assert held is replacements[0] and held is not stale
+ assert not stale.locked()
+ assert held.locked()
+ rag.pop_faiss_locks_for_user(username)
+ assert (
+ rag._get_collection_lock(username, "collection", purpose="rebuild")
+ is held
+ )
+ assert not held.locked()
+
+
+def test_physical_relative_and_absolute_aliases_keep_sharing_a_lock(
+ tmp_path, monkeypatch, lock_users
+):
+ (tmp_path / "indices").mkdir()
+ monkeypatch.chdir(tmp_path)
+ paths = (
+ "indices/index.faiss",
+ "indices/./index.faiss",
+ "indices/../indices/index.faiss",
+ str(tmp_path / "indices" / "index.faiss"),
+ )
+ lock = rag._get_faiss_write_lock(lock_users[0], paths[0])
+ for path in paths:
+ assert rag._get_faiss_write_lock(lock_users[0], path) is lock
+ with rag._hold_faiss_write_lock(lock_users[0], paths[0]):
+ with rag._hold_faiss_write_lock(lock_users[0], path) as held:
+ assert held is lock
+
+
+def test_physical_symlink_alias_keeps_sharing_a_lock(tmp_path, lock_users):
+ target = tmp_path / "index.faiss"
+ alias = tmp_path / "alias.faiss"
+ target.touch()
+ try:
+ alias.symlink_to(target)
+ except (OSError, NotImplementedError) as exc:
+ if os.name == "nt":
+ pytest.skip(f"Windows symlink creation unavailable: {exc}")
+ raise
+
+ lock = rag._get_faiss_write_lock(lock_users[0], str(target))
+ assert rag._get_faiss_write_lock(lock_users[0], str(alias)) is lock
+ with rag._hold_faiss_write_lock(lock_users[0], str(target)):
+ with rag._hold_faiss_write_lock(lock_users[0], str(alias)) as held:
+ assert held is lock
diff --git a/tests/research_library/services/test_collection_rebuild.py b/tests/research_library/services/test_collection_rebuild.py
new file mode 100644
index 0000000000..02b78f9716
--- /dev/null
+++ b/tests/research_library/services/test_collection_rebuild.py
@@ -0,0 +1,1745 @@
+"""Real SQLite/FAISS tests for publishing complete collection generations."""
+
+import hashlib
+import os
+import sqlite3
+import subprocess
+import sys
+import threading
+from contextlib import contextmanager
+from pathlib import Path
+from types import MethodType, SimpleNamespace
+from unittest.mock import MagicMock
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine, event
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ EmbeddingProvider,
+ RagDocumentStatus,
+ RAGIndex,
+ SourceType,
+)
+from local_deep_research.research_library.services import library_rag_service
+from local_deep_research.vector_stores import facade
+from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+)
+
+
+class LocalEmbeddings(Embeddings):
+ def __init__(self, model):
+ self.model = model
+ self.fail_on = None
+
+ def embed_query(self, text):
+ seed = int.from_bytes(
+ hashlib.sha256((self.model + text).encode()).digest()[:4], "big"
+ )
+ return np.random.default_rng(seed).random(8).tolist()
+
+ def embed_documents(self, texts):
+ if self.fail_on and any(self.fail_on in text for text in texts):
+ raise RuntimeError("Embedding backend unavailable")
+ return [self.embed_query(text) for text in texts]
+
+
+class RebuildWorld:
+ collection_id = "rebuild-collection"
+ collection_name = "collection_rebuild-collection"
+ doc_info = [("document-0", "First"), ("document-1", "Second")]
+
+ def __init__(
+ self,
+ root,
+ monkeypatch,
+ *,
+ seed=True,
+ encrypted=False,
+ real_integrity=False,
+ ):
+ self.root = Path(root)
+ monkeypatch.setenv("LDR_DATA_DIR", str(root))
+ engine_kwargs = {}
+ if encrypted:
+ from local_deep_research.database.sqlcipher_compat import (
+ get_sqlcipher_module,
+ )
+
+ engine_kwargs["module"] = get_sqlcipher_module().dbapi2
+ self.engine = create_engine(
+ f"sqlite:///{root}/rebuild.sqlite", **engine_kwargs
+ )
+
+ @event.listens_for(self.engine, "connect")
+ def foreign_keys(connection, _record):
+ if encrypted:
+ connection.execute(
+ "PRAGMA key = 'test-password'"
+ ) # gitleaks:allow
+ connection.execute("PRAGMA kdf_iter = 1000")
+ connection.execute("PRAGMA foreign_keys=ON")
+
+ self.make_session = sessionmaker(
+ bind=self.engine, expire_on_commit=False
+ )
+ self.local = threading.local()
+ monkeypatch.setattr(
+ library_rag_service, "get_user_db_session", self.session
+ )
+ monkeypatch.setattr(facade, "get_user_db_session", self.session)
+ if real_integrity:
+ from local_deep_research.security.file_integrity import (
+ integrity_manager,
+ )
+ from local_deep_research.database import thread_local_session
+
+ monkeypatch.setattr(
+ integrity_manager, "get_user_db_session", self.session
+ )
+ monkeypatch.setattr(
+ thread_local_session,
+ "get_current_thread_session",
+ lambda: getattr(self.local, "session", None),
+ )
+ else:
+ integrity = MagicMock()
+ integrity.verify_file.return_value = (True, None)
+ monkeypatch.setattr(
+ library_rag_service,
+ "FileIntegrityManager",
+ lambda *a, **k: integrity,
+ )
+ if seed:
+ Base.metadata.create_all(self.engine)
+ with self.session() as session:
+ session.add(
+ SourceType(
+ id="source", name="document", display_name="Document"
+ )
+ )
+ session.add(
+ Collection(
+ id=self.collection_id,
+ name="Rebuild test",
+ embedding_model="model-A",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=8,
+ chunk_size=100,
+ chunk_overlap=0,
+ splitter_type="recursive",
+ text_separators=["\n", " "],
+ distance_metric="cosine",
+ normalize_vectors=True,
+ index_type="flat",
+ )
+ )
+ for doc_id, title in self.doc_info:
+ body = (
+ f"Original text for {doc_id}. Searchable before rebuilding. "
+ * 5
+ )
+ session.add(
+ Document(
+ id=doc_id,
+ source_type_id="source",
+ document_hash=hashlib.sha256(
+ body.encode()
+ ).hexdigest(),
+ title=title,
+ filename=f"{doc_id}.txt",
+ file_size=len(body.encode()),
+ file_type="txt",
+ text_content=body,
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.add(
+ DocumentCollection(
+ document_id=doc_id,
+ collection_id=self.collection_id,
+ indexed=False,
+ )
+ )
+ session.commit()
+ with self.service() as service:
+ for doc_id, _title in self.doc_info:
+ assert (
+ service.index_document(doc_id, self.collection_id)[
+ "status"
+ ]
+ == "success"
+ )
+
+ @contextmanager
+ def session(self, *_args, **_kwargs):
+ existing = getattr(self.local, "session", None)
+ if existing is not None:
+ yield existing
+ return
+ with self.make_session() as session:
+ self.local.session = session
+ try:
+ yield session
+ except BaseException:
+ session.rollback()
+ raise
+ finally:
+ self.local.session = None
+
+ def service(self, model="model-A"):
+ return library_rag_service.LibraryRAGService(
+ username="rebuild-user",
+ db_password="test-password", # gitleaks:allow
+ embedding_manager=SimpleNamespace(
+ embeddings=LocalEmbeddings(model)
+ ),
+ embedding_model=model,
+ embedding_provider="sentence_transformers",
+ chunk_size=100,
+ chunk_overlap=0,
+ text_separators=["\n", " "],
+ )
+
+ def snapshot(self):
+ with self.session() as session:
+ collection = session.get(Collection, self.collection_id)
+ indices = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=self.collection_name)
+ .all()
+ )
+ return {
+ "model": collection.embedding_model,
+ "indices": sorted(
+ (
+ r.id,
+ r.index_hash,
+ r.is_current,
+ r.chunk_count,
+ r.total_documents,
+ )
+ for r in indices
+ ),
+ "files": {
+ r.index_path: Path(r.index_path).read_bytes()
+ for r in indices
+ },
+ "chunks": [
+ (r.id, r.source_id, r.chunk_text)
+ for r in session.query(DocumentChunk)
+ .filter_by(collection_name=self.collection_name)
+ .order_by(DocumentChunk.id)
+ ],
+ "status": [
+ (r.document_id, r.rag_index_id, r.chunk_count)
+ for r in session.query(RagDocumentStatus)
+ .filter_by(collection_id=self.collection_id)
+ .order_by(RagDocumentStatus.document_id)
+ ],
+ "links": [
+ (r.document_id, r.indexed, r.chunk_count)
+ for r in session.query(DocumentCollection)
+ .filter_by(collection_id=self.collection_id)
+ .order_by(DocumentCollection.document_id)
+ ],
+ }
+
+ def pending_rebuild_since(self):
+ with self.session() as session:
+ return session.get(
+ Collection, self.collection_id
+ ).rebuild_pending_since
+
+ def assert_searchable(self, model="model-A"):
+ with self.service(model) as service:
+ hits = service.search("Searchable", self.collection_id, 100)
+ assert {hit.source_id for hit in hits} == {
+ doc_id for doc_id, _title in self.doc_info
+ }
+
+ def assert_no_staging(self):
+ with self.session() as session:
+ assert (
+ session.query(RAGIndex)
+ .filter(RAGIndex.collection_name != self.collection_name)
+ .count()
+ == 0
+ )
+ assert (
+ session.query(DocumentChunk)
+ .filter(DocumentChunk.collection_name != self.collection_name)
+ .count()
+ == 0
+ )
+
+
+def world(tmp_path, monkeypatch):
+ result = RebuildWorld(tmp_path, monkeypatch)
+ yield result
+ result.engine.dispose()
+
+
[email protected]("model", ["model-A", "model-B"])
+def test_complete_rebuild_switches_generation_only_after_all_documents(
+ world, model
+):
+ before = world.snapshot()
+ observed = []
+
+ def progress(completed, *_args):
+ assert world.snapshot() == before
+ world.assert_searchable()
+ observed.append(completed)
+
+ with world.service(model) as service:
+ result = service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=2,
+ progress_callback=progress,
+ )
+ assert result["successful"] == 2
+ assert result["failed"] == 0
+ assert sorted(observed) == [1, 2]
+ after = world.snapshot()
+ assert after["model"] == model
+ assert after["indices"][0][0] != before["indices"][0][0]
+ assert all(not Path(path).exists() for path in before["files"])
+ world.assert_searchable(model)
+ world.assert_no_staging()
+ # Subsequent ordinary writes must reopen the published generation path.
+ with world.service(model) as service:
+ assert (
+ service.index_document(
+ "document-0", world.collection_id, force_reindex=True
+ )["status"]
+ == "success"
+ )
+ world.assert_searchable(model)
+
+
+def test_embedding_failure_after_partial_preparation_preserves_old_index(world):
+ before = world.snapshot()
+ with world.service("model-B") as service:
+ service.embedding_manager.embeddings.fail_on = "document-1"
+ with pytest.raises(RuntimeError, match="previous index was preserved"):
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ assert world.snapshot() == before
+ assert world.pending_rebuild_since() is not None
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
[email protected]("cancel_after", [1, 2])
+def test_cancellation_preserves_the_published_generation(world, cancel_after):
+ before = world.snapshot()
+ stop = threading.Event()
+
+ def progress(completed, *_args):
+ if completed == cancel_after:
+ stop.set()
+
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=progress,
+ is_cancelled=stop.is_set,
+ )
+ assert result["cancelled"] is True
+ assert world.snapshot() == before
+ assert world.pending_rebuild_since() is not None
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
+def test_cancelled_rebuild_notice_survives_incremental_indexing_until_rebuilt(
+ world, loguru_caplog
+):
+ """An automatic incremental run cannot finish a cancelled model change."""
+ before = world.snapshot()
+ stop = threading.Event()
+
+ def cancel_after_preparation(*_args):
+ stop.set()
+
+ with (
+ loguru_caplog.at_level("WARNING"),
+ world.service("model-B") as replacement,
+ ):
+ cancelled = replacement.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=cancel_after_preparation,
+ is_cancelled=stop.is_set,
+ )
+ assert cancelled["cancelled"]
+ pending_since = world.pending_rebuild_since()
+ assert pending_since is not None and pending_since.utcoffset() is not None
+ assert "Automatic indexing does not retry full rebuilds" in (
+ loguru_caplog.text
+ )
+ assert world.snapshot() == before
+
+ # Both the immediate auto-indexer and scheduled sweep use this ordinary
+ # path with the collection's existing configuration. Neither applies the
+ # requested replacement to documents that are already indexed.
+ with world.service("model-A") as incremental:
+ aggregate = incremental.index_documents_parallel(
+ world.doc_info,
+ world.collection_id,
+ force_reindex=False,
+ max_workers=1,
+ )
+ assert aggregate["successful"] == aggregate["failed"] == 0
+ assert aggregate["skipped"] == len(world.doc_info)
+ incremental.reconcile_collection_index(world.collection_id)
+ assert world.pending_rebuild_since() == pending_since
+ assert world.snapshot() == before
+ world.assert_searchable()
+ world.assert_no_staging()
+
+ # Only a complete replacement clears the durable notice and changes the
+ # collection's configuration and generation together.
+ with world.service("model-B") as replacement:
+ aggregate = replacement.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ assert aggregate["failed"] == 0 and not aggregate["cancelled"]
+ assert world.pending_rebuild_since() is None
+ assert world.snapshot()["model"] == "model-B"
+ assert world.snapshot()["indices"][0][0] != before["indices"][0][0]
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+
+
+def test_failed_stage_persist_preserves_the_published_generation(
+ world, monkeypatch
+):
+ before = world.snapshot()
+ original = FaissVectorStore.persist
+ writes = []
+
+ def fail_second_write(store, path):
+ assert str(path) not in before["files"]
+ writes.append(path)
+ if len(writes) == 2:
+ raise OSError("Disk full")
+ return original(store, path)
+
+ monkeypatch.setattr(FaissVectorStore, "persist", fail_second_write)
+ with (
+ world.service("model-B") as service,
+ pytest.raises(OSError, match="Disk full"),
+ ):
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ assert len(writes) == 2
+ assert world.snapshot() == before
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
+def test_cancellation_stops_rebuild_embedding_after_the_current_batch(
+ world, monkeypatch
+):
+ before = world.snapshot()
+ with world.session() as session:
+ session.get(Document, "document-0").text_content = (
+ "Replacement text that requires many embedding batches. " * 200
+ )
+ session.commit()
+ stop = threading.Event()
+ batch_sizes = []
+
+ with world.service("model-B") as service:
+ embeddings = service.embedding_manager.embeddings
+ original = embeddings.embed_documents
+
+ def cancel_after_this_batch(texts):
+ batch_sizes.append(len(texts))
+ stop.set()
+ return original(texts)
+
+ monkeypatch.setattr(
+ embeddings, "embed_documents", cancel_after_this_batch
+ )
+ result = service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ is_cancelled=stop.is_set,
+ )
+
+ assert batch_sizes == [32]
+ assert result["cancelled"] is True
+ assert world.snapshot() == before
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
+def test_publication_commit_failure_restores_rows_and_keeps_old_files(world):
+ before = world.snapshot()
+ old_id = before["indices"][0][0]
+ failed = []
+
+ def fail_publication(session):
+ replacement = (
+ session.query(RAGIndex)
+ .filter(
+ RAGIndex.collection_name == world.collection_name,
+ RAGIndex.id != old_id,
+ )
+ .first()
+ )
+ if replacement is not None and not failed:
+ failed.append(replacement.id)
+ raise RuntimeError("Injected commit failure")
+
+ event.listen(world.make_session, "before_commit", fail_publication)
+ try:
+ with (
+ world.service("model-B") as service,
+ pytest.raises(RuntimeError, match="Injected commit failure"),
+ ):
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ finally:
+ event.remove(world.make_session, "before_commit", fail_publication)
+ assert failed
+ assert world.snapshot() == before
+ assert world.pending_rebuild_since() is not None
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
[email protected]("damage", ["missing", "corrupt"])
+def test_publication_requires_durable_vectors(world, damage):
+ before = world.snapshot()
+
+ def progress(completed, *_args):
+ if completed != len(world.doc_info):
+ return
+ with world.session() as session:
+ stage = (
+ session.query(RAGIndex)
+ .filter(RAGIndex.collection_name != world.collection_name)
+ .one()
+ )
+ path = Path(stage.index_path)
+ if damage == "missing":
+ path.unlink()
+ else:
+ path.write_bytes(b"truncated FAISS data")
+
+ with world.service("model-B") as service, pytest.raises(RuntimeError):
+ service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=progress,
+ )
+ assert world.snapshot() == before
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
+def test_edit_during_rebuild_rejects_stale_preparation(world):
+ before = world.snapshot()
+
+ def progress(completed, *_args):
+ if completed == 1:
+ with world.session() as session:
+ session.get(
+ Document, "document-0"
+ ).text_content = "New text while rebuilding"
+ session.commit()
+
+ with (
+ world.service("model-B") as service,
+ pytest.raises(ValueError, match="documents changed"),
+ ):
+ service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=progress,
+ )
+ assert world.snapshot() == before
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
[email protected]("prepare_before_publication", [False, True])
+def test_prepared_worker_cannot_overwrite_a_new_collection_configuration(
+ world, prepare_before_publication
+):
+ with world.service() as original:
+ prepared = (
+ original._prepare_document("document-0", world.collection_id, True)[
+ "prepared"
+ ]
+ if prepare_before_publication
+ else None
+ )
+ with world.service("model-B") as replacement:
+ replacement.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ published = world.snapshot()
+ if prepared is None:
+ prepared = original._prepare_document(
+ "document-0", world.collection_id, True
+ )["prepared"]
+ result = original._write_prepared_document(prepared)
+ assert result["status"] == "error"
+ assert "configuration changed" in result["error"]
+ assert world.snapshot() == published
+ world.assert_searchable("model-B")
+
+
[email protected]("operation", ["reindex", "unindexed", "empty"])
+def test_direct_worker_cannot_overwrite_a_new_collection_configuration(
+ world, operation
+):
+ with world.service() as original:
+ with world.service("model-B") as replacement:
+ replacement.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ with world.session() as session:
+ if operation == "unindexed":
+ session.query(DocumentCollection).filter_by(
+ document_id="document-0", collection_id=world.collection_id
+ ).one().indexed = False
+ elif operation == "empty":
+ session.get(Document, "document-0").text_content = ""
+ session.commit()
+ published = world.snapshot()
+ original.embedding_manager.embeddings.fail_on = "Original"
+ result = original.index_document(
+ "document-0",
+ world.collection_id,
+ force_reindex=operation != "unindexed",
+ )
+ assert result["status"] == "error"
+ assert "configuration changed" in result["error"]
+ assert world.snapshot() == published
+ world.assert_searchable("model-B")
+
+
[email protected]("change", ["configuration", "membership", "index"])
+def test_concurrent_collection_changes_are_not_overwritten(world, change):
+ changed = []
+
+ def progress(completed, *_args):
+ if completed != len(world.doc_info):
+ return
+ with world.session() as session:
+ if change == "configuration":
+ session.get(Collection, world.collection_id).chunk_size = 200
+ elif change == "membership":
+ session.query(DocumentCollection).filter_by(
+ document_id="document-1", collection_id=world.collection_id
+ ).delete()
+ else:
+ index = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=world.collection_name)
+ .one()
+ )
+ index.total_documents += 1
+ session.commit()
+ changed.append(world.snapshot())
+
+ with (
+ world.service("model-B") as service,
+ pytest.raises(ValueError, match="changed"),
+ ):
+ service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=progress,
+ )
+ assert changed and world.snapshot() == changed[0]
+ world.assert_no_staging()
+
+
[email protected]("remove_after", [1, 2])
+def test_document_removed_from_search_during_rebuild_stays_removed(
+ world, monkeypatch, remove_after
+):
+ from local_deep_research.web_search_engines.engines import (
+ local_embedding_manager,
+ )
+
+ monkeypatch.setattr(
+ local_embedding_manager, "get_user_db_session", world.session
+ )
+ removed = []
+
+ def remove_from_search(completed, *_args):
+ if completed != remove_after:
+ return
+ with world.service() as remover:
+ manager = remover.embedding_manager
+ manager.username = remover.username
+ manager.db_password = remover.db_password
+ manager._delete_chunks_from_db = MethodType(
+ local_embedding_manager.LocalEmbeddingManager._delete_chunks_from_db,
+ manager,
+ )
+ result = remover.remove_document_from_rag(
+ "document-0", world.collection_id
+ )
+ assert result["status"] == "success"
+ assert result["deleted_count"] > 0
+ removed.append(world.snapshot())
+
+ with (
+ world.service("model-B") as service,
+ pytest.raises(ValueError, match="indexing state changed"),
+ ):
+ service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=remove_from_search,
+ )
+ assert removed and world.snapshot() == removed[0]
+ with world.service() as reader:
+ hits = reader.search("Searchable", world.collection_id, 100)
+ assert {hit.source_id for hit in hits} == {"document-1"}
+ world.assert_no_staging()
+
+
[email protected]("empty_collection", [False, True])
+def test_successful_empty_rebuild_clears_the_old_index(world, empty_collection):
+ before = world.snapshot()
+ with world.session() as session:
+ if empty_collection:
+ session.query(DocumentCollection).filter_by(
+ collection_id=world.collection_id
+ ).delete()
+ else:
+ session.query(Document).update({"text_content": ""})
+ session.commit()
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ [] if empty_collection else world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ )
+ assert result["failed"] == 0
+ assert world.pending_rebuild_since() is None
+ after = world.snapshot()
+ assert after["model"] == "model-B"
+ assert not after["indices"] and not after["chunks"] and not after["status"]
+ assert all(
+ not indexed and count == 0 for _doc, indexed, count in after["links"]
+ )
+ assert all(not Path(path).exists() for path in before["files"])
+ world.assert_no_staging()
+
+
+def test_retired_files_are_deleted_only_after_publication_commits(
+ world, monkeypatch
+):
+ from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+ )
+
+ before = world.snapshot()
+ original = CascadeHelper.delete_faiss_index_files
+ removed = []
+
+ def inspect_committed_publication(path, **kwargs):
+ # A separate session observes only committed state, even if a caller
+ # mistakenly invokes cleanup from inside the publication transaction.
+ with world.make_session() as session:
+ assert (
+ session.get(Collection, world.collection_id).embedding_model
+ == "model-B"
+ )
+ indices = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=world.collection_name)
+ .all()
+ )
+ assert (
+ len(indices) == 1 and indices[0].id != before["indices"][0][0]
+ )
+ assert str(path) not in {row.index_path for row in indices}
+ removed.append(str(path))
+ return original(path, **kwargs)
+
+ monkeypatch.setattr(
+ CascadeHelper, "delete_faiss_index_files", inspect_committed_publication
+ )
+ with world.service("model-B") as service:
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ assert set(removed) == set(before["files"])
+ world.assert_searchable("model-B")
+
+
+def test_callback_error_after_commit_keeps_the_published_generation(world):
+ failed = []
+
+ def mark_publication(session):
+ collection = session.get(Collection, world.collection_id)
+ session.info["publishing"] = collection.embedding_model == "model-B"
+
+ def fail_after_publication(session):
+ if session.info.pop("publishing", False):
+ failed.append(True)
+ raise RuntimeError("Post-commit callback failed")
+
+ event.listen(world.make_session, "before_commit", mark_publication)
+ event.listen(world.make_session, "after_commit", fail_after_publication)
+ try:
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ finally:
+ event.remove(world.make_session, "before_commit", mark_publication)
+ event.remove(world.make_session, "after_commit", fail_after_publication)
+ assert failed and result["failed"] == 0
+ assert world.snapshot()["model"] == "model-B"
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+
+
+def _crash_after_staging(root, phase):
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ world = RebuildWorld(root, monkeypatch, seed=False)
+ if phase == "published":
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ monkeypatch.setattr(
+ CollectionRebuild,
+ "_unlink",
+ staticmethod(lambda _paths: os._exit(73)),
+ )
+
+ def crash(completed, *_args):
+ if completed == 1 and phase == "preparing":
+ os._exit(73)
+
+ with world.service("model-B") as service:
+ service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=crash,
+ )
+
+
[email protected]("phase", ["preparing", "published"])
+def test_process_interruption_leaves_a_complete_generation_searchable(
+ world, phase
+):
+ before = world.snapshot()
+ worker = (
+ "import runpy, sys; "
+ "ns = runpy.run_path(sys.argv[1]); "
+ "ns['_crash_after_staging'](sys.argv[2], sys.argv[3])"
+ )
+ child = subprocess.run(
+ [sys.executable, "-c", worker, __file__, str(world.root), phase],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ )
+ assert child.returncode == 73, child.stderr
+ # The exit bypasses finally/cleanup on either side of publication.
+ if phase == "preparing":
+ with world.session() as session:
+ assert (
+ session.query(RAGIndex)
+ .filter(RAGIndex.collection_name != world.collection_name)
+ .count()
+ == 1
+ )
+ assert world.snapshot() == before
+ world.assert_searchable()
+ else:
+ assert world.snapshot()["model"] == "model-B"
+ assert all(Path(path).exists() for path in before["files"])
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+ # A later attempt can still replace the published generation. The
+ # abandoned generation stays unselected; deleting unknown stages here
+ # could destroy a rebuild still running in another process.
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ assert result["failed"] == 0
+ world.assert_searchable("model-B")
+
+
+def test_encrypted_rebuild_with_real_integrity_records(tmp_path, monkeypatch):
+ world = RebuildWorld(
+ tmp_path, monkeypatch, encrypted=True, real_integrity=True
+ )
+ try:
+ before = world.snapshot()
+ with world.service("model-B") as service:
+ service.embedding_manager.embeddings.fail_on = "document-1"
+ with pytest.raises(
+ RuntimeError, match="previous index was preserved"
+ ):
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ assert world.snapshot() == before
+ world.assert_searchable()
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=2
+ )
+ assert result["successful"] == 2
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+ assert (
+ not (tmp_path / "rebuild.sqlite")
+ .read_bytes()
+ .startswith(b"SQLite format 3")
+ )
+ assert all(
+ b"Original text" not in payload
+ for payload in world.snapshot()["files"].values()
+ )
+ finally:
+ world.engine.dispose()
+
+
+def test_cancellation_during_publication_publishes_the_whole_generation(world):
+ """Cancellation is decided before the publication transaction opens.
+
+ A cancel that arrives while the switch is being written cannot stop the
+ transaction part way through: it publishes the complete generation.
+ """
+ stop = threading.Event()
+ before = world.snapshot()
+
+ def cancel_on_configuration_switch(
+ _collection, value, _old_value, _initiator
+ ):
+ if value == "model-B":
+ stop.set()
+
+ event.listen(
+ Collection.embedding_model, "set", cancel_on_configuration_switch
+ )
+ try:
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ is_cancelled=stop.is_set,
+ )
+ finally:
+ event.remove(
+ Collection.embedding_model, "set", cancel_on_configuration_switch
+ )
+ assert stop.is_set() and not result["cancelled"]
+ assert result["successful"] == 2 and result["failed"] == 0
+ assert world.snapshot()["model"] == "model-B"
+ assert all(not Path(path).exists() for path in before["files"])
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+
+
+class TaskCancelCheck:
+ """The background worker's cancel check over production session scopes.
+
+ ``get_user_db_session`` gives every scope on a thread the same
+ thread-local Session, and rolls that Session back when a scope raises,
+ even a nested one. ``RebuildWorld.session`` does neither, so these tests
+ run the real function over one Session per thread. The check is the real
+ ``_is_task_cancelled``, as ``_background_index_worker`` passes it.
+ """
+
+ task_id = "rebuild-task"
+
+ def __init__(self, world, monkeypatch):
+ from local_deep_research.database import (
+ session_context,
+ thread_local_session,
+ )
+ from local_deep_research.database.models.queue import TaskMetadata
+ from local_deep_research.web.routers import rag as rag_routes
+
+ self.world = world
+ self.routes = rag_routes
+ self.TaskMetadata = TaskMetadata
+ self.local = threading.local()
+ self.sessions = []
+ self.sessions_lock = threading.Lock()
+ # Whether a get_user_db_session scope was already open on the
+ # polling thread, for every poll of the check.
+ self.polls = []
+ monkeypatch.setattr(
+ thread_local_session, "get_metrics_session", self.thread_session
+ )
+ for module in (library_rag_service, facade):
+ monkeypatch.setattr(
+ module,
+ "get_user_db_session",
+ session_context.get_user_db_session,
+ )
+ with world.session() as session:
+ session.add(
+ TaskMetadata(
+ task_id=self.task_id,
+ status="processing",
+ task_type="indexing",
+ )
+ )
+ session.commit()
+
+ def thread_session(self, _username, _password):
+ session = getattr(self.local, "session", None)
+ if session is None:
+ session = self.local.session = self.world.make_session()
+ with self.sessions_lock:
+ self.sessions.append(session)
+ return session
+
+ def check(self, service):
+ from local_deep_research.database.thread_local_session import (
+ thread_session_manager,
+ )
+
+ def is_cancelled():
+ self.polls.append(thread_session_manager.in_scope())
+ return self.routes._is_task_cancelled(
+ service.username, service.db_password, self.task_id
+ )
+
+ return is_cancelled
+
+ def cancel(self):
+ """Record a cancel request through another connection."""
+ with self.world.make_session() as session:
+ session.get(self.TaskMetadata, self.task_id).status = "cancelled"
+ session.commit()
+
+ @contextmanager
+ def failing_task_reads(self):
+ """Fail every task-row statement in the driver, like an I/O error."""
+
+ def fail(_cursor, statement, _parameters, _context):
+ if "task_metadata" in statement:
+ raise sqlite3.OperationalError("disk I/O error")
+ return False
+
+ event.listen(self.world.engine, "do_execute", fail)
+ try:
+ yield
+ finally:
+ event.remove(self.world.engine, "do_execute", fail)
+
+ def close(self):
+ for session in self.sessions:
+ session.close()
+
+
+def task_check(world, monkeypatch):
+ result = TaskCancelCheck(world, monkeypatch)
+ yield result
+ result.close()
+
+
+def test_database_cancel_before_publication_preserves_the_index(
+ world, task_check, monkeypatch
+):
+ """The check runs before the publication scope opens, never inside it."""
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ before = world.snapshot()
+ validate_vectors = CollectionRebuild._validate_vectors
+
+ def cancel_once_staged(rebuild):
+ expected_chunks = validate_vectors(rebuild)
+ task_check.cancel()
+ return expected_chunks
+
+ monkeypatch.setattr(
+ CollectionRebuild, "_validate_vectors", cancel_once_staged
+ )
+ with world.service("model-B") as service:
+ result = service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ is_cancelled=task_check.check(service),
+ )
+ assert result["cancelled"] is True
+ assert task_check.polls and not any(task_check.polls), task_check.polls
+ assert world.snapshot() == before
+ world.assert_searchable()
+ world.assert_no_staging()
+
+
+def test_cancel_check_after_validation_cannot_publish_unvalidated_rows(
+ world, task_check, monkeypatch
+):
+ """A rollback after validation must not let the publication commit.
+
+ The publication used to check cancellation here. When that check's read
+ fails, get_user_db_session rolls back the shared Session, which releases
+ SQLite's writer lock and the validated snapshot, and _is_task_cancelled
+ swallows the error. A writer can then commit a change that the
+ publication's writes, in a new transaction, would overwrite.
+ """
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ before = world.snapshot()
+ validate_sources = CollectionRebuild._validate_sources
+
+ def validate_then_check(rebuild, session, collection):
+ validate_sources(rebuild, session, collection)
+ with task_check.failing_task_reads():
+ assert not task_check.routes._is_task_cancelled(
+ rebuild.service.username,
+ rebuild.service.db_password,
+ task_check.task_id,
+ )
+ # The rollback released the writer lock: remove a document from
+ # search through another connection, as a concurrent writer could.
+ with world.make_session() as other:
+ other.query(DocumentCollection).filter_by(
+ document_id="document-1", collection_id=world.collection_id
+ ).update({"indexed": False, "chunk_count": 0})
+ other.query(RagDocumentStatus).filter_by(
+ document_id="document-1", collection_id=world.collection_id
+ ).delete()
+ other.commit()
+
+ monkeypatch.setattr(
+ CollectionRebuild, "_validate_sources", validate_then_check
+ )
+ with (
+ world.service("model-B") as service,
+ pytest.raises(RuntimeError, match="lost its transaction"),
+ ):
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )
+ expected = dict(
+ before,
+ links=[
+ ("document-1", False, 0) if row[0] == "document-1" else row
+ for row in before["links"]
+ ],
+ status=[row for row in before["status"] if row[0] != "document-1"],
+ )
+ assert world.snapshot() == expected
+ world.assert_no_staging()
+
+
+def test_failing_cancel_check_cannot_lose_the_published_index(
+ world, task_check
+):
+ """A cancel check whose read fails must not empty the publication.
+
+ _is_task_cancelled swallows the error after get_user_db_session rolled
+ back this thread's Session. Inside the publication that rollback used to
+ discard every publication write. The empty commit then counted as a
+ publication, and the previous generation's files were deleted while its
+ rows stayed current.
+ """
+ before = world.snapshot()
+ with (
+ world.service("model-B") as service,
+ task_check.failing_task_reads(),
+ ):
+ result = service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ is_cancelled=task_check.check(service),
+ )
+ assert result["cancelled"] is False
+ assert result["successful"] == 2 and result["failed"] == 0
+ assert world.snapshot()["model"] == "model-B"
+ assert all(not Path(path).exists() for path in before["files"])
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+
+
+def test_search_finishes_on_the_old_generation_before_publication(
+ world, monkeypatch
+):
+ before = world.snapshot()
+ searching = threading.Event()
+ resume = threading.Event()
+ staged = threading.Event()
+ completed = threading.Event()
+ hits = []
+ errors = []
+ original = facade.VectorIndex.search
+
+ def pause(index, query, *args, **kwargs):
+ if query == "pause":
+ searching.set()
+ assert resume.wait(10), "Test did not release the search"
+ return original(index, query, *args, **kwargs)
+
+ monkeypatch.setattr(facade.VectorIndex, "search", pause)
+
+ def reader():
+ try:
+ with world.service() as service:
+ hits.extend(service.search("pause", world.collection_id, 100))
+ except BaseException as exc:
+ errors.append(exc)
+
+ def progress(count, *_args):
+ if count == len(world.doc_info):
+ staged.set()
+
+ def publisher():
+ try:
+ with world.service("model-B") as service:
+ service.rebuild_collection(
+ world.doc_info,
+ world.collection_id,
+ max_workers=1,
+ progress_callback=progress,
+ )
+ completed.set()
+ except BaseException as exc:
+ errors.append(exc)
+
+ reader_thread = threading.Thread(target=reader)
+ publisher_thread = threading.Thread(target=publisher)
+ reader_thread.start()
+ try:
+ assert searching.wait(10)
+ publisher_thread.start()
+ assert staged.wait(10), (
+ "Embedding must continue while the old index is searched"
+ )
+ assert not completed.is_set()
+ assert world.snapshot() == before
+ finally:
+ resume.set()
+ reader_thread.join(timeout=10)
+ if publisher_thread.ident is not None:
+ publisher_thread.join(timeout=10)
+ assert not reader_thread.is_alive() and not publisher_thread.is_alive()
+ assert not errors and completed.is_set()
+ assert {hit.source_id for hit in hits} == {
+ doc_id for doc_id, _ in world.doc_info
+ }
+ world.assert_searchable("model-B")
+ world.assert_no_staging()
+
+
+def test_index_clear_then_reindex_cannot_lose_recreated_file(
+ world, monkeypatch
+):
+ from local_deep_research.research_library.deletion.services import (
+ collection_deletion,
+ )
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ monkeypatch.setattr(
+ collection_deletion, "get_user_db_session", world.session
+ )
+ old_path = Path(next(iter(world.snapshot()["files"])))
+ retiring = threading.Event()
+ release = threading.Event()
+ observed = threading.Event()
+ written = threading.Event()
+ admission = []
+ errors = []
+ original_unlink = CollectionRebuild._unlink
+
+ def pause_retirement(paths):
+ if str(old_path) in {str(path) for path in paths}:
+ retiring.set()
+ assert release.wait(30)
+ original_unlink(paths)
+
+ monkeypatch.setattr(
+ CollectionRebuild, "_unlink", staticmethod(pause_retirement)
+ )
+
+ def publish():
+ try:
+ with world.service("model-A") as service:
+ assert (
+ service.rebuild_collection(
+ world.doc_info, world.collection_id, max_workers=1
+ )["failed"]
+ == 0
+ )
+ except BaseException as exc:
+ errors.append(exc)
+
+ def clear_then_write():
+ try:
+ result = collection_deletion.CollectionDeletionService(
+ "rebuild-user"
+ ).delete_collection_index_only(world.collection_id)
+ assert result["deleted"], result
+ with world.service("model-A") as service:
+ # Observe the production writer's existing lock. The model
+ # reset above is performed by the real public delete service.
+ lock = library_rag_service._get_collection_lock(
+ service.username,
+ world.collection_id,
+ purpose="transaction",
+ )
+ acquired = lock.acquire(blocking=False)
+ admission.append(acquired)
+ observed.set()
+ if not acquired:
+ assert lock.acquire()
+ try:
+ for document_id, _ in world.doc_info:
+ result = service.index_document(
+ document_id, world.collection_id, force_reindex=True
+ )
+ assert result["status"] == "success", result
+ assert old_path.is_file()
+ finally:
+ lock.release()
+ written.set()
+ except BaseException as exc:
+ errors.append(exc)
+ observed.set()
+
+ publisher = threading.Thread(target=publish)
+ writer = threading.Thread(target=clear_then_write)
+ try:
+ publisher.start()
+ assert retiring.wait(30), errors
+ writer.start()
+ assert observed.wait(30), errors
+ if admission == [True]:
+ assert written.wait(30), errors
+ finally:
+ release.set()
+ publisher.join(30)
+ if writer.ident is not None:
+ writer.join(30)
+ assert not publisher.is_alive() and not writer.is_alive()
+ assert not errors, errors
+ assert written.is_set()
+ assert old_path.is_file(), "retirement deleted the newly written index"
+ world.assert_searchable("model-A")
+
+
+_ADVANCED_COLUMNS = (
+ "splitter_type",
+ "text_separators",
+ "distance_metric",
+ "normalize_vectors",
+ "index_type",
+)
+
+
+def test_legacy_collection_without_stored_settings_keeps_indexing(
+ world, monkeypatch
+):
+ """Index a collection created before #1054 through the real factory.
+
+ Migration 0032 adds the advanced columns NULL, and get_rag_service fills
+ them from the user's current settings. The configuration check must
+ resolve them the same way, or every ordinary index call fails once the
+ user has customised one of them (here the text separators).
+ """
+ from local_deep_research.research_library.services import (
+ rag_service_factory,
+ )
+
+ with world.session() as session:
+ collection = session.get(Collection, world.collection_id)
+ for column in _ADVANCED_COLUMNS:
+ setattr(collection, column, None)
+ session.commit()
+ settings = {
+ "local_search_embedding_model": "model-A",
+ "local_search_embedding_provider": "sentence_transformers",
+ "local_search_chunk_size": 100,
+ "local_search_chunk_overlap": 0,
+ "local_search_text_separators": ["\n", " "],
+ }
+ manager = MagicMock()
+ manager.get_setting.side_effect = lambda key, default=None: settings.get(
+ key, default
+ )
+ real_service = library_rag_service.LibraryRAGService
+
+ def service_with_local_embeddings(**kwargs):
+ return real_service(
+ embedding_manager=SimpleNamespace(
+ embeddings=LocalEmbeddings(kwargs["embedding_model"])
+ ),
+ **kwargs,
+ )
+
+ monkeypatch.setattr(
+ rag_service_factory, "get_settings_manager", lambda **_kw: manager
+ )
+ monkeypatch.setattr(
+ rag_service_factory, "get_user_db_session", world.session
+ )
+ monkeypatch.setattr(
+ rag_service_factory, "LibraryRAGService", service_with_local_embeddings
+ )
+
+ with rag_service_factory.get_rag_service(
+ "rebuild-user", world.collection_id
+ ) as service:
+ assert service.text_separators == ["\n", " "]
+ result = service.index_document(
+ "document-0", world.collection_id, force_reindex=True
+ )
+ assert result["status"] == "success", result
+ aggregate = service.index_documents_parallel(
+ world.doc_info,
+ world.collection_id,
+ force_reindex=True,
+ max_workers=1,
+ )
+ assert aggregate["successful"] == 2 and aggregate["failed"] == 0, aggregate
+ world.assert_searchable()
+
+
+def test_configuration_check_resolves_every_unset_column(world):
+ """Each column the factory fills from settings resolves alike here."""
+ from local_deep_research.research_library.services.library_rag_service import (
+ _COLLECTION_INDEX_SETTINGS,
+ resolve_collection_index_settings,
+ )
+
+ legacy = Collection(id="legacy", name="Legacy", embedding_model="model-A")
+ with world.service() as service:
+ own = {
+ name: getattr(service, name) for name in _COLLECTION_INDEX_SETTINGS
+ }
+ assert resolve_collection_index_settings(legacy, own) == own
+ assert service._matches_collection_configuration(legacy)
+ # A stored value, such as one a rebuild published, still differs.
+ legacy.chunk_size = service.chunk_size + 1
+ assert not service._matches_collection_configuration(legacy)
+
+
[email protected]("cancel", ["before_check", "after_check"])
+def test_background_rebuild_status_reports_what_publication_did(
+ world, task_check, monkeypatch, cancel
+):
+ """A cancel after publish()'s check cannot stop the publication.
+
+ Its task must then report the new index as in use, not stay
+ ``cancelled``, which reads as "previous index kept". A cancel recorded
+ before that check still cancels.
+ """
+ from contextlib import nullcontext
+
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ before = world.snapshot()
+ routes = task_check.routes
+ check = CollectionRebuild._check_cancelled
+
+ with world.service("model-B") as service:
+
+ def request_cancel():
+ # What the cancel endpoint writes.
+ routes._do_update_task_status(
+ service.username,
+ service.db_password,
+ task_check.task_id,
+ status="cancelled",
+ progress_message="Cancellation requested...",
+ )
+
+ def check_around_a_cancel(is_cancelled):
+ if cancel == "before_check":
+ request_cancel()
+ check(is_cancelled)
+ if cancel == "after_check":
+ request_cancel()
+
+ monkeypatch.setattr(
+ CollectionRebuild,
+ "_check_cancelled",
+ staticmethod(check_around_a_cancel),
+ )
+ monkeypatch.setattr(
+ routes,
+ "_get_rag_service_for_thread",
+ lambda *_args, **_kwargs: nullcontext(service),
+ )
+ service.reconcile_collection_index = MagicMock(
+ return_value={
+ "indexed_documents": 2,
+ "indexed_chunks": 4,
+ "live_vectors": 4,
+ "orphan_vectors": 0,
+ }
+ )
+ routes._background_index_worker(
+ task_check.task_id,
+ world.collection_id,
+ service.username,
+ service.db_password,
+ True,
+ 1,
+ )
+
+ with world.session() as session:
+ task = session.get(task_check.TaskMetadata, task_check.task_id)
+ status, message = task.status, task.progress_message
+ result = (task.metadata_json or {}).get("result")
+ if cancel == "before_check":
+ assert status == "cancelled", (status, message)
+ assert world.snapshot() == before
+ world.assert_no_staging()
+ return
+ assert status == "completed", (status, message)
+ assert message.endswith(routes._LATE_CANCEL_NOTE), message
+ assert result["durable_indexed_documents"] == 2, result
+ assert world.snapshot()["model"] == "model-B"
+ world.assert_searchable("model-B")
+
+
+def test_lost_transaction_in_an_unchanged_empty_rebuild_is_not_published(
+ world, task_check, monkeypatch
+):
+ """The guard fails before the target configuration is recorded.
+
+ With no chunks, no index rows and an unchanged configuration, the state
+ after the guard's rollback equals the target. A target recorded first
+ let _is_published() report the refused publication as committed.
+ """
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ with world.session() as session:
+ session.query(DocumentCollection).filter_by(
+ collection_id=world.collection_id
+ ).delete()
+ session.commit()
+ with world.service("model-A") as service:
+ # Clears the index and stores this service's configuration.
+ assert (
+ service.rebuild_collection([], world.collection_id)["failed"] == 0
+ )
+ validate_sources = CollectionRebuild._validate_sources
+
+ def validate_then_lose_the_transaction(rebuild, session, collection):
+ validate_sources(rebuild, session, collection)
+ with task_check.failing_task_reads():
+ assert not task_check.routes._is_task_cancelled(
+ rebuild.service.username,
+ rebuild.service.db_password,
+ task_check.task_id,
+ )
+
+ monkeypatch.setattr(
+ CollectionRebuild,
+ "_validate_sources",
+ validate_then_lose_the_transaction,
+ )
+ with (
+ world.service("model-A") as service,
+ pytest.raises(RuntimeError, match="lost its transaction"),
+ ):
+ service.rebuild_collection([], world.collection_id)
+ assert world.pending_rebuild_since() is not None
+ world.assert_no_staging()
+
+
+def test_empty_rebuild_commit_failure_keeps_notice_until_a_successful_retry(
+ world,
+):
+ """Unchanged empty contents cannot disguise a rolled-back publication."""
+ with world.session() as session:
+ session.query(DocumentCollection).filter_by(
+ collection_id=world.collection_id
+ ).delete()
+ session.commit()
+ with world.service() as service:
+ service.rebuild_collection([], world.collection_id)
+ before = world.snapshot()
+ assert world.pending_rebuild_since() is None
+ requested = []
+ failed = []
+
+ def fail_the_publication(session):
+ collection = session.get(Collection, world.collection_id)
+ if collection.rebuild_pending_since is not None:
+ requested.append(collection.rebuild_pending_since)
+ elif requested and not failed:
+ failed.append(True)
+ raise RuntimeError("Injected empty publication failure")
+
+ event.listen(world.make_session, "before_commit", fail_the_publication)
+ try:
+ with (
+ world.service() as service,
+ pytest.raises(RuntimeError, match="empty publication failure"),
+ ):
+ service.rebuild_collection([], world.collection_id)
+ finally:
+ event.remove(world.make_session, "before_commit", fail_the_publication)
+
+ assert failed and requested
+ assert world.pending_rebuild_since() == requested[0]
+ assert world.snapshot() == before
+ world.assert_no_staging()
+ with world.service() as service:
+ aggregate = service.rebuild_collection([], world.collection_id)
+ assert aggregate["failed"] == 0
+ assert world.pending_rebuild_since() is None
+ assert world.snapshot() == before
+
+
+def _abandon_a_staged_rebuild(world, service):
+ """Stage one document as a rebuild does, then skip close() like an exit."""
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ rebuild = CollectionRebuild(
+ service,
+ world.collection_id,
+ world.doc_info,
+ session_factory=world.session,
+ )
+ rebuild.write(rebuild.prepare("document-0")["prepared"])
+ with world.session() as session:
+ stage = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=rebuild.stage_name)
+ .one()
+ )
+ stage_path = Path(stage.index_path)
+ assert (
+ session.query(DocumentChunk)
+ .filter_by(collection_name=rebuild.stage_name)
+ .count()
+ )
+ assert stage_path.is_file()
+ return rebuild, stage_path
+
+
+ "operation", ["delete_collection", "delete_collection_index_only"]
+)
+def test_deleting_a_collection_or_its_index_removes_unfinished_rebuilds(
+ world, monkeypatch, operation
+):
+ """Staged chunk rows hold document text; nothing else removes them."""
+ from local_deep_research.research_library.deletion.services import (
+ collection_deletion,
+ )
+
+ monkeypatch.setattr(
+ collection_deletion, "get_user_db_session", world.session
+ )
+ with world.service("model-B") as service:
+ _rebuild, stage_path = _abandon_a_staged_rebuild(world, service)
+ assert world.pending_rebuild_since() is not None
+
+ deletion = collection_deletion.CollectionDeletionService("rebuild-user")
+ result = (
+ deletion.delete_collection(
+ world.collection_id, delete_orphaned_documents=False
+ )
+ if operation == "delete_collection"
+ else deletion.delete_collection_index_only(world.collection_id)
+ )
+
+ assert result["deleted"], result
+ if operation == "delete_collection_index_only":
+ assert world.pending_rebuild_since() is None
+ world.assert_no_staging()
+ assert not stage_path.exists()
+
+
+def test_clearing_an_index_leaves_a_running_rebuild_to_clean_itself(
+ world, monkeypatch
+):
+ """A rebuild in this process holds the rebuild lock and owns its stage."""
+ from local_deep_research.research_library.deletion.services import (
+ collection_deletion,
+ )
+
+ monkeypatch.setattr(
+ collection_deletion, "get_user_db_session", world.session
+ )
+ with world.service("model-B") as service:
+ rebuild, stage_path = _abandon_a_staged_rebuild(world, service)
+ holding = threading.Event()
+ release = threading.Event()
+
+ def hold_the_rebuild_lock():
+ with library_rag_service._hold_collection_lock(
+ "rebuild-user", world.collection_id, purpose="rebuild"
+ ):
+ holding.set()
+ release.wait(30)
+
+ holder = threading.Thread(target=hold_the_rebuild_lock)
+ holder.start()
+ try:
+ assert holding.wait(30)
+ result = collection_deletion.CollectionDeletionService(
+ "rebuild-user"
+ ).delete_collection_index_only(world.collection_id)
+ finally:
+ release.set()
+ holder.join(30)
+
+ assert result["deleted"], result
+ with world.session() as session:
+ assert (
+ session.query(RAGIndex)
+ .filter_by(collection_name=rebuild.stage_name)
+ .count()
+ == 1
+ )
+ assert stage_path.is_file()
diff --git a/tests/research_library/services/test_download_text_quality.py b/tests/research_library/services/test_download_text_quality.py
index 3c989ebc0a..c9ca31efba 100644
--- a/tests/research_library/services/test_download_text_quality.py
+++ b/tests/research_library/services/test_download_text_quality.py
@@ -620,9 +620,10 @@ def test_text_replacement_keeps_index_totals_correct_after_reindex(
vector_index = SimpleNamespace(
index_prepared=lambda **kwargs: SimpleNamespace(added=1)
)
- indexer = SimpleNamespace(
+ indexer = LibraryRAGService.__new__(LibraryRAGService)
+ indexer.__dict__.update(
username=case.service.username,
- db_password=case.service.password,
+ _db_password=case.service.password,
rag_index_record=None,
embedding_model="test",
embedding_provider="sentence_transformers",
@@ -630,7 +631,11 @@ def test_text_replacement_keeps_index_totals_correct_after_reindex(
_embed_texts_cancellable=lambda texts, cancelled: [
[1.0, 0.0] for _ in texts
],
- _get_index_hash=lambda collection, *args: collection,
+ # Match the per-collection hashes seeded by extraction_case so the
+ # real transaction lock resolves the same index as the write path.
+ _get_index_hash=lambda collection, *args: collection.removeprefix(
+ "collection_"
+ ),
_get_index_path=lambda index_hash: (
case.service.library_root / index_hash
),
diff --git a/tests/research_library/services/test_index_documents_parallel.py b/tests/research_library/services/test_index_documents_parallel.py
index 699f2b35ca..12552c12ee 100644
--- a/tests/research_library/services/test_index_documents_parallel.py
+++ b/tests/research_library/services/test_index_documents_parallel.py
@@ -957,6 +957,10 @@ class TestWritePreparedDocumentReindexDelta:
def test_chunk_count_delta_captures_old_chunks_before_merge(self):
import hashlib
+ import numpy as np
+ from local_deep_research.research_library.services.library_rag_service import (
+ _PreparedDocument,
+ )
svc = _make_service()
svc.rag_index_record = MagicMock()
@@ -985,7 +989,8 @@ class TestWritePreparedDocumentReindexDelta:
mock_doc.text_content = body
session = MagicMock()
- # session.query calls (Phase-3 gate runs unconditionally):
+ # session.query first resolves the transaction lock index, then
+ # runs the Phase-3 gate unconditionally:
# 1. DocumentCollection link (gate)
# 2. Document existence (gate)
# 3. RagDocumentStatus existence (gate)
@@ -1002,7 +1007,9 @@ class TestWritePreparedDocumentReindexDelta:
q_existing = make_q(first_val=mock_existing)
q_doc_coll = make_q()
q_rag_index = make_q(first_val=mock_rag_index)
+ index_lookup = make_q(first_val=MagicMock(index_hash="generation"))
session.query.side_effect = [
+ index_lookup,
q_link,
q_doc,
q_gate_status,
@@ -1012,14 +1019,12 @@ class TestWritePreparedDocumentReindexDelta:
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)
+ prepared = _PreparedDocument(
+ document_id="doc-1",
+ collection_id="coll-1",
+ vectors=np.zeros((2, 8), dtype="float32"),
+ chunk_inputs=[MagicMock(), MagicMock()],
+ ) # 2 new chunks (delta = 2 - 5 = -3).
prepared.content_hash = body_hash
prepared.initial_indexed = False
prepared.status_exists = True
diff --git a/tests/research_library/services/test_issue_6559_rag_indexing_lock.py b/tests/research_library/services/test_issue_6559_rag_indexing_lock.py
index 88731555f4..6df85f8028 100644
--- a/tests/research_library/services/test_issue_6559_rag_indexing_lock.py
+++ b/tests/research_library/services/test_issue_6559_rag_indexing_lock.py
@@ -33,6 +33,18 @@ from local_deep_research.research_library.services.library_rag_service import (
from local_deep_research.vector_stores.facade import ChunkInput
+def _mock_session_with_unconfigured_collection():
+ """Model the collection lookup used before indexing existing test data."""
+ session = MagicMock()
+
+ def get(model, identity):
+ assert model is Collection
+ return Collection(id=identity)
+
+ session.get.side_effect = get
+ return session
+
+
class TestRAGIndexingLockDecoupling:
"""Test suite verifying lock decoupling across embedding round-trip."""
@@ -52,6 +64,7 @@ class TestRAGIndexingLockDecoupling:
rag_rec = MagicMock(spec=RAGIndex)
rag_rec.id = 1
rag_rec.index_path = "/tmp/test_index"
+ rag_rec.index_hash = "test_hash"
rag_rec.chunk_count = 0
rag_rec.total_documents = 0
svc.rag_index_record = rag_rec
@@ -108,7 +121,7 @@ class TestRAGIndexingLockDecoupling:
session_active = False
return False
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
def query_side_effect(model):
q = MagicMock()
@@ -192,7 +205,7 @@ class TestRAGIndexingLockDecoupling:
doc_coll.indexed = False
doc_coll.chunk_count = 0
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
mock_session.query.return_value.filter_by.return_value.first.return_value = doc
# Fail during Phase 2 embedding
@@ -254,7 +267,7 @@ class TestRAGIndexingLockDecoupling:
doc_coll.indexed = False
doc_coll.chunk_count = 0
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
def query_side_effect(model):
q = MagicMock()
@@ -332,7 +345,7 @@ class TestRAGIndexingLockDecoupling:
doc_coll.indexed = False
doc_coll.chunk_count = 0
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
def query_side_effect(model):
q = MagicMock()
@@ -415,8 +428,8 @@ class TestRAGIndexingLockDecoupling:
doc_coll.chunk_count = 0
# Phase 1 sees link; Phase 3 sees link deleted (None)
- p1_session = MagicMock()
- p3_session = MagicMock()
+ p1_session = _mock_session_with_unconfigured_collection()
+ p3_session = _mock_session_with_unconfigured_collection()
def p1_query(model):
q = MagicMock()
@@ -515,8 +528,8 @@ class TestRAGIndexingLockDecoupling:
doc_coll.indexed = False
doc_coll.chunk_count = 0
- p1_session = MagicMock()
- p3_session = MagicMock()
+ p1_session = _mock_session_with_unconfigured_collection()
+ p3_session = _mock_session_with_unconfigured_collection()
def p1_query(model):
q = MagicMock()
@@ -604,8 +617,8 @@ class TestRAGIndexingLockDecoupling:
doc_coll = MagicMock(spec=DocumentCollection)
doc_coll.indexed = False
- p1_session = MagicMock()
- p3_session = MagicMock()
+ p1_session = _mock_session_with_unconfigured_collection()
+ p3_session = _mock_session_with_unconfigured_collection()
p1_session.query.return_value.filter_by.return_value.first.return_value = doc
@@ -661,7 +674,7 @@ class TestRAGIndexingLockDecoupling:
def test_write_prepared_document_revalidation_gate(self, mock_service):
"""_write_prepared_document enforces revalidation gate before persisting."""
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
current_doc = MagicMock(spec=Document)
current_doc.text_content = "Post-edit content"
link = MagicMock(spec=DocumentCollection)
@@ -723,7 +736,7 @@ class TestRAGIndexingLockDecoupling:
``_prepare_document`` runs. Phase 3 must create the link and persist
vectors instead of returning skipped.
"""
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
current_doc = MagicMock(spec=Document)
current_doc.text_content = "Orphan research download"
created_link = MagicMock(spec=DocumentCollection)
@@ -800,7 +813,7 @@ class TestRAGIndexingLockDecoupling:
def test_write_prepared_concurrent_unlink_still_skips(self, mock_service):
"""A link present at prepare and gone at write is still a concurrent removal."""
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
current_doc = MagicMock(spec=Document)
current_doc.text_content = "Linked note"
@@ -876,7 +889,7 @@ class TestRAGIndexingLockDecoupling:
doc.extraction_method = None
doc.word_count = 2
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
def query_side_effect(model):
q = MagicMock()
@@ -1048,7 +1061,7 @@ class TestRAGIndexingLockDecoupling:
doc_coll.indexed = True
doc_coll.chunk_count = 5
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
mock_session.query.return_value.filter_by.return_value.first.return_value = doc
class DummyCtx:
@@ -1087,7 +1100,7 @@ class TestRAGIndexingLockDecoupling:
doc_coll = MagicMock(spec=DocumentCollection)
doc_coll.indexed = False
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
# 1st .first() = Document lookup, 2nd .first() = DocumentChunk prior lookup
mock_session.query.return_value.filter_by.return_value.first.side_effect = [
doc,
@@ -1346,7 +1359,7 @@ class TestRAGIndexingLockDecoupling:
snapshot (None) preserves main's unconditional-create behavior
instead of misreading absence as a concurrent unlink.
"""
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
body = "Legacy orphan without snapshots"
current_doc = MagicMock(spec=Document)
current_doc.text_content = body
@@ -1450,8 +1463,9 @@ class TestRAGIndexingLockDecoupling:
q_update = make_q()
q_update.update.return_value = 0
- mock_session = MagicMock()
+ mock_session = _mock_session_with_unconfigured_collection()
mock_session.query.side_effect = [
+ make_q(first_val=mock_service.rag_index_record), # Transaction lock
q_link,
q_doc,
q_gate_status,
@@ -1528,7 +1542,7 @@ class TestRAGIndexingLockDecoupling:
q.first.return_value = first_val
return q
- p1_session = MagicMock()
+ p1_session = _mock_session_with_unconfigured_collection()
p1_session.query.side_effect = {
Document: make_q(doc),
Collection: make_q(MagicMock(spec=Collection)),
diff --git a/tests/research_library/services/test_library_rag_service.py b/tests/research_library/services/test_library_rag_service.py
index 686e3edf48..4d387c13c2 100644
--- a/tests/research_library/services/test_library_rag_service.py
+++ b/tests/research_library/services/test_library_rag_service.py
@@ -376,6 +376,8 @@ class TestLibraryRAGServiceIndexDocument:
def test_index_document_not_found(self, mocker):
"""Returns error when document not found."""
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session.__enter__ = Mock(return_value=mock_session)
mock_session.__exit__ = Mock(return_value=False)
mock_session.query.return_value.filter_by.return_value.first.return_value = None
@@ -425,11 +427,14 @@ class TestLibraryRAGServiceIndexDocument:
mock_doc.text_content = None
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session.__enter__ = Mock(return_value=mock_session)
mock_session.__exit__ = Mock(return_value=False)
- # 1st .first() = Document lookup; 2nd = prior-chunk probe -> None so the
+ # After resolving the generation, Document lookup; 2nd = prior-chunk probe -> None so the
# empty-text branch returns error (no prior chunks to purge).
mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ None, # No existing generation for the transaction lock.
mock_doc,
None,
]
@@ -486,6 +491,8 @@ class TestLibraryRAGServiceIndexDocument:
mock_doc.text_content = "Some text content"
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session.__enter__ = Mock(return_value=mock_session)
mock_session.__exit__ = Mock(return_value=False)
mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc
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 e12dacc7f2..e4b7b790a6 100644
--- a/tests/research_library/services/test_library_rag_service_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_coverage.py
@@ -270,6 +270,8 @@ class TestIndexDocument:
def test_returns_error_when_document_not_found(self, mock_session_ctx):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value.__enter__ = MagicMock(
return_value=mock_session
)
@@ -287,6 +289,8 @@ class TestIndexDocument:
):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value.__enter__ = MagicMock(
return_value=mock_session
)
@@ -295,9 +299,10 @@ class TestIndexDocument:
mock_document = MagicMock()
mock_document.text_content = None
- # 1st .first() = Document lookup; 2nd = prior-chunk probe -> None so the
+ # After resolving the generation, Document lookup; 2nd = prior-chunk probe -> None so the
# empty-text branch returns error (no prior chunks to purge).
mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ None, # No existing generation for the transaction lock.
mock_document,
None,
]
@@ -315,6 +320,8 @@ class TestIndexDocument:
):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value.__enter__ = MagicMock(
return_value=mock_session
)
diff --git a/tests/research_library/services/test_library_rag_service_deep_coverage.py b/tests/research_library/services/test_library_rag_service_deep_coverage.py
index e5589eeb00..374f668993 100644
--- a/tests/research_library/services/test_library_rag_service_deep_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_deep_coverage.py
@@ -584,6 +584,8 @@ class TestIndexDocumentExceptionPath:
):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value = _make_session_ctx(mock_session)
mock_document = MagicMock()
@@ -632,14 +634,17 @@ class TestIndexDocumentExceptionPath:
"""When no DocumentCollection exists, ensure_in_collection is called."""
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value = _make_session_ctx(mock_session)
mock_document = MagicMock()
mock_document.text_content = None # triggers error after dc creation
- # 1st .first() = Document lookup; 2nd = the empty-text branch's
+ # After resolving the generation, Document lookup; 2nd = the empty-text branch's
# prior-chunk probe -> None (no prior chunks, so error, not purge).
mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ None, # No existing generation for the transaction lock.
mock_document,
None,
]
diff --git a/tests/research_library/services/test_library_rag_service_index_coverage.py b/tests/research_library/services/test_library_rag_service_index_coverage.py
index bab1b8eeb2..19312c88dc 100644
--- a/tests/research_library/services/test_library_rag_service_index_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_index_coverage.py
@@ -113,13 +113,16 @@ class TestIndexDocumentNoTextContent:
):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value = _make_session_ctx(mock_session)
mock_doc = _make_document(text_content=None)
- # 1st .first() = Document lookup -> the doc; 2nd = the prior-chunk probe
+ # After resolving the generation, Document lookup -> the doc; 2nd = the prior-chunk probe
# in the empty-text branch -> None (no prior chunks, so error, not purge).
mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ None, # No existing generation for the transaction lock.
mock_doc,
None,
]
@@ -138,13 +141,16 @@ class TestIndexDocumentNoTextContent:
):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value = _make_session_ctx(mock_session)
mock_doc = _make_document(text_content="")
- # 1st .first() = Document lookup -> the doc; 2nd = the prior-chunk probe
+ # After resolving the generation, Document lookup -> the doc; 2nd = the prior-chunk probe
# in the empty-text branch -> None (no prior chunks, so error, not purge).
mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ None, # No existing generation for the transaction lock.
mock_doc,
None,
]
@@ -160,6 +166,8 @@ class TestIndexDocumentNoTextContent:
def test_document_not_found_returns_error(self, mock_session_ctx):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value = _make_session_ctx(mock_session)
def query_side(model):
@@ -183,6 +191,8 @@ class TestIndexDocumentNoTextContent:
):
svc = _make_service()
mock_session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ mock_session.get.return_value = MagicMock(embedding_model=None)
mock_session_ctx.return_value = _make_session_ctx(mock_session)
mock_doc = _make_document()
diff --git a/tests/research_library/services/test_library_rag_service_index_failure.py b/tests/research_library/services/test_library_rag_service_index_failure.py
index 5043fdc944..554f3054af 100644
--- a/tests/research_library/services/test_library_rag_service_index_failure.py
+++ b/tests/research_library/services/test_library_rag_service_index_failure.py
@@ -74,6 +74,8 @@ def test_index_document_not_marked_indexed_when_store_persists_no_embeddings(
svc = _make_service()
session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ session.get.return_value = MagicMock(embedding_model=None)
mock_get_session.return_value = _ctx_yielding(session)
session.query.return_value.filter_by.return_value.first.return_value = (
_make_doc()
diff --git a/tests/research_library/services/test_library_rag_service_rollback.py b/tests/research_library/services/test_library_rag_service_rollback.py
index e44a757019..d2140d4a7b 100644
--- a/tests/research_library/services/test_library_rag_service_rollback.py
+++ b/tests/research_library/services/test_library_rag_service_rollback.py
@@ -77,6 +77,8 @@ def test_index_document_rolls_back_session_on_exception(
svc = _make_service()
session = MagicMock()
+ # This unit fixture has no saved collection configuration.
+ session.get.return_value = MagicMock(embedding_model=None)
mock_get_session.return_value = _ctx_yielding(session)
session.query.return_value.filter_by.return_value.first.return_value = (
diff --git a/tests/research_library/services/test_rag_transaction_ownership.py b/tests/research_library/services/test_rag_transaction_ownership.py
index 91ae86e004..a58ff4fa25 100644
--- a/tests/research_library/services/test_rag_transaction_ownership.py
+++ b/tests/research_library/services/test_rag_transaction_ownership.py
@@ -89,7 +89,16 @@ def rig(tmp_path):
service.username = "local_review"
service._db_password = "test-only"
service.embedding_model = "test-model"
- service.embedding_provider = "test-provider"
+ service.embedding_provider = "sentence_transformers"
+ service.chunk_size = 500
+ service.chunk_overlap = 50
+ service.splitter_type = "recursive"
+ service.text_separators = list(
+ rag_service_module.DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS
+ )
+ service.distance_metric = "cosine"
+ service.normalize_vectors = True
+ service.index_type = "flat"
service.rag_index_record = SimpleNamespace(id=1)
service.text_splitter = MagicMock()
service.text_splitter.split_documents.side_effect = lambda docs: docs
@@ -352,6 +361,39 @@ def test_bulk_entries_reject_before_reading_or_embedding(rig, entry):
)
[email protected]("has_document", [False, True])
+def test_rebuild_preserves_the_callers_uncommitted_transaction(
+ rig, has_document
+):
+ if has_document:
+ add_membership(rig)
+ documents = [("doc", "Doc")] if has_document else []
+ with get_user_db_session("local_review", "test-only") as outer:
+ document = outer.get(Document, "doc")
+ document.title = "Caller edit"
+ outer.flush()
+ caught = None
+ try:
+ rig.service.rebuild_collection(documents, "collection")
+ except Exception as exc:
+ caught = exc
+
+ assert outer.in_transaction(), (
+ "rebuild consumed the caller's transaction"
+ )
+ assert document.title == "Caller edit"
+ with rig.factory() as observer:
+ assert observer.get(Document, "doc").title == "Original"
+ assert isinstance(caught, RuntimeError)
+ assert str(caught) == SCOPE_ERROR
+ assert rig.observations == []
+ rig.service._get_vector_index.assert_not_called()
+ outer.commit()
+
+ with rig.factory() as check:
+ assert check.get(Document, "doc").title == "Caller edit"
+
+
def test_background_index_worker_indexes_outside_its_setup_scope(rig):
"""The normal collection Index action must not lend its setup scope.
@@ -370,6 +412,11 @@ def test_background_index_worker_indexes_outside_its_setup_scope(rig):
# Indexed before, so the worker skips first-index metadata capture.
collection = setup.query(Collection).filter_by(id="collection").one()
collection.embedding_model = "test-model"
+ collection.embedding_model_type = (
+ EmbeddingProvider.SENTENCE_TRANSFORMERS
+ )
+ collection.chunk_size = 500
+ collection.chunk_overlap = 50
setup.add(
TaskMetadata(
task_id="task",
@@ -442,6 +489,7 @@ _INDEXING_METHODS = frozenset(
"index_documents_parallel",
"index_all_documents",
"index_documents_batch",
+ "rebuild_collection",
"_index_one",
"_index_document_locked",
"_prepare_document",
diff --git a/tests/research_library/services/test_reconcile_collection_index.py b/tests/research_library/services/test_reconcile_collection_index.py
index 822b718f5b..706d7edcca 100644
--- a/tests/research_library/services/test_reconcile_collection_index.py
+++ b/tests/research_library/services/test_reconcile_collection_index.py
@@ -218,13 +218,15 @@ class TestReconcilePreservesIndexedAt:
rag_index_q = _build_query_mock()
session = MagicMock()
# Order of session.query() calls in production:
- # 0. RAGIndex no-op write claim (rag_index_q)
- # 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)
+ # 0. Current generation lookup for the collection lock
+ # 1. RAGIndex no-op write claim (rag_index_q)
+ # 2. DocumentChunk rows (chunk_q)
+ # 3. RagDocumentStatus prior indexed_at (prior_status_q)
+ # 4. DocumentCollection links (empty_q)
+ # 5. RagDocumentStatus bulk delete (empty_q — same shape)
+ # 6. RAGIndex row (rag_index_q)
session.query.side_effect = [
+ _build_query_mock(first_row=MagicMock(index_hash="generation")),
rag_index_q, # SQLite write claim before reading chunks
chunk_q,
prior_status_q,
@@ -283,6 +285,7 @@ class TestReconcilePartialDurabilityAndOrphans:
rag_index_q = _build_query_mock()
session = MagicMock()
session.query.side_effect = [
+ _build_query_mock(first_row=MagicMock(index_hash="generation")),
rag_index_q, # SQLite write claim before reading chunks
chunk_q,
empty_q,
@@ -318,6 +321,7 @@ class TestReconcilePartialDurabilityAndOrphans:
rag_index_q = _build_query_mock()
session = MagicMock()
session.query.side_effect = [
+ _build_query_mock(first_row=MagicMock(index_hash="generation")),
rag_index_q, # SQLite write claim before reading chunks
chunk_q,
empty_q,
diff --git a/tests/research_library/services/test_search_dimension_mismatch.py b/tests/research_library/services/test_search_dimension_mismatch.py
index 6bdab5114e..770d90de8d 100644
--- a/tests/research_library/services/test_search_dimension_mismatch.py
+++ b/tests/research_library/services/test_search_dimension_mismatch.py
@@ -70,7 +70,9 @@ class _RaisingVectorIndex:
def _bare_service() -> LibraryRAGService:
"""A ``LibraryRAGService`` with ``__init__`` bypassed (only search() runs)."""
- return object.__new__(LibraryRAGService)
+ service = object.__new__(LibraryRAGService)
+ service.username = "search-user"
+ return service
# --- the real FaissVectorStore really raises ValueError("...dimension...") ----
diff --git a/tests/security/test_library_rag_security_fastapi.py b/tests/security/test_library_rag_security_fastapi.py
index 2222be2c63..d9f2e35e89 100644
--- a/tests/security/test_library_rag_security_fastapi.py
+++ b/tests/security/test_library_rag_security_fastapi.py
@@ -1254,6 +1254,13 @@ class TestIndexingErrorAllowlistMatchesService:
for text in _SAFE_INDEXING_ERRORS:
assert _client_indexing_error(text) == text
+ for detail in (
+ f"{text}: /srv/private.db",
+ f"/srv/private.db: {text}",
+ ):
+ assert _client_indexing_error(detail) == (
+ "Indexing failed. Check the server logs for details."
+ )
for template in _WITHHELD_SERVICE_ERRORS:
assert _client_indexing_error(
template.replace("{}", "OperationalError")
diff --git a/tests/web/routers/test_rag_indexing_admission.py b/tests/web/routers/test_rag_indexing_admission.py
index 24cff8f44d..b3e74051b9 100644
--- a/tests/web/routers/test_rag_indexing_admission.py
+++ b/tests/web/routers/test_rag_indexing_admission.py
@@ -12,7 +12,7 @@ from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from local_deep_research.database.models import Base
-from local_deep_research.database.models.library import Collection
+from local_deep_research.database.models.library import Collection, RAGIndex
from local_deep_research.database.models.queue import TaskMetadata
from local_deep_research.web.routers import rag
@@ -24,7 +24,12 @@ def admission(tmp_path, monkeypatch):
connect_args={"check_same_thread": False},
)
Base.metadata.create_all(
- engine, tables=[Collection.__table__, TaskMetadata.__table__]
+ engine,
+ tables=[
+ Collection.__table__,
+ RAGIndex.__table__,
+ TaskMetadata.__table__,
+ ],
)
sessions = sessionmaker(bind=engine)
@@ -154,10 +159,10 @@ def test_collection_indexers_exclude_each_other(
json.loads(next(stream).removeprefix("data: "))["type"] == "start"
)
- reset = Mock(
- side_effect=AssertionError("a competing run must not reset the index")
+ rebuild = Mock(
+ side_effect=AssertionError("a competing run must not rebuild the index")
)
- monkeypatch.setattr(rag, "_reset_collection_for_reindex", reset)
+ monkeypatch.setattr(admission.service, "rebuild_collection", rebuild)
try:
if second == "background":
refused = rag._start_background_index_sync(
@@ -174,7 +179,7 @@ def test_collection_indexers_exclude_each_other(
}
finally:
contender.close()
- reset.assert_not_called()
+ rebuild.assert_not_called()
admission.service.index_documents_parallel.assert_not_called()
finally:
if stream is not None:
diff --git a/tests/web/routers/test_rag_indexing_pipeline.py b/tests/web/routers/test_rag_indexing_pipeline.py
index 51ddc80c08..48b349e783 100644
--- a/tests/web/routers/test_rag_indexing_pipeline.py
+++ b/tests/web/routers/test_rag_indexing_pipeline.py
@@ -5,7 +5,7 @@ Everything here drives REAL production code: a real ``LibraryRAGService``
writing real FAISS files under ``LDR_DATA_DIR``, real ``DocumentChunk`` /
``RAGIndex`` / ``RagDocumentStatus`` rows against the real schema, and the
router's real ``_background_index_worker`` /
-``_reset_collection_for_reindex`` / ``_start_background_index_sync`` /
+``_start_background_index_sync`` /
``cancel_indexing`` entry points. The ONLY faked boundary is the
embedding backend (a deterministic, network-free ``Embeddings``) --
mirroring the real-components harness in
@@ -15,12 +15,9 @@ No embedding model or LLM is ever loaded or called.
Four claims are examined. Open defects use *strict xfail* markers, with
passing controls beside them so the harness cannot mask a failure:
-1. **force-reindex is destroy-then-rebuild, not non-destructive.**
- ``_reset_collection_for_reindex`` deletes the chunk rows, deletes the
- ``RAGIndex`` rows and unlinks the ``.faiss`` files BEFORE a single new
- vector is written, and commits. When the indexing step then fails the
- previously-indexed content is gone: the collection is silently
- unsearchable until some later reindex succeeds.
+1. **Failed force-reindex preserves the published generation.** Replacement
+ chunks and files stay under a staging identity until all documents are
+ ready. The previous searchable content survives failed preparation.
2. **Chunking settings reach indexing but not query time** (the mechanism
behind #5745). ``_get_index_hash`` covers ``splitter_type`` and
@@ -42,7 +39,7 @@ passing controls beside them so the harness cannot mask a failure:
4. **Concurrent collection indexing is mutually excluded.** The shared
admission gate checks both streaming workers and background tasks before
- a second run can reach the destructive reset helper.
+ a second run can start preparing a replacement.
Plus a cancellation guard: ``cancel_indexing`` scans ALL in-progress tasks
(``.all()``, as ``start_background_index`` does) instead of ``.first()``, so
@@ -156,9 +153,7 @@ def world(tmp_path, monkeypatch, mocker):
# Production turns foreign keys ON for every connection
# (``sqlcipher_utils._configure_connection``), and
- # ``_reset_collection_for_reindex`` relies on it: it deletes only the
- # ``RAGIndex`` rows and documents that ``RagDocumentStatus``
- # "cascade-deletes via FK". SQLite defaults the pragma OFF, so without
+ # RAG index deletion relies on cascading RagDocumentStatus rows. SQLite defaults the pragma OFF, so without
# this the harness would silently diverge from production on exactly
# the behaviour under test.
@event.listens_for(engine, "connect")
@@ -349,8 +344,7 @@ def test_harness_indexes_and_searches_real_components(world, seeded):
class TestForceReindexDurabilityOnFailure:
- """``_background_index_worker(force_reindex=True)`` commits the deletion
- of the previous index BEFORE embedding anything."""
+ """A background rebuild keeps the previous index until publication."""
@staticmethod
def _seed_index(session, collection_id, document_id):
@@ -362,16 +356,10 @@ class TestForceReindexDurabilityOnFailure:
assert files and all(p.exists() for p in files)
return files
- def test_force_reindex_prologue_runs_before_any_indexing_call(
+ def test_force_reindex_preserves_published_state_during_preparation(
self, world, seeded
):
- """Control for the xfail below: pins the ORDER that causes it.
-
- The reset is committed and the ``.faiss`` files unlinked while the
- indexing step has not been entered yet -- captured from inside the
- stubbed ``index_documents_parallel``, so this is the worker's real
- sequencing, not an inference from reading it.
- """
+ """Inspect the real worker at the replacement preparation boundary."""
from local_deep_research.web.routers import rag as rag_mod
session = world
@@ -403,32 +391,9 @@ class TestForceReindexDurabilityOnFailure:
)
assert svc.index_documents_parallel.call_count == 1
- assert observed["chunks"] == 0, (
- "the old chunk rows are already deleted and committed by the "
- "time the first document is handed to the indexer"
- )
- assert observed["files_present"] == [False for _ in files], (
- "the old .faiss file is already unlinked by the time the first "
- "document is handed to the indexer"
- )
+ assert observed["chunks"] > 0
+ assert observed["files_present"] == [True for _ in files]
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "force-reindex is destroy-then-rebuild with no staging area. "
- "_background_index_worker calls _reset_collection_for_reindex "
- "(DELETE DocumentChunk + DELETE RAGIndex + indexed=False), "
- "COMMITS, then _unlink_reindex_faiss_files -- all before "
- "index_documents_parallel runs. Any failure in the indexing "
- "step (backend down, egress policy, crash, OOM) therefore "
- "leaves the collection with zero searchable content; "
- "get_rag_stats reports 0 indexed and search returns [] until "
- "some later reindex succeeds. Fix by building the new index "
- "under a temporary hash and swapping it in only after the "
- "indexing step reports success, or by deferring the reset "
- "until the first document has been written."
- ),
- )
def test_failed_force_reindex_leaves_previous_content_searchable(
self, world, seeded
):
@@ -1426,48 +1391,6 @@ class TestConcurrentIndexingOfOneCollection:
f"already in flight was admitted: {result!r}"
)
- def test_reset_prologue_destroys_committed_work_of_another_run(
- self, world, seeded
- ):
- """The raw reset helper is destructive; callers must hold admission."""
- from local_deep_research.web.routers.rag import (
- _reset_collection_for_reindex,
- _unlink_reindex_faiss_files,
- )
-
- session = world
- collection_id, document_id = seeded
- collection_name = f"collection_{collection_id}"
-
- run_a = _make_service()
- assert (
- run_a.index_document(document_id, collection_id)["status"]
- == "success"
- )
- files = _stored_index_files(session, collection_name)
- assert files and all(p.exists() for p in files)
- assert any(
- SECRET in h.text for h in run_a.search(QUERY, collection_id, 5)
- )
-
- paths = _reset_collection_for_reindex(session, collection_id)
- session.commit()
- _unlink_reindex_faiss_files(paths)
-
- assert (
- session.query(DocumentChunk)
- .filter_by(collection_name=collection_name)
- .count()
- == 0
- )
- assert (
- session.query(RagDocumentStatus)
- .filter_by(collection_id=collection_id)
- .count()
- == 0
- )
- assert not any(p.exists() for p in files)
-
# ---------------------------------------------------------------------------
# (5) cancellation: the in-progress scan that start_background_index fixed
@@ -1531,3 +1454,100 @@ class TestCancelIndexingTaskLookup:
"the active indexing task for this collection was left in "
f"{mine.status!r}; the worker keeps running after a 'cancel'"
)
+
+
+class TestCollectionRebuildNotice:
+ def test_notice_survives_expired_and_new_incremental_tasks(
+ self, world, seeded
+ ):
+ from datetime import timedelta
+ from local_deep_research.database.queue_service import UserQueueService
+ from local_deep_research.web.routers import rag as rag_mod
+
+ collection_id, document_id = seeded
+ with _make_service() as service:
+ service.index_document(document_id, collection_id)
+ pending = datetime(2025, 1, 1, tzinfo=UTC)
+ world.get(Collection, collection_id).rebuild_pending_since = pending
+ task_id = _seed_task(world, "old-cancelled", collection_id, "cancelled")
+ task = world.query(TaskMetadata).filter_by(task_id=task_id).one()
+ task.completed_at = datetime.now(UTC) - timedelta(days=8)
+ world.commit()
+ UserQueueService(world).cleanup_old_tasks()
+ assert world.query(TaskMetadata).count() == 0
+ status = rag_mod.get_index_status(
+ _fake_request(), collection_id, USERNAME
+ )
+ assert status["status"] == "idle"
+ assert status["rebuild_pending_since"] == pending.isoformat()
+ assert status["has_published_index"] is True
+ assert status["index_last_updated_at"] is not None
+ _seed_task(world, "incremental", collection_id, "completed")
+ status = rag_mod.get_index_status(
+ _fake_request(), collection_id, USERNAME
+ )
+ assert status["force_reindex"] is False
+ assert status["rebuild_pending_since"] == pending.isoformat()
+ documents = rag_mod.get_collection_documents(
+ _fake_request(), collection_id, USERNAME
+ )
+ assert (
+ documents["collection"]["rebuild_pending_since"]
+ == pending.isoformat()
+ )
+
+ def test_cancel_status_waits_for_worker_and_reports_publication(
+ self, world, seeded
+ ):
+ from local_deep_research.web.routers import rag as rag_mod
+
+ collection_id, _ = seeded
+ task_id = _seed_task(world, "late-publication", collection_id)
+ task = world.query(TaskMetadata).filter_by(task_id=task_id).one()
+ task.metadata_json = {
+ "collection_id": collection_id,
+ "force_reindex": True,
+ }
+ world.commit()
+ key = (USERNAME, collection_id)
+ with rag_mod._active_sse_indexers_lock:
+ rag_mod._active_background_indexers[key] = task_id
+ try:
+ assert rag_mod.cancel_indexing(
+ _fake_request(), collection_id, USERNAME
+ )["success"]
+ status = rag_mod.get_index_status(
+ _fake_request(), collection_id, USERNAME
+ )
+ assert status["status"] == "cancelled"
+ assert status["worker_active"] is True
+ assert status["force_reindex"] is True
+ assert status["has_published_index"] is False
+ rag_mod._do_update_task_status(
+ USERNAME,
+ DB_PASSWORD,
+ task_id,
+ status="completed",
+ progress_message="Rebuild complete.",
+ published_rebuild=True,
+ )
+ finally:
+ rag_mod._unregister_background_indexer(
+ USERNAME, collection_id, task_id
+ )
+ status = rag_mod.get_index_status(
+ _fake_request(), collection_id, USERNAME
+ )
+ assert status["status"] == "completed"
+ assert status["worker_active"] is False
+ assert "new index is in use" in status["progress_message"]
+ # A stale cancellation must never rewrite the published outcome.
+ rag_mod._do_update_task_status(
+ USERNAME, DB_PASSWORD, task_id, status="cancelled"
+ )
+ assert (
+ rag_mod.get_index_status(_fake_request(), collection_id, USERNAME)[
+ "status"
+ ]
+ == "completed"
+ )
diff --git a/tests/web/routers/test_rag_reindex_commit_then_unlink.py b/tests/web/routers/test_rag_reindex_commit_then_unlink.py
index bfc8ae6c76..a5d40c8d86 100644
--- a/tests/web/routers/test_rag_reindex_commit_then_unlink.py
+++ b/tests/web/routers/test_rag_reindex_commit_then_unlink.py
@@ -1,65 +1,23 @@
-"""Force-reindex: ONE commit, and the FAISS files unlinked only AFTER it.
-
-Ported from ``tests/research_library/routes/test_rag_routes_gaps_coverage.py``
-(``TestCommitOnceThenUnlinkAfterCommit``), deleted in the Flask->FastAPI
-migration. Nothing on the branch replaced it: ``_unlink_reindex_faiss_files``
-appears in no test, and ``grep`` for a recorded ``["commit", "unlink"]`` order
-across ``tests/`` returns nothing.
-
-The property, at all three hand-copied call sites (``index_all``,
-``index_collection``, ``_background_index_worker``):
-
-1. The new embedding metadata and the force-reindex reset land in ONE
- ``db_session.commit()``. Two commits leave a window in which the
- Collection carries the NEW embedding config while the OLD ``RAGIndex``
- row and its FAISS file (built with the old config) still exist -- a
- config/index mismatch that surfaces as silently wrong search results.
-2. ``_unlink_reindex_faiss_files`` runs AFTER that commit. Unlinking first
- orphans the files: the ``RAGIndex`` row referencing them was deleted by
- the reset, and if the transaction then rolls back the row comes back
- pointing at files that are already gone.
-
-Both halves are invisible in the response -- the SSE body and the task
-status are identical either way -- so they are pinned structurally, by
-recording the call sequence, the technique
-``tests/web/test_pagination_bounds.py`` uses for the same reason.
-
-Parametrized per site rather than bundled: the three blocks are duplicated
-source, so a first failing assert must not mask a regression at the other
-two.
+"""Routes delegate full replacements without mutating the published state.
+
+Real commit/rollback and post-commit file removal are exercised by
+services/test_collection_rebuild.py. These tests pin the three entry points,
+their incremental controls, error responses and short setup-session lifetime.
"""
import json
-from contextlib import ExitStack, contextmanager
+from contextlib import contextmanager
from unittest.mock import MagicMock, Mock, patch
import pytest
from starlette.requests import Request
-from local_deep_research.research_library.deletion.utils.cascade_helper import (
- RemoteVectorStoreDropError,
-)
from local_deep_research.web.routers import rag as rag_module
_DB_CTX = "local_deep_research.database.session_context"
_DB_UTILS = "local_deep_research.utilities.db_utils"
_SESSION_PASSWORDS = "local_deep_research.database.session_passwords"
-
-FAISS_PATHS = ["/tmp/coll-1.faiss", "/tmp/coll-1.faiss.ids"]
-
-# What the mocked settings manager returns from ``get_all_settings()``. Each
-# force-reindex site must hand exactly this object to the reset: it selects
-# the user's vector-store provider (and carries its connection config), and
-# without it the cascade silently resolves the global default provider
-# (#5765).
-SETTINGS_SNAPSHOT = {
- "local_search_vector_store_provider": {"value": "some_remote_store"}
-}
-
-
-# ---------------------------------------------------------------------------
-# Harness
-# ---------------------------------------------------------------------------
+SETTINGS_SNAPSHOT = {}
def _request(path="/library/api/rag/index-all", query_string=b""):
@@ -75,21 +33,12 @@ def _request(path="/library/api/rag/index-all", query_string=b""):
)
-def _collection():
- collection = Mock()
- collection.id = "coll-1"
- collection.name = "Test"
- # Not None, so only ``force_reindex`` can drive the metadata write --
- # otherwise the "collection has no embedding model yet" arm would fire
- # too and the single-commit assertion would be ambiguous.
- collection.embedding_model = "already-set"
- return collection
-
-
def _db_session():
session = MagicMock()
+ collection = Mock(id="coll-1", embedding_model="already-set")
+ collection.name = "Test"
session.query.return_value.filter_by.return_value.first.return_value = (
- _collection()
+ collection
)
return session
@@ -102,10 +51,9 @@ def _settings_manager():
def _drain(response):
- """Consume an SSE ``StreamingResponse`` so its generator actually runs."""
import asyncio
- async def _collect():
+ async def collect():
chunks = []
async for chunk in response.body_iterator:
chunks.append(
@@ -113,525 +61,123 @@ def _drain(response):
)
return b"".join(chunks).decode()
- return asyncio.run(_collect())
+ return asyncio.run(collect())
-@contextmanager
-def _reindex_recorder(db_session, extra=()):
- """Record the order of ``commit`` and ``unlink`` around the reset."""
- call_order = []
- db_session.commit.side_effect = lambda: call_order.append("commit")
-
- def record_unlink(paths):
- call_order.append("unlink")
+ "site", ["index_all", "index_collection", "background"]
+)
[email protected]("force", [False, True])
[email protected]("failed", [False, True])
+def test_routes_use_the_rebuild_boundary_without_early_metadata_writes(
+ site, force, failed
+):
+ db = _db_session()
+ service = MagicMock()
+ service.__enter__.return_value = service
+ depth = 0
+ aggregate = {
+ "successful": 1,
+ "skipped": 0,
+ "failed": 0,
+ "errors": [],
+ "results": {"doc-1": {"status": "success"}},
+ "cancelled": False,
+ "total": 1,
+ }
+ service.reconcile_collection_index.return_value = {
+ "indexed_documents": 1,
+ "indexed_chunks": 1,
+ "live_vectors": 1,
+ "orphan_vectors": 0,
+ }
@contextmanager
- def fake_session(*args, **kwargs):
- yield db_session
-
- settings_manager = _settings_manager()
- patches = [
- patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
- # index_all imports get_settings_manager function-locally from
- # db_utils; index_collection uses rag.py's module-level import.
+ def session(*_args, **_kwargs):
+ nonlocal depth
+ depth += 1
+ try:
+ yield db
+ finally:
+ depth -= 1
+
+ def run(doc_info, collection_id, **kwargs):
+ assert depth == 0, "Embedding must not hold the route's setup session"
+ assert doc_info == [("doc-1", "First")]
+ assert collection_id == "coll-1"
+ if failed:
+ raise RuntimeError("Embedding backend unavailable")
+ if kwargs.get("progress_callback"):
+ kwargs["progress_callback"](1, 1, "First", "success")
+ return aggregate
+
+ selected = (
+ service.rebuild_collection
+ if force
+ else service.index_documents_parallel
+ )
+ selected.side_effect = run
+ doc = Mock(id="doc-1", filename="First", title="First")
+ with (
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=session),
patch(
f"{_DB_UTILS}.get_settings_manager",
- return_value=settings_manager,
+ return_value=_settings_manager(),
),
patch.object(
- rag_module, "get_settings_manager", return_value=settings_manager
+ rag_module, "get_settings_manager", return_value=_settings_manager()
),
- patch.object(rag_module, "_store_collection_embedding_metadata"),
+ patch.object(rag_module, "get_rag_service", return_value=service),
patch.object(
- rag_module,
- "_reset_collection_for_reindex",
- return_value=list(FAISS_PATHS),
+ rag_module, "_get_rag_service_for_thread", return_value=service
),
patch.object(
- rag_module,
- "_unlink_reindex_faiss_files",
- side_effect=record_unlink,
- ),
- patch.object(rag_module, "_query_documents_to_index", return_value=[]),
- *extra,
- ]
- started = [p.start() for p in patches]
- reset_mock, unlink_mock = started[4], started[5]
- try:
- yield call_order, reset_mock, unlink_mock
- finally:
- for p in reversed(patches):
- p.stop()
-
-
-# ---------------------------------------------------------------------------
-# One runner per call site
-# ---------------------------------------------------------------------------
-
-
-def _run_index_all(db_session):
- with _reindex_recorder(
- db_session,
- extra=[
- patch.object(
- rag_module, "get_rag_service", return_value=MagicMock()
- )
- ],
- ) as (call_order, reset_mock, unlink_mock):
- response = rag_module.index_all(
- _request(query_string=b"collection_id=coll-1&force_reindex=true"),
- username="alice",
- )
- _drain(response)
- # The reset is fed the handler's own authenticated `username`
- # parameter directly (not read back off the RAG service object) --
- # see rag.py's docstring on why a server-backed vector store needs
- # it to derive the remote collection name -- and the user's settings
- # snapshot, captured on the request thread (#5765).
- reset_mock.assert_called_once_with(
- db_session,
- "coll-1",
- "alice",
- settings_snapshot=SETTINGS_SNAPSHOT,
- )
- unlink_mock.assert_called_once_with(FAISS_PATHS)
- return call_order, db_session.commit.call_count
-
-
-def _run_index_collection(db_session):
- with _reindex_recorder(
- db_session,
- extra=[
- patch.object(
- rag_module, "get_rag_service", return_value=MagicMock()
- ),
- patch(
- f"{_SESSION_PASSWORDS}.session_password_store",
- Mock(get_session_password=Mock(return_value=None)),
- ),
- ],
- ) as (call_order, reset_mock, unlink_mock):
- response = rag_module.index_collection(
- _request(
- path="/library/api/collections/coll-1/index",
- query_string=b"force_reindex=true",
- ),
- "coll-1",
- username="alice",
- )
- _drain(response)
- # See _run_index_all: the reset is fed the authenticated `username`
- # parameter directly, and the settings snapshot.
- reset_mock.assert_called_once_with(
- db_session,
- "coll-1",
- "alice",
- settings_snapshot=SETTINGS_SNAPSHOT,
- )
- unlink_mock.assert_called_once_with(FAISS_PATHS)
- return call_order, db_session.commit.call_count
-
-
-def _run_background_worker(db_session):
- service = MagicMock()
- service.__enter__ = Mock(return_value=service)
- service.__exit__ = Mock(return_value=False)
-
- with _reindex_recorder(
- db_session,
- extra=[
- patch.object(
- rag_module, "_get_rag_service_for_thread", return_value=service
- ),
- patch.object(rag_module, "_update_task_status"),
- ],
- ) as (call_order, reset_mock, unlink_mock):
- # The worker cannot build a snapshot itself (#3453); the start route
- # captures one and hands it over -- see
- # test_background_start_captures_the_settings_snapshot below.
- rag_module._background_index_worker(
- "task-1",
- "coll-1",
- "alice",
- "pw",
- force_reindex=True,
- settings_snapshot=SETTINGS_SNAPSHOT,
- )
- # See _run_index_all: the reset is fed the authenticated `username`
- # parameter directly, and the snapshot it was handed.
- reset_mock.assert_called_once_with(
- db_session,
- "coll-1",
- "alice",
- settings_snapshot=SETTINGS_SNAPSHOT,
- )
- unlink_mock.assert_called_once_with(FAISS_PATHS)
- return call_order, db_session.commit.call_count
-
-
-RUNNERS = {
- "index_all": _run_index_all,
- "index_collection": _run_index_collection,
- "background_worker": _run_background_worker,
-}
-
-
-# ===========================================================================
-# The property
-# ===========================================================================
-
-
[email protected]("site", sorted(RUNNERS))
-def test_the_reindex_commits_once_then_unlinks(site):
- call_order, commit_count = RUNNERS[site](_db_session())
-
- assert call_order == ["commit", "unlink"], (
- f"{site}: the metadata write + reset must be committed BEFORE the "
- "FAISS files are unlinked -- unlinking first orphans files a "
- f"rolled-back transaction would still reference. Got: {call_order}"
- )
- assert commit_count == 1, (
- f"{site}: the embedding metadata and the reset must land in ONE "
- "commit; committing the config separately leaves the new config "
- "live alongside the old index. Got "
- f"{commit_count} commits"
- )
-
-
[email protected]("site", sorted(RUNNERS))
-def test_nothing_is_reset_or_unlinked_without_force_reindex(site):
- """Discriminator: the reset and the unlink belong to ``force_reindex``
- alone. An ordinary incremental index that dropped the collection's chunks
- and deleted its FAISS file would destroy a working index on every run.
- """
- db_session = _db_session()
- service = MagicMock()
- service.__enter__ = Mock(return_value=service)
- service.__exit__ = Mock(return_value=False)
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield db_session
-
- with (
- patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
- patch(
- f"{_DB_UTILS}.get_settings_manager",
- return_value=_settings_manager(),
- ),
- patch.object(rag_module, "_store_collection_embedding_metadata"),
- patch.object(rag_module, "_reset_collection_for_reindex") as reset_mock,
- patch.object(rag_module, "_unlink_reindex_faiss_files") as unlink_mock,
- patch.object(rag_module, "_query_documents_to_index", return_value=[]),
- patch.object(rag_module, "get_rag_service", return_value=MagicMock()),
+ rag_module, "_store_collection_embedding_metadata"
+ ) as store,
patch.object(
- rag_module, "_get_rag_service_for_thread", return_value=service
+ rag_module,
+ "_query_documents_to_index",
+ return_value=[(Mock(), doc)],
),
- patch.object(rag_module, "_update_task_status"),
+ patch.object(rag_module, "_register_sse_indexer", return_value=True),
+ patch.object(rag_module, "_update_task_status") as status,
+ patch.object(rag_module, "_is_task_cancelled", return_value=False),
patch(
f"{_SESSION_PASSWORDS}.session_password_store",
Mock(get_session_password=Mock(return_value=None)),
),
):
- if site == "index_all":
- _drain(
- rag_module.index_all(
- _request(query_string=b"collection_id=coll-1"),
- username="alice",
- )
- )
- elif site == "index_collection":
- _drain(
- rag_module.index_collection(
- _request(path="/library/api/collections/coll-1/index"),
- "coll-1",
- username="alice",
- )
- )
- else:
+ if site == "background":
rag_module._background_index_worker(
- "task-1", "coll-1", "alice", "pw", force_reindex=False
+ "task-1", "coll-1", "alice", "pw", force
)
-
- reset_mock.assert_not_called()
- # Called with the empty list the no-force path produces -- never with
- # paths to delete.
- for call in unlink_mock.call_args_list:
- assert call.args[0] == [], (
- f"{site}: an incremental index must not unlink FAISS files: "
- f"{call.args[0]}"
- )
-
-
-# ===========================================================================
-# A failed remote drop surfaces retry guidance, not a generic internal error
-# (#5765 R5) -- reusing the same ``_reindex_recorder``/RUNNERS harness above,
-# just swapping the reset's ``return_value`` for a ``side_effect`` that
-# raises the way ``CascadeHelper.delete_rag_indices_for_collection`` does
-# when the vector store is unreachable.
-# ===========================================================================
-
-
-def _run_with_failed_drop(site, db_session, error=None):
- """Drive ``site`` with ``_reset_collection_for_reindex`` raising
- ``error`` (by default a retryable ``RemoteVectorStoreDropError``), and
- return what the caller sees: the drained SSE body for the two routes, or
- the ``_update_task_status`` mock for the background worker.
- """
- if error is None:
- error = RemoteVectorStoreDropError("no route to host", retryable=True)
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield db_session
-
- with ExitStack() as stack:
- stack.enter_context(
- patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session)
- )
- stack.enter_context(
- patch(
- f"{_DB_UTILS}.get_settings_manager",
- return_value=_settings_manager(),
+ assert status.call_args.kwargs["status"] == (
+ "failed" if failed else "completed"
)
- )
- stack.enter_context(
- patch.object(rag_module, "_store_collection_embedding_metadata")
- )
- stack.enter_context(
- patch.object(
- rag_module,
- "_reset_collection_for_reindex",
- side_effect=error,
- )
- )
- stack.enter_context(
- patch.object(rag_module, "_unlink_reindex_faiss_files")
- )
- stack.enter_context(
- patch.object(
- rag_module, "_query_documents_to_index", return_value=[]
- )
- )
-
- if site == "index_all":
- stack.enter_context(
- patch.object(
- rag_module, "get_rag_service", return_value=MagicMock()
- )
- )
- return _drain(
- rag_module.index_all(
- _request(
- query_string=b"collection_id=coll-1&force_reindex=true"
- ),
- username="alice",
- )
- )
- if site == "index_collection":
- stack.enter_context(
- patch.object(
- rag_module, "get_rag_service", return_value=MagicMock()
- )
- )
- stack.enter_context(
- patch(
- f"{_SESSION_PASSWORDS}.session_password_store",
- Mock(get_session_password=Mock(return_value=None)),
- )
+ else:
+ request = _request(
+ query_string=f"collection_id=coll-1&force_reindex={str(force).lower()}".encode()
)
- return _drain(
- rag_module.index_collection(
- _request(
- path="/library/api/collections/coll-1/index",
- query_string=b"force_reindex=true",
- ),
- "coll-1",
- username="alice",
+ response = (
+ rag_module.index_all(request, username="alice")
+ if site == "index_all"
+ else rag_module.index_collection(
+ request, "coll-1", username="alice"
)
)
- service = MagicMock()
- service.__enter__ = Mock(return_value=service)
- service.__exit__ = Mock(return_value=False)
- stack.enter_context(
- patch.object(
- rag_module,
- "_get_rag_service_for_thread",
- return_value=service,
- )
- )
- status_mock = stack.enter_context(
- patch.object(rag_module, "_update_task_status")
- )
- rag_module._background_index_worker(
- "task-1", "coll-1", "alice", "pw", force_reindex=True
- )
- return status_mock
-
-
[email protected]("site", ["index_all", "index_collection"])
-def test_sse_surfaces_retry_guidance_when_remote_drop_fails(site):
- body = _run_with_failed_drop(site, _db_session())
-
- events = _sse_events(body)
- error_events = [e for e in events if e.get("type") == "error"]
- assert len(error_events) == 1, events
- assert (
- "Retry once the vector store is available" in error_events[0]["error"]
- )
- assert "internal error" not in error_events[0]["error"].lower(), (
- f"{site}: a failed remote drop must not fall through to the "
- f"generic catch-all message: {error_events[0]['error']}"
+ events = _sse_events(_drain(response))
+ assert events[-1]["type"] == ("error" if failed else "complete")
+ selected.assert_called_once()
+ other = (
+ service.index_documents_parallel
+ if force
+ else service.rebuild_collection
)
-
-
-def test_background_worker_surfaces_retry_guidance_when_remote_drop_fails():
- status_mock = _run_with_failed_drop("background_worker", _db_session())
-
- status_mock.assert_called_once()
- _, kwargs = status_mock.call_args
- assert kwargs["status"] == "failed"
- assert "Retry once the vector store is available" in kwargs["error_message"]
- assert "internal error" not in kwargs["error_message"].lower()
-
-
-def _failure_text(site, error):
- outcome = _run_with_failed_drop(site, _db_session(), error=error)
- if site == "background_worker":
- return outcome.call_args.kwargs["error_message"]
- error_events = [e for e in _sse_events(outcome) if e.get("type") == "error"]
- assert len(error_events) == 1, outcome
- return error_events[0]["error"]
-
-
- "site", ["index_all", "index_collection", "background_worker"]
-)
-def test_a_permanent_drop_failure_does_not_invite_a_retry(site):
- """Missing configuration, auth failures and a store with no drop
- implementation will fail the same way every time; telling the user to
- retry once the vector store is available would send them in a loop."""
- text = _failure_text(
- site, RemoteVectorStoreDropError("forbidden", retryable=False)
- )
-
- assert "Retry once" not in text, f"{site}: {text}"
- assert "Retrying will not help" in text, f"{site}: {text}"
- assert "internal error" not in text.lower()
-
-
- "site", ["index_all", "index_collection", "background_worker"]
-)
-def test_a_partial_drop_is_reported(site):
- """Collections dropped before the failing one stay dropped while the
- rollback restores their rows; the user must be told, since a normal
- re-index will not rebuild them."""
- text = _failure_text(
- site,
- RemoteVectorStoreDropError("down", retryable=True, dropped=2),
- )
-
- assert "2 vector-store collection(s) had already been removed" in text
- assert "force re-index" in text
-
-
-class _SyncThread:
- """``threading.Thread`` stand-in that runs its target synchronously."""
-
- def __init__(
- self, target=None, args=(), kwargs=None, daemon=None, name=None
- ):
- self._target = target
-
- def start(self):
- self._target()
-
-
[email protected]("force_reindex", [True, False])
-def test_background_start_captures_the_settings_snapshot(force_reindex):
- """The background worker must not build a settings snapshot itself
- (#3453), so the start route captures one on its request-scoped session
- and hands it to the worker -- a force-reindex needs it to resolve the
- user's vector-store provider (#5765). An incremental run resets nothing
- and gets none."""
- db_session = MagicMock()
- db_session.query.return_value.filter.return_value.all.return_value = []
- manager = _settings_manager()
- worker_kwargs = {}
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield db_session
-
- with (
- patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
- patch.object(rag_module, "get_settings_manager", return_value=manager),
- patch.object(
- rag_module,
- "_background_index_worker",
- side_effect=lambda *a, **kw: worker_kwargs.update(kw),
- ),
- patch("threading.Thread", _SyncThread),
- ):
- result = rag_module._start_background_index_sync(
- "coll-1", "alice", "pw", force_reindex
- )
-
- assert result["success"] is True
- expected = SETTINGS_SNAPSHOT if force_reindex else None
- assert worker_kwargs["settings_snapshot"] is expected
-
-
-def test_force_reindex_is_parsed_as_a_boolean_not_a_truthy_string():
- """``?force_reindex=false`` must NOT force a reindex. A raw string
- "false" is truthy, so a missing ``.lower() == "true"`` silently wipes and
- rebuilds every caller's index."""
- db_session = _db_session()
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield db_session
-
- with (
- patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
- patch(
- f"{_DB_UTILS}.get_settings_manager",
- return_value=_settings_manager(),
- ),
- patch.object(rag_module, "_store_collection_embedding_metadata"),
- patch.object(rag_module, "_reset_collection_for_reindex") as reset_mock,
- patch.object(rag_module, "_unlink_reindex_faiss_files"),
- patch.object(rag_module, "_query_documents_to_index", return_value=[]),
- patch.object(rag_module, "get_rag_service", return_value=MagicMock()),
- ):
- _drain(
- rag_module.index_all(
- _request(
- query_string=b"collection_id=coll-1&force_reindex=false"
- ),
- username="alice",
- )
- )
-
- reset_mock.assert_not_called()
-
-
-# ===========================================================================
-# "cleared" is a handled non-failure, not an error
-# ===========================================================================
-#
-# A document whose text was emptied since it was last indexed comes back from
-# ``index_document`` as ``status: "cleared"`` -- its stale vectors were
-# purged, which is correct behaviour, not a failure. Three aggregation sites
-# share the ``in ("skipped", "cleared")`` classification. Dropping "cleared"
-# from any one of them buckets a correct purge into ``failed`` and surfaces a
-# blank-error failure row to the user.
-#
-# ``tests/research_library/services/test_library_rag_service_index_coverage.py``
-# asserts that ``index_documents_batch`` passes the per-document
-# ``"cleared"`` status THROUGH, but that dict carries no counters -- the
-# classification itself is untested at every site.
+ other.assert_not_called()
+ store.assert_not_called()
+ db.commit.assert_not_called()
+ if failed:
+ service.reconcile_collection_index.assert_not_called()
CLEARED_AGGREGATE = {
@@ -672,7 +218,6 @@ def test_cleared_counts_as_skipped_in_the_index_all_sse_loop():
return_value=_settings_manager(),
),
patch.object(rag_module, "_store_collection_embedding_metadata"),
- patch.object(rag_module, "_reset_collection_for_reindex"),
patch.object(
rag_module,
"_query_documents_to_index",
diff --git a/tests/web/routers/test_rag_task_status_race.py b/tests/web/routers/test_rag_task_status_race.py
new file mode 100644
index 0000000000..ce77ea04dd
--- /dev/null
+++ b/tests/web/routers/test_rag_task_status_race.py
@@ -0,0 +1,178 @@
+"""A cancellation read must not overwrite a worker's committed outcome."""
+
+from contextlib import contextmanager
+from datetime import UTC, datetime
+from importlib import import_module
+
+import pytest
+from sqlalchemy import create_engine, select, update as sql_update
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models.queue import TaskMetadata
+
+
+def task_sessions(tmp_path, monkeypatch):
+ """Reuse the request's real Session while another connection finishes."""
+ engine = create_engine(f"sqlite:///{tmp_path}/task-status.sqlite")
+ TaskMetadata.__table__.create(engine)
+ factory = sessionmaker(bind=engine, expire_on_commit=False)
+ with factory() as seed:
+ seed.add(
+ TaskMetadata(
+ task_id="rebuild-task",
+ task_type="indexing",
+ status="processing",
+ progress_message="Preparing replacement",
+ metadata_json={
+ "collection_id": "collection",
+ "force_reindex": True,
+ },
+ )
+ )
+ seed.commit()
+
+ session_context = import_module(
+ "local_deep_research.database.session_context"
+ )
+ try:
+ with factory() as request_session:
+
+ @contextmanager
+ def reused_session(*_args, **_kwargs):
+ # cancel_indexing opens an outer scope, then the status helper
+ # opens another scope on that thread. Production reuses this
+ # Session and its identity map rather than making a fresh one.
+ yield request_session
+
+ monkeypatch.setattr(
+ session_context, "get_user_db_session", reused_session
+ )
+ yield factory, request_session
+ finally:
+ engine.dispose()
+
+
[email protected]("worker_outcome", ["completed", "failed"])
+def test_stale_cancel_lookup_cannot_replace_the_workers_final_outcome(
+ task_sessions, worker_outcome
+):
+ routes = import_module("local_deep_research.web.routers.rag")
+ factory, request_session = task_sessions
+ # Hold the object that cancel_indexing found before the worker finished.
+ cached_task = (
+ request_session.query(TaskMetadata)
+ .filter_by(task_id="rebuild-task", status="processing")
+ .one()
+ )
+ finished_at = datetime(2026, 10, 18, 12, tzinfo=UTC)
+ with factory() as worker:
+ task = worker.get(TaskMetadata, "rebuild-task")
+ task.status = worker_outcome
+ task.progress_message = "Worker's final outcome"
+ task.completed_at = finished_at
+ worker.commit()
+ # A second SELECT alone reuses this identity-mapped value. No DB write
+ # happened on the request connection, so SQLite permits the other commit.
+ assert cached_task.status == "processing"
+
+ routes._do_update_task_status(
+ "task-user",
+ "test-only",
+ "rebuild-task",
+ status="cancelled",
+ progress_message="Cancellation requested...",
+ )
+
+ with factory() as observer:
+ task = observer.get(TaskMetadata, "rebuild-task")
+ assert task.status == worker_outcome
+ assert task.progress_message == "Worker's final outcome"
+ assert task.completed_at == finished_at
+
+
+def test_published_rebuild_refreshes_a_stale_cancel_and_retains_its_note(
+ task_sessions,
+):
+ routes = import_module("local_deep_research.web.routers.rag")
+ factory, worker_session = task_sessions
+ cached_task = worker_session.get(TaskMetadata, "rebuild-task")
+ with factory() as cancellation:
+ task = cancellation.get(TaskMetadata, "rebuild-task")
+ task.status = "cancelled"
+ task.progress_message = "Cancellation requested..."
+ cancellation.commit()
+ assert cached_task.status == "processing"
+
+ routes._do_update_task_status(
+ "task-user",
+ "test-only",
+ "rebuild-task",
+ status="completed",
+ progress_message="Published the replacement.",
+ published_rebuild=True,
+ )
+ with factory() as observer:
+ task = observer.get(TaskMetadata, "rebuild-task")
+ assert task.status == "completed"
+ assert task.progress_message == (
+ "Published the replacement. " + routes._LATE_CANCEL_NOTE
+ )
+ final_message = task.progress_message
+ finished_at = task.completed_at
+
+ # Retried completion/progress and a stale cancel must preserve the
+ # explanation that publication finished despite the cancel request.
+ for update in (
+ {"status": "completed", "progress_message": "Duplicate completion"},
+ {"progress_message": "Old progress callback"},
+ {"status": "cancelled", "progress_message": "Stale cancellation"},
+ ):
+ routes._do_update_task_status(
+ "task-user", "test-only", "rebuild-task", **update
+ )
+ with factory() as observer:
+ task = observer.get(TaskMetadata, "rebuild-task")
+ assert task.status == "completed"
+ assert task.progress_message == final_message
+ assert task.completed_at == finished_at
+
+
+def test_missing_task_releases_the_writer_without_creating_or_changing_rows(
+ task_sessions,
+):
+ routes = import_module("local_deep_research.web.routers.rag")
+ factory, _request_session = task_sessions
+ tasks = TaskMetadata.__table__
+
+ # Reserve a separate connection before the helper borrows the request's
+ # Session. Keep both scopes open: closing that Session here would conceal
+ # a missing commit by releasing its zero-row UPDATE's SQLite writer lock.
+ with factory.kw["bind"].connect() as writer:
+ writer.exec_driver_sql("PRAGMA busy_timeout=50")
+ before = writer.execute(select(tasks)).mappings().all()
+
+ routes._do_update_task_status(
+ "task-user",
+ "test-only",
+ "missing-task",
+ status="completed",
+ progress_message="No such task",
+ progress_current=99,
+ result_metadata={"successful": 99},
+ )
+
+ assert writer.execute(select(tasks)).mappings().all() == before
+ result = writer.execute(
+ sql_update(tasks)
+ .where(tasks.c.task_id == "rebuild-task")
+ .values(progress_message="Written by another connection")
+ )
+ assert result.rowcount == 1
+ writer.commit()
+
+ with factory() as observer:
+ assert observer.get(TaskMetadata, "missing-task") is None
+ assert observer.get(TaskMetadata, "rebuild-task").progress_message == (
+ "Written by another connection"
+ )
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index 34853e1533..80c9b75c0e 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -164,8 +164,8 @@ EXPECTED_REMOVED = [
("PUT", "/settings/api/{:path}"),
# The library's bulk re-index trigger moved from GET to POST. It runs
# the embedding/index pipeline over every document in the collection
- # (`?force_reindex=true` discards and rebuilds vectors that already
- # exist), so it is a mutation and belongs on a verb CSRFMiddleware
+ # (`?force_reindex=true` stages and atomically replaces vectors that
+ # already exist), so it is a mutation and belongs on a verb CSRFMiddleware
# guards — enforcement there is keyed on the method, and a per-path
# allowlist cannot stand in for it (the middleware compares
# `scope["path"]` as a string, the router matches a `$`-anchored