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(library): drop a remote vector collection before deleting its RAGIndex row (#5786)

LearningCircuit873a29979cee
diff --git a/changelog.d/5765.misc.md b/changelog.d/5765.misc.md
new file mode 100644
index 0000000000..e50e9183c2
--- /dev/null
+++ b/changelog.d/5765.misc.md
@@ -0,0 +1,31 @@
+The library deletion cascade is now vector-store-provider aware instead of
+assuming FAISS. No server-backed vector store provider exists yet (FAISS,
+the only shipping provider, stores its vectors in local files), so this is
+preparatory hardening rather than a fix for a bug any user could hit today,
+and FAISS deletions are unchanged. It sets the contract the first
+server-backed provider (e.g. Milvus) plugs into: deleting a collection,
+deleting just its index, and force-reindexing it now pass the user's settings
+snapshot to the cascade, which picks each index's provider (the provider
+recorded on the index once the model has one, else the configured one) and
+calls that provider's `drop_collection()` *before* the `RAGIndex` rows are
+removed, while the index hash needed to address the collection still exists.
+Deleting the rows first would leave the vectors permanently unaddressable.
+Such a provider still has to implement `drop_collection()` (deriving the
+collection name the same way it does at creation) and read its connection
+settings from the snapshot. If a drop fails, the operation is aborted and
+rolled back and reported as failed instead of silently stranding vectors on a
+remote backend: HTTP 503 with retry guidance when the vector store is
+unreachable or timed out, HTTP 500 without it for failures a retry cannot fix
+(misconfiguration, authentication, no drop support). Remote drops are not
+transactional, so if one of several collections fails after others were
+already dropped, the error says so; those collections' index records are
+kept and need a retried delete or a force re-index.
+The deletion now reads the user's vector-cleanup settings (previously it read
+none), and that read never writes: it does not seed or commit default
+settings on the deletion's session. Once a server-backed provider exists, a
+snapshot that cannot be read aborts the deletion or force re-index instead of
+silently falling back to the default provider; while only local-file
+providers (FAISS) are registered, an unreadable snapshot falls back to the
+defaults and the deletion proceeds.
+Deleting a collection's index now answers 500 rather than 404 for a failure
+other than a missing collection.
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 4fd3e5bc34..1a27867a42 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
@@ -22,7 +22,12 @@ from ....database.models.library import (
SourceType,
)
from ....database.session_context import get_user_db_session
-from ..utils.cascade_helper import CascadeHelper
+from ..utils.cascade_helper import (
+ CascadeHelper,
+ RemoteVectorStoreDropError,
+ read_vector_cleanup_settings_snapshot,
+ remote_drop_failure_message,
+)
# System collection types that must never be deleted via the public API.
# These collections hold first-class user data whose lifecycle is owned by
@@ -40,6 +45,45 @@ PROTECTED_COLLECTION_TYPES = frozenset(
)
+def _user_settings_snapshot(session) -> Dict[str, Any]:
+ """The user's settings snapshot, read through the deletion's own session.
+
+ The RAG-index cascade needs it to resolve the user's vector-store provider
+ and its connection config (#5765); without it the provider silently falls
+ back to the global default. Read through ``session`` (the caller's own
+ per-user session), so this is safe off the request thread.
+
+ Strictly read-only: ``seed_defaults=False`` because the default
+ constructor seeds an EMPTY settings table from the defaults files and
+ COMMITS on ``session`` -- mid-deletion, outside the deletion's own
+ rollback. An empty table still reads as all-defaults (the manager merges
+ its in-memory defaults). Fails closed on an unreadable snapshot once a
+ server-backed store exists (see read_vector_cleanup_settings_snapshot).
+ """
+ from ....settings.manager import SettingsManager
+
+ return read_vector_cleanup_settings_snapshot(
+ SettingsManager(session, seed_defaults=False)
+ )
+
+
+def _remote_drop_failure_result(
+ collection_id: str, exc: RemoteVectorStoreDropError, outcome: str
+) -> Dict[str, Any]:
+ """Result dict for a deletion aborted by a failed remote drop."""
+ return {
+ "deleted": False,
+ "collection_id": collection_id,
+ "error": remote_drop_failure_message(exc, outcome),
+ # Stable machine-readable keys so callers (the router) map this shape
+ # to a status code without pattern matching the human-readable
+ # "error" text (#5765): ``vector_store_error`` marks the shape and
+ # ``retryable`` says whether a retry can succeed (503) or not (500).
+ "vector_store_error": True,
+ "retryable": exc.retryable,
+ }
+
+
class CollectionDeletionService:
"""Service for collection deletion operations."""
@@ -63,7 +107,8 @@ class CollectionDeletionService:
The following are deleted:
- DocumentChunks for this collection
- - FAISS index files
+ - Vector data (FAISS index files, or the provider's remote
+ collection — dropped before the RAGIndex rows, see #5765)
- RAGIndex records
- CollectionFolder records (CASCADE)
- DocumentCollection links (CASCADE)
@@ -138,22 +183,39 @@ class CollectionDeletionService:
]
result["documents_unlinked"] = len(doc_ids_in_collection)
- # 2. Delete DocumentChunks for this collection
- result["chunks_deleted"] = (
- CascadeHelper.delete_collection_chunks(
- session, collection_name
- )
- )
-
- # 3. Delete RAGIndex records (DB only). The on-disk FAISS files
- # are unlinked AFTER the commit below — steps 4-8 still do DB
+ # 2. Delete RAGIndex records (DB only). The on-disk FAISS files
+ # are unlinked AFTER the commit below — steps 3-8 still do DB
# work that could raise and roll back, and a rollback restores
# the RAGIndex rows but not files already deleted from disk.
+ #
+ # A SERVER-BACKED store is the opposite case and is handled
+ # inside the helper: its remote collection is dropped BEFORE
+ # the rows go, because the collection name is derived from
+ # RAGIndex.index_hash. Deferring that to post-commit like the
+ # files would leave the vectors unaddressable (#5765). A
+ # failed drop raises RemoteVectorStoreDropError, caught below.
+ #
+ # This runs BEFORE the first write of this transaction (the
+ # chunk delete below) so a remote drop's network call is not
+ # made while holding the user's database write lock. The
+ # user's settings snapshot selects the provider and carries
+ # its connection config.
rag_result = CascadeHelper.delete_rag_indices_for_collection(
- session, collection_name, unlink_files=False
+ session,
+ collection_name,
+ unlink_files=False,
+ username=self.username,
+ settings_snapshot=_user_settings_snapshot(session),
)
result["indices_deleted"] = rag_result["deleted_indices"]
faiss_paths_to_unlink = rag_result["index_paths"]
+
+ # 3. Delete DocumentChunks for this collection
+ result["chunks_deleted"] = (
+ CascadeHelper.delete_collection_chunks(
+ session, collection_name
+ )
+ )
# Orphaned documents hard-deleted below may still have chunk
# rows/vectors in OTHER collections (a partial reindex can strand
# them). Collect them here and purge those after the commit —
@@ -243,6 +305,28 @@ class CollectionDeletionService:
f"{result['orphaned_documents_deleted']} orphaned deleted"
)
+ except RemoteVectorStoreDropError as exc:
+ # A remote collection could not be dropped, so its vectors are
+ # still there. Roll back so the RAGIndex rows — the only handle
+ # to those vectors — survive, and report the deletion as
+ # FAILED. Completing it here would be the one outcome that
+ # cannot be undone or retried (#5765). Collections dropped
+ # before the failing one stay dropped (exc.dropped); the
+ # message says so rather than claiming nothing changed.
+ #
+ # Logged from the error's sanitized fields, at WARNING and
+ # with no traceback: a traceback (logger.exception) would
+ # add frame state, and the backend client's error text can
+ # carry a URI or token.
+ drop_detail = exc.log_detail()
+ logger.warning(
+ f"Aborted deletion of collection {collection_id}: could "
+ f"not drop its vector-store collection: {drop_detail}"
+ )
+ session.rollback()
+ return _remote_drop_failure_result(
+ collection_id, exc, "the collection was not deleted"
+ )
except Exception:
logger.exception(f"Failed to delete collection {collection_id}")
session.rollback()
@@ -342,22 +426,29 @@ class CollectionDeletionService:
"documents_reset": 0,
}
- # 1. Delete DocumentChunks
- result["chunks_deleted"] = (
- CascadeHelper.delete_collection_chunks(
- session, collection_name
- )
- )
-
- # 2. Delete RAGIndex records (DB only). Files are unlinked after
- # the commit — steps 3-5 do more DB work that could roll back,
+ # 1. Delete RAGIndex records (DB only). Files are unlinked after
+ # the commit — steps 2-5 do more DB work that could roll back,
# and a rollback can't restore files already removed from disk.
+ # A server-backed store's remote collection is dropped inside
+ # the helper BEFORE the rows go, and before this
+ # transaction's first write (see delete_collection).
rag_result = CascadeHelper.delete_rag_indices_for_collection(
- session, collection_name, unlink_files=False
+ session,
+ collection_name,
+ unlink_files=False,
+ username=self.username,
+ settings_snapshot=_user_settings_snapshot(session),
)
result["indices_deleted"] = rag_result["deleted_indices"]
faiss_paths_to_unlink = rag_result["index_paths"]
+ # 2. Delete DocumentChunks
+ result["chunks_deleted"] = (
+ CascadeHelper.delete_collection_chunks(
+ session, collection_name
+ )
+ )
+
# 3. Reset DocumentCollection indexed status
result["documents_reset"] = (
session.query(DocumentCollection)
@@ -404,6 +495,19 @@ class CollectionDeletionService:
return result
+ except RemoteVectorStoreDropError as exc:
+ # See delete_collection: keep the RAGIndex rows so the remote
+ # collection stays addressable, and report failure. Logged
+ # the same way (sanitized fields, no traceback).
+ drop_detail = exc.log_detail()
+ logger.warning(
+ f"Aborted index deletion for collection {collection_id}: "
+ f"could not drop its vector-store collection: {drop_detail}"
+ )
+ session.rollback()
+ return _remote_drop_failure_result(
+ collection_id, exc, "the index was not deleted"
+ )
except Exception:
logger.exception(
f"Failed to delete index for collection {collection_id}"
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 d39e414037..de7a7a29e5 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
@@ -3,13 +3,14 @@ Cascade helper for deletion operations.
Handles cleanup of related records that don't have proper FK constraints:
- DocumentChunk (source_id has no FK constraint)
-- FAISS index files
+- Local vector-index files (FAISS)
+- Server-backed vector collections (dropped before their RAGIndex row goes)
- Filesystem files
"""
import time
from pathlib import Path
-from typing import Dict, List, Optional, Any, Union
+from typing import Any, Dict, Iterable, List, NamedTuple, Optional, Type, Union
from loguru import logger
from sqlalchemy.orm import Session
@@ -31,6 +32,181 @@ from ....database.models.download_tracker import DownloadTracker
_STALE_TMP_AGE_SECONDS = 3600
+class RemoteVectorStoreDropError(RuntimeError):
+ """A server-backed vector collection could not be dropped.
+
+ Raised by :meth:`CascadeHelper.delete_rag_indices_for_collection` when a
+ ``RAGIndex`` row belongs to a server-backed (not local-file) store and its
+ collection could not be dropped.
+
+ This is deliberately an exception rather than a logged warning: it is
+ raised BEFORE any ``RAGIndex`` row is deleted, so it aborts the caller's
+ transaction and leaves ``index_hash`` -- the only handle by which the
+ remote collection can be addressed -- intact. Reporting the deletion as
+ successful here is what turns retained vectors into *unrecoverable*
+ vectors (issue #5765).
+
+ The message is fixed text plus the provider key, an ``index_hash`` prefix
+ and the *type name* of the underlying error -- never that error's own
+ text, which for a network client can carry a backend URI or credential.
+ For the same reason the underlying error is not chained (``from None``),
+ and callers log :meth:`log_detail` without a traceback.
+
+ Attributes:
+ retryable: True only when the failure is known to be transient: the
+ backend could not be reached or timed out (``ConnectionError`` /
+ ``TimeoutError``, or an error carrying ``retryable = True`` -- see
+ :meth:`BaseVectorStore.drop_collection`). False for failures a
+ retry cannot fix: no username, a row with no ``index_hash``, an
+ unknown provider, a store with no drop implementation, an
+ authentication/permission error, or anything unclassified.
+ dropped: how many remote collections this call had ALREADY dropped
+ (or found absent) before the failure. Remote drops cannot be made
+ all-or-nothing: when this is non-zero those collections are gone
+ although the caller's rollback restores their ``RAGIndex`` rows
+ (and the collection's ``indexed`` flags), so search over them
+ returns nothing until the operation is retried -- ``drop_collection``
+ is idempotent, so a retried delete completes -- or the collection
+ is force re-indexed. A normal (non-force) re-index does NOT
+ rebuild them, because the restored rows still read as indexed.
+ cause_type: type name of the underlying error, if there was one.
+ """
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ retryable: bool = False,
+ dropped: int = 0,
+ cause_type: Optional[str] = None,
+ ) -> None:
+ super().__init__(message)
+ self.retryable = retryable
+ self.dropped = dropped
+ self.cause_type = cause_type
+
+ def log_detail(self) -> str:
+ """A log line for this failure built only from sanitized fields.
+
+ Callers log this -- at WARNING, with no traceback -- instead of the
+ exception itself: the message is fixed text plus a provider key, an
+ ``index_hash`` prefix and a type name, and nothing else about the
+ underlying error is recorded.
+ """
+ return (
+ f"{self.args[0]} (retryable={self.retryable}, "
+ f"already dropped={self.dropped})"
+ )
+
+
+def _is_transient_drop_failure(exc: BaseException) -> bool:
+ """Whether a ``drop_collection`` failure is worth retrying.
+
+ An explicit boolean ``retryable`` attribute on the error wins, so a
+ backend can classify its own client's exceptions. Otherwise only the
+ built-in transport failures count as transient; everything else
+ (``PermissionError``, ``NotImplementedError``, auth errors, unknown
+ exceptions) is reported as permanent rather than inviting an endless
+ retry loop.
+ """
+ flag = getattr(exc, "retryable", None)
+ if isinstance(flag, bool):
+ return flag
+ return isinstance(exc, (ConnectionError, TimeoutError))
+
+
+def remote_drop_failure_message(
+ exc: RemoteVectorStoreDropError, outcome: str
+) -> str:
+ """User-facing text for a failed remote drop.
+
+ ``outcome`` states what did NOT happen, e.g. ``"the collection was not
+ deleted"``. The text is built only from fixed phrases and counts, never
+ from the underlying error.
+ """
+ if exc.retryable:
+ message = (
+ f"Vector store unreachable — {outcome}. Retry once the vector "
+ "store is available."
+ )
+ else:
+ message = (
+ f"The vector store could not drop the collection — {outcome}. "
+ "Retrying will not help until the vector store configuration or "
+ "permissions are fixed; see the server log."
+ )
+ if exc.dropped:
+ message += (
+ f" {exc.dropped} vector-store collection(s) had already been "
+ "removed before the failure; their index records were kept, so "
+ "search over them returns nothing until this is retried "
+ "successfully or the collection is force re-indexed."
+ )
+ return message
+
+
+def read_vector_cleanup_settings_snapshot(settings_manager: Any) -> dict:
+ """The user's settings snapshot for a vector cleanup, failing closed.
+
+ The cascade resolves each row's provider -- and a server-backed store's
+ connection config -- from this snapshot (#5765). A non-strict
+ ``get_all_settings()`` answers a failed settings query with a
+ defaults-only snapshot, which would silently select the global default
+ provider and connection config: the drop would miss (or target the wrong
+ store), be counted as "already absent", and the rows -- the only handle to
+ the real collection -- would then be deleted.
+
+ So the read is strict. On failure:
+
+ * while only local-file providers exist
+ (:func:`~local_deep_research.vector_stores.config.only_local_file_providers_registered`),
+ the snapshot cannot change the cleanup (every row's files are unlinked,
+ nothing is dropped), so this degrades to the non-strict read instead of
+ failing a deletion that would otherwise succeed;
+ * otherwise it raises :class:`RemoteVectorStoreDropError` (not retryable)
+ BEFORE any row is touched, so callers abort exactly as for a failed
+ drop.
+
+ ``settings_manager`` is only read from. The caller chooses how it is
+ built; a caller inside a transaction must use one that does not seed and
+ commit defaults (``SettingsManager(session, seed_defaults=False)``).
+ """
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from ....vector_stores import config as vs_config
+
+ try:
+ return settings_manager.get_all_settings(strict=True)
+ except (SQLAlchemyError, LookupError) as exc:
+ cause_type = type(exc).__name__
+ if vs_config.only_local_file_providers_registered():
+ logger.warning(
+ "Could not read the user's settings ({}); continuing the vector "
+ "cleanup with defaults because only local-file vector stores "
+ "exist",
+ cause_type,
+ )
+ return settings_manager.get_all_settings()
+ raise RemoteVectorStoreDropError(
+ "Could not read the user's settings "
+ f"({cause_type}), so the vector-store provider and its connection "
+ "config are unknown; refusing to delete the RAGIndex records that "
+ "hold the only handle to their vectors.",
+ retryable=False,
+ cause_type=cause_type,
+ )
+
+
+class _PlannedIndex(NamedTuple):
+ """One ``RAGIndex`` row with its vector cleanup decided up front."""
+
+ row: RAGIndex
+ provider: str
+ # None for a local-file store (unlink its files); the store class for a
+ # server-backed one (drop its collection).
+ remote_store: Optional[Type[Any]]
+
+
class CascadeHelper:
"""Helper class for cleaning up related records during deletion."""
@@ -352,33 +528,262 @@ class CascadeHelper:
logger.exception(f"Failed to delete FAISS files for: {index_path}")
return False
+ @staticmethod
+ def _row_provider_key(index: RAGIndex) -> Optional[str]:
+ """The provider recorded on ``index`` itself, if the model has one.
+
+ ``RAGIndex`` has no provider column yet. The first server-backed
+ provider is expected to add one (the open Milvus PR, #5331, adds
+ ``vector_store_provider``), and once it exists it -- not the current
+ setting -- is what built the row's vectors: a user who switched
+ providers can hold rows of both kinds in one collection. Read
+ defensively so this works before and after that column lands.
+ """
+ raw = getattr(index, "vector_store_provider", None)
+ if isinstance(raw, str) and raw.strip():
+ return raw
+ return None
+
+ @staticmethod
+ def _plan_vector_cleanup(
+ indices: Iterable[RAGIndex],
+ settings_snapshot: Optional[dict],
+ ) -> List[_PlannedIndex]:
+ """Decide, ONCE per call, how each row's vectors are cleaned up.
+
+ A row's provider is its recorded provider when it has one, else the
+ user's configured provider resolved from ``settings_snapshot``. Doing
+ this in one pass and handing the result to both the drop and the
+ delete loop means the two can never disagree (a provider resolved
+ twice could flip between the reads, skip both the drop and the unlink,
+ and still delete the rows).
+ """
+ from ....vector_stores import config as vs_config
+
+ default_key: Optional[str] = None
+ store_by_key: Dict[str, Optional[Type[Any]]] = {}
+ plan: List[_PlannedIndex] = []
+ for index in indices:
+ key = CascadeHelper._row_provider_key(index)
+ if key is None:
+ if default_key is None:
+ default_key = vs_config.resolve_provider(settings_snapshot)
+ key = default_key
+ if key not in store_by_key:
+ try:
+ if vs_config.provider_is_local_file(key, settings_snapshot):
+ store_by_key[key] = None
+ else:
+ store_by_key[key] = vs_config.get_vector_store_class(
+ key, settings_snapshot
+ )
+ except ValueError:
+ # Unknown/unregistered provider: we cannot tell whether
+ # there is a remote collection, let alone drop it, so we
+ # must not delete the row that names it.
+ raise RemoteVectorStoreDropError(
+ f"RAGIndex row for collection {index.collection_name} "
+ "uses an unknown vector-store provider; cannot clean "
+ "up its vectors.",
+ retryable=False,
+ ) from None
+ plan.append(_PlannedIndex(index, key, store_by_key[key]))
+ return plan
+
+ @staticmethod
+ def _drop_planned_remote_collections(
+ plan: List[_PlannedIndex],
+ *,
+ username: Optional[str],
+ settings_snapshot: Optional[dict],
+ ) -> int:
+ """Drop the remote collections of the server-backed rows in ``plan``.
+
+ See :meth:`drop_remote_vector_collections` for the contract.
+ """
+ remote = [
+ (item, item.remote_store)
+ for item in plan
+ if item.remote_store is not None
+ ]
+ if not remote:
+ return 0
+
+ if not username:
+ # A server-backed collection's name is derived from the username
+ # plus index_hash; with no username we cannot name -- hence cannot
+ # delete -- the collection. Fail loudly rather than delete the rows
+ # and strand vectors nothing can address.
+ raise RemoteVectorStoreDropError(
+ f"Cannot drop {remote[0][0].provider} vector collections without "
+ "a username; refusing to delete the RAGIndex rows that hold "
+ "the only handle to them.",
+ retryable=False,
+ )
+
+ # Validate EVERY row's index_hash before dropping anything. This must
+ # stay a separate pass ahead of the drop loop below, not a check
+ # inside it: a bad row sorted after good ones would otherwise let the
+ # loop drop their collections first and only then abort, destroying
+ # collections whose rows survive the rollback. Failing here, before
+ # any drop_collection call, keeps a bad row's abort a true no-op.
+ for item, _store in remote:
+ if not item.row.index_hash:
+ raise RemoteVectorStoreDropError(
+ f"RAGIndex row for collection {item.row.collection_name} "
+ f"has no index_hash; cannot address its {item.provider} "
+ "collection.",
+ retryable=False,
+ )
+
+ dropped = 0
+ completed = 0
+ for item, store_class in remote:
+ index_hash = item.row.index_hash
+ try:
+ if store_class.drop_collection(
+ username=username,
+ index_hash=index_hash,
+ settings_snapshot=settings_snapshot,
+ ):
+ dropped += 1
+ except Exception as exc:
+ # Includes NotImplementedError: a store that declares itself
+ # server-backed but never implemented a drop path would
+ # otherwise silently orphan every collection it created.
+ #
+ # ``from None``: the cause's text can carry a backend URI or
+ # token, and a chained cause is printed by any traceback
+ # logger. Only its type name is kept.
+ raise RemoteVectorStoreDropError(
+ f"Failed to drop {item.provider} collection for index "
+ f"{index_hash[:12]}...: {type(exc).__name__}. The index "
+ "record was NOT deleted.",
+ retryable=_is_transient_drop_failure(exc),
+ dropped=completed,
+ cause_type=type(exc).__name__,
+ ) from None
+ completed += 1
+
+ logger.info(
+ f"Dropped {dropped} vector collection(s) "
+ f"({completed - dropped} already absent) before deleting their "
+ "RAGIndex records"
+ )
+ return dropped
+
+ @staticmethod
+ def drop_remote_vector_collections(
+ indices: Iterable[RAGIndex],
+ *,
+ username: Optional[str],
+ settings_snapshot: Optional[dict] = None,
+ ) -> int:
+ """Drop the server-side collections backing ``indices``.
+
+ Rows whose provider is a local-file store are skipped -- those are
+ cleaned up by unlinking their index files instead -- so this returns 0
+ for an all-FAISS input. Each row's provider is its recorded provider
+ when the model has one, else the provider configured in
+ ``settings_snapshot`` (see :meth:`_plan_vector_cleanup`).
+
+ MUST be called while the ``RAGIndex`` rows still exist: the backend
+ collection name is derived from ``(username, index_hash)`` and
+ ``index_hash`` lives on the row. See #5765.
+
+ Remote drops are not transactional: if the Nth drop fails, the first
+ N-1 collections are already gone. The error's ``dropped`` attribute
+ says how many, so callers can say so instead of "nothing was deleted".
+
+ Returns:
+ The number of collections actually dropped (an already-absent
+ collection counts as 0 — ``drop_collection`` is idempotent).
+
+ Raises:
+ RemoteVectorStoreDropError: if a server-backed collection could
+ not be dropped, or cannot be addressed (no ``username``, a row
+ with no ``index_hash``, an unknown provider). Its
+ ``retryable`` attribute says whether a retry can help. The
+ caller must abort — and roll back — rather than delete rows.
+ """
+ # Any iterable, a generator included: the plan is a list built in ONE
+ # pass, and it -- not ``indices`` -- is what the validation pass and
+ # the drop loop both walk. (Walking a generator twice would exhaust
+ # it on the first pass and silently skip the validation guard.)
+ plan = CascadeHelper._plan_vector_cleanup(indices, settings_snapshot)
+ return CascadeHelper._drop_planned_remote_collections(
+ plan, username=username, settings_snapshot=settings_snapshot
+ )
+
@staticmethod
def delete_rag_indices_for_collection(
session: Session,
collection_name: str,
*,
unlink_files: bool = True,
+ username: Optional[str] = None,
+ settings_snapshot: Optional[dict] = None,
) -> Dict[str, Any]:
"""
- Delete RAGIndex records (and, by default, their FAISS files) for a
- collection.
+ Delete RAGIndex records (and their vectors) for a collection.
+
+ Vector cleanup is provider-aware, decided per row (see
+ :meth:`_plan_vector_cleanup`):
+
+ * Local-file store (FAISS): the ``.faiss``/``.pkl``/``.idmap.json``
+ files are unlinked — here when ``unlink_files`` is True, otherwise by
+ the caller after its commit (see ``index_paths`` below).
+ * Server-backed store: the remote collection is dropped **before** the
+ ``RAGIndex`` rows are deleted, because its name is derived from
+ ``index_hash`` which only exists on those rows. If a drop fails,
+ :class:`RemoteVectorStoreDropError` propagates before any row is
+ deleted and the caller must roll back. Collections dropped before
+ the failing one stay dropped (see the error's ``dropped``) — see
+ #5765.
+
+ The remote drops run inside the caller's transaction (they must
+ happen while the rows exist, before they are deleted in that same
+ 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
+ server-backed stores make network calls here (FAISS never does), and
+ their ``drop_collection`` is expected to bound each call with a
+ client timeout.
Args:
session: Database session
- collection_name: The collection name (e.g., "collection_<uuid>")
- unlink_files: When True (default) the on-disk .faiss/.pkl/.idmap
- files are unlinked here. When False, ONLY the RAGIndex DB rows
- are staged for deletion and the file paths are returned under
- ``index_paths`` — the caller is responsible for unlinking them
- AFTER its transaction commits. Deleting files in-transaction is
+ collection_name: Name of the collection (e.g., "collection_<uuid>")
+ unlink_files: When True (default), unlink the FAISS files here.
+ When False, only the RAGIndex rows are deleted and the index
+ paths are returned in ``index_paths`` so the caller can unlink
+ them AFTER its own commit. Unlinking before the commit is
unsafe when more DB work follows before the commit: a later
rollback restores the RAGIndex rows but cannot restore the
already-unlinked files, leaving the collection pointing at a
- missing index (silently-broken search).
+ missing index (silently-broken search). Ignored for
+ server-backed rows, which have no files.
+ username: Owner of the indices. Required when a row's provider is
+ server-backed (it is half of the derived remote collection
+ name); unused for local-file providers, which is why it stays
+ optional.
+ settings_snapshot: The user's settings snapshot. Production
+ callers MUST pass it: it selects the configured provider for
+ rows that do not record their own, and carries the connection
+ config ``drop_collection`` needs. Without it the provider
+ falls back to the global default (FAISS).
Returns:
- Dict with deletion results (includes ``index_paths`` when
- ``unlink_files`` is False).
+ Dict with deletion results (``index_paths`` lists local-file rows
+ only, and only when ``unlink_files`` is False).
+
+ Raises:
+ RemoteVectorStoreDropError: a server-backed collection could not be
+ dropped or addressed. Deliberately NOT swallowed: completing
+ the row delete anyway is what makes the leftover vectors
+ unaddressable.
"""
indices = (
session.query(RAGIndex)
@@ -386,6 +791,24 @@ class CascadeHelper:
.all()
)
+ # Resolved ONCE; both the drop and the delete loop below read it.
+ plan = CascadeHelper._plan_vector_cleanup(indices, settings_snapshot)
+
+ # ORDERING IS THE FIX (#5765): drop the remote collections FIRST,
+ # while index_hash is still readable from the rows deleted below. A
+ # failure raises, so the caller's transaction rolls back with the
+ # rows — and therefore the vectors' only name — intact.
+ #
+ # A partial failure (collection 2 of 3 unreachable) leaves the
+ # already-dropped collections gone while their rows (and the
+ # documents' indexed flags) survive the rollback; the error's
+ # ``dropped`` count lets the caller say so. That direction is
+ # recoverable — a retried delete or a force re-index reconciles it
+ # (``drop_collection`` is idempotent) — the opposite order is not.
+ CascadeHelper._drop_planned_remote_collections(
+ plan, username=username, settings_snapshot=settings_snapshot
+ )
+
deleted_indices = 0
deleted_files = 0
index_paths: List[str] = []
@@ -407,27 +830,34 @@ class CascadeHelper:
# allowed_root would refuse to delete a legacy-layout index and
# orphan its files. Kept consistent with the external callers above.
rag_indices_root = None
- if unlink_files:
+ if unlink_files and any(item.remote_store is None for item in plan):
from ....config.paths import get_cache_directory
rag_indices_root = get_cache_directory() / "rag_indices"
- for index in indices:
- path = str(index.index_path)
- if unlink_files:
- if CascadeHelper.delete_faiss_index_files(
- path, allowed_root=rag_indices_root
- ):
- deleted_files += 1
- else:
- index_paths.append(path)
+ for item in plan:
+ index = item.row
+ # index_path is only meaningful for a local-file store. For a
+ # server-backed row it names no file, so neither unlinking it here
+ # nor handing it to the caller's post-commit unlink would do
+ # anything but log a confusing miss — its vectors were already
+ # dropped above.
+ if item.remote_store is None:
+ path = str(index.index_path)
+ if unlink_files:
+ if CascadeHelper.delete_faiss_index_files(
+ path, allowed_root=rag_indices_root
+ ):
+ deleted_files += 1
+ else:
+ index_paths.append(path)
session.delete(index)
deleted_indices += 1
logger.debug(
f"Deleted {deleted_indices} RAGIndex records and {deleted_files} "
- f"FAISS files for collection {collection_name}"
+ f"index files for collection {collection_name}"
)
return {
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index 46b80b5628..e023d4fbe3 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -629,6 +629,8 @@ class SettingsManager(ISettingsManager):
self,
db_session: Optional[Session] = None,
owns_session: bool = False,
+ *,
+ seed_defaults: bool = True,
):
"""
Initialize the settings manager
@@ -639,6 +641,13 @@ class SettingsManager(ISettingsManager):
Defaults to False (safe for borrowed sessions). Set to True
only when this manager created/owns the session — currently
only get_settings_manager() in db_utils.py does this.
+ seed_defaults: If True (the default), an empty settings table is
+ seeded from the defaults files and COMMITTED on
+ ``db_session`` here. Pass False for a read-only manager on a
+ session that belongs to someone else's transaction (e.g. a
+ deletion reading the user's snapshot mid-transaction): reads
+ still merge the in-memory defaults, so an empty table reads
+ as all-defaults without writing anything.
"""
self.db_session = db_session
self._owns_session = owns_session
@@ -652,7 +661,7 @@ class SettingsManager(ISettingsManager):
self.__settings_locked: Optional[bool] = None
# Auto-initialize settings if database is empty
- if self.db_session:
+ if self.db_session and seed_defaults:
self._ensure_settings_initialized()
def close(self):
diff --git a/src/local_deep_research/vector_stores/__init__.py b/src/local_deep_research/vector_stores/__init__.py
index 3abe8d6188..3b91b8be14 100644
--- a/src/local_deep_research/vector_stores/__init__.py
+++ b/src/local_deep_research/vector_stores/__init__.py
@@ -9,6 +9,7 @@ from .base import BaseVectorStore
from .config import (
VALID_VECTOR_STORE_PROVIDERS,
get_vector_store_class,
+ provider_is_local_file,
resolve_provider,
)
@@ -16,5 +17,6 @@ __all__ = [
"BaseVectorStore",
"VALID_VECTOR_STORE_PROVIDERS",
"get_vector_store_class",
+ "provider_is_local_file",
"resolve_provider",
]
diff --git a/src/local_deep_research/vector_stores/base.py b/src/local_deep_research/vector_stores/base.py
index 58727fd084..f331c50d10 100644
--- a/src/local_deep_research/vector_stores/base.py
+++ b/src/local_deep_research/vector_stores/base.py
@@ -15,8 +15,9 @@ prescribe their per-user paths, integrity checksums, or reload/merge locking
model that :class:`LibraryRAGService` layers on top. Those are *local-file*
concerns (see :attr:`is_local_file`): a future server-backed store (e.g.
Qdrant) would set ``is_local_file = False``, no-op :meth:`persist` /
-:meth:`load`, and the service layer would skip the file lock + integrity
-machinery for it. So this base class makes adding a backend *easier* (a clean,
+:meth:`load`, implement :meth:`drop_collection` (the deletion path cannot
+``unlink()`` a remote collection), and the service layer would skip the file
+lock + integrity machinery for it. So this base class makes adding a backend *easier* (a clean,
verified query surface), not *free* — a real server backend still requires
refactoring the file/lock/integrity layer in the service.
@@ -267,3 +268,76 @@ class BaseVectorStore(ABC):
raise NotImplementedError(
f"{type(self).__name__} does not support persist()"
)
+
+ # ------------------------------------------------------------------ #
+ # Lifecycle (server-backed stores)
+ # ------------------------------------------------------------------ #
+ @classmethod
+ def drop_collection(
+ cls,
+ *,
+ username: str,
+ index_hash: str,
+ settings_snapshot: Optional[dict] = None,
+ ) -> bool:
+ """Permanently remove the backing collection for one RAG index.
+
+ The deletion counterpart of :meth:`create`, so the library deletion
+ cascade can dispose of vectors it cannot simply ``unlink()``. It is a
+ **classmethod on purpose**: a deletion path must be able to drop a
+ collection without first loading it (loading a possibly-corrupt or
+ already-absent index just to delete it is both wasteful and
+ failure-prone).
+
+ Identity
+ --------
+ The collection is addressed by ``(username, index_hash)`` rather than
+ by an instance, because those two values are the only stable handle
+ available at deletion time: ``index_hash`` lives on the ``RAGIndex``
+ row, and that row is deleted by the same cascade. An implementation
+ MUST derive the backend collection name from these same two inputs at
+ BOTH creation and deletion, or the name it computes here will not
+ match the one it created and drop_collection will silently miss.
+
+ Nothing enforces that yet: :meth:`create` does not currently receive
+ ``username`` or ``index_hash`` (it takes ``dimension``/``index_type``/
+ ``metric``/``normalize``/``path``/``lock``/``integrity_record``/
+ ``integrity_verify``), so there is no shared derivation to reuse. The
+ first server-backed provider MUST extend the creation path to accept
+ both, thread them through into whatever it uses to name the remote
+ collection, and use that exact derivation here too (see the follow-up
+ design issue, #6769).
+
+ **Ordering contract**: callers MUST invoke this while the ``RAGIndex``
+ row still exists. Once the row is gone ``index_hash`` is unrecoverable
+ and the remote collection becomes *unaddressable* -- orphaned vectors
+ that no longer have a name (see issue #5765).
+
+ Contract for implementations:
+
+ * Idempotent -- return ``False`` (not raise) when the collection is
+ already absent, ``True`` when one was actually dropped.
+ * Raise on *transport / permission* failure. Returning ``False`` for an
+ unreachable backend would let the caller record a successful deletion
+ while the user's vectors survive on third-party infrastructure.
+ * Make the failure classifiable. The cascade tells the user to retry
+ only for a *transient* failure: a ``ConnectionError`` /
+ ``TimeoutError`` (or subclass), or any exception carrying a boolean
+ ``retryable`` attribute set to True. Everything else -- auth or
+ permission errors, missing connection config, unrecognised client
+ exceptions -- is reported as permanent, so translate the backend
+ client's own "unreachable" / "timed out" exceptions accordingly.
+ * Bound each call with a client timeout: the cascade calls this inside
+ the user's database transaction.
+ * Read connection config from ``settings_snapshot`` -- the deletion
+ callers pass the user's snapshot. Only the exception's type name is
+ surfaced to users and logs, never its message.
+
+ Local-file stores (:attr:`is_local_file` True) do not implement this --
+ their deletion path unlinks the index files instead -- so the base
+ implementation raises :class:`NotImplementedError`. Server-backed
+ stores MUST override it.
+ """
+ raise NotImplementedError(
+ f"{cls.__name__} does not support drop_collection()"
+ )
diff --git a/src/local_deep_research/vector_stores/config.py b/src/local_deep_research/vector_stores/config.py
index 8921e9c983..d2930d29dc 100644
--- a/src/local_deep_research/vector_stores/config.py
+++ b/src/local_deep_research/vector_stores/config.py
@@ -16,6 +16,20 @@ VALID_VECTOR_STORE_PROVIDERS = ["faiss"]
_DEFAULT_PROVIDER = "faiss"
+# Providers whose store persists to a local file this process owns end to end,
+# i.e. ``BaseVectorStore.is_local_file``. Duplicated here as a *cheap* lookup so
+# callers that only need to branch on it -- notably the deletion cascade, which
+# must choose between unlinking index files and dropping a remote collection --
+# don't have to import the backend module just to read a class attribute.
+# Importing ``faiss_store`` pulls in the native ``faiss`` extension, which is a
+# lot of machinery to load on a path that is about to delete things.
+#
+# MUST stay in sync with each class's ``is_local_file``; a test asserts it.
+# Only local-file providers are listed: an unlisted provider falls through to
+# the real class (see ``provider_is_local_file``), which a remote provider has
+# to be imported for anyway to call ``drop_collection``.
+_LOCAL_FILE_PROVIDERS = frozenset({"faiss"})
+
# Lazily-populated {provider_key: class}. Populated on first use to avoid
# importing faiss at module import time.
_PROVIDER_CLASSES: Dict[str, Type[BaseVectorStore]] = {}
@@ -39,6 +53,53 @@ def resolve_provider(settings_snapshot: Optional[dict] = None) -> str:
return _DEFAULT_PROVIDER
+def _normalize_provider_key(key: str) -> str:
+ """Normalize a provider key from a settings/DB value.
+
+ Such a value may carry surrounding whitespace/quotes/case (mirrors
+ ``embeddings_config.get_embeddings``).
+ """
+ return key.strip().strip("\"'").strip().lower()
+
+
+def provider_is_local_file(
+ provider: Optional[str] = None,
+ settings_snapshot: Optional[dict] = None,
+) -> bool:
+ """Return whether ``provider`` stores its vectors in a local file.
+
+ This is the discriminator between "unlink the index files" and "drop the
+ remote collection" on deletion paths (see ``BaseVectorStore.is_local_file``).
+
+ Answers from :data:`_LOCAL_FILE_PROVIDERS` without importing the backend
+ when it can; otherwise falls back to the authoritative class attribute.
+ """
+ key = _normalize_provider_key(
+ provider or resolve_provider(settings_snapshot)
+ ) # gitleaks:allow
+ if key in _LOCAL_FILE_PROVIDERS:
+ return True
+ return get_vector_store_class(key, settings_snapshot).is_local_file
+
+
+def only_local_file_providers_registered() -> bool:
+ """Return whether every known provider is a local-file store.
+
+ True today (FAISS only). While it holds, which provider a user selected
+ cannot change how a deletion cleans up vectors -- every row's files are
+ unlinked and nothing is dropped remotely -- so a deletion does not need
+ the user's settings snapshot to be trustworthy. The first server-backed
+ provider (listed in :data:`VALID_VECTOR_STORE_PROVIDERS` or registered in
+ the class registry) makes this False, and callers must then fail closed
+ when the snapshot cannot be read (see
+ ``cascade_helper.read_vector_cleanup_settings_snapshot``).
+ """
+ known = set(VALID_VECTOR_STORE_PROVIDERS) | set(_PROVIDER_CLASSES)
+ return {_normalize_provider_key(key) for key in known} <= (
+ _LOCAL_FILE_PROVIDERS
+ )
+
+
def get_vector_store_class(
provider: Optional[str] = None,
settings_snapshot: Optional[dict] = None,
@@ -50,9 +111,7 @@ def get_vector_store_class(
providers, so the factory hands back the class rather than an instance).
"""
key = provider or resolve_provider(settings_snapshot) # gitleaks:allow
- # Normalize like embeddings_config.get_embeddings: a provider from a
- # settings/DB value may carry surrounding whitespace/quotes/case.
- key = key.strip().strip("\"'").strip().lower()
+ key = _normalize_provider_key(key)
classes = _load_provider_classes()
if key not in classes:
raise ValueError(
diff --git a/src/local_deep_research/web/routers/library_delete.py b/src/local_deep_research/web/routers/library_delete.py
index de105650a5..78772b7624 100644
--- a/src/local_deep_research/web/routers/library_delete.py
+++ b/src/local_deep_research/web/routers/library_delete.py
@@ -294,9 +294,24 @@ def delete_collection(
return {"success": True, **result}
error = result.get("error", "Unknown error")
# 404 not found, 409 for a protected/system collection the service
- # refuses to delete, else 400. FastAPI doesn't honor Flask's
- # `(body, status)` tuple return, so use JSONResponse explicitly.
- if "not found" in error.lower():
+ # refuses to delete, 503 when the vector store couldn't be reached
+ # (the collection was not deleted; a retry can succeed), 500 when a
+ # vector-store collection could not be dropped for a reason a retry
+ # won't fix (misconfiguration, auth, no drop support), else 400.
+ # FastAPI doesn't honor Flask's `(body, status)` tuple return, so use
+ # JSONResponse explicitly. The 503/500 cases are keyed off
+ # ``result["retryable"]`` / ``result["vector_store_error"]`` (set by
+ # CollectionDeletionService when RemoteVectorStoreDropError
+ # propagates out of CascadeHelper) rather than matching the "error"
+ # text, so a wording change can't silently misroute a DELETE onto
+ # 404 — which a naive retry/cleanup layer would read as "already
+ # gone" and mark deleted, while the remote vectors and RAGIndex row
+ # survive (see #5765).
+ if result.get("retryable"):
+ status_code = 503
+ elif result.get("vector_store_error"):
+ status_code = 500
+ elif "not found" in error.lower():
status_code = 404
elif result.get("collection_type") in PROTECTED_COLLECTION_TYPES:
status_code = 409
@@ -330,7 +345,26 @@ def delete_collection_index(
if result.get("deleted"):
return {"success": True, **result}
- return JSONResponse({"success": False, **result}, status_code=404)
+ # 503 when the vector store couldn't be reached (the index was not
+ # deleted; a retry can succeed), 500 when a vector-store collection
+ # could not be dropped for a reason a retry won't fix — see
+ # delete_collection above for why this is keyed off the service's
+ # machine-readable keys rather than the error text. 404 ONLY for a
+ # genuinely missing collection; any other failure (the service's
+ # generic "Failed to delete collection index" after a rollback) is
+ # a 500, not a 404 a cleanup layer would read as "already gone".
+ # Kept as literal JSONResponse(status_code=...) branches (rather
+ # than one call fed by a variable) so every code stays visible to
+ # tests/web/test_route_table_parity.py's AST scan, which only
+ # credits a route with a status code when it sees a literal
+ # `status_code=<int>` at the call site.
+ if result.get("retryable"):
+ return JSONResponse({"success": False, **result}, status_code=503)
+ if result.get("vector_store_error"):
+ return JSONResponse({"success": False, **result}, status_code=500)
+ if "not found" in str(result.get("error", "")).lower():
+ return JSONResponse({"success": False, **result}, status_code=404)
+ return JSONResponse({"success": False, **result}, status_code=500)
except Exception as e:
return handle_api_error("deleting collection index", e)
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 705c930539..3d3b95473b 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -1269,10 +1269,32 @@ 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.
+ from ...research_library.deletion.utils.cascade_helper import (
+ RemoteVectorStoreDropError,
+ read_vector_cleanup_settings_snapshot,
+ remote_drop_failure_message,
+ )
+
# Fetch batch size from settings in this thread before generator runs
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)
@@ -1326,7 +1348,10 @@ def index_all(
changed = True
if force_reindex:
faiss_reset_paths = _reset_collection_for_reindex(
- db_session, collection_id
+ db_session,
+ collection_id,
+ username,
+ settings_snapshot=reset_settings_snapshot,
)
changed = True
if changed:
@@ -1412,6 +1437,26 @@ def index_all(
f"Bulk indexing complete: {results['successful']} successful, {results['skipped']} skipped, {results['failed']} failed"
)
+ except RemoteVectorStoreDropError as exc:
+ # Caught ahead of the catch-all below: this is an actionable
+ # vector-store failure, not an internal error. Force-reindex rolls
+ # back, keeping the RAGIndex rows (the remote collections' only
+ # handle); the message says whether a retry can help and whether
+ # some collections were already dropped (#5765). Logged from the
+ # error's sanitized fields, with no traceback (a traceback would
+ # add frame state; the backend's error text can carry secrets).
+ drop_detail = exc.log_detail()
+ logger.warning(
+ "Force-reindex aborted: could not drop the vector-store "
+ f"collection before rebuilding it: {drop_detail}"
+ )
+ drop_error = {
+ "type": "error",
+ "error": remote_drop_failure_message(
+ exc, "indexing was aborted"
+ ),
+ }
+ yield f"data: {json.dumps(drop_error)}\n\n"
except Exception:
logger.exception("Error in bulk indexing")
yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
@@ -3163,8 +3208,10 @@ def _store_collection_embedding_metadata(collection, rag_service):
)
-def _reset_collection_for_reindex(db_session, collection_id):
- """Clear old chunks, FAISS indices, and indexed-state before a force rebuild.
+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
@@ -3176,6 +3223,19 @@ def _reset_collection_for_reindex(db_session, collection_id):
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
@@ -3197,7 +3257,11 @@ def _reset_collection_for_reindex(db_session, 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
+ 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}"
@@ -3316,6 +3380,18 @@ 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.
+ from ...research_library.deletion.utils.cascade_helper import (
+ RemoteVectorStoreDropError,
+ read_vector_cleanup_settings_snapshot,
+ remote_drop_failure_message,
+ )
+
# Resolve the parallel worker bound before the generator runs — the
# parallel helper must never touch SettingsManager from a worker thread.
with get_user_db_session(username, db_password) as _settings_session:
@@ -3326,6 +3402,13 @@ def index_collection(
)
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():
@@ -3374,7 +3457,10 @@ def index_collection(
changed = True
if force_reindex:
faiss_reset_paths = _reset_collection_for_reindex(
- db_session, collection_id
+ db_session,
+ collection_id,
+ username,
+ settings_snapshot=reset_settings_snapshot,
)
changed = True
if changed:
@@ -3559,6 +3645,26 @@ def index_collection(
yield f"data: {json.dumps({'type': 'complete', 'results': results})}\n\n"
logger.info("SSE generator finished successfully")
+ except RemoteVectorStoreDropError as exc:
+ # Caught ahead of the catch-all below: this is an actionable
+ # vector-store failure, not an internal error. Force-reindex rolls
+ # back, keeping the RAGIndex rows (the remote collections' only
+ # handle); the message says whether a retry can help and whether
+ # some collections were already dropped (#5765). Logged from the
+ # error's sanitized fields, with no traceback (a traceback would
+ # add frame state; the backend's error text can carry secrets).
+ drop_detail = exc.log_detail()
+ logger.warning(
+ "Force-reindex aborted: could not drop the vector-store "
+ f"collection before rebuilding it: {drop_detail}"
+ )
+ drop_error = {
+ "type": "error",
+ "error": remote_drop_failure_message(
+ exc, "indexing was aborted"
+ ),
+ }
+ yield f"data: {json.dumps(drop_error)}\n\n"
except Exception:
logger.exception("Error in collection indexing")
yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
@@ -3856,6 +3962,7 @@ def _background_index_worker(
db_password: str,
force_reindex: bool,
max_workers: int = 4,
+ settings_snapshot: Optional[dict] = None,
):
"""
Background worker thread for indexing documents.
@@ -3867,8 +3974,16 @@ def _background_index_worker(
this worker — background threads cannot call
: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).
"""
from ...database.session_context import get_user_db_session
+ from ...research_library.deletion.utils.cascade_helper import (
+ RemoteVectorStoreDropError,
+ remote_drop_failure_message,
+ )
try:
# Create RAG service (thread-safe, no Flask context needed)
@@ -3905,7 +4020,10 @@ def _background_index_worker(
changed = True
if force_reindex:
faiss_reset_paths = _reset_collection_for_reindex(
- db_session, collection_id
+ db_session,
+ collection_id,
+ username,
+ settings_snapshot=settings_snapshot,
)
changed = True
if changed:
@@ -4127,6 +4245,25 @@ def _background_index_worker(
f"Background indexing task {task_id} completed: {results}"
)
+ except RemoteVectorStoreDropError as exc:
+ # Caught ahead of the catch-all below: this is an actionable
+ # vector-store failure, not an internal error (see index_all's
+ # handler), and logged the same way.
+ drop_detail = exc.log_detail()
+ logger.warning(
+ f"Background indexing task {task_id}: force-reindex aborted, "
+ f"could not drop the vector-store collection before rebuilding "
+ f"it: {drop_detail}"
+ )
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ status="failed",
+ error_message=remote_drop_failure_message(
+ exc, "indexing was aborted"
+ ),
+ )
except Exception as e:
logger.exception(f"Background indexing task {task_id} failed")
_update_task_status(
@@ -4354,6 +4491,27 @@ def _start_background_index_sync(
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
+ # 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
+ # read_vector_cleanup_settings_snapshot).
+ from ...research_library.deletion.utils.cascade_helper import (
+ read_vector_cleanup_settings_snapshot,
+ )
+
+ _bg_settings_snapshot = (
+ read_vector_cleanup_settings_snapshot(
+ get_settings_manager(db_session, username)
+ )
+ if force_reindex
+ else None
+ )
+
# Create new task
task_id = str(uuid.uuid4())
task = TaskMetadata(
@@ -4402,6 +4560,7 @@ def _start_background_index_sync(
db_password,
force_reindex,
_bg_max_workers,
+ settings_snapshot=_bg_settings_snapshot,
)
thread = threading.Thread(target=_ctx_worker, daemon=True)
diff --git a/tests/research_library/deletion/test_provider_aware_vector_cleanup.py b/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
new file mode 100644
index 0000000000..0b1758b568
--- /dev/null
+++ b/tests/research_library/deletion/test_provider_aware_vector_cleanup.py
@@ -0,0 +1,1163 @@
+"""Provider-aware vector cleanup in the library deletion cascade (issue #5765).
+
+The cascade used to be FAISS-only: it deleted the ``RAGIndex`` rows and then,
+post-commit, unlinked ``.faiss``/``.pkl``/``.idmap.json`` files. For a
+server-backed store that is a silent no-op on files that never existed, and the
+remote collection is never dropped.
+
+Worse than a leak: a server-backed collection is named from ``username`` and
+``index_hash`` -- illustrated here as ``sha256(f"{username}:{index_hash}")``,
+though no such derivation exists yet (``BaseVectorStore.create()`` does not
+even receive those inputs; see ``vector_stores/base.py`` and issue #6769) --
+and ``index_hash`` lives on the very ``RAGIndex`` row the cascade deletes.
+Delete the row first and the vectors become *unaddressable* -- the app can no
+longer name them, so it can never clean them up.
+
+So the property under test is an ORDERING one: every remote drop must happen
+BEFORE any ``RAGIndex`` row is deleted, and a failed drop must abort the whole
+deletion rather than complete it.
+
+These tests use a stub provider registered in the vector-store registry, so
+they neither need nor import a real server backend (Milvus lands in #5331) --
+and the local-file assertions deliberately avoid importing ``faiss``.
+"""
+
+from contextlib import contextmanager
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+ RemoteVectorStoreDropError,
+ remote_drop_failure_message,
+)
+from local_deep_research.vector_stores import (
+ BaseVectorStore,
+ provider_is_local_file,
+)
+
+
+# --------------------------------------------------------------------------- #
+# Stub provider plumbing
+# --------------------------------------------------------------------------- #
+def _make_remote_stub(
+ events, *, error=None, result=True, implement=True, snapshots=None
+):
+ """Build a server-backed (``is_local_file = False``) store class.
+
+ ``drop_collection`` appends to ``events`` so tests can assert it ran, with
+ what, and -- crucially -- WHEN relative to the row deletes. The
+ ``settings_snapshot`` each call received is appended to ``snapshots``.
+ ``error`` is an exception to raise, or a callable mapping the
+ ``index_hash`` to one (or to None, to succeed).
+
+ Never instantiated (``drop_collection`` is a classmethod by design), so the
+ abstract methods are deliberately left unimplemented.
+ """
+
+ if snapshots is None:
+ snapshots = []
+
+ namespace = {
+ "provider_key": "stub_remote",
+ "provider_name": "Stub Remote",
+ "is_local_file": False,
+ }
+
+ if implement:
+
+ @classmethod
+ def drop_collection(
+ cls, *, username, index_hash, settings_snapshot=None
+ ):
+ events.append(("drop", username, index_hash))
+ snapshots.append(settings_snapshot)
+ failure = error(index_hash) if callable(error) else error
+ if failure is not None:
+ raise failure
+ return result
+
+ namespace["drop_collection"] = drop_collection
+
+ return type("_RemoteStub", (BaseVectorStore,), namespace)
+
+
+@contextmanager
+def _registered_as_default(store_class):
+ """Make ``store_class`` the resolved provider for the duration.
+
+ Pre-populating ``_PROVIDER_CLASSES`` also stops the registry lazily
+ importing the FAISS backend (and its native extension).
+ """
+ from local_deep_research.vector_stores import config as vs_config
+
+ saved_classes = dict(vs_config._PROVIDER_CLASSES)
+ saved_default = vs_config._DEFAULT_PROVIDER
+ vs_config._PROVIDER_CLASSES.clear()
+ vs_config._PROVIDER_CLASSES[store_class.provider_key] = store_class
+ vs_config._DEFAULT_PROVIDER = store_class.provider_key
+ try:
+ yield
+ finally:
+ vs_config._DEFAULT_PROVIDER = saved_default
+ vs_config._PROVIDER_CLASSES.clear()
+ vs_config._PROVIDER_CLASSES.update(saved_classes)
+
+
+def _fake_index(index_hash, index_path="/nowhere/idx"):
+ index = MagicMock()
+ index.index_hash = index_hash
+ index.index_path = index_path
+ index.collection_name = "collection_abc"
+ return index
+
+
+def _session_returning(indices, events=None):
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.all.return_value = indices
+ if events is not None:
+ session.delete.side_effect = lambda row: events.append(
+ ("delete_row", row.index_hash)
+ )
+ return session
+
+
+# --------------------------------------------------------------------------- #
+# The crux: ordering
+# --------------------------------------------------------------------------- #
+class TestRemoteDropOrdering:
+ def test_drops_every_remote_collection_before_deleting_any_row(self):
+ """THE fix for #5765.
+
+ Mutation check: moving the drop after the ``session.delete`` loop (the
+ pre-fix ordering, and the natural "clean up after commit" instinct)
+ flips these assertions.
+ """
+ events = []
+ indices = [_fake_index("hash-one"), _fake_index("hash-two")]
+ session = _session_returning(indices, events)
+
+ with _registered_as_default(_make_remote_stub(events)):
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ assert events == [
+ ("drop", "alice", "hash-one"),
+ ("drop", "alice", "hash-two"),
+ ("delete_row", "hash-one"),
+ ("delete_row", "hash-two"),
+ ]
+ # Stated as the invariant too, so a future reordering fails loudly on
+ # the property and not just on an exact-sequence equality.
+ last_drop = max(i for i, e in enumerate(events) if e[0] == "drop")
+ first_row_delete = min(
+ i for i, e in enumerate(events) if e[0] == "delete_row"
+ )
+ assert last_drop < first_row_delete
+ assert result["deleted_indices"] == 2
+
+ def test_remote_store_reports_no_files_to_unlink(self):
+ """A server-backed store has no .faiss/.pkl to unlink.
+
+ Returning its ``index_path`` would send the caller's post-commit
+ cleanup after a file that never existed -- the original silent no-op.
+ """
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+
+ with _registered_as_default(_make_remote_stub(events)):
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ assert result["index_paths"] == []
+ assert result["deleted_files"] == 0
+
+ def test_remote_store_does_not_unlink_files_when_unlink_files_true(
+ self, tmp_path
+ ):
+ """Even on the unlink_files=True path, no filesystem work happens.
+
+ The stray ``.faiss`` file is placed INSIDE ``get_cache_directory() /
+ "rag_indices"`` -- which is patched to ``tmp_path`` -- so it sits
+ squarely within ``delete_faiss_index_files``'s ``allowed_root``
+ containment check. If the ``is_local_file`` guards were fully
+ reverted (so the code always tried the FAISS unlink path for any
+ provider), the containment check alone would NOT refuse this path
+ and would happily delete it -- so "the file still exists" would pass
+ for the wrong reason (rescued by containment, not by the
+ server-backed dispatch this test is meant to cover). ``delete_files``
+ is a mock (``patch.object`` on ``delete_faiss_index_files``), so the
+ file is never at risk either way; asserting
+ ``delete_faiss_index_files.assert_not_called()`` checks the actual
+ dispatch instead of a filesystem side effect that the mock makes
+ meaningless.
+ """
+ events = []
+ rag_indices_root = tmp_path / "rag_indices"
+ rag_indices_root.mkdir()
+ stray = rag_indices_root / "idx.faiss"
+ stray.write_text("not really a faiss index")
+ session = _session_returning(
+ [_fake_index("hash-one", str(rag_indices_root / "idx"))], events
+ )
+
+ with (
+ _registered_as_default(_make_remote_stub(events)),
+ patch(
+ "local_deep_research.config.paths.get_cache_directory",
+ return_value=tmp_path,
+ ),
+ patch.object(
+ CascadeHelper, "delete_faiss_index_files"
+ ) as delete_files,
+ ):
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=True,
+ username="alice",
+ )
+
+ delete_files.assert_not_called()
+
+
+# --------------------------------------------------------------------------- #
+# Failure mode: refuse to complete a deletion we cannot make good on
+# --------------------------------------------------------------------------- #
+class TestRemoteDropFailureAborts:
+ def test_unreachable_store_aborts_before_any_row_is_deleted(self):
+ events = []
+ indices = [_fake_index("hash-one"), _fake_index("hash-two")]
+ session = _session_returning(indices, events)
+ stub = _make_remote_stub(events, error=ConnectionError("no route"))
+
+ with _registered_as_default(stub):
+ with pytest.raises(RemoteVectorStoreDropError) as excinfo:
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ session.delete.assert_not_called()
+ # The message must say the row survives.
+ assert "NOT deleted" in str(excinfo.value)
+ assert excinfo.value.retryable is True
+ assert excinfo.value.cause_type == "ConnectionError"
+
+ def test_missing_username_refuses_rather_than_orphaning(self):
+ """Half the derived collection name is the username.
+
+ Without it the vectors cannot be named, so deleting the rows would
+ strand them permanently -- refuse instead.
+ """
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+
+ with _registered_as_default(_make_remote_stub(events)):
+ with pytest.raises(RemoteVectorStoreDropError):
+ CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc", unlink_files=False
+ )
+
+ session.delete.assert_not_called()
+ assert events == []
+
+ def test_row_without_index_hash_refuses(self):
+ events = []
+ session = _session_returning([_fake_index("")], events)
+
+ with _registered_as_default(_make_remote_stub(events)):
+ with pytest.raises(RemoteVectorStoreDropError):
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ session.delete.assert_not_called()
+
+ def test_a_bad_row_after_good_ones_drops_nothing(self):
+ """The validation pass must run in full BEFORE any drop_collection
+ call. A bad row sorted after good ones must not let the loop drop
+ their collections first and only then abort -- that would destroy
+ remote collections whose rows survive the rollback, with no way to
+ re-drop them."""
+ events = []
+ session = _session_returning(
+ [_fake_index("hash-one"), _fake_index("")], events
+ )
+
+ with _registered_as_default(_make_remote_stub(events)):
+ with pytest.raises(RemoteVectorStoreDropError):
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ assert events == []
+ session.delete.assert_not_called()
+
+ def test_server_backed_store_without_a_drop_implementation_refuses(self):
+ """A backend that sets is_local_file=False but never implemented
+ drop_collection would otherwise orphan every collection it created.
+ The base class's NotImplementedError is caught and converted."""
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+ stub = _make_remote_stub(events, implement=False)
+
+ with _registered_as_default(stub):
+ with pytest.raises(RemoteVectorStoreDropError):
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ session.delete.assert_not_called()
+
+ def test_already_absent_collection_is_not_an_error(self):
+ """drop_collection returning False means "nothing was there" -- an
+ idempotent re-delete must still remove the rows."""
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+
+ with _registered_as_default(_make_remote_stub(events, result=False)):
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ assert result["deleted_indices"] == 1
+ session.delete.assert_called_once()
+
+
+# --------------------------------------------------------------------------- #
+# No regression on the FAISS path
+# --------------------------------------------------------------------------- #
+class TestLocalFilePathUnchanged:
+ def test_default_provider_is_local_file(self):
+ """Guards the dispatch: if this ever flipped, every FAISS deletion
+ would start trying to drop a remote collection."""
+ assert provider_is_local_file() is True
+
+ def test_local_provider_defers_paths_and_never_drops(self, tmp_path):
+ """unlink_files=False must behave exactly as before: rows staged for
+ deletion, file left on disk, path handed back for the post-commit
+ unlink. No drop_collection anywhere near it."""
+ base = tmp_path / "rag_indices" / "idx"
+ base.parent.mkdir()
+ faiss_file = base.with_suffix(".faiss")
+ faiss_file.write_text("faiss-data")
+ session = _session_returning([_fake_index("hash-one", str(base))])
+
+ from local_deep_research.vector_stores import config as vs_config
+
+ # A server-backed row is the only thing that looks up a store class
+ # (to call its drop_collection); a FAISS row never does -- which also
+ # means the native faiss backend is never imported on this path.
+ with patch.object(vs_config, "get_vector_store_class") as never:
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc", unlink_files=False, username="alice"
+ )
+
+ never.assert_not_called()
+ assert result["index_paths"] == [str(base)]
+ assert result["deleted_indices"] == 1
+ assert faiss_file.exists()
+
+ def test_local_provider_still_unlinks_on_unlink_files_true(self, tmp_path):
+ base = tmp_path / "rag_indices" / "idx"
+ base.parent.mkdir()
+ faiss_file = base.with_suffix(".faiss")
+ faiss_file.write_text("faiss-data")
+ session = _session_returning([_fake_index("hash-one", str(base))])
+
+ with patch(
+ "local_deep_research.config.paths.get_cache_directory",
+ return_value=tmp_path,
+ ):
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc", unlink_files=True, username="alice"
+ )
+
+ assert result["deleted_files"] == 1
+ assert result["index_paths"] == []
+ assert not faiss_file.exists()
+
+ def test_drop_helper_is_a_noop_for_a_local_provider(self):
+ """Called directly (not via the cascade) it must still self-guard."""
+ assert (
+ CascadeHelper.drop_remote_vector_collections(
+ [_fake_index("hash-one")], username="alice"
+ )
+ == 0
+ )
+
+ def test_local_file_fast_path_matches_the_class_attribute(self):
+ """The registry keeps a cheap _LOCAL_FILE_PROVIDERS set so the deletion
+ path can branch without importing the native backend. Guard it against
+ drifting from the authoritative class attribute."""
+ pytest.importorskip("faiss")
+ from local_deep_research.vector_stores.config import (
+ _LOCAL_FILE_PROVIDERS,
+ )
+ from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+ )
+
+ assert (
+ FaissVectorStore.provider_key in _LOCAL_FILE_PROVIDERS
+ ) is FaissVectorStore.is_local_file
+
+
+# --------------------------------------------------------------------------- #
+# Service-level: a failed drop is reported as a FAILED deletion
+# --------------------------------------------------------------------------- #
+class TestCollectionDeletionServiceFailureReporting:
+ @staticmethod
+ def _patched_session(session):
+ cm = MagicMock()
+ cm.__enter__ = Mock(return_value=session)
+ cm.__exit__ = Mock(return_value=None)
+ return cm
+
+ def test_delete_collection_fails_when_vector_store_unreachable(self):
+ """Silently completing is the one option that is off the table: the
+ rows carry the only handle to the surviving vectors."""
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+ session.get.return_value = MagicMock(collection_type="custom")
+ stub = _make_remote_stub(events, error=ConnectionError("no route"))
+
+ with patch(
+ "local_deep_research.research_library.deletion.services."
+ "collection_deletion.get_user_db_session",
+ return_value=self._patched_session(session),
+ ):
+ with _registered_as_default(stub):
+ result = CollectionDeletionService(
+ username="testuser"
+ ).delete_collection("col-123")
+
+ assert result["deleted"] is False
+ assert "Vector store unreachable" in result["error"]
+ assert "the collection was not deleted" in result["error"]
+ assert result["retryable"] is True
+ assert result["vector_store_error"] is True
+ session.rollback.assert_called_once()
+ session.commit.assert_not_called()
+ # The username reached the drop -- it is half the collection name.
+ assert events == [("drop", "testuser", "hash-one")]
+
+ def test_delete_index_only_fails_when_vector_store_unreachable(self):
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+ session.get.return_value = MagicMock()
+ stub = _make_remote_stub(events, error=ConnectionError("no route"))
+
+ with patch(
+ "local_deep_research.research_library.deletion.services."
+ "collection_deletion.get_user_db_session",
+ return_value=self._patched_session(session),
+ ):
+ with _registered_as_default(stub):
+ result = CollectionDeletionService(
+ username="testuser"
+ ).delete_collection_index_only("col-123")
+
+ assert result["deleted"] is False
+ assert "Vector store unreachable" in result["error"]
+ assert result["retryable"] is True
+ assert result["vector_store_error"] is True
+ session.rollback.assert_called_once()
+ session.commit.assert_not_called()
+
+
+# --------------------------------------------------------------------------- #
+# The production callers must feed the user's settings snapshot through
+# --------------------------------------------------------------------------- #
+#
+# ``_registered_as_default`` above reaches the remote branch by overwriting
+# the global default, which is NOT how a user selects a provider: a provider
+# setting is read from the user's settings snapshot (that is the shape the
+# open Milvus PR, #5331, gives ``resolve_provider``: no snapshot -> the
+# default). So the tests below register the stub WITHOUT making it the
+# default, stand in a snapshot-reading ``resolve_provider``, and drive the
+# real production callers. If any caller stops passing the snapshot, the
+# provider resolves to FAISS, no drop happens, and they fail.
+
+_PROVIDER_SETTING = "local_search_vector_store_provider"
+
+
+def _snapshot_selecting(provider_key):
+ return {
+ _PROVIDER_SETTING: {"value": provider_key},
+ # Connection config travels in the same snapshot.
+ "local_search_stub_uri": {"value": "http://vector-store.invalid"},
+ }
+
+
+def _resolve_from_snapshot(settings_snapshot=None):
+ if not settings_snapshot:
+ return "faiss"
+ raw = settings_snapshot.get(_PROVIDER_SETTING)
+ if isinstance(raw, dict):
+ raw = raw.get("value")
+ return str(raw or "faiss")
+
+
+@contextmanager
+def _registered_behind_a_setting(store_class):
+ """Register ``store_class`` as selectable by a snapshot only.
+
+ The default stays FAISS; only a snapshot carrying the provider setting
+ selects the stub.
+ """
+ from local_deep_research.vector_stores import config as vs_config
+
+ saved_classes = dict(vs_config._PROVIDER_CLASSES)
+ vs_config._PROVIDER_CLASSES.clear()
+ vs_config._PROVIDER_CLASSES[store_class.provider_key] = store_class
+ try:
+ with patch.object(
+ vs_config, "resolve_provider", side_effect=_resolve_from_snapshot
+ ):
+ yield
+ finally:
+ vs_config._PROVIDER_CLASSES.clear()
+ vs_config._PROVIDER_CLASSES.update(saved_classes)
+
+
+def _settings_manager_returning(snapshot):
+ manager = Mock()
+ manager.get_all_settings.return_value = snapshot
+ return manager
+
+
+def _patched_user_session(session):
+ cm = MagicMock()
+ cm.__enter__ = Mock(return_value=session)
+ cm.__exit__ = Mock(return_value=None)
+ return patch(
+ "local_deep_research.research_library.deletion.services."
+ "collection_deletion.get_user_db_session",
+ return_value=cm,
+ )
+
+
+class TestProductionCallersForwardTheSettingsSnapshot:
+ @pytest.mark.parametrize(
+ "operation", ["delete_collection", "delete_collection_index_only"]
+ )
+ def test_service_drops_the_collection_of_the_configured_provider(
+ self, operation
+ ):
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ events, snapshots = [], []
+ snapshot = _snapshot_selecting("stub_remote")
+ session = _session_returning([_fake_index("hash-one")], events)
+ session.get.return_value = MagicMock(collection_type="custom")
+ stub = _make_remote_stub(events, snapshots=snapshots)
+
+ with (
+ _patched_user_session(session),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=_settings_manager_returning(snapshot),
+ ) as get_manager,
+ _registered_behind_a_setting(stub),
+ ):
+ service = CollectionDeletionService(username="testuser")
+ if operation == "delete_collection":
+ service.delete_collection(
+ "col-123", delete_orphaned_documents=False
+ )
+ else:
+ service.delete_collection_index_only("col-123")
+
+ # The snapshot is read through the deletion's own session, by a
+ # manager that must not seed-and-commit defaults mid-deletion.
+ get_manager.assert_called_once_with(session, seed_defaults=False)
+ assert ("drop", "testuser", "hash-one") in events, (
+ f"{operation}: the user's configured server-backed provider "
+ "was never asked to drop its collection -- the settings "
+ "snapshot did not reach the cascade"
+ )
+ # ...and it reached drop_collection, which needs its connection
+ # config.
+ assert snapshots == [snapshot]
+ # Still ordered: the drop precedes the row delete.
+ assert events.index(("drop", "testuser", "hash-one")) < events.index(
+ ("delete_row", "hash-one")
+ )
+
+ def test_without_the_setting_the_default_provider_is_used(self):
+ """Control for the test above: the same call with a snapshot that
+ does not select the stub resolves to FAISS and drops nothing -- so
+ it is the forwarded snapshot, not the stub's registration, that
+ selects the provider."""
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+ session.get.return_value = MagicMock(collection_type="custom")
+
+ with (
+ _patched_user_session(session),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=_settings_manager_returning({}),
+ ),
+ _registered_behind_a_setting(_make_remote_stub(events)),
+ ):
+ CollectionDeletionService(username="testuser").delete_collection(
+ "col-123", delete_orphaned_documents=False
+ )
+
+ 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,
+ )
+
+ 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
+ )
+
+ assert events[:2] == [
+ ("drop", "alice", "hash-one"),
+ ("delete_row", "hash-one"),
+ ]
+ assert snapshots == [snapshot]
+ assert paths == []
+
+
+# --------------------------------------------------------------------------- #
+# Per-row provider, resolved once
+# --------------------------------------------------------------------------- #
+class TestPerRowProviderResolution:
+ def test_mixed_provider_rows_are_each_cleaned_up_by_their_own_provider(
+ self, tmp_path
+ ):
+ """Once ``RAGIndex`` records its provider (the open Milvus PR adds
+ ``vector_store_provider``), a user who switched providers holds rows
+ of both kinds in one collection. Each row must be cleaned up by the
+ provider that built it: a FAISS row's files are handed back for
+ unlinking and a server-backed row's collection is dropped --
+ whatever the current setting says."""
+ events = []
+ faiss_row = _fake_index("hash-faiss", str(tmp_path / "idx"))
+ faiss_row.vector_store_provider = "faiss"
+ remote_row = _fake_index("hash-remote")
+ remote_row.vector_store_provider = "stub_remote"
+ session = _session_returning([faiss_row, remote_row], events)
+
+ # No snapshot: the configured provider is FAISS.
+ with _registered_behind_a_setting(_make_remote_stub(events)):
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc", unlink_files=False, username="alice"
+ )
+
+ assert [e for e in events if e[0] == "drop"] == [
+ ("drop", "alice", "hash-remote")
+ ]
+ assert result["index_paths"] == [str(tmp_path / "idx")]
+ assert result["deleted_indices"] == 2
+
+ def test_a_recorded_faiss_row_is_not_dropped_under_a_remote_setting(self):
+ events = []
+ faiss_row = _fake_index("hash-faiss")
+ faiss_row.vector_store_provider = "faiss"
+ session = _session_returning([faiss_row], events)
+
+ with _registered_behind_a_setting(_make_remote_stub(events)):
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ settings_snapshot=_snapshot_selecting("stub_remote"),
+ )
+
+ assert [e for e in events if e[0] == "drop"] == []
+ assert result["index_paths"] == ["/nowhere/idx"]
+
+ def test_the_configured_provider_is_resolved_once_per_call(self):
+ """Resolving it separately for the drop and for the delete loop
+ could flip between the reads -- skipping both the drop and the
+ unlink while still deleting the rows."""
+ from local_deep_research.vector_stores import config as vs_config
+
+ events = []
+ session = _session_returning(
+ [_fake_index("h1"), _fake_index("h2"), _fake_index("h3")], events
+ )
+ snapshot = _snapshot_selecting("stub_remote")
+
+ with _registered_behind_a_setting(_make_remote_stub(events)):
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ settings_snapshot=snapshot,
+ )
+ resolve_calls = vs_config.resolve_provider.call_count
+
+ assert resolve_calls == 1
+ assert [e[0] for e in events] == ["drop"] * 3 + ["delete_row"] * 3
+
+ def test_an_unknown_recorded_provider_refuses_permanently(self):
+ events = []
+ row = _fake_index("hash-one")
+ row.vector_store_provider = "no_such_provider"
+ session = _session_returning([row], events)
+
+ with _registered_behind_a_setting(_make_remote_stub(events)):
+ with pytest.raises(RemoteVectorStoreDropError) as excinfo:
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username="alice",
+ )
+
+ assert excinfo.value.retryable is False
+ session.delete.assert_not_called()
+
+ def test_a_generator_of_rows_is_validated_before_anything_is_dropped(self):
+ """``drop_remote_vector_collections`` accepts any iterable. A
+ generator walked twice (validate, then drop) would be exhausted by
+ the validation pass; one walked lazily would drop the good row
+ before reaching the bad one."""
+ events = []
+
+ with _registered_as_default(_make_remote_stub(events)):
+ with pytest.raises(RemoteVectorStoreDropError):
+ CascadeHelper.drop_remote_vector_collections(
+ (row for row in [_fake_index("good"), _fake_index("")]),
+ username="alice",
+ )
+ assert events == []
+
+ dropped = CascadeHelper.drop_remote_vector_collections(
+ (row for row in [_fake_index("one"), _fake_index("two")]),
+ username="alice",
+ )
+
+ assert dropped == 2
+ assert events == [("drop", "alice", "one"), ("drop", "alice", "two")]
+
+
+# --------------------------------------------------------------------------- #
+# Transient vs permanent failures, partial drops, and what gets surfaced
+# --------------------------------------------------------------------------- #
+class _ClientSaysRetryable(Exception):
+ retryable = True
+
+
+class _ClientSaysPermanent(ConnectionError):
+ retryable = False
+
+
+def _drop_error(stub, *, username="alice", rows=None):
+ session = _session_returning(rows or [_fake_index("hash-one")])
+ with _registered_as_default(stub):
+ with pytest.raises(RemoteVectorStoreDropError) as excinfo:
+ CascadeHelper.delete_rag_indices_for_collection(
+ session,
+ "collection_abc",
+ unlink_files=False,
+ username=username,
+ )
+ session.delete.assert_not_called()
+ return excinfo.value
+
+
+class TestFailureClassification:
+ @pytest.mark.parametrize(
+ ("error", "retryable"),
+ [
+ (ConnectionError("refused"), True),
+ (ConnectionRefusedError("refused"), True),
+ (TimeoutError("timed out"), True),
+ (_ClientSaysRetryable("503 from server"), True),
+ (PermissionError("forbidden"), False),
+ (RuntimeError("authentication failed"), False),
+ (ValueError("bad collection name"), False),
+ (_ClientSaysPermanent("TLS certificate rejected"), False),
+ ],
+ ids=lambda value: (
+ type(value).__name__
+ if isinstance(value, BaseException)
+ else str(value)
+ ),
+ )
+ def test_only_transient_failures_are_retryable(self, error, retryable):
+ exc = _drop_error(_make_remote_stub([], error=error))
+
+ assert exc.retryable is retryable
+ assert exc.cause_type == type(error).__name__
+
+ def test_a_missing_drop_implementation_is_permanent(self):
+ exc = _drop_error(_make_remote_stub([], implement=False))
+
+ assert exc.retryable is False
+ assert exc.cause_type == "NotImplementedError"
+
+ def test_a_missing_username_is_permanent(self):
+ assert _drop_error(_make_remote_stub([]), username=None).retryable is (
+ False
+ )
+
+ def test_a_missing_index_hash_is_permanent(self):
+ exc = _drop_error(_make_remote_stub([]), rows=[_fake_index("")])
+
+ assert exc.retryable is False
+
+ def test_the_messages_differ_for_transient_and_permanent(self):
+ transient = RemoteVectorStoreDropError("x", retryable=True)
+ permanent = RemoteVectorStoreDropError("x", retryable=False)
+
+ assert "Retry once the vector store is available" in (
+ remote_drop_failure_message(transient, "it was not deleted")
+ )
+ permanent_text = remote_drop_failure_message(
+ permanent, "it was not deleted"
+ )
+ assert "Retry once" not in permanent_text
+ assert "Retrying will not help" in permanent_text
+
+ def test_the_service_maps_a_permanent_failure_to_non_retryable(self):
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ session = _session_returning([_fake_index("hash-one")], [])
+ session.get.return_value = MagicMock(collection_type="custom")
+ stub = _make_remote_stub([], error=PermissionError("forbidden"))
+
+ with _patched_user_session(session), _registered_as_default(stub):
+ result = CollectionDeletionService(
+ username="testuser"
+ ).delete_collection("col-123")
+
+ assert result["deleted"] is False
+ assert result["retryable"] is False
+ assert result["vector_store_error"] is True
+ assert "Retry once" not in result["error"]
+ session.rollback.assert_called_once()
+ session.commit.assert_not_called()
+
+
+class TestPartialDropIsReportedHonestly:
+ def test_a_failure_after_earlier_drops_counts_them(self):
+ """Remote drops cannot be rolled back. When the second of three
+ fails, the first is already gone -- the error must say so rather
+ than let callers claim nothing was deleted."""
+ events = []
+ stub = _make_remote_stub(
+ events,
+ error=lambda index_hash: (
+ ConnectionError("down") if index_hash == "hash-two" else None
+ ),
+ )
+ rows = [_fake_index("hash-one"), _fake_index("hash-two")]
+ rows.append(_fake_index("hash-three"))
+
+ exc = _drop_error(stub, rows=rows)
+
+ assert exc.dropped == 1
+ assert [e for e in events if e[0] == "drop"] == [
+ ("drop", "alice", "hash-one"),
+ ("drop", "alice", "hash-two"),
+ ]
+ message = remote_drop_failure_message(exc, "the index was not deleted")
+ assert "nothing was deleted" not in message
+ assert "1 vector-store collection(s) had already been removed" in (
+ message
+ )
+ assert "force re-index" in message
+
+ def test_a_failure_on_the_first_drop_claims_no_removal(self):
+ exc = _drop_error(_make_remote_stub([], error=ConnectionError("down")))
+
+ assert exc.dropped == 0
+ assert "already been removed" not in remote_drop_failure_message(
+ exc, "the index was not deleted"
+ )
+
+
+class TestBackendErrorTextIsNotSurfaced:
+ def test_the_cause_text_is_neither_in_the_message_nor_chained(self):
+ """A network client's error text can carry the backend URI or a
+ token. Only its type name may be surfaced, and the cause must not be
+ chained: a chained cause is printed by any traceback logger."""
+ secret = "https://admin:[email protected]:19530"
+ exc = _drop_error(_make_remote_stub([], error=ConnectionError(secret)))
+
+ assert "s3cr3t-token" not in str(exc)
+ assert exc.__cause__ is None
+ assert exc.__suppress_context__ is True
+
+ def test_the_service_logs_no_traceback_for_a_failed_drop(self):
+ from local_deep_research.research_library.deletion.services import (
+ collection_deletion,
+ )
+
+ session = _session_returning([_fake_index("hash-one")], [])
+ session.get.return_value = MagicMock(collection_type="custom")
+ stub = _make_remote_stub(
+ [], error=ConnectionError("https://admin:s3cr3t-token@host")
+ )
+
+ with (
+ _patched_user_session(session),
+ _registered_as_default(stub),
+ patch.object(collection_deletion, "logger") as logger,
+ ):
+ collection_deletion.CollectionDeletionService(
+ username="testuser"
+ ).delete_collection("col-123")
+
+ logger.exception.assert_not_called()
+ logged = " ".join(str(c) for c in logger.method_calls)
+ assert "s3cr3t-token" not in logged
+
+
+# --------------------------------------------------------------------------- #
+# Reading the settings snapshot must not write, and must fail closed
+# --------------------------------------------------------------------------- #
+def empty_settings_session():
+ """A real SQLite session over a schema with an EMPTY settings table."""
+ from sqlalchemy import create_engine
+ from sqlalchemy.orm import sessionmaker
+
+ from local_deep_research.database.models import Base
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ try:
+ yield session
+ finally:
+ session.close()
+ engine.dispose()
+
+
+class TestSnapshotReadHasNoSideEffects:
+ def test_an_empty_settings_table_is_read_without_seeding_or_commit(
+ self, empty_settings_session
+ ):
+ """The snapshot is read mid-deletion through the deletion's own
+ session. A default ``SettingsManager`` seeds an empty settings table
+ and COMMITS -- outside the deletion's rollback. The deletion's read
+ must write nothing and still see every default."""
+ from local_deep_research.database.models import Setting
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ _user_settings_snapshot,
+ )
+ from local_deep_research.settings.manager import SettingsManager
+
+ session = empty_settings_session
+ with patch.object(session, "commit", wraps=session.commit) as commit:
+ snapshot = _user_settings_snapshot(session)
+
+ commit.assert_not_called()
+ assert not session.new
+ assert session.query(Setting).count() == 0
+ # Defaults-only is the CORRECT answer for an empty table.
+ defaults = SettingsManager().default_settings
+ assert set(defaults) <= set(snapshot)
+ for key in ("search.tool", "llm.provider"):
+ assert snapshot[key]["value"] == defaults[key]["value"]
+
+ def test_stored_settings_override_the_defaults(
+ self, empty_settings_session
+ ):
+ """Control: the read-only read still sees the user's own rows."""
+ from local_deep_research.database.models import Setting
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ _user_settings_snapshot,
+ )
+
+ session = empty_settings_session
+ session.add(
+ Setting(
+ key="search.tool",
+ value="user-choice",
+ type="SEARCH",
+ name="Search tool",
+ ui_element="text",
+ )
+ )
+ session.commit()
+
+ snapshot = _user_settings_snapshot(session)
+
+ assert snapshot["search.tool"]["value"] == "user-choice"
+ assert session.query(Setting).count() == 1
+
+
+class _UnreadableSettings:
+ """A settings manager whose strict read fails like a stale enum row."""
+
+ def __init__(self):
+ self.calls = []
+
+ def get_all_settings(self, strict=False):
+ self.calls.append(strict)
+ if strict:
+ raise LookupError("'CHAT' is not among the defined enum values")
+ return {"defaults": {"value": True}}
+
+
+class TestUnreadableSnapshotFailsClosed:
+ def test_it_degrades_to_defaults_while_only_local_stores_exist(self):
+ """FAISS-only: the snapshot cannot change the cleanup, so a broken
+ settings row must not block a deletion that would succeed."""
+ from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ read_vector_cleanup_settings_snapshot,
+ )
+
+ manager = _UnreadableSettings()
+
+ assert read_vector_cleanup_settings_snapshot(manager) == {
+ "defaults": {"value": True}
+ }
+ assert manager.calls == [True, False]
+
+ def test_it_refuses_once_a_server_backed_store_exists(self):
+ """A defaults-only snapshot would resolve the global default
+ provider and connection config, the drop would miss, and the rows
+ -- the only handle to the real collection -- would be deleted."""
+ from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ read_vector_cleanup_settings_snapshot,
+ )
+
+ manager = _UnreadableSettings()
+ with _registered_behind_a_setting(_make_remote_stub([])):
+ with pytest.raises(RemoteVectorStoreDropError) as info:
+ read_vector_cleanup_settings_snapshot(manager)
+
+ assert info.value.retryable is False
+ assert info.value.cause_type == "LookupError"
+ assert manager.calls == [True]
+
+ def test_the_service_aborts_before_dropping_or_deleting_anything(self):
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+ session.get.return_value = MagicMock(collection_type="custom")
+ stub = _make_remote_stub(events)
+
+ with (
+ _patched_user_session(session),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=_UnreadableSettings(),
+ ),
+ _registered_behind_a_setting(stub),
+ ):
+ result = CollectionDeletionService(
+ username="testuser"
+ ).delete_collection("col-123", delete_orphaned_documents=False)
+
+ assert result["deleted"] is False
+ assert result["vector_store_error"] is True
+ assert result["retryable"] is False
+ assert events == []
+ session.rollback.assert_called_once()
+ session.commit.assert_not_called()
+
+
+class TestDropPrecedesTheFirstWrite:
+ @pytest.mark.parametrize(
+ "operation", ["delete_collection", "delete_collection_index_only"]
+ )
+ def test_the_remote_drop_runs_before_the_chunk_delete(self, operation):
+ """The drop is a network call; made after the chunk delete it would
+ hold the user's database write lock for its whole duration."""
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ events = []
+ session = _session_returning([_fake_index("hash-one")], events)
+ session.get.return_value = MagicMock(collection_type="custom")
+ stub = _make_remote_stub(events)
+
+ with (
+ _patched_user_session(session),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=_settings_manager_returning(
+ _snapshot_selecting("stub_remote")
+ ),
+ ),
+ patch.object(
+ CascadeHelper,
+ "delete_collection_chunks",
+ side_effect=lambda *a, **k: events.append(("chunks",)) or 0,
+ ),
+ _registered_behind_a_setting(stub),
+ ):
+ service = CollectionDeletionService(username="testuser")
+ if operation == "delete_collection":
+ service.delete_collection(
+ "col-123", delete_orphaned_documents=False
+ )
+ else:
+ service.delete_collection_index_only("col-123")
+
+ assert ("chunks",) in events
+ assert events.index(("drop", "testuser", "hash-one")) < events.index(
+ ("chunks",)
+ )
diff --git a/tests/research_library/routes/test_rag_indexing_helpers.py b/tests/research_library/routes/test_rag_indexing_helpers.py
index e479922a97..5414791f9f 100644
--- a/tests/research_library/routes/test_rag_indexing_helpers.py
+++ b/tests/research_library/routes/test_rag_indexing_helpers.py
@@ -175,7 +175,7 @@ class TestResetCollectionForReindex:
"index_paths": ["/idx/a", "/idx/b"],
}
- paths = _reset_collection_for_reindex(db, "cid")
+ paths = _reset_collection_for_reindex(db, "cid", "alice")
cascade.delete_collection_chunks.assert_called_once_with(
db, "collection_cid"
@@ -186,7 +186,11 @@ class TestResetCollectionForReindex:
# 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
+ db,
+ "collection_cid",
+ unlink_files=False,
+ username="alice",
+ settings_snapshot=None,
)
assert paths == ["/idx/a", "/idx/b"]
# Marks documents unindexed
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 0bb9d5e4c1..ba7cdd0977 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 AsyncMock, MagicMock, Mock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch
import pytest
@@ -1093,7 +1093,14 @@ class TestIndexAll:
)
mock_store.assert_called_once_with(mock_coll, mock_rag)
- mock_reset.assert_called_once_with(db_session, "coll-1")
+ # 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
+ )
def test_incremental_does_not_reset(self):
"""A non-force index-all must NOT wipe existing chunks/indices."""
@@ -1208,16 +1215,21 @@ class TestCommitOnceThenUnlinkAfterCommit:
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_service=mock_rag,
query_params={
"collection_id": "coll-1",
"force_reindex": "true",
},
)
- reset.assert_called_once_with(db_session, "coll-1")
+ # 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
@@ -1239,13 +1251,18 @@ class TestCommitOnceThenUnlinkAfterCommit:
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_service=mock_rag,
query_params={"force_reindex": "true"},
)
- reset.assert_called_once_with(db_session, "coll-1")
+ # 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
@@ -1289,7 +1306,12 @@ class TestCommitOnceThenUnlinkAfterCommit:
_background_index_worker(
"task-1", "coll-1", USERNAME, "pass", force_reindex=True
)
- reset.assert_called_once_with(db_session, "coll-1")
+ # 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
diff --git a/tests/web/routers/test_library_delete_branch_outcomes.py b/tests/web/routers/test_library_delete_branch_outcomes.py
index dc71efa32f..671a97b385 100644
--- a/tests/web/routers/test_library_delete_branch_outcomes.py
+++ b/tests/web/routers/test_library_delete_branch_outcomes.py
@@ -315,6 +315,42 @@ def test_a_collection_refused_for_another_reason_is_a_400():
assert _body(response)["success"] is False
+def test_deleting_a_collection_with_unreachable_vector_store_is_a_503():
+ """The vector-store-unreachable shape (``retryable: True``, set by
+ ``CollectionDeletionService`` when ``RemoteVectorStoreDropError``
+ propagates from the cascade -- see #5765) must be a 503, not fall
+ through to the 404/400 branches below it. The collection was not
+ deleted (the service rolled back), so a client retrying this exact
+ request can succeed once the vector store is reachable again (the drop
+ is idempotent) -- a 503 says so; a
+ 404 would read as "already gone" to a naive retry/cleanup layer, which
+ would then mark it deleted while the RAGIndex rows and remote vectors
+ both survive.
+ """
+ service = Mock()
+ service.delete_collection.return_value = {
+ "deleted": False,
+ "error": (
+ "Vector store unreachable — the collection was not deleted. "
+ "Retry once the vector store is available."
+ ),
+ "vector_store_error": True,
+ "retryable": True,
+ }
+
+ response = _call(
+ delete_collection, _request(), "coll-1", collection=service
+ )
+
+ assert response.status_code == 503, (
+ f"a retryable vector-store-unreachable failure must be 503, got "
+ f"{response.status_code}"
+ )
+ body = _body(response)
+ assert body["success"] is False
+ assert body["retryable"] is True
+
+
def test_deleting_a_collection_asks_for_orphan_cleanup():
"""``delete_orphaned_documents=True`` is the difference between deleting
a collection and leaving its documents behind as unreachable rows."""
@@ -371,6 +407,79 @@ def test_deleting_the_index_of_a_missing_collection_is_a_404():
assert _body(response)["success"] is False
+def test_deleting_the_index_with_unreachable_vector_store_is_a_503():
+ """Same 503 mapping as ``delete_collection`` above, for the sibling
+ endpoint -- see #5765."""
+ service = Mock()
+ service.delete_collection_index_only.return_value = {
+ "deleted": False,
+ "error": (
+ "Vector store unreachable — the index was not deleted. Retry "
+ "once the vector store is available."
+ ),
+ "vector_store_error": True,
+ "retryable": True,
+ }
+
+ response = _call(
+ delete_collection_index, _request(), "coll-1", collection=service
+ )
+
+ assert response.status_code == 503, (
+ f"a retryable vector-store-unreachable failure must be 503, got "
+ f"{response.status_code}"
+ )
+ body = _body(response)
+ assert body["success"] is False
+ assert body["retryable"] is True
+
+
+_PERMANENT_DROP_FAILURE = {
+ "deleted": False,
+ "error": (
+ "The vector store could not drop the collection — the index was "
+ "not deleted. Retrying will not help until the vector store "
+ "configuration or permissions are fixed; see the server log."
+ ),
+ "vector_store_error": True,
+ "retryable": False,
+}
+
+
+def test_deleting_a_collection_with_a_permanent_drop_failure_is_a_500():
+ """A drop that fails for a reason a retry cannot fix (auth, missing
+ configuration, a store with no drop support -- #5765) is neither a 503
+ (which invites a retry) nor a 404 (which reads as "already gone"), nor
+ the generic 400 for a bad request."""
+ service = Mock()
+ service.delete_collection.return_value = dict(_PERMANENT_DROP_FAILURE)
+
+ response = _call(
+ delete_collection, _request(), "coll-1", collection=service
+ )
+
+ assert response.status_code == 500
+ body = _body(response)
+ assert body["success"] is False
+ assert body["retryable"] is False
+
+
+def test_deleting_the_index_with_a_permanent_drop_failure_is_a_500():
+ service = Mock()
+ service.delete_collection_index_only.return_value = dict(
+ _PERMANENT_DROP_FAILURE
+ )
+
+ response = _call(
+ delete_collection_index, _request(), "coll-1", collection=service
+ )
+
+ assert response.status_code == 500
+ body = _body(response)
+ assert body["success"] is False
+ assert body["retryable"] is False
+
+
# ===========================================================================
# The two deletion previews
# ===========================================================================
@@ -571,3 +680,21 @@ def test_a_service_crash_is_a_scrubbed_500_not_a_traceback(
response = _call(handler, _request(), *args, **{kind: service})
_assert_scrubbed_500(response)
+
+
+def test_a_generic_index_delete_failure_is_a_500_not_a_404():
+ """The service's generic failure (it rolled back) is not "already
+ gone": a 404 would let a cleanup layer mark the index deleted."""
+ service = Mock()
+ service.delete_collection_index_only.return_value = {
+ "deleted": False,
+ "collection_id": "coll-1",
+ "error": "Failed to delete collection index",
+ }
+
+ response = _call(
+ delete_collection_index, _request(), "coll-1", collection=service
+ )
+
+ assert response.status_code == 500
+ assert _body(response)["success"] is False
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 3e423b63de..bfc8ae6c76 100644
--- a/tests/web/routers/test_rag_reindex_commit_then_unlink.py
+++ b/tests/web/routers/test_rag_reindex_commit_then_unlink.py
@@ -30,12 +30,15 @@ two.
"""
import json
-from contextlib import contextmanager
+from contextlib import ExitStack, 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"
@@ -44,6 +47,15 @@ _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
@@ -85,6 +97,7 @@ def _db_session():
def _settings_manager():
manager = Mock()
manager.get_setting.side_effect = lambda key, default=None: default
+ manager.get_all_settings.return_value = SETTINGS_SNAPSHOT
return manager
@@ -116,11 +129,17 @@ def _reindex_recorder(db_session, extra=()):
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.
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
),
patch.object(rag_module, "_store_collection_embedding_metadata"),
patch.object(
@@ -137,7 +156,7 @@ def _reindex_recorder(db_session, extra=()):
*extra,
]
started = [p.start() for p in patches]
- reset_mock, unlink_mock = started[3], started[4]
+ reset_mock, unlink_mock = started[4], started[5]
try:
yield call_order, reset_mock, unlink_mock
finally:
@@ -164,7 +183,17 @@ def _run_index_all(db_session):
username="alice",
)
_drain(response)
- reset_mock.assert_called_once_with(db_session, "coll-1")
+ # 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
@@ -191,7 +220,14 @@ def _run_index_collection(db_session):
username="alice",
)
_drain(response)
- reset_mock.assert_called_once_with(db_session, "coll-1")
+ # 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
@@ -210,10 +246,25 @@ def _run_background_worker(db_session):
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
+ "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,
)
- reset_mock.assert_called_once_with(db_session, "coll-1")
unlink_mock.assert_called_once_with(FAISS_PATHS)
return call_order, db_session.commit.call_count
@@ -312,6 +363,226 @@ def test_nothing_is_reset_or_unlinked_without_force_reindex(site):
)
+# ===========================================================================
+# 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(),
+ )
+ )
+ 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)),
+ )
+ )
+ return _drain(
+ rag_module.index_collection(
+ _request(
+ path="/library/api/collections/coll-1/index",
+ query_string=b"force_reindex=true",
+ ),
+ "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']}"
+ )
+
+
+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
diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.py
index cf8aaac0e6..bcb79c34a6 100644
--- a/tests/web/test_route_table_parity.py
+++ b/tests/web/test_route_table_parity.py
@@ -1733,6 +1733,16 @@ EXPECTED_STATUS_CODES_GAINED = {
("POST", "/settings/api/search-favorites/toggle"): [403],
("POST", "/settings/save_all_settings"): [403],
("PUT", "/settings/api/search-favorites"): [403],
+ # New branches (#5765): when the deletion cascade cannot drop a
+ # (currently hypothetical -- FAISS is the only shipping provider)
+ # server-backed vector collection, the index is not deleted and the
+ # route answers 503 (vector store unreachable, retryable) or 500
+ # (a failure a retry won't fix) instead of the sibling 404, so a retry
+ # layer doesn't read the failure as "already gone" and mark it deleted.
+ # Kept as literal `JSONResponse(..., status_code=...)` calls (like the
+ # existing literal 404 beside them) specifically so this scan sees
+ # them; library_delete.py:delete_collection_index.
+ ("DELETE", "/library/api/collections/{}/index"): [500, 503],
# Mass-assignment fix: FolderManager.update_folder used to run a blind
# hasattr-gated setattr loop (accepting any field name, including
# SQLAlchemy internals). normalize_folder_update now allowlists