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.

refactor(rag): dedicated vector-store module for the library RAG index (#5143)

LearningCircuit3ff108d75004
diff --git a/.github/scripts/check-file-writes.sh b/.github/scripts/check-file-writes.sh
index 201157a3dc..1623296d2b 100755
--- a/.github/scripts/check-file-writes.sh
+++ b/.github/scripts/check-file-writes.sh
@@ -188,10 +188,17 @@ if [ -n "$ALL_MATCHES" ]; then
# metadata only — journal names, ISSNs, h-indices; no PII/secrets)
# - journal_quality/data_sources/*.py — same family, per-source adapters
# that write the intermediate JSON manifests under the user data dir
+ # - vector_stores/implementations/faiss_store.py — persists the faiss
+ # index (vectors + integer DocumentChunk.ids only, never chunk
+ # text/metadata; see base.py's "SECURITY INVARIANT" — the interface
+ # has no text parameter, so no backend can persist it)
+ # - vector_stores/legacy_cleanup.py — writes the text-free
+ # ``.idmap.json`` migration sidecar (plain position->uuid JSON map,
+ # no chunk text; see the module docstring / `_ID_RE`)
# If you add an entry here, document WHY the file's writes are safe
# (public data, not user-specific, not encrypted at rest by design).
if [ "$skip_line" -eq 0 ]; then
- if echo "$line" | grep -qE "web/app_factory\.py|document_loaders/bytes_loader\.py|journal_quality/downloader\.py|journal_quality/data_sources/.+\.py"; then
+ if echo "$line" | grep -qE "web/app_factory\.py|document_loaders/bytes_loader\.py|journal_quality/downloader\.py|journal_quality/data_sources/.+\.py|vector_stores/implementations/faiss_store\.py|vector_stores/legacy_cleanup\.py"; then
skip_line=1
fi
fi
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.yml
index 845a40b018..90fdac4c36 100644
--- a/.github/workflows/docker-tests.yml
+++ b/.github/workflows/docker-tests.yml
@@ -692,6 +692,27 @@ jobs:
echo "::endgroup::"
fi
+ # The library shard runs the legacy plaintext-.pkl RAG migration
+ # E2E test. Phase-1 (migrate_legacy_docstores) runs only at server
+ # STARTUP, so the legacy .pkl fixtures + encrypted-DB rows MUST be
+ # seeded BEFORE the server boots. Same KDF/env as init_test_database
+ # and the server so the seeded encrypted DB opens at login. Writes
+ # <LDR_DATA_DIR>/migtest_manifest.json for the node test to consume.
+ if [ "${SHARD}" = "library" ]; then
+ echo "::group::Seed legacy .pkl migration fixtures"
+ docker run --rm \
+ -v "${GITHUB_WORKSPACE}":/app \
+ -v "${GITHUB_WORKSPACE}/ci-data":/data \
+ -e TEST_ENV=true \
+ -e LDR_DATA_DIR=/data \
+ -e LDR_DB_CONFIG_KDF_ITERATIONS=1000 \
+ -e LDR_TEST_MODE=1 \
+ -w /app/src \
+ "${TEST_IMAGE}" \
+ python ../tests/ui_tests/seed_legacy_pkl_migration.py
+ echo "::endgroup::"
+ fi
+
echo "::group::Start application server"
docker run -d \
--name ldr-server \
@@ -746,10 +767,17 @@ jobs:
echo "::endgroup::"
echo "::group::Run UI tests for shard ${SHARD}"
+ # Mount the server's data volume read-through as /data and export
+ # LDR_DATA_DIR so the library shard's legacy-.pkl migration test can
+ # read <LDR_DATA_DIR>/migtest_manifest.json and make its on-disk
+ # assertions (the .pkl is gone, a text-free sidecar was written).
+ # Inert for every other shard: their node tests never read /data.
docker run --rm \
-v "${GITHUB_WORKSPACE}":/app \
+ -v "${GITHUB_WORKSPACE}/ci-data":/data \
-e CI=true \
-e PUPPETEER_HEADLESS=true \
+ -e LDR_DATA_DIR=/data \
-e LDR_DB_CONFIG_KDF_ITERATIONS=1000 \
-e LDR_TEST_MODE=1 \
--network host \
diff --git a/changelog.d/+test-queue-processor-env-gate.misc.md b/changelog.d/+test-queue-processor-env-gate.misc.md
new file mode 100644
index 0000000000..ec4925139c
--- /dev/null
+++ b/changelog.d/+test-queue-processor-env-gate.misc.md
@@ -0,0 +1 @@
+Pytest app fixtures now skip starting the background research queue processor by default, while `LDR_WEB_QUEUE_PROCESSOR_ENABLED=true` keeps an explicit opt-in for tests that exercise queue behavior.
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.py
index e356e08721..66994f746f 100644
--- a/src/local_deep_research/database/encrypted_db.py
+++ b/src/local_deep_research/database/encrypted_db.py
@@ -775,7 +775,50 @@ class DatabaseManager:
with self._connections_lock:
if username in self.connections:
return self.connections[username]
- return self._open_user_database_cold(username, password, open_start)
+ engine = self._open_user_database_cold(
+ username, password, open_start
+ )
+
+ # Phase 2 of the RAG vector-store cutover runs OUTSIDE init_lock (only
+ # on the path that actually did the cold-open — the early returns above
+ # belong to a thread that already ran it). It re-enters
+ # open_user_database() via get_user_db_session on a session-cache miss;
+ # doing it while still holding the non-reentrant init_lock would
+ # self-deadlock if a concurrent close_user_database() evicted the
+ # freshly-cached connection between the cache write and that re-entry.
+ if engine is not None:
+ self._run_phase2_rekey(username, password)
+ return engine
+
+ def _run_phase2_rekey(self, username: str, password: str) -> None:
+ """Re-key a user's legacy FAISS indices (uuid-keyed -> DocumentChunk.id
+ -keyed), once, at login. See vector_stores/legacy_rekey.py.
+
+ A fast no-op (one get_setting call) once the per-user marker
+ (research_library.rag_index_rekeyed_v2) is set, or when the user has no
+ legacy sidecars — the common case. Wrapped so a re-key problem never
+ blocks login; it logs its own errors. Must be called AFTER the init_lock
+ is released (see open_user_database) to avoid a re-entrant self-deadlock.
+ """
+ try:
+ from ..vector_stores.legacy_rekey import rekey_user_indexes
+
+ rekey_user_indexes(username, password)
+ except Exception as e:
+ # NO rendered traceback + redacted message — the password-redaction
+ # invariant (tests/security/test_password_redaction_invariant.py).
+ # `password` (the unrecoverable SQLCipher master key) is live in this
+ # frame and every frame of the rekey chain, so ANY traceback render
+ # leaks it under LDR_LOGURU_DIAGNOSE. logger.opt(exception=True) does
+ # NOT suppress that (it renders identically to logger.exception) and
+ # also evades the AST guardrail, so log a redacted message with no
+ # stack, matching every other handler in this file.
+ from ..security.log_sanitizer import redact_secrets
+
+ safe_msg = redact_secrets(str(e), password)
+ logger.warning(
+ f"RAG index re-key failed for user {username}: {safe_msg}"
+ )
def _open_user_database_cold(
self, username: str, password: str, open_start: float
@@ -935,6 +978,14 @@ class DatabaseManager:
with self._connections_lock:
self.connections[username] = engine
+ # NOTE: the phase-2 RAG index re-key does NOT run here. It re-enters
+ # open_user_database() (via get_user_db_session on a session-cache
+ # miss), and this method runs while holding the non-reentrant
+ # per-user init_lock — so a concurrent close_user_database() evicting
+ # the just-cached connection would make that re-entrant open miss the
+ # fast-path and self-deadlock on the lock this thread already holds.
+ # open_user_database() runs it AFTER releasing the lock instead.
+
elapsed_ms = (time.perf_counter() - open_start) * 1000
if elapsed_ms > 100:
logger.info(
diff --git a/src/local_deep_research/database/migrations/versions/0023_drop_chunk_collection_unique.py b/src/local_deep_research/database/migrations/versions/0023_drop_chunk_collection_unique.py
new file mode 100644
index 0000000000..8f431da83c
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0023_drop_chunk_collection_unique.py
@@ -0,0 +1,84 @@
+"""Drop the uix_chunk_collection unique constraint on document_chunks
+
+The RAG vector store was reworked to one-row-per-chunk keyed by the integer
+primary key (no cross-document chunk sharing). Under that model, identical text
+in two documents — or a repeated/blank chunk within one document — legitimately
+produces two ``document_chunks`` rows, which the old
+``UniqueConstraint(chunk_hash, collection_name)`` would reject with an
+IntegrityError on the first such insert. ``chunk_hash`` remains a plain index
+for query-time result de-duplication.
+
+Revision ID: 0023
+Revises: 0022
+Create Date: 2026-07-12
+
+Migration Notes:
+================
+- Uses SQLite batch mode (table recreation) for the constraint drop.
+- Idempotent: skips if the constraint is already absent (fresh databases
+ created after the model change never had it).
+"""
+
+from alembic import op
+from sqlalchemy import inspect, text
+
+# revision identifiers, used by Alembic.
+revision = "0023"
+down_revision = "0022"
+branch_labels = None
+depends_on = None
+
+_TABLE = "document_chunks"
+_CONSTRAINT = "uix_chunk_collection"
+
+
+def _has_unique_constraint(name: str) -> bool:
+ bind = op.get_bind()
+ inspector = inspect(bind)
+ if not inspector.has_table(_TABLE):
+ return False
+ names = {uc.get("name") for uc in inspector.get_unique_constraints(_TABLE)}
+ return name in names
+
+
+def upgrade():
+ if not _has_unique_constraint(_CONSTRAINT):
+ return
+ with op.batch_alter_table(_TABLE) as batch_op:
+ batch_op.drop_constraint(_CONSTRAINT, type_="unique")
+
+
+def downgrade():
+ if _has_unique_constraint(_CONSTRAINT):
+ return
+ bind = op.get_bind()
+ if not inspect(bind).has_table(_TABLE):
+ return
+ # The one-row-per-chunk model this migration enables legitimately produces
+ # duplicate (chunk_hash, collection_name) rows. Re-adding the UNIQUE
+ # constraint over such data raises a cryptic IntegrityError mid batch-rebuild
+ # and strands an _alembic_tmp_document_chunks table (only the upgrade path
+ # sweeps those). Detect duplicates first and fail with an actionable message
+ # — we must NOT silently delete rows to satisfy the constraint, because a
+ # dropped row's chunk text is user data whose only copy may be that row.
+ dupes = bind.execute(
+ text(
+ "SELECT COUNT(*) FROM ("
+ " SELECT 1 FROM document_chunks"
+ " GROUP BY chunk_hash, collection_name HAVING COUNT(*) > 1"
+ ")"
+ )
+ ).scalar()
+ if dupes:
+ raise RuntimeError(
+ f"Cannot downgrade past 0023: {dupes} (chunk_hash, collection_name) "
+ "group(s) in document_chunks contain duplicate rows, which the "
+ "re-added uix_chunk_collection UNIQUE constraint forbids. The "
+ "one-row-per-chunk vector-store model legitimately creates these. "
+ "De-duplicate document_chunks manually (choosing which rows to keep) "
+ "before downgrading, or remain on revision 0023+."
+ )
+ with op.batch_alter_table(_TABLE) as batch_op:
+ batch_op.create_unique_constraint(
+ _CONSTRAINT, ["chunk_hash", "collection_name"]
+ )
diff --git a/src/local_deep_research/database/migrations/versions/0024_chunk_id_autoincrement.py b/src/local_deep_research/database/migrations/versions/0024_chunk_id_autoincrement.py
new file mode 100644
index 0000000000..1a53b5b7cc
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0024_chunk_id_autoincrement.py
@@ -0,0 +1,75 @@
+"""Make document_chunks.id use SQLite AUTOINCREMENT (never reuse ids)
+
+The integer primary key of ``document_chunks`` keys the vector store. A plain
+SQLite ``INTEGER PRIMARY KEY`` is a ROWID, which SQLite RECYCLES: after the
+highest-id row is deleted, the next insert can reuse that id. Because vector
+removal is best-effort, a stale vector for a deleted id can outlive its row;
+if that id is then recycled by an unrelated later chunk, search would rehydrate
+the WRONG document's text by that id. ``AUTOINCREMENT`` makes the id strictly
+monotonic (never reused), closing that window.
+
+SQLite cannot ``ALTER`` a column to add AUTOINCREMENT, so this recreates the
+table (batch mode) with ``sqlite_autoincrement=True``, preserving all rows,
+columns and indexes. Idempotent: skips if the table is already AUTOINCREMENT
+(fresh databases created after the model change) or absent.
+
+Revision ID: 0024
+Revises: 0023
+Create Date: 2026-07-12
+"""
+
+from alembic import op
+from sqlalchemy import inspect
+
+# revision identifiers, used by Alembic.
+revision = "0024"
+down_revision = "0023"
+branch_labels = None
+depends_on = None
+
+_TABLE = "document_chunks"
+
+
+def _table_sql() -> str:
+ bind = op.get_bind()
+ row = bind.exec_driver_sql(
+ "SELECT sql FROM sqlite_master "
+ "WHERE type='table' AND name='document_chunks'"
+ ).fetchone()
+ return (row[0] or "") if row else ""
+
+
+def _has_autoincrement() -> bool:
+ return "AUTOINCREMENT" in _table_sql().upper()
+
+
+def upgrade():
+ bind = op.get_bind()
+ if not inspect(bind).has_table(_TABLE):
+ return
+ if _has_autoincrement():
+ return
+ # recreate="always" forces a full table rebuild even with no column ops;
+ # table_kwargs adds AUTOINCREMENT to the recreated CREATE TABLE. Existing
+ # rows (and their current ids) are copied over unchanged; only NEW ids
+ # become monotonic.
+ with op.batch_alter_table(
+ _TABLE,
+ recreate="always",
+ table_kwargs={"sqlite_autoincrement": True},
+ ):
+ pass
+
+
+def downgrade():
+ bind = op.get_bind()
+ if not inspect(bind).has_table(_TABLE):
+ return
+ if not _has_autoincrement():
+ return
+ with op.batch_alter_table(
+ _TABLE,
+ recreate="always",
+ table_kwargs={"sqlite_autoincrement": False},
+ ):
+ pass
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index d6d3626800..fcdfc2f27d 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -610,14 +610,24 @@ class DocumentChunk(Base):
created_at = Column(UtcDateTime, default=utcnow(), nullable=False)
last_accessed = Column(UtcDateTime, nullable=True)
- # Indexes for efficient queries
+ # Indexes for efficient queries.
+ # NOTE: the old UniqueConstraint("chunk_hash", "collection_name",
+ # name="uix_chunk_collection") was DROPPED (migration 0023). The RAG store
+ # is now one-row-per-chunk keyed by the int PK (no cross-document chunk
+ # sharing), so identical text in two documents legitimately produces two
+ # rows; the unique constraint would raise IntegrityError on that (and on a
+ # document with a repeated/blank chunk). chunk_hash stays a plain index for
+ # query-time result de-duplication.
__table_args__ = (
- UniqueConstraint(
- "chunk_hash", "collection_name", name="uix_chunk_collection"
- ),
Index("idx_chunk_source", "source_type", "source_id"),
Index("idx_chunk_collection", "collection_name", "created_at"),
Index("idx_chunk_embedding", "embedding_id"),
+ # AUTOINCREMENT so this id is NEVER reused after rows are deleted.
+ # The id keys the vector store; a plain SQLite ROWID gets recycled, so
+ # a recycled id could be re-adopted by an unrelated later chunk while a
+ # stale vector for the old id still lingers in the index — making search
+ # rehydrate the WRONG document's text. A monotonic id closes that.
+ {"sqlite_autoincrement": True},
)
def __repr__(self):
diff --git a/src/local_deep_research/database/session_passwords.py b/src/local_deep_research/database/session_passwords.py
index 31808ad31b..6949fb219a 100644
--- a/src/local_deep_research/database/session_passwords.py
+++ b/src/local_deep_research/database/session_passwords.py
@@ -100,3 +100,42 @@ class SessionPasswordStore(CredentialStoreBase):
# Global instance
session_password_store = SessionPasswordStore()
+
+
+def capture_request_db_password(username: str) -> Optional[str]:
+ """Best-effort capture of the encrypted-DB password from the request
+ thread.
+
+ ``ThreadPoolExecutor.submit`` does NOT copy the calling thread's
+ ``ContextVar`` snapshot, so background workers cannot recover the
+ password through the usual request-context probes. Callers that need
+ to hand a password to a worker (or to a service like the RAG factory
+ that must open the encrypted DB to read index config) capture it here
+ while still on the request thread and pass it explicitly.
+
+ Returns ``None`` if the password cannot be located — on encrypted-DB
+ installs the caller should then skip the DB-touching work rather than
+ fail loudly.
+ """
+ try:
+ from flask import (
+ g,
+ has_app_context,
+ has_request_context,
+ session as flask_session,
+ )
+
+ if has_app_context() and hasattr(g, "user_password"):
+ return g.user_password
+ if has_request_context():
+ session_id = flask_session.get("session_id")
+ if session_id:
+ return session_password_store.get_session_password(
+ username, session_id
+ )
+ except Exception:
+ logger.debug(
+ "Failed to capture DB password from request context",
+ exc_info=True,
+ )
+ return None
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index 4bc36e3df5..38a2744a81 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -954,6 +954,21 @@ def run_server():
diagnose=False,
)
logger.info("Starting Local Deep Research MCP server...")
+
+ # Phase-1 of the RAG plaintext-at-rest migration must run here too, not only
+ # in the ldr-web entrypoint: an MCP-only deployment (Claude Desktop / Code /
+ # OpenClaw) that never launches ldr-web would otherwise never purge a
+ # pre-existing legacy plaintext <hash>.pkl docstore, leaving chunk text on
+ # disk indefinitely. The sweep is filesystem-only (no DB/login needed),
+ # idempotent (a clean tree no-ops), and logs its own errors — wrapped so a
+ # cleanup issue never blocks the server. Mirrors web/app.py's main().
+ try:
+ from ..vector_stores.legacy_cleanup import migrate_legacy_docstores
+
+ migrate_legacy_docstores()
+ except Exception:
+ logger.exception("Legacy RAG docstore migration failed at MCP startup")
+
mcp.run(transport="stdio")
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 7f85e3d580..e099368734 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
@@ -7,7 +7,7 @@ Handles:
- RAG index and chunks are deleted
"""
-from typing import Dict, Any
+from typing import Dict, List, Any
from loguru import logger
@@ -145,11 +145,20 @@ class CollectionDeletionService:
)
)
- # 3. Delete RAGIndex records and FAISS files
+ # 3. Delete RAGIndex records (DB only). The on-disk FAISS files
+ # are unlinked AFTER the commit below — steps 4-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.
rag_result = CascadeHelper.delete_rag_indices_for_collection(
- session, collection_name
+ session, collection_name, unlink_files=False
)
result["indices_deleted"] = rag_result["deleted_indices"]
+ faiss_paths_to_unlink = rag_result["index_paths"]
+ # 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 —
+ # delete_document_completely does not touch DocumentChunk.
+ orphaned_doc_ids: List[str] = []
# 4. Count folders before deletion
result["folders_deleted"] = (
@@ -212,6 +221,7 @@ class CollectionDeletionService:
CascadeHelper.delete_document_completely(
session, doc_id
)
+ orphaned_doc_ids.append(doc_id)
result["orphaned_documents_deleted"] += 1
logger.info(
f"Deleted orphaned document {doc_id[:8]}..."
@@ -227,8 +237,6 @@ class CollectionDeletionService:
f"{result['orphaned_documents_deleted']} orphaned deleted"
)
- return result
-
except Exception:
logger.exception(f"Failed to delete collection {collection_id}")
session.rollback()
@@ -238,6 +246,47 @@ class CollectionDeletionService:
"error": "Failed to delete collection",
}
+ # Post-commit best-effort cleanup, OUTSIDE the deletion transaction and
+ # its try/except: the DB delete is already durable, so a failure here
+ # must NOT be reported as a failed collection delete — it isn't one. It
+ # would only leave orphaned files/vectors, logged for ops visibility.
+ for faiss_path in faiss_paths_to_unlink:
+ CascadeHelper.delete_faiss_index_files(faiss_path)
+
+ # Purge each hard-deleted orphan's vectors + chunk rows in its OTHER
+ # collections (this collection's chunks were removed in step 2). Reuses
+ # DocumentDeletionService's per-collection vector purge + chunk backstop.
+ if orphaned_doc_ids:
+ from .document_deletion import DocumentDeletionService
+ from ....database.models.library import DocumentChunk
+
+ deleter = DocumentDeletionService(self.username)
+ for doc_id in orphaned_doc_ids:
+ try:
+ with get_user_db_session(self.username) as purge_session:
+ coll_rows = (
+ purge_session.query(DocumentChunk.collection_name)
+ .filter_by(source_type="document", source_id=doc_id)
+ .distinct()
+ .all()
+ )
+ collection_ids = [
+ row[0].removeprefix("collection_")
+ for row in coll_rows
+ if row[0]
+ ]
+ deleter._purge_document_rag(
+ doc_id, collection_ids, full_delete=True
+ )
+ except Exception:
+ logger.opt(exception=True).error(
+ "Failed to purge orphaned document {} after collection "
+ "delete (delete already committed)",
+ doc_id,
+ )
+
+ return result
+
def delete_collection_index_only(
self, collection_id: str
) -> Dict[str, Any]:
@@ -279,11 +328,14 @@ class CollectionDeletionService:
)
)
- # 2. Delete RAGIndex records and FAISS files
+ # 2. Delete RAGIndex records (DB only). Files are unlinked after
+ # the commit — steps 3-5 do more DB work that could roll back,
+ # and a rollback can't restore files already removed from disk.
rag_result = CascadeHelper.delete_rag_indices_for_collection(
- session, collection_name
+ session, collection_name, unlink_files=False
)
result["indices_deleted"] = rag_result["deleted_indices"]
+ faiss_paths_to_unlink = rag_result["index_paths"]
# 3. Reset DocumentCollection indexed status
result["documents_reset"] = (
@@ -305,6 +357,11 @@ class CollectionDeletionService:
collection.chunk_overlap = None
session.commit()
+
+ # DB delete durable — now unlink the FAISS files (best-effort).
+ for faiss_path in faiss_paths_to_unlink:
+ CascadeHelper.delete_faiss_index_files(faiss_path)
+
result["deleted"] = True
logger.info(
diff --git a/src/local_deep_research/research_library/deletion/services/document_deletion.py b/src/local_deep_research/research_library/deletion/services/document_deletion.py
index 10d031a984..ec5e37f027 100644
--- a/src/local_deep_research/research_library/deletion/services/document_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/document_deletion.py
@@ -7,7 +7,7 @@ Handles:
- Remove from collection (unlink or delete if orphaned)
"""
-from typing import Dict, Any
+from typing import Dict, List, Any
from loguru import logger
@@ -17,9 +17,11 @@ from ....database.models.library import (
Document,
DocumentChunk,
DocumentCollection,
+ RagDocumentStatus,
SourceType,
)
from ....database.session_context import get_user_db_session
+from ....database.session_passwords import capture_request_db_password
from ..utils.cascade_helper import CascadeHelper
@@ -79,6 +81,18 @@ class DocumentDeletionService:
"error": str (if failed)
}
"""
+ result: Dict[str, Any] = {
+ "deleted": False,
+ "document_id": document_id,
+ "title": None,
+ "blob_deleted": False,
+ "blob_size": 0,
+ "chunks_deleted": 0,
+ "collections_unlinked": 0,
+ "file_deleted": False,
+ }
+ rag_collection_ids: List[str] = []
+
with get_user_db_session(self.username) as session:
try:
# Get document
@@ -110,16 +124,7 @@ class DocumentDeletionService:
}
title = document.title or document.filename or "Untitled"
- result: Dict[str, Any] = {
- "deleted": False,
- "document_id": document_id,
- "title": title,
- "blob_deleted": False,
- "blob_size": 0,
- "chunks_deleted": 0,
- "collections_unlinked": 0,
- "file_deleted": False,
- }
+ result["title"] = title
# 1. Get collections before deletion for chunk cleanup
collections = CascadeHelper.get_document_collections(
@@ -127,15 +132,40 @@ class DocumentDeletionService:
)
result["collections_unlinked"] = len(collections)
- # 2. Delete DocumentChunks for ALL collections this document is in
- total_chunks_deleted = 0
- for collection_id in collections:
- collection_name = f"collection_{collection_id}"
- chunks_deleted = CascadeHelper.delete_document_chunks(
- session, document_id, collection_name
+ # Every collection that may hold FAISS vectors / chunk rows
+ # for this document: the UNION of its linked collections and
+ # the collections that actually have chunk rows. The chunk-row
+ # half matters because a partial/failed reindex can leave
+ # chunks in a collection whose join row is gone or was never
+ # marked indexed. Used by the post-commit RAG purge below.
+ chunk_collection_rows = (
+ session.query(DocumentChunk.collection_name)
+ .filter_by(source_type="document", source_id=document_id)
+ .distinct()
+ .all()
+ )
+ rag_collection_ids = list(
+ {str(c) for c in collections}
+ | {
+ row[0].removeprefix("collection_")
+ for row in chunk_collection_rows
+ if row[0]
+ }
+ )
+
+ # 2. Count chunks for stats. The rows themselves (and their
+ # FAISS vectors) are removed in the post-commit RAG cleanup
+ # phase below — purge_document_vectors resolves the FAISS
+ # int ids from these rows, so they must outlive this
+ # transaction (mirrors NoteService.delete_note).
+ result["chunks_deleted"] = (
+ session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.source_id == document_id,
+ DocumentChunk.source_type == "document",
)
- total_chunks_deleted += chunks_deleted
- result["chunks_deleted"] = total_chunks_deleted
+ .count()
+ )
# 3. Get blob size before deletion (for stats)
result["blob_size"] = CascadeHelper.get_document_blob_size(
@@ -163,19 +193,18 @@ class DocumentDeletionService:
# 5. Update DownloadTracker
CascadeHelper.update_download_tracker(session, document)
- # 6. Delete the document and all related records
+ # 6. Delete the document and all related records (leaves the
+ # DocumentChunk rows for the post-commit cleanup phase).
CascadeHelper.delete_document_completely(session, document_id)
session.commit()
result["deleted"] = True
logger.info(
f"Deleted document {document_id[:8]}... ({title}): "
- f"{total_chunks_deleted} chunks, "
+ f"{result['chunks_deleted']} chunks, "
f"{result['blob_size']} bytes blob"
)
- return result
-
except Exception:
logger.exception(f"Failed to delete document {document_id}")
session.rollback()
@@ -185,6 +214,97 @@ class DocumentDeletionService:
"error": "Failed to delete document",
}
+ # Post-commit FAISS + chunk-row cleanup. Runs after the deletion
+ # transaction has committed — releasing SQLite's single write lock —
+ # so the slow vector-store IO never blocks another writer.
+ if result["deleted"]:
+ self._purge_document_rag(
+ document_id, rag_collection_ids, full_delete=True
+ )
+
+ return result
+
+ def _purge_document_rag(
+ self,
+ document_id: str,
+ collection_ids: List[str],
+ *,
+ full_delete: bool,
+ ) -> None:
+ """Remove a document's FAISS vectors and chunk rows post-commit.
+
+ Called after the deletion/unlink transaction has committed —
+ releasing SQLite's single write lock — so the slow vector-store IO
+ here never blocks another writer. For each collection the vectors
+ are purged BEFORE their chunk rows (``purge_document_vectors``
+ resolves the FAISS int ids from those rows), then the rows are
+ deleted.
+
+ A final sweep then guarantees no chunk row survives even when the
+ per-collection purge could not run — e.g. the DB password is
+ unavailable on an encrypted-DB install, or a collection has no
+ current FAISS index. ``full_delete`` selects the sweep scope: True
+ (the document is gone) sweeps every remaining chunk row for the
+ document; False (a single unlink) sweeps only the listed
+ collections, leaving the document's chunks in its other collections
+ intact.
+
+ Best-effort: the DB delete already committed, so failures here are
+ logged, not surfaced.
+ """
+ if collection_ids:
+ dbpw = capture_request_db_password(self.username)
+ from ...services.rag_service_factory import get_rag_service
+
+ for collection_id in collection_ids:
+ try:
+ # A fresh service per collection so the factory resolves
+ # THAT collection's stored embedding model/provider — a
+ # shared instance would compute the wrong index hash and
+ # purge nothing for non-default-embedding collections.
+ with get_rag_service(
+ self.username,
+ collection_id=collection_id,
+ db_password=dbpw,
+ ) as rag:
+ rag.purge_document_vectors(document_id, collection_id)
+ rag.purge_document_chunks(document_id, collection_id)
+ except Exception:
+ # exception=True keeps the stack trace. dbpw is a live
+ # local here, but frame-local values only render under
+ # the opt-in LDR_LOGURU_DIAGNOSE dev flag — every
+ # persistent sink sets diagnose=False — so the password
+ # cannot reach a log in normal operation.
+ logger.opt(exception=True).error(
+ "Failed to remove RAG entries for document {} "
+ "from collection {}",
+ document_id,
+ collection_id,
+ )
+
+ # Guaranteed backstop: remove any chunk rows the RAG purge could not
+ # reach. Their vectors can't be resolved without the rows, but the
+ # collection-scoped rehydration filter already stops an orphaned
+ # vector from ever surfacing another document's text, so dropping the
+ # rows here keeps the deletion complete and safe.
+ try:
+ with get_user_db_session(self.username) as session:
+ if full_delete:
+ CascadeHelper.delete_document_chunks(session, document_id)
+ else:
+ for collection_id in collection_ids:
+ CascadeHelper.delete_document_chunks(
+ session,
+ document_id,
+ f"collection_{collection_id}",
+ )
+ session.commit()
+ except Exception:
+ logger.opt(exception=True).error(
+ "Failed to sweep residual chunk rows for document {}",
+ document_id,
+ )
+
def delete_blob_only(self, document_id: str) -> Dict[str, Any]:
"""
Delete PDF binary but keep document metadata and text content.
@@ -394,14 +514,33 @@ class DocumentDeletionService:
"chunks_deleted": 0,
}
- # Delete chunks for this document in this collection
+ # Count chunks for this document in this collection (for
+ # stats). Their rows and FAISS vectors are removed in the
+ # post-commit RAG cleanup phase — purge_document_vectors
+ # resolves the FAISS int ids from these rows, so they must
+ # outlive this transaction.
collection_name = f"collection_{collection_id}"
- result["chunks_deleted"] = CascadeHelper.delete_document_chunks(
- session, document_id, collection_name
+ result["chunks_deleted"] = (
+ session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.source_id == document_id,
+ DocumentChunk.source_type == "document",
+ DocumentChunk.collection_name == collection_name,
+ )
+ .count()
)
# Remove the link
session.delete(doc_collection)
+ # Clear the RagDocumentStatus row for this (document, collection)
+ # — the "indexed" marker read by get_rag_stats / the RAG status
+ # route. Its FK cascades fire only when the Document, Collection,
+ # or RAGIndex is deleted; a mere unlink deletes none of those, so
+ # a leftover row reports the just-removed document as still
+ # indexed in this collection.
+ session.query(RagDocumentStatus).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).delete(synchronize_session=False)
session.flush()
# Check if document is in any other collection
@@ -409,6 +548,12 @@ class DocumentDeletionService:
session, document_id
)
+ # Default (unlink, and note-orphan): purge only THIS
+ # collection's vectors/chunks; the document (or note) and its
+ # chunks in other collections stay intact.
+ full_delete = False
+ rag_collection_ids: List[str] = [collection_id]
+
if remaining_count == 0 and _is_note_document(
session, document
):
@@ -431,11 +576,28 @@ class DocumentDeletionService:
f"Document {document_id[:8]}... is orphaned, deleting"
)
- # Delete remaining chunks (shouldn't be any, but be safe)
- session.query(DocumentChunk).filter(
- DocumentChunk.source_id == document_id,
- DocumentChunk.source_type == "document",
- ).delete(synchronize_session=False)
+ # Full delete: purge vectors/chunks across EVERY collection
+ # that still holds chunk rows for this document, not just
+ # the one being removed (a partial reindex can strand
+ # chunks elsewhere). Rows are deleted in the post-commit
+ # phase so purge_document_vectors can resolve their ids.
+ chunk_collection_rows = (
+ session.query(DocumentChunk.collection_name)
+ .filter_by(
+ source_type="document", source_id=document_id
+ )
+ .distinct()
+ .all()
+ )
+ full_delete = True
+ rag_collection_ids = list(
+ {collection_id}
+ | {
+ row[0].removeprefix("collection_")
+ for row in chunk_collection_rows
+ if row[0]
+ }
+ )
# Update DownloadTracker
CascadeHelper.update_download_tracker(session, document)
@@ -458,7 +620,8 @@ class DocumentDeletionService:
except Exception:
logger.exception("Failed to delete filesystem file")
- # Delete document and all related records
+ # Delete document and all related records (leaves the
+ # DocumentChunk rows for the post-commit cleanup phase).
CascadeHelper.delete_document_completely(
session, document_id
)
@@ -473,8 +636,6 @@ class DocumentDeletionService:
f"(deleted={result['document_deleted']})"
)
- return result
-
except Exception:
logger.exception(
f"Failed to remove document {document_id} "
@@ -489,6 +650,14 @@ class DocumentDeletionService:
"error": "Failed to remove document from collection",
}
+ # Post-commit FAISS + chunk-row cleanup, after the transaction has
+ # committed and released SQLite's write lock.
+ self._purge_document_rag(
+ document_id, rag_collection_ids, full_delete=full_delete
+ )
+
+ return result
+
def get_deletion_preview(self, document_id: str) -> Dict[str, Any]:
"""
Get a preview of what will be deleted.
diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
index 258273b444..4311e99289 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
@@ -7,6 +7,7 @@ Handles cleanup of related records that don't have proper FK constraints:
- Filesystem files
"""
+import time
from pathlib import Path
from typing import Dict, List, Optional, Any
@@ -23,6 +24,12 @@ from ....database.models.library import (
)
from ....database.models.download_tracker import DownloadTracker
+# A <name>.*.tmp younger than this is assumed to be a concurrent writer's live
+# persist() temp (not yet os.replace()d into place); deleting it would crash
+# that write. Matches FaissVectorStore.persist()'s own stale-temp sweep so both
+# paths agree on when a temp is certainly crash-orphaned rather than in-flight.
+_STALE_TMP_AGE_SECONDS = 3600
+
class CascadeHelper:
"""Helper class for cleaning up related records during deletion."""
@@ -192,13 +199,65 @@ class CascadeHelper:
logger.debug(f"Deleted FAISS index file: {faiss_file}")
deleted_any = True
- # Pickle file for metadata
+ # Pickle file for metadata (legacy pre-cutover format)
pkl_file = path.with_suffix(".pkl")
if pkl_file.is_file():
pkl_file.unlink()
logger.debug(f"Deleted FAISS pkl file: {pkl_file}")
deleted_any = True
+ # Migration sidecar (.idmap.json) — the text-free position->uuid map
+ # phase-1 writes and phase-2 consumes. If a collection is deleted
+ # during the .pkl -> .idmap.json cutover window (phase-1 ran, phase-2
+ # hasn't), the sidecar would otherwise be orphaned on disk forever.
+ idmap_file = path.with_suffix(".idmap.json")
+ if idmap_file.is_file():
+ idmap_file.unlink()
+ logger.debug(f"Deleted FAISS idmap sidecar: {idmap_file}")
+ deleted_any = True
+
+ # Sweep crash-orphaned temp files (persist writes <name>.*.tmp) and
+ # quarantined siblings (<name>.corrupt-<ns>) for the whole family,
+ # so deleting a collection doesn't leave them on disk forever — a
+ # leftover .pkl.corrupt-* is quarantined PLAINTEXT.
+ parent = path.parent
+ now = time.time()
+ for base in (faiss_file, pkl_file, idmap_file):
+ # .tmp files are AGE-GATED: FaissVectorStore.persist() writes to
+ # a <name>.*.tmp then os.replace()s it into place, so a live temp
+ # is a concurrent writer's not-yet-renamed file — unlinking it
+ # would crash that persist with FileNotFoundError. Only sweep
+ # temps old enough to be certainly crash-orphaned (mirrors
+ # persist()'s own _STALE_TMP_AGE_SECONDS sweep). A younger temp is
+ # left; a later delete/persist sweeps it once it ages out.
+ for stray in parent.glob(f"{base.name}.*.tmp"):
+ try:
+ if now - stray.stat().st_mtime < _STALE_TMP_AGE_SECONDS:
+ continue
+ stray.unlink()
+ logger.debug(f"Removed stray temp index file: {stray}")
+ deleted_any = True
+ except FileNotFoundError:
+ # Raced a concurrent writer's os.replace() — already gone.
+ continue
+ except OSError:
+ logger.warning(
+ f"Could not remove stray index file {stray}"
+ )
+ # .corrupt-* are quarantine artefacts (and .pkl.corrupt-* is
+ # PLAINTEXT) — always safe and required to remove, no age gate.
+ for stray in parent.glob(f"{base.name}.corrupt-*"):
+ try:
+ stray.unlink()
+ logger.debug(f"Removed quarantined index file: {stray}")
+ deleted_any = True
+ except FileNotFoundError:
+ continue
+ except OSError:
+ logger.warning(
+ f"Could not remove stray index file {stray}"
+ )
+
return deleted_any
except Exception:
logger.exception(f"Failed to delete FAISS files for: {index_path}")
@@ -208,16 +267,29 @@ class CascadeHelper:
def delete_rag_indices_for_collection(
session: Session,
collection_name: str,
+ *,
+ unlink_files: bool = True,
) -> Dict[str, Any]:
"""
- Delete RAGIndex records and their FAISS files for a collection.
+ Delete RAGIndex records (and, by default, their FAISS files) for a
+ collection.
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
+ 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).
Returns:
- Dict with deletion results
+ Dict with deletion results (includes ``index_paths`` when
+ ``unlink_files`` is False).
"""
indices = (
session.query(RAGIndex)
@@ -227,11 +299,15 @@ class CascadeHelper:
deleted_indices = 0
deleted_files = 0
+ index_paths: List[str] = []
for index in indices:
- # Delete FAISS files
- if CascadeHelper.delete_faiss_index_files(str(index.index_path)):
- deleted_files += 1
+ path = str(index.index_path)
+ if unlink_files:
+ if CascadeHelper.delete_faiss_index_files(path):
+ deleted_files += 1
+ else:
+ index_paths.append(path)
session.delete(index)
deleted_indices += 1
@@ -244,6 +320,7 @@ class CascadeHelper:
return {
"deleted_indices": deleted_indices,
"deleted_files": deleted_files,
+ "index_paths": index_paths,
}
@staticmethod
@@ -331,41 +408,6 @@ class CascadeHelper:
)
return [dc.collection_id for dc in doc_collections]
- @staticmethod
- def remove_from_faiss_index(
- username: str,
- collection_name: str,
- chunk_ids: List[str],
- ) -> bool:
- """
- Remove specific chunks from a FAISS index.
-
- Args:
- username: Username for RAG service
- collection_name: Collection name
- chunk_ids: List of chunk IDs to remove
-
- Returns:
- True if successful
- """
- try:
- from ...services.library_rag_service import LibraryRAGService
-
- with LibraryRAGService(
- username=username,
- ) as rag_service:
- # This uses the existing remove functionality
- if (
- hasattr(rag_service, "faiss_index")
- and rag_service.faiss_index
- ):
- if hasattr(rag_service.faiss_index, "delete"):
- rag_service.faiss_index.delete(chunk_ids)
- return True
- except Exception:
- logger.exception("Failed to remove chunks from FAISS index")
- return False
-
@staticmethod
def delete_document_completely(
session: Session,
diff --git a/src/local_deep_research/research_library/notes/services/note_service.py b/src/local_deep_research/research_library/notes/services/note_service.py
index dc5cc6de9b..4d4c77aa44 100644
--- a/src/local_deep_research/research_library/notes/services/note_service.py
+++ b/src/local_deep_research/research_library/notes/services/note_service.py
@@ -25,6 +25,7 @@ from sqlalchemy.orm import Session, joinedload
from ....database.models import (
Collection,
Document,
+ DocumentChunk,
DocumentCollection,
NoteChangeType,
NoteLink,
@@ -67,43 +68,18 @@ def escape_markdown_link_label(label: str) -> str:
def _capture_request_db_password(username: str) -> Optional[str]:
- """Best-effort capture of the encrypted-DB password from the request
- thread, intended to be passed to background workers.
-
- Stdlib ``ThreadPoolExecutor.submit`` does NOT copy the calling thread's
- ``ContextVar`` snapshot — so the third probe inside
- ``get_user_db_session`` (``get_search_context()``) returns nothing on
- worker threads, and on encrypted-DB installs every background DB write
- raises ``DatabaseSessionError`` and is swallowed. This helper extracts
- the password while still on the request thread so callers can pass it
- explicitly through ``_submit_summary_task`` to
- ``_populate_change_summary_async``.
-
- Returns ``None`` if the password cannot be located (caller should
- skip the background task on encrypted DBs in that case).
+ """Capture the encrypted-DB password from the request thread.
+
+ Thin wrapper over the shared
+ ``database.session_passwords.capture_request_db_password`` (kept as a
+ module-local name so the many call sites in this file stay unchanged).
+ Needed because ``ThreadPoolExecutor.submit`` does not copy the calling
+ thread's ``ContextVar`` snapshot, so background workers otherwise lose
+ the password and every encrypted-DB write is swallowed.
"""
- try:
- from flask import (
- g,
- has_app_context,
- has_request_context,
- session as flask_session,
- )
- from ....database.session_passwords import session_password_store
+ from ....database.session_passwords import capture_request_db_password
- if has_app_context() and hasattr(g, "user_password"):
- return g.user_password
- if has_request_context():
- session_id = flask_session.get("session_id")
- if session_id:
- return session_password_store.get_session_password(
- username, session_id
- )
- except Exception:
- logger.debug(
- "Failed to capture DB password for background task", exc_info=True
- )
- return None
+ return capture_request_db_password(username)
# Bounded thread pool for AI change-summary generation. summarize_changes is
@@ -1201,9 +1177,10 @@ class NoteService:
Both halves of the RAG state are purged: the FAISS vectors first
(``purge_document_vectors`` — replace-on-reindex can never fire
- again for a deleted document id, and the shared search flows build
- snippets straight from the docstore with no Document-existence
- check, so lingering vectors would serve the deleted note's text
+ again for a deleted document id, and the shared search flows
+ rehydrate snippets straight from the ``DocumentChunk`` rows in the
+ (encrypted) DB by id, with no Document-existence check, so
+ lingering vectors would serve the deleted note's text
indefinitely), then the ``DocumentChunk`` rows
(``purge_document_chunks``). The ghost-hit filter in
``NoteAIService.semantic_search`` / ``find_similar_passages``
@@ -1217,14 +1194,32 @@ class NoteService:
if document is None:
return False
- # Capture the indexed-collection set before the cascade
- # destroys these rows.
+ # Capture (before the cascade destroys them) every collection
+ # where this note might have vectors to purge: the UNION of
+ # DocumentCollection.indexed=True AND collections that actually
+ # have chunk rows. The chunk-row half is essential — an edited
+ # note has indexed=False during the edit->reindex window while
+ # its pre-edit chunks/vectors still exist, so gating on the
+ # indexed flag alone would strand orphaned vectors.
indexed_rows = (
session.query(DocumentCollection.collection_id)
.filter_by(document_id=note_id, indexed=True)
.all()
)
- indexed_collection_ids = [row[0] for row in indexed_rows]
+ chunk_rows = (
+ session.query(DocumentChunk.collection_name)
+ .filter_by(source_type="document", source_id=note_id)
+ .distinct()
+ .all()
+ )
+ indexed_collection_ids = list(
+ {row[0] for row in indexed_rows}
+ | {
+ row[0].removeprefix("collection_")
+ for row in chunk_rows
+ if row[0]
+ }
+ )
session.delete(document)
session.commit()
@@ -1246,18 +1241,26 @@ class NoteService:
# LibraryRAGService would compute the wrong index
# hash and silently purge nothing for any
# non-default-embedding collection). Per-collection
- # instances also avoid one service's loaded
- # faiss_index carrying over into another
- # collection's save_local under the shared lock.
+ # instances also avoid one collection's cached
+ # ``rag_index_record`` / loaded vector index
+ # carrying over into another collection's
+ # ``purge_document_vectors`` call.
with get_rag_service(
self.username,
collection_id=collection_id,
db_password=dbpw,
) as rag:
- # Vectors BEFORE chunk rows: the rows are the
- # ownership evidence the vector purge consults
- # to keep chunks shared with other documents
- # (see purge_document_vectors).
+ # Vectors BEFORE chunk rows: purge_document_vectors
+ # -> VectorIndex.delete looks up the DocumentChunk
+ # rows by (source_type, source_id, collection_name)
+ # to learn which FAISS int ids to remove, and
+ # deletes those matching rows itself. The rows
+ # must still exist when this runs, or the lookup
+ # finds nothing and the vectors (and their
+ # persisted text) are stranded in the FAISS store
+ # forever. purge_document_chunks below then only
+ # has to catch whatever purge_document_vectors
+ # didn't match (e.g. no current FAISS index).
rag.purge_document_vectors(note_id, collection_id)
# purge_document_chunks, not
# remove_document_from_rag: the Document (and
@@ -1267,13 +1270,37 @@ class NoteService:
# leave the chunks orphaned.
rag.purge_document_chunks(note_id, collection_id)
except Exception:
- logger.exception(
+ # exception=True keeps the stack trace. `dbpw` is a
+ # live local, but frame-local values render only under
+ # the opt-in LDR_LOGURU_DIAGNOSE dev flag — every
+ # persistent sink sets diagnose=False — so the password
+ # cannot leak into logs in normal operation.
+ logger.opt(exception=True).error(
"Failed to remove RAG entries for note {} "
"from collection {}",
note_id,
collection_id,
)
+ # Guaranteed backstop: delete any DocumentChunk rows the per-
+ # collection purge above could not reach (get_rag_service failing
+ # because the request-thread password is unavailable, a transient
+ # FAISS/DB error, a stored-config mismatch). chunk_text holds the
+ # note's content and collection search rehydrates hits purely by
+ # DocumentChunk.id — a surviving row would keep serving the deleted
+ # note's text. The matching orphaned vector then resolves to no row
+ # and is filtered out. Mirrors DocumentDeletionService's backstop.
+ try:
+ with get_user_db_session(self.username) as sweep_session:
+ sweep_session.query(DocumentChunk).filter_by(
+ source_type="document", source_id=note_id
+ ).delete(synchronize_session=False)
+ sweep_session.commit()
+ except Exception:
+ logger.opt(exception=True).error(
+ "Failed to sweep residual chunk rows for note {}", note_id
+ )
+
return True
except Exception:
@@ -1510,29 +1537,48 @@ class NoteService:
.first()
)
- if not doc_coll:
- return False
-
- # Capture the indexed flag before the join row is gone: the
- # RAG purge below needs it, and delete_note derives its
- # purge set from exactly these rows — once this row is
- # deleted, a later delete_note can no longer clean this
- # collection's chunks/vectors for the note.
- was_indexed = bool(doc_coll.indexed)
-
- session.delete(doc_coll)
- session.commit()
- logger.info(
- f"Removed note {note_id} from collection {collection_id}"
- )
-
- # Purge the note's chunks/vectors from THIS collection's RAG
- # store (outside the DB session, mirroring delete_note). Without
- # this, the collection's search keeps returning the removed
- # note's content indefinitely — the shared collection-search
- # flow builds snippets straight from the docstore with no
- # Document-existence check — and because the join row is gone,
- # no later delete_note can reach these entries either.
+ link_existed = doc_coll is not None
+ if doc_coll:
+ # Purge if this collection is flagged indexed OR the note
+ # still has chunk rows here — the chunk-row half catches the
+ # edit->reindex window where indexed=False but the pre-edit
+ # chunks/vectors still exist. Captured before the link is
+ # deleted.
+ was_indexed = bool(doc_coll.indexed) or (
+ session.query(DocumentChunk.id)
+ .filter_by(
+ source_type="document",
+ source_id=note_id,
+ collection_name=f"collection_{collection_id}",
+ )
+ .first()
+ is not None
+ )
+ session.delete(doc_coll)
+ session.commit()
+ logger.info(
+ f"Removed note {note_id} from collection {collection_id}"
+ )
+ else:
+ # The link is already gone (a concurrent removal). Do NOT
+ # return early: a racing index_document could have (re)created
+ # chunk rows for this (note, collection) AFTER the link was
+ # deleted, and there is no other route-level retry for that
+ # pair — an early return would leave the removed note's
+ # plaintext searchable here forever. Fall through to the
+ # unconditional backstop chunk sweep below (which removes the
+ # plaintext rows); the full RAG vector purge is skipped since
+ # there is no link to unlink.
+ was_indexed = False
+
+ # Best-effort FAISS + chunk cleanup for the collection the note was
+ # unlinked from — mirrors delete_note. Without it, the note's chunk
+ # rows and vectors linger in that collection's index, so the removed
+ # note stays fully searchable there. Vectors BEFORE chunk rows (the
+ # int-id lookup needs the rows to still exist). Uses get_rag_service
+ # so THAT collection's stored embedding model resolves the right
+ # index hash. Failures are logged, not surfaced (the unlink already
+ # committed).
if was_indexed:
dbpw = _capture_request_db_password(self.username)
from ...services.rag_service_factory import get_rag_service
@@ -1546,16 +1592,40 @@ class NoteService:
rag.purge_document_vectors(note_id, collection_id)
rag.purge_document_chunks(note_id, collection_id)
except Exception:
- # Best-effort: the membership change already committed;
- # log for ops but don't fail the user's action.
- logger.exception(
- "Failed to purge RAG entries for note {} removed "
- "from collection {}",
+ # exception=True keeps the stack trace. `dbpw` (the DB
+ # password) is a live local, but frame-local values render
+ # only under the opt-in LDR_LOGURU_DIAGNOSE dev flag — every
+ # persistent sink sets diagnose=False — so it cannot leak.
+ logger.opt(exception=True).error(
+ "Failed to purge RAG entries for note {} removed from "
+ "collection {}",
note_id,
collection_id,
)
- return True
+ # Guaranteed backstop, scoped to THIS collection only (the note
+ # survives in its other collections): delete any DocumentChunk rows
+ # the purge above could not reach, so the unlinked note's text stops
+ # surfacing in this collection's search even when the RAG purge
+ # failed. Mirrors DocumentDeletionService's scoped backstop.
+ try:
+ with get_user_db_session(self.username) as sweep_session:
+ sweep_session.query(DocumentChunk).filter_by(
+ source_type="document",
+ source_id=note_id,
+ collection_name=f"collection_{collection_id}",
+ ).delete(synchronize_session=False)
+ sweep_session.commit()
+ except Exception:
+ logger.opt(exception=True).error(
+ "Failed to sweep residual chunk rows for note {} in "
+ "collection {}",
+ note_id,
+ collection_id,
+ )
+ # False when the link was already gone (nothing to unlink), True when
+ # this call performed the removal — preserves the prior contract.
+ return link_existed
except Exception:
logger.exception("Error removing note {} from collection", note_id)
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 213caca564..958b1aff93 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -888,16 +888,33 @@ def index_all():
.filter_by(id=collection_id)
.first()
)
+
+ if not collection:
+ yield f"data: {json.dumps({'type': 'error', 'error': 'Collection not found'})}\n\n"
+ return
+
+ # Persist the new embedding config AND reset the old
+ # chunks/RAGIndex in ONE transaction. Two separate commits would
+ # leave a crash window where the Collection carries the NEW
+ # embedding config while the OLD RAGIndex row + FAISS file (built
+ # with the old config) still exist — a config/index mismatch.
+ changed = False
+ faiss_reset_paths = []
if collection is not None and (
collection.embedding_model is None or force_reindex
):
_store_collection_embedding_metadata(
collection, rag_service
)
- db_session.commit()
+ changed = True
if force_reindex:
- _reset_collection_for_reindex(db_session, collection_id)
+ faiss_reset_paths = _reset_collection_for_reindex(
+ db_session, collection_id
+ )
+ changed = True
+ if changed:
db_session.commit()
+ _unlink_reindex_faiss_files(faiss_reset_paths)
doc_info = [
(doc.id, doc.title)
@@ -939,7 +956,8 @@ def index_all():
if result["status"] == "success":
results["successful"] += 1
- elif result["status"] == "skipped":
+ elif result["status"] in ("skipped", "cleared"):
+ # "cleared" (empty-text purge) is a handled non-failure.
results["skipped"] += 1
else:
results["failed"] += 1
@@ -2176,6 +2194,12 @@ def _reset_collection_for_reindex(db_session, collection_id):
previous run was cancelled midway). Shared so a force-reindex behaves the
same whether started via the SSE route or the background worker. Does not
commit — the caller owns the transaction.
+
+ Returns the list of on-disk FAISS index paths to unlink AFTER the caller
+ commits. The RAGIndex ROWS are deleted in this transaction, but the files
+ must NOT be removed before the commit that could still roll back — a
+ rollback would restore the rows while the files were already gone, leaving
+ the collection pointing at missing indices (mirrors collection deletion).
"""
# Import stays function-local: hoisting it would pull in the whole
# deletion package (deletion/__init__ imports its services) at
@@ -2192,10 +2216,10 @@ def _reset_collection_for_reindex(db_session, collection_id):
f"Cleared {deleted_chunks} old chunks for collection {collection_id}"
)
- # Delete old FAISS index files (.faiss + .pkl) and RAGIndex records.
- # RagDocumentStatus rows cascade-delete via FK ondelete="CASCADE".
+ # 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
+ db_session, collection_name, unlink_files=False
)
logger.info(
f"Cleared old RAG indices for collection {collection_id}: {rag_result}"
@@ -2211,6 +2235,18 @@ def _reset_collection_for_reindex(db_session, collection_id):
}
)
logger.info(f"Reset indexing state for collection {collection_id}")
+ return rag_result["index_paths"]
+
+
+def _unlink_reindex_faiss_files(index_paths):
+ """Unlink FAISS index files returned by _reset_collection_for_reindex, AFTER
+ the caller's DB commit. Best-effort: the DB delete is already durable."""
+ if not index_paths:
+ return
+ from ..deletion.utils.cascade_helper import CascadeHelper
+
+ for path in index_paths:
+ CascadeHelper.delete_faiss_index_files(path)
def _query_documents_to_index(db_session, collection_id, force_reindex):
@@ -2283,18 +2319,25 @@ def index_collection(collection_id):
yield f"data: {json.dumps({'type': 'error', 'error': 'Collection not found'})}\n\n"
return
- # Store embedding metadata on first index or force reindex
+ # Store embedding metadata AND reset the old index in ONE commit
+ # (prevents stale / mixed-model vectors). Committing the config
+ # write separately from the reset leaves a window where a crash
+ # keeps the new config but the old vectors survive.
+ changed = False
+ faiss_reset_paths = []
if collection.embedding_model is None or force_reindex:
_store_collection_embedding_metadata(
collection, rag_service
)
- db_session.commit()
-
- # Clean up old index data for a fresh rebuild (prevents stale /
- # mixed-model vectors). Shared with the background worker.
+ changed = True
if force_reindex:
- _reset_collection_for_reindex(db_session, collection_id)
+ faiss_reset_paths = _reset_collection_for_reindex(
+ db_session, collection_id
+ )
+ changed = True
+ if changed:
db_session.commit()
+ _unlink_reindex_faiss_files(faiss_reset_paths)
# Get documents to index
doc_links = _query_documents_to_index(
@@ -2380,7 +2423,8 @@ def index_collection(collection_id):
results["successful"] += 1
# DocumentCollection status is already updated in index_document
# No need to update link here
- elif result.get("status") == "skipped":
+ elif result.get("status") in ("skipped", "cleared"):
+ # "cleared" (empty-text purge) is a handled non-failure.
results["skipped"] += 1
else:
results["failed"] += 1
@@ -2675,19 +2719,24 @@ def _background_index_worker(
)
return
- # Store embedding metadata on first index or force reindex
+ # Store embedding metadata AND reset the old index in ONE commit,
+ # so a crash between them can't leave the new config committed
+ # while the old (stale/mixed-model) vectors survive.
+ changed = False
+ faiss_reset_paths = []
if collection.embedding_model is None or force_reindex:
_store_collection_embedding_metadata(
collection, rag_service
)
- db_session.commit()
-
- # Clean up old index data for a fresh rebuild.
- # This prevents mixed-model vectors if cancelled midway
- # and ensures accurate stats during partial reindex.
+ changed = True
if force_reindex:
- _reset_collection_for_reindex(db_session, collection_id)
+ faiss_reset_paths = _reset_collection_for_reindex(
+ db_session, collection_id
+ )
+ changed = True
+ if changed:
db_session.commit()
+ _unlink_reindex_faiss_files(faiss_reset_paths)
# Get documents to index
doc_links = _query_documents_to_index(
@@ -2749,7 +2798,8 @@ def _background_index_worker(
if result.get("status") == "success":
results["successful"] += 1
- elif result.get("status") == "skipped":
+ elif result.get("status") in ("skipped", "cleared"):
+ # "cleared" (empty-text purge) is a handled non-failure.
results["skipped"] += 1
else:
results["failed"] += 1
diff --git a/src/local_deep_research/research_library/services/faiss_safe_load.py b/src/local_deep_research/research_library/services/faiss_safe_load.py
index e07ce2bd44..0012ea7e45 100644
--- a/src/local_deep_research/research_library/services/faiss_safe_load.py
+++ b/src/local_deep_research/research_library/services/faiss_safe_load.py
@@ -24,18 +24,13 @@ The payload is the 2-tuple ``(docstore, index_to_docstore_id)`` written by
unpickle. If a future LangChain/Pydantic version changes the on-disk format
to need additional classes, loading fails closed (a clear error) rather than
silently — and the round-trip test in
-``tests/research_library/services/test_faiss_safe_load.py`` will catch it so
+``tests/vector_stores/test_faiss_safe_load_security.py`` will catch it so
the allow-list can be widened deliberately.
"""
import pickle
-from pathlib import Path
from typing import Any
-from langchain_community.vectorstores import FAISS
-from langchain_community.vectorstores.faiss import dependable_faiss_import
-from langchain_core.embeddings import Embeddings
-
# (module, qualname) pairs that a legitimate FAISS docstore pickle resolves
# via ``Unpickler.find_class``. Determined empirically by round-tripping a
# real ``save_local`` payload with varied metadata; only these two appear.
@@ -96,48 +91,20 @@ class _RestrictedFaissUnpickler(pickle._Unpickler):
)
-def safe_load_faiss(
- folder_path: str,
- embeddings: Embeddings,
- *,
- index_name: str,
- normalize_L2: bool = False,
-) -> FAISS:
- """Load a FAISS index from disk without dangerous deserialization.
-
- Drop-in replacement for ``FAISS.load_local(...,
- allow_dangerous_deserialization=True)`` for the index/docstore layout
- this project writes via ``FAISS.save_local``.
-
- Args:
- folder_path: Directory containing ``<index_name>.faiss`` and
- ``<index_name>.pkl``.
- embeddings: Embeddings used for subsequent queries.
- index_name: Base name of the index files (the ``.faiss`` stem).
- normalize_L2: Whether vectors are L2-normalized (must match how the
- index was built).
-
- Returns:
- A :class:`FAISS` vector store.
-
- Raises:
- pickle.UnpicklingError: If the ``.pkl`` references any class outside
- the allow-list (tampering or an unexpected format change).
+def load_index_to_docstore_id(pkl_path: str) -> dict:
+ """Read ONLY the ``index_to_docstore_id`` (FAISS position -> docstore key)
+ map from a legacy ``<index>.pkl``, discarding the docstore.
+
+ Uses :class:`_RestrictedFaissUnpickler`, so a tampered
+ ``.pkl`` cannot execute code on read. The returned dict contains only ints
+ (FAISS positions) and the original string ids (uuids) — **no document text
+ or metadata** — which is exactly what the one-time index-format migration
+ needs to preserve when it strips the plaintext docstore from disk.
+
+ The docstore (which holds the chunk text) IS deserialized into memory
+ transiently by ``pickle`` here, but it is never written back out — only the
+ id map is returned.
"""
- path = Path(folder_path)
-
- # The .faiss file is a binary FAISS index (not pickle); read it as usual.
- faiss = dependable_faiss_import()
- index = faiss.read_index(str(path / f"{index_name}.faiss"))
-
- # The .pkl is the only attack surface — unpickle it under restriction.
- with open(path / f"{index_name}.pkl", "rb") as f:
- docstore, index_to_docstore_id = _RestrictedFaissUnpickler(f).load()
-
- return FAISS(
- embeddings,
- index,
- docstore,
- index_to_docstore_id,
- normalize_L2=normalize_L2,
- )
+ with open(pkl_path, "rb") as f:
+ _docstore, index_to_docstore_id = _RestrictedFaissUnpickler(f).load()
+ return index_to_docstore_id
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index a58f4e33d2..6123562386 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -36,11 +36,34 @@ from ...web_search_engines.engines.local_embedding_manager import (
LocalEmbeddingManager,
)
from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifier
+from ...security.file_integrity.integrity_manager import NO_INTEGRITY_RECORD
+from ...vector_stores.facade import VectorIndex, ChunkInput, SearchResult
+from langchain_core.embeddings import Embeddings
import hashlib
-from faiss import IndexFlatL2, IndexFlatIP, IndexHNSWFlat
-from langchain_community.vectorstores import FAISS
-from langchain_community.docstore.in_memory import InMemoryDocstore
-from .faiss_safe_load import safe_load_faiss
+
+
+class _LazyEmbeddings(Embeddings):
+ """Embeddings proxy that defers backend construction until first use.
+
+ A ``VectorIndex`` built purely to ``delete()`` never touches ``embeddings``
+ (delete resolves rows by id and calls ``store.apply(remove_ids=...)``).
+ ``LocalEmbeddingManager.embeddings`` is a lazy property that, on first
+ access, synchronously loads the real backend (a SentenceTransformer costs
+ seconds and hundreds of MB of RSS, an Ollama client opens live httpx
+ connections). Handing that property straight to the delete path forces that
+ cost once per (deleted-document x collection). This proxy pulls the real
+ embeddings from the manager only if ``embed_*`` is genuinely called, so the
+ delete path pays nothing while index/search paths still work unchanged.
+ """
+
+ def __init__(self, manager) -> None:
+ self._manager = manager
+
+ def embed_documents(self, texts):
+ return self._manager.embeddings.embed_documents(texts)
+
+ def embed_query(self, text):
+ return self._manager.embeddings.embed_query(text)
# Module-level locks serialise the FAISS save+record critical section and the
@@ -85,19 +108,28 @@ def _get_faiss_write_lock(username: str, index_path: str) -> threading.Lock:
def pop_faiss_locks_for_user(username: str) -> None:
- """Remove all FAISS-write locks belonging to ``username``.
-
- Called from the user-close paths (connection_cleanup) so the dict
- doesn't grow one entry per (user × collection) across the process
- lifetime. Safe to call while a lock is held: the holder keeps using
- its local reference, and the next access lazily creates a fresh
- lock. Same semantics as ``pop_user_critical_lock`` in
- web/queue/processor_v2.py.
+ """Remove FAISS-write locks belonging to ``username`` that are NOT in use.
+
+ Called from the user-close paths (connection_cleanup) so the dict doesn't
+ grow one entry per (user × collection) across the process lifetime.
+
+ A lock that is currently HELD must NOT be evicted: the next writer would
+ then create a FRESH lock and run concurrently with the current holder on
+ the same index file (lost update / torn write). So each candidate is probed
+ with a non-blocking acquire — only locks we can immediately acquire (hence
+ not held) are removed; a held lock is left in place and cleaned up by a
+ later call once its write finishes. (No deadlock: a writer never holds a
+ faiss lock while waiting on ``_faiss_write_locks_lock``.)
"""
with _faiss_write_locks_lock:
stale = [k for k in _faiss_write_locks if k[0] == username]
for k in stale:
- _faiss_write_locks.pop(k, None)
+ lock = _faiss_write_locks.get(k)
+ if lock is not None and lock.acquire(blocking=False):
+ try:
+ _faiss_write_locks.pop(k, None)
+ finally:
+ lock.release()
class LibraryRAGService:
@@ -264,8 +296,6 @@ class LibraryRAGService:
else None,
)
- # Initialize or load FAISS index for library collection
- self.faiss_index = None
self.rag_index_record = None
# Initialize file integrity manager for FAISS indexes
@@ -291,10 +321,6 @@ class LibraryRAGService:
self.embedding_manager.close()
self.embedding_manager = None
- # Clear FAISS index
- if self.faiss_index is not None:
- self.faiss_index = None
-
# Clear other resources
self.rag_index_record = None
self.integrity_manager = None
@@ -350,16 +376,22 @@ class LibraryRAGService:
user_scope = hashlib.sha256(self.username.encode("utf-8")).hexdigest()[
:16
]
- cache_dir = get_cache_directory() / "rag_indices" / user_scope
+ rag_root = get_cache_directory() / "rag_indices"
+ cache_dir = rag_root / user_scope
cache_dir.mkdir(parents=True, exist_ok=True)
- # 0o700: filesystem-level defense-in-depth so other local
- # accounts can't browse another LDR user's vector caches.
- try:
- cache_dir.chmod(0o700)
- except OSError:
- # Best-effort: some filesystems (e.g. Windows shares) don't
- # honor chmod; the per-user path scope is still applied.
- pass
+ # 0o700: filesystem-level defense-in-depth so other local OS accounts
+ # can't browse another LDR user's vector caches. mkdir(parents=True)
+ # silently creates the intermediate rag_indices/ root under the process
+ # umask (typically 0o755, world-traversable), so harden the ROOT too —
+ # chmod'ing only the per-user leaf leaves a 0o755 rag_indices/ that lets
+ # another OS user traverse in and stat/enumerate every account's caches.
+ for d in (rag_root, cache_dir):
+ try:
+ d.chmod(0o700)
+ except OSError:
+ # Best-effort: some filesystems (e.g. Windows shares) don't
+ # honor chmod; the per-user path scope is still applied.
+ pass
return cache_dir / f"{index_hash}.faiss"
def _migrate_legacy_index_files(
@@ -368,7 +400,7 @@ class LibraryRAGService:
"""Relocate a pre-per-user-scoping index into the per-user directory.
Before the per-user path scoping, indexes lived directly in the
- shared ``cache/rag_indices/`` directory. ``load_or_create_faiss_index``
+ shared ``cache/rag_indices/`` directory. ``_preflight_index_path``
recomputes the path and ignores the stored one, so without this
one-time migration an upgrading user's existing index is never
found again: semantic search silently returns nothing while
@@ -391,9 +423,43 @@ class LibraryRAGService:
return
try:
legacy_pkl = legacy_path.with_suffix(".pkl")
+ # Relocate phase-1's text-free .idmap.json sidecar BEFORE the
+ # .faiss, then move the .faiss LAST. phase-2 rekey looks for the
+ # sidecar next to the .faiss (legacy_rekey._sidecar_for =
+ # <stem>.idmap.json); leaving it at the legacy location orphans
+ # it, and a not-yet-rekeyed index then has no findable sidecar →
+ # rekey sees "no sidecar + old format" and destructively
+ # quarantines a healthy index. Ordering matters for crash
+ # recovery: the re-entry guard keys ONLY on index_path (the
+ # .faiss), so moving the .faiss last makes this idempotent — a
+ # crash after the sidecar move but before the .faiss move leaves
+ # the .faiss at the legacy path (guard still False) and re-entry
+ # simply retries (the sidecar move no-ops, new one exists). The
+ # reverse order would strand index_path.exists()=True with the
+ # sidecar orphaned at the legacy root, which the guard never
+ # re-invokes this to fix.
+ legacy_sidecar = legacy_path.with_name(
+ legacy_path.stem + ".idmap.json"
+ )
+ if legacy_sidecar.exists():
+ new_sidecar = index_path.with_name(
+ index_path.stem + ".idmap.json"
+ )
+ if not new_sidecar.exists():
+ legacy_sidecar.rename(new_sidecar)
legacy_path.rename(index_path)
+ # DELETE (don't relocate) any legacy plaintext .pkl companion:
+ # the new store writes NO .pkl, so moving it would just carry the
+ # plaintext chunk text to the new location. Its text lives in the
+ # encrypted DB.
if legacy_pkl.exists():
- legacy_pkl.rename(index_path.with_suffix(".pkl"))
+ try:
+ legacy_pkl.unlink()
+ except OSError:
+ logger.warning(
+ f"Could not remove legacy plaintext .pkl "
+ f"{legacy_pkl} — delete it manually"
+ )
except OSError:
logger.exception(
f"Failed to migrate legacy FAISS index "
@@ -476,27 +542,18 @@ class LibraryRAGService:
f"document(s) so the next index run rebuilds the index."
)
- @staticmethod
- def _deduplicate_chunks(
- chunks: List[LangchainDocument],
- chunk_ids: List[str],
- existing_ids: Optional[set] = None,
- ) -> Tuple[List[LangchainDocument], List[str]]:
- """Deduplicate chunks by ID within a batch, optionally excluding existing IDs."""
- seen_ids: set = set()
- new_chunks: List[LangchainDocument] = []
- new_ids: List[str] = []
- for chunk, chunk_id in zip(chunks, chunk_ids):
- if chunk_id not in seen_ids and (
- existing_ids is None or chunk_id not in existing_ids
- ):
- new_chunks.append(chunk)
- new_ids.append(chunk_id)
- seen_ids.add(chunk_id)
- return new_chunks, new_ids
-
- def _get_or_create_rag_index(self, collection_id: str) -> RAGIndex:
- """Get or create RAGIndex record for the current configuration."""
+ def _get_or_create_rag_index(
+ self, collection_id: str, *, promote_current: bool = True
+ ) -> RAGIndex:
+ """Get or create RAGIndex record for the current configuration.
+
+ ``promote_current`` (default True) controls whether reusing an existing,
+ not-current row re-promotes it to ``is_current`` (demoting others). Read
+ paths (search) pass False: a mere search under a stale/different config
+ must NOT silently flip which index the collection considers current —
+ only an actual write (index) should. Creating a brand-new index still
+ promotes it regardless (it's the collection's only index for that config).
+ """
with get_user_db_session(self.username, self.db_password) as session:
# Use collection_<uuid> format
collection_name = f"collection_{collection_id}"
@@ -510,6 +567,16 @@ class LibraryRAGService:
)
if not rag_index:
+ # A new index (e.g. an embedding-model change yields a new
+ # index_hash) supersedes any prior current index for this
+ # collection. Demote the old current row(s) FIRST so exactly one
+ # row is ever is_current=True — every read path resolves "the"
+ # current index via filter_by(is_current=True).first(), which
+ # would otherwise return an arbitrary one of several.
+ session.query(RAGIndex).filter_by(
+ collection_name=collection_name, is_current=True
+ ).update({"is_current": False})
+
# Create new index record
index_path = self._get_index_path(index_hash)
@@ -544,26 +611,45 @@ class LibraryRAGService:
session.commit()
session.refresh(rag_index)
logger.info(f"Created new RAG index: {index_hash}")
+ elif promote_current and not rag_index.is_current:
+ # An existing index for THIS (collection, model) config is being
+ # reused (on a WRITE path) but is not marked current. After an
+ # embedding-model switch-and-revert (A -> B -> back to A), row A
+ # was demoted when B was created and never re-promoted, so "the
+ # current index" bookkeeping (filter_by(is_current=True)) would
+ # keep pointing at the now-inactive B. Demote any other current
+ # row for this collection and promote this one, mirroring the
+ # create branch. Gated on promote_current so a read-path search
+ # under a stale config can't steal the current pointer.
+ session.query(RAGIndex).filter(
+ RAGIndex.collection_name == collection_name,
+ RAGIndex.is_current.is_(True),
+ RAGIndex.id != rag_index.id,
+ ).update({"is_current": False})
+ rag_index.is_current = True
+ session.commit()
+ session.refresh(rag_index)
return rag_index
def _quarantine_corrupt_index(self, index_path: Path, reason: str) -> None:
- """Rename a corrupted FAISS index and its ``.pkl`` companion to
- ``<path>.corrupt-<ns>`` instead of deleting them.
+ """Rename a corrupted FAISS index to ``<path>.corrupt-<ns>``
+ instead of deleting it; any legacy plaintext ``.pkl`` companion
+ is deleted outright rather than preserved.
Preserves user data for inspection/recovery. The
dimension-mismatch branch elsewhere in this method intentionally
*deletes* — that case rebuilds from scratch and the old bytes
are unreadable with the new model. This helper is for the two
"transient or unknown failure" branches (verify_file said no,
- load_local raised) where the on-disk bytes may still be
- usable by a human.
+ loading the index into a ``VectorIndex``/faiss raised) where the
+ on-disk bytes may still be usable by a human.
Raises ``OSError`` on rename failure (disk full, read-only fs,
permission denied). Re-raising prevents silent data loss: if we
- swallowed the error, the next ``save_local`` would truncate the
- corrupt bytes anyway. Caller paths log the exception via the
- broader try/except around their indexer call.
+ swallowed the error, the next ``persist()``/``faiss.write_index``
+ would overwrite the corrupt bytes anyway. Caller paths log the
+ exception via the broader try/except around their indexer call.
# TODO(#4197-followup): FileIntegrityRecord.consecutive_failures
# is not reset by the next record_file call, leaking failure
@@ -602,21 +688,51 @@ class LibraryRAGService:
f"indexing) to recover."
)
if pkl_path.exists():
- pkl_path.rename(pkl_target)
- logger.info(f"Quarantined companion PKL to {pkl_target}")
+ # DELETE (not rename) any .pkl companion. The new store writes
+ # NO .pkl, so a .pkl next to a .faiss is a LEGACY plaintext
+ # docstore — its chunk text lives in the (encrypted) DB, so
+ # renaming it aside to .corrupt-<ns> would needlessly preserve
+ # plaintext chunk text on disk. Plaintext removal is not optional.
+ try:
+ pkl_path.unlink()
+ logger.info(f"Removed legacy plaintext PKL {pkl_path}")
+ except OSError:
+ logger.warning(
+ f"Could not remove legacy plaintext PKL {pkl_path} — "
+ "delete it manually"
+ )
else:
- # Missing .pkl is recoverable (FAISS may have crashed
- # mid-write between .faiss and .pkl). Not re-raised:
- # the .faiss is already preserved, fresh build will
- # write a fresh .pkl.
+ # Missing .pkl is the normal case for the new store. Not
+ # re-raised: the .faiss is already preserved.
+ logger.debug(f"No PKL companion at {pkl_path}.")
+ except OSError:
+ if not index_path.exists():
+ # The source is already gone — most likely another worker
+ # PROCESS quarantined the same corrupt index concurrently (the
+ # per-path lock is a threading.Lock, so it serialises only
+ # threads within ONE process, not across gunicorn workers /
+ # the scheduler process). The objective — get the corrupt bytes
+ # off index_path so the caller rebuilds fresh — is already met,
+ # so don't abort a healthy rebuild with a spurious
+ # FileNotFoundError. Still purge any lingering plaintext .pkl:
+ # the no-plaintext-at-rest invariant is not optional even here.
+ if pkl_path.exists():
+ try:
+ pkl_path.unlink()
+ except OSError:
+ logger.warning(
+ f"Could not remove legacy plaintext PKL {pkl_path} "
+ "— delete it manually"
+ )
logger.warning(
- f"PKL companion missing at {pkl_path}; only "
- f".faiss quarantined."
+ f"Corrupt index {index_path} was already quarantined by "
+ f"another worker (reason: {reason}); proceeding to rebuild."
)
- except OSError:
- # Disk-full, read-only fs, or permission error. Re-raise
- # so the caller surfaces a real failure instead of letting
- # the next save_local truncate the corrupt bytes.
+ return
+ # A genuine failure (disk-full, read-only fs, permission denied)
+ # with the corrupt bytes STILL in place. Re-raise so the caller
+ # surfaces a real failure instead of letting the next
+ # persist()/write_index overwrite the corrupt bytes.
logger.exception(
f"Failed to quarantine corrupted index at {index_path}"
)
@@ -707,362 +823,30 @@ class LibraryRAGService:
f"Failed to prune quarantined file {stale}; continuing"
)
- # Cap on candidates run through the shared-text check. A document with
- # more distinct edited-away/deleted chunks than this is pathologically
- # large; rather than scan the collection for thousands of needles under
- # the FAISS write lock, keep them all (don't purge) — safe (never drops
- # a live document's vector), at worst leaving the same ghost vectors the
- # notes semantic-search ghost-hit filter already suppresses.
- _MAX_SHARED_TEXT_CANDIDATES = 512
-
- def _shared_text_survivors(
- self,
- candidates: list,
- collection_id: Optional[str],
- exclude_document_id: str,
- ) -> set:
- """Purge candidates whose chunk text another collection member
- still contains.
-
- ``candidates`` is a list of ``(embedding_id, chunk_text)``. Chunk
- rows are deduped per (chunk_hash, collection) with one mutable
- ``source_id`` owner, so ownership alone cannot prove a vector is
- unused: a self-owned row may be serving other documents' identical
- text (boilerplate, license blocks). Chunks are contiguous slices
- of ``Document.text_content`` (the splitters segment, they don't
- rewrite), so a substring containment test against the collection's
- other current members is a sound "someone still needs this" check.
-
- Each OTHER member's ``text_content`` is read exactly once (one
- SQLCipher decrypt per member) and the still-pending candidates are
- checked against it in memory, resolved ones dropped as we go. The
- previous implementation issued one ``instr()`` full-scan query PER
- candidate — O(candidates × collection text) of decryption under the
- FAISS write lock, which on the deletion path (every chunk of the
- document is a candidate) turned deleting a large note into a
- minutes-long, lock-holding stall.
- """
- survivors: set = set()
- pending = [
- (fid, chunk_text) for fid, chunk_text in candidates if chunk_text
- ]
- if not pending or collection_id is None:
- return survivors
- if len(pending) > self._MAX_SHARED_TEXT_CANDIDATES:
- logger.warning(
- "Shared-text purge check skipped for {} candidate chunks "
- "(> cap {}); keeping them to avoid an unbounded scan — the "
- "ghost-hit filter covers any residual vectors",
- len(pending),
- self._MAX_SHARED_TEXT_CANDIDATES,
- )
- return {fid for fid, _ in pending}
- with get_user_db_session(self.username, self.db_password) as session:
- member_texts = (
- session.query(Document.text_content)
- .join(
- DocumentCollection,
- DocumentCollection.document_id == Document.id,
- )
- .filter(
- DocumentCollection.collection_id == collection_id,
- Document.id != exclude_document_id,
- Document.text_content.isnot(None),
- )
- .yield_per(1)
- )
- for (member_text,) in member_texts:
- if not pending:
- break
- still = []
- for fid, chunk_text in pending:
- if chunk_text in member_text:
- survivors.add(fid)
- else:
- still.append((fid, chunk_text))
- pending = still
- return survivors
-
- def _merge_and_persist_locked(
+ def _preflight_index_path(
self,
- index_path: Path,
- chunks_to_add: list,
- embedding_ids: list,
- force_reindex: bool = False,
- replace_document_id: Optional[str] = None,
- replace_collection_id: Optional[str] = None,
- ) -> Dict[str, int]:
- """Read-modify-write the on-disk FAISS index under the
- ``(username, index_path)`` write lock so concurrent workers
- don't lose each other's embeddings.
-
- Without this, two workers indexing different documents into
- the same collection both load on-disk state X into memory,
- each calls ``add_documents`` on their own private FAISS object
- (worker A: ``X+docA``, worker B: ``X+docB``), then they save
- in sequence — last writer wins, the loser's chunks are gone
- from the FAISS file. The chunks survive in the per-document
- DB rows so a force-reindex rebuilds, but the index file is
- wrong until then. See AI review of #4200.
-
- The slow embedding + DB-chunk-insert path stays OUTSIDE this
- lock (handled by the caller). The lock only covers the fast
- FAISS reload→merge→save sequence (~10-100ms even for large
- indices), so cross-document parallelism is preserved up to
- the point where the in-memory states need reconciliation.
-
- Args:
- index_path: Path of the on-disk ``.faiss`` file.
- chunks_to_add: Chunks the caller wants to add.
- embedding_ids: Matching embedding/chunk IDs (same length).
- force_reindex: If True, delete any IDs from
- ``embedding_ids`` that already exist in the index
- (so the caller's metadata wins). If False, skip IDs
- that already exist (idempotent re-indexing).
- replace_document_id: Replace-on-reindex — purge the document's
- PRIOR chunk vectors from the index before adding the new
- ones. The set is derived from the freshly-reloaded FAISS
- docstore by ``metadata['document_id']`` (and collection),
- so it is authoritative and self-healing: a crash or a
- concurrent indexer that left orphan vectors is cleaned by
- the next re-index regardless of what any ephemeral DB
- snapshot said, and the last writer under the lock removes
- ALL prior versions' vectors. Ids also being re-added are
- kept.
- replace_collection_id: Scope the replace purge to this
- collection's chunks for the document (a document can be
- indexed into multiple collections).
-
- Returns:
- ``{"added": n, "skipped": m}`` for caller logging.
- """
- with _get_faiss_write_lock(self.username, str(index_path)):
- # Reload from disk to absorb other writers' saves. If the
- # file doesn't exist or fails verification, keep whatever
- # the caller already had in ``self.faiss_index`` (likely
- # a fresh in-memory index from load_or_create_faiss_index).
- if index_path.exists():
- verified, _reason = self.integrity_manager.verify_file(
- index_path
- )
- if verified:
- try:
- # safe_load_faiss replaces load_local's dangerous
- # pickle deserialization with a restricted unpickler
- # (see faiss_safe_load) so a tampered .pkl cannot
- # execute code on load.
- self.faiss_index = safe_load_faiss(
- str(index_path.parent),
- self.embedding_manager.embeddings,
- index_name=index_path.stem,
- # Must match the creation-time setting at build
- # time (normalize_L2=self.normalize_vectors below)
- # — reloading an unnormalized index with
- # normalize_L2=True silently mixes normalized and
- # raw vectors in the same index.
- normalize_L2=self.normalize_vectors,
- )
- except Exception:
- # Reload failed (torn write, etc.). Keep
- # in-memory state — it's stale but valid;
- # better than losing this write entirely.
- logger.warning(
- "Failed to reload FAISS for merge; "
- "proceeding with in-memory state."
- )
-
- # Replace-on-reindex: purge the document's prior chunk vectors
- # (different chunk hashes from an earlier content version) that
- # would otherwise be orphaned in the index forever — unbounded
- # growth + stale duplicate hits on every note edit. The set is
- # derived HERE, from the freshly-reloaded docstore, by matching
- # each vector's metadata['document_id'] (and collection) — NOT
- # from a caller-supplied snapshot. This makes it authoritative
- # and self-healing: it catches vectors a crashed or concurrent
- # earlier indexer left behind, and the last writer under the
- # lock removes every prior version's vectors. Ids we're about
- # to re-add are kept.
- purged_count = 0
- if replace_document_id and hasattr(self.faiss_index, "docstore"):
- keep = set(embedding_ids)
- purge = []
- for fid, fdoc in self.faiss_index.docstore._dict.items():
- if fid in keep:
- continue
- meta = getattr(fdoc, "metadata", None) or {}
- if meta.get("document_id") != replace_document_id:
- continue
- fdoc_coll = meta.get("collection_id")
- if (
- replace_collection_id is not None
- and fdoc_coll is not None
- and fdoc_coll != replace_collection_id
- ):
- continue
- purge.append(fid)
- purge_texts = {
- fid: getattr(
- self.faiss_index.docstore._dict.get(fid),
- "page_content",
- None,
- )
- for fid in purge
- }
- if purge:
- # Exclusive-ownership check: within a collection the
- # schema dedups chunk rows by (chunk_hash,
- # collection_name), so one vector can serve several
- # documents while its metadata still names whichever
- # document indexed the text first. The DocumentChunk
- # row is the authoritative owner record
- # (_store_chunks_to_db re-points it to the latest
- # claimant); a candidate whose row belongs to a
- # DIFFERENT document is still in use — deleting it
- # would silently drop that document's content from
- # search while it still shows as indexed. Skip those
- # (they become the same benign orphan the pre-purge
- # code always left behind). Rowless candidates are
- # true orphans and stay purgeable.
- with get_user_db_session(
- self.username, self.db_password
- ) as session:
- foreign_owned = set()
- for i in range(0, len(purge), 500):
- batch = purge[i : i + 500]
- foreign_owned.update(
- row[0]
- for row in session.query(
- DocumentChunk.embedding_id
- ).filter(
- DocumentChunk.embedding_id.in_(batch),
- DocumentChunk.source_id
- != replace_document_id,
- )
- )
- if foreign_owned:
- logger.info(
- f"Replace-on-reindex: keeping "
- f"{len(foreign_owned)} shared chunk vector(s) "
- f"now owned by other documents"
- )
- purge = [
- fid for fid in purge if fid not in foreign_owned
- ]
- if purge:
- # Shared-text check: the single mutable source_id owner
- # can't represent multi-document sharing — a SELF-owned
- # row can still be serving another document's identical
- # text (ownership is last-claimer-wins, and rows created
- # before the repoint logic kept their first claimant).
- # Keep any candidate whose chunk text still appears in
- # another current member of this collection; deleting it
- # would silently drop that document's content from
- # search while it still shows as indexed. False keeps
- # are the same benign orphans the pre-purge code always
- # left behind.
- still_shared = self._shared_text_survivors(
- [(fid, purge_texts.get(fid)) for fid in purge],
- replace_collection_id,
- replace_document_id,
- )
- if still_shared:
- logger.info(
- f"Replace-on-reindex: keeping "
- f"{len(still_shared)} chunk vector(s) whose "
- f"text other collection documents still contain"
- )
- purge = [
- fid for fid in purge if fid not in still_shared
- ]
- if purge:
- logger.info(
- f"Replace-on-reindex: removing {len(purge)} prior "
- f"chunk vector(s) for document "
- f"{str(replace_document_id)[:8]}... from FAISS"
- )
- self.faiss_index.delete(purge)
- purged_count = len(purge)
-
- # Force-reindex: remove old copies of IDs we're about to
- # re-add, so updated metadata replaces stale. Dedup via
- # set→list because ``embedding_ids`` can contain repeats
- # (same chunk hash appearing twice in the document) —
- # FAISS.delete with duplicate IDs raises.
- if force_reindex and hasattr(self.faiss_index, "docstore"):
- fresh_ids = set(self.faiss_index.docstore._dict.keys())
- old_chunk_ids = list(
- {eid for eid in embedding_ids if eid in fresh_ids}
- )
- if old_chunk_ids:
- logger.info(
- f"Force re-index: removing {len(old_chunk_ids)} "
- f"existing chunks from FAISS"
- )
- self.faiss_index.delete(old_chunk_ids)
-
- # Dedup against the freshly-loaded state.
- if not force_reindex and hasattr(self.faiss_index, "docstore"):
- fresh_ids = set(self.faiss_index.docstore._dict.keys())
- else:
- fresh_ids = None
-
- new_chunks, new_ids = self._deduplicate_chunks(
- chunks_to_add, embedding_ids, fresh_ids
- )
-
- if new_chunks:
- self.faiss_index.add_documents(new_chunks, ids=new_ids)
-
- self.faiss_index.save_local(
- str(index_path.parent), index_name=index_path.stem
- )
- self.integrity_manager.record_file(
- index_path,
- related_entity_type="rag_index",
- related_entity_id=self.rag_index_record.id,
- )
-
- return {
- "added": len(new_chunks),
- "skipped": len(chunks_to_add) - len(new_chunks),
- "added_ids": new_ids,
- "purged": purged_count,
- }
-
- def load_or_create_faiss_index(
- self, collection_id: str, *, reset_stale_state: bool = False
- ) -> FAISS:
- """
- Load existing FAISS index or create new one.
-
- Args:
- collection_id: UUID of the collection
- reset_stale_state: When the on-disk index is gone (missing,
- quarantined, or deleted on dimension mismatch) but DB rows
- still claim indexed content, reset those rows so a regular
- re-index rebuilds instead of no-opping. Only write paths
- (index/delete operations) may pass True: the default False
- keeps read paths — this method is also how searches load
- the index — free of destructive DB writes, so a transient
- integrity failure during a mere search cannot wipe the
- collection's indexed state and trigger a full re-embed.
-
- Returns:
- FAISS vector store instance
+ collection_id: str,
+ rag_index: RAGIndex,
+ *,
+ reset_stale_state: bool = False,
+ ) -> Path:
+ """Verify -> quarantine -> dimension-check pre-flight for ``rag_index``.
+
+ Extracted from the pre-cutover ``load_or_create_faiss_index``
+ (deleted — the old LangChain-FAISS path is gone) so every
+ index/search/delete call site shares ONE recovery path instead of
+ duplicating it. Mutates ``rag_index.index_path`` / ``rag_index.embedding_dimension``
+ in place — matching the pre-refactor behavior of stamping the
+ recomputed path/dimension back onto the in-memory record so callers
+ that read ``self.rag_index_record`` afterwards see the current
+ values — and returns the resolved on-disk path.
+
+ Deliberately does NOT load or construct a vector store: that stays
+ the caller's job (via ``VectorIndex(...)``), so a corrupt/foreign/
+ dimension-mismatched file surfaces as an exception from THAT
+ construction, which the caller catches to quarantine + rebuild (see
+ ``_get_vector_index``).
"""
- rag_index = self._get_or_create_rag_index(collection_id)
- self.rag_index_record = rag_index
-
- # Always recompute the index path from username + index_hash so
- # the per-user scoping (F2 fix) applies retroactively to
- # RAGIndex rows created before the path layout changed. The
- # stored `rag_index.index_path` may point to a pre-fix shared
- # location; if the file still lives there we relocate it into
- # the per-user directory (one-time upgrade migration) instead
- # of stranding it.
- # We also stamp the recomputed path back onto the in-memory
- # record so the downstream save_local() sites that read
- # `self.rag_index_record.index_path` pick up the new location.
index_path = self._get_index_path(rag_index.index_hash)
stored_path = (
Path(rag_index.index_path) if rag_index.index_path else None
@@ -1071,182 +855,349 @@ class LibraryRAGService:
if not index_path.exists() and stored_path is not None:
self._migrate_legacy_index_files(stored_path, index_path, rag_index)
- # Hold the per-(username, index_path) write lock across the
- # entire verify → quarantine → load sequence. A narrower scope
- # leaves room for a concurrent save_local to race the
- # verification (verify sees bytes A, save overwrites with bytes
- # B, load_local reads bytes B which no longer match verified
- # checksum). See #4197. The fresh-build path below this block
- # is in-memory only and doesn't need the lock.
+ # Hold the per-(username, index_path) write lock across the entire
+ # verify -> quarantine -> dimension-check sequence — see #4197 (a
+ # narrower scope would let a concurrent writer's save race the
+ # verification).
if index_path.exists():
- load_lock = _get_faiss_write_lock(self.username, str(index_path))
- with load_lock:
- # Verify integrity before loading
+ lock = _get_faiss_write_lock(self.username, str(index_path))
+ with lock:
verified, reason = self.integrity_manager.verify_file(
index_path
)
if not verified:
- logger.error(
- f"Integrity verification failed for {index_path}: "
- f"{reason}. Quarantining for recovery; creating "
- f"new index."
- )
- self._quarantine_corrupt_index(index_path, reason)
- else:
+ if reason == NO_INTEGRITY_RECORD:
+ # A MISSING record is not proven corruption, and unlike
+ # checksum_mismatch it cannot be attacker-induced: the
+ # record lives in the per-user ENCRYPTED DB, so removing
+ # it needs the DB password (which also decrypts
+ # everything). It only arises from our own crash between
+ # the index write and record_file (see legacy_rekey
+ # Phase B) or a pre-integrity-feature index. ADOPT the
+ # byte-present file by recording its integrity now — on
+ # BOTH read and write paths. Adoption is non-destructive
+ # (it only records a checksum), so a read path may do it:
+ # refusing here instead would hard-fail EVERY search on a
+ # byte-healthy, missing-record index forever (a read-only
+ # collection is never revisited by a write op that would
+ # otherwise adopt it). If the bytes are actually
+ # unreadable/foreign/wrong-dim, the VectorIndex load below
+ # still raises and the caller handles it — corruption is
+ # caught either way. Only checksum_mismatch (genuine
+ # tamper) is refused/quarantined below.
+ logger.warning(
+ f"No integrity record for {index_path}; adopting the "
+ "existing index (recording its integrity) rather than "
+ "quarantining — a missing record is not corruption."
+ )
+ self.integrity_manager.record_file(
+ index_path,
+ related_entity_type="rag_index",
+ related_entity_id=rag_index.id,
+ )
+ # Adopted = now trusted: fall through to the SAME
+ # embedding-dimension-drift probe the verified branch
+ # runs, so an adopted index whose model dimension changed
+ # is rebuilt rather than silently mismatched at add time.
+ verified = True
+ elif not reset_stale_state:
+ # Read path (search): refuse to serve an index that
+ # failed verification for a reason OTHER than a missing
+ # record (a checksum_mismatch = genuine tamper, or a
+ # transient read failure), but do NOT destroy it —
+ # quarantine is a WRITE-path recovery decision. A
+ # subsequent index/write operation quarantines + rebuilds.
+ raise RuntimeError(
+ f"Integrity verification failed for {index_path}: "
+ f"{reason} — refusing on a read path (a subsequent "
+ "index/write operation will quarantine + rebuild)"
+ )
+ elif reason and reason.startswith(
+ "checksum_calculation_failed"
+ ):
+ # Transient: could not READ the file to compute its
+ # checksum (disk hiccup, momentary lock). This says
+ # NOTHING about tampering — unlike checksum_mismatch — so
+ # quarantining would force a needless full re-embed of a
+ # healthy collection. Raise so the operation retries (like
+ # the read path) instead of destroying the index.
+ raise RuntimeError(
+ f"Integrity check could not read {index_path} "
+ f"({reason}) — refusing to quarantine on a transient "
+ "read failure; retry the operation."
+ )
+ else:
+ logger.error(
+ f"Integrity verification failed for {index_path}: "
+ f"{reason}. Quarantining for recovery; creating "
+ f"new index."
+ )
+ self._quarantine_corrupt_index(index_path, reason)
+ if verified:
# Probe the embedding model OUTSIDE the quarantine
- # try-block: embed_query fails when the embedding
- # provider is unreachable (e.g. Ollama down), which
- # says nothing about the index files. Inside the try
- # it would quarantine a healthy index and silently
- # replace it with an empty one; here it propagates a
- # clear provider error instead.
+ # decision: embed_query fails when the provider itself
+ # is unreachable (e.g. Ollama down), which says nothing
+ # about the index file's health, and must propagate
+ # rather than trigger a destructive rebuild of a
+ # healthy index.
current_dim = len(
self.embedding_manager.embeddings.embed_query(
"dimension_check"
)
)
stored_dim = rag_index.embedding_dimension
-
- try:
- # Check for embedding dimension mismatch before loading
- if stored_dim and current_dim != stored_dim:
- logger.warning(
- f"Embedding dimension mismatch detected! "
- f"Index created with dim={stored_dim}, "
- f"current model returns dim={current_dim}. "
- f"Deleting old index and rebuilding."
+ if stored_dim and current_dim != stored_dim:
+ if not reset_stale_state:
+ # Read path: surface the mismatch instead of
+ # deleting the index + wiping DB state (which a mere
+ # search must never do). A write/index operation
+ # owns the destructive rebuild.
+ raise RuntimeError(
+ f"Embedding dimension mismatch for {index_path}: "
+ f"index dim={stored_dim}, model dim="
+ f"{current_dim} — refusing on a read path"
)
- # Delete old index files (legitimate deletion:
- # the bytes are unreadable with the new model).
- try:
- index_path.unlink()
- pkl_path = index_path.with_suffix(".pkl")
- if pkl_path.exists():
- pkl_path.unlink()
- logger.info(
- f"Deleted old FAISS index files at {index_path}"
- )
- except Exception:
- logger.exception(
- "Failed to delete old index files"
- )
-
- # Update RAGIndex with new dimension and reset counts
- with get_user_db_session(
- self.username, self.db_password
- ) as session:
- idx = (
- session.query(RAGIndex)
- .filter_by(id=rag_index.id)
- .first()
- )
- if idx:
- idx.embedding_dimension = current_dim
- idx.chunk_count = 0
- idx.total_documents = 0
- session.commit()
- logger.info(
- f"Updated RAGIndex dimension to {current_dim}"
- )
-
- # Clear rag_document_status for this index
- session.query(RagDocumentStatus).filter_by(
- rag_index_id=rag_index.id
- ).delete()
+ logger.warning(
+ f"Embedding dimension mismatch detected! "
+ f"Index created with dim={stored_dim}, "
+ f"current model returns dim={current_dim}. "
+ f"Deleting old index and rebuilding."
+ )
+ try:
+ index_path.unlink()
+ pkl_path = index_path.with_suffix(".pkl")
+ if pkl_path.exists():
+ pkl_path.unlink()
+ logger.info(
+ f"Deleted old index files at {index_path}"
+ )
+ except Exception:
+ logger.exception("Failed to delete old index files")
+
+ with get_user_db_session(
+ self.username, self.db_password
+ ) as session:
+ idx = (
+ session.query(RAGIndex)
+ .filter_by(id=rag_index.id)
+ .first()
+ )
+ if idx:
+ idx.embedding_dimension = current_dim
session.commit()
logger.info(
- "Cleared indexed status for documents in this "
- "collection"
+ f"Updated RAGIndex dimension to {current_dim}"
)
-
- # Update local reference for index creation below
- rag_index.embedding_dimension = current_dim
- # Fall through to create new index below
- else:
- # Dimensions match (or no stored dimension), load
- # index via the restricted-unpickler loader (see
- # faiss_safe_load) instead of load_local, so a
- # tampered .pkl cannot execute code on load.
- faiss_index = safe_load_faiss(
- str(index_path.parent),
- self.embedding_manager.embeddings,
- index_name=index_path.stem,
- # Match the creation-time flag; see the
- # reload in _merge_and_persist_locked.
- normalize_L2=self.normalize_vectors,
- )
- logger.info(
- f"Loaded existing FAISS index from {index_path}"
- )
- return faiss_index
- except Exception:
- # load_local raised (torn .pkl, malformed pickle,
- # FAISS read failure). The .faiss bytes may still
- # be recoverable, so quarantine before falling
- # through to fresh build — don't just leave
- # broken state on disk.
- logger.warning(
- "Failed to load FAISS index, quarantining "
- "and creating new one"
+ # Reset RAGIndex counts, RagDocumentStatus, and
+ # DocumentCollection.indexed together — a hand-rolled
+ # partial reset here previously left
+ # DocumentCollection.indexed=True, which makes
+ # index_document/index_collection skip every document
+ # and search silently return nothing after the rebuild.
+ self._reset_index_state_for_rebuild(
+ collection_id, rag_index
)
- if index_path.exists():
- self._quarantine_corrupt_index(
- index_path, "load_local_raised"
- )
+ rag_index.embedding_dimension = current_dim
- # Falling through to a fresh build means the on-disk index is gone
- # (missing, quarantined, or deleted on dimension mismatch). If DB
- # rows still claim indexed content, reset them so a regular
- # (non-force) re-index actually rebuilds instead of no-opping.
- # Write callers only (see the reset_stale_state doc above) — a
- # read/search caller must not mutate index state.
- if reset_stale_state:
- self._reset_index_state_for_rebuild(collection_id, rag_index)
+ if not index_path.exists():
+ # The new per-user path is missing — but that alone does NOT mean the
+ # index is gone. A one-time legacy-path relocation
+ # (_migrate_legacy_index_files above) can fail transiently (a rename
+ # hitting disk-full, an AV/backup file lock, a busy network mount),
+ # leaving the bytes fully intact at the stored legacy path. Treating
+ # that as "gone" would wipe a healthy collection's indexed bookkeeping
+ # — even on a mere search — and force a needless full re-embed. Only
+ # self-heal when the bytes are absent at BOTH the new and the legacy
+ # location; otherwise leave the state alone so the next write-path
+ # access retries the relocation.
+ legacy_bytes_present = bool(
+ stored_path is not None
+ and stored_path != index_path
+ and stored_path.exists()
+ )
+ if not legacy_bytes_present:
+ stale_indexed = bool(
+ (rag_index.chunk_count or 0) > 0
+ or (rag_index.total_documents or 0) > 0
+ )
+ if stale_indexed:
+ # DB says indexed, but the file is GONE at both locations
+ # (cache dir cleared, restored without the cache dir, lost
+ # volume, crash between quarantine and rebuild). Reset so it
+ # self-heals — even on a READ path: an absent file has
+ # nothing to preserve, and without this search silently
+ # returns [] forever (get_rag_stats still reports 100%
+ # indexed and a normal reindex short-circuits on
+ # indexed=True, so nothing ever recovers it).
+ logger.warning(
+ f"RAG index file for collection {collection_id} is "
+ f"MISSING at {index_path} while the collection is marked "
+ "indexed — resetting indexed state so it rebuilds "
+ "(search would otherwise return no results indefinitely)."
+ )
+ self._reset_index_state_for_rebuild(
+ collection_id, rag_index
+ )
+ elif reset_stale_state:
+ self._reset_index_state_for_rebuild(
+ collection_id, rag_index
+ )
- # Create new FAISS index with configurable type and distance metric
- logger.info(
- f"Creating new FAISS index: type={self.index_type}, metric={self.distance_metric}, dimension={rag_index.embedding_dimension}"
+ return index_path
+
+ def _get_vector_index(
+ self,
+ collection_id: str,
+ collection_name: str,
+ *,
+ reset_stale_state: bool = False,
+ ) -> VectorIndex:
+ """Build a :class:`VectorIndex` for ``collection_id``.
+
+ Single call site for the index/search/delete paths: runs the
+ verify/quarantine/dimension-check pre-flight, then constructs the
+ facade. On a ``ValueError``/``RuntimeError`` from the underlying
+ store's ``load()`` (corrupt bytes, a foreign/pre-migration format
+ that isn't an ``IndexIDMap2``, or a dimension mismatch the
+ pre-flight didn't already catch) the corrupt file is quarantined,
+ stale per-document indexed state is reset, and construction is
+ retried once as a fresh, empty store.
+
+ NOTE: like ``_get_or_create_rag_index``, this CREATES a RAGIndex
+ row if none exists for the configured (collection, embedding model)
+ — callers on a delete-only path that must not create an index
+ (e.g. ``remove_documents_from_index``) guard with their own
+ existence check before calling this.
+ """
+ # Only WRITE paths (reset_stale_state=True) may re-promote a reused
+ # index to is_current; a read-path search must not flip the pointer.
+ rag_index = self._get_or_create_rag_index(
+ collection_id, promote_current=reset_stale_state
)
+ self.rag_index_record = rag_index
+ index_path = self._preflight_index_path(
+ collection_id, rag_index, reset_stale_state=reset_stale_state
+ )
+ lock = _get_faiss_write_lock(self.username, str(index_path))
- # Create index based on type and distance metric
- if self.index_type == "hnsw":
- # HNSW: Fast approximate search, best for large collections
- # M=32 is a good default for connections per layer
- index = IndexHNSWFlat(rag_index.embedding_dimension, 32)
- logger.info("Created HNSW index with M=32 connections")
- elif self.index_type == "ivf":
- # IVF requires training, for now fall back to flat
- # TODO: Implement IVF with proper training
+ # nested=True: these run reentrantly inside VectorIndex.apply(), which
+ # holds just-flushed, uncommitted DocumentChunk rows on this same
+ # thread-local session. The integrity write must run in a SAVEPOINT and
+ # let apply()'s caller commit — a plain commit/rollback here would
+ # settle or DISCARD those pending rows (silently losing indexed text
+ # while the vectors persist). See FileIntegrityManager._integrity_write.
+ def _record(path: Path) -> None:
+ self.integrity_manager.record_file(
+ path,
+ related_entity_type="rag_index",
+ related_entity_id=rag_index.id,
+ nested=True,
+ )
+
+ def _verify(path: Path):
+ return self.integrity_manager.verify_file(path, nested=True)
+
+ kwargs = {
+ "username": self.username,
+ "db_password": self.db_password,
+ # Lazy: index()/search() resolve the real backend on first embed_*
+ # call (identical behaviour, one extra attribute hop), while the
+ # delete-only path (remove_documents_from_index) never materialises
+ # it at all. See _LazyEmbeddings.
+ "embeddings": _LazyEmbeddings(self.embedding_manager),
+ "embedding_model": self.embedding_model,
+ "embedding_model_type": EmbeddingProvider(self.embedding_provider),
+ "collection_name": collection_name,
+ "dimension": rag_index.embedding_dimension,
+ "path": index_path,
+ "lock": lock,
+ "integrity_record": _record,
+ "integrity_verify": _verify,
+ # Use the STORED index config, not this service instance's. The
+ # RAGIndex row is stamped with index_type/metric/normalize at
+ # creation (see _get_or_create_rag_index); the constructing
+ # LibraryRAGService may carry different CURRENT defaults (the
+ # factory falls back to global settings for a collection whose
+ # metadata was never stored). Building against self.* would load a
+ # real HNSW file while labelling it "flat" (or vice-versa), and
+ # FaissVectorStore.supports_delete trusts the label — routing a
+ # removal through remove_ids on an HNSW index (unsupported → raises)
+ # or silently rewriting a flat file as HNSW. This mirrors the fix
+ # already applied to purge_document_vectors below.
+ "index_type": rag_index.index_type or self.index_type,
+ "metric": rag_index.distance_metric or self.distance_metric,
+ "normalize": (
+ rag_index.normalize_vectors
+ if rag_index.normalize_vectors is not None
+ else self.normalize_vectors
+ ),
+ }
+ try:
+ return VectorIndex(**kwargs)
+ except (ValueError, RuntimeError):
+ if not reset_stale_state:
+ # Read paths (search) must stay side-effect-free. A transient
+ # load failure (OOM, a disk hiccup, a momentarily-locked file)
+ # on an existing, byte-healthy index must NOT quarantine the
+ # file or wipe the collection's indexed state — that would turn
+ # a retryable blip into a forced full re-embed of the whole
+ # collection triggered by a mere search. Surface the error;
+ # quarantine + rebuild is a WRITE-path (reset_stale_state=True)
+ # decision. (A never-indexed collection never reaches here — no
+ # file exists, so VectorIndex.create() succeeds above.)
+ raise
+ # A load failure here — after _preflight_index_path's verify_file
+ # just PASSED on the same bytes — is ambiguous: it is either a
+ # genuine format/dimension mismatch (deterministic — needs a rebuild)
+ # OR a transient OS hiccup (EMFILE under concurrent multi-user load,
+ # a momentary AV-scan/backup file lock; the byte-healthy file loads
+ # fine moments later). faiss surfaces BOTH as the same RuntimeError,
+ # so quarantining unconditionally destroys a provably-healthy index
+ # and forces a needless full re-embed on a mere transient blip.
+ # Distinguish by RETRYING the load once: a transient failure clears,
+ # a deterministic one repeats. Only quarantine when the retry also
+ # fails. (Mirrors _preflight_index_path's transient-vs-tamper split.)
logger.warning(
- "IVF index type not yet fully implemented, using Flat index"
+ f"Failed to load vector store at {index_path}; retrying once "
+ "before quarantining (may be a transient OS hiccup)"
)
- if self.distance_metric in ("cosine", "dot_product"):
- index = IndexFlatIP(rag_index.embedding_dimension)
- else:
- index = IndexFlatL2(rag_index.embedding_dimension)
- else: # "flat" or default
- # Flat index: Exact search
- if self.distance_metric in ("cosine", "dot_product"):
- # For cosine similarity, use inner product (IP) with normalized vectors
- index = IndexFlatIP(rag_index.embedding_dimension)
- logger.info(
- "Created Flat index with Inner Product (for cosine similarity)"
- )
- else: # l2
- index = IndexFlatL2(rag_index.embedding_dimension)
- logger.info("Created Flat index with L2 distance")
-
- faiss_index = FAISS(
- self.embedding_manager.embeddings,
- index=index,
- docstore=InMemoryDocstore(), # Minimal - chunks in DB
- index_to_docstore_id={},
- normalize_L2=self.normalize_vectors, # Use configurable normalization
- )
- logger.info(
- f"FAISS index created with normalization={self.normalize_vectors}"
- )
- return faiss_index
+ try:
+ return VectorIndex(**kwargs)
+ except (ValueError, RuntimeError):
+ pass
+ logger.warning(
+ f"Vector store at {index_path} failed to load twice; "
+ "quarantining and rebuilding fresh"
+ )
+ with lock:
+ if index_path.exists():
+ self._quarantine_corrupt_index(
+ index_path, "vector_index_load_failed"
+ )
+ self._reset_index_state_for_rebuild(collection_id, rag_index)
+ return VectorIndex(**kwargs)
+
+ def search(
+ self, query: str, collection_id: str, top_k: int
+ ) -> List[SearchResult]:
+ """Semantic search within ``collection_id`` via the vector store.
+
+ Runs the same verify/quarantine/dimension pre-flight as indexing
+ (through ``_get_vector_index``), then delegates to
+ ``VectorIndex.search``. ``reset_stale_state`` is left at its
+ default False — this is a read path: a transient integrity hiccup
+ during a mere search must not wipe the collection's indexed state
+ and force a full re-embed.
+
+ Callers are expected to have already confirmed the collection has
+ indexed documents (e.g. via ``get_rag_stats``) before calling this
+ — this method will otherwise create an empty RAGIndex/store for a
+ never-indexed (collection, embedding model) pair and return no
+ results, rather than raising.
+ """
+ collection_name = f"collection_{collection_id}"
+ vindex = self._get_vector_index(collection_id, collection_name)
+ return vindex.search(query, top_k)
def get_current_index_info(
self, collection_id: Optional[str] = None
@@ -1321,6 +1272,43 @@ class LibraryRAGService:
"last_updated_at": rag_index.last_updated_at.isoformat(),
}
+ def _flag_document_for_reindex(
+ self, session, document_id: str, collection_id: str
+ ) -> None:
+ """Mark a document NOT indexed so the reconciler re-embeds it.
+
+ Used on index_document failure paths: ``VectorIndex.index()`` runs
+ ``store.apply()`` — DURABLY mutating the FAISS file — BEFORE the DB
+ commit, so a failure/rollback after that point can leave the source's
+ prior chunk rows resurrected with no vectors (silently unsearchable)
+ while ``DocumentCollection.indexed`` is reverted to its pre-attempt
+ state. The background reconciler only revisits ``indexed=False`` rows,
+ so without this flag the document stays permanently, silently
+ unsearchable. Best-effort + committed in its own statement;
+ index_document owns per-document commits (see index_all_documents), so
+ this clobbers no caller.
+ """
+ try:
+ session.query(DocumentCollection).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).update(
+ {"indexed": False, "chunk_count": 0},
+ synchronize_session=False,
+ )
+ session.query(RagDocumentStatus).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).delete(synchronize_session=False)
+ session.commit()
+ except Exception:
+ safe_rollback(
+ session, "library_rag_service._flag_document_for_reindex"
+ )
+ logger.warning(
+ f"Could not flag document {document_id} for re-index after a "
+ f"failed index of collection {collection_id}; a manual reindex "
+ "may be needed to restore its search."
+ )
+
def index_document(
self, document_id: str, collection_id: str, force_reindex: bool = False
) -> Dict[str, Any]:
@@ -1357,6 +1345,83 @@ class LibraryRAGService:
# Validate text content
if not document.text_content:
+ # A previously-indexed document now cleared to empty text (e.g.
+ # a note edited down to whitespace) must have its stale
+ # chunks/vectors PURGED, not left searchable. The note-edit path
+ # already set indexed=False, so detect prior chunks directly and
+ # remove them via the facade's empty-replace.
+ collection_name = f"collection_{collection_id}"
+ has_prior = (
+ session.query(DocumentChunk.id)
+ .filter_by(
+ source_type="document",
+ source_id=document_id,
+ collection_name=collection_name,
+ )
+ .first()
+ is not None
+ )
+ if has_prior:
+ # Same store-durable-before-DB-commit hazard as the main
+ # reindex path below, but this branch sits OUTSIDE that
+ # path's try/except: the empty-replace apply() DURABLY
+ # removes the prior vectors before the commit here. On
+ # failure, roll back and flag the document for re-index so
+ # the reconciler re-runs the purge instead of leaving
+ # resurrected rows whose vectors are gone (silently
+ # unsearchable) marked indexed.
+ try:
+ vindex = self._get_vector_index(
+ collection_id,
+ collection_name,
+ reset_stale_state=True,
+ )
+ vindex.index(
+ source_type="document",
+ source_id=document_id,
+ chunks=[],
+ replace=True,
+ session=session,
+ )
+ doc_collection.indexed = False
+ doc_collection.chunk_count = 0
+ # Clear the canonical RagDocumentStatus row too. Row
+ # existence is the "indexed" marker get_rag_stats / the
+ # RAG status route read, so it MUST move with
+ # DocumentCollection.indexed — a leftover row would
+ # report this just-purged (now empty, unsearchable)
+ # document as still indexed with a stale chunk_count.
+ # Mirrors remove_document_from_rag and the three sibling
+ # not-indexed paths; the cleared branch was the lone
+ # exception.
+ session.query(RagDocumentStatus).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).delete(synchronize_session=False)
+ session.commit()
+ except Exception as e:
+ safe_rollback(
+ session,
+ "library_rag_service.index_document cleared",
+ )
+ self._flag_document_for_reindex(
+ session, document_id, collection_id
+ )
+ logger.exception(
+ f"Error purging cleared document {document_id} "
+ f"for collection {collection_id}"
+ )
+ return {
+ "status": "error",
+ "error": f"Operation failed: {type(e).__name__}",
+ }
+ return {
+ "status": "cleared",
+ "message": (
+ "Document has no text content; prior chunks/"
+ "vectors purged"
+ ),
+ "chunk_count": 0,
+ }
return {
"status": "error",
"error": "Document has no text content",
@@ -1365,18 +1430,15 @@ class LibraryRAGService:
# Replace-on-reindex context: a document being re-indexed (e.g.
# a note whose content changed) has prior chunks with DIFFERENT
# content hashes from the new text. Left alone they accumulate
- # in both the DB and FAISS forever — unbounded per-edit growth
- # plus stale duplicate search hits. The cleanup is handled
- # durably and concurrency-safely below: the FAISS purge derives
- # the document's prior vectors from the index docstore by
- # metadata under the write lock (authoritative + self-healing,
- # not from an ephemeral pre-committed snapshot), and the DB
- # chunk rows are pruned inside the main transaction after the
- # new chunks are stored (so a failure rolls back together with
- # everything else, never orphaning rows or poisoning the
- # shared session). The prune and the chunk-store below both use
- # the single ``collection_name`` value so they can never filter
- # on a different name than was stored.
+ # in both the DB and the vector store forever — unbounded
+ # per-edit growth plus stale duplicate search hits.
+ # ``VectorIndex.index(replace=True)`` below handles this: it
+ # looks up the source's prior DocumentChunk rows (authoritative,
+ # queried fresh — not from an ephemeral pre-committed snapshot),
+ # applies the vector-store removal durably, then deletes those
+ # rows in the SAME transaction this method already holds open
+ # (so a failure rolls back together with everything else, never
+ # orphaning rows or poisoning the shared session).
try:
# Create LangChain Document from text
@@ -1422,79 +1484,75 @@ class LibraryRAGService:
f"collection_{collection_id}" if collection else "unknown"
)
- # Store chunks in database using embedding manager
- embedding_ids = self.embedding_manager._store_chunks_to_db(
- chunks=chunks,
- collection_name=collection_name,
- source_type="document",
- source_id=document_id,
+ document_title = (
+ document.title or document.filename or "Untitled"
)
-
- # Guard the "chunks produced but nothing stored" case.
- # _store_chunks_to_db appends one id per chunk on success
- # (a reused id for a pre-existing chunk, a fresh id for a new
- # one), so len(embedding_ids) == len(chunks); it returns []
- # ONLY when it caught an exception. A non-empty chunk set with
- # no embedding ids therefore means the store failed: no vectors
- # were persisted. Do NOT fall through to mark the document
- # indexed=True: a document flagged indexed must be searchable
- # (its embeddings must exist), and the background reconciler
- # only retries rows with indexed=False. Marking it indexed here
- # would leave it silently unsearchable and never retried.
- if chunks and not embedding_ids:
- logger.error(
- f"Chunk store returned no embeddings for document "
- f"{document_id} in collection {collection_id} "
- f"({len(chunks)} chunks); leaving it unindexed for retry"
- )
- return {
- "status": "error",
- "error": "Failed to store chunks: no embeddings were persisted",
- }
-
- # Load or create FAISS index (lazy; the merge step
- # below will reload from disk under the lock anyway).
- if self.faiss_index is None:
- self.faiss_index = self.load_or_create_faiss_index(
- collection_id, reset_stale_state=True
+ # Mirrors the parent doc's metadata dict built above (source,
+ # ids, bibliographic fields) so it survives into each
+ # chunk's ``DocumentChunk.document_metadata`` — this goes
+ # ONLY to the encrypted DB (never the vector store; see the
+ # SECURITY INVARIANT in vector_stores/base.py) and future-
+ # proofs citation/UI features that read per-chunk metadata.
+ shared_chunk_metadata = {
+ "source": document.original_url,
+ "document_id": document_id,
+ "collection_id": collection_id,
+ "document_title": document_title,
+ "title": document_title,
+ "authors": document.authors,
+ "published_date": str(document.published_date)
+ if document.published_date
+ else None,
+ "doi": document.doi,
+ "arxiv_id": document.arxiv_id,
+ "pmid": document.pmid,
+ "pmcid": document.pmcid,
+ "extraction_method": document.extraction_method,
+ "word_count": document.word_count,
+ }
+ chunk_inputs = [
+ ChunkInput(
+ text=chunk.page_content,
+ metadata={
+ **shared_chunk_metadata,
+ "chunk_index": i,
+ },
)
+ for i, chunk in enumerate(chunks)
+ ]
- # Read-modify-write the on-disk FAISS index under
- # the per-(user, index_path) lock. The lock spans
- # reload + dedup + add + save so concurrent indexers
- # of different documents into the same collection
- # don't lose each other's embeddings (see AI review
- # of #4200).
- index_path = Path(self.rag_index_record.index_path)
- unique_count = len(set(embedding_ids))
- batch_dups = len(chunks) - unique_count
- merge_stats = self._merge_and_persist_locked(
- index_path,
- chunks,
- embedding_ids,
- force_reindex=force_reindex,
- replace_document_id=document_id,
- replace_collection_id=collection_id,
+ # Embed + persist via the new int-id-keyed vector store —
+ # this writes DocumentChunk rows (text only in the encrypted
+ # DB) and the vector-store's ids/vectors (never text; see
+ # the SECURITY INVARIANT in vector_stores/base.py). Passing
+ # ``session`` means the facade does not commit/rollback —
+ # this transaction still owns that (below).
+ #
+ # replace=True ALWAYS: a full-document (re)index owns all of a
+ # source's chunks, so it must drop the source's prior
+ # chunks/vectors before adding the new ones. force_reindex is
+ # NOT a safe proxy: a note edit clears the indexed STATUS
+ # (_mark_note_stale_for_reindex_in_session) but leaves the
+ # pre-edit chunk rows/vectors in place, so the subsequent
+ # non-forced reindex would reach here with force_reindex=False
+ # AND prior chunks present — appending would leave stale/deleted
+ # note text permanently searchable and duplicate every chunk.
+ # For a genuinely never-indexed source, prior_ids is empty and
+ # replace is a no-op, so this is always safe.
+ vindex = self._get_vector_index(
+ collection_id, collection_name, reset_stale_state=True
+ )
+ index_stats = vindex.index(
+ source_type="document",
+ source_id=document_id,
+ chunks=chunk_inputs,
+ replace=True,
+ session=session,
)
- if merge_stats["added"]:
- if force_reindex:
- logger.info(
- f"Force re-index: added {merge_stats['added']} "
- f"chunks with updated metadata to FAISS index"
- )
- else:
- already_exist = unique_count - merge_stats["added"]
- logger.info(
- f"Added {merge_stats['added']} new embeddings to FAISS "
- f"({already_exist} already exist, "
- f"{batch_dups} batch duplicates removed)"
- )
- else:
- logger.info(
- f"All {len(chunks)} chunks already exist in FAISS index, skipping"
- )
logger.info(
- f"Saved FAISS index to {index_path} with integrity tracking"
+ f"Vector index update for document {document_id}: "
+ f"{index_stats.added} added, {index_stats.removed} "
+ f"removed ({index_stats.chunks} chunks total)"
)
from datetime import datetime, UTC
@@ -1556,30 +1614,11 @@ class LibraryRAGService:
f"Updated RAGIndex stats: chunk_count +{len(chunks)}, total_documents +1"
)
- # Replace-on-reindex DB prune: remove this document's prior
- # chunk rows that the new content no longer uses (embedding
- # ids not in the freshly-stored set). Runs INSIDE this
- # transaction (after _store_chunks_to_db, before the final
- # commit) so a failure rolls back with everything else —
- # no separate pre-commit, no session poisoning, no orphaned
- # rows. Unchanged chunks reuse their existing row (their id
- # is in embedding_ids) and are kept.
- fresh_ids = [e for e in embedding_ids if e]
- stale_q = session.query(DocumentChunk).filter(
- DocumentChunk.source_id == document_id,
- DocumentChunk.source_type == "document",
- DocumentChunk.collection_name == collection_name,
- )
- if fresh_ids:
- stale_q = stale_q.filter(
- DocumentChunk.embedding_id.notin_(fresh_ids)
- )
- pruned = stale_q.delete(synchronize_session=False)
- if pruned:
- logger.info(
- f"Re-index of {document_id[:8]}...: pruned {pruned} "
- f"stale chunk row(s) the new content no longer uses"
- )
+ # Replace-on-reindex DB prune: no longer needed here —
+ # ``VectorIndex.index(replace=True)`` above already deletes
+ # this source's prior DocumentChunk rows (and their
+ # vectors) as part of the same transaction/lock when
+ # ``force_reindex`` is set.
# Flush ORM changes to database before commit
session.flush()
@@ -1601,7 +1640,6 @@ class LibraryRAGService:
return {
"status": "success",
"chunk_count": len(chunks),
- "embedding_ids": embedding_ids,
}
except Exception as e:
@@ -1612,6 +1650,15 @@ class LibraryRAGService:
# returning the error dict so the caller sees a clean
# session. (Same pattern as the #3827 fix.)
safe_rollback(session, "library_rag_service.index_document")
+ # Backstop for the store-durable-before-DB-commit window: a
+ # REPLACE reindex ran store.apply() (DURABLY removing this
+ # source's prior vectors) before the DB commit, so the rollback
+ # above resurrects rows whose vectors are already gone while
+ # reverting indexed→its pre-attempt True. Flag for re-index so
+ # the reconciler re-embeds and store+DB reconverge.
+ self._flag_document_for_reindex(
+ session, document_id, collection_id
+ )
logger.exception(
f"Error indexing document {document_id} for collection {collection_id}"
)
@@ -1676,7 +1723,11 @@ class LibraryRAGService:
if result["status"] == "success":
results["successful"] += 1
- elif result["status"] == "skipped":
+ elif result["status"] in ("skipped", "cleared"):
+ # "cleared" (a previously-indexed doc emptied to no text,
+ # its stale vectors purged) is a handled non-failure, not an
+ # error — counting it in "failed" would surface a blank-error
+ # failure for a correct purge.
results["skipped"] += 1
else:
results["failed"] += 1
@@ -1740,30 +1791,60 @@ class LibraryRAGService:
f"collection_{collection_id}" if collection else "unknown"
)
- # Delete chunks from database
- deleted_count = self.embedding_manager._delete_chunks_from_db(
- collection_name=collection_name,
- source_id=document_id,
- )
-
- # _delete_chunks_from_db is DB-only — also drop the document's
- # vectors from the FAISS index, otherwise they (and their
- # persisted text) keep surfacing in search until a full
- # reindex. Best-effort: a FAISS hiccup must not fail the DB
- # removal that already succeeded.
+ # Remove the document's vectors from the FAISS index FIRST.
+ # ``remove_documents_from_index`` -> ``VectorIndex.delete``
+ # looks up the DocumentChunk rows by (source_type, source_id,
+ # collection_name) to learn which FAISS int ids to remove,
+ # and deletes those matching rows itself as part of the same
+ # operation. If the DB rows were deleted first, that lookup
+ # would find nothing and the vectors (and their persisted
+ # text) would be stranded in the FAISS store forever — never
+ # removed and never re-discoverable by a later cleanup.
+ # Best-effort: a FAISS hiccup must not fail the DB removal
+ # below.
+ # ``remove_documents_from_index`` deletes the matching chunk
+ # rows itself (one row per removed vector) and returns that
+ # count. Capture it so the reported ``deleted_count`` reflects
+ # the rows removed here, not just the backstop sweep below: in
+ # the normal path those rows are already gone by the time the
+ # backstop runs, so the backstop returns ~0 and — left
+ # uncounted — would under-report the removal (often as 0) to
+ # the caller/UI.
+ removed_vectors = 0
try:
- self.remove_documents_from_index(
+ removed_vectors = self.remove_documents_from_index(
[document_id], collection_id
)
except Exception:
- logger.warning(
- "Could not remove document vectors from FAISS index"
+ logger.exception(
+ f"Could not remove document {document_id} vectors "
+ f"from FAISS index for collection {collection_id}"
)
+ # DB-only cleanup for any rows ``remove_documents_from_index``
+ # did not match (e.g. no current FAISS index for this
+ # collection). Disjoint from ``removed_vectors`` above (those
+ # rows are already committed-deleted), so the two sum to the
+ # true total removed.
+ deleted_count = removed_vectors + (
+ self.embedding_manager._delete_chunks_from_db(
+ collection_name=collection_name,
+ source_id=document_id,
+ )
+ )
+
# Update DocumentCollection RAG status
doc_collection.indexed = False
doc_collection.chunk_count = 0
doc_collection.last_indexed_at = None
+ # Clear the canonical RagDocumentStatus row too. Row-existence is
+ # the "indexed" marker get_rag_stats / the RAG status route read,
+ # so it MUST move together with DocumentCollection.indexed — a
+ # leftover row would report the just-removed document as still
+ # indexed.
+ session.query(RagDocumentStatus).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).delete(synchronize_session=False)
session.commit()
logger.info(
@@ -1779,6 +1860,45 @@ class LibraryRAGService:
safe_rollback(
session, "library_rag_service.remove_document_from_rag"
)
+ # Backstop for the store-durable-before-DB-commit window:
+ # remove_documents_from_index -> VectorIndex.delete ran
+ # store.apply() (DURABLY removing this document's vectors) BEFORE
+ # the DB status work above committed, so the rollback can leave
+ # the row still marked indexed=True with its vectors already gone
+ # -- indexed-but-unsearchable, and over-reported as indexed by
+ # get_rag_stats with no auto-recovery. Durably COMPLETE the
+ # removal's status change so the DB matches the removed vectors:
+ # mark it not-indexed and drop the canonical RagDocumentStatus
+ # row. This is a REMOVAL backstop, not a re-index one (contrast
+ # index_document's _flag_document_for_reindex) -- the vectors are
+ # intentionally gone, so we finish the removal rather than
+ # resurrect the document. Best-effort: a retry of the removal
+ # reconciles it if this too fails.
+ try:
+ session.query(DocumentCollection).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).update(
+ {
+ "indexed": False,
+ "chunk_count": 0,
+ "last_indexed_at": None,
+ },
+ synchronize_session=False,
+ )
+ session.query(RagDocumentStatus).filter_by(
+ document_id=document_id, collection_id=collection_id
+ ).delete(synchronize_session=False)
+ session.commit()
+ except Exception:
+ safe_rollback(
+ session,
+ "library_rag_service.remove_document_from_rag backstop",
+ )
+ logger.warning(
+ f"Could not finalize removal state for document "
+ f"{document_id} in collection {collection_id}; a retry "
+ "of the removal will reconcile it."
+ )
logger.exception(
f"Error removing document {document_id} from collection {collection_id}"
)
@@ -1817,26 +1937,28 @@ class LibraryRAGService:
self, document_id: str, collection_id: str
) -> int:
"""Remove a deleted document's chunk vectors from the collection's
- FAISS index.
+ vector store.
Companion to ``purge_document_chunks`` for callers that delete the
``Document`` row itself (note deletion). Without this the vectors
lingered until a replace-on-reindex of the SAME document id — which
can never fire again once the document is deleted — so collection
- search (which builds snippets straight from the FAISS docstore,
- with no Document-existence check) kept serving the deleted content
- indefinitely.
-
- Runs the same reload → purge → save sequence as replace-on-reindex
- (``_merge_and_persist_locked`` with an empty add set), including
- its shared-chunk ownership check: a vector whose ``DocumentChunk``
- row is owned by a different document survives, because that
- document still contains the identical text.
-
- Call BEFORE ``purge_document_chunks`` if pairing both — the
- ownership rows are the evidence the purge consults. (Rowless
- vectors are treated as orphans and purged, so the reverse order
- still converges; this order just keeps the check authoritative.)
+ search kept serving the deleted content indefinitely.
+
+ Routes to ``VectorIndex.delete(source_type="document",
+ source_id=document_id)``. Unlike the pre-cutover implementation,
+ no separate "shared chunk ownership" check is needed here: the new
+ store is one-row-per-source (see the "One row = one vector" note in
+ vector_stores/facade.py) — identical text in two documents gets two
+ independent rows/vectors, so deleting this document's rows can
+ never remove another document's vector.
+
+ Deliberately does NOT go through ``_get_vector_index`` /
+ ``_get_or_create_rag_index``: a deletion path must not create an
+ index record (or probe the embedding provider) just to delete from
+ it, and does not quarantine/rebuild on a failed load — an
+ unreadable index has nothing purgeable right now; quarantine/
+ rebuild decisions stay with the indexing paths.
Returns the number of vectors removed.
"""
@@ -1856,8 +1978,23 @@ class LibraryRAGService:
return 0
self.rag_index_record = rag_index
- index_path = self._get_index_path(rag_index.index_hash)
- if not index_path.exists():
+ # Resolve where the file ACTUALLY lives, the way the index/search paths
+ # do — but without _preflight's side effects (this deletion path must
+ # not relocate/record/create). rag_index.index_path is the authoritative
+ # DB record (the legacy shared-cache path pre-migration, the per-user
+ # path after _preflight relocates it); _get_index_path(index_hash) only
+ # recomputes the POST-migration location. Checking only the recomputed
+ # path silently no-ops on an un-migrated install — the file is still at
+ # the legacy index_path, so the deleted document's real vector survives.
+ recomputed_path = self._get_index_path(rag_index.index_hash)
+ recorded_path = (
+ Path(rag_index.index_path) if rag_index.index_path else None
+ )
+ if recorded_path is not None and recorded_path.exists():
+ index_path = recorded_path
+ elif recomputed_path.exists():
+ index_path = recomputed_path
+ else:
return 0
verified, reason = self.integrity_manager.verify_file(index_path)
if not verified:
@@ -1869,15 +2006,68 @@ class LibraryRAGService:
)
return 0
- stats = self._merge_and_persist_locked(
- index_path,
- [],
- [],
- force_reindex=False,
- replace_document_id=document_id,
- replace_collection_id=collection_id,
- )
- return stats.get("purged", 0)
+ lock = _get_faiss_write_lock(self.username, str(index_path))
+
+ # nested=True: these run reentrantly inside VectorIndex.apply(), which
+ # holds just-flushed, uncommitted DocumentChunk rows on this same
+ # thread-local session. The integrity write must run in a SAVEPOINT and
+ # let apply()'s caller commit — a plain commit/rollback here would
+ # settle or DISCARD those pending rows (silently losing indexed text
+ # while the vectors persist). See FileIntegrityManager._integrity_write.
+ def _record(path: Path) -> None:
+ self.integrity_manager.record_file(
+ path,
+ related_entity_type="rag_index",
+ related_entity_id=rag_index.id,
+ nested=True,
+ )
+
+ def _verify(path: Path):
+ return self.integrity_manager.verify_file(path, nested=True)
+
+ try:
+ vindex = VectorIndex(
+ username=self.username,
+ db_password=self.db_password,
+ # Delete-only path: never materialise the embedding backend.
+ # VectorIndex.delete() resolves rows by id and never calls
+ # embed_*; forcing the model here would cost seconds + hundreds
+ # of MB of RSS per deleted document for nothing.
+ embeddings=_LazyEmbeddings(self.embedding_manager),
+ embedding_model=self.embedding_model,
+ embedding_model_type=EmbeddingProvider(self.embedding_provider),
+ collection_name=collection_name,
+ dimension=rag_index.embedding_dimension,
+ path=index_path,
+ lock=lock,
+ integrity_record=_record,
+ integrity_verify=_verify,
+ # Use the STORED index config, not the service instance's — a
+ # service built with defaults (index_type="flat") would evaluate
+ # supports_delete wrongly for an HNSW collection and silently
+ # fail the removal. NULL (legacy rows) falls back to self.*.
+ index_type=rag_index.index_type or self.index_type,
+ metric=rag_index.distance_metric or self.distance_metric,
+ normalize=(
+ rag_index.normalize_vectors
+ if rag_index.normalize_vectors is not None
+ else self.normalize_vectors
+ ),
+ )
+ stats = vindex.delete(source_type="document", source_id=document_id)
+ except (ValueError, RuntimeError, OSError):
+ # OSError too: this is a BEST-EFFORT purge whose caller goes on to
+ # delete the DocumentChunk rows. A disk error from the FAISS
+ # persist() (OSError) must not escape and abort that row deletion —
+ # it would strand the chunk rows while leaving the vectors, the
+ # opposite inconsistency. Skip the vector purge and let the caller
+ # proceed; the vectors reconcile on the next re-index.
+ logger.warning(
+ f"Skipping vector purge for document {document_id}: could "
+ f"not load or update index {index_path}"
+ )
+ return 0
+ return stats.removed
def index_documents_batch(
self,
@@ -1947,15 +2137,16 @@ class LibraryRAGService:
}
continue
- # Validate text content
- if not document.text_content:
- results[doc_id] = {
- "status": "error",
- "error": "Document has no text content",
- }
- continue
-
- # Index the document
+ # Do NOT short-circuit empty text_content here: a document/note
+ # edited down to empty still has its PRIOR chunks + vectors on
+ # disk, and only index_document's empty-content branch purges
+ # them (via an empty-replace). Returning an "error" here left
+ # that stale (plaintext) content permanently searchable through
+ # the bulk "Index All" path — and self-perpetuating, since the
+ # doc's indexed flag never flips. Route it through index_document
+ # so the batch path gets the same purge-on-clear as the SSE /
+ # single-document paths; it returns "cleared" (purged) or the
+ # same "error" when there were no prior chunks.
try:
result = self.index_document(
doc_id, collection_id, force_reindex
@@ -2052,114 +2243,47 @@ class LibraryRAGService:
"chunk_overlap": self.chunk_overlap,
}
- def remove_collection_from_index(
- self, collection_name: str
- ) -> Dict[str, Any]:
- """
- Remove all documents from a collection from the FAISS index.
-
- Args:
- collection_name: Name of the collection (e.g., "collection_123")
-
- Returns:
- Dict with status and count of removed chunks
- """
- from ...database.models import DocumentChunk
- from ...database.session_context import get_user_db_session
-
- try:
- with get_user_db_session(
- self.username, self.db_password
- ) as session:
- # Get all chunk IDs for this collection. Select only the
- # id column — loading full DocumentChunk rows would pull
- # every chunk's text into memory just to build the id
- # list (#4560).
- chunks = (
- session.query(DocumentChunk.id)
- .filter_by(collection_name=collection_name)
- .all()
- )
-
- if not chunks:
- return {"status": "success", "deleted_count": 0}
-
- chunk_ids = [
- f"{collection_name}_{chunk.id}" for chunk in chunks
- ]
-
- # Load FAISS index if not already loaded
- if self.faiss_index is None:
- # Extract collection_id from collection_name (format: "collection_<uuid>")
- collection_id = collection_name.removeprefix("collection_")
- self.faiss_index = self.load_or_create_faiss_index(
- collection_id, reset_stale_state=True
- )
-
- # Remove from FAISS index. delete + save + record must all
- # be inside the same lock — otherwise a concurrent writer
- # could sandwich a save_local between our delete and our
- # save, leaving stale chunks back on disk (#4197).
- if hasattr(self.faiss_index, "delete"):
- try:
- index_path = (
- Path(self.rag_index_record.index_path)
- if self.rag_index_record
- else None
- )
- if index_path:
- with _get_faiss_write_lock(
- self.username, str(index_path)
- ):
- self.faiss_index.delete(chunk_ids)
- self.faiss_index.save_local(
- str(index_path.parent),
- index_name=index_path.stem,
- )
- self.integrity_manager.record_file(
- index_path,
- related_entity_type="rag_index",
- related_entity_id=self.rag_index_record.id,
- )
- else:
- # No index path → in-memory-only delete
- self.faiss_index.delete(chunk_ids)
- except Exception:
- logger.warning("Could not delete chunks from FAISS")
-
- logger.info(
- f"Removed {len(chunk_ids)} chunks from collection {collection_name}"
- )
-
- return {"status": "success", "deleted_count": len(chunk_ids)}
-
- except Exception as e:
- logger.exception(
- f"Error removing collection {collection_name} from index"
- )
- return {
- "status": "error",
- "error": f"Operation failed: {type(e).__name__}",
- }
-
def remove_documents_from_index(
- self, document_ids: List[str], collection_id: str
+ self,
+ document_ids: List[str],
+ collection_id: str,
+ *,
+ chunk_ids_by_document: Optional[Dict[str, List[int]]] = None,
) -> int:
- """Delete given documents' vectors from a collection's FAISS index.
+ """Delete given documents' vectors from a collection's vector store.
- FAISS-only: the DB chunk rows are removed separately by the caller.
- This closes the gap where deleting a document's DB chunks left its
- vectors (and their persisted text) in the FAISS docstore, so the
+ Vector-store-only: the DB chunk rows are removed separately by the
+ caller. This closes the gap where deleting a document's DB chunks
+ left its vectors (and their persisted text — now impossible, see
+ vector_stores/base.py's SECURITY INVARIANT) in the store, so the
document kept surfacing in semantic search until a full reindex.
- Matching is by docstore metadata (``document_id`` for library docs,
- ``source_id`` for uploads). Returns the number of vectors removed.
- No-ops (returns 0) when the collection has no current FAISS index.
+ For each id, calls ``VectorIndex.delete(source_type="document",
+ source_id=...)`` — which looks up the matching ``DocumentChunk``
+ rows by (source_type, source_id, collection_name) — UNLESS
+ ``chunk_ids_by_document`` supplies that document's chunk ids
+ directly, in which case ``VectorIndex.delete_ids(ids)`` is used
+ instead. Callers whose own per-item transactions must delete the DB
+ rows eagerly (for their own atomicity/rollback semantics) BEFORE
+ this batched cleanup runs need the latter: the source_id lookup
+ would find nothing once the rows are already gone (see the Zotero
+ sync caller). Hardcodes ``source_type="document"``: both current
+ callers (Zotero sync cleanup, ``remove_document_from_rag``) only
+ ever pass library-document ids (the pre-cutover implementation
+ matched a mixed ``document_id``/``source_id`` metadata key
+ generically across "document" and "user_document" sources, but
+ nothing ever called it with anything but library documents).
+
+ Returns the total number of vectors removed across all ids. No-ops
+ (returns 0) when the collection has no current vector index — this
+ guard runs BEFORE building a ``VectorIndex`` so a delete call never
+ creates one (``_get_vector_index`` would otherwise create the
+ RAGIndex row via ``_get_or_create_rag_index``).
"""
from ...database.models.library import RAGIndex
from ...database.session_context import get_user_db_session
- wanted = {d for d in document_ids if d}
+ wanted = [d for d in document_ids if d]
if not wanted:
return 0
@@ -2177,57 +2301,77 @@ class LibraryRAGService:
return 0
try:
- if self.faiss_index is None:
- self.faiss_index = self.load_or_create_faiss_index(
- collection_id
- )
- docstore = getattr(self.faiss_index, "docstore", None)
- store = getattr(docstore, "_dict", None)
- if not store:
- return 0
-
- vector_ids = [
- vid
- for vid, doc in store.items()
- if (
- (getattr(doc, "metadata", None) or {}).get("document_id")
- in wanted
- or (getattr(doc, "metadata", None) or {}).get("source_id")
- in wanted
- )
- ]
- if not vector_ids or not hasattr(self.faiss_index, "delete"):
- return 0
+ # reset_stale_state=True is REQUIRED on this write path. If the
+ # pre-flight finds the index corrupt it quarantines the file
+ # (renames it aside); a fresh EMPTY store is then built and the
+ # delete loop below persists that empty store over the real path.
+ # Without resetting the per-document indexed state, the DB would
+ # still claim every other document is indexed while their vectors
+ # are gone — silently wiping the whole collection's search with no
+ # recovery but a manual full reindex. The reset only fires when the
+ # index was actually quarantined (guarded on the file no longer
+ # existing), so a healthy remove is unaffected. search() omits this
+ # flag safely because it never persists an empty store.
+ vindex = self._get_vector_index(
+ collection_id, collection_name, reset_stale_state=True
+ )
+ except (ValueError, RuntimeError):
+ logger.warning(
+ "Could not load vector index for "
+ f"{collection_name} while removing document vectors"
+ )
+ return 0
- index_path = (
- Path(self.rag_index_record.index_path)
- if self.rag_index_record
+ # Collect ALL removable chunk ids across every document, then remove
+ # them in ONE apply() (vindex.delete_ids). For an HNSW collection each
+ # apply() rebuilds the whole index, so a per-document loop is
+ # O(documents x collection_size); a single batched call rebuilds once.
+ # Captured ids are used directly; documents without captured ids have
+ # their chunk ids resolved by (source_type, source_id, collection_name)
+ # — those rows still exist at this point.
+ all_ids: List[int] = []
+ unresolved: List[str] = []
+ for document_id in wanted:
+ captured = (
+ chunk_ids_by_document.get(document_id)
+ if chunk_ids_by_document
else None
)
- # delete + save under the per-index lock (see #4197).
- if index_path:
- with _get_faiss_write_lock(self.username, str(index_path)):
- self.faiss_index.delete(vector_ids)
- self.faiss_index.save_local(
- str(index_path.parent),
- index_name=index_path.stem,
- )
- self.integrity_manager.record_file(
- index_path,
- related_entity_type="rag_index",
- related_entity_id=self.rag_index_record.id,
- )
+ if captured:
+ all_ids.extend(int(i) for i in captured if i is not None)
else:
- self.faiss_index.delete(vector_ids)
+ unresolved.append(document_id)
+
+ if unresolved:
+ in_chunk = 500 # keep below SQLITE_MAX_VARIABLE_NUMBER (999)
+ with get_user_db_session(
+ self.username, self.db_password
+ ) as session:
+ for i in range(0, len(unresolved), in_chunk):
+ batch = unresolved[i : i + in_chunk]
+ all_ids.extend(
+ row.id
+ for row in session.query(DocumentChunk.id).filter(
+ DocumentChunk.source_type == "document",
+ DocumentChunk.collection_name == collection_name,
+ DocumentChunk.source_id.in_(batch),
+ )
+ )
+
+ removed = 0
+ if all_ids:
+ try:
+ stats = vindex.delete_ids(sorted(set(all_ids)))
+ removed = stats.removed
+ except Exception:
+ logger.warning(
+ f"Could not remove {len(set(all_ids))} vectors for "
+ f"{len(wanted)} document(s) from {collection_name}"
+ )
+ if removed:
logger.info(
- f"Removed {len(vector_ids)} vectors for "
+ f"Removed {removed} vectors for "
f"{len(wanted)} document(s) from {collection_name}"
)
- return len(vector_ids)
- except Exception:
- logger.warning(
- "Could not remove document vectors from FAISS index for "
- f"{collection_name}"
- )
- return 0
+ return removed
diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.py
index 17f9066cba..0579be057b 100644
--- a/src/local_deep_research/research_library/services/library_service.py
+++ b/src/local_deep_research/research_library/services/library_service.py
@@ -1056,7 +1056,37 @@ class LibraryService:
CascadeHelper.delete_document_completely(session, document_id)
session.commit()
- return True
+ # Post-commit: purge the removed document's FAISS vectors + chunk rows
+ # (delete_document_completely leaves DocumentChunk rows, so without this
+ # the deleted content keeps surfacing in collection search). Best-effort;
+ # the DB delete already committed. Mirrors sync_library_with_filesystem.
+ try:
+ from ..deletion.services.document_deletion import (
+ DocumentDeletionService,
+ )
+ from ...database.models.library import DocumentChunk
+
+ with get_user_db_session(self.username) as purge_session:
+ coll_rows = (
+ purge_session.query(DocumentChunk.collection_name)
+ .filter_by(source_type="document", source_id=document_id)
+ .distinct()
+ .all()
+ )
+ collection_ids = [
+ row[0].removeprefix("collection_")
+ for row in coll_rows
+ if row[0]
+ ]
+ DocumentDeletionService(self.username)._purge_document_rag(
+ document_id, collection_ids, full_delete=True
+ )
+ except Exception:
+ logger.opt(exception=True).error(
+ "Failed to purge removed document {} (delete already committed)",
+ document_id,
+ )
+ return True
def open_file_location(self, document_id: str) -> bool:
"""Open the folder containing the document."""
@@ -1180,6 +1210,9 @@ class LibraryService:
"trackers_updated": 0,
"missing_files": [],
}
+ # Documents deleted below — their FAISS vectors + chunk rows are
+ # purged AFTER this transaction commits (see the post-commit block).
+ removed_doc_ids: List[str] = []
# Sync documents with filesystem
for doc in documents:
@@ -1223,6 +1256,7 @@ class LibraryService:
CascadeHelper.delete_document_completely(
session, doc.id
)
+ removed_doc_ids.append(doc.id)
stats["trackers_updated"] += 1
else:
# No tracker or path - delete the document entry
@@ -1230,13 +1264,55 @@ class LibraryService:
from ..deletion.utils.cascade_helper import CascadeHelper
CascadeHelper.delete_document_completely(session, doc.id)
+ removed_doc_ids.append(doc.id)
session.commit()
logger.info(
f"Library sync completed: {stats['files_found']} found, {stats['files_missing']} missing"
)
- return stats
+ # Post-commit: purge the removed documents' FAISS vectors + chunk rows.
+ # delete_document_completely leaves DocumentChunk rows (no FK), so
+ # without this the removed doc's vectors and chunk_text linger and keep
+ # surfacing in collection search. Reuse DocumentDeletionService's
+ # post-commit purge (per-collection vector removal + guaranteed chunk-row
+ # backstop), run after the session above has closed.
+ if removed_doc_ids:
+ from ..deletion.services.document_deletion import (
+ DocumentDeletionService,
+ )
+ from ...database.models.library import DocumentChunk
+
+ deleter = DocumentDeletionService(self.username)
+ for doc_id in removed_doc_ids:
+ # Best-effort per document: the sync's DB deletes already
+ # committed, so a purge hiccup here must not raise out of the
+ # sync (which would report the whole operation as failed) nor
+ # abort the remaining documents' purges.
+ try:
+ with get_user_db_session(self.username) as purge_session:
+ coll_rows = (
+ purge_session.query(DocumentChunk.collection_name)
+ .filter_by(source_type="document", source_id=doc_id)
+ .distinct()
+ .all()
+ )
+ collection_ids = [
+ row[0].removeprefix("collection_")
+ for row in coll_rows
+ if row[0]
+ ]
+ deleter._purge_document_rag(
+ doc_id, collection_ids, full_delete=True
+ )
+ except Exception:
+ logger.opt(exception=True).error(
+ "Failed to purge removed document {} after library sync "
+ "(delete already committed)",
+ doc_id,
+ )
+
+ return stats
def mark_for_redownload(self, document_ids: List[str]) -> int:
"""
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
index 494dd3ba52..8fc7ddf27c 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -48,6 +48,7 @@ from ...database.models.library import (
Collection,
Document,
DocumentBlob,
+ DocumentChunk,
DocumentCollection,
DocumentStatus,
)
@@ -59,6 +60,7 @@ from ...security import (
UnsafeFilenameError,
)
from ...settings.manager import SettingsManager
+from ...utilities.type_utils import to_bool
from ..deletion.utils.cascade_helper import CascadeHelper
from ..services.pdf_storage_manager import (
DEFAULT_MAX_PDF_SIZE_MB,
@@ -485,6 +487,15 @@ class ZoteroSyncService:
# their vectors must also leave the default Library collection's index
# (a kept/foreign doc's default-collection vectors stay valid).
hard_deleted_doc_ids: List[str] = []
+ # (document_id, collection_id) -> FAISS int chunk ids, captured by
+ # _release_document / _purge_collection_chunks just BEFORE they
+ # eagerly delete the matching DocumentChunk rows (each in its own
+ # per-item transaction, for that transaction's atomicity — a cascade
+ # failure must roll the rows back too). The finally-block vector
+ # purge below runs AFTER those rows are gone, so it needs these
+ # captured ids to find the FAISS vectors instead of the row lookup
+ # VectorIndex.delete would otherwise do. See _cleanup_removed_vectors.
+ pending_chunk_ids: Dict[Tuple[str, str], List[int]] = {}
ldr_collection_id: Optional[str] = None
default_collection_id: Optional[str] = None
try:
@@ -553,6 +564,7 @@ class ZoteroSyncService:
mapped[key],
source_type_id,
default_collection_id,
+ pending_chunk_ids,
)
session.commit()
except Exception:
@@ -670,6 +682,7 @@ class ZoteroSyncService:
source_type_id,
pdf_storage,
default_collection_id,
+ pending_chunk_ids,
)
except ZoteroTransientError:
# A rate-limit / 5xx (from a PDF/full-text fetch inside
@@ -713,6 +726,7 @@ class ZoteroSyncService:
prior_row.id,
source_type_id,
default_collection_id,
+ pending_chunk_ids,
)
session.commit()
except Exception:
@@ -802,15 +816,21 @@ class ZoteroSyncService:
if ldr_collection_id and self.password:
if reindexed_doc_ids:
self._cleanup_removed_vectors(
- reindexed_doc_ids, ldr_collection_id
+ reindexed_doc_ids,
+ ldr_collection_id,
+ pending_chunk_ids=pending_chunk_ids,
)
if released_doc_ids:
self._cleanup_removed_vectors(
- released_doc_ids, ldr_collection_id
+ released_doc_ids,
+ ldr_collection_id,
+ pending_chunk_ids=pending_chunk_ids,
)
if removed_doc_ids:
self._cleanup_removed_vectors(
- removed_doc_ids, ldr_collection_id
+ removed_doc_ids,
+ ldr_collection_id,
+ pending_chunk_ids=pending_chunk_ids,
)
# The default Library collection carries every synced doc too
# (ambient membership), so its index needs the same care:
@@ -824,11 +844,15 @@ class ZoteroSyncService:
):
if reindexed_doc_ids:
self._cleanup_removed_vectors(
- reindexed_doc_ids, default_collection_id
+ reindexed_doc_ids,
+ default_collection_id,
+ pending_chunk_ids=pending_chunk_ids,
)
if hard_deleted_doc_ids:
self._cleanup_removed_vectors(
- hard_deleted_doc_ids, default_collection_id
+ hard_deleted_doc_ids,
+ default_collection_id,
+ pending_chunk_ids=pending_chunk_ids,
)
# Auto-index outside the sync transaction (best-effort, async).
@@ -865,12 +889,26 @@ class ZoteroSyncService:
return stats
def _cleanup_removed_vectors(
- self, document_ids: List[str], ldr_collection_id: str
+ self,
+ document_ids: List[str],
+ ldr_collection_id: str,
+ pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
) -> None:
"""Remove the given documents' vectors from the collection's FAISS
index. No-op if the collection was never RAG-indexed. Best-effort —
never raises (it runs inside a ``finally`` where a propagating exception
- would mask the real sync error), so the imports live inside the try."""
+ would mask the real sync error), so the imports live inside the try.
+
+ The DocumentChunk rows for these documents are ALREADY GONE by the
+ time this runs (the per-item transactions that released/removed/
+ reindexed them deleted them eagerly, for their own atomicity — see
+ ``_release_document`` / ``_purge_collection_chunks``), so the usual
+ source_id lookup in ``VectorIndex.delete`` would find nothing.
+ ``pending_chunk_ids`` (keyed by ``(document_id, ldr_collection_id)``)
+ carries the ids those per-item transactions captured BEFORE deleting
+ the rows, so ``remove_documents_from_index`` can purge the exact
+ FAISS vectors via ``VectorIndex.delete_ids`` instead.
+ """
try:
from ...database.models.library import RAGIndex
from ..services.library_rag_service import LibraryRAGService
@@ -892,6 +930,30 @@ class ZoteroSyncService:
)
chunk_size = rag_index.chunk_size
chunk_overlap = rag_index.chunk_overlap
+ # This is a DELETE path, so the stored index_type MUST be
+ # threaded through: LibraryRAGService defaults index_type="flat",
+ # and removing from a real HNSW collection under the wrong type
+ # would take the in-place remove_ids path (unsupported for HNSW)
+ # and silently fail instead of the rebuild path. distance_metric
+ # / normalize_vectors are threaded too for parity with the
+ # search engines. NULL (legacy rows) → the service defaults.
+ index_type = rag_index.index_type or "flat"
+ distance_metric = rag_index.distance_metric or "cosine"
+ normalize_vectors = to_bool(
+ rag_index.normalize_vectors, default=True
+ )
+
+ chunk_ids_by_document = None
+ if pending_chunk_ids:
+ chunk_ids_by_document = {
+ doc_id: ids
+ for doc_id in document_ids
+ if (
+ ids := pending_chunk_ids.get(
+ (doc_id, ldr_collection_id)
+ )
+ )
+ }
with LibraryRAGService(
username=self.username,
@@ -899,10 +961,15 @@ class ZoteroSyncService:
embedding_provider=embedding_provider,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
+ index_type=index_type,
+ distance_metric=distance_metric,
+ normalize_vectors=normalize_vectors,
db_password=self.password,
) as rag_service:
removed = rag_service.remove_documents_from_index(
- document_ids, ldr_collection_id
+ document_ids,
+ ldr_collection_id,
+ chunk_ids_by_document=chunk_ids_by_document,
)
logger.info(
f"Zotero: cleared {removed} FAISS vectors for "
@@ -1034,9 +1101,13 @@ class ZoteroSyncService:
source_type_id: str,
pdf_storage: PDFStorageManager,
default_collection_id: Optional[str] = None,
+ pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
) -> Tuple[Optional[str], str, bool]:
"""Create or update the LDR document for a Zotero item.
+ ``pending_chunk_ids`` is forwarded to ``_purge_collection_chunks`` —
+ see the note on ``_release_document``.
+
Returns ``(document_id, action, reindexed_in_place)`` where action is
``"imported"`` | ``"updated"`` | ``"skipped"``. ``reindexed_in_place``
is True only when an existing document's content changed and its stale
@@ -1167,6 +1238,7 @@ class ZoteroSyncService:
existing.id,
ldr_collection_id,
default_collection_id,
+ pending_chunk_ids,
)
return existing.id, "updated", True
# Content is byte-identical (matched by hash), so the existing
@@ -1284,7 +1356,11 @@ class ZoteroSyncService:
# the matching FAISS vectors before that re-index runs.
if not created:
self._purge_collection_chunks(
- session, doc.id, ldr_collection_id, default_collection_id
+ session,
+ doc.id,
+ ldr_collection_id,
+ default_collection_id,
+ pending_chunk_ids,
)
return doc.id, ("imported" if created else "updated"), (not created)
@@ -1342,6 +1418,7 @@ class ZoteroSyncService:
doc_id: str,
coll_id: str,
default_collection_id: Optional[str] = None,
+ pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
) -> None:
"""Purge a doc's RAG chunks and clear the link's indexed flag, forcing
a re-index after an in-place text change — for this collection AND
@@ -1351,11 +1428,22 @@ class ZoteroSyncService:
Raises on failure so the whole per-item transaction rolls back (the
item retries next sync) — swallowing here would let the caller purge
FAISS vectors for chunks that still exist.
+
+ ``pending_chunk_ids`` — see the note on ``_release_document``: when
+ supplied, each collection's chunk ids are captured into it BEFORE
+ being eagerly deleted below, so the later batched
+ ``_cleanup_removed_vectors`` pass can purge those exact FAISS ids
+ via ``VectorIndex.delete_ids`` instead of a now-futile source_id
+ lookup. ``None`` (what direct unit tests pass) skips capture.
"""
targets = [coll_id]
if default_collection_id and default_collection_id != coll_id:
targets.append(default_collection_id)
for cid in targets:
+ if pending_chunk_ids is not None:
+ ZoteroSyncService._capture_chunk_ids(
+ pending_chunk_ids, session, doc_id, cid
+ )
CascadeHelper.delete_document_chunks(
session, doc_id, collection_name=f"collection_{cid}"
)
@@ -1647,6 +1735,7 @@ class ZoteroSyncService:
row: ZoteroItemMap,
source_type_id: str,
default_collection_id: Optional[str] = None,
+ pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
) -> Optional[str]:
"""Remove an item that no longer exists in Zotero.
@@ -1658,6 +1747,8 @@ class ZoteroSyncService:
mapping row, never destroy a shared or foreign-owned document (and its
blob/chunks) out from under the other references / the user.
+ ``pending_chunk_ids`` — see :meth:`_release_document`.
+
Returns the RELEASED document_id (so the caller can clear its FAISS
vectors for this collection after the transaction), or None when the
document is kept — either it has no document, or a byte-identical twin
@@ -1671,6 +1762,7 @@ class ZoteroSyncService:
row.id,
source_type_id,
default_collection_id,
+ pending_chunk_ids,
)
session.delete(row)
return released
@@ -1683,6 +1775,7 @@ class ZoteroSyncService:
keep_mapping_id,
source_type_id: str,
default_collection_id: Optional[str] = None,
+ pending_chunk_ids: Optional[Dict[Tuple[str, str], List[int]]] = None,
) -> Optional[str]:
"""Release a document from this collection: drop its collection link and
RAG chunks, hard-deleting the document only when nothing else references
@@ -1696,6 +1789,20 @@ class ZoteroSyncService:
onto a *different* existing document, orphaning the item's prior doc.
Returns ``doc_id`` so the caller can clear its FAISS vectors after the
transaction.
+
+ The chunk rows this method deletes below are the SAME rows a later,
+ BATCHED ``_cleanup_removed_vectors`` call needs to find (by
+ source_id + collection_name) to know which FAISS vectors to remove
+ — but by the time that batched call runs, deleting the rows here
+ (eagerly, so a cascade failure rolls back this whole transaction —
+ see the comment above the ``if referenced_elsewhere`` branch below)
+ has already made them unfindable. When the caller supplies
+ ``pending_chunk_ids`` (keyed by ``(doc_id, collection_id)``), this
+ captures each affected collection's chunk ids into it BEFORE
+ deleting the rows, so the caller can purge those exact FAISS ids
+ later via ``VectorIndex.delete_ids`` instead of the now-futile
+ source_id lookup. ``None`` (the default, and what direct unit tests
+ pass) skips capture and behaves exactly as before.
"""
if not doc_id:
return None
@@ -1755,6 +1862,13 @@ class ZoteroSyncService:
# collection's link AND its RAG chunks so it stops surfacing here.
# The caller clears this collection's FAISS vectors for the returned
# doc_id after the transaction.
+ if pending_chunk_ids is not None:
+ self._capture_chunk_ids(
+ pending_chunk_ids,
+ session,
+ doc_id,
+ coll_id,
+ )
CascadeHelper.delete_document_chunks(
session, doc_id, collection_name=f"collection_{coll_id}"
)
@@ -1765,11 +1879,55 @@ class ZoteroSyncService:
doc = session.query(Document).filter_by(id=doc_id).first()
if doc:
# DocumentChunk has no FK cascade — delete RAG chunks
- # explicitly before removing the document.
+ # explicitly before removing the document. Capture ids for
+ # BOTH collections this doc can possibly be in — established
+ # above (doc_owned_by_zotero and not referenced_elsewhere)
+ # to be at most coll_id and default_collection_id.
+ if pending_chunk_ids is not None:
+ self._capture_chunk_ids(
+ pending_chunk_ids, session, doc_id, coll_id
+ )
+ if (
+ default_collection_id
+ and default_collection_id != coll_id
+ ):
+ self._capture_chunk_ids(
+ pending_chunk_ids,
+ session,
+ doc_id,
+ default_collection_id,
+ )
CascadeHelper.delete_document_chunks(session, doc.id)
CascadeHelper.delete_document_completely(session, doc.id)
return doc_id
+ @staticmethod
+ def _capture_chunk_ids(
+ pending_chunk_ids: Dict[Tuple[str, str], List[int]],
+ session,
+ doc_id: str,
+ collection_id: str,
+ ) -> None:
+ """Snapshot ``doc_id``'s chunk-row int ids for ``collection_id`` into
+ ``pending_chunk_ids`` BEFORE they are eagerly deleted by the caller.
+
+ A plain SELECT (no locking/mutation) — safe to run just ahead of the
+ row-deleting statement in the same transaction. See the note on
+ ``pending_chunk_ids`` in :meth:`_release_document`.
+ """
+ ids = [
+ row.id
+ for row in session.query(DocumentChunk.id).filter_by(
+ source_type="document",
+ source_id=doc_id,
+ collection_name=f"collection_{collection_id}",
+ )
+ ]
+ if ids:
+ pending_chunk_ids.setdefault((doc_id, collection_id), []).extend(
+ ids
+ )
+
@staticmethod
def _document_exists(session, document_id: Optional[str]) -> bool:
if not document_id:
diff --git a/src/local_deep_research/security/file_integrity/integrity_manager.py b/src/local_deep_research/security/file_integrity/integrity_manager.py
index da721f8c1c..e681249661 100644
--- a/src/local_deep_research/security/file_integrity/integrity_manager.py
+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py
@@ -4,6 +4,7 @@ File Integrity Manager - Main service for file integrity verification.
Provides smart verification with embedded statistics and sparse failure logging.
"""
+from contextlib import contextmanager
from datetime import datetime, UTC
from pathlib import Path
from typing import Optional, Tuple, List
@@ -80,6 +81,58 @@ class FileIntegrityManager:
except Exception:
logger.warning("[FILE_INTEGRITY] Startup cleanup failed")
+ @contextmanager
+ def _integrity_write(self, session, nested: bool):
+ """Wrap an integrity write so it settles correctly for the caller.
+
+ ``nested=False`` (default, standalone callers): commit the
+ (thread-local) session — immediate durability.
+
+ ``nested=True``: run the write inside a SAVEPOINT and DON'T commit, so
+ the caller's outer transaction commits it. REQUIRED when record_file /
+ verify_file run reentrantly INSIDE another open transaction — the vector
+ store calls them during apply(), which has just-flushed, uncommitted
+ DocumentChunk rows on the SAME thread-local session. A plain commit
+ would settle those rows early, and a transient-failure rollback would
+ DISCARD them; a SAVEPOINT scopes any failure to just the integrity
+ write, leaving the caller's rows intact, and both commit together.
+ Same connection, so no second-writer SQLite contention.
+ """
+ if nested:
+ with session.begin_nested():
+ yield
+ else:
+ yield
+ session.commit()
+
+ @contextmanager
+ def _session_for(self, nested: bool):
+ """Yield the session for an integrity op.
+
+ Standalone (nested=False): a normal ``get_user_db_session``.
+
+ Reentrant (nested=True): the caller's LIVE thread-local session,
+ obtained via ``get_current_thread_session`` — NOT ``get_user_db_session``.
+ Re-entering ``get_user_db_session`` in a NON-request (background/
+ scheduler) context routes through ``ThreadSessionManager.get_session``,
+ which on re-acquisition runs a validation ``SELECT 1`` and then
+ ``session.rollback()`` to release the DEFERRED lock — that rollback
+ would discard the CALLER's just-flushed, uncommitted DocumentChunk rows
+ before our SAVEPOINT ever runs (silent data loss: vectors persisted,
+ text rows gone). The live-session accessor has no such side effect.
+ """
+ if nested:
+ from ...database.thread_local_session import (
+ get_current_thread_session,
+ )
+
+ existing = get_current_thread_session()
+ if existing is not None:
+ yield existing
+ return
+ with get_user_db_session(self.username, self.password) as session:
+ yield session
+
def _normalize_path(self, file_path: Path) -> str:
"""
Normalize path for consistent storage and lookup.
@@ -112,6 +165,8 @@ class FileIntegrityManager:
file_path: Path,
related_entity_type: Optional[str] = None,
related_entity_id: Optional[int] = None,
+ *,
+ nested: bool = False,
) -> FileIntegrityRecord:
"""
Create or update integrity record for a file.
@@ -140,7 +195,8 @@ class FileIntegrityManager:
file_stat = file_path.stat()
normalized_path = self._normalize_path(file_path)
- with get_user_db_session(self.username, self.password) as session:
+ nested_error: Optional[Exception] = None
+ with self._session_for(nested) as session:
# Check if record exists (using normalized path)
record = (
session.query(FileIntegrityRecord)
@@ -148,42 +204,60 @@ class FileIntegrityManager:
.first()
)
- if record:
- # Update existing record
- record.checksum = checksum
- record.file_size = file_stat.st_size
- record.file_mtime = file_stat.st_mtime
- record.algorithm = verifier.get_algorithm()
- record.updated_at = datetime.now(UTC)
- logger.info(f"[FILE_INTEGRITY] Updated record for: {file_path}")
- else:
- # Create new record
- record = FileIntegrityRecord(
- file_path=normalized_path,
- file_type=verifier.get_file_type(),
- checksum=checksum,
- algorithm=verifier.get_algorithm(),
- file_size=file_stat.st_size,
- file_mtime=file_stat.st_mtime,
- verify_on_load=True,
- allow_modifications=verifier.allows_modifications(),
- related_entity_type=related_entity_type,
- related_entity_id=related_entity_id,
- total_verifications=0,
- consecutive_successes=0,
- consecutive_failures=0,
- )
- session.add(record)
- logger.info(
- f"[FILE_INTEGRITY] Created record for: {file_path} (type: {verifier.get_file_type()})"
- )
-
- session.commit()
- session.refresh(record)
- return record
+ try:
+ with self._integrity_write(session, nested):
+ if record:
+ # Update existing record
+ record.checksum = checksum
+ record.file_size = file_stat.st_size
+ record.file_mtime = file_stat.st_mtime
+ record.algorithm = verifier.get_algorithm()
+ record.updated_at = datetime.now(UTC)
+ logger.info(
+ f"[FILE_INTEGRITY] Updated record for: {file_path}"
+ )
+ else:
+ # Create new record
+ record = FileIntegrityRecord(
+ file_path=normalized_path,
+ file_type=verifier.get_file_type(),
+ checksum=checksum,
+ algorithm=verifier.get_algorithm(),
+ file_size=file_stat.st_size,
+ file_mtime=file_stat.st_mtime,
+ verify_on_load=True,
+ allow_modifications=verifier.allows_modifications(),
+ related_entity_type=related_entity_type,
+ related_entity_id=related_entity_id,
+ total_verifications=0,
+ consecutive_successes=0,
+ consecutive_failures=0,
+ )
+ session.add(record)
+ logger.info(
+ f"[FILE_INTEGRITY] Created record for: {file_path} (type: {verifier.get_file_type()})"
+ )
+ except Exception as exc:
+ if not nested:
+ # Standalone: let get_user_db_session roll back the failed
+ # write (original behavior — nothing else is pending).
+ raise
+ # Nested: the SAVEPOINT already rolled back JUST this write; the
+ # caller's flushed rows are intact. We must NOT let the exception
+ # escape this block, or get_user_db_session's except would do a
+ # FULL session.rollback() and discard them. Exit cleanly, then
+ # re-raise below so apply()'s retry/failure logic still sees it.
+ nested_error = exc
+
+ if nested_error is None:
+ session.refresh(record)
+
+ if nested_error is not None:
+ raise nested_error
+ return record
def verify_file(
- self, file_path: Path, force: bool = False
+ self, file_path: Path, force: bool = False, *, nested: bool = False
) -> Tuple[bool, Optional[str]]:
"""
Verify file integrity with smart checking.
@@ -201,7 +275,7 @@ class FileIntegrityManager:
"""
normalized_path = self._normalize_path(file_path)
- with get_user_db_session(self.username, self.password) as session:
+ with self._session_for(nested) as session:
record = (
session.query(FileIntegrityRecord)
.filter_by(file_path=normalized_path)
@@ -221,20 +295,36 @@ class FileIntegrityManager:
)
return True, None
- # Perform verification
+ # Perform verification (the RESULT below is computed here and is
+ # independent of the stats bookkeeping write that follows).
passed, reason = self._do_verification(record, file_path, session)
- # Update statistics
- self._update_stats(record, passed, session)
-
- # Log failure if needed
- if not passed:
- self._log_failure(
- record, file_path, reason or "Unknown failure", session
+ try:
+ with self._integrity_write(session, nested):
+ # Update statistics
+ self._update_stats(record, passed, session)
+
+ # Log failure if needed
+ if not passed:
+ self._log_failure(
+ record,
+ file_path,
+ reason or "Unknown failure",
+ session,
+ )
+ except Exception:
+ if not nested:
+ raise
+ # Nested: the SAVEPOINT rolled back only this stats write; the
+ # caller's flushed rows are intact. Do NOT let the exception
+ # escape (get_user_db_session would FULL-rollback the caller's
+ # session). Stats bookkeeping is best-effort — the verification
+ # result is already decided, so log and return it.
+ logger.warning(
+ "[FILE_INTEGRITY] Could not persist verification stats for "
+ f"{file_path} (verification result unaffected)"
)
- session.commit()
-
if passed:
logger.info(
f"[FILE_INTEGRITY] Verification passed: {file_path}"
diff --git a/src/local_deep_research/vector_stores/__init__.py b/src/local_deep_research/vector_stores/__init__.py
new file mode 100644
index 0000000000..3abe8d6188
--- /dev/null
+++ b/src/local_deep_research/vector_stores/__init__.py
@@ -0,0 +1,20 @@
+"""Vector-store abstraction.
+
+A small provider interface (:class:`BaseVectorStore`) plus a registry, mirroring
+the embeddings/LLM provider pattern, so vector backends can be added later
+behind a setting. Only FAISS is implemented today.
+"""
+
+from .base import BaseVectorStore
+from .config import (
+ VALID_VECTOR_STORE_PROVIDERS,
+ get_vector_store_class,
+ resolve_provider,
+)
+
+__all__ = [
+ "BaseVectorStore",
+ "VALID_VECTOR_STORE_PROVIDERS",
+ "get_vector_store_class",
+ "resolve_provider",
+]
diff --git a/src/local_deep_research/vector_stores/base.py b/src/local_deep_research/vector_stores/base.py
new file mode 100644
index 0000000000..10dcece3e7
--- /dev/null
+++ b/src/local_deep_research/vector_stores/base.py
@@ -0,0 +1,204 @@
+"""Abstract base class for vector stores.
+
+Mirrors the embeddings/LLM provider pattern (``BaseEmbeddingProvider``,
+``BaseLLM`` + factory): a small typed interface plus a registry so a future
+release can add backends (Qdrant, pgvector, Milvus, ...) selectable by a
+setting. **Only FAISS is implemented today** — there is intentionally no
+settings selector wired yet.
+
+Scope / honest boundary
+-----------------------
+This abstraction covers the *vector-storage operations* — create / add /
+search / delete / reconstruct / persist / count. It deliberately does **not**
+cover the per-user file paths, on-disk integrity checksums, or the per-index
+write-lock + reload/merge concurrency 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, verified query surface), not *free* — a real server backend
+still requires refactoring the file/lock/integrity layer in the service.
+
+Identity model
+--------------
+Vectors are keyed by an application-supplied **int64 id**. In this codebase
+that id is ``DocumentChunk.id`` (the encrypted-DB primary key); the store holds
+only vectors + ids, and all text/metadata is rehydrated from the DB by id.
+
+============================================================================
+SECURITY INVARIANT — NEVER pass document text to a vector store
+============================================================================
+Every method here accepts ONLY an integer id and its embedding vector.
+Callers MUST NOT pass document/chunk text (or any other user content) into a
+vector-store method, and implementations MUST NOT persist such text.
+
+The per-user database is encrypted; a vector index is not (it is a local file
+for FAISS, or an external service for a future backend). Keeping user content
+out of the vector store keeps the encrypted database the sole home of that
+content. Because the interface has no text parameter, the protection is
+STRUCTURAL rather than a matter of discipline — no backend (FAISS today, or a
+swapped-in Qdrant/pgvector tomorrow) can receive or store the text. The
+authoritative text lives solely in the encrypted DB
+(``DocumentChunk.chunk_text``), keyed by the same int id; retrieval rehydrates
+snippets from there by id (see ``LibraryRAGService`` / the search engines).
+============================================================================
+"""
+
+from abc import ABC, abstractmethod
+from pathlib import Path
+from typing import List, Optional, Sequence, Tuple
+
+import numpy as np
+
+
+class BaseVectorStore(ABC):
+ """Abstract interface for a per-collection vector index.
+
+ An instance wraps a single collection's index (stateful, in-memory, backed
+ by a persisted file for local-file stores). Construct via :meth:`create`
+ (new, empty) or :meth:`load` (from disk).
+ """
+
+ # Override in subclasses.
+ provider_key: str = "base" # unique id; matches the (future) setting value
+ provider_name: str = "Base" # display name for logs/UI
+ # True when the store persists to a local file this process owns end to end
+ # — i.e. the service's file write-lock + integrity checksum + reload/merge
+ # model applies. A server-backed store sets this False.
+ is_local_file: bool = True
+ # True when the store can invert id -> vector (needed for the in-place
+ # format migration, which re-keys vectors without re-embedding).
+ supports_reconstruct: bool = True
+ # Embedding dimension this instance was constructed/loaded for. Concrete
+ # subclasses set this in __init__/create()/load(); declared here (no
+ # default — there is no sensible universal value) so callers like the
+ # facade can read it via the abstract interface.
+ dimension: int
+
+ # ------------------------------------------------------------------ #
+ # Construction
+ # ------------------------------------------------------------------ #
+ @classmethod
+ @abstractmethod
+ def create(
+ cls,
+ *,
+ dimension: int,
+ index_type: str,
+ metric: str,
+ normalize: bool,
+ **kwargs,
+ ) -> "BaseVectorStore":
+ """Create a new, empty store for vectors of ``dimension``.
+
+ Args:
+ dimension: Embedding dimension.
+ index_type: Backend index family (e.g. ``"flat"``, ``"hnsw"``).
+ metric: Distance metric (``"l2"``, ``"cosine"``, ``"dot_product"``).
+ normalize: Whether query/doc vectors are L2-normalized before use
+ (cosine similarity via inner product on normalized vectors).
+ """
+
+ @classmethod
+ @abstractmethod
+ def load(
+ cls,
+ path: Path,
+ *,
+ dimension: int,
+ index_type: str,
+ metric: str,
+ normalize: bool,
+ **kwargs,
+ ) -> "BaseVectorStore":
+ """Load a persisted store from ``path`` (local-file stores only).
+
+ ``dimension`` / ``index_type`` / ``metric`` / ``normalize`` describe how
+ the index was built (some backends persist this, some do not); callers
+ pass the values from settings so search-time normalization matches
+ build-time normalization.
+ """
+
+ # ------------------------------------------------------------------ #
+ # Vector operations
+ # ------------------------------------------------------------------ #
+ @abstractmethod
+ def add(self, ids: List[int], vectors: np.ndarray) -> None:
+ """Add vectors under the given int64 ids (aligned 1:1, same length).
+
+ ids + vectors ONLY — never text (see the module-level "SECURITY
+ INVARIANT" block). The text stays in the encrypted DB.
+ """
+
+ @abstractmethod
+ def search(
+ self, query_vector: np.ndarray, k: int
+ ) -> List[Tuple[int, float]]:
+ """Return up to ``k`` ``(id, distance)`` pairs, nearest first.
+
+ ``distance`` is the backend's raw score (L2 distance or inner product);
+ callers map it to a relevance score. Absent/empty slots are filtered.
+ """
+
+ @abstractmethod
+ def delete(self, ids: List[int]) -> int:
+ """Remove the given ids. Returns the number actually removed.
+
+ May raise for index families that do not support removal (e.g. FAISS
+ HNSW) — callers handle that the same way they did pre-abstraction.
+ """
+
+ @abstractmethod
+ def live_ids(self) -> List[int]:
+ """Return every id currently stored (the authoritative membership)."""
+
+ @abstractmethod
+ def count(self) -> int:
+ """Return the number of vectors currently stored."""
+
+ @abstractmethod
+ def apply(
+ self,
+ *,
+ add_ids: List[int],
+ add_vectors: Optional[np.ndarray],
+ remove_ids: Sequence[int] = (),
+ dedup: bool = True,
+ ) -> dict:
+ """Durably apply a batch of removals + additions as one atomic unit.
+
+ This is the single write primitive. The caller computes *which* ids to
+ remove and add (from its own authoritative source — for LDR, the
+ encrypted DB); the store applies them and persists so that a concurrent
+ writer to the same logical index cannot lose either party's changes.
+ *How* that atomicity/isolation is achieved is backend-specific (a
+ local-file backend takes a per-index lock and reload-merges; a
+ server-backed store issues upserts/deletes) and is not part of this
+ contract.
+
+ Contract: removals are applied before additions, and ``dedup`` skips
+ additions whose id is already present after removal — so a "replace" is
+ expressed as ``remove_ids`` + ``add_ids`` of the same id. On failure the
+ store must not be left durably half-applied.
+
+ Returns a stats dict (e.g. ``{"added": n, "removed": m}``). ids +
+ vectors ONLY — never text (see the module "SECURITY INVARIANT").
+ """
+
+ # ------------------------------------------------------------------ #
+ # Optional (local-file / reconstructable stores)
+ # ------------------------------------------------------------------ #
+ def reconstruct(self, id: int) -> Optional[np.ndarray]:
+ """Return the stored vector for ``id`` (migration helper).
+
+ Only meaningful when :attr:`supports_reconstruct` is True.
+ """
+ raise NotImplementedError(
+ f"{type(self).__name__} does not support reconstruct()"
+ )
+
+ def persist(self, path: Path) -> None:
+ """Durably write the store to ``path`` (local-file stores only)."""
+ raise NotImplementedError(
+ f"{type(self).__name__} does not support persist()"
+ )
diff --git a/src/local_deep_research/vector_stores/config.py b/src/local_deep_research/vector_stores/config.py
new file mode 100644
index 0000000000..8921e9c983
--- /dev/null
+++ b/src/local_deep_research/vector_stores/config.py
@@ -0,0 +1,62 @@
+"""Vector-store provider registry and factory.
+
+Mirrors ``embeddings/embeddings_config.py``: a flat list of valid providers, a
+lazily-populated class registry, and a single resolution entry point. Only
+FAISS is registered today, and there is no settings key selecting a provider
+yet — ``resolve_provider`` always returns ``"faiss"``. The seam exists so a
+future backend is a bounded addition (register the class, add a setting) rather
+than a rewrite of the call sites.
+"""
+
+from typing import Dict, Optional, Type
+
+from .base import BaseVectorStore
+
+VALID_VECTOR_STORE_PROVIDERS = ["faiss"]
+
+_DEFAULT_PROVIDER = "faiss"
+
+# Lazily-populated {provider_key: class}. Populated on first use to avoid
+# importing faiss at module import time.
+_PROVIDER_CLASSES: Dict[str, Type[BaseVectorStore]] = {}
+
+
+def _load_provider_classes() -> Dict[str, Type[BaseVectorStore]]:
+ if not _PROVIDER_CLASSES:
+ from .implementations.faiss_store import FaissVectorStore
+
+ _PROVIDER_CLASSES[FaissVectorStore.provider_key] = FaissVectorStore
+ return _PROVIDER_CLASSES
+
+
+def resolve_provider(settings_snapshot: Optional[dict] = None) -> str:
+ """Return the configured vector-store provider key.
+
+ No settings key selects this yet — always ``"faiss"``. The
+ ``settings_snapshot`` parameter is accepted now so callers don't change when
+ a setting is introduced later.
+ """
+ return _DEFAULT_PROVIDER
+
+
+def get_vector_store_class(
+ provider: Optional[str] = None,
+ settings_snapshot: Optional[dict] = None,
+) -> Type[BaseVectorStore]:
+ """Return the :class:`BaseVectorStore` subclass for ``provider``.
+
+ Callers construct instances via the class's ``.create(...)`` / ``.load(...)``
+ classmethods (a vector store is stateful, unlike the stateless embeddings
+ 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()
+ classes = _load_provider_classes()
+ if key not in classes:
+ raise ValueError(
+ f"Unknown vector-store provider '{key}'. "
+ f"Valid providers: {sorted(classes)}"
+ )
+ return classes[key]
diff --git a/src/local_deep_research/vector_stores/facade.py b/src/local_deep_research/vector_stores/facade.py
new file mode 100644
index 0000000000..c4a27b7404
--- /dev/null
+++ b/src/local_deep_research/vector_stores/facade.py
@@ -0,0 +1,524 @@
+"""High-level semantic-index facade: ``index`` / ``search`` / ``delete``.
+
+This is the single simple entry point to the vector subsystem. It is the ONE
+place in the ``vector_stores`` package that bridges three things:
+
+ * the embedding model (a LangChain ``Embeddings``),
+ * the encrypted DB (``DocumentChunk`` — the authoritative home of chunk text
+ and metadata), and
+ * a swappable :class:`BaseVectorStore` (ids + vectors only).
+
+``base.py`` and ``implementations/`` stay DB-agnostic; only this module imports
+``DocumentChunk``. The vector store holds an int64 id per chunk
+(``DocumentChunk.id``); text/metadata are rehydrated from the DB by that id on
+search — the store never receives text (see the "SECURITY INVARIANT" in
+:mod:`.base`).
+
+One row = one vector. Identical text in two documents produces two rows/vectors
+(no cross-document sharing); this keeps provenance correct and deletes trivial.
+Exact-duplicate *files* are an ingestion-time concern, handled upstream.
+"""
+
+import hashlib
+import threading
+import uuid
+from contextlib import contextmanager
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import (
+ Callable,
+ Iterator,
+ List,
+ Optional,
+ Sequence,
+ Tuple,
+ TypedDict,
+ cast,
+)
+
+import numpy as np
+from langchain_core.embeddings import Embeddings
+from loguru import logger
+from sqlalchemy.orm import Session
+
+from ..database.models.library import DocumentChunk
+from ..database.session_context import get_user_db_session
+from .config import get_vector_store_class
+
+
+class _BindKwargs(TypedDict):
+ """Keyword arguments forwarded to ``store_cls.create()``/``.load()``.
+
+ A plain ``dict`` would infer a uniform (``object``) value type, erasing
+ each field's real type when unpacked via ``**bind`` — a ``TypedDict``
+ keeps each key's type through the ``**`` unpacking so mypy can check the
+ call against ``BaseVectorStore.create``/``.load``.
+ """
+
+ dimension: int
+ index_type: str
+ metric: str
+ normalize: bool
+ path: Path
+ lock: threading.Lock
+ integrity_record: Callable[[Path], None]
+ integrity_verify: Callable[[Path], Tuple[bool, Optional[str]]]
+
+
+@dataclass
+class ChunkInput:
+ """One chunk to index: its text plus optional positional/title metadata.
+
+ Kept backend- and framework-neutral (not a LangChain ``Document``) so the
+ facade never couples to a specific splitter/vector library.
+ """
+
+ text: str
+ metadata: dict = field(default_factory=dict)
+
+
+@dataclass
+class SearchResult:
+ """A search hit, rehydrated from the encrypted DB by chunk id."""
+
+ chunk_id: int
+ text: str
+ # Raw backend score; the relevance formula is the caller's choice. ``metric``
+ # says how to read it: for cosine/dot_product (inner product) HIGHER is more
+ # similar; for l2 LOWER is closer. Branch on it or scores invert.
+ distance: float
+ metric: str
+ metadata: dict
+ document_title: Optional[str]
+ source_id: Optional[str]
+ source_type: Optional[str]
+
+
+@dataclass
+class IndexStats:
+ """Result of :meth:`VectorIndex.index`."""
+
+ chunks: int
+ added: int
+ removed: int
+
+
+@dataclass
+class DeleteStats:
+ """Result of :meth:`VectorIndex.delete`."""
+
+ removed: int
+ rows_deleted: int
+
+
+class VectorIndex:
+ """Per-collection semantic index. Construct once per (collection, user).
+
+ Persistence resources (``path`` / ``lock`` / integrity hooks) are injected —
+ the caller (service layer) owns per-user path resolution and the write-lock
+ registry; this facade just wires them into the store.
+ """
+
+ def __init__(
+ self,
+ *,
+ username: str,
+ db_password: str,
+ embeddings: Embeddings,
+ embedding_model: str,
+ embedding_model_type, # EmbeddingProvider enum (DocumentChunk column)
+ collection_name: str,
+ dimension: int,
+ path: Path,
+ lock: threading.Lock,
+ integrity_record: Callable[[Path], None],
+ integrity_verify: Callable[[Path], Tuple[bool, Optional[str]]],
+ index_type: str = "flat",
+ metric: str = "cosine",
+ normalize: bool = True,
+ provider: str = "faiss",
+ ) -> None:
+ self.username = username
+ self.db_password = db_password # gitleaks:allow
+ self.embeddings = embeddings
+ self.embedding_model = embedding_model
+ self.embedding_model_type = embedding_model_type
+ self.collection_name = collection_name
+ # Canonicalize the metric so the physical index BUILD (faiss_store:
+ # inner-product iff metric in ("cosine","dot_product")) and the search
+ # engines' relevance formula (which branch on ``metric == "l2"``) agree.
+ # A non-canonical value like "L2"/"Cosine"/" cosine " would otherwise
+ # build one index type but be scored as the other, silently corrupting
+ # relevance. Both the store (via ``bind`` below) and SearchResult.metric
+ # then see the same canonical string.
+ metric = (metric or "cosine").strip().lower()
+ self.metric = metric
+
+ store_cls = get_vector_store_class(provider)
+ path = Path(path)
+ bind: _BindKwargs = {
+ "dimension": dimension,
+ "index_type": index_type,
+ "metric": metric,
+ "normalize": normalize,
+ "path": path,
+ "lock": lock,
+ "integrity_record": integrity_record,
+ "integrity_verify": integrity_verify,
+ }
+ # ``bind`` already carries ``path``; pass it only via kwargs (load()'s
+ # first param is path) so we don't hand ``path`` twice.
+ self._store = (
+ store_cls.load(**bind)
+ if path.exists()
+ else store_cls.create(**bind)
+ )
+
+ @contextmanager
+ def _db(self, session: Optional[Session]) -> Iterator[Tuple[Session, bool]]:
+ """Yield ``(session, owns)``.
+
+ ``get_user_db_session`` returns a THREAD-LOCAL, reused session, so this
+ facade must not blindly ``commit()``/``rollback()`` — it would settle a
+ caller's unrelated pending work. When the caller passes its own
+ ``session``, we use it and yield ``owns=False`` (the caller owns the
+ transaction boundary and the apply()-then-commit durability gap). Only
+ when no session is passed do we open one and own commit/rollback.
+ """
+ if session is not None:
+ yield session, False
+ else:
+ with get_user_db_session(self.username, self.db_password) as s:
+ yield s, True
+
+ # ------------------------------------------------------------------ #
+ # index
+ # ------------------------------------------------------------------ #
+ def index(
+ self,
+ *,
+ source_type: str,
+ source_id: Optional[str],
+ chunks: Sequence[ChunkInput],
+ replace: bool = True,
+ session: Optional[Session] = None,
+ ) -> IndexStats:
+ """Embed + persist ``chunks`` for one source into this collection.
+
+ Ordering: write chunk rows and ``flush()`` for their int ids, then
+ ``store.apply()`` (persists vectors atomically under its lock), then
+ delete the source's prior rows, then ``commit()`` (only if we own the
+ session). If ``store.apply()`` fails we roll back — the new rows never
+ existed, so no DB row can point at a missing vector.
+
+ ``store.apply()`` persists vectors durably BEFORE the DB commit, so if
+ the commit later fails the vectors outlive their (rolled-back) rows as
+ orphans — searchable-by-nothing, cleaned on the next re-index of the
+ source. When ``session`` is passed the caller owns that window.
+
+ ``replace=True`` removes this source's PRIOR chunks/vectors first;
+ ``False`` appends.
+ """
+ chunks = list(chunks)
+ # An empty chunk list with replace=True still must remove this source's
+ # PRIOR rows/vectors — e.g. a note edited down to whitespace yields zero
+ # chunks, and skipping here would leave the user-cleared content
+ # permanently searchable. Only a genuine no-op (nothing to add AND
+ # nothing to replace) returns early.
+ if not chunks and (not replace or source_id is None):
+ return IndexStats(chunks=0, added=0, removed=0)
+
+ texts = [c.text for c in chunks]
+ vectors = (
+ np.asarray(self.embeddings.embed_documents(texts), dtype="float32")
+ if texts
+ else None
+ )
+
+ sid = str(source_id) if source_id is not None else None
+ with self._db(session) as (sess, owns):
+ prior_ids: List[int] = []
+ if replace and sid is not None:
+ # Scope the prior-chunk lookup to THIS store's embedding-model
+ # config. collection_name is identical across every model config
+ # for a collection (only RAGIndex.index_hash / the physical
+ # .faiss path differ per model), so a lookup by
+ # (source_type, source_id, collection_name) alone would also
+ # match rows indexed under a DIFFERENT model. Those ids would
+ # then be handed to THIS (physically separate, model-specific)
+ # store as remove_ids — where faiss silently no-ops on unknown
+ # ids — and _finalize_db would still DELETE the rows. Result: a
+ # reindex under model B destroys model A's chunk text (its only
+ # copy) while A's .faiss keeps the now-unresolvable vector,
+ # even though A's index is deliberately kept for model revert.
+ prior_ids = [
+ row.id
+ for row in sess.query(DocumentChunk.id).filter_by(
+ source_type=source_type,
+ source_id=sid,
+ collection_name=self.collection_name,
+ embedding_model=self.embedding_model,
+ embedding_model_type=self.embedding_model_type,
+ )
+ ]
+
+ rows = [self._build_row(c, source_type, sid) for c in chunks]
+ if rows:
+ sess.add_all(rows)
+ sess.flush() # assigns int PKs to every row in one round-trip
+ # SQLAlchemy's legacy Column() declarative style types instance
+ # attribute access as Column[int] rather than int; cast() is a
+ # no-op at runtime (row.id is already an int post-flush()).
+ new_ids = [cast(int, row.id) for row in rows]
+
+ try:
+ stats = self._store.apply(
+ add_ids=new_ids,
+ add_vectors=vectors,
+ remove_ids=prior_ids,
+ )
+ except Exception:
+ # apply() failed without a durable change (fail-closed reload /
+ # add error / atomic-save) — a clean DB rollback keeps them
+ # consistent.
+ if owns:
+ sess.rollback()
+ raise
+ # apply() is DURABLE from here; a DB-side failure below leaves the
+ # store and DB possibly disagreeing (orphan vectors/rows).
+ self._finalize_db(
+ sess, owns, prior_ids, f"index {source_type}/{sid}"
+ )
+
+ return IndexStats(
+ chunks=len(chunks),
+ added=stats["added"],
+ removed=stats["removed"],
+ )
+
+ @staticmethod
+ def _finalize_db(
+ session: Session,
+ owns: bool,
+ delete_ids: List[int],
+ what: str,
+ ) -> int:
+ """Delete rows + commit (if owned), AFTER a durable ``store.apply()``.
+
+ Covers the whole post-apply DB window in one place: if either the
+ prior-row delete OR the commit fails, the store has already persisted
+ vectors that the DB won't reflect (orphan vectors / rows) — a
+ known-inconsistent state that reconciles on the next re-index of the
+ source. Log it loudly, roll back if we own the session, then re-raise.
+ ``synchronize_session="fetch"`` keeps the reused thread-local session's
+ identity map from serving stale, already-deleted objects. Returns the
+ number of rows deleted.
+ """
+ deleted = 0
+ try:
+ if delete_ids:
+ deleted = (
+ session.query(DocumentChunk)
+ .filter(DocumentChunk.id.in_(delete_ids))
+ .delete(synchronize_session="fetch")
+ )
+ if owns:
+ session.commit()
+ except Exception:
+ logger.exception(
+ f"{what}: vectors were persisted but the DB update failed; "
+ "store and DB will reconcile on the next re-index of the source"
+ )
+ if owns:
+ session.rollback()
+ raise
+ return deleted
+
+ def _build_row(
+ self, chunk: ChunkInput, source_type: str, source_id: Optional[str]
+ ) -> DocumentChunk:
+ meta = chunk.metadata or {}
+ return DocumentChunk(
+ chunk_hash=hashlib.sha256(chunk.text.encode()).hexdigest(),
+ source_type=source_type,
+ source_id=source_id,
+ collection_name=self.collection_name,
+ chunk_text=chunk.text,
+ chunk_index=meta.get("chunk_index", 0),
+ start_char=meta.get("start_char", 0),
+ end_char=meta.get("end_char", len(chunk.text)),
+ word_count=len(chunk.text.split()),
+ # embedding_id stays populated: it's the old-uuid -> new-int join key
+ # the one-time index-format migration needs. (Legacy NOT NULL UNIQUE
+ # column; drop it only in a later, separate migration.)
+ embedding_id=uuid.uuid4().hex,
+ embedding_model=self.embedding_model,
+ embedding_model_type=self.embedding_model_type,
+ embedding_dimension=self._store.dimension,
+ document_title=meta.get("document_title") or meta.get("title"),
+ document_metadata=meta or None,
+ )
+
+ # ------------------------------------------------------------------ #
+ # search
+ # ------------------------------------------------------------------ #
+ def search(
+ self,
+ query: str,
+ top_k: int,
+ session: Optional[Session] = None,
+ ) -> List[SearchResult]:
+ """Embed ``query``, search the store, rehydrate hits from the DB by id.
+
+ Orphan hits (a vector whose DB row is gone) are skipped — there is no
+ in-store text to fall back to, and skipping is the correct signal.
+ """
+ if top_k <= 0:
+ return []
+ query_vec = np.asarray(
+ self.embeddings.embed_query(query), dtype="float32"
+ )
+ hits = self._store.search(query_vec, top_k) # [(chunk_id, distance)]
+ if not hits:
+ return []
+
+ ids = [cid for cid, _ in hits]
+ with self._db(session) as (sess, _owns):
+ # Scope rehydration to THIS collection. A hit id is a DocumentChunk.id
+ # from this collection's index, but an orphan/stale vector (e.g. a
+ # rolled-back insert left a vector whose id was later reused by a
+ # chunk in a DIFFERENT collection) could otherwise match a row that
+ # belongs elsewhere and leak that other document's text into this
+ # collection's results. Filtering by collection_name makes such a
+ # hit resolve to no row here and be skipped as an orphan.
+ rows = {
+ # cast(): row.id is Column[int] under the legacy Column()
+ # declarative style; a no-op at runtime.
+ cast(int, row.id): row
+ for row in sess.query(DocumentChunk).filter(
+ DocumentChunk.id.in_(ids),
+ DocumentChunk.collection_name == self.collection_name,
+ )
+ }
+
+ results: List[SearchResult] = []
+ for chunk_id, distance in hits:
+ row = rows.get(chunk_id)
+ if row is None:
+ logger.debug(
+ f"Search hit {chunk_id} has no DocumentChunk row; skipping"
+ )
+ continue
+ # SQLAlchemy's legacy Column() declarative style types instance
+ # attribute access as Column[...] rather than the plain Python
+ # value; cast() to the DB-verified runtime type (no conversion,
+ # so a None stays None rather than becoming e.g. the "None"
+ # string a str()/int() call would produce).
+ results.append(
+ SearchResult(
+ chunk_id=chunk_id,
+ text=cast(str, row.chunk_text),
+ distance=distance,
+ metric=self.metric,
+ metadata=cast(Optional[dict], row.document_metadata) or {},
+ document_title=cast(Optional[str], row.document_title),
+ source_id=cast(Optional[str], row.source_id),
+ source_type=cast(Optional[str], row.source_type),
+ )
+ )
+ return results
+
+ # ------------------------------------------------------------------ #
+ # delete
+ # ------------------------------------------------------------------ #
+ def delete(
+ self,
+ *,
+ source_type: str,
+ source_id: str,
+ session: Optional[Session] = None,
+ ) -> DeleteStats:
+ """Remove all of one source's chunks/vectors from this collection.
+
+ ``store.apply()`` (the durable side) runs before the DB delete + commit,
+ matching :meth:`index`'s ordering.
+
+ Re-queries ``DocumentChunk`` by (source_type, source_id,
+ collection_name) at call time to discover the ids to remove, so the
+ rows must still exist when this is called. If a caller has already
+ deleted those rows elsewhere, this finds nothing to do; use
+ :meth:`delete_ids` instead with the ids captured before deletion.
+ """
+ sid = str(source_id)
+ with self._db(session) as (sess, owns):
+ ids = [
+ row.id
+ for row in sess.query(DocumentChunk.id).filter_by(
+ source_type=source_type,
+ source_id=sid,
+ collection_name=self.collection_name,
+ )
+ ]
+ if not ids:
+ return DeleteStats(removed=0, rows_deleted=0)
+
+ try:
+ stats = self._store.apply(
+ add_ids=[], add_vectors=None, remove_ids=ids
+ )
+ except Exception:
+ if owns:
+ sess.rollback()
+ raise
+ # Guard the row-delete AND commit together (mirrors index()): a bare
+ # query(...).delete() that raised after the durable apply() above
+ # would leave orphan rows with no rollback and no diagnostic.
+ rows_deleted = self._finalize_db(
+ sess, owns, ids, f"delete {source_type}/{sid}"
+ )
+
+ return DeleteStats(removed=stats["removed"], rows_deleted=rows_deleted)
+
+ def delete_ids(
+ self,
+ ids: Sequence[int],
+ *,
+ session: Optional[Session] = None,
+ ) -> DeleteStats:
+ """Remove specific chunk ids' vectors from this collection's store.
+
+ For callers that already captured the ``DocumentChunk`` int ids
+ BEFORE the matching rows were deleted elsewhere — e.g. a caller
+ whose own per-item transaction must delete the rows eagerly (for
+ its own atomicity/rollback semantics) ahead of a later BATCHED
+ vector-store cleanup pass. Unlike :meth:`delete`, this does NOT
+ re-query ``DocumentChunk`` by (source_type, source_id,
+ collection_name) to discover the ids — by the time this runs the
+ rows the ids came from may already be gone, and that lookup would
+ find nothing (see the "rows must still exist" requirement noted on
+ :meth:`delete`). Any rows matching the given ids that do still
+ exist are cleaned up too (defensive; normally none are left).
+ """
+ wanted = sorted({int(i) for i in ids if i is not None})
+ if not wanted:
+ return DeleteStats(removed=0, rows_deleted=0)
+
+ with self._db(session) as (sess, owns):
+ try:
+ stats = self._store.apply(
+ add_ids=[], add_vectors=None, remove_ids=wanted
+ )
+ except Exception:
+ if owns:
+ sess.rollback()
+ raise
+ # Guard the row-delete AND commit together (mirrors index()).
+ rows_deleted = self._finalize_db(
+ sess, owns, wanted, f"delete_ids ({len(wanted)} ids)"
+ )
+
+ return DeleteStats(removed=stats["removed"], rows_deleted=rows_deleted)
+
+ def count(self) -> int:
+ """Number of vectors currently in the store."""
+ return self._store.count()
diff --git a/src/local_deep_research/vector_stores/implementations/__init__.py b/src/local_deep_research/vector_stores/implementations/__init__.py
new file mode 100644
index 0000000000..4becf9461e
--- /dev/null
+++ b/src/local_deep_research/vector_stores/implementations/__init__.py
@@ -0,0 +1 @@
+"""Concrete vector-store implementations."""
diff --git a/src/local_deep_research/vector_stores/implementations/faiss_store.py b/src/local_deep_research/vector_stores/implementations/faiss_store.py
new file mode 100644
index 0000000000..d70d3b0699
--- /dev/null
+++ b/src/local_deep_research/vector_stores/implementations/faiss_store.py
@@ -0,0 +1,1039 @@
+"""FAISS-backed vector store.
+
+Drives raw ``faiss`` directly via an :class:`IndexIDMap2` keyed by
+application-supplied int64 ids (``DocumentChunk.id``). The store holds **only**
+vectors + ids — no document text, no metadata (see the "SECURITY INVARIANT"
+block in :mod:`..base`: text must never reach a vector store). Persistence is
+``faiss.write_index`` / ``faiss.read_index`` (pure binary), with no companion
+docstore file.
+
+``IndexIDMap2`` keeps id management in the faiss C++ layer (no Python-side
+position map, no position renumbering on delete), which lets the caller key
+vectors directly by ``DocumentChunk.id`` and rehydrate all text/metadata from
+the encrypted DB by that id.
+"""
+
+import os
+import tempfile
+import threading
+import time
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Callable, Iterator, List, Optional, Sequence, Tuple, cast
+
+import numpy as np
+from faiss import (
+ METRIC_INNER_PRODUCT,
+ METRIC_L2,
+ IDSelectorBatch,
+ IndexFlatIP,
+ IndexFlatL2,
+ IndexHNSWFlat,
+ IndexIDMap2,
+ downcast_index,
+ normalize_L2,
+ read_index,
+ vector_to_array,
+ write_index,
+)
+from loguru import logger
+
+from ..base import BaseVectorStore
+
+# HNSW connections-per-layer (parity with the previous wrapper's default).
+_HNSW_M = 32
+# Metrics that use inner product on L2-normalized vectors (cosine similarity).
+_IP_METRICS = ("cosine", "dot_product")
+# persist() only sweeps ``.tmp`` files older than this — long enough that no
+# single index write could still be in flight, so a concurrent (multi-process)
+# writer's just-created temp is never mistaken for an orphan and deleted.
+_STALE_TMP_AGE_SECONDS = 3600
+# Max squared L2 norm allowed for a raw (normalize=False) vector. faiss's L2/IP
+# distance math (e.g. ||q-v||^2 ~ 4*norm^2 worst case) is done in float32; a row
+# whose squared norm approaches float32's max overflows internally and faiss then
+# returns the reserved -1 sentinel for a REAL vector, which search() drops. Real
+# embeddings sit many orders of magnitude below this; this only rejects
+# pathological/overflowing magnitudes.
+_MAX_SAFE_SQ_NORM = float(np.finfo(np.float32).max) / 8.0
+
+
+def _canon(value: Optional[str], default: str) -> str:
+ """Canonicalize an index_type / metric string (strip + lower) so every
+ construction path — the facade, the legacy rekey builder, direct create() —
+ agrees. A non-canonical 'HNSW'/'Cosine' would otherwise build one structure
+ but be interpreted as another (wrong index type, wrong metric, corrupted
+ relevance) depending on which case-sensitive comparison ran."""
+ return (value or default).strip().lower()
+
+
+class FaissVectorStore(BaseVectorStore):
+ """A single collection's FAISS index (``IndexIDMap2`` over a base index).
+
+ Concurrency: the injected write lock is a ``threading.Lock`` — it serializes
+ writers (and, via ``_read_guard``, readers) within ONE process only. This
+ assumes a single-process deployment. Under a multi-process server (e.g.
+ ``gunicorn -w N``) two workers hold independent locks and a lost update is
+ possible; a cross-process (file) lock would be required for that deployment.
+ """
+
+ provider_key = "faiss"
+ provider_name = "FAISS"
+ is_local_file = True
+ supports_reconstruct = True
+
+ def __init__(
+ self,
+ index: IndexIDMap2,
+ *,
+ dimension: int,
+ index_type: str,
+ metric: str,
+ normalize: bool,
+ ) -> None:
+ self._index = index
+ self.dimension = dimension
+ self.index_type = _canon(index_type, "flat")
+ self.metric = _canon(metric, "cosine")
+ self.normalize = normalize
+ # Set if a failed apply() could not resync in-memory state to disk; a
+ # poisoned instance must refuse reads rather than serve state that
+ # disagrees with the durable file (a fresh load/apply clears it).
+ self._poisoned = False
+ # Persistence binding (set by _bind via create()/load()). Required only
+ # for apply(); a search-only load can leave these unset. Injected by the
+ # caller so this store never imports a lock registry or DB integrity
+ # model — it only owns the choreography, not the resources.
+ self._path: Optional[Path] = None
+ self._lock: Optional[threading.Lock] = None
+ self._integrity_record: Optional[Callable[[Path], None]] = None
+ self._integrity_verify: Optional[
+ Callable[[Path], Tuple[bool, Optional[str]]]
+ ] = None
+
+ def _bind(
+ self,
+ path: Optional[Path],
+ lock: Optional[threading.Lock],
+ integrity_record: Optional[Callable[[Path], None]],
+ integrity_verify: Optional[
+ Callable[[Path], Tuple[bool, Optional[str]]]
+ ],
+ ) -> None:
+ """Attach the persistence resources apply() needs (injected, not imported).
+
+ ``path``: where this index's ``.faiss`` lives (caller resolves the
+ per-user path). ``lock``: the per-index write lock (caller owns the
+ registry + its lifecycle). ``integrity_record`` / ``integrity_verify``:
+ closures over the caller's file-integrity manager, so save+record stay
+ under the same lock without this class knowing about the DB.
+ """
+ self._path = Path(path) if path is not None else None
+ self._lock = lock
+ self._integrity_record = integrity_record
+ self._integrity_verify = integrity_verify
+ if (
+ self._path is not None
+ and lock is not None
+ and (integrity_record is None or integrity_verify is None)
+ ):
+ logger.warning(
+ "FaissVectorStore bound for writes without integrity hooks; "
+ "torn-write/corruption detection is disabled for this index"
+ )
+
+ # ------------------------------------------------------------------ #
+ # Construction
+ # ------------------------------------------------------------------ #
+ @staticmethod
+ def _build_base_index(dimension: int, index_type: str, metric: str):
+ """Build the base faiss index (parity with the prior wrapper).
+
+ ``ivf`` is not implemented and falls back to flat, exactly as before.
+ """
+ index_type = _canon(index_type, "flat")
+ metric = _canon(metric, "cosine")
+ # Inner product for cosine/dot-product (on normalized vectors), else L2.
+ metric_type = (
+ METRIC_INNER_PRODUCT if metric in _IP_METRICS else METRIC_L2
+ )
+ if index_type == "hnsw":
+ logger.info(f"Created HNSW index with M={_HNSW_M} connections")
+ # Pass the metric explicitly — IndexHNSWFlat defaults to L2, which
+ # would return L2 distances even for a cosine collection.
+ return IndexHNSWFlat(dimension, _HNSW_M, metric_type)
+ # "flat" (default), "ivf" (falls back to flat), or anything else.
+ if metric in _IP_METRICS:
+ return IndexFlatIP(dimension)
+ return IndexFlatL2(dimension)
+
+ @staticmethod
+ def _physical_config_reason(
+ index: IndexIDMap2, index_type: str, metric: str
+ ) -> Optional[str]:
+ """Why an on-disk IndexIDMap2's PHYSICAL base index / metric does NOT
+ match ``index_type``/``metric`` (or ``None`` if it matches).
+
+ A stale/foreign file of the wrong type must never be adopted: an HNSW
+ file treated as flat makes ``supports_delete`` wrongly True so
+ ``delete()`` raises, and a flat file treated as hnsw makes
+ ``apply(remove_ids)`` silently REBUILD the file as HNSW. cosine and
+ dot_product are physically identical (both inner-product), so the metric
+ FAMILY is compared, not the exact string. Shared by load() and the
+ reload/restore paths so all three enforce the same invariant.
+ """
+ base = downcast_index(index.index)
+ want_type = _canon(index_type, "flat")
+ if isinstance(base, IndexHNSWFlat) != (want_type == "hnsw"):
+ return (
+ f"physical index {type(base).__name__} != index_type "
+ f"{want_type!r}"
+ )
+ want_metric_type = (
+ METRIC_INNER_PRODUCT
+ if _canon(metric, "cosine") in _IP_METRICS
+ else METRIC_L2
+ )
+ if base.metric_type != want_metric_type:
+ return (
+ f"physical metric_type {base.metric_type} != metric "
+ f"{_canon(metric, 'cosine')!r}"
+ )
+ return None
+
+ @classmethod
+ def create(
+ cls,
+ *,
+ dimension: int,
+ index_type: str,
+ metric: str,
+ normalize: bool,
+ path: Optional[Path] = None,
+ lock: Optional[threading.Lock] = None,
+ integrity_record: Optional[Callable[[Path], None]] = None,
+ integrity_verify: Optional[
+ Callable[[Path], Tuple[bool, Optional[str]]]
+ ] = None,
+ **kwargs,
+ ) -> "FaissVectorStore":
+ base = cls._build_base_index(dimension, index_type, metric)
+ store = cls(
+ IndexIDMap2(base),
+ dimension=dimension,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+ store._bind(path, lock, integrity_record, integrity_verify)
+ return store
+
+ @classmethod
+ def load(
+ cls,
+ path: Path,
+ *,
+ dimension: int,
+ index_type: str,
+ metric: str,
+ normalize: bool,
+ lock: Optional[threading.Lock] = None,
+ integrity_record: Optional[Callable[[Path], None]] = None,
+ integrity_verify: Optional[
+ Callable[[Path], Tuple[bool, Optional[str]]]
+ ] = None,
+ **kwargs,
+ ) -> "FaissVectorStore":
+ """Load a persisted ``IndexIDMap2`` from ``path`` (a ``.faiss`` file).
+
+ ``read_index`` is a pure binary read — no pickle. Post-migration every
+ on-disk index is an ``IndexIDMap2``; a raw base index here means either
+ a pre-migration file (should be converted first) or corruption, and is
+ surfaced rather than silently coerced.
+
+ ``lock`` / ``integrity_*`` are only needed if the caller will later
+ write via :meth:`apply`; a search-only load can omit them.
+ """
+ index = read_index(str(path))
+ if not isinstance(index, IndexIDMap2):
+ raise ValueError(
+ f"Index at {path} is {type(index).__name__}, not IndexIDMap2 "
+ "(pre-migration or corrupt format)"
+ )
+ # Catch embedding-model drift early: a persisted index whose dimension
+ # no longer matches the configured model would otherwise fail with an
+ # opaque faiss error deep inside a later add()/search().
+ if index.d != dimension:
+ raise ValueError(
+ f"Index at {path} has dimension {index.d}, expected {dimension} "
+ "(embedding model/config changed — reindex required)"
+ )
+ # Verify the PHYSICAL index matches the caller-declared index_type/metric
+ # instead of trusting the label. A stale file left at this path (e.g. a
+ # force-reindex whose unlink failed, or a foreign/pre-canonicalization
+ # file) could otherwise be adopted under a mismatched config: an HNSW
+ # file loaded as "flat" makes supports_delete wrongly True so .delete()
+ # raises a C++ RuntimeError, while a Flat file loaded as "hnsw" makes
+ # .apply(remove_ids) silently REBUILD the file as HNSW. Introspect the
+ # real base index + metric and refuse a mismatch so the caller
+ # quarantines + rebuilds. (cosine/dot_product are physically identical —
+ # both METRIC_INNER_PRODUCT — so we compare the metric FAMILY, not the
+ # exact string; _build_base_index only ever encodes HNSW-vs-Flat and
+ # IP-vs-L2.)
+ reason = cls._physical_config_reason(index, index_type, metric)
+ if reason:
+ raise ValueError(
+ f"Index at {path}: {reason} — refusing a mismatched index "
+ "(reindex required)"
+ )
+ store = cls(
+ index,
+ dimension=dimension,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+ store._bind(path, lock, integrity_record, integrity_verify)
+ return store
+
+ # ------------------------------------------------------------------ #
+ # Internal helpers
+ # ------------------------------------------------------------------ #
+ def _prepare(self, vectors: np.ndarray) -> np.ndarray:
+ """Return a contiguous float32 2-D copy, L2-normalized if configured.
+
+ A copy is always made so ``normalize_L2`` (which mutates in place) never
+ touches the caller's array.
+ """
+ vecs = np.array(vectors, dtype="float32", copy=True, order="C")
+ if vecs.ndim == 1:
+ vecs = vecs.reshape(1, -1)
+ # Validate dimension explicitly. FAISS only guards this with an internal
+ # ``assert`` (no message), which is STRIPPED under ``python -O`` — a
+ # wrong-dimension array would then be added/searched silently, corrupting
+ # the index with no error. Fail loudly instead.
+ if vecs.shape[1] != self.dimension:
+ raise ValueError(
+ f"vector dimension {vecs.shape[1]} != index dimension "
+ f"{self.dimension}"
+ )
+ # Reject non-finite INPUT first: NaN/Inf from a bad embedding poison the
+ # index — the vector becomes permanently unsearchable and NaN distances
+ # corrupt ranking — with no error. Fail loudly so the caller fixes it.
+ if not np.isfinite(vecs).all():
+ raise ValueError(
+ "vectors contain non-finite values (NaN/Inf) — bad embedding"
+ )
+ if self.normalize:
+ # normalize_L2 silently maps a zero-magnitude row (and one whose
+ # squared norm overflows float32) to ALL-ZEROS, not NaN, so the
+ # finite input passes the check above yet becomes a degenerate,
+ # effectively-unsearchable vector. Reject those explicitly (norm in
+ # float32 to match faiss: a real overflow is a non-finite norm here).
+ norms = np.sqrt((vecs**2).sum(axis=1))
+ if not np.isfinite(norms).all() or (norms == 0).any():
+ raise ValueError(
+ "vectors contain a zero-magnitude or overflow-magnitude row "
+ "that L2 normalization cannot represent — bad embedding"
+ )
+ normalize_L2(vecs)
+ else:
+ # normalize=False: raw vectors go straight into faiss's L2/IP
+ # distance math. A large-but-finite magnitude (which passes the
+ # isfinite check above) overflows float32 INSIDE that computation,
+ # and faiss then returns the reserved -1 sentinel for a REAL vector —
+ # search() drops it as an "empty slot", silently losing the hit.
+ # Reject rows whose squared L2 norm approaches float32's max (computed
+ # in float64 so the check itself can't overflow).
+ sq_norms = (vecs.astype("float64") ** 2).sum(axis=1)
+ if (sq_norms > _MAX_SAFE_SQ_NORM).any():
+ raise ValueError(
+ "vectors contain a magnitude too large for float32 distance "
+ "computation (would overflow to a dropped/mis-ranked search "
+ "hit) — normalize the embeddings or use a bounded model"
+ )
+ return vecs
+
+ # ------------------------------------------------------------------ #
+ # Vector operations
+ # ------------------------------------------------------------------ #
+ def add(self, ids: List[int], vectors: np.ndarray) -> None:
+ id_arr = np.asarray(list(ids), dtype="int64")
+ # Guard empty BEFORE _prepare: a length-0 1-D array would otherwise
+ # reshape to one row of dimension 0 and raise a spurious mismatch.
+ if len(id_arr) == 0:
+ return
+ vecs = self._prepare(vectors)
+ if len(id_arr) != len(vecs):
+ raise ValueError(
+ f"ids/vectors length mismatch: {len(id_arr)} != {len(vecs)}"
+ )
+ self._index.add_with_ids(vecs, id_arr)
+
+ @contextmanager
+ def _read_guard(self) -> Iterator[None]:
+ """Serialize a read against a concurrent ``apply()`` and refuse a
+ poisoned instance.
+
+ faiss is not safe for concurrent search-vs-add/remove on the *same*
+ index object; when this instance is bound for writes (a shared, cached
+ instance), reads take the same lock ``apply()`` uses. Internal callers
+ that already hold the lock (e.g. ``_dedup_new``) must use the
+ ``*_unlocked`` helpers, not these public methods, to avoid re-entrancy
+ deadlock (``threading.Lock`` is not reentrant).
+ """
+ if self._lock is not None:
+ with self._lock:
+ if self._poisoned:
+ raise RuntimeError(
+ "vector store in-memory state is poisoned by a failed "
+ "write; reload the index before reading"
+ )
+ yield
+ else:
+ if self._poisoned:
+ raise RuntimeError(
+ "vector store in-memory state is poisoned by a failed "
+ "write; reload the index before reading"
+ )
+ yield
+
+ def search(
+ self, query_vector: np.ndarray, k: int
+ ) -> List[Tuple[int, float]]:
+ if k <= 0:
+ return []
+ with self._read_guard():
+ if self._index.ntotal == 0:
+ return []
+ # Clamp k to the number of stored vectors: faiss allocates k*4 bytes
+ # of result buffer per query, so an unbounded k (a buggy/hostile
+ # caller passing e.g. 10**9) would OOM. Searching for more neighbours
+ # than exist only pads the result with -1 slots we skip anyway, so
+ # this never changes the returned hits.
+ k = min(k, self._index.ntotal)
+ q = self._prepare(query_vector)
+ distances, ids = self._index.search(q, k)
+ results: List[Tuple[int, float]] = []
+ for dist, vid in zip(distances[0], ids[0]):
+ # faiss returns -1 for empty slots when fewer than k neighbors.
+ if vid == -1:
+ continue
+ results.append((int(vid), float(dist)))
+ return results
+
+ @property
+ def supports_delete(self) -> bool:
+ """False for HNSW — faiss ``remove_ids`` is unimplemented for it."""
+ return self.index_type != "hnsw"
+
+ def delete(self, ids: List[int]) -> int:
+ id_list = [i for i in ids if i is not None]
+ if not id_list:
+ return 0
+ if not self.supports_delete:
+ # faiss HNSW has no remove_ids; surface a clear, actionable error
+ # rather than the opaque C++ "remove_ids not implemented" RuntimeError
+ # (or a silent no-op). apply() never reaches this — it routes HNSW
+ # removals through _rebuild_dropping() (a full index rebuild) — so
+ # this guards only a direct delete() call on an HNSW store.
+ raise RuntimeError(
+ f"delete/replace is unsupported for index_type="
+ f"'{self.index_type}' (faiss HNSW cannot remove vectors); "
+ "removals go through apply(), which rebuilds the index"
+ )
+ id_arr = np.asarray(id_list, dtype="int64")
+ return int(self._index.remove_ids(IDSelectorBatch(id_arr)))
+
+ def _rebuild_dropping(self, remove_ids: List[int]) -> int:
+ """Remove ids from an index that has no ``remove_ids`` (HNSW) by
+ rebuilding it from its own reconstructed vectors.
+
+ The only way to delete from a faiss HNSW index is to build a fresh one
+ holding every surviving vector. Runs under ``apply()``'s write lock and
+ uses the raw/unlocked helpers to avoid re-entrant self-deadlock.
+
+ No re-embedding: ``IndexIDMap2`` preserves each vector for
+ reconstruction by id, so survivors are reconstructed and re-added
+ VERBATIM via ``add_with_ids`` — deliberately bypassing ``_prepare`` so
+ the stored vectors (already L2-normalized if ``normalize`` is set) are
+ not normalized a second time. Returns the count actually removed (ids
+ absent from the index are ignored, matching ``delete``'s leniency).
+ """
+ remove_set = {int(i) for i in remove_ids}
+ live = self._live_ids_unlocked()
+ keep = [i for i in live if i not in remove_set]
+ removed = len(live) - len(keep)
+ if removed == 0:
+ return 0
+ if keep:
+ vecs = np.empty((len(keep), self.dimension), dtype="float32")
+ for row, vid in enumerate(keep):
+ vecs[row] = self._index.reconstruct(int(vid))
+ base = self._build_base_index(
+ self.dimension, self.index_type, self.metric
+ )
+ new_index = IndexIDMap2(base)
+ if keep:
+ new_index.add_with_ids(vecs, np.asarray(keep, dtype="int64"))
+ self._index = new_index
+ return removed
+
+ def _live_ids_unlocked(self) -> List[int]:
+ if self._index.ntotal == 0:
+ return []
+ # faiss is untyped (ignore_missing_imports); tell mypy what the raw
+ # C++ id-map array becomes after the numpy round-trip.
+ return cast(
+ List[int],
+ vector_to_array(self._index.id_map).astype("int64").tolist(),
+ )
+
+ def live_ids(self) -> List[int]:
+ with self._read_guard():
+ return self._live_ids_unlocked()
+
+ def count(self) -> int:
+ with self._read_guard():
+ return int(self._index.ntotal)
+
+ def reconstruct(self, id: int) -> Optional[np.ndarray]:
+ # Honor the Optional contract: faiss raises RuntimeError for an id not
+ # in the index; return None instead of propagating.
+ with self._read_guard():
+ try:
+ # faiss is untyped; reconstruct() returns a raw ndarray here.
+ return cast(np.ndarray, self._index.reconstruct(int(id)))
+ except RuntimeError:
+ return None
+
+ def _file_fingerprint(self) -> Optional[tuple]:
+ """A cheap staleness token for the on-disk index file (stat, no read).
+
+ Shared across FaissVectorStore INSTANCES via the file itself. This is
+ why the off-lock rebuild uses it and NOT a per-instance counter: the
+ normal caller builds a FRESH store per operation (only the write lock is
+ shared via the registry), so a concurrent writer is a different Python
+ object whose mutation would never bump this instance's counter. The
+ on-disk file, in contrast, is written by every writer. ``os.replace``
+ gives the target a fresh inode on every persist (mkstemp temp + rename),
+ and mtime_ns/size change with content, so any persist by any writer
+ changes this tuple. Returns None if the file does not exist yet.
+ """
+ if self._path is None:
+ return None
+ try:
+ st = os.stat(self._path)
+ except OSError:
+ return None
+ return (st.st_ino, st.st_mtime_ns, st.st_size)
+
+ def persist(self, path: Path) -> None:
+ """Atomically write the index to ``path`` (temp file + ``os.replace``).
+
+ The temp+rename closes the torn-write window (#4197): a concurrent
+ reader/verifier never observes a half-written ``.faiss`` — it sees
+ either the old bytes or the new bytes, never a truncated mix.
+ """
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ # Keep the index dir private: the raw vectors are weakly invertible, so
+ # other local accounts must not be able to read them. Structural, not
+ # left to the caller.
+ try:
+ path.parent.chmod(0o700)
+ except OSError:
+ logger.warning(f"Could not chmod {path.parent} to 0o700")
+ # Sweep stale temp files left by a previously hard-killed write. Within
+ # one process persist() runs under this index's write lock, so no
+ # in-process writer owns a ``<name>.*.tmp`` here. But that lock is
+ # per-process (a threading.Lock in a per-process registry), so under
+ # ``gunicorn -w N`` a SECOND worker can be mid-persist for the SAME path
+ # with its temp not yet renamed — unlinking it would crash that write
+ # with FileNotFoundError at fsync. Only sweep temps OLDER than a generous
+ # threshold: a genuinely orphaned temp (from a past hard kill) is
+ # minutes/hours old, while an in-flight one was just created, and no
+ # single write approaches this age — so a live temp is never swept.
+ now = time.time()
+ for stale in path.parent.glob(f"{path.name}.*.tmp"):
+ try:
+ if now - stale.stat().st_mtime < _STALE_TMP_AGE_SECONDS:
+ continue # too recent — may be a concurrent worker's temp
+ stale.unlink()
+ except OSError:
+ logger.warning(f"Could not remove stale temp file {stale}")
+ # mkstemp creates the temp file O_EXCL with a random name inside the
+ # (private) index dir — no predictable-name symlink-swap window.
+ # Safe: this writes only the faiss index — vectors + integer
+ # DocumentChunk.ids, never chunk text/metadata (see base.py's
+ # "SECURITY INVARIANT" — the interface has no text parameter, so no
+ # backend can persist it). Not sensitive data at rest.
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(path.parent), prefix=f"{path.name}.", suffix=".tmp"
+ )
+ os.close(fd)
+ tmp = Path(tmp_name)
+ try:
+ write_index(self._index, str(tmp))
+ # fsync the temp bytes BEFORE the rename so a crash/power-loss can't
+ # leave a renamed-but-unflushed (torn) index — the rename is only
+ # atomic w.r.t. what has actually reached disk.
+ with open(tmp, "rb") as f:
+ os.fsync(f.fileno())
+ os.replace(tmp, path)
+ # fsync the directory so the rename itself is durable across a crash.
+ try:
+ dir_fd = os.open(str(path.parent), os.O_RDONLY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ except OSError:
+ pass # directory fsync is unsupported on some platforms
+ finally:
+ if tmp.exists():
+ try:
+ tmp.unlink()
+ except OSError:
+ logger.warning(f"Could not remove temp index file {tmp}")
+
+ # ------------------------------------------------------------------ #
+ # Durable batch write (apply)
+ # ------------------------------------------------------------------ #
+ def _reload_under_lock(self) -> None:
+ """Re-read the on-disk index so this write absorbs other writers' saves.
+
+ Called while holding the write lock. If the file does not exist yet
+ (first write), keep the current fresh in-memory index and proceed.
+
+ But if the file EXISTS and cannot be trusted — integrity verify fails,
+ the read fails, or it is a foreign format — FAIL CLOSED: raise rather
+ than proceed to overwrite it with our (possibly stale) in-memory copy.
+ Overwriting would clobber a concurrent writer's committed save and
+ silently "heal" a corrupt/tampered file, defeating both the reload-merge
+ guarantee and integrity detection. The caller decides whether to
+ quarantine + rebuild.
+ """
+ if self._path is None or not self._path.exists():
+ # No durable file to merge against. Normally keep the current
+ # in-memory index (a genuine first write). BUT if a prior apply()
+ # failed to persist and poisoned this instance, the in-memory index
+ # holds a stale, never-persisted mutation — and _read_guard blocks
+ # reads but apply() doesn't check _poisoned, so this now-succeeding
+ # write would silently persist that earlier failed change. Discard it
+ # (rebuild an empty index) so only THIS operation's mutation lands.
+ if self._poisoned:
+ base = self._build_base_index(
+ self.dimension, self.index_type, self.metric
+ )
+ self._index = IndexIDMap2(base)
+ self._poisoned = False
+ logger.warning(
+ "Discarded a stale in-memory mutation from a prior failed "
+ "apply() (no durable file to reconcile against)"
+ )
+ return
+ if self._integrity_verify is not None:
+ ok, reason = self._integrity_verify(self._path)
+ if not ok:
+ raise RuntimeError(
+ "Refusing to overwrite index whose integrity check failed "
+ f"on reload ({reason})"
+ )
+ try:
+ index = read_index(str(self._path))
+ except Exception as exc:
+ raise RuntimeError(
+ f"Refusing to overwrite index that failed to reload: {exc}"
+ ) from exc
+ if not isinstance(index, IndexIDMap2):
+ raise RuntimeError(
+ f"Refusing to overwrite: on-disk index is "
+ f"{type(index).__name__}, not IndexIDMap2 (foreign/corrupt)"
+ )
+ # Same dimension guard load() enforces: adding a self.dimension-wide
+ # vector into a differently-sized index would otherwise trip only
+ # faiss's internal assert (stripped under `python -O`), silently
+ # corrupting the index. Fail closed instead.
+ if index.d != self.dimension:
+ raise RuntimeError(
+ f"Refusing to overwrite: on-disk index dimension {index.d} "
+ f"!= configured {self.dimension} (embedding model/config changed)"
+ )
+ # Same physical-type/metric guard load() enforces: a stale/foreign file
+ # of the wrong base type or metric must not be adopted here either, or
+ # apply() would misroute its delete (HNSW-as-flat raises; flat-as-hnsw
+ # silently rebuilds the file as HNSW).
+ reason = self._physical_config_reason(
+ index, self.index_type, self.metric
+ )
+ if reason:
+ raise RuntimeError(f"Refusing to overwrite: {reason}")
+ self._index = index
+ # In-memory state now equals the verified durable file (integrity,
+ # type, dimension and physical-config all checked above), so any stale
+ # never-persisted mutation that poisoned this instance is resolved.
+ # Clear the flag — mirroring the no-durable-file branch above — so a
+ # concurrent read during _apply_hnsw's off-lock rebuild window is not
+ # spuriously refused by _read_guard while self._index is actually valid.
+ self._poisoned = False
+
+ def _restore_from_disk(self) -> None:
+ """Best-effort resync of the in-memory index to the durable file.
+
+ Used after a failed ``apply()`` so a partial in-memory mutation (e.g. a
+ removal that landed before an add/persist raised) never leaves this
+ instance diverged from disk. If the file can't be read, drop nothing —
+ the next ``apply()`` reloads under the lock anyway.
+ """
+ try:
+ if self._path is not None and self._path.exists():
+ index = read_index(str(self._path))
+ # Only trust a resync to a same-format, same-dimension AND
+ # same physical-type/metric index; anything else means we cannot
+ # safely represent disk state in memory, so fall through to
+ # poisoning (rather than silently adopting a wrong-typed file).
+ if (
+ isinstance(index, IndexIDMap2)
+ and index.d == self.dimension
+ and self._physical_config_reason(
+ index, self.index_type, self.metric
+ )
+ is None
+ ):
+ self._index = index
+ # In-memory now matches the durable file again, so this
+ # instance is consistent — clear any prior poisoning so reads
+ # aren't blocked forever after a recovered failure.
+ self._poisoned = False
+ return
+ except Exception:
+ # Re-read/verify of the durable index failed; the poison flag and
+ # warning just below handle it (reads are refused until the next
+ # clean apply() reloads under the lock).
+ logger.debug("Resync re-read of the durable index failed")
+ # Could not resync in-memory state to disk. Mark poisoned so reads
+ # refuse to serve a possibly half-mutated index; the next successful
+ # apply() (which reloads under the lock) clears it.
+ self._poisoned = True
+ logger.warning(
+ "Could not restore in-memory index from disk after a failed "
+ "apply(); marking store poisoned until the next successful write"
+ )
+
+ @staticmethod
+ def _require_add_vectors(add_vectors: Optional[np.ndarray]) -> np.ndarray:
+ """Narrow ``add_vectors`` to non-Optional for the type checker.
+
+ ``apply()`` already raises this identical ``ValueError`` before
+ dispatching to ``_apply_locked``/``_apply_hnsw`` whenever ``add_ids``
+ is non-empty and ``add_vectors`` is ``None``; this re-checks (rather
+ than just asserting) so mypy can see the narrowed, non-Optional type
+ at each call site without an inline ``raise`` inside a ``try`` block.
+ """
+ if add_vectors is None:
+ raise ValueError("add_ids given without add_vectors")
+ return add_vectors
+
+ def _dedup_new(
+ self, ids: List[int], vectors: np.ndarray
+ ) -> Tuple[List[int], np.ndarray]:
+ """Drop ids already present in the index and within-batch duplicates.
+
+ Keeps the first occurrence of each id. Returns aligned (ids, vectors).
+ Runs under ``apply()``'s lock — uses the unlocked live-ids helper to
+ avoid re-entrant self-deadlock.
+ """
+ live = set(self._live_ids_unlocked())
+ keep_rows: List[int] = []
+ seen: set = set()
+ for row, vid in enumerate(ids):
+ if vid in live or vid in seen:
+ continue
+ seen.add(vid)
+ keep_rows.append(row)
+ if len(keep_rows) == len(ids):
+ return list(ids), vectors
+ kept_ids = [ids[r] for r in keep_rows]
+ kept_vecs = (
+ np.asarray(vectors)[keep_rows]
+ if keep_rows
+ else np.empty((0, self.dimension), dtype="float32")
+ )
+ return kept_ids, kept_vecs
+
+ def apply(
+ self,
+ *,
+ add_ids: List[int],
+ add_vectors: Optional[np.ndarray],
+ remove_ids: Sequence[int] = (),
+ dedup: bool = True,
+ ) -> dict:
+ if self._lock is None or self._path is None:
+ raise RuntimeError(
+ "FaissVectorStore.apply() requires a persistence binding "
+ "(path + lock); construct via create()/load() with them set."
+ )
+ add_ids = list(add_ids or [])
+ # Drop None remove-ids up front so BOTH dispatch paths are safe: the
+ # flat/IVF delete() already filters None, but the HNSW rebuild path
+ # (_rebuild_dropping / IDSelectorBatch) does not and would raise an
+ # unhandled TypeError. A None remove-id matches nothing anyway.
+ remove_ids = [i for i in (remove_ids or []) if i is not None]
+ if add_ids and add_vectors is None:
+ raise ValueError("add_ids given without add_vectors")
+ # HNSW has no in-place remove_ids: any removal or id-collision forces a
+ # full O(collection) graph rebuild. Route that through the off-lock path
+ # so the (expensive) rebuild does NOT hold the write lock that also
+ # gates every search() — only the snapshot and the final swap are
+ # locked. flat/IVF (real remove_ids) stay on the fully-locked path.
+ if not self.supports_delete:
+ return self._apply_hnsw(add_ids, add_vectors, remove_ids, dedup)
+ return self._apply_locked(add_ids, add_vectors, remove_ids, dedup)
+
+ def _apply_locked(
+ self,
+ add_ids: List[int],
+ add_vectors: Optional[np.ndarray],
+ remove_ids: List[int],
+ dedup: bool,
+ ) -> dict:
+ """Fully-locked apply: reload -> remove(+collision) -> add -> persist.
+
+ Used for flat/IVF (in-place ``remove_ids``) and as the race fallback for
+ the off-lock HNSW path. Holds the write lock for the whole operation.
+ """
+ # apply() already required a persistence binding before dispatching
+ # here (path + lock not None) -- narrow the Optionals once, locally,
+ # so mypy sees the same invariant.
+ lock = self._lock
+ path = self._path
+ if lock is None or path is None:
+ raise RuntimeError(
+ "FaissVectorStore._apply_locked() requires a persistence "
+ "binding (path + lock); apply() should have already "
+ "validated this before dispatching here"
+ )
+ with lock:
+ # #4200: reload under the lock so we merge onto other writers' saves.
+ # Fails closed if the on-disk file exists but can't be trusted.
+ self._reload_under_lock()
+ try:
+ # Replace-on-collision. An add_id that is ALREADY live is either
+ # an idempotent re-add OR — critically — a REUSED DocumentChunk.id
+ # whose prior row was rolled back: SQLite recycles AUTOINCREMENT
+ # ids on ROLLBACK, so a failed index() commit can leave a stale
+ # orphan vector under an id that a later, unrelated chunk then
+ # reuses. Either way the NEW vector must win, so every colliding
+ # live id is removed along with remove_ids BEFORE the add.
+ effective_remove = list(remove_ids)
+ if add_ids:
+ live_now = set(self._live_ids_unlocked())
+ effective_remove.extend(
+ i for i in dict.fromkeys(add_ids) if i in live_now
+ )
+
+ if not effective_remove:
+ removed = 0
+ elif self.supports_delete:
+ removed = self.delete(effective_remove)
+ else:
+ removed = self._rebuild_dropping(effective_remove)
+
+ added = 0
+ if add_ids:
+ checked_vectors = self._require_add_vectors(add_vectors)
+ ids, vecs = (
+ self._dedup_new(add_ids, checked_vectors)
+ if dedup
+ else (add_ids, checked_vectors)
+ )
+ if ids:
+ self.add(ids, vecs)
+ added = len(ids)
+
+ # Atomic save + integrity record, both under the same lock so a
+ # concurrent writer can't slip bytes between them (#4197).
+ self.persist(path)
+ self._record_integrity()
+ except Exception:
+ # delete()/add() mutate self._index in place before persist; if
+ # anything after the reload raised, resync in-memory state to the
+ # durable file so search()/count() can't disagree with disk.
+ self._restore_from_disk()
+ raise
+ self._poisoned = False
+ return {"added": added, "removed": removed}
+
+ def _apply_hnsw(
+ self,
+ add_ids: List[int],
+ add_vectors: Optional[np.ndarray],
+ remove_ids: List[int],
+ dedup: bool,
+ _attempts: int = 3,
+ ) -> dict:
+ """Apply for HNSW (which has no in-place ``remove_ids``).
+
+ A pure add goes in-place under the lock (cheap — O(added)). A removal or
+ id-collision forces a full graph rebuild; that expensive rebuild runs
+ OFF the write lock from a locked snapshot, then is swapped in under a
+ short lock only if no concurrent write happened meanwhile (version
+ check). On a race it retries, then falls back to a fully-locked rebuild.
+ So concurrent search() blocks only for the fast snapshot + the swap,
+ not the whole O(collection) graph build.
+ """
+ # apply() already required a persistence binding before dispatching
+ # here (path + lock not None) -- narrow the Optionals once, locally,
+ # so mypy sees the same invariant across both phases below.
+ lock = self._lock
+ path = self._path
+ if lock is None or path is None:
+ raise RuntimeError(
+ "FaissVectorStore._apply_hnsw() requires a persistence "
+ "binding (path + lock); apply() should have already "
+ "validated this before dispatching here"
+ )
+ # ---- Phase 1: snapshot under the lock (reconstruct is O(N) but fast) --
+ with lock:
+ self._reload_under_lock()
+ live = set(self._live_ids_unlocked())
+ # A live add id is a collision that must be REPLACED, so treat it as
+ # a removal — the rebuild then re-adds it with the NEW vector.
+ remove_set = (
+ {int(i) for i in remove_ids} | {i for i in add_ids if i in live}
+ ) & live
+
+ if not remove_set:
+ # No structural change -> cheap in-place add under the lock.
+ try:
+ added = 0
+ if add_ids:
+ checked_vectors = self._require_add_vectors(add_vectors)
+ ids, vecs = (
+ self._dedup_new(add_ids, checked_vectors)
+ if dedup
+ else (add_ids, checked_vectors)
+ )
+ if ids:
+ self.add(ids, vecs)
+ added = len(ids)
+ self.persist(path)
+ self._record_integrity()
+ except Exception:
+ self._restore_from_disk()
+ raise
+ self._poisoned = False
+ return {"added": added, "removed": 0}
+
+ keep = [i for i in live if i not in remove_set]
+ removed = len(remove_set)
+ keep_vecs = np.empty((len(keep), self.dimension), dtype="float32")
+ for row, vid in enumerate(keep):
+ keep_vecs[row] = self._index.reconstruct(int(vid))
+ # New adds: within-batch dedup + normalize NOW so Phase 2 is a pure
+ # faiss build. Collisions were pulled out of `keep`, so re-adding
+ # them here gives the new vector; brand-new ids weren't live.
+ new_ids: List[int] = []
+ new_vecs = np.empty((0, self.dimension), dtype="float32")
+ if add_ids:
+ seen: set = set()
+ rows: List[int] = []
+ for row, vid in enumerate(add_ids):
+ if vid in seen:
+ continue
+ seen.add(vid)
+ rows.append(row)
+ new_ids.append(vid)
+ if rows:
+ new_vecs = self._prepare(np.asarray(add_vectors)[rows])
+ # Per-FILE staleness token (shared across instances) — NOT a
+ # per-instance counter, which a concurrent writer's separate store
+ # object would never touch. See _file_fingerprint.
+ fingerprint = self._file_fingerprint()
+
+ # ---- Phase 2: build the new graph OFF the lock (the expensive part) --
+ final_ids = list(keep) + list(new_ids)
+ base = self._build_base_index(
+ self.dimension, self.index_type, self.metric
+ )
+ new_index = IndexIDMap2(base)
+ if final_ids:
+ final_vecs = (
+ np.vstack([keep_vecs, new_vecs]) if len(new_ids) else keep_vecs
+ )
+ new_index.add_with_ids(
+ final_vecs, np.asarray(final_ids, dtype="int64")
+ )
+
+ # ---- Phase 3: swap under a short lock iff the FILE is unchanged ------
+ with lock:
+ stale = self._file_fingerprint() != fingerprint
+ if not stale:
+ try:
+ self._index = new_index
+ self.persist(path)
+ self._record_integrity()
+ except Exception:
+ self._restore_from_disk()
+ raise
+ self._poisoned = False
+
+ # Fallback runs OUTSIDE the lock — self._lock is a non-reentrant
+ # threading.Lock, so _apply_hnsw/_apply_locked (which re-acquire it)
+ # must not be called while it is held. A concurrent write mutated the
+ # index during our off-lock build, so the snapshot is stale: retry
+ # (bounded), then give up racing and rebuild fully locked (correct, just
+ # blocks reads for that attempt).
+ if stale:
+ if _attempts > 1:
+ logger.debug(
+ f"HNSW rebuild snapshot stale (concurrent write); "
+ f"retrying, {_attempts - 1} attempt(s) remaining"
+ )
+ return self._apply_hnsw(
+ add_ids, add_vectors, remove_ids, dedup, _attempts - 1
+ )
+ logger.warning(
+ "HNSW rebuild snapshot stale after all retries; falling "
+ "back to fully-locked rebuild"
+ )
+ return self._apply_locked(add_ids, add_vectors, remove_ids, dedup)
+ return {"added": len(new_ids), "removed": removed}
+
+ def _record_integrity(self, attempts: int = 3) -> None:
+ """Record the persisted file's integrity checksum, with retries.
+
+ A transient failure here (e.g. a DB hiccup) after a successful
+ ``persist()`` would leave the file valid but its checksum stale — and
+ the next reload would then fail closed forever. Retrying makes that
+ unlikely; if it still fails, we raise so the caller rolls back the DB
+ txn and the service pre-flight quarantines + rebuilds (its recovery),
+ rather than silently leaving DB rows pointing at an unverifiable file.
+ """
+ if self._integrity_record is None:
+ return
+ # Only called from apply()'s write paths, which already required a
+ # persistence binding (path + lock not None) before dispatching here.
+ path = self._path
+ if path is None:
+ raise RuntimeError(
+ "FaissVectorStore._record_integrity() requires self._path "
+ "to be set; only called from apply()'s write paths"
+ )
+ last: Optional[Exception] = None
+ for attempt in range(1, attempts + 1):
+ try:
+ self._integrity_record(path)
+ return
+ except Exception as exc: # noqa: BLE001 - retried, then re-raised
+ last = exc
+ detail = f"{type(exc).__name__}: {exc}"
+ logger.warning(
+ f"Integrity record attempt {attempt}/{attempts} failed "
+ f"({detail})" + ("; retrying" if attempt < attempts else "")
+ )
+ raise RuntimeError(
+ f"failed to record index integrity after {attempts} attempts: "
+ f"{last}"
+ ) from last
diff --git a/src/local_deep_research/vector_stores/legacy_cleanup.py b/src/local_deep_research/vector_stores/legacy_cleanup.py
new file mode 100644
index 0000000000..d6fd3cb381
--- /dev/null
+++ b/src/local_deep_research/vector_stores/legacy_cleanup.py
@@ -0,0 +1,732 @@
+"""One-time migration of legacy RAG index docstore files off disk.
+
+The previous RAG index format persisted a companion ``<hash>.pkl`` docstore next
+to each ``<hash>.faiss``. That docstore held the chunk **text** (plaintext at
+rest) plus the ``index_to_docstore_id`` map (FAISS position -> uuid) that the
+index needs. The current format stores no text in the index — text lives only in
+the encrypted DB and is rehydrated by id.
+
+This runs at startup (pure filesystem, no login / DB access). For each legacy
+``.pkl`` it:
+
+ 1. extracts ONLY the ``index_to_docstore_id`` map (position -> uuid) into a
+ small, **text-free** ``<hash>.idmap.json`` sidecar (plain JSON — no pickle,
+ no text, no metadata), then
+ 2. deletes the ``.pkl`` — removing all plaintext from disk.
+
+The per-user, login-time re-key (elsewhere) later consumes the sidecar to
+rebuild the index keyed by ``DocumentChunk.id`` (no re-embedding), then deletes
+the sidecar. If a ``.pkl`` can't be read (corrupt), it is deleted anyway
+(plaintext removed) and that collection falls back to a normal reindex.
+
+IMPORTANT: this MUST ship in the same release as the vector-store cutover.
+Before the cutover the old code still reads the ``.pkl``'s text for snippets, so
+removing it early would break search — do NOT wire this into startup until the
+old FAISS path is gone. It is exposed as a plain function so it can be called
+from tests and from the cutover's startup hook.
+"""
+
+import json
+import os
+import re
+import stat
+import tempfile
+import time
+from pathlib import Path
+from typing import Dict, List, Mapping, Tuple
+
+import numpy as np
+from faiss import (
+ IndexFlatIP,
+ IndexFlatL2,
+ IndexHNSWFlat,
+ IndexIDMap,
+ IndexIDMap2,
+ read_index,
+ vector_to_array,
+)
+from loguru import logger
+
+from ..config.paths import get_cache_directory
+from ..research_library.services.faiss_safe_load import (
+ load_index_to_docstore_id,
+)
+
+_RAG_CACHE_SUBDIR = "rag_indices"
+_SIDECAR_SUFFIX = ".idmap.json"
+# Only sweep sidecar ``.tmp`` files older than this — long enough that no single
+# write is still in flight, so a concurrent (multi-process) phase-1 run's temp is
+# never mistaken for an orphan. Mirrors faiss_store._STALE_TMP_AGE_SECONDS.
+_STALE_TMP_AGE_SECONDS = 3600
+
+# A legitimate docstore key is a ``uuid.uuid4().hex`` (32 hex chars, what
+# _store_chunks_to_db writes); accept the dashed uuid form too. Anything else in
+# a (tampered) ``.pkl`` — arbitrary text, whitespace — is rejected so it can
+# never be smuggled into the "text-free" sidecar.
+_ID_RE = re.compile(
+ r"[0-9a-f]{32}"
+ r"|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
+ re.IGNORECASE,
+)
+# Anchored so a crafted name like ``x.pkl.corrupt-1.idmap.json`` is NOT matched.
+_QUARANTINE_RE = re.compile(r"\.pkl\.corrupt-[0-9-]+$")
+
+
+def _rag_cache_root() -> Path:
+ return get_cache_directory() / _RAG_CACHE_SUBDIR
+
+
+def _is_live_pkl(path: Path) -> bool:
+ """A live legacy docstore ``<hash>.pkl`` (has a re-keyable sibling index)."""
+ return path.is_file() and path.name.endswith(".pkl")
+
+
+def _is_quarantined_pkl(path: Path) -> bool:
+ """A quarantined docstore ``<hash>.pkl.corrupt-<ns>`` (dead, no sidecar)."""
+ return path.is_file() and _QUARANTINE_RE.search(path.name) is not None
+
+
+def _sidecar_for(pkl_path: Path) -> Path:
+ # <hash>.pkl -> <hash>.idmap.json
+ return pkl_path.with_name(pkl_path.stem + _SIDECAR_SUFFIX)
+
+
+def _find_legacy_docstores(root: Path) -> Tuple[List[Path], List[str]]:
+ """Return ``(found_docstores, unscannable_dirs)``.
+
+ A non-empty ``unscannable_dirs`` means ``os.walk`` could not read a
+ directory, so a plaintext ``.pkl`` inside it may survive UNDETECTED — the
+ caller must treat that as an INCOMPLETE migration, not clean success (a
+ re-scan is blind to the very same unreadable directory)."""
+ if not root.exists():
+ return [], []
+
+ scan_errors: List[str] = []
+
+ def _onerror(exc: OSError) -> None:
+ # os.walk (like rglob) SILENTLY skips a directory it can't scan. This
+ # migration's whole guarantee is "no plaintext .pkl left on disk", so a
+ # scan error must be LOUD and must fail the completeness check —
+ # otherwise an unreadable subdir could hide an un-deleted .pkl while the
+ # run reports clean success.
+ target = getattr(exc, "filename", "?")
+ scan_errors.append(str(target))
+ logger.error(
+ "RAG plaintext migration could not scan "
+ f"{target} ({exc}); a legacy .pkl there may "
+ "NOT have been removed — fix permissions and re-run, or delete it "
+ "manually."
+ )
+
+ found: List[Path] = []
+ for dirpath, dirs, files in os.walk(str(root), onerror=_onerror):
+ # os.walk does NOT descend into symlinked subdirectories
+ # (followlinks=False) and does NOT call onerror for them — they are
+ # silently skipped. A legacy .pkl inside one would survive undetected,
+ # so flag each symlinked subdir as unscanned (same as a permission
+ # error) rather than miss it. followlinks=True is avoided deliberately:
+ # a symlink cycle would hang the migration.
+ for d in dirs:
+ sub = Path(dirpath) / d
+ # A stat error (PermissionError, etc.) on a SINGLE entry must never
+ # abort the whole walk — that would leave EVERY .pkl on disk while
+ # the caller logs "migration failed". Flag the entry and keep going.
+ try:
+ is_link = sub.is_symlink()
+ except OSError:
+ scan_errors.append(str(sub))
+ logger.exception(
+ f"RAG plaintext migration could not stat directory {sub}; "
+ "a legacy .pkl there may NOT have been removed."
+ )
+ continue
+ if is_link:
+ scan_errors.append(str(sub))
+ logger.error(
+ "RAG plaintext migration did not descend into symlinked "
+ f"directory {sub}; a legacy .pkl inside may NOT have been "
+ "removed — replace the symlink with a real directory and "
+ "re-run, or delete the .pkl manually."
+ )
+ for name in files:
+ p = Path(dirpath) / name
+ try:
+ is_pkl = _is_live_pkl(p) or _is_quarantined_pkl(p)
+ except OSError:
+ scan_errors.append(str(p))
+ logger.exception(
+ f"RAG plaintext migration could not stat file {p}; "
+ "a legacy .pkl there may NOT have been removed."
+ )
+ continue
+ if is_pkl:
+ # A symlinked .pkl is a trap: _is_*_pkl / is_file() follow the
+ # link, so it looks migratable, but _delete_file's unlink()
+ # removes only the symlink — the real plaintext file it points
+ # to (potentially OUTSIDE the cache root) survives untouched
+ # while the run logs clean success. Don't follow it: flag it as
+ # unresolved (incomplete migration) so an operator removes the
+ # real file. We deliberately do NOT auto-delete the target — it
+ # can be an arbitrary path we must not unlink blindly. A stat
+ # error here is treated as "can't tell" -> unresolved.
+ try:
+ is_link = p.is_symlink()
+ except OSError:
+ is_link = True
+ if is_link:
+ scan_errors.append(str(p))
+ logger.error(
+ f"RAG plaintext migration found a SYMLINKED (or "
+ f"un-statable) docstore {p}; deleting the link would "
+ "leave the real plaintext file intact. Remove the real "
+ "target manually, then re-run."
+ )
+ continue
+ found.append(p)
+ return sorted(found), scan_errors
+
+
+def _delete_file(path: Path) -> None:
+ """Delete ``path`` cross-platform (Windows + POSIX).
+
+ Windows raises ``PermissionError`` when a file carries the read-only
+ attribute; clear it and retry once. On POSIX ``unlink`` succeeds even while a
+ file is open. A still-failing delete propagates to the caller, which records
+ it — the re-scan then reports it.
+ """
+ try:
+ path.unlink()
+ return
+ except FileNotFoundError:
+ return
+ except PermissionError:
+ pass
+ try:
+ os.chmod(path, stat.S_IWRITE | stat.S_IREAD)
+ except OSError:
+ pass
+ path.unlink()
+
+
+def _write_sidecar_atomic(sidecar: Path, id_map: Dict[str, str]) -> None:
+ """Atomically write the text-free position->uuid map as JSON."""
+ sidecar.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ sidecar.parent.chmod(0o700)
+ except OSError:
+ logger.warning(f"Could not chmod {sidecar.parent} to 0o700")
+ # Sweep stale sidecar temps from a previously hard-killed migration. Phase-1
+ # normally runs single-threaded at startup, but under a multi-process server
+ # (gunicorn -w N) two workers can start it concurrently — only sweep temps
+ # OLDER than a generous threshold so a concurrent worker's just-created,
+ # still-in-flight temp for the same sidecar is never mistaken for an orphan
+ # and unlinked (which would crash its write). Mirrors FaissVectorStore.persist.
+ now = time.time()
+ for stale in sidecar.parent.glob(f"{sidecar.name}.*.tmp"):
+ try:
+ if now - stale.stat().st_mtime < _STALE_TMP_AGE_SECONDS:
+ continue
+ stale.unlink()
+ except OSError:
+ logger.warning(f"Could not remove stale sidecar temp {stale}")
+ # Safe: this writes only the text-free ``.idmap.json`` sidecar — a plain
+ # position->uuid JSON map (see module docstring / `_ID_RE`), never chunk
+ # text/metadata. Not sensitive data at rest.
+ fd, tmp_name = tempfile.mkstemp(
+ dir=str(sidecar.parent), prefix=f"{sidecar.name}.", suffix=".tmp"
+ )
+ tmp = Path(tmp_name)
+ try:
+ # Safe: same text-free id-map as above, written via the fd from
+ # mkstemp — no chunk text/metadata ever passes through this path.
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ json.dump(id_map, f)
+ f.flush()
+ os.fsync(
+ f.fileno()
+ ) # durable before the rename (crash-consistency)
+ os.replace(tmp, sidecar)
+ # fsync the directory so the rename itself survives a crash (mirrors
+ # FaissVectorStore.persist); unsupported on some platforms.
+ try:
+ dir_fd = os.open(str(sidecar.parent), os.O_RDONLY)
+ try:
+ os.fsync(dir_fd)
+ finally:
+ os.close(dir_fd)
+ except OSError:
+ pass
+ finally:
+ if tmp.exists():
+ try:
+ tmp.unlink()
+ except OSError:
+ logger.warning(f"Could not remove temp sidecar {tmp}")
+
+
+def _extract_map(pkl_path: Path) -> bool:
+ """Extract the text-free position->uuid map to a sidecar next to ``pkl_path``.
+
+ Returns True if the sidecar was written (so the login re-key can rebuild
+ without re-embedding). Returns False if the ``.pkl`` couldn't be read — the
+ caller still deletes the ``.pkl`` (plaintext removal is not optional) and
+ that collection will fall back to a full reindex.
+ """
+ try:
+ raw = load_index_to_docstore_id(str(pkl_path))
+ except Exception as exc:
+ logger.warning(
+ f"Could not read legacy docstore {pkl_path} "
+ f"({type(exc).__name__}); that collection will reindex"
+ )
+ return False
+ # Validate shape + content. A malformed/tampered map (non-dict, non-int
+ # positions, or non-uuid values that could smuggle text into the "text-free"
+ # sidecar) falls to the reindex fallback — it must never crash the whole
+ # migration (a DoS leaving other users' plaintext on disk) nor leak content.
+ if not isinstance(raw, dict):
+ logger.warning(
+ f"Legacy docstore {pkl_path} has an unexpected id-map shape; "
+ "that collection will reindex"
+ )
+ return False
+ id_map: Dict[str, str] = {}
+ for pos, key in raw.items():
+ # Require key to be a real str and match it DIRECTLY (never str(key)).
+ # A tampered .pkl can put an arbitrary unpickled object here; calling
+ # str() on a maliciously deep/shared nested structure is a pickle
+ # "billion laughs" amplification that can hang/OOM the whole startup
+ # migration. A legitimate index_to_docstore_id value is always a uuid
+ # string, so a non-str (or non-uuid) value is simply rejected to the
+ # reindex fallback — it can never reach str().
+ # pos must be a plausible faiss array position. Bounding it also stops
+ # str(pos) below from raising ValueError on a maliciously huge int
+ # (Python's int->str digit limit), which would otherwise escape this
+ # loop uncaught and abort the whole startup migration — leaving other
+ # users' plaintext .pkl files on disk. bool is an int subclass; the
+ # range check harmlessly admits True/False (1/0), rejected downstream.
+ if (
+ not isinstance(pos, int)
+ or isinstance(pos, bool) # bool is an int subclass; True/False
+ # would serialize as "True"/"False" and never match a str(pos)
+ # lookup at rekey time, silently orphaning that chunk's vector.
+ or not (0 <= pos < 2**31)
+ or not isinstance(key, str)
+ or not _ID_RE.fullmatch(key)
+ ):
+ logger.warning(
+ f"Legacy docstore {pkl_path} has an unexpected id-map entry; "
+ "that collection will reindex"
+ )
+ return False
+ id_map[str(pos)] = key
+ try:
+ _write_sidecar_atomic(_sidecar_for(pkl_path), id_map)
+ except OSError:
+ logger.exception(
+ f"Could not write id-map sidecar for {pkl_path}; that "
+ "collection will reindex"
+ )
+ return False
+ return True
+
+
+def migrate_legacy_docstores() -> Dict[str, int]:
+ """Extract each legacy ``.pkl``'s id-map to a text-free sidecar, then delete
+ the ``.pkl``, removing all plaintext docstores from disk.
+
+ Returns ``{"found", "extracted", "deleted", "reindex_fallback",
+ "remaining"}``. Re-scans afterward and logs a prominent error recommending
+ manual deletion if any docstore remains — plaintext must never pass
+ silently. Idempotent (a clean tree is a no-op).
+ """
+ root = _rag_cache_root()
+ # SECURITY: refuse to operate on a SYMLINKED cache root. os.walk (and
+ # Path.chmod below) follow a symlinked TOP-LEVEL path unconditionally —
+ # followlinks=False only guards descent into symlinked CHILDREN found
+ # mid-walk (which _find_legacy_docstores already flags). A symlinked
+ # rag_indices/ would otherwise make this migration chmod 0o700 and
+ # pattern-delete .pkl files OUTSIDE the intended tree (an admin who
+ # symlinked the cache onto a bigger volume, or a hostile account that can
+ # write the cache parent), reporting clean success. Treat it exactly like a
+ # symlinked subdir: log loudly and refuse rather than following it. Uses
+ # is_symlink() (an lstat, does NOT follow) so it is safe to call first.
+ if root.is_symlink():
+ logger.error(
+ f"RAG cache root {root} is a symlink; refusing to migrate through "
+ "it (following it would chmod/delete files outside the intended "
+ "cache tree). Replace it with a real directory and restart."
+ )
+ return {
+ "found": 0,
+ "extracted": 0,
+ "deleted": 0,
+ "reindex_fallback": 0,
+ "remaining": 0,
+ "scan_errors": 1,
+ }
+ # Harden the RAG cache ROOT at the earliest point it is touched so another
+ # local OS account can't traverse into any user's vector caches. Both the
+ # leaf-only chmod in _write_sidecar_atomic and _get_index_path otherwise
+ # leave the root at the process umask (typically world-traversable) between
+ # startup and the first index op.
+ if root.exists():
+ try:
+ root.chmod(0o700)
+ except OSError:
+ logger.warning(f"Could not chmod RAG cache root {root} to 0o700")
+ found, scan_errors = _find_legacy_docstores(root)
+ if not found and not scan_errors:
+ logger.debug(f"RAG cache: no legacy docstore files under {root}")
+ return {
+ "found": 0,
+ "extracted": 0,
+ "deleted": 0,
+ "reindex_fallback": 0,
+ "remaining": 0,
+ "scan_errors": 0,
+ }
+
+ extracted = 0
+ deleted = 0
+ reindex_fallback = 0
+ for pkl in found:
+ # Live .pkl: preserve the re-key map before deleting. Quarantined
+ # (.pkl.corrupt-*): dead — just delete, no sidecar.
+ if _is_live_pkl(pkl):
+ if _extract_map(pkl):
+ extracted += 1
+ else:
+ reindex_fallback += 1
+ try:
+ _delete_file(pkl)
+ deleted += 1
+ except OSError:
+ logger.exception(f"RAG cache: could not delete {pkl}")
+
+ # Re-scan is the source of truth (partial failures, POSIX unlink-of-open).
+ # A scan error is NOT clean success: an unreadable directory hides its
+ # contents from BOTH the delete pass above and this re-scan, so a plaintext
+ # .pkl inside it could survive while `remaining` reads empty. Treat any
+ # unscannable dir as an unresolved leftover.
+ remaining, rescan_errors = _find_legacy_docstores(root)
+ if remaining or rescan_errors:
+ parts = []
+ if remaining:
+ parts.append(
+ f"{len(remaining)} legacy docstore file(s) remain on disk: "
+ + ", ".join(str(p) for p in remaining)
+ )
+ if rescan_errors:
+ parts.append(
+ f"{len(rescan_errors)} director(ies) could not be scanned "
+ "(a plaintext .pkl inside may NOT have been removed): "
+ + ", ".join(rescan_errors)
+ )
+ logger.error(
+ "RAG cache: plaintext migration did NOT complete cleanly — "
+ + "; ".join(parts)
+ + ". Fix permissions and re-run, or delete the file(s) manually."
+ )
+ else:
+ logger.info(
+ f"RAG cache: extracted {extracted} id-map(s), removed {deleted} "
+ f"legacy docstore file(s) from {root}"
+ + (
+ f" ({reindex_fallback} unreadable -> will reindex)"
+ if reindex_fallback
+ else ""
+ )
+ )
+ return {
+ "found": len(found),
+ "extracted": extracted,
+ "deleted": deleted,
+ "reindex_fallback": reindex_fallback,
+ "remaining": len(remaining),
+ "scan_errors": len(rescan_errors),
+ }
+
+
+def rekey_index_file(
+ faiss_path: Path,
+ sidecar_path: Path,
+ uuid_to_id: Mapping[str, int],
+ *,
+ dimension: int,
+ index_type: str,
+ metric: str,
+ normalize: bool,
+) -> Dict[str, int]:
+ """Convert one old-format index to the new ``IndexIDMap2`` keyed by int id,
+ WITHOUT re-embedding — the login-time (phase-2) half of the migration.
+
+ Reads the raw old ``.faiss`` (reconstructs each vector by position), maps
+ position -> uuid (from the ``.idmap.json`` sidecar) -> int ``DocumentChunk.id``
+ (via ``uuid_to_id``), builds a fresh ``IndexIDMap2`` keyed by those ints,
+ writes it atomically over ``faiss_path``, and **reads it back and verifies**.
+ Positions whose uuid has no DB row are orphans and are dropped.
+
+ Does NOT delete the sidecar (nor acquire the write lock, nor re-record file
+ integrity) — the caller owns all three. The caller deletes the sidecar ONLY
+ after recording the new file's integrity, so a crash/failure between persist
+ and integrity-record leaves the sidecar as a retry signal; the ``IndexIDMap2``
+ guard above then makes that retry a clean no-op. Raises on a failed read-back
+ verification (the caller quarantines + falls back to a normal reindex).
+ """
+ # Import here to avoid a module-load cycle (implementations import base only).
+ from .implementations.faiss_store import FaissVectorStore
+
+ faiss_path = Path(faiss_path)
+ sidecar_path = Path(sidecar_path)
+
+ old = read_index(str(faiss_path))
+
+ # Crash-consistency guard. rekey persists the new IndexIDMap2 (atomic
+ # replace) and only unlinks the sidecar AFTER a successful read-back verify.
+ # If the process dies in that window, faiss_path is ALREADY the new format
+ # but the sidecar survives, so the next login re-enters here on an
+ # already-migrated file. Running the reconstruct path below on an
+ # IndexIDMap2 is not merely wrong — reconstruct_n(0, ntotal) would treat
+ # 0..ntotal-1 as *ids* to look up; a missing id raises a C++ faiss
+ # exception that SWIG does NOT surface as a catchable Python exception on
+ # this call path, aborting the whole process (and, if the int ids happen to
+ # fall in 0..ntotal-1, silently reconstructing the WRONG vectors instead).
+ # Either way the re-key is already done — report success WITHOUT deleting
+ # the sidecar. The CALLER owns sidecar deletion (only after it has recorded
+ # file integrity), so an interrupted prior run that persisted the new index
+ # but hadn't yet recorded integrity is recoverable: this re-entry succeeds,
+ # the caller (re)records integrity, THEN drops the sidecar. Deleting it here
+ # would lose that retry signal.
+ if isinstance(old, IndexIDMap2):
+ # Same dimension guard the fresh re-key path enforces below: an
+ # already-migrated index whose width no longer matches the configured
+ # embedding model (model changed post-migration) must be rebuilt, not
+ # silently accepted. Raise so the caller quarantines + reindexes now,
+ # rather than deferring to an opaque dimension failure at first search.
+ if old.d != dimension:
+ raise ValueError(
+ f"rekey {faiss_path}: already-migrated index dim {old.d} != "
+ f"expected {dimension} (embedding model changed) — reindex"
+ )
+ # Cross-check the on-disk ids against what the CURRENT sidecar + DB
+ # resolution says they should be — the fresh path below does this via a
+ # read-back verify; this short-circuit must too. Without it, a stale or
+ # FOREIGN IndexIDMap2 sitting at this path (e.g. two collections/users
+ # colliding on the pre-per-user-scoping shared cache path, or a retry
+ # after the uuid->id resolution changed) would be silently adopted, and
+ # its baked-in ids would rehydrate the WRONG document's text on search.
+ try:
+ pos_to_uuid = json.loads(sidecar_path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ # The sidecar is the caller's COMPLETION SIGNAL: it is deleted only
+ # AFTER a successful re-key records the new index's integrity (see
+ # rekey_user_indexes Phase B). A concurrent worker — another process
+ # (gunicorn -w N / the scheduler) with no cross-process mutex, or a
+ # thread whose sidecar check passed before that worker won the lock —
+ # can finalize and delete it between our caller's sidecar check and
+ # this read. A missing sidecar next to an already-IndexIDMap2 file of
+ # the right dimension therefore means "already finalized by another
+ # worker" — the SAME signature rekey_user_indexes treats as done at
+ # its top-of-loop no-sidecar branch (skipped_no_sidecar). Report
+ # success rather than letting the FileNotFoundError bubble up and
+ # QUARANTINE a healthy, just-rekeyed index (forcing a needless full
+ # re-embed). No id cross-check: there is no sidecar left to check
+ # against, exactly as the caller's no-sidecar branch also skips it.
+ logger.info(
+ f"Re-key skipped for {faiss_path.name}: already migrated to "
+ "IndexIDMap2; its sidecar was removed by a concurrent finalizer"
+ )
+ return {
+ "reconstructed": int(old.ntotal),
+ "kept": int(old.ntotal),
+ "orphaned": 0,
+ }
+ expected_ids = {
+ int(uuid_to_id[u]) for u in pos_to_uuid.values() if u in uuid_to_id
+ }
+ on_disk_id_list = (
+ vector_to_array(old.id_map).astype("int64").tolist()
+ if old.ntotal
+ else []
+ )
+ # Multiplicity, not just membership: a duplicate id (e.g. [5, 5, 6, 7])
+ # has the SAME set as {5, 6, 7}, so the set comparison below cannot see
+ # it (sets dedupe) — exactly the corruption the fresh-build path rejects
+ # at ``len(set(kept_ids)) != len(kept_ids)``. A duplicate baked into an
+ # already-migrated IndexIDMap2 double-counts/mis-scores that chunk in
+ # search, so reject it here too rather than silently adopt it.
+ if len(set(on_disk_id_list)) != len(on_disk_id_list):
+ raise ValueError(
+ f"rekey {faiss_path}: already-migrated index has duplicate "
+ "DocumentChunk.id(s) — refusing to adopt an id-collided index; "
+ "quarantine + reindex"
+ )
+ if set(on_disk_id_list) != expected_ids:
+ raise ValueError(
+ f"rekey {faiss_path}: already-migrated index ids do not match "
+ "the sidecar/DB resolution — refusing to adopt a stale/foreign "
+ "index; quarantine + reindex"
+ )
+ logger.info(
+ f"Re-key skipped for {faiss_path.name}: already migrated to "
+ "IndexIDMap2 (interrupted prior run — caller will finalize)"
+ )
+ return {
+ "reconstructed": int(old.ntotal),
+ "kept": int(old.ntotal),
+ "orphaned": 0,
+ }
+
+ # The crash hazard is the WHOLE IndexIDMap family, not just IndexIDMap2:
+ # reconstruct_n on a plain IndexIDMap (our own format's superclass) also
+ # raises an untranslated C++ faiss exception that aborts the process
+ # (SIGABRT), bypassing every try/except. A plain IndexIDMap is never a
+ # format we write (we only ever persist IndexIDMap2) nor the pre-migration
+ # raw base index we mean to reconstruct here — so it is foreign/corrupt.
+ # Raise a CATCHABLE ValueError so the caller quarantines + reindexes,
+ # instead of falling through to the process-killing reconstruct_n below.
+ if isinstance(old, IndexIDMap):
+ raise ValueError(
+ f"rekey {faiss_path}: on-disk index is {type(old).__name__} "
+ "(IndexIDMap family but not IndexIDMap2) — refusing to reconstruct "
+ "a foreign/corrupt index; quarantine + reindex instead"
+ )
+
+ # Positive whitelist. The IndexIDMap guard above is only one of MANY faiss
+ # classes that abort the process on reconstruct_n: any index type that isn't
+ # a plain reconstruct-safe base index (e.g. a corrupt/tampered/foreign file
+ # that happens to decode as IndexIVFPQFastScan) segfaults at reconstruct_n
+ # below — an untranslated C++ abort that bypasses the caller's try/except
+ # and, on the login-time rekey path, crash-loops the worker. Only the base
+ # classes _build_base_index actually produces are reconstruct-safe here;
+ # reject anything else with a CATCHABLE ValueError so the caller quarantines
+ # + reindexes.
+ if not isinstance(old, (IndexFlatL2, IndexFlatIP, IndexHNSWFlat)):
+ raise ValueError(
+ f"rekey {faiss_path}: on-disk index is {type(old).__name__}, not a "
+ "reconstruct-safe base index (IndexFlatL2/IndexFlatIP/IndexHNSWFlat)"
+ " — refusing a foreign/corrupt index; quarantine + reindex instead"
+ )
+
+ ntotal = int(old.ntotal)
+ if old.d != dimension:
+ raise ValueError(
+ f"rekey {faiss_path}: index dim {old.d} != expected {dimension}"
+ )
+
+ try:
+ pos_to_uuid = json.loads(sidecar_path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ # A concurrent worker (multi-process: gunicorn -w N / the scheduler,
+ # with no cross-process lock) may have finished re-keying this SAME
+ # index between our read_index() above and this read — persisting a new
+ # IndexIDMap2 and deleting the sidecar as its completion signal
+ # (legacy_rekey Phase B, which persists the new index BEFORE unlinking
+ # the sidecar). Re-read the on-disk file: if it is now an IndexIDMap2 of
+ # the right dimension, the migration is already done, so report success
+ # rather than letting FileNotFoundError bubble up — the caller treats
+ # that as un-rekeyable and QUARANTINES a perfectly good, just-migrated
+ # index (forcing a needless full re-embed). Only if the file is still
+ # NOT migrated (a genuinely missing sidecar next to an old-format file)
+ # do we re-raise so the caller quarantines. This mirrors the
+ # already-migrated short-circuit's own FileNotFoundError handling above.
+ now_on_disk = None
+ try:
+ now_on_disk = read_index(str(faiss_path))
+ except Exception:
+ # Probe only: a failed/partial read just means "not a valid
+ # migrated index yet" — now_on_disk stays None and we re-raise the
+ # original FileNotFoundError below.
+ logger.debug(
+ f"Concurrent-migration re-read probe failed for {faiss_path.name}"
+ )
+ if isinstance(now_on_disk, IndexIDMap2) and now_on_disk.d == dimension:
+ logger.info(
+ f"Re-key skipped for {faiss_path.name}: a concurrent worker "
+ "migrated it (sidecar already removed)"
+ )
+ return {
+ "reconstructed": int(now_on_disk.ntotal),
+ "kept": int(now_on_disk.ntotal),
+ "orphaned": 0,
+ }
+ raise
+
+ # Reconstruct ALL vectors by position in one bounded call. reconstruct_n only
+ # touches positions 0..ntotal-1, avoiding the out-of-range garbage that a
+ # hand-rolled reconstruct(i) loop risks (faiss #4413).
+ if ntotal:
+ vectors = np.asarray(old.reconstruct_n(0, ntotal), dtype="float32")
+ else:
+ vectors = np.empty((0, dimension), dtype="float32")
+
+ kept_ids: List[int] = []
+ kept_rows: List[int] = []
+ orphaned = 0
+ for pos in range(ntotal):
+ uid = pos_to_uuid.get(str(pos))
+ int_id = uuid_to_id.get(uid) if uid is not None else None
+ if int_id is None:
+ orphaned += 1
+ continue
+ kept_ids.append(int(int_id))
+ kept_rows.append(pos)
+
+ # Two legacy positions must never map to the SAME DocumentChunk.id: that
+ # would bake a duplicate id into the IndexIDMap2 (which tolerates dupes),
+ # producing phantom, mis-scored search hits — and the set()-based read-back
+ # verify below cannot see it (sets dedupe). A duplicate means the sidecar /
+ # uuid->id resolution is inconsistent, so refuse and let the caller
+ # quarantine + reindex cleanly from the DB rather than persist corruption.
+ if len(set(kept_ids)) != len(kept_ids):
+ raise ValueError(
+ f"rekey {faiss_path}: {len(kept_ids) - len(set(kept_ids))} duplicate "
+ "DocumentChunk.id(s) from the legacy id-map — refusing to persist an "
+ "id-collided index; quarantine + reindex instead"
+ )
+
+ kept_vecs = (
+ vectors[kept_rows]
+ if kept_rows
+ else np.empty((0, dimension), dtype="float32")
+ )
+
+ store = FaissVectorStore.create(
+ dimension=dimension,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+ if kept_ids:
+ store.add(kept_ids, kept_vecs)
+ store.persist(faiss_path) # atomic temp + os.replace
+
+ # Read-back verify BEFORE removing the sidecar (the only remaining re-key
+ # input): the new file must load as IndexIDMap2 with exactly the kept ids.
+ verify = FaissVectorStore.load(
+ faiss_path,
+ dimension=dimension,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+ if set(verify.live_ids()) != set(kept_ids):
+ raise RuntimeError(
+ f"rekey {faiss_path}: read-back verify failed "
+ f"({verify.count()} ids on disk != {len(kept_ids)} expected)"
+ )
+
+ # NOTE: the sidecar is deliberately NOT deleted here. The caller deletes it
+ # ONLY after it has recorded the new file's integrity, so a crash/failure
+ # between persist and integrity-record leaves the sidecar as a retry signal
+ # (the IndexIDMap2 guard at the top makes the retry a clean no-op re-key).
+ logger.info(
+ f"Re-keyed {faiss_path.name}: {len(kept_ids)} vectors "
+ f"({orphaned} orphaned, {ntotal} reconstructed)"
+ )
+ return {
+ "reconstructed": ntotal,
+ "kept": len(kept_ids),
+ "orphaned": orphaned,
+ }
diff --git a/src/local_deep_research/vector_stores/legacy_rekey.py b/src/local_deep_research/vector_stores/legacy_rekey.py
new file mode 100644
index 0000000000..c4834673d9
--- /dev/null
+++ b/src/local_deep_research/vector_stores/legacy_rekey.py
@@ -0,0 +1,587 @@
+"""Login-time (phase-2) re-key of legacy RAG indices -- the per-user half of
+the vector-store cutover.
+
+``migrate_legacy_docstores`` (phase 1, ``legacy_cleanup.py``) runs once at
+server startup and turns each legacy ``<hash>.pkl`` docstore into a small,
+text-free ``<hash>.idmap.json`` sidecar (FAISS position -> uuid), deleting the
+plaintext ``.pkl``. It cannot go further: rebuilding the index keyed by
+``DocumentChunk.id`` needs the per-user encrypted DB (to resolve uuid ->
+``DocumentChunk.id``), which is only available once a user has logged in.
+
+This module is that second half. ``rekey_user_indexes`` is called once per
+user at login time (from ``database/encrypted_db.py``
+``_open_user_database_cold``, AFTER the user's DB connection is already
+cached -- see that function's docstring for why it must run there and not
+earlier). For each of the user's ``RAGIndex`` rows whose on-disk ``.faiss``
+still has a sidecar (i.e. phase 1 ran but phase 2 hasn't), it resolves
+``uuid -> DocumentChunk.id`` from the DB, re-keys the index in place via
+``legacy_cleanup.rekey_index_file`` (no re-embedding), and re-records file
+integrity. Any single index that fails is quarantined (moved aside) and its
+collection's indexed state is reset so the normal indexing path rebuilds it
+from scratch -- one bad index never blocks the rest of the user's indices,
+and this whole step never blocks login (the caller wraps it in try/except).
+
+Gated behind a one-time per-user settings marker
+(``research_library.rag_index_rekeyed_v2``) so this is a single
+``get_setting`` call (fast no-op) on every login after the first successful
+run, and for every user who has no legacy sidecars at all -- the common case
+once the fleet has passed through the cutover once.
+"""
+
+import json
+import time
+from pathlib import Path
+from typing import Dict, Iterable, List, Optional, cast
+
+from loguru import logger
+
+from ..database.models.library import (
+ DocumentChunk,
+ DocumentCollection,
+ RAGIndex,
+ RagDocumentStatus,
+)
+from ..database.session_context import get_user_db_session
+from ..security.file_integrity import FAISSIndexVerifier, FileIntegrityManager
+from ..security.log_sanitizer import redact_secrets
+from ..utilities.db_utils import get_settings_manager
+from .legacy_cleanup import rekey_index_file
+
+# Settings key gating the one-time per-user re-key. Only set after every one
+# of the user's indices has been resolved (rekeyed, skipped, or
+# quarantined) -- see ``rekey_user_indexes`` for what happens if the process
+# is killed mid-run (next login just retries the remaining sidecars).
+REKEY_MARKER_SETTING = "research_library.rag_index_rekeyed_v2"
+
+# SQLITE_MAX_VARIABLE_NUMBER is 999 on older SQLite builds; chunk the
+# embedding_id IN() lookup well below it. Mirrors ``_IN_CLAUSE_CHUNK`` in
+# research_library/notes/services/note_service.py.
+_IN_CLAUSE_CHUNK = 500
+
+_SIDECAR_SUFFIX = ".idmap.json"
+
+
+def _sidecar_for(faiss_path: Path) -> Path:
+ # <hash>.faiss -> <hash>.idmap.json (same stem as legacy_cleanup uses
+ # for <hash>.pkl -> <hash>.idmap.json, since .pkl and .faiss share a stem).
+ return faiss_path.with_name(faiss_path.stem + _SIDECAR_SUFFIX)
+
+
+def _is_idmap2(faiss_path: Path) -> Optional[bool]:
+ """``True`` iff the ``.faiss`` loads as the new ``IndexIDMap2`` format;
+ ``False`` if it loads as a DIFFERENT (old) format; ``None`` if it could NOT
+ be read at all.
+
+ Used to tell an already-migrated index (IndexIDMap2, no sidecar) apart from
+ a phase-1 reindex-fallback leftover (an OLD-format base index whose ``.pkl``
+ was deleted without writing a sidecar). The caller quarantines ONLY on a
+ definite ``False``. A ``None`` (transient IO/permission error) must NOT
+ destructively quarantine + full-re-embed a possibly-healthy index — the
+ caller withholds the marker and retries next login instead. A genuinely
+ corrupt file that keeps failing is still caught by the normal index/search
+ load-failure path, which quarantines there.
+ """
+ from faiss import IndexIDMap2, read_index
+
+ try:
+ index = read_index(str(faiss_path))
+ except Exception:
+ return None
+ return isinstance(index, IndexIDMap2)
+
+
+def _load_uuid_to_id(
+ username: str, db_password: str, uuids: Iterable[str]
+) -> Dict[str, int]:
+ """Resolve ``DocumentChunk.embedding_id`` (uuid) -> ``DocumentChunk.id``
+ (int) for the given uuids, chunking the ``IN()`` list. uuids with no
+ matching row (deleted chunks) are simply absent from the result --
+ ``rekey_index_file`` drops those positions as orphans."""
+ uuid_list = list(uuids)
+ uuid_to_id: Dict[str, int] = {}
+ with get_user_db_session(username, db_password) as session:
+ for i in range(0, len(uuid_list), _IN_CLAUSE_CHUNK):
+ batch = uuid_list[i : i + _IN_CLAUSE_CHUNK]
+ rows = (
+ session.query(DocumentChunk.embedding_id, DocumentChunk.id)
+ .filter(DocumentChunk.embedding_id.in_(batch))
+ .all()
+ )
+ uuid_to_id.update(dict(rows))
+ return uuid_to_id
+
+
+def _resolve_index_params(rag_index: RAGIndex, settings) -> Dict:
+ """RAGIndex row values win; fall back to the current ``local_search_*``
+ defaults for legacy rows that predate these columns -- mirrors the
+ default resolution in ``rag_service_factory.get_rag_service``."""
+ return {
+ "dimension": rag_index.embedding_dimension,
+ "index_type": rag_index.index_type
+ or (settings.get_setting("local_search_index_type") or "flat"),
+ "metric": rag_index.distance_metric
+ or (settings.get_setting("local_search_distance_metric") or "cosine"),
+ "normalize": (
+ rag_index.normalize_vectors
+ if rag_index.normalize_vectors is not None
+ else settings.get_bool_setting("local_search_normalize_vectors")
+ ),
+ }
+
+
+def _persist_rekeyed_config(
+ username: str, db_password: str, rag_index_id: int, params: Dict
+) -> None:
+ """Pin the config the physical file was ACTUALLY built with onto the
+ RAGIndex row.
+
+ Legacy rows predate the index_type/distance_metric/normalize_vectors
+ columns, so ``_resolve_index_params`` fills them from the live
+ ``local_search_*`` settings and ``rekey_index_file`` bakes that choice into
+ the .faiss file. If the row is left NULL, every later access re-resolves the
+ SAME settings-fallback chain — so changing a global default afterward makes
+ the runtime reinterpret the file under a different index_type/metric/
+ normalize than it was built with. Write the resolved values back (only where
+ the row is still NULL — never override an explicit stored value)."""
+ with get_user_db_session(username, db_password) as session:
+ row = session.query(RAGIndex).filter_by(id=rag_index_id).first()
+ if row is None:
+ return
+ changed = False
+ if row.index_type is None:
+ row.index_type = params["index_type"]
+ changed = True
+ if row.distance_metric is None:
+ row.distance_metric = params["metric"]
+ changed = True
+ if row.normalize_vectors is None:
+ row.normalize_vectors = params["normalize"]
+ changed = True
+ if changed:
+ session.commit()
+
+
+def _purge_redundant_pkl(faiss_path: Path, db_password: str) -> bool:
+ """Delete a legacy plaintext ``.pkl`` that has become REDUNDANT.
+
+ Once phase-1 has extracted the sidecar (or the index is already an
+ IndexIDMap2), the ``.pkl``'s chunk text lives only in the encrypted DB and
+ the id-map lives in the sidecar, so the ``.pkl`` is pure leftover plaintext.
+ Phase-1 deletes it, but that one-time unlink can fail (a directory the app
+ can't write, a read-only mount, an AV/EDR lock) AFTER the sidecar was
+ written — leaving plaintext on disk that no later step revisits once the
+ per-user completion marker is set. Callers invoke this at every phase-2
+ finalization point (re-key success, already-migrated skip) as a backstop.
+
+ Returns True if the ``.pkl`` is absent or was deleted, False if deletion
+ failed (the caller then withholds the completion marker so phase-2 retries
+ instead of gating the user out with plaintext still on disk). Deliberately
+ NOT called where a ``.pkl`` is still NEEDED (no sidecar + old-format index,
+ i.e. phase-1 hasn't converted it yet) — that case is handled separately.
+ """
+ pkl = faiss_path.with_suffix(".pkl")
+ if not pkl.exists():
+ return True
+ try:
+ pkl.unlink()
+ logger.info(f"Removed surviving legacy plaintext .pkl {pkl}")
+ return True
+ except OSError as exc:
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Could not remove surviving legacy plaintext .pkl {pkl}; "
+ "withholding re-key completion so it is retried next login: "
+ f"{safe_msg}"
+ )
+ return False
+
+
+def _quarantine_and_reset(
+ username: str,
+ db_password: str,
+ rag_index: RAGIndex,
+ faiss_path: Path,
+ sidecar_path: Path,
+ lock,
+) -> None:
+ """Move the broken index pair aside and reset the collection's indexed
+ state so the normal indexing path rebuilds it from scratch.
+
+ Mirrors ``LibraryRAGService._quarantine_corrupt_index`` +
+ ``_reset_index_state_for_rebuild`` in spirit (rename-aside, never
+ delete; clear ``RagDocumentStatus`` + ``DocumentCollection.indexed`` so
+ the next index run does real work instead of skipping everything).
+ Kept as a free function here (rather than reusing those bound methods
+ directly) so this module doesn't have to construct a full
+ ``LibraryRAGService`` -- which would pull in an embedding provider --
+ just to quarantine a broken re-key.
+
+ Raises on rename failure so the caller can log it distinctly and, in
+ turn, withhold the per-user completion marker (see
+ ``rekey_user_indexes``) so this index is retried on the next login
+ instead of being silently abandoned behind a "done" marker.
+ """
+ # Reset DB state FIRST, then move the files aside. These two steps are not
+ # atomic, so ordering decides what a crash in between leaves behind:
+ # - DB-first (here): the collection is durably flagged "needs reindex"
+ # before its file is touched. A crash after the commit leaves a stray
+ # (still-original or renamed) file that the next index run simply
+ # rebuilds over — no data lost, no wrong state.
+ # - file-first (the reverse) would strand the collection as "indexed" with
+ # its backing index renamed away and no recoverable data until an admin
+ # intervenes — the exact permanent-loss failure this ordering avoids.
+ collection_id = rag_index.collection_name.removeprefix("collection_")
+ with get_user_db_session(username, db_password) as session:
+ idx = session.query(RAGIndex).filter_by(id=rag_index.id).first()
+ if idx:
+ idx.chunk_count = 0
+ idx.total_documents = 0
+ session.query(RagDocumentStatus).filter_by(
+ rag_index_id=rag_index.id
+ ).delete()
+ # Only the CURRENT index backs the collection's live searches, so only
+ # its failure should force the whole collection to re-embed. Quarantining
+ # a STALE (is_current=False) row must NOT flip the collection's live
+ # DocumentCollection.indexed state -- the current index is still healthy
+ # and serving searches; clearing this row's RAGIndex + RagDocumentStatus
+ # above is enough. (rekey_user_indexes now re-keys stale rows too, so
+ # this guard is what keeps a stale-row failure from needlessly
+ # re-embedding the whole collection.)
+ if idx is not None and idx.is_current:
+ session.query(DocumentCollection).filter_by(
+ collection_id=collection_id, indexed=True
+ ).update({"indexed": False, "chunk_count": 0})
+ session.commit()
+
+ # Hold the per-(user, index_path) write lock for the renames so they don't
+ # race a concurrent search/index reading the same .faiss (which would see
+ # the file vanish mid-operation).
+ ns = time.time_ns()
+ with lock:
+ if faiss_path.exists():
+ faiss_path.rename(Path(f"{faiss_path}.corrupt-{ns}"))
+ if sidecar_path.exists():
+ sidecar_path.rename(Path(f"{sidecar_path}.corrupt-{ns}"))
+ # Also DELETE (not rename) any lingering legacy plaintext .pkl companion.
+ # Phase-1 normally removes it at startup, but if it couldn't then
+ # (unreadable/symlinked at that moment) or it reappeared, quarantining
+ # the .faiss must not leave the plaintext docstore on disk. Renaming
+ # aside like the .faiss would preserve the plaintext, so unlink it. Let
+ # an unlink failure PROPAGATE (like the renames above): swallowing it
+ # counted the quarantine as clean success and set the completion marker
+ # while plaintext survived on disk. The caller instead logs it and
+ # withholds the marker so phase-2 retries.
+ pkl = faiss_path.with_suffix(".pkl")
+ if pkl.exists():
+ pkl.unlink()
+ logger.warning(
+ f"Quarantined un-rekeyable RAG index {faiss_path} for collection "
+ f"{collection_id}; reset its indexed state so it rebuilds on next use."
+ )
+
+
+def rekey_user_indexes(username: str, db_password: str) -> Dict[str, int]:
+ """Re-key this user's legacy RAG indices (phase 2 of the cutover), once.
+
+ MUST be called only after ``username``'s DB connection is already in
+ ``db_manager.connections``. This function goes through
+ ``get_user_db_session`` / ``FileIntegrityManager``, both of which
+ re-enter ``db_manager.open_user_database`` on a thread-local
+ session-cache miss. Calling this from inside ``_open_user_database_cold``
+ BEFORE the connection is cached would deadlock: ``open_user_database``
+ serializes the cold-open behind a per-user ``threading.Lock`` (not
+ reentrant), which this same thread is already holding at that point.
+
+ Returns a stats dict (``checked``/``rekeyed``/``quarantined``/
+ ``skipped_no_sidecar``/``skipped_no_faiss``). Does not raise -- every
+ per-index failure is caught and quarantined; the caller wraps this call
+ anyway as defense in depth.
+ """
+ stats = {
+ "checked": 0,
+ "rekeyed": 0,
+ "quarantined": 0,
+ "skipped_no_sidecar": 0,
+ "skipped_no_faiss": 0,
+ }
+
+ with get_user_db_session(username, db_password) as session:
+ settings = get_settings_manager(db_session=session, username=username)
+ if settings.get_bool_setting(REKEY_MARKER_SETTING, False):
+ return stats # already done for this user -- fast no-op
+ # Re-key EVERY RAGIndex row phase-1 converted, not just the current one.
+ # A collection can have stale historical rows (is_current=False) from an
+ # earlier embedding-model switch, and those are NOT unreachable: reverting
+ # the embedding-model setting re-resolves a search to the stale row by
+ # index_hash (library_rag_service._get_or_create_rag_index looks the row
+ # up by hash, NOT is_current), and a still-old-format .faiss then fails to
+ # load and hard-fails search. Phase-1 already writes text-free sidecars
+ # for ALL of them, so phase-2 must re-key ALL of them. To keep a stale
+ # row's re-key FAILURE from collaterally wiping the healthy current
+ # index's indexed state, _quarantine_and_reset resets the collection-wide
+ # DocumentCollection.indexed flag ONLY for the current row (see there).
+ indexes: List[RAGIndex] = session.query(RAGIndex).all()
+
+ if not indexes:
+ settings.set_setting(REKEY_MARKER_SETTING, True)
+ return stats
+
+ # Lazy import: avoids a module-load cycle (this is a leaf import used
+ # only inside this function -- see rekey_index_file's docstring for the
+ # same pattern in legacy_cleanup.py).
+ from ..research_library.services.library_rag_service import (
+ _get_faiss_write_lock,
+ )
+
+ integrity_manager = None # built lazily -- only if a sidecar is found
+ # Only set the completion marker if every index was actually resolved
+ # (rekeyed / skipped / quarantined). If quarantining itself fails (e.g.
+ # disk full mid-rename), that index is left untouched and the marker is
+ # withheld so the NEXT login retries it, instead of silently abandoning
+ # it forever behind a "done" marker.
+ all_resolved = True
+
+ for rag_index in indexes:
+ stats["checked"] += 1
+ faiss_path = Path(rag_index.index_path)
+ sidecar_path = _sidecar_for(faiss_path)
+ # Per-(user, index_path) write lock, held for every file mutation
+ # (re-key persist, quarantine renames) so none race a concurrent
+ # search/index on the same .faiss.
+ lock = _get_faiss_write_lock(username, str(faiss_path))
+
+ if not sidecar_path.exists():
+ # No sidecar means EITHER already fully migrated (the .faiss is an
+ # IndexIDMap2) OR phase-1 hit its reindex-fallback: a corrupt/
+ # malformed legacy .pkl was deleted WITHOUT writing a sidecar,
+ # leaving the OLD-format .faiss stranded. The latter would otherwise
+ # be skipped forever while the DB still claims the collection is
+ # indexed, so its search silently breaks. Distinguish by format and
+ # quarantine + reset the un-migratable one so it rebuilds. (This
+ # runs once — the whole function is per-user marker-gated.)
+ fmt = _is_idmap2(faiss_path) if faiss_path.exists() else True
+ if fmt is None:
+ # Could NOT read the .faiss to determine its format (transient
+ # IO/permission). Do NOT quarantine a possibly-healthy index —
+ # withhold the marker and retry next login.
+ logger.warning(
+ f"Could not read {faiss_path} to check its format; will "
+ "retry next login (NOT quarantining a possibly-healthy "
+ "index)."
+ )
+ all_resolved = False
+ continue
+ if faiss_path.exists() and fmt is False:
+ # A no-sidecar old-format .faiss has TWO causes, and only one is
+ # the "phase-1 gave up" (reindex-fallback) case that warrants a
+ # destructive quarantine. If the legacy plaintext .pkl companion
+ # STILL EXISTS, phase-1 simply hasn't converted this file yet
+ # (it ran before this collection existed / crashed early / a
+ # sibling process's phase-1 hasn't reached it) — its sidecar is
+ # still to come. Quarantining now would force a needless full
+ # re-embed instead of the cheap rekey phase-1 will enable, and it
+ # would delete an intact docstore out from under phase-1. Withhold
+ # the completion marker and retry next login, by which point
+ # phase-1 (which runs every startup) will have written the
+ # sidecar and removed the .pkl.
+ if faiss_path.with_suffix(".pkl").exists():
+ logger.warning(
+ f"Old-format index {faiss_path} still has its legacy "
+ ".pkl and no sidecar — phase-1 has not converted it yet; "
+ "will retry next login (NOT quarantining)."
+ )
+ all_resolved = False
+ continue
+ logger.warning(
+ f"Un-migratable old-format index {faiss_path} has no "
+ "sidecar (phase-1 reindex-fallback); quarantining so its "
+ "collection rebuilds."
+ )
+ try:
+ _quarantine_and_reset(
+ username,
+ db_password,
+ rag_index,
+ faiss_path,
+ sidecar_path,
+ lock,
+ )
+ stats["quarantined"] += 1
+ except Exception as exc:
+ # db_password is a live parameter of this function; a
+ # rendered traceback (loguru diagnose=True) would dump it.
+ # Drop the traceback and redact str(exc). See encrypted_db.
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Failed to quarantine {faiss_path}; will retry next "
+ f"login: {safe_msg}"
+ )
+ all_resolved = False
+ continue
+ # Already migrated (IndexIDMap2, no sidecar). Backstop: purge any
+ # legacy plaintext .pkl that survived phase-1 here too — this is the
+ # retry landing spot after a re-key whose Phase-B .pkl unlink failed
+ # (sidecar already gone), so without it the marker would be set with
+ # plaintext still on disk.
+ if not _purge_redundant_pkl(faiss_path, db_password):
+ all_resolved = False
+ stats["skipped_no_sidecar"] += 1
+ continue
+ if not faiss_path.exists():
+ # Orphaned sidecar (index file itself is already gone) -- there
+ # is nothing to re-key. Purge any legacy plaintext .pkl that
+ # survived next to the now-gone .faiss (a phase-1 .pkl-unlink
+ # failure, or a partial _quarantine_and_reset that renamed the
+ # .faiss aside before reaching its own pkl.unlink, can leave one
+ # here) BEFORE dropping the sidecar. Every other finalization branch
+ # backstops the plaintext .pkl this way; without it this branch is
+ # the one path that can set the per-user completion marker while an
+ # encryption-defeating plaintext .pkl still sits on disk. Withhold
+ # the marker if EITHER cleanup fails so phase-2 retries next login.
+ stats["skipped_no_faiss"] += 1
+ if not _purge_redundant_pkl(faiss_path, db_password):
+ all_resolved = False
+ try:
+ sidecar_path.unlink(missing_ok=True)
+ except OSError:
+ logger.warning(
+ f"Could not remove orphaned sidecar {sidecar_path}; "
+ "will retry next login"
+ )
+ all_resolved = False
+ continue
+
+ # Resolve + PIN the index config onto the row BEFORE building the file,
+ # so the row records what the file is built with even across a
+ # crash/retry. Pinning AFTER a successful build would break the retry
+ # path: if settings change between a crashed attempt and the retry, the
+ # retry re-resolves DIFFERENT params, hits rekey_index_file's
+ # already-migrated short-circuit (which only checks dim + ids), and pins
+ # a config that disagrees with the physical file. Pinning FIRST makes the
+ # row the source of truth that _resolve_index_params reads on retry (row
+ # wins over settings), so the resolved params match the file at every
+ # crash point. A transient failure here must NOT quarantine a healthy
+ # legacy file — withhold the marker and retry next login.
+ try:
+ params = _resolve_index_params(rag_index, settings)
+ # SQLAlchemy's legacy Column() declarative style types instance
+ # attribute access as Column[int] rather than int; cast() is a
+ # no-op at runtime.
+ _persist_rekeyed_config(
+ username, db_password, cast(int, rag_index.id), params
+ )
+ except Exception as exc:
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Failed to pin index config for RAG index {rag_index.id} "
+ f"({faiss_path}); will retry next login: {safe_msg}"
+ )
+ all_resolved = False
+ continue
+
+ # Resolve the sidecar map + uuid->DocumentChunk.id (a DB read). A failure
+ # HERE is transient and unrelated to the index file's health — a
+ # 'database is locked' timeout under concurrent writes, or a momentary
+ # OSError reading the sidecar. It must NOT quarantine a perfectly healthy
+ # legacy index (which would force a needless full re-embed); withhold the
+ # marker and retry next login instead.
+ try:
+ pos_to_uuid = json.loads(sidecar_path.read_text(encoding="utf-8"))
+ uuid_to_id = _load_uuid_to_id(
+ username, db_password, set(pos_to_uuid.values())
+ )
+ except Exception as exc:
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Could not resolve sidecar/DB ids for RAG index "
+ f"{rag_index.id} ({faiss_path}); will retry next login "
+ f"(NOT quarantining — the index file is untouched): {safe_msg}"
+ )
+ all_resolved = False
+ continue
+
+ # Phase A -- re-key. A failure HERE is a genuinely un-rekeyable index
+ # (corrupt/foreign format, dimension mismatch, duplicate-id sidecar):
+ # quarantine + reset so the collection rebuilds from the DB.
+ try:
+ with lock:
+ rekey_index_file(faiss_path, sidecar_path, uuid_to_id, **params)
+ except Exception as exc:
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Re-key failed for RAG index {rag_index.id} "
+ f"({faiss_path}); quarantining -- collection will reindex: "
+ f"{safe_msg}"
+ )
+ try:
+ _quarantine_and_reset(
+ username,
+ db_password,
+ rag_index,
+ faiss_path,
+ sidecar_path,
+ lock,
+ )
+ stats["quarantined"] += 1
+ except Exception as exc:
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Failed to quarantine {faiss_path} after re-key "
+ f"failure -- leaving files as-is; will retry next login: "
+ f"{safe_msg}"
+ )
+ all_resolved = False
+ continue
+
+ # Phase B -- the re-key SUCCEEDED (byte-verified new IndexIDMap2).
+ # Record the new file's integrity, THEN delete the sidecar (the
+ # completion signal). A failure here must NOT quarantine a perfectly
+ # good index (the bug this split fixes): leave the sidecar so the next
+ # login retries -- rekey_index_file's IndexIDMap2 guard makes that a
+ # clean no-op re-key -- and withhold the completion marker.
+ try:
+ with lock:
+ if integrity_manager is None:
+ integrity_manager = FileIntegrityManager(
+ username, db_password
+ )
+ integrity_manager.register_verifier(FAISSIndexVerifier())
+ integrity_manager.record_file(
+ faiss_path,
+ related_entity_type="rag_index",
+ # cast(): rag_index.id is Column[int] under the legacy
+ # Column() declarative style; a no-op at runtime.
+ related_entity_id=cast(int, rag_index.id),
+ )
+ # Config was already pinned before the build (see above), so
+ # Phase B only records integrity and drops the sidecar signal.
+ sidecar_path.unlink(missing_ok=True)
+ # Backstop: if phase-1 wrote the sidecar but its .pkl unlink
+ # failed, the plaintext .pkl is still on disk. The re-key just
+ # succeeded from the sidecar and the text is in the DB, so purge
+ # the now-redundant .pkl; withhold the marker if it can't be
+ # removed so this index is retried rather than gated out with
+ # plaintext surviving.
+ if not _purge_redundant_pkl(faiss_path, db_password):
+ all_resolved = False
+ stats["rekeyed"] += 1
+ except Exception as exc:
+ safe_msg = redact_secrets(str(exc), db_password)
+ logger.warning(
+ f"Re-key of {faiss_path} succeeded but finalization "
+ "(integrity record / sidecar removal) failed; leaving sidecar "
+ f"to retry next login: {safe_msg}"
+ )
+ all_resolved = False
+
+ if all_resolved:
+ settings.set_setting(REKEY_MARKER_SETTING, True)
+ logger.info(
+ f"RAG index re-key for user {username}: "
+ f"checked={stats['checked']} rekeyed={stats['rekeyed']} "
+ f"quarantined={stats['quarantined']} "
+ f"skipped_no_sidecar={stats['skipped_no_sidecar']} "
+ f"skipped_no_faiss={stats['skipped_no_faiss']}"
+ + ("" if all_resolved else " (incomplete -- will retry next login)")
+ )
+ return stats
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 997e1548ef..1dcb42ab29 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -70,6 +70,21 @@ def main():
config_logger("ldr_web", debug=config["debug"])
logger.info(f"Starting Local Deep Research v{__version__}")
+ # One-time removal of plaintext legacy RAG docstores (phase 1 of the
+ # vector-store cutover -- see vector_stores/legacy_cleanup.py). Pure
+ # filesystem, no DB/login required, so it belongs here at the real
+ # server-start entrypoint rather than in create_app() -- create_app()
+ # is exercised by ~32 tests (many without LDR_DATA_DIR isolation) and
+ # wiring it there would delete a developer's real .pkl files on every
+ # test run. Wrapped so a cleanup issue never blocks boot; the function
+ # logs its own errors and is idempotent.
+ try:
+ from ..vector_stores.legacy_cleanup import migrate_legacy_docstores
+
+ migrate_legacy_docstores()
+ except Exception:
+ logger.exception("Legacy RAG docstore migration failed at startup")
+
# Create the Flask app and SocketIO instance
app, socket_service = create_app()
diff --git a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
index 7dcce92c10..834ec3beb2 100644
--- a/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
+++ b/src/local_deep_research/web_search_engines/engines/local_embedding_manager.py
@@ -1,10 +1,6 @@
-import hashlib
import threading
-import uuid
-from datetime import UTC, datetime
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, Optional
-from langchain_core.documents import Document
from ...database.models.library import DocumentChunk
from ...database.session_context import get_user_db_session
@@ -52,9 +48,6 @@ class LocalEmbeddingManager:
self._embeddings = None
self._embedding_lock = threading.Lock()
- # Vector store cache
- self.vector_stores: dict[str, Any] = {}
-
# Track if this manager has been closed
self._closed = False
@@ -78,8 +71,6 @@ class LocalEmbeddingManager:
_close_base_llm(self._embeddings)
self._embeddings = None
- # Clear vector store cache
- self.vector_stores.clear()
logger.debug("LocalEmbeddingManager closed")
def __enter__(self):
@@ -162,144 +153,14 @@ class LocalEmbeddingManager:
settings_snapshot=self.settings_snapshot,
)
- def _store_chunks_to_db(
- self,
- chunks: List[Document],
- collection_name: str,
- source_path: Optional[str] = None,
- source_id: Optional[int] = None,
- source_type: str = "local_file",
- ) -> List[str]:
- """
- Store document chunks in the database.
-
- Args:
- chunks: List of LangChain Document chunks
- collection_name: Name of the collection (e.g., 'personal_notes', 'library')
- source_path: Path to source file (for local files)
- source_id: ID of source document (for library documents)
- source_type: Type of source ('local_file' or 'library')
-
- Returns:
- List of chunk embedding IDs (UUIDs) for FAISS mapping
- """
- if not self.username:
- logger.warning(
- "No username available, cannot store chunks in database"
- )
- return []
-
- chunk_ids = []
-
- try:
- with get_user_db_session(
- self.username, self.db_password
- ) as session:
- for idx, chunk in enumerate(chunks):
- # Generate unique hash for chunk
- chunk_text = chunk.page_content
- chunk_hash = hashlib.sha256(chunk_text.encode()).hexdigest()
-
- # Generate unique embedding ID
- embedding_id = uuid.uuid4().hex
-
- # Extract metadata
- metadata = chunk.metadata or {}
- document_title = metadata.get(
- "filename", metadata.get("title", "Unknown")
- )
-
- # Calculate word count
- word_count = len(chunk_text.split())
-
- # Get character positions from metadata if available
- start_char = metadata.get("start_char", 0)
- end_char = metadata.get("end_char", len(chunk_text))
-
- # Check if chunk already exists. Scoped to the collection
- # to mirror the schema's uix_chunk_collection UNIQUE —
- # the previous hash-only lookup reused a row (and its
- # embedding id) across collections, mis-attributing the
- # chunk's collection_name and sharing one embedding id
- # between different collections' FAISS indexes.
- existing_chunk = (
- session.query(DocumentChunk)
- .filter_by(
- chunk_hash=chunk_hash,
- collection_name=collection_name,
- )
- .first()
- )
-
- if existing_chunk:
- # Update existing chunk
- existing_chunk.last_accessed = datetime.now(UTC)
- if (
- existing_chunk.source_id != source_id
- or existing_chunk.source_type != source_type
- ):
- # Within a collection the schema dedups chunk
- # rows by hash, so identical text in two
- # documents shares one row + one vector. Track
- # ownership last-claimer-wins: the re-index
- # purge in library_rag_service treats the row's
- # source_id as the authoritative owner and only
- # deletes a shared vector when the re-indexed
- # document still owns it — re-pointing here is
- # what keeps another document's copy alive when
- # the original indexer edits its chunk away.
- existing_chunk.source_type = source_type
- existing_chunk.source_id = source_id
- existing_chunk.source_path = (
- str(source_path) if source_path else None
- )
- existing_chunk.document_title = document_title
- existing_chunk.document_metadata = metadata
- existing_chunk.chunk_index = idx
- existing_chunk.start_char = start_char
- existing_chunk.end_char = end_char
- existing_chunk.word_count = word_count
- chunk_ids.append(existing_chunk.embedding_id)
- logger.debug(
- f"Chunk already exists, reusing: {existing_chunk.embedding_id}"
- )
- else:
- # Create new chunk
- db_chunk = DocumentChunk(
- chunk_hash=chunk_hash,
- source_type=source_type,
- source_id=source_id,
- source_path=str(source_path)
- if source_path
- else None,
- collection_name=collection_name,
- chunk_text=chunk_text,
- chunk_index=idx,
- start_char=start_char,
- end_char=end_char,
- word_count=word_count,
- embedding_id=embedding_id,
- embedding_model=self.embedding_model,
- embedding_model_type=self.embedding_model_type,
- document_title=document_title,
- document_metadata=metadata,
- )
- session.add(db_chunk)
- chunk_ids.append(embedding_id)
-
- session.commit()
- logger.info(
- f"Stored {len(chunk_ids)} chunks to database for collection '{collection_name}'"
- )
-
- except Exception as e:
- safe_msg = scrub_error(e, self.db_password)
- logger.exception(
- f"Error storing chunks to database for collection '{collection_name}' ({type(e).__name__}): {safe_msg}"
- )
- return []
-
- return chunk_ids
+ # NOTE(cutover): the old ``_store_chunks_to_db`` (LangChain-Document-list
+ # -> DocumentChunk rows, with chunk-hash+collection dedup/reuse for a
+ # FAISS uuid-keyed docstore) was deleted here. Its caller
+ # ``LibraryRAGService.index_document`` now writes chunk rows via
+ # ``vector_stores.facade.VectorIndex.index`` instead (int-id keyed,
+ # one row per source's chunk, no cross-source hash dedup/reuse; see
+ # the "One row = one vector" note in vector_stores/facade.py). Grep
+ # confirmed no other production callers before deletion.
def _delete_chunks_from_db(
self,
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
index ec80d646a8..19f2c575ae 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_collection.py
@@ -7,8 +7,6 @@ Provides semantic search within a specific document collection using RAG.
import os
from typing import List, Dict, Any, Optional
-import faiss
-
from ...security.secure_logging import logger
from .search_engine_library import LibraryRAGSearchEngine
from ...constants import SNIPPET_LENGTH_LONG
@@ -21,37 +19,6 @@ from ...config.paths import get_library_directory
from ...utilities.type_utils import to_bool
-def _relevance_from_faiss_score(vector_store: Any, score: float) -> float:
- """Map a raw FAISS score to a [0, 1] relevance that grows with similarity.
-
- ``similarity_search_with_score`` returns the score straight from the
- underlying FAISS index, and what it means depends on that index's metric
- (chosen in ``LibraryRAGService.load_or_create_faiss_index`` from the
- collection's ``distance_metric``):
-
- - ``METRIC_L2``: a (squared) distance, ``0`` for an exact match and larger
- the farther apart. ``1 / (1 + distance)`` maps it to ``(0, 1]``,
- decreasing with distance.
- - ``METRIC_INNER_PRODUCT`` (built for the default ``cosine`` metric and for
- ``dot_product``): a similarity, larger for nearer vectors, and in
- ``[-1, 1]`` for the normalized vectors this service indexes. Here
- ``1 / (1 + score)`` inverts the ranking (a perfect match -> 0.5, an
- unrelated vector -> 1.0) and divides by zero for an anti-correlated pair
- (``score == -1``). Map it with ``(score + 1) / 2`` instead, clamped to
- ``[0, 1]``.
-
- The invariant both branches preserve: relevance is monotonically increasing
- in true similarity and bounded to ``[0, 1]``, so the nearest neighbour
- always gets the highest ``relevance_score``.
- """
- index = getattr(vector_store, "index", None)
- if getattr(index, "metric_type", None) == faiss.METRIC_INNER_PRODUCT:
- return max(0.0, min(1.0, (float(score) + 1.0) / 2.0))
- # L2 distance, or an index we cannot introspect: keep the historical
- # distance -> similarity mapping.
- return float(1.0 / (1.0 + float(score)))
-
-
class CollectionSearchEngine(LibraryRAGSearchEngine):
"""
Search engine for a specific document collection using RAG.
@@ -215,6 +182,19 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
normalize_vectors = to_bool(
rag_index.normalize_vectors, default=True
)
+ # Thread the stored distance metric through too: it is what
+ # LibraryRAGService stamps onto each SearchResult.metric, which
+ # in turn selects the relevance formula below. Defaulting to
+ # "cosine" (the LibraryRAGService default) would mislabel an
+ # l2/dot_product collection and apply the wrong [0,1] mapping.
+ # NULL (legacy rows) → "cosine" preserves prior behavior.
+ distance_metric = rag_index.distance_metric or "cosine"
+ # Thread the stored index_type too (like metric/normalize): with
+ # it left at the "flat" default, _get_vector_index would fall
+ # back to flat for a legacy NULL-index_type row that is physically
+ # HNSW, mislabelling the store (wrong supports_delete/relevance,
+ # and now a load()-time config-mismatch rejection). NULL → "flat".
+ index_type = rag_index.index_type or "flat"
# Create RAG service with collection's embedding settings
with LibraryRAGService(
@@ -224,6 +204,8 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
normalize_vectors=normalize_vectors,
+ distance_metric=distance_metric,
+ index_type=index_type,
) as rag_service:
# Check if there are indexed documents
stats = rag_service.get_rag_stats(self.collection_id)
@@ -233,16 +215,16 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
)
return []
- # Load and search the FAISS index for this collection
- vector_store = rag_service.load_or_create_faiss_index(
- self.collection_id
+ # Search this collection's vector index via the new
+ # int-id-keyed store (chunk text is rehydrated from the
+ # encrypted DB by id — never read from the vector store
+ # itself; see the SECURITY INVARIANT in
+ # vector_stores/base.py).
+ search_results = rag_service.search(
+ query, self.collection_id, limit
)
- docs_with_scores = vector_store.similarity_search_with_score(
- query, k=limit
- )
-
- if not docs_with_scores:
+ if not search_results:
logger.info(
f"No results found in collection '{self.collection_name}'"
)
@@ -250,26 +232,29 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
# Convert to search result format
results = []
- for doc, score in docs_with_scores:
- metadata = doc.metadata or {}
+ for r in search_results:
+ metadata = dict(r.metadata or {})
# Get document ID
- doc_id = metadata.get("source_id") or metadata.get(
- "document_id"
+ doc_id = (
+ r.source_id
+ or metadata.get("source_id")
+ or metadata.get("document_id")
)
# Get title
title = (
- metadata.get("document_title")
+ r.document_title
+ or metadata.get("document_title")
or metadata.get("title")
or (f"Document {doc_id}" if doc_id else "Untitled")
)
# Create snippet from content
snippet = (
- doc.page_content[:SNIPPET_LENGTH_LONG] + "..."
- if len(doc.page_content) > SNIPPET_LENGTH_LONG
- else doc.page_content
+ r.text[:SNIPPET_LENGTH_LONG] + "..."
+ if len(r.text) > SNIPPET_LENGTH_LONG
+ else r.text
)
# Generate document URL
@@ -279,6 +264,28 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
metadata["collection_id"] = self.collection_id
metadata["collection_name"] = self.collection_name
+ # r.distance's meaning depends on r.metric. Map both to a
+ # [0, 1] relevance that grows with similarity:
+ # - cosine/dot_product (inner product on normalized
+ # vectors): a similarity in [-1, 1] where higher is
+ # nearer, so (d+1)/2 clamped to [0, 1]. Using it raw would
+ # yield negative relevance for anti-correlated hits and
+ # break downstream [0,1] consumers (similarity %, filters).
+ # - anything else (l2, or a non-standard metric string): a
+ # (squared) distance >= 0 where LOWER is nearer, so
+ # 1/(1+d) in (0, 1].
+ # This IP test MUST match faiss_store._build_base_index,
+ # which builds an inner-product index iff the metric is
+ # cosine/dot_product and an L2 index otherwise. A bare
+ # `metric == "l2"` here would score a non-standard metric
+ # (which builds an L2 index) with the IP formula, inverting
+ # the ranking.
+ relevance = (
+ max(0.0, min(1.0, (r.distance + 1.0) / 2.0))
+ if r.metric in ("cosine", "dot_product")
+ else 1.0 / (1.0 + r.distance)
+ )
+
result = {
"title": title,
"snippet": snippet,
@@ -286,9 +293,7 @@ class CollectionSearchEngine(LibraryRAGSearchEngine):
"link": document_url,
"source": "library",
"source_type": "library",
- "relevance_score": _relevance_from_faiss_score(
- vector_store, score
- ),
+ "relevance_score": float(relevance),
"metadata": metadata,
}
results.append(result)
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_library.py b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
index 600f266204..7a286fe3a8 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_library.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_library.py
@@ -182,8 +182,13 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
logger.info("No collections found for user")
return []
- # Search across all collections and merge results
- all_docs_with_scores = []
+ # Search across all collections and merge results. Each
+ # (SearchResult, relevance, metadata) tuple is pre-scored per
+ # its OWN collection's metric before merging, so a collection
+ # indexed with cosine/dot_product doesn't get compared on the
+ # wrong scale against one indexed with l2 (see the
+ # relevance-formula comment below).
+ all_results = []
failed_collections = []
for collection in collections:
collection_id = collection.get("id")
@@ -218,6 +223,23 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
chunk_overlap = (
rag_index.chunk_overlap or self.chunk_overlap
)
+ # Thread the stored normalization flag AND distance
+ # metric through, exactly like CollectionSearchEngine.
+ # Without normalize_vectors, LibraryRAGService defaults
+ # True and would L2-normalize the query against a
+ # raw-vector collection, flipping the top hit. Without
+ # distance_metric, every collection is labeled "cosine"
+ # and l2/dot_product hits get the wrong [0,1] mapping in
+ # the cross-collection merge below. NULL → prior default.
+ normalize_vectors = to_bool(
+ rag_index.normalize_vectors, default=True
+ )
+ distance_metric = rag_index.distance_metric or "cosine"
+ # Thread the stored index_type too (like metric/
+ # normalize): a legacy NULL-index_type row that is
+ # physically HNSW would otherwise fall back to "flat",
+ # mislabelling the store. NULL → "flat".
+ index_type = rag_index.index_type or "flat"
# Create RAG service with the collection's embedding settings
with LibraryRAGService(
@@ -226,6 +248,9 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
embedding_provider=embedding_provider,
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
+ normalize_vectors=normalize_vectors,
+ distance_metric=distance_metric,
+ index_type=index_type,
) as rag_service:
# Get RAG stats to check if there are any indexed documents
stats = rag_service.get_rag_stats(collection_id)
@@ -235,27 +260,43 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
)
continue
- # Load the FAISS index for this collection
- vector_store = rag_service.load_or_create_faiss_index(
- collection_id
- )
-
- # Search this collection's index
- docs_with_scores = (
- vector_store.similarity_search_with_score(
- query, k=limit
- )
+ # Search this collection's vector index via the new
+ # int-id-keyed store (chunk text is rehydrated from
+ # the encrypted DB by id — never read from the
+ # vector store itself; see the SECURITY INVARIANT
+ # in vector_stores/base.py).
+ search_results = rag_service.search(
+ query, collection_id, limit
)
- # Add collection info to metadata and append to results
- for doc, score in docs_with_scores:
- if not doc.metadata:
- doc.metadata = {}
- doc.metadata["collection_id"] = collection_id
- doc.metadata["collection_name"] = collection.get(
+ # Score per THIS collection's own metric, add
+ # collection info to metadata, and append to the
+ # cross-collection merge list.
+ for r in search_results:
+ metadata = dict(r.metadata or {})
+ metadata["collection_id"] = collection_id
+ metadata["collection_name"] = collection.get(
"name", "Unknown"
)
- all_docs_with_scores.append((doc, score))
+ # Map r.distance to a [0,1] relevance growing with
+ # similarity: cosine/dot_product is an inner product
+ # in [-1,1] (higher=nearer) -> (d+1)/2 clamped; l2 (or
+ # any non-standard metric) is a distance >=0 (lower=
+ # nearer) -> 1/(1+d) in (0,1]. Raw IP would give
+ # negative relevance and break [0,1] consumers.
+ # Scoring here (per-collection, before the merge)
+ # keeps different-metric collections comparable once
+ # merged. The IP test MUST match faiss_store.
+ # _build_base_index (inner-product iff cosine/
+ # dot_product, else L2): a bare `metric == "l2"` would
+ # score a non-standard metric — which builds an L2
+ # index — with the IP formula and invert the ranking.
+ relevance = (
+ max(0.0, min(1.0, (r.distance + 1.0) / 2.0))
+ if r.metric in ("cosine", "dot_product")
+ else 1.0 / (1.0 + r.distance)
+ )
+ all_results.append((r, relevance, metadata))
except Exception as e:
# One broken collection must not abort the others, but
@@ -270,13 +311,15 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
)
continue
- # Sort all results by score (lower is better for distance)
- all_docs_with_scores.sort(key=lambda x: x[1])
+ # Sort all results by relevance, descending (higher is always
+ # better post-transform, regardless of the source collection's
+ # metric — see the per-result relevance comment above).
+ all_results.sort(key=lambda item: item[1], reverse=True)
# Take top results across all collections
- docs_with_scores = all_docs_with_scores[:limit]
+ top_results = all_results[:limit]
- if not docs_with_scores:
+ if not top_results:
if failed_collections:
# Zero results AND at least one collection errored:
# reporting "no results" here would hide the failure.
@@ -295,29 +338,29 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
f"collection(s) failed: {failed_collections}"
)
- # Convert Document objects to search results format
+ # Convert to the search-result dict format
results = []
- for doc, score in docs_with_scores:
- # Extract metadata from Document object
- metadata = doc.metadata or {}
-
+ for r, relevance, metadata in top_results:
# Try both source_id and document_id for compatibility
- doc_id = metadata.get("source_id") or metadata.get(
- "document_id"
+ doc_id = (
+ r.source_id
+ or metadata.get("source_id")
+ or metadata.get("document_id")
)
- # Get title from metadata, with fallbacks
+ # Get title from the result, with fallbacks
title = (
- metadata.get("document_title")
+ r.document_title
+ or metadata.get("document_title")
or metadata.get("title")
or (f"Document {doc_id}" if doc_id else "Untitled")
)
- # Content is stored in page_content
+ # Content is rehydrated from the encrypted DB by chunk id
snippet = (
- doc.page_content[:SNIPPET_LENGTH_LONG] + "..."
- if len(doc.page_content) > SNIPPET_LENGTH_LONG
- else doc.page_content
+ r.text[:SNIPPET_LENGTH_LONG] + "..."
+ if len(r.text) > SNIPPET_LENGTH_LONG
+ else r.text
)
# Generate URL to document content
@@ -361,9 +404,7 @@ class LibraryRAGSearchEngine(BaseSearchEngine):
"link": document_url, # Add "link" for source extraction
"source": "library",
"source_type": "library",
- "relevance_score": float(
- 1 / (1 + score)
- ), # Convert distance to similarity
+ "relevance_score": float(relevance),
"metadata": metadata,
}
diff --git a/tests/database/models/test_library_models_extended.py b/tests/database/models/test_library_models_extended.py
index ba4a826648..2e11b5b967 100644
--- a/tests/database/models/test_library_models_extended.py
+++ b/tests/database/models/test_library_models_extended.py
@@ -363,8 +363,16 @@ class TestDocumentChunkModel:
assert chunk.id is not None
- def test_chunk_unique_per_collection(self, session):
- """Chunk hash should be unique per collection."""
+ def test_chunk_duplicate_hash_allowed_per_collection(self, session):
+ """Duplicate (chunk_hash, collection_name) rows are ALLOWED.
+
+ The old ``uix_chunk_collection`` unique constraint was dropped
+ (migration 0023): the vector store is now one-row-per-chunk keyed by
+ the integer id, so identical text in two documents — or a repeated/
+ blank chunk — legitimately produces two rows instead of an
+ IntegrityError. ``chunk_hash`` remains a plain index for query-time
+ de-duplication only.
+ """
chunk_hash = "duplicate_hash" * 5
chunk1 = DocumentChunk(
@@ -383,7 +391,7 @@ class TestDocumentChunkModel:
session.add(chunk1)
session.commit()
- # Same hash, same collection should fail
+ # Same hash, same collection now succeeds (constraint dropped).
chunk2 = DocumentChunk(
chunk_hash=chunk_hash,
source_type="document",
@@ -398,9 +406,15 @@ class TestDocumentChunkModel:
embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
)
session.add(chunk2)
+ session.commit() # must NOT raise
- with pytest.raises(Exception):
- session.commit()
+ rows = (
+ session.query(DocumentChunk)
+ .filter_by(chunk_hash=chunk_hash, collection_name="collection_1")
+ .all()
+ )
+ assert len(rows) == 2
+ assert rows[0].id != rows[1].id
def test_chunk_repr(self, session):
"""DocumentChunk __repr__ should work."""
diff --git a/tests/database/test_migration_0022_note_references.py b/tests/database/test_migration_0022_note_references.py
index 006625e7ce..5671fa72ef 100644
--- a/tests/database/test_migration_0022_note_references.py
+++ b/tests/database/test_migration_0022_note_references.py
@@ -199,14 +199,44 @@ class TestModelMigrationParity:
class TestMigration0022HeadAlignment:
"""Head-alignment guard (moved from the 0019 test file per the repo
- convention of keeping this in the newest migration's test)."""
+ convention of keeping this in the newest migration's test).
- def test_head_revision_is_0022(self):
+ The assertion tracks the latest migration file dynamically (instead of
+ a hardcoded revision id), so it no longer needs to be relocated every
+ time a new migration lands here. 0023 (drop uix_chunk_collection) and
+ 0024 (sqlite_autoincrement on document_chunks) advance the head past
+ 0022 without requiring any change to this test.
+ """
+
+ def test_head_revision_matches_latest_migration_file(self):
from local_deep_research.database.alembic_runner import (
get_head_revision,
+ get_migrations_dir,
+ )
+
+ versions_dir = get_migrations_dir() / "versions"
+ revision_ids = sorted(
+ p.name[:4]
+ for p in versions_dir.glob("*.py")
+ if p.name[:4].isdigit()
+ )
+ assert revision_ids, "no migration files found in versions dir"
+ assert get_head_revision() == revision_ids[-1]
+
+ def test_single_head_no_branches(self):
+ """The revision graph must never branch into multiple heads."""
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
)
- assert get_head_revision() == "0022"
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ heads = script.get_heads()
+ assert len(heads) == 1, f"expected a single head, found {heads}"
def test_0022_chains_correctly_to_0021(self):
from alembic.config import Config
diff --git a/tests/database/test_migration_0023_0024_rag.py b/tests/database/test_migration_0023_0024_rag.py
new file mode 100644
index 0000000000..8363d96274
--- /dev/null
+++ b/tests/database/test_migration_0023_0024_rag.py
@@ -0,0 +1,486 @@
+"""
+Tests for migrations 0023 (drop uix_chunk_collection) and 0024 (document_chunks
+AUTOINCREMENT).
+
+Covers:
+- 0023 downgrade REFUSES with a RuntimeError when document_chunks has
+ duplicate (chunk_hash, collection_name) rows, without deleting anything
+ or moving the alembic version off 0023.
+- 0023 downgrade SUCCEEDS (re-adding the unique constraint) when there are
+ no duplicates.
+- 0024 makes document_chunks.id an AUTOINCREMENT column so ids are never
+ reused after the max-id row is deleted — the invariant the faiss
+ id-keyed vector store depends on to avoid cross-document text leaks.
+- The migration chain is single-headed: 0022 -> 0023 -> 0024.
+"""
+
+import uuid
+
+import pytest
+from alembic import command
+from sqlalchemy import create_engine, inspect, text
+
+from local_deep_research.database.alembic_runner import get_alembic_config
+
+
+def _upgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.upgrade(config, revision)
+
+
+def _downgrade_to(engine, revision):
+ config = get_alembic_config(engine)
+ with engine.begin() as conn:
+ config.attributes["connection"] = conn
+ command.downgrade(config, revision)
+
+
+def _current_revision(engine):
+ with engine.connect() as conn:
+ row = conn.execute(
+ text("SELECT version_num FROM alembic_version")
+ ).first()
+ return row[0] if row else None
+
+
+def _get_unique_constraint_names(engine, table):
+ insp = inspect(engine)
+ if not insp.has_table(table):
+ return set()
+ names = set()
+ for u in insp.get_unique_constraints(table):
+ if u.get("name"):
+ names.add(u["name"])
+ return names
+
+
+def _table_sql(engine, table):
+ with engine.connect() as conn:
+ row = conn.execute(
+ text(
+ "SELECT sql FROM sqlite_master WHERE type='table' AND name=:n"
+ ),
+ {"n": table},
+ ).first()
+ return (row[0] or "") if row else ""
+
+
+def _insert_chunk(
+ conn,
+ *,
+ chunk_hash="hash-a",
+ collection_name="collection_x",
+ chunk_text="some chunk text",
+ embedding_id=None,
+):
+ """Insert a minimal, valid document_chunks row.
+
+ NOT NULL columns per the model: chunk_hash, source_type,
+ collection_name, chunk_text, chunk_index, start_char, end_char,
+ word_count, embedding_id (unique), embedding_model,
+ embedding_model_type, created_at.
+ """
+ conn.execute(
+ text(
+ "INSERT INTO document_chunks "
+ "(chunk_hash, source_type, source_id, collection_name, "
+ "chunk_text, chunk_index, start_char, end_char, word_count, "
+ "embedding_id, embedding_model, embedding_model_type, "
+ "created_at) VALUES "
+ "(:chunk_hash, 'document', 'doc-1', :collection_name, "
+ ":chunk_text, 0, 0, 10, 2, :embedding_id, 'test-model', "
+ "'sentence_transformers', CURRENT_TIMESTAMP)"
+ ),
+ {
+ "chunk_hash": chunk_hash,
+ "collection_name": collection_name,
+ "chunk_text": chunk_text,
+ "embedding_id": embedding_id or str(uuid.uuid4()),
+ },
+ )
+
+
+def fresh_engine(tmp_path):
+ db_path = tmp_path / "rag_migration_test.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ yield engine
+ engine.dispose()
+
+
+def engine_at_0023(fresh_engine):
+ _upgrade_to(fresh_engine, "0023")
+ return fresh_engine
+
+
+def engine_at_0024(fresh_engine):
+ _upgrade_to(fresh_engine, "0024")
+ return fresh_engine
+
+
+# ---------------------------------------------------------------------------
+# 0023 — dropping uix_chunk_collection, and refusing to bring it back over
+# duplicate data.
+# ---------------------------------------------------------------------------
+
+
+class TestMigration0023DropUniqueConstraint:
+ def test_upgrade_drops_the_unique_constraint(self, engine_at_0023):
+ names = _get_unique_constraint_names(engine_at_0023, "document_chunks")
+ assert "uix_chunk_collection" not in names
+
+ def test_upgrade_allows_duplicate_chunk_hash_collection_rows(
+ self, engine_at_0023
+ ):
+ """Positive control: proves upgrade genuinely lifted the constraint,
+ not merely that inspection doesn't see its name."""
+ engine = engine_at_0023
+ with engine.begin() as conn:
+ _insert_chunk(
+ conn, chunk_hash="dup-hash", collection_name="dup-coll"
+ )
+ _insert_chunk(
+ conn, chunk_hash="dup-hash", collection_name="dup-coll"
+ )
+ with engine.connect() as conn:
+ count = conn.execute(
+ text(
+ "SELECT COUNT(*) FROM document_chunks "
+ "WHERE chunk_hash='dup-hash' AND collection_name='dup-coll'"
+ )
+ ).scalar()
+ assert count == 2
+
+ def test_downgrade_refuses_with_runtime_error_on_duplicates(
+ self, engine_at_0023
+ ):
+ """The core safety guarantee: downgrading past 0023 while
+ document_chunks holds duplicate (chunk_hash, collection_name) rows
+ must raise, not silently delete a row to satisfy the constraint —
+ a dropped row's chunk_text may be the only copy of that user data.
+ """
+ engine = engine_at_0023
+ with engine.begin() as conn:
+ _insert_chunk(
+ conn, chunk_hash="same-hash", collection_name="same-coll"
+ )
+ _insert_chunk(
+ conn, chunk_hash="same-hash", collection_name="same-coll"
+ )
+
+ with engine.connect() as conn:
+ before_count = conn.execute(
+ text("SELECT COUNT(*) FROM document_chunks")
+ ).scalar()
+ assert before_count == 2, "seed failed"
+
+ with pytest.raises(RuntimeError, match="Cannot downgrade past 0023"):
+ _downgrade_to(engine, "0022")
+
+ # No rows were silently dropped to force the constraint back on.
+ with engine.connect() as conn:
+ after_count = conn.execute(
+ text("SELECT COUNT(*) FROM document_chunks")
+ ).scalar()
+ assert after_count == before_count, (
+ "downgrade must never delete rows to satisfy the re-added "
+ "unique constraint"
+ )
+
+ # The alembic version must remain at 0023 — the failed downgrade
+ # must not silently advance the recorded revision.
+ assert _current_revision(engine) == "0023"
+
+ # The table must still be usable (no stranded _alembic_tmp table
+ # left over from an aborted batch rebuild).
+ insp = inspect(engine)
+ assert insp.has_table("document_chunks")
+ assert not insp.has_table("_alembic_tmp_document_chunks")
+
+ def test_downgrade_succeeds_without_duplicates(self, engine_at_0023):
+ """Negative control: with no duplicate (chunk_hash, collection_name)
+ rows, downgrade must succeed and the unique constraint must be back.
+ """
+ engine = engine_at_0023
+ with engine.begin() as conn:
+ _insert_chunk(conn, chunk_hash="hash-1", collection_name="coll-1")
+ _insert_chunk(conn, chunk_hash="hash-2", collection_name="coll-1")
+ _insert_chunk(conn, chunk_hash="hash-1", collection_name="coll-2")
+
+ _downgrade_to(engine, "0022")
+
+ assert _current_revision(engine) == "0022"
+ names = _get_unique_constraint_names(engine, "document_chunks")
+ assert "uix_chunk_collection" in names
+
+ # And the constraint is genuinely enforced again: a fresh duplicate
+ # insert now fails.
+ with engine.connect() as conn:
+ count = conn.execute(
+ text("SELECT COUNT(*) FROM document_chunks")
+ ).scalar()
+ assert count == 3, "downgrade must not delete legitimate rows either"
+
+
+# ---------------------------------------------------------------------------
+# 0024 — AUTOINCREMENT on document_chunks.id: ids must never be reused.
+# ---------------------------------------------------------------------------
+
+
+class TestMigration0024Autoincrement:
+ def test_upgrade_marks_table_autoincrement(self, engine_at_0024):
+ sql = _table_sql(engine_at_0024, "document_chunks")
+ assert "AUTOINCREMENT" in sql.upper()
+
+ def test_deleted_max_id_is_never_reused(self, engine_at_0024):
+ """The security invariant the faiss id-keyed vector store relies
+ on: once an id has been used, it is never handed out again — even
+ after the row holding the current maximum id is deleted. Without
+ AUTOINCREMENT, SQLite's plain ROWID allocation recycles the freed
+ max id on the next insert, which would let a later, unrelated
+ chunk's vector rehydrate under a stale/removed id and leak the
+ wrong document's text.
+ """
+ engine = engine_at_0024
+
+ with engine.begin() as conn:
+ _insert_chunk(conn, chunk_hash="h1", collection_name="c1")
+ _insert_chunk(conn, chunk_hash="h2", collection_name="c1")
+ _insert_chunk(conn, chunk_hash="h3", collection_name="c1")
+
+ with engine.connect() as conn:
+ ids = [
+ row[0]
+ for row in conn.execute(
+ text("SELECT id FROM document_chunks ORDER BY id")
+ ).fetchall()
+ ]
+ assert len(ids) == 3
+ max_id_before = max(ids)
+
+ # Delete the row holding the current maximum id — the scenario a
+ # plain ROWID table would recycle.
+ with engine.begin() as conn:
+ conn.execute(
+ text("DELETE FROM document_chunks WHERE id = :id"),
+ {"id": max_id_before},
+ )
+
+ with engine.begin() as conn:
+ _insert_chunk(conn, chunk_hash="h4", collection_name="c1")
+
+ with engine.connect() as conn:
+ new_id = conn.execute(
+ text("SELECT id FROM document_chunks WHERE chunk_hash='h4'")
+ ).scalar()
+
+ assert new_id > max_id_before, (
+ f"id {new_id} was reused/recycled after deleting the previous "
+ f"max id {max_id_before} — AUTOINCREMENT is not effective"
+ )
+ # Every id ever used (including the deleted one) must stay strictly
+ # below every id used afterward.
+ assert new_id not in ids
+
+ def test_sanity_plain_rowid_would_have_reused_the_id(self, tmp_path):
+ """Control proving the assertion above actually bites: a plain
+ (non-AUTOINCREMENT) INTEGER PRIMARY KEY table DOES recycle the
+ freed max id in this exact insert/delete/insert sequence, so the
+ migration is doing real work and the test above isn't vacuous.
+ """
+ db_path = tmp_path / "plain_rowid_control.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ try:
+ with engine.begin() as conn:
+ conn.execute(
+ text(
+ "CREATE TABLE plain_ids "
+ "(id INTEGER PRIMARY KEY, val TEXT)"
+ )
+ )
+ conn.execute(text("INSERT INTO plain_ids (val) VALUES ('a')"))
+ conn.execute(text("INSERT INTO plain_ids (val) VALUES ('b')"))
+ conn.execute(text("INSERT INTO plain_ids (val) VALUES ('c')"))
+
+ with engine.connect() as conn:
+ max_id_before = conn.execute(
+ text("SELECT MAX(id) FROM plain_ids")
+ ).scalar()
+
+ with engine.begin() as conn:
+ conn.execute(
+ text("DELETE FROM plain_ids WHERE id = :id"),
+ {"id": max_id_before},
+ )
+ conn.execute(text("INSERT INTO plain_ids (val) VALUES ('d')"))
+
+ with engine.connect() as conn:
+ new_id = conn.execute(
+ text("SELECT id FROM plain_ids WHERE val='d'")
+ ).scalar()
+
+ assert new_id == max_id_before, (
+ "control assumption broken: plain ROWID table did not "
+ "recycle the freed max id, so the AUTOINCREMENT test above "
+ "would pass even if migration 0024 were a no-op"
+ )
+ finally:
+ engine.dispose()
+
+ def test_downgrade_removes_autoincrement(self, engine_at_0024):
+ _downgrade_to(engine_at_0024, "0023")
+ sql = _table_sql(engine_at_0024, "document_chunks")
+ assert "AUTOINCREMENT" not in sql.upper()
+
+ def test_upgrade_preserves_existing_rows(self, engine_at_0023):
+ """Rows and their ids inserted before the 0024 rebuild must survive
+ the batch table-recreation unchanged."""
+ engine = engine_at_0023
+ with engine.begin() as conn:
+ _insert_chunk(conn, chunk_hash="pre-h1", collection_name="pre-c1")
+ _insert_chunk(conn, chunk_hash="pre-h2", collection_name="pre-c1")
+
+ with engine.connect() as conn:
+ before = sorted(
+ conn.execute(
+ text("SELECT id, chunk_hash FROM document_chunks")
+ ).fetchall()
+ )
+
+ _upgrade_to(engine, "0024")
+
+ with engine.connect() as conn:
+ after = sorted(
+ conn.execute(
+ text("SELECT id, chunk_hash FROM document_chunks")
+ ).fetchall()
+ )
+ assert before == after
+
+ def test_upgrade_downgrade_upgrade_round_trip_preserves_rows_and_reapplies_protection(
+ self, engine_at_0023
+ ):
+ """A full 0024 -> 0023 -> 0024 rebuild cycle must be lossless, and
+ the second upgrade must genuinely re-establish the id-reuse
+ protection — not merely leave the schema looking right while the
+ underlying SQLite AUTOINCREMENT bookkeeping was lost in the
+ downgrade/upgrade round trip.
+ """
+ engine = engine_at_0023
+ with engine.begin() as conn:
+ _insert_chunk(conn, chunk_hash="rt-h1", collection_name="rt-c1")
+ _insert_chunk(conn, chunk_hash="rt-h2", collection_name="rt-c1")
+ _insert_chunk(conn, chunk_hash="rt-h3", collection_name="rt-c1")
+
+ with engine.connect() as conn:
+ before = sorted(
+ conn.execute(
+ text("SELECT id, chunk_hash FROM document_chunks")
+ ).fetchall()
+ )
+ assert len(before) == 3, "seed failed"
+
+ _upgrade_to(engine, "0024")
+ _downgrade_to(engine, "0023")
+ _upgrade_to(engine, "0024")
+
+ assert _current_revision(engine) == "0024"
+
+ with engine.connect() as conn:
+ after = sorted(
+ conn.execute(
+ text("SELECT id, chunk_hash FROM document_chunks")
+ ).fetchall()
+ )
+ assert before == after, (
+ "the full set of (id, chunk_hash) rows must be identical after "
+ "an upgrade -> downgrade -> upgrade rebuild cycle"
+ )
+
+ sql = _table_sql(engine, "document_chunks")
+ assert "AUTOINCREMENT" in sql.upper(), (
+ "AUTOINCREMENT must be present again after the second upgrade, "
+ "not just the first"
+ )
+
+ # The id-reuse protection must be genuinely re-established by the
+ # second upgrade, not just reported present in the schema text:
+ # deleting the max-id row then inserting a new chunk must yield a
+ # strictly greater id, never a recycled one.
+ with engine.connect() as conn:
+ max_id_before = conn.execute(
+ text("SELECT MAX(id) FROM document_chunks")
+ ).scalar()
+
+ with engine.begin() as conn:
+ conn.execute(
+ text("DELETE FROM document_chunks WHERE id = :id"),
+ {"id": max_id_before},
+ )
+
+ with engine.begin() as conn:
+ _insert_chunk(conn, chunk_hash="rt-h4", collection_name="rt-c1")
+
+ with engine.connect() as conn:
+ new_id = conn.execute(
+ text("SELECT id FROM document_chunks WHERE chunk_hash='rt-h4'")
+ ).scalar()
+
+ assert new_id > max_id_before, (
+ f"id {new_id} was reused/recycled after the round trip, despite "
+ f"deleting the previous max id {max_id_before} — the second "
+ "upgrade did not genuinely re-establish AUTOINCREMENT protection"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Migration chain
+# ---------------------------------------------------------------------------
+
+
+class TestMigrationChain:
+ def test_single_head_no_branches(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ heads = script.get_heads()
+ assert len(heads) == 1, f"expected a single head, found {heads}"
+
+ def test_0023_chains_to_0022_and_0024_chains_to_0023(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ assert script.get_revision("0023").down_revision == "0022"
+ assert script.get_revision("0024").down_revision == "0023"
+
+ def test_0024_is_the_head(self):
+ from alembic.config import Config
+ from alembic.script import ScriptDirectory
+
+ from local_deep_research.database.alembic_runner import (
+ get_migrations_dir,
+ )
+
+ config = Config()
+ config.set_main_option("script_location", str(get_migrations_dir()))
+ script = ScriptDirectory.from_config(config)
+ (head,) = script.get_heads()
+ assert head == "0024"
diff --git a/tests/mcp/test_server_coverage.py b/tests/mcp/test_server_coverage.py
index e1efc62fba..3301476ffb 100644
--- a/tests/mcp/test_server_coverage.py
+++ b/tests/mcp/test_server_coverage.py
@@ -256,3 +256,42 @@ class TestGenerateReportValidation:
result = generate_report(query="test", searches_per_section=11)
assert result["status"] == "error"
assert result["error_type"] == "validation_error"
+
+
+# ---------------------------------------------------------------------------
+# run_server wires phase-1 legacy-plaintext migration
+# ---------------------------------------------------------------------------
+class TestRunServerRunsPhase1Migration:
+ """An MCP-only deployment (ldr-mcp) must still purge pre-existing legacy
+ plaintext .pkl docstores — run_server() calls migrate_legacy_docstores()
+ before handing off to mcp.run()."""
+
+ def test_run_server_calls_migrate_legacy_docstores(self, mocker):
+ from local_deep_research.mcp import server as mcp_server
+
+ mocker.patch.object(mcp_server.logger, "remove")
+ mocker.patch.object(mcp_server.logger, "add")
+ mocker.patch.object(mcp_server.mcp, "run")
+ migrate = mocker.patch(
+ "local_deep_research.vector_stores.legacy_cleanup.migrate_legacy_docstores"
+ )
+
+ mcp_server.run_server()
+
+ migrate.assert_called_once_with()
+
+ def test_run_server_survives_migration_failure(self, mocker):
+ """A migration error must never block the MCP server from starting."""
+ from local_deep_research.mcp import server as mcp_server
+
+ mocker.patch.object(mcp_server.logger, "remove")
+ mocker.patch.object(mcp_server.logger, "add")
+ run = mocker.patch.object(mcp_server.mcp, "run")
+ mocker.patch(
+ "local_deep_research.vector_stores.legacy_cleanup.migrate_legacy_docstores",
+ side_effect=OSError("disk gone"),
+ )
+
+ mcp_server.run_server() # must not raise
+
+ run.assert_called_once_with(transport="stdio")
diff --git a/tests/notes/test_post_review_bugfixes.py b/tests/notes/test_post_review_bugfixes.py
index 322b25517d..8d5b1363c4 100644
--- a/tests/notes/test_post_review_bugfixes.py
+++ b/tests/notes/test_post_review_bugfixes.py
@@ -13,6 +13,7 @@ import pytest
from local_deep_research.database.models import (
Collection,
Document,
+ DocumentChunk,
DocumentCollection,
NoteChangeType,
NoteVersion,
@@ -1123,6 +1124,68 @@ class TestDeleteNoteRagCleanup:
is None
)
+ def test_delete_note_purges_edit_window_collection_with_chunks(
+ self, patched_session, note_source_type
+ ):
+ # Edit->reindex window: DocumentCollection.indexed is False (cleared by
+ # the edit) but the note's pre-edit chunk rows/vectors still exist.
+ # delete_note must STILL purge them (gate on chunk-row existence, not
+ # just the indexed flag), or they orphan.
+ note_id = str(uuid.uuid4())
+ patched_session.add(
+ Document(
+ id=note_id,
+ title="edited note",
+ text_content="stale content",
+ file_type="note",
+ file_size=13,
+ source_type_id=note_source_type.id,
+ document_hash=_generate_hash("edit_window_note"),
+ tags=[],
+ )
+ )
+ coll = Collection(
+ id=str(uuid.uuid4()), name="edited", collection_type="notes"
+ )
+ patched_session.add(coll)
+ patched_session.add(
+ DocumentCollection(
+ document_id=note_id, collection_id=coll.id, indexed=False
+ )
+ )
+ patched_session.add(
+ DocumentChunk(
+ chunk_hash=_generate_hash("ew_chunk"),
+ source_type="document",
+ source_id=note_id,
+ collection_name=f"collection_{coll.id}",
+ chunk_text="stale",
+ chunk_index=0,
+ start_char=0,
+ end_char=5,
+ word_count=1,
+ embedding_id=str(uuid.uuid4()),
+ embedding_model="m",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ )
+ )
+ patched_session.commit()
+
+ mock_rag = MagicMock()
+ with patch(
+ "local_deep_research.research_library.services.rag_service_factory.get_rag_service"
+ ) as mock_factory:
+ mock_factory.return_value.__enter__.return_value = mock_rag
+ ok = NoteService(username="testuser").delete_note(note_id)
+
+ assert ok is True
+ # Despite indexed=False, the chunk-bearing collection is purged.
+ purged = {
+ c.args[1] for c in mock_rag.purge_document_chunks.call_args_list
+ }
+ assert coll.id in purged
+
class TestDbPasswordGuard:
"""fix: when ``_capture_request_db_password`` returns None
diff --git a/tests/research_library/conftest.py b/tests/research_library/conftest.py
index a3344bee23..07cc320f17 100644
--- a/tests/research_library/conftest.py
+++ b/tests/research_library/conftest.py
@@ -332,7 +332,6 @@ def mock_embedding_manager(mocker):
mock.embeddings = mocker.Mock()
mock.embeddings.embed_query.return_value = [0.1] * 384
mock.embeddings.embed_documents.return_value = [[0.1] * 384]
- mock._store_chunks_to_db.return_value = ["chunk_1", "chunk_2"]
mock._delete_chunks_from_db.return_value = 5
return mock
diff --git a/tests/research_library/deletion/services/test_collection_deletion.py b/tests/research_library/deletion/services/test_collection_deletion.py
index b1d93df951..b0560cb283 100644
--- a/tests/research_library/deletion/services/test_collection_deletion.py
+++ b/tests/research_library/deletion/services/test_collection_deletion.py
@@ -1,13 +1,19 @@
"""Tests for CollectionDeletionService."""
+from contextlib import contextmanager
from unittest.mock import MagicMock, Mock, patch
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from local_deep_research.database.models import Base
from local_deep_research.database.models.library import (
Collection,
CollectionFolder,
Document,
DocumentCollection,
+ EmbeddingProvider,
+ RAGIndex,
SourceType,
)
from local_deep_research.research_library.deletion.services.collection_deletion import (
@@ -80,7 +86,8 @@ class TestCollectionDeletionServiceDeleteCollection:
) as mock_helper:
mock_helper.delete_collection_chunks.return_value = 10
mock_helper.delete_rag_indices_for_collection.return_value = {
- "deleted_indices": 1
+ "deleted_indices": 1,
+ "index_paths": [],
}
result = service.delete_collection("col-123")
@@ -123,7 +130,8 @@ class TestCollectionDeletionServiceDeleteCollection:
) as mock_helper:
mock_helper.delete_collection_chunks.return_value = 5
mock_helper.delete_rag_indices_for_collection.return_value = {
- "deleted_indices": 1
+ "deleted_indices": 1,
+ "index_paths": [],
}
mock_helper.delete_document_completely.return_value = True
@@ -213,7 +221,8 @@ class TestCollectionDeletionServiceOrphanedNoteProtection:
) as mock_helper:
mock_helper.delete_collection_chunks.return_value = 0
mock_helper.delete_rag_indices_for_collection.return_value = {
- "deleted_indices": 0
+ "deleted_indices": 0,
+ "index_paths": [],
}
result = service.delete_collection(
@@ -302,7 +311,8 @@ class TestCollectionDeletionServiceDeleteIndexOnly:
) as mock_helper:
mock_helper.delete_collection_chunks.return_value = 20
mock_helper.delete_rag_indices_for_collection.return_value = {
- "deleted_indices": 1
+ "deleted_indices": 1,
+ "index_paths": [],
}
result = service.delete_collection_index_only("col-123")
@@ -364,3 +374,115 @@ class TestCollectionDeletionServiceGetDeletionPreview:
assert result["name"] == "Test Collection"
assert result["documents_count"] == 10
assert result["has_rag_index"] is True
+
+
+class TestCollectionDeletionServiceIndexOnlyPostCommitUnlink:
+ """Tripwire for delete_collection_index_only's post-commit FAISS unlink.
+
+ Unlike delete_collection (explicitly fixed so its post-commit unlink loop
+ runs OUTSIDE the try/except — a file-unlink failure there can never
+ misreport an already-committed DB delete as failed),
+ delete_collection_index_only's post-commit unlink loop is still INSIDE
+ the try/except. Today this stays green because
+ CascadeHelper.delete_faiss_index_files swallows its own exceptions and
+ never propagates. If that helper is ever changed to raise instead, this
+ method would report ``deleted: False`` even though the DB commit already
+ durably persisted the index deletion — a misreported failure. This test
+ forces that latent path (by mocking the helper to raise) and asserts the
+ DB state so a future change surfaces the misreport loudly.
+ """
+
+ def test_delete_collection_index_only_postcommit_unlink_exception_does_not_misreport_failure(
+ self, tmp_path, monkeypatch
+ ):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ collection_id = "col-tripwire"
+ collection_name = f"collection_{collection_id}"
+
+ session.add(
+ Collection(
+ id=collection_id,
+ name="Tripwire Collection",
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=8,
+ chunk_size=500,
+ chunk_overlap=50,
+ )
+ )
+ session.add(
+ RAGIndex(
+ collection_name=collection_name,
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=8,
+ index_path=str(tmp_path / f"{collection_name}.faiss"),
+ index_hash="deadbeef" * 8,
+ chunk_size=500,
+ chunk_overlap=50,
+ )
+ )
+ session.add(
+ DocumentCollection(
+ document_id="doc-1",
+ collection_id=collection_id,
+ indexed=True,
+ chunk_count=3,
+ )
+ )
+ session.commit()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ with patch(
+ "local_deep_research.research_library.deletion.services.collection_deletion.get_user_db_session",
+ _shared_session,
+ ):
+ with patch(
+ "local_deep_research.research_library.deletion.services.collection_deletion.CascadeHelper.delete_faiss_index_files",
+ side_effect=Exception("boom"),
+ ):
+ service = CollectionDeletionService(username="testuser")
+ result = service.delete_collection_index_only(collection_id)
+
+ # Misreported: the exception is caught by the surrounding try/except,
+ # which rolls back (a no-op here — already committed) and returns
+ # deleted=False.
+ assert result["deleted"] is False
+
+ # But the commit already happened BEFORE the unlink loop raised, so
+ # the DB-side deletion is durably persisted despite the reported
+ # failure — the RAGIndex row is gone, DocumentCollection status was
+ # reset, and the collection's embedding info was cleared.
+ session.expire_all()
+ assert (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .first()
+ is None
+ )
+
+ doc_collection = (
+ session.query(DocumentCollection)
+ .filter_by(collection_id=collection_id)
+ .first()
+ )
+ assert doc_collection.indexed is False
+ assert doc_collection.chunk_count == 0
+
+ collection = session.query(Collection).get(collection_id)
+ assert collection.embedding_model is None
+ assert collection.embedding_model_type is None
+ assert collection.embedding_dimension is None
+ assert collection.chunk_size is None
+ assert collection.chunk_overlap is None
+
+ session.close()
+ engine.dispose()
diff --git a/tests/research_library/deletion/services/test_collection_deletion_flow.py b/tests/research_library/deletion/services/test_collection_deletion_flow.py
new file mode 100644
index 0000000000..22aca39418
--- /dev/null
+++ b/tests/research_library/deletion/services/test_collection_deletion_flow.py
@@ -0,0 +1,658 @@
+"""LARGE complete-flow test: collection deletion SAFETY with REAL DB + REAL
+on-disk FAISS files.
+
+Drives the real production stack end to end:
+
+ * ``LibraryRAGService.index_document`` (real chunk splitting + real
+ ``VectorIndex``/``FaissVectorStore``) to build a genuine ``.faiss`` file
+ under ``cache/rag_indices`` and real ``DocumentChunk``/``RAGIndex`` rows,
+ exactly as ``tests/vector_stores/test_no_plaintext_production_path.py``
+ does.
+ * ``CollectionDeletionService.delete_collection`` (the real service under
+ test) against that on-disk state.
+
+Focus is the FLOW + rollback/orphan safety of ``delete_collection`` — NOT the
+low-level ``unlink_files`` file-sweep contract, which is already covered by
+``tests/research_library/deletion/utils/test_cascade_helper_sweep.py``.
+
+Covered:
+ (a) HAPPY PATH — index a real collection with 2 documents, delete it,
+ confirm the ``.faiss`` file is gone, ``DocumentChunk`` rows are gone,
+ and the ``RAGIndex`` row is gone.
+ (b) DEFERRED-UNLINK ORDER — a forced mid-transaction failure (raised
+ between the RAGIndex row-delete and the commit) rolls back the DB
+ change AND leaves the ``.faiss`` file on disk untouched (no
+ rollback-orphan where the row is restored but the file is already
+ gone). Verified via a completely FRESH session/connection against a
+ file-backed sqlite DB, not just the mutated in-process session.
+ (c) POST-COMMIT UNLINK FAILURE SWALLOWED — the on-disk unlink is made to
+ fail (permission-denied directory) AFTER a successful commit; the
+ delete must still report success and the DB rows must still be gone.
+ (d) ORPHANED-DOCUMENT CROSS-COLLECTION SAFETY — a document that lives in
+ TWO collections: deleting one collection must leave the other
+ collection's chunks/vectors, and a real semantic search against it,
+ completely untouched.
+
+Each destructive scenario is paired with a "control" run that behaves
+normally, so the injected-failure assertions are proven to actually bite
+(they are not vacuously true).
+"""
+
+import uuid
+from contextlib import contextmanager
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.config.paths import get_cache_directory
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ RAGIndex,
+ SourceType,
+)
+from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+_FACADE_MOD = "local_deep_research.vector_stores.facade"
+_COLLECTION_DELETION_MOD = (
+ "local_deep_research.research_library.deletion.services.collection_deletion"
+)
+
+USERNAME = "flowuser"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings (mirrors the canonical harness
+ in ``tests/vector_stores/test_no_plaintext_production_path.py``)."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _make_document(
+ session, *, title: str, body: str, source_type_id: str
+) -> str:
+ import hashlib
+
+ document_id = uuid.uuid4().hex
+ session.add(
+ Document(
+ id=document_id,
+ source_type_id=source_type_id,
+ document_hash=hashlib.sha256(body.encode()).hexdigest(),
+ title=title,
+ text_content=body,
+ original_url=f"http://example.com/{document_id}",
+ file_size=len(body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ return document_id
+
+
+def flow_env(tmp_path, monkeypatch, mocker):
+ """Real, file-backed sqlite DB + real on-disk cache tree.
+
+ File-backed (not ``:memory:``) so a completely FRESH session (a new
+ connection to the same file) can verify persisted state independent of
+ the mutated in-process session's identity map — required for the
+ rollback assertions in test (b) to be meaningful.
+ """
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ db_path = tmp_path / "flow.db"
+ engine = create_engine(f"sqlite:///{db_path}")
+ Base.metadata.create_all(engine)
+ SessionLocal = sessionmaker(bind=engine)
+ session = SessionLocal()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _shared_session)
+ mocker.patch(f"{_FACADE_MOD}.get_user_db_session", _shared_session)
+ mocker.patch(
+ f"{_COLLECTION_DELETION_MOD}.get_user_db_session", _shared_session
+ )
+
+ fim = MagicMock()
+ fim.verify_file.return_value = (True, None)
+ fim.record_file.return_value = None
+ mocker.patch(f"{_RAG_MOD}.FileIntegrityManager", return_value=fim)
+
+ source_type = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(source_type)
+ session.commit()
+
+ class Env:
+ pass
+
+ env = Env()
+ env.tmp_path = tmp_path
+ env.engine = engine
+ env.SessionLocal = SessionLocal
+ env.session = session
+ env.source_type_id = source_type.id
+
+ yield env
+
+ session.close()
+ engine.dispose()
+
+
+def _index_two_documents(env, collection_id: str):
+ """Index two real documents into ``collection_id`` via the real
+ ``LibraryRAGService.index_document`` production path. Returns
+ (document_id_1, document_id_2)."""
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = _FakeEmbeddings(dim=8)
+
+ svc = LibraryRAGService(
+ username=USERNAME,
+ db_password="pw", # gitleaks:allow
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ )
+ try:
+ doc1 = _make_document(
+ env.session,
+ title="Doc One",
+ body="The quick brown fox jumps over the lazy dog. " * 10,
+ source_type_id=env.source_type_id,
+ )
+ doc2 = _make_document(
+ env.session,
+ title="Doc Two",
+ body="A second unrelated document about mountain climbing. " * 10,
+ source_type_id=env.source_type_id,
+ )
+ env.session.commit()
+
+ r1 = svc.index_document(doc1, collection_id)
+ r2 = svc.index_document(doc2, collection_id)
+ assert r1["status"] == "success", r1
+ assert r2["status"] == "success", r2
+ assert r1["chunk_count"] > 0
+ assert r2["chunk_count"] > 0
+ finally:
+ svc.close()
+
+ return doc1, doc2
+
+
+def _make_collection(env, *, name: str) -> str:
+ collection_id = uuid.uuid4().hex
+ env.session.add(Collection(id=collection_id, name=name))
+ env.session.commit()
+ return collection_id
+
+
+def _rag_index_rows(session, collection_name: str):
+ return (
+ session.query(RAGIndex).filter_by(collection_name=collection_name).all()
+ )
+
+
+def _chunk_count(session, collection_name: str) -> int:
+ return (
+ session.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ )
+
+
+# --------------------------------------------------------------------------
+# (a) Happy path
+# --------------------------------------------------------------------------
+class TestHappyPathDeletesEverything:
+ def test_delete_collection_removes_faiss_file_and_db_rows(self, flow_env):
+ env = flow_env
+ collection_id = _make_collection(env, name="Happy Path Collection")
+ collection_name = f"collection_{collection_id}"
+
+ _index_two_documents(env, collection_id)
+
+ # Preconditions: real state actually exists before deletion.
+ rag_rows_before = _rag_index_rows(env.session, collection_name)
+ assert len(rag_rows_before) == 1
+ faiss_path = Path(rag_rows_before[0].index_path).with_suffix(".faiss")
+ assert faiss_path.is_file()
+ assert faiss_path.stat().st_size > 0
+ assert _chunk_count(env.session, collection_name) > 0
+
+ # Also confirm it lives under the real cache/rag_indices tree.
+ rag_root = get_cache_directory() / "rag_indices"
+ assert list(rag_root.rglob("*.faiss")), (
+ "expected the real production indexing path to have written "
+ "under cache/rag_indices"
+ )
+
+ service = CollectionDeletionService(username=USERNAME)
+ result = service.delete_collection(
+ collection_id, delete_orphaned_documents=False
+ )
+
+ assert result["deleted"] is True, result
+ assert result["indices_deleted"] == 1
+ assert result["chunks_deleted"] > 0
+
+ # Observable on-disk state: the .faiss file is really gone.
+ assert not faiss_path.is_file(), (
+ "the .faiss index file should have been unlinked after a "
+ "successful collection delete"
+ )
+
+ # Observable DB state: chunks and the RAGIndex row are really gone.
+ assert _chunk_count(env.session, collection_name) == 0
+ assert _rag_index_rows(env.session, collection_name) == []
+
+ # And the collection row itself is gone.
+ assert (
+ env.session.query(Collection).filter_by(id=collection_id).first()
+ is None
+ )
+
+
+# --------------------------------------------------------------------------
+# (b) Deferred-unlink order: mid-transaction failure rolls back the DB and
+# leaves the file on disk (no restored-row-but-missing-file orphan).
+# --------------------------------------------------------------------------
+class TestDeferredUnlinkOrderOnRollback:
+ def _inject_failure_on_collection_delete(self, session):
+ """Monkeypatch this session's ``.delete`` to raise the FIRST time
+ it is asked to delete a ``Collection`` row — i.e. AFTER the RAGIndex
+ rows have already been staged for deletion (an earlier step in
+ ``delete_collection``) but BEFORE ``session.commit()``."""
+ original_delete = session.delete
+
+ def _boom(instance):
+ if isinstance(instance, Collection):
+ raise RuntimeError("INJECTED_MID_TRANSACTION_FAILURE")
+ return original_delete(instance)
+
+ session.delete = _boom
+ return original_delete
+
+ def test_mid_transaction_failure_rolls_back_row_and_leaves_file(
+ self, flow_env
+ ):
+ env = flow_env
+ collection_id = _make_collection(env, name="Rollback Collection")
+ collection_name = f"collection_{collection_id}"
+
+ _index_two_documents(env, collection_id)
+
+ rag_rows_before = _rag_index_rows(env.session, collection_name)
+ assert len(rag_rows_before) == 1
+ faiss_path = Path(rag_rows_before[0].index_path).with_suffix(".faiss")
+ assert faiss_path.is_file()
+ chunks_before = _chunk_count(env.session, collection_name)
+ assert chunks_before > 0
+
+ self._inject_failure_on_collection_delete(env.session)
+
+ service = CollectionDeletionService(username=USERNAME)
+ result = service.delete_collection(
+ collection_id, delete_orphaned_documents=False
+ )
+
+ assert result["deleted"] is False
+ assert "error" in result
+
+ # The file must NOT have been touched: delete_collection's
+ # post-commit unlink loop is unreachable once the except-branch's
+ # early `return` fires.
+ assert faiss_path.is_file(), (
+ "the .faiss file was unlinked despite the transaction rolling "
+ "back — a rollback-orphan (row restored, file already gone)"
+ )
+
+ # Verify the DB rollback via a COMPLETELY FRESH session/connection
+ # against the file-backed DB — not the mutated in-process session —
+ # so this is a real persisted-state check, not an ORM identity-map
+ # artifact.
+ fresh = env.SessionLocal()
+ try:
+ fresh_rows = (
+ fresh.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .all()
+ )
+ assert len(fresh_rows) == 1, (
+ "RAGIndex row was not rolled back after the injected "
+ "mid-transaction failure"
+ )
+ assert (
+ fresh.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == chunks_before
+ ), "DocumentChunk rows were not rolled back"
+ assert (
+ fresh.query(Collection).filter_by(id=collection_id).first()
+ is not None
+ ), "Collection row was not rolled back"
+ finally:
+ fresh.close()
+
+ def test_control_without_injected_failure_both_row_and_file_go(
+ self, flow_env
+ ):
+ """Control: proves the assertions above actually bite. Without the
+ injected failure, the SAME setup results in the row AND the file
+ both being removed — so "row restored / file present" in the test
+ above is a real signal of a bug, not something that always holds."""
+ env = flow_env
+ collection_id = _make_collection(env, name="Control Collection")
+ collection_name = f"collection_{collection_id}"
+
+ _index_two_documents(env, collection_id)
+ rag_rows_before = _rag_index_rows(env.session, collection_name)
+ faiss_path = Path(rag_rows_before[0].index_path).with_suffix(".faiss")
+ assert faiss_path.is_file()
+
+ # No failure injected this time.
+ service = CollectionDeletionService(username=USERNAME)
+ result = service.delete_collection(
+ collection_id, delete_orphaned_documents=False
+ )
+
+ assert result["deleted"] is True, result
+ assert not faiss_path.is_file()
+ fresh = env.SessionLocal()
+ try:
+ assert (
+ fresh.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == 0
+ )
+ finally:
+ fresh.close()
+
+
+# --------------------------------------------------------------------------
+# (c) Post-commit unlink failure is swallowed: a committed delete must not
+# be reported as failed just because a file could not be removed.
+# --------------------------------------------------------------------------
+class TestPostCommitUnlinkFailureSwallowed:
+ def test_unlink_failure_after_commit_still_reports_success(self, flow_env):
+ env = flow_env
+ collection_id = _make_collection(env, name="Unlink Failure Collection")
+ collection_name = f"collection_{collection_id}"
+
+ _index_two_documents(env, collection_id)
+
+ rag_rows_before = _rag_index_rows(env.session, collection_name)
+ assert len(rag_rows_before) == 1
+ faiss_path = Path(rag_rows_before[0].index_path).with_suffix(".faiss")
+ assert faiss_path.is_file()
+
+ service = CollectionDeletionService(username=USERNAME)
+
+ # Force the post-commit on-disk unlink to fail the way a genuine
+ # permission/IO error would — WITHOUT relying on directory mode bits.
+ # CI runs as root, which bypasses a read-only (0o555) directory and
+ # unlinks the file anyway, making the old chmod approach vacuous (and
+ # red in CI). Patching Path.unlink to raise drives
+ # CascadeHelper.delete_faiss_index_files into its best-effort
+ # except-swallow branch with the file left on disk — exactly the
+ # state a real unlink failure produces. Scoped to the delete call so
+ # the real cleanup sweep at the end still runs normally.
+ with patch(
+ "pathlib.Path.unlink",
+ side_effect=PermissionError("simulated read-only directory"),
+ ):
+ result = service.delete_collection(
+ collection_id, delete_orphaned_documents=False
+ )
+
+ # The DB delete committed durably; a mere unlink hiccup must NOT flip
+ # this into a reported failure.
+ assert result["deleted"] is True, result
+ assert result["indices_deleted"] == 1
+
+ # The file-unlink genuinely failed and is still on disk (proves the
+ # injected failure really fired, not a no-op).
+ assert faiss_path.is_file(), (
+ "expected the on-disk unlink to have been blocked (Path.unlink "
+ "patched to raise) — if the file is gone the failure never "
+ "actually fired and this test is vacuous"
+ )
+
+ # DB rows are gone regardless of the on-disk hiccup.
+ fresh = env.SessionLocal()
+ try:
+ assert (
+ fresh.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == 0
+ )
+ assert (
+ fresh.query(DocumentChunk)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == 0
+ )
+ finally:
+ fresh.close()
+
+ # Now that permissions are restored, a fresh delete_faiss_index_files
+ # sweep would succeed — proving the earlier failure was a real,
+ # transient permission issue and not some unrelated brokenness.
+ from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+ )
+
+ assert (
+ CascadeHelper.delete_faiss_index_files(
+ str(faiss_path.with_suffix(""))
+ )
+ is True
+ )
+ assert not faiss_path.is_file()
+
+ def test_control_writable_dir_unlink_succeeds(self, flow_env):
+ """Control: proves the patched-unlink failure above is what causes
+ the earlier "file survives" — with a real (unpatched) unlink the same
+ delete removes the file, so "file survives" isn't just how this store
+ always behaves."""
+ env = flow_env
+ collection_id = _make_collection(env, name="Writable Dir Collection")
+ collection_name = f"collection_{collection_id}"
+
+ _index_two_documents(env, collection_id)
+ rag_rows_before = _rag_index_rows(env.session, collection_name)
+ faiss_path = Path(rag_rows_before[0].index_path).with_suffix(".faiss")
+ assert faiss_path.is_file()
+
+ service = CollectionDeletionService(username=USERNAME)
+ result = service.delete_collection(
+ collection_id, delete_orphaned_documents=False
+ )
+
+ assert result["deleted"] is True
+ assert not faiss_path.is_file()
+
+
+# --------------------------------------------------------------------------
+# (d) Orphaned-document cross-collection safety: a document shared by two
+# collections must keep its OTHER collection's chunks/vectors intact
+# when one collection is deleted.
+# --------------------------------------------------------------------------
+class TestCrossCollectionSafety:
+ def test_deleting_one_collection_leaves_other_collections_intact(
+ self, flow_env
+ ):
+ env = flow_env
+ collection_a = _make_collection(env, name="Collection A")
+ collection_b = _make_collection(env, name="Collection B")
+ collection_name_a = f"collection_{collection_a}"
+ collection_name_b = f"collection_{collection_b}"
+
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = _FakeEmbeddings(dim=8)
+ svc = LibraryRAGService(
+ username=USERNAME,
+ db_password="pw", # gitleaks:allow
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ )
+ try:
+ shared_doc = _make_document(
+ env.session,
+ title="Shared Doc",
+ body="This content is shared across two collections and must "
+ "survive deletion of just one of them. " * 8,
+ source_type_id=env.source_type_id,
+ )
+ only_in_b = _make_document(
+ env.session,
+ title="Only In B",
+ body="This document lives only in collection B. " * 8,
+ source_type_id=env.source_type_id,
+ )
+ env.session.commit()
+
+ # Index the shared doc into BOTH collections, and a second doc
+ # only into B (so B is not trivially empty after A is deleted).
+ r_a = svc.index_document(shared_doc, collection_a)
+ r_b1 = svc.index_document(shared_doc, collection_b)
+ r_b2 = svc.index_document(only_in_b, collection_b)
+ assert r_a["status"] == "success", r_a
+ assert r_b1["status"] == "success", r_b1
+ assert r_b2["status"] == "success", r_b2
+
+ # B's shared search works BEFORE the deletion (sanity baseline).
+ hits_before = svc.search(
+ "shared across two collections", collection_b, top_k=5
+ )
+ assert hits_before
+ finally:
+ svc.close()
+
+ rag_rows_a = _rag_index_rows(env.session, collection_name_a)
+ rag_rows_b = _rag_index_rows(env.session, collection_name_b)
+ assert len(rag_rows_a) == 1
+ assert len(rag_rows_b) == 1
+ faiss_a = Path(rag_rows_a[0].index_path).with_suffix(".faiss")
+ faiss_b = Path(rag_rows_b[0].index_path).with_suffix(".faiss")
+ assert faiss_a.is_file()
+ assert faiss_b.is_file()
+
+ chunks_b_before = _chunk_count(env.session, collection_name_b)
+ assert chunks_b_before > 0
+
+ # The shared document is NOT orphaned by deleting A (it remains
+ # linked to B), so delete_orphaned_documents's value should not
+ # matter here — use the default (True) to also prove that.
+ service = CollectionDeletionService(username=USERNAME)
+ result = service.delete_collection(collection_a)
+
+ assert result["deleted"] is True, result
+ # The shared doc must not have been treated as orphaned.
+ assert result["orphaned_documents_deleted"] == 0
+
+ # Collection A's own index/chunks are gone.
+ assert not faiss_a.is_file()
+ assert _chunk_count(env.session, collection_name_a) == 0
+ assert _rag_index_rows(env.session, collection_name_a) == []
+
+ # Collection B is COMPLETELY untouched: same file, same chunk count,
+ # same RAGIndex row, and the document row itself still exists.
+ assert faiss_b.is_file()
+ assert faiss_b.stat().st_size > 0
+ assert _chunk_count(env.session, collection_name_b) == chunks_b_before
+ assert len(_rag_index_rows(env.session, collection_name_b)) == 1
+ assert (
+ env.session.query(Document).filter_by(id=shared_doc).first()
+ is not None
+ ), "the shared document itself must not have been hard-deleted"
+ assert (
+ env.session.query(DocumentCollection)
+ .filter_by(document_id=shared_doc, collection_id=collection_b)
+ .first()
+ is not None
+ )
+
+ # Strongest proof: a REAL search against B's live store still finds
+ # the shared document's content, rehydrated from the DB.
+ emb_mgr2 = MagicMock()
+ emb_mgr2.embeddings = _FakeEmbeddings(dim=8)
+ svc2 = LibraryRAGService(
+ username=USERNAME,
+ db_password="pw", # gitleaks:allow
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr2,
+ )
+ try:
+ hits_after = svc2.search(
+ "shared across two collections", collection_b, top_k=5
+ )
+ assert hits_after, (
+ "collection B's search broke after deleting unrelated "
+ "collection A"
+ )
+ finally:
+ svc2.close()
+
+ # And FaissVectorStore.load() on B's real on-disk file directly
+ # shows its ids are still all live (no vectors silently dropped).
+ from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+ )
+
+ store_b = FaissVectorStore.load(
+ faiss_b,
+ dimension=8,
+ index_type=rag_rows_b[0].index_type or "flat",
+ metric=rag_rows_b[0].distance_metric or "cosine",
+ normalize=(
+ rag_rows_b[0].normalize_vectors
+ if rag_rows_b[0].normalize_vectors is not None
+ else True
+ ),
+ )
+ live_ids = store_b.live_ids()
+ db_ids = [
+ row.id
+ for row in env.session.query(DocumentChunk.id)
+ .filter_by(collection_name=collection_name_b)
+ .all()
+ ]
+ assert set(live_ids) == set(db_ids)
+ assert len(live_ids) == chunks_b_before
diff --git a/tests/research_library/deletion/services/test_document_deletion.py b/tests/research_library/deletion/services/test_document_deletion.py
index 1b66b5ba2c..21e60b3e65 100644
--- a/tests/research_library/deletion/services/test_document_deletion.py
+++ b/tests/research_library/deletion/services/test_document_deletion.py
@@ -67,12 +67,17 @@ class TestDocumentDeletionServiceDeleteDocument:
mock_doc.storage_mode = "database"
mock_doc.file_path = None
mock_session.query.return_value.get.return_value = mock_doc
-
- with patch(
- "local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper"
- ) as mock_helper:
+ # chunks_deleted now comes from a COUNT query (rows are removed
+ # in the post-commit purge phase, not inline).
+ mock_session.query.return_value.filter.return_value.count.return_value = 5
+
+ with (
+ patch(
+ "local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper"
+ ) as mock_helper,
+ patch.object(service, "_purge_document_rag") as mock_purge,
+ ):
mock_helper.get_document_collections.return_value = ["col-1"]
- mock_helper.delete_document_chunks.return_value = 5
mock_helper.get_document_blob_size.return_value = 1024
mock_helper.delete_document_completely.return_value = True
@@ -82,6 +87,9 @@ class TestDocumentDeletionServiceDeleteDocument:
assert result["document_id"] == "doc-123"
assert result["chunks_deleted"] == 5
assert result["blob_size"] == 1024
+ # FAISS vectors + chunk rows are purged post-commit as a full delete.
+ mock_purge.assert_called_once()
+ assert mock_purge.call_args.kwargs["full_delete"] is True
def test_handles_exception_gracefully(self):
"""Should handle exceptions and rollback."""
@@ -245,11 +253,16 @@ class TestDocumentDeletionServiceRemoveFromCollection:
# Set up query chain
mock_session.query.return_value.get.return_value = mock_doc
mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc_collection
-
- with patch(
- "local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper"
- ) as mock_helper:
- mock_helper.delete_document_chunks.return_value = 3
+ # chunks_deleted now comes from a COUNT query (rows are removed
+ # in the post-commit purge phase, not inline).
+ mock_session.query.return_value.filter.return_value.count.return_value = 3
+
+ with (
+ patch(
+ "local_deep_research.research_library.deletion.services.document_deletion.CascadeHelper"
+ ) as mock_helper,
+ patch.object(service, "_purge_document_rag") as mock_purge,
+ ):
mock_helper.count_document_in_collections.return_value = (
1 # Still in another collection
)
@@ -259,6 +272,10 @@ class TestDocumentDeletionServiceRemoveFromCollection:
assert result["unlinked"] is True
assert result["chunks_deleted"] == 3
assert result["document_deleted"] is False
+ # A plain unlink purges only THIS collection's vectors/chunks.
+ mock_purge.assert_called_once()
+ assert mock_purge.call_args.kwargs["full_delete"] is False
+ assert mock_purge.call_args.args[1] == ["col-456"]
class TestDocumentDeletionServiceGetDeletionPreview:
diff --git a/tests/research_library/deletion/services/test_document_deletion_coverage.py b/tests/research_library/deletion/services/test_document_deletion_coverage.py
index 2c5d3d820a..2c26690ba9 100644
--- a/tests/research_library/deletion/services/test_document_deletion_coverage.py
+++ b/tests/research_library/deletion/services/test_document_deletion_coverage.py
@@ -4,9 +4,21 @@ Covers uncovered paths: filesystem deletion, title fallbacks, orphaned documents
multiple collections, exception handling in blob deletion, filesystem errors, etc.
"""
+import uuid
+from contextlib import contextmanager
from unittest.mock import MagicMock, Mock, patch
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ EmbeddingProvider,
+)
from local_deep_research.research_library.deletion.services.document_deletion import (
DocumentDeletionService,
)
@@ -15,6 +27,10 @@ MODULE_PATH = (
"local_deep_research.research_library.deletion.services.document_deletion"
)
UTILS_PATH = "local_deep_research.research_library.utils"
+RAG_SERVICE_FACTORY_PATH = (
+ "local_deep_research.research_library.services.rag_service_factory."
+ "get_rag_service"
+)
def _make_session_context():
@@ -181,14 +197,19 @@ class TestDeleteDocumentMultipleCollections:
mock_doc.storage_mode = "database"
mock_doc.file_path = None
mock_session.query.return_value.get.return_value = mock_doc
+ # chunks_deleted is now a COUNT of the document's chunk rows;
+ # the rows/vectors are removed in the post-commit purge phase.
+ mock_session.query.return_value.filter.return_value.count.return_value = 10
- with patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper:
+ with (
+ patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper,
+ patch.object(service, "_purge_document_rag") as mock_purge,
+ ):
mock_helper.get_document_collections.return_value = [
"col-1",
"col-2",
"col-3",
]
- mock_helper.delete_document_chunks.side_effect = [3, 5, 2]
mock_helper.get_document_blob_size.return_value = 512
mock_helper.delete_document_completely.return_value = True
@@ -199,7 +220,10 @@ class TestDeleteDocumentMultipleCollections:
assert result["collections_unlinked"] == 3
assert result["blob_deleted"] is True
assert result["blob_size"] == 512
- assert mock_helper.delete_document_chunks.call_count == 3
+ # Post-commit purge covers all three collections as a full delete.
+ mock_purge.assert_called_once()
+ assert mock_purge.call_args.kwargs["full_delete"] is True
+ assert set(mock_purge.call_args.args[1]) == {"col-1", "col-2", "col-3"}
def test_blob_size_zero_means_blob_not_deleted(self):
"""Should set blob_deleted=False when blob_size is 0."""
@@ -263,7 +287,10 @@ class TestDeleteDocumentExceptionRollback:
mock_doc.file_path = None
mock_session.query.return_value.get.return_value = mock_doc
- with patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper:
+ with (
+ patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper,
+ patch.object(service, "_purge_document_rag"),
+ ):
mock_helper.get_document_collections.return_value = []
mock_helper.get_document_blob_size.return_value = 0
mock_helper.delete_document_completely.return_value = True
@@ -271,6 +298,8 @@ class TestDeleteDocumentExceptionRollback:
result = service.delete_document("doc-12345678")
assert result["deleted"] is True
+ # One commit for the deletion transaction (the post-commit purge —
+ # which opens its own session — is isolated here).
mock_session.commit.assert_called_once()
@@ -580,8 +609,10 @@ class TestRemoveFromCollectionException:
mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc_collection
with patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper:
- mock_helper.delete_document_chunks.side_effect = Exception(
- "db error"
+ # Chunk rows are no longer deleted inline; raise from the
+ # collection-count step, which runs inside the transaction.
+ mock_helper.count_document_in_collections.side_effect = (
+ Exception("db error")
)
result = service.remove_from_collection(
"doc-12345678", "col-12345678"
@@ -630,8 +661,10 @@ class TestRemoveFromCollectionException:
mock_session.query.return_value.get.return_value = mock_doc
mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc_collection
- with patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper:
- mock_helper.delete_document_chunks.return_value = 0
+ with (
+ patch(f"{MODULE_PATH}.CascadeHelper") as mock_helper,
+ patch.object(service, "_purge_document_rag"),
+ ):
mock_helper.count_document_in_collections.return_value = 1
result = service.remove_from_collection(
@@ -639,6 +672,7 @@ class TestRemoveFromCollectionException:
)
assert result["unlinked"] is True
+ # One commit for the unlink transaction (post-commit purge isolated).
mock_session.commit.assert_called_once()
mock_session.delete.assert_called_once_with(mock_doc_collection)
@@ -815,3 +849,228 @@ class TestRemoveFromCollectionOrphanedNoFilePath:
assert result["unlinked"] is True
assert result["document_deleted"] is True
mock_helper.delete_filesystem_file.assert_not_called()
+
+
+def _make_real_chunk(document_id, collection_name, index=0):
+ """Build a real, valid DocumentChunk row for a real (in-memory) session.
+
+ Fills every NOT NULL column so it can actually be inserted/committed --
+ the whole point of these tests is running _purge_document_rag against a
+ real session instead of a mock.
+ """
+ return DocumentChunk(
+ chunk_hash=f"hash-{uuid.uuid4().hex}",
+ source_type="document",
+ source_id=document_id,
+ collection_name=collection_name,
+ chunk_text=f"chunk text {index}",
+ chunk_index=index,
+ start_char=0,
+ end_char=10,
+ word_count=2,
+ embedding_id=uuid.uuid4().hex,
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ )
+
+
+def _make_real_session():
+ """A fresh in-memory-sqlite session over the real Base metadata."""
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ return sessionmaker(bind=engine)()
+
+
+@contextmanager
+def _shared_session_cm(session):
+ """A get_user_db_session-shaped context manager yielding one real session."""
+ yield session
+
+
+class TestRemoveFromCollectionOrphanRealSession:
+ """Real (in-memory sqlite) session tests for the orphan branch of
+ remove_from_collection (~lines 584-600): rag_collection_ids is built as
+ the UNION of the removed collection_id with every distinct
+ "collection_<id>" prefix still present among the document's
+ DocumentChunk rows, via `{collection_id} | {row.removeprefix(...)}`.
+
+ Every other orphan test in this file fully mocks the session, so
+ chunk_collection_rows iterates empty and this union/removeprefix logic
+ never actually runs against real distinct rows.
+ """
+
+ def test_remove_from_collection_orphan_purges_all_stranded_collections_not_just_removed_one(
+ self,
+ ):
+ session = _make_real_session()
+
+ document_id = "doc-orphan-union-1"
+ collection_id = "col-1"
+
+ document = Document(
+ id=document_id,
+ source_type_id="source-type-upload",
+ document_hash=f"hash-{uuid.uuid4().hex}",
+ file_size=100,
+ file_type="pdf",
+ storage_mode="database",
+ file_path=None,
+ original_url=None,
+ )
+ collection = Collection(id=collection_id, name="Collection One")
+ doc_collection = DocumentCollection(
+ document_id=document_id, collection_id=collection_id
+ )
+ session.add_all([document, collection, doc_collection])
+ session.commit()
+
+ # Stray chunk rows in THREE other collections that have NO
+ # DocumentCollection join row -- i.e. already-stranded chunks that
+ # the union must still sweep even though the document is only
+ # formally linked to collection_id ("col-1").
+ session.add(_make_real_chunk(document_id, "collection_col-2"))
+ session.add(_make_real_chunk(document_id, "collection_col-3"))
+ session.add(_make_real_chunk(document_id, "collection_col-4"))
+ session.commit()
+
+ service = DocumentDeletionService(username="testuser")
+
+ def _get_session(*_a, **_k):
+ return _shared_session_cm(session)
+
+ with (
+ patch(f"{MODULE_PATH}.get_user_db_session", _get_session),
+ patch.object(service, "_purge_document_rag") as mock_purge,
+ ):
+ result = service.remove_from_collection(document_id, collection_id)
+
+ assert result["unlinked"] is True
+ assert result["document_deleted"] is True
+
+ mock_purge.assert_called_once()
+ call_args = mock_purge.call_args
+ assert call_args.args[0] == document_id
+ assert set(call_args.args[1]) == {"col-1", "col-2", "col-3", "col-4"}
+ assert call_args.kwargs["full_delete"] is True
+
+
+class TestPurgeDocumentRagBackstop:
+ """Tests for DocumentDeletionService._purge_document_rag executed against
+ a REAL (in-memory sqlite) session -- every other reference to this method
+ in the suite mocks it away via patch.object, so these are the first to
+ actually run its body: the per-collection try/except loop and the
+ guaranteed backstop chunk-row sweep.
+ """
+
+ def test_purge_document_rag_backstop_removes_chunks_even_when_every_collection_purge_raises(
+ self,
+ ):
+ session = _make_real_session()
+ document_id = "doc-backstop-1"
+ session.add(_make_real_chunk(document_id, "collection_col-1"))
+ session.add(_make_real_chunk(document_id, "collection_col-2"))
+ session.commit()
+
+ service = DocumentDeletionService(username="testuser")
+
+ def _get_session(*_a, **_k):
+ return _shared_session_cm(session)
+
+ with (
+ patch(f"{MODULE_PATH}.get_user_db_session", _get_session),
+ patch(
+ RAG_SERVICE_FACTORY_PATH,
+ side_effect=Exception("db password unavailable"),
+ ) as mock_get_rag_service,
+ patch.object(
+ session, "commit", wraps=session.commit
+ ) as mock_commit,
+ ):
+ service._purge_document_rag(
+ document_id, ["col-1", "col-2"], full_delete=True
+ )
+
+ # The per-collection loop kept going across BOTH collections even
+ # though every call raised -- the try/except swallows and continues.
+ assert mock_get_rag_service.call_count == 2
+
+ # The guaranteed backstop still swept every residual chunk row for
+ # the document, across every collection, and committed it.
+ remaining = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, source_type="document")
+ .all()
+ )
+ assert remaining == []
+ mock_commit.assert_called_once()
+
+
+class TestPurgeDocumentRagPartialUnlink:
+ """Tests for the full_delete=False vs full_delete=True backstop-sweep
+ scopes: a partial unlink sweeps only the listed collection's chunk rows,
+ a full delete sweeps every collection's chunk rows for the document.
+ """
+
+ def _seed_two_collections(self, session, document_id):
+ session.add(_make_real_chunk(document_id, "collection_col-A"))
+ session.add(_make_real_chunk(document_id, "collection_col-B"))
+ session.commit()
+
+ def test_purge_document_rag_partial_unlink_leaves_other_collections_chunks_intact(
+ self,
+ ):
+ session = _make_real_session()
+ document_id = "doc-partial-1"
+ self._seed_two_collections(session, document_id)
+
+ service = DocumentDeletionService(username="testuser")
+
+ def _get_session(*_a, **_k):
+ return _shared_session_cm(session)
+
+ with (
+ patch(f"{MODULE_PATH}.get_user_db_session", _get_session),
+ patch(
+ RAG_SERVICE_FACTORY_PATH,
+ side_effect=Exception("no rag service"),
+ ),
+ ):
+ service._purge_document_rag(
+ document_id, ["col-A"], full_delete=False
+ )
+
+ remaining = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, source_type="document")
+ .all()
+ )
+ remaining_collections = {row.collection_name for row in remaining}
+ assert remaining_collections == {"collection_col-B"}
+
+ def test_purge_document_rag_full_delete_sweeps_every_collection(self):
+ session = _make_real_session()
+ document_id = "doc-partial-2"
+ self._seed_two_collections(session, document_id)
+
+ service = DocumentDeletionService(username="testuser")
+
+ def _get_session(*_a, **_k):
+ return _shared_session_cm(session)
+
+ with (
+ patch(f"{MODULE_PATH}.get_user_db_session", _get_session),
+ patch(
+ RAG_SERVICE_FACTORY_PATH,
+ side_effect=Exception("no rag service"),
+ ),
+ ):
+ service._purge_document_rag(
+ document_id, ["col-A"], full_delete=True
+ )
+
+ remaining = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, source_type="document")
+ .all()
+ )
+ assert remaining == []
diff --git a/tests/research_library/deletion/utils/test_cascade_helper_coverage.py b/tests/research_library/deletion/utils/test_cascade_helper_coverage.py
index 5b5d5e5d32..459f24d567 100644
--- a/tests/research_library/deletion/utils/test_cascade_helper_coverage.py
+++ b/tests/research_library/deletion/utils/test_cascade_helper_coverage.py
@@ -11,12 +11,11 @@ test_cascade_helper_edge_cases.py:
- delete_rag_indices_for_collection: no FAISS files deleted (index_path missing)
- update_download_tracker: no tracker row found → returns False
- update_download_tracker: exception in get_url_hash → returns False
-- remove_from_faiss_index: faiss_index missing → returns False
- delete_document_completely: logs debug when deleted > 0
"""
from pathlib import Path
-from unittest.mock import MagicMock, Mock, patch
+from unittest.mock import MagicMock, patch
MODULE = "local_deep_research.research_library.deletion.utils.cascade_helper"
@@ -169,42 +168,3 @@ class TestUpdateDownloadTrackerNoTracker:
)
assert result is False
-
-
-# ---------------------------------------------------------------------------
-# remove_from_faiss_index – no faiss_index attribute
-# ---------------------------------------------------------------------------
-
-
-class TestRemoveFromFaissIndexNoop:
- def test_rag_service_without_faiss_index_returns_false(self):
- mock_rag = MagicMock(spec=[]) # spec=[] means no attributes
-
- mock_cm = MagicMock()
- mock_cm.__enter__ = Mock(return_value=mock_rag)
- mock_cm.__exit__ = Mock(return_value=False)
-
- with patch(
- "local_deep_research.research_library.services.library_rag_service.LibraryRAGService",
- return_value=mock_cm,
- ):
- result = CascadeHelper.remove_from_faiss_index(
- username="alice",
- collection_name="collection_abc",
- chunk_ids=["c1", "c2"],
- )
-
- assert result is False
-
- def test_exception_during_rag_service_init_returns_false(self):
- with patch(
- "local_deep_research.research_library.services.library_rag_service.LibraryRAGService",
- side_effect=Exception("rag init failed"),
- ):
- result = CascadeHelper.remove_from_faiss_index(
- username="bob",
- collection_name="collection_xyz",
- chunk_ids=["c1"],
- )
-
- assert result is False
diff --git a/tests/research_library/deletion/utils/test_cascade_helper_sweep.py b/tests/research_library/deletion/utils/test_cascade_helper_sweep.py
new file mode 100644
index 0000000000..9bdef14fc8
--- /dev/null
+++ b/tests/research_library/deletion/utils/test_cascade_helper_sweep.py
@@ -0,0 +1,266 @@
+"""Tests for the stray-file SWEEP in CascadeHelper.delete_faiss_index_files.
+
+The existing test_cascade_helper_edge_cases.py only covers the primary
+.faiss/.pkl pair on None/empty input. This file covers the sweep logic added
+alongside the RAG vector-store refactor:
+
+ (a) the migration sidecar (<name>.idmap.json) is removed
+ (b) quarantine files (<name>.faiss.corrupt-<ns>, <name>.pkl.corrupt-<ns>) are
+ ALWAYS removed regardless of age -- a leftover .pkl.corrupt-* is
+ quarantined PLAINTEXT, so leaving it behind is a data leak
+ (c) crash-orphaned .tmp files are age-gated: a FRESH .tmp (a live writer's
+ not-yet-renamed persist() temp) survives, while a STALE .tmp (older than
+ _STALE_TMP_AGE_SECONDS) is swept
+ (d) delete_rag_indices_for_collection's unlink_files=False contract: index
+ paths are returned but files are NOT unlinked (deferred-unlink, so a
+ later rollback can't leave the collection pointing at a missing index)
+"""
+
+import os
+import time
+from unittest.mock import MagicMock
+
+from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+ _STALE_TMP_AGE_SECONDS,
+)
+
+
+def _age_file(path, seconds_old):
+ """Set a file's mtime/atime to `seconds_old` seconds in the past."""
+ now = time.time()
+ target = now - seconds_old
+ os.utime(path, (target, target))
+
+
+class TestIdmapSidecarSweep:
+ """(a) <name>.idmap.json sidecar is removed."""
+
+ def test_idmap_sidecar_removed(self, tmp_path):
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ idmap = base.with_suffix(".idmap.json")
+ idmap.write_text("{}")
+
+ result = CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert result is True
+ assert not idmap.exists()
+
+ def test_idmap_sidecar_removed_when_faiss_missing(self, tmp_path):
+ """The sidecar can outlive its .faiss during the cutover window."""
+ base = tmp_path / "index"
+ idmap = base.with_suffix(".idmap.json")
+ idmap.write_text("{}")
+
+ result = CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert result is True
+ assert not idmap.exists()
+
+
+class TestQuarantineSweepAlwaysRemoved:
+ """(b) .corrupt-<ns> quarantine files are removed regardless of age."""
+
+ def test_faiss_corrupt_quarantine_removed_even_if_fresh(self, tmp_path):
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ quarantined = tmp_path / "index.faiss.corrupt-abc123"
+ quarantined.write_text("corrupted binary blob")
+ # Fresh mtime -- age must NOT matter for quarantine files.
+ _age_file(quarantined, 0)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert not quarantined.exists()
+
+ def test_pkl_corrupt_quarantine_removed_even_if_fresh(self, tmp_path):
+ """A .pkl.corrupt-* is quarantined PLAINTEXT -- must always be swept."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ quarantined = tmp_path / "index.pkl.corrupt-def456"
+ quarantined.write_text("plaintext chunk text leaked here")
+ _age_file(quarantined, 0)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert not quarantined.exists()
+
+ def test_pkl_corrupt_quarantine_removed_even_if_old(self, tmp_path):
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ quarantined = tmp_path / "index.pkl.corrupt-old789"
+ quarantined.write_text("plaintext chunk text leaked here")
+ _age_file(quarantined, _STALE_TMP_AGE_SECONDS * 10)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert not quarantined.exists()
+
+ def test_idmap_corrupt_quarantine_removed(self, tmp_path):
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ quarantined = tmp_path / "index.idmap.json.corrupt-ghi789"
+ quarantined.write_text("{}")
+ _age_file(quarantined, 0)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert not quarantined.exists()
+
+ def test_multiple_quarantine_generations_all_removed(self, tmp_path):
+ """Repeated corruption events can leave several quarantine files;
+ all of them must be swept, not just the newest/oldest."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ q1 = tmp_path / "index.pkl.corrupt-gen1"
+ q2 = tmp_path / "index.pkl.corrupt-gen2"
+ q1.write_text("plaintext leak 1")
+ q2.write_text("plaintext leak 2")
+ _age_file(q1, _STALE_TMP_AGE_SECONDS * 10)
+ _age_file(q2, 0)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert not q1.exists()
+ assert not q2.exists()
+
+
+class TestTmpSweepAgeGate:
+ """(c) fresh .tmp survives (live writer), stale .tmp is swept."""
+
+ def test_fresh_tmp_survives(self, tmp_path):
+ """A .tmp younger than _STALE_TMP_AGE_SECONDS may be a concurrent
+ writer's not-yet-renamed persist() temp; deleting it would crash
+ that write, so it must be left alone."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ fresh_tmp = tmp_path / "index.faiss.abc123.tmp"
+ fresh_tmp.write_text("in-progress write")
+ _age_file(fresh_tmp, 0)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert fresh_tmp.exists()
+
+ def test_stale_tmp_is_swept(self, tmp_path):
+ """A .tmp older than _STALE_TMP_AGE_SECONDS is certainly
+ crash-orphaned and must be removed."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ stale_tmp = tmp_path / "index.faiss.abc123.tmp"
+ stale_tmp.write_text("orphaned write")
+ _age_file(stale_tmp, _STALE_TMP_AGE_SECONDS + 60)
+
+ result = CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert result is True
+ assert not stale_tmp.exists()
+
+ def test_boundary_just_under_threshold_survives(self, tmp_path):
+ """One second younger than the threshold must still be treated as
+ 'fresh' -- confirms the age gate uses '<', not '<='."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ boundary_tmp = tmp_path / "index.faiss.boundary.tmp"
+ boundary_tmp.write_text("borderline write")
+ _age_file(boundary_tmp, _STALE_TMP_AGE_SECONDS - 5)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert boundary_tmp.exists()
+
+ def test_fresh_and_stale_tmp_coexist_only_stale_removed(self, tmp_path):
+ """Sanity-check the assertion actually discriminates on age: with
+ one fresh and one stale .tmp present, only the stale one is gone
+ and the fresh one remains -- this would fail if the sweep either
+ removed everything or removed nothing."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ fresh_tmp = tmp_path / "index.faiss.fresh.tmp"
+ stale_tmp = tmp_path / "index.faiss.stale.tmp"
+ fresh_tmp.write_text("live writer")
+ stale_tmp.write_text("crash orphan")
+ _age_file(fresh_tmp, 0)
+ _age_file(stale_tmp, _STALE_TMP_AGE_SECONDS * 2)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert fresh_tmp.exists()
+ assert not stale_tmp.exists()
+
+ def test_pkl_tmp_family_also_age_gated(self, tmp_path):
+ """The sweep runs per-base (.faiss, .pkl, .idmap.json) -- confirm the
+ .pkl family's tmp siblings are age-gated the same way."""
+ base = tmp_path / "index"
+ base.with_suffix(".faiss").write_text("faiss-data")
+ base.with_suffix(".pkl").write_text("pkl-data")
+ fresh_tmp = tmp_path / "index.pkl.fresh.tmp"
+ stale_tmp = tmp_path / "index.pkl.stale.tmp"
+ fresh_tmp.write_text("live writer")
+ stale_tmp.write_text("crash orphan")
+ _age_file(fresh_tmp, 0)
+ _age_file(stale_tmp, _STALE_TMP_AGE_SECONDS * 2)
+
+ CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert fresh_tmp.exists()
+ assert not stale_tmp.exists()
+
+
+class TestDeleteRagIndicesForCollectionUnlinkContract:
+ """(d) unlink_files=False defers unlinking; unlink_files=True (default)
+ unlinks immediately."""
+
+ def _make_session_with_index(self, tmp_path, base_name="index"):
+ base = tmp_path / base_name
+ faiss_file = base.with_suffix(".faiss")
+ faiss_file.write_text("faiss-data")
+
+ rag_index = MagicMock()
+ rag_index.index_path = str(base)
+
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.all.return_value = [
+ rag_index
+ ]
+ return session, rag_index, faiss_file
+
+ def test_unlink_files_false_returns_paths_and_leaves_files(self, tmp_path):
+ session, rag_index, faiss_file = self._make_session_with_index(tmp_path)
+
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc", unlink_files=False
+ )
+
+ assert result["index_paths"] == [str(faiss_file.with_suffix(""))]
+ assert result["deleted_files"] == 0
+ assert result["deleted_indices"] == 1
+ # Deferred-unlink contract: the file must still be on disk.
+ assert faiss_file.exists()
+ # DB row is still staged for deletion.
+ session.delete.assert_called_once_with(rag_index)
+
+ def test_unlink_files_true_unlinks_and_omits_paths(self, tmp_path):
+ session, rag_index, faiss_file = self._make_session_with_index(tmp_path)
+
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc", unlink_files=True
+ )
+
+ assert result["index_paths"] == []
+ assert result["deleted_files"] == 1
+ assert result["deleted_indices"] == 1
+ assert not faiss_file.exists()
+
+ def test_default_unlink_files_is_true(self, tmp_path):
+ """Confirms the default parameter value matches the True behavior
+ (the safe/backwards-compatible default), not the deferred one."""
+ session, rag_index, faiss_file = self._make_session_with_index(tmp_path)
+
+ result = CascadeHelper.delete_rag_indices_for_collection(
+ session, "collection_abc"
+ )
+
+ assert result["index_paths"] == []
+ assert not faiss_file.exists()
diff --git a/tests/research_library/routes/test_rag_indexing_helpers.py b/tests/research_library/routes/test_rag_indexing_helpers.py
index dd8f2981ff..161bc7d210 100644
--- a/tests/research_library/routes/test_rag_indexing_helpers.py
+++ b/tests/research_library/routes/test_rag_indexing_helpers.py
@@ -170,17 +170,25 @@ class TestResetCollectionForReindex:
) as cascade:
cascade.delete_collection_chunks.return_value = 12
cascade.delete_rag_indices_for_collection.return_value = {
- "deleted": 1
+ "deleted_indices": 1,
+ "deleted_files": 0,
+ "index_paths": ["/idx/a", "/idx/b"],
}
- _reset_collection_for_reindex(db, "cid")
+ paths = _reset_collection_for_reindex(db, "cid")
cascade.delete_collection_chunks.assert_called_once_with(
db, "collection_cid"
)
+ # RAGIndex ROWS are deleted in this transaction, but the on-disk
+ # files are unlinked by the caller AFTER the commit — so a rollback
+ # can't orphan already-deleted files. delete_rag_indices_for_collection
+ # is therefore called with unlink_files=False and its index_paths
+ # are returned for the post-commit unlink.
cascade.delete_rag_indices_for_collection.assert_called_once_with(
- db, "collection_cid"
+ db, "collection_cid", unlink_files=False
)
+ assert paths == ["/idx/a", "/idx/b"]
# Marks documents unindexed
db.query.return_value.filter_by.return_value.update.assert_called_once()
diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
index 830f90d4b2..14ee1e5949 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
@@ -8,6 +8,8 @@ Covers:
"""
import json
+import re
+from contextlib import contextmanager
from unittest.mock import MagicMock, Mock, patch
import pytest
@@ -15,6 +17,7 @@ import pytest
from local_deep_research.constants import DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS
from ._route_helpers_rag import (
+ _DB_CTX,
_ROUTES,
_auth_client,
_build_mock_query,
@@ -695,6 +698,411 @@ class TestIndexAll:
mock_reset.assert_not_called()
+ def _collect_sse_events(self, response):
+ """Parse SSE events from streaming response."""
+ events = []
+ for line in response.data.decode().split("\n"):
+ if line.startswith("data: "):
+ events.append(json.loads(line[6:]))
+ return events
+
+ def test_index_all_collection_not_found_yields_error_and_short_circuits(
+ self, app
+ ):
+ """A non-existent collection_id must short-circuit before any
+ document query or batch indexing runs, yielding a single error
+ event and no 'complete' event. Without the guard, a bad id would
+ fall through to '_query_documents_to_index' returning [] and
+ silently report a successful 'No documents to index' completion.
+ """
+ db_session = _make_db_session()
+ db_session.query = Mock(
+ return_value=_build_mock_query(first_result=None)
+ )
+ mock_rag = Mock()
+
+ with (
+ patch(f"{_ROUTES}._query_documents_to_index") as mock_query_docs,
+ patch(
+ f"{_ROUTES}._store_collection_embedding_metadata"
+ ) as mock_store,
+ patch(f"{_ROUTES}._reset_collection_for_reindex") as mock_reset,
+ ):
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ ],
+ ) as (client, ctx):
+ resp = client.get(
+ "/library/api/rag/index-all?collection_id=nonexistent"
+ )
+ events = self._collect_sse_events(resp)
+
+ error_events = [e for e in events if e.get("type") == "error"]
+ assert len(error_events) == 1
+ assert "not found" in error_events[0]["error"].lower()
+ assert not any(e.get("type") == "complete" for e in events)
+ mock_query_docs.assert_not_called()
+ mock_store.assert_not_called()
+ mock_reset.assert_not_called()
+
+
+class TestCommitOnceThenUnlinkAfterCommit:
+ """Regression guard for the crash-window fix at all three hand-copied
+ call sites that persist embedding metadata + a force-reindex reset in
+ ONE commit, then unlink the returned FAISS files only AFTER that commit
+ lands: index_all, index_collection, and the background worker.
+
+ Unlinking before the commit would orphan the FAISS files (referenced by
+ a RAGIndex row the reset already deleted) if the transaction then rolled
+ back. Parametrized per-site — bundling the 3 sites into one test body
+ would let a first failed assert mask failures at the other two sites.
+ """
+
+ def _run_index_all(self, app):
+ mock_coll = Mock()
+ mock_coll.id = "coll-1"
+ mock_coll.embedding_model = "already-set"
+ db_session = _make_db_session()
+ db_session.query = Mock(
+ return_value=_build_mock_query(first_result=mock_coll)
+ )
+ mock_rag = Mock()
+
+ call_order = []
+ faiss_paths = ["/tmp/coll-1.faiss", "/tmp/coll-1.faiss.ids"]
+ db_session.commit.side_effect = lambda: call_order.append("commit")
+
+ def record_unlink(paths):
+ call_order.append("unlink")
+
+ with (
+ patch(f"{_ROUTES}._store_collection_embedding_metadata"),
+ patch(
+ f"{_ROUTES}._reset_collection_for_reindex",
+ return_value=faiss_paths,
+ ) as mock_reset,
+ patch(
+ f"{_ROUTES}._unlink_reindex_faiss_files",
+ side_effect=record_unlink,
+ ) as mock_unlink,
+ patch(f"{_ROUTES}._query_documents_to_index", return_value=[]),
+ ):
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ ],
+ ) as (client, ctx):
+ resp = client.get(
+ "/library/api/rag/index-all"
+ "?collection_id=coll-1&force_reindex=true"
+ )
+ resp.get_data() # drain the SSE generator to completion
+
+ mock_reset.assert_called_once_with(db_session, "coll-1")
+ mock_unlink.assert_called_once_with(faiss_paths)
+
+ return call_order, db_session.commit.call_count
+
+ def _run_index_collection(self, app):
+ mock_coll = Mock()
+ mock_coll.id = "coll-1"
+ mock_coll.name = "Test"
+ mock_coll.embedding_model = "already-set"
+ db_session = _make_db_session()
+ db_session.query = Mock(
+ return_value=_build_mock_query(first_result=mock_coll)
+ )
+ mock_rag = Mock()
+
+ call_order = []
+ faiss_paths = ["/tmp/coll-1.faiss", "/tmp/coll-1.faiss.ids"]
+ db_session.commit.side_effect = lambda: call_order.append("commit")
+
+ def record_unlink(paths):
+ call_order.append("unlink")
+
+ with (
+ patch(f"{_ROUTES}._store_collection_embedding_metadata"),
+ patch(
+ f"{_ROUTES}._reset_collection_for_reindex",
+ return_value=faiss_paths,
+ ) as mock_reset,
+ patch(
+ f"{_ROUTES}._unlink_reindex_faiss_files",
+ side_effect=record_unlink,
+ ) as mock_unlink,
+ patch(f"{_ROUTES}._query_documents_to_index", return_value=[]),
+ ):
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ Mock(get_session_password=Mock(return_value=None)),
+ ),
+ ],
+ ) as (client, ctx):
+ resp = client.get(
+ "/library/api/collections/coll-1/index?force_reindex=true"
+ )
+ resp.get_data() # drain the SSE generator to completion
+
+ mock_reset.assert_called_once_with(db_session, "coll-1")
+ mock_unlink.assert_called_once_with(faiss_paths)
+
+ return call_order, db_session.commit.call_count
+
+ def _run_background_worker(self, app):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = Mock()
+ mock_svc.__enter__ = Mock(return_value=mock_svc)
+ mock_svc.__exit__ = Mock(return_value=False)
+
+ mock_coll = Mock()
+ mock_coll.id = "coll-1"
+ mock_coll.embedding_model = "already-set"
+
+ db_session = _make_db_session()
+ db_session.query = Mock(
+ return_value=_build_mock_query(first_result=mock_coll)
+ )
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ call_order = []
+ faiss_paths = ["/tmp/coll-1.faiss", "/tmp/coll-1.faiss.ids"]
+ db_session.commit.side_effect = lambda: call_order.append("commit")
+
+ def record_unlink(paths):
+ call_order.append("unlink")
+
+ with (
+ patch(
+ f"{_ROUTES}._get_rag_service_for_thread",
+ return_value=mock_svc,
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{_ROUTES}._update_task_status"),
+ patch(f"{_ROUTES}._store_collection_embedding_metadata"),
+ patch(
+ f"{_ROUTES}._reset_collection_for_reindex",
+ return_value=faiss_paths,
+ ) as mock_reset,
+ patch(
+ f"{_ROUTES}._unlink_reindex_faiss_files",
+ side_effect=record_unlink,
+ ) as mock_unlink,
+ patch(f"{_ROUTES}._query_documents_to_index", return_value=[]),
+ ):
+ _background_index_worker(
+ "task-1", "coll-1", "user", "pass", force_reindex=True
+ )
+
+ mock_reset.assert_called_once_with(db_session, "coll-1")
+ mock_unlink.assert_called_once_with(faiss_paths)
+
+ return call_order, db_session.commit.call_count
+
+ @pytest.mark.parametrize(
+ "runner_name",
+ ["_run_index_all", "_run_index_collection", "_run_background_worker"],
+ ids=["index_all", "index_collection", "background_worker"],
+ )
+ def test_commit_once_then_unlink_after_commit(self, app, runner_name):
+ call_order, commit_call_count = getattr(self, runner_name)(app)
+ # The commit must precede the unlink — never the reverse — and must
+ # happen exactly once (not once per helper call).
+ assert call_order == ["commit", "unlink"]
+ assert commit_call_count == 1
+
+
+class TestClearedStatusIsSkippedNotFailed:
+ """A 'cleared' index result (the empty-text purge) must bucket into
+ 'skipped', not 'errors'/'failed', at all three call sites that share
+ this classification: index_all, index_collection, and the background
+ worker. Parametrized so a typo in any one of the three duplicated
+ ``in ("skipped", "cleared")`` checks is caught individually rather than
+ masked by the other two passing.
+ """
+
+ def _collect_sse_events(self, response):
+ events = []
+ for line in response.data.decode().split("\n"):
+ if line.startswith("data: "):
+ events.append(json.loads(line[6:]))
+ return events
+
+ def _run_index_all(self, app):
+ mock_coll = Mock()
+ mock_coll.id = "coll-1"
+ mock_coll.embedding_model = "already-set"
+ db_session = _make_db_session()
+ db_session.query = Mock(
+ return_value=_build_mock_query(first_result=mock_coll)
+ )
+
+ mock_rag = Mock()
+ mock_rag.index_documents_batch.return_value = {
+ "doc-1": {"status": "cleared"}
+ }
+
+ with (
+ patch(f"{_ROUTES}._store_collection_embedding_metadata"),
+ patch(f"{_ROUTES}._reset_collection_for_reindex"),
+ patch(
+ f"{_ROUTES}._query_documents_to_index",
+ return_value=[(Mock(), Mock(id="doc-1", title="t"))],
+ ),
+ ):
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ ],
+ ) as (client, ctx):
+ resp = client.get(
+ "/library/api/rag/index-all?collection_id=coll-1"
+ )
+ events = self._collect_sse_events(resp)
+
+ complete = [e for e in events if e["type"] == "complete"][0]
+ return complete["results"]["skipped"], complete["results"]["failed"]
+
+ def _run_index_collection(self, app):
+ mock_coll = Mock()
+ mock_coll.id = "coll-1"
+ mock_coll.name = "Test"
+ mock_coll.embedding_model = "model"
+
+ mock_link = Mock()
+ mock_doc = Mock()
+ mock_doc.id = "doc-1"
+ mock_doc.filename = "cleared.pdf"
+ mock_doc.title = None
+
+ db_session = _make_db_session()
+ call_count = [0]
+
+ def query_side_effect(*args):
+ call_count[0] += 1
+ q = _build_mock_query()
+ if call_count[0] == 1:
+ q.first.return_value = mock_coll
+ elif call_count[0] == 2:
+ q.join.return_value = q
+ q.filter.return_value = q
+ q.all.return_value = [(mock_link, mock_doc)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ mock_rag = Mock()
+ mock_rag.index_document.return_value = {"status": "cleared"}
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ Mock(get_session_password=Mock(return_value=None)),
+ ),
+ ],
+ ) as (client, ctx):
+ resp = client.get("/library/api/collections/coll-1/index")
+ events = self._collect_sse_events(resp)
+
+ complete = [e for e in events if e["type"] == "complete"][0]
+ return complete["results"]["skipped"], complete["results"]["failed"]
+
+ def _run_background_worker(self, app):
+ from local_deep_research.research_library.routes.rag_routes import (
+ _background_index_worker,
+ )
+
+ mock_svc = Mock()
+ mock_svc.__enter__ = Mock(return_value=mock_svc)
+ mock_svc.__exit__ = Mock(return_value=False)
+ mock_svc.index_document.return_value = {"status": "cleared"}
+
+ mock_coll = Mock()
+ mock_coll.embedding_model = "model"
+
+ doc = Mock()
+ doc.id = "doc-1"
+ doc.filename = "cleared.pdf"
+ doc.title = None
+ link = Mock()
+
+ db_session = _make_db_session()
+ query_counter = {"n": 0}
+
+ def query_side_effect(*models):
+ query_counter["n"] += 1
+ q = _build_mock_query()
+ if query_counter["n"] == 1:
+ q.first.return_value = mock_coll
+ else:
+ q.all.return_value = [(link, doc)]
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+
+ @contextmanager
+ def fake_session(*a, **kw):
+ yield db_session
+
+ statuses = []
+
+ def track_status(username, db_password, task_id, **kwargs):
+ statuses.append(kwargs)
+
+ with (
+ patch(
+ f"{_ROUTES}._get_rag_service_for_thread",
+ return_value=mock_svc,
+ ),
+ patch(f"{_DB_CTX}.get_user_db_session", side_effect=fake_session),
+ patch(f"{_ROUTES}._update_task_status", side_effect=track_status),
+ ):
+ _background_index_worker(
+ "task-1", "coll-1", "user", "pass", force_reindex=False
+ )
+
+ completed = [s for s in statuses if s.get("status") == "completed"]
+ assert len(completed) == 1
+ match = re.search(
+ r"(\d+) indexed, (\d+) failed, (\d+) skipped",
+ completed[0]["progress_message"],
+ )
+ assert match is not None
+ _successful, failed, skipped = (int(g) for g in match.groups())
+ return skipped, failed
+
+ @pytest.mark.parametrize(
+ "runner_name",
+ ["_run_index_all", "_run_index_collection", "_run_background_worker"],
+ ids=["index_all", "index_collection", "background_worker"],
+ )
+ def test_cleared_counts_as_skipped_not_failed(self, app, runner_name):
+ skipped, failed = getattr(self, runner_name)(app)
+ assert skipped == 1
+ assert failed == 0
+
class TestRagServiceCloseLifecycle:
"""Regression coverage for the RAG-service close-on-exit guarantee.
diff --git a/tests/research_library/services/test_faiss_safe_load.py b/tests/research_library/services/test_faiss_safe_load.py
deleted file mode 100644
index 8b9e742e35..0000000000
--- a/tests/research_library/services/test_faiss_safe_load.py
+++ /dev/null
@@ -1,184 +0,0 @@
-"""Tests for the restricted-unpickler FAISS loader (faiss_safe_load).
-
-Covers:
-- A real ``FAISS.save_local`` index round-trips through ``safe_load_faiss``
- (proves the restricted unpickler accepts legitimate docstore payloads).
-- A malicious pickle that would execute code under a plain ``pickle.load`` is
- rejected before execution (proves the RCE is actually closed, including the
- realistic ".pkl-only swap" where the .faiss is left byte-identical).
-"""
-
-import datetime
-import io
-import pickle
-from pathlib import Path
-
-import pytest
-from langchain_community.docstore.in_memory import InMemoryDocstore
-from langchain_community.vectorstores import FAISS
-from langchain_core.documents import Document
-
-from local_deep_research.research_library.services.faiss_safe_load import (
- _RestrictedFaissUnpickler,
- safe_load_faiss,
-)
-
-try: # location varies across langchain versions
- from langchain_community.embeddings import FakeEmbeddings
-except Exception: # pragma: no cover
- from langchain_core.embeddings import FakeEmbeddings
-
-
-def _build_and_save(
- dir_path: Path, index_name: str = "index"
-) -> FakeEmbeddings:
- """Create a small real FAISS index on disk and return its embeddings."""
- emb = FakeEmbeddings(size=16)
- texts = ["alpha chunk", "beta chunk", "gamma chunk"]
- # Metadata mirrors what the RAG service attaches: plain scalars + lists.
- metas = [
- {"source": "a.pdf", "page": 1, "word_count": 2, "authors": None},
- {"source": "b.pdf", "page": 2, "tags": ["x", "y"]},
- {"source": "c.pdf", "score": 0.9, "nested": {"k": 1}},
- ]
- vs = FAISS.from_texts(texts, emb, metadatas=metas)
- vs.save_local(str(dir_path), index_name=index_name)
- return emb
-
-
-class TestSafeLoadRoundTrip:
- def test_loads_real_index(self, tmp_path):
- emb = _build_and_save(tmp_path)
- vs = safe_load_faiss(
- str(tmp_path), emb, index_name="index", normalize_L2=True
- )
- contents = {d.page_content for d in vs.docstore._dict.values()}
- assert contents == {"alpha chunk", "beta chunk", "gamma chunk"}
- assert len(vs.index_to_docstore_id) == 3
- # Metadata (scalars, list, nested dict) survives the restricted load.
- metas = [d.metadata for d in vs.docstore._dict.values()]
- assert any(m.get("tags") == ["x", "y"] for m in metas)
- # normalize_L2 is threaded into the FAISS constructor by hand — guard
- # it, since a silent drop would corrupt cosine-distance search.
- assert vs._normalize_L2 is True
-
- def test_normalize_l2_defaults_false(self, tmp_path):
- emb = _build_and_save(tmp_path)
- vs = safe_load_faiss(str(tmp_path), emb, index_name="index")
- assert vs._normalize_L2 is False
-
- def test_search_works_after_safe_load(self, tmp_path):
- emb = _build_and_save(tmp_path)
- vs = safe_load_faiss(str(tmp_path), emb, index_name="index")
- results = vs.similarity_search("alpha", k=1)
- assert len(results) == 1
-
-
-# Module-level helpers so pickle can reference them by qualified name. The
-# payload writes a marker file instead of doing real harm, so the test can
-# prove (a) it WOULD run under plain pickle and (b) it does NOT under the
-# restricted unpickler.
-def _write_marker(path: str):
- Path(path).write_text("EXECUTED")
- return InMemoryDocstore({})
-
-
-class _Evil:
- def __init__(self, marker: str):
- self._marker = marker
-
- def __reduce__(self):
- return (_write_marker, (self._marker,))
-
-
-class TestSafeLoadBlocksMalicious:
- def test_restricted_unpickler_blocks_and_does_not_execute(self, tmp_path):
- marker = tmp_path / "marker.txt"
- blob = pickle.dumps((_Evil(str(marker)), {0: "id"}))
-
- # Sanity: a plain pickle.load DOES execute the payload. This
- # unsafe call is the point of the test — it demonstrates the very
- # RCE that safe_load_faiss prevents, on a benign marker payload.
- pickle.loads(blob) # noqa: S301
- assert marker.read_text() == "EXECUTED"
- marker.unlink()
-
- # The restricted unpickler refuses and never runs the payload.
- with pytest.raises(pickle.UnpicklingError):
- _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
- assert not marker.exists()
-
- def test_safe_load_faiss_rejects_pkl_only_swap(self, tmp_path):
- """The realistic attack: leave .faiss byte-identical, swap the .pkl."""
- emb = _build_and_save(tmp_path) # valid .faiss + .pkl
- marker = tmp_path / "marker.txt"
- faiss_before = (tmp_path / "index.faiss").read_bytes()
-
- (tmp_path / "index.pkl").write_bytes(
- pickle.dumps((_Evil(str(marker)), {0: "id"}))
- )
-
- with pytest.raises(pickle.UnpicklingError):
- safe_load_faiss(str(tmp_path), emb, index_name="index")
- assert not marker.exists()
- # We did not touch the .faiss (mirrors the attack precondition).
- assert (tmp_path / "index.faiss").read_bytes() == faiss_before
-
- def test_blocks_copyreg_extension_opcode_even_when_cache_warm(
- self, tmp_path
- ):
- """copyreg EXT1/EXT2/EXT4 opcodes resolve a callable via the extension
- registry. ``find_class`` alone is NOT enough: ``get_extension``
- short-circuits on the process-global ``copyreg._extension_cache`` and
- skips ``find_class`` once a code has been resolved. So this test WARMS
- the cache first (a plain ``pickle.loads`` that runs the payload), which
- is exactly the state in which a ``find_class``-only guard would be
- bypassed — then asserts the restricted unpickler still refuses (proving
- the ``get_extension`` override, not ``find_class``, does the blocking).
- """
- import copyreg
- import pickletools
-
- marker = tmp_path / "marker.txt"
- code = 0xC0DE
- copyreg.add_extension(
- _write_marker.__module__, _write_marker.__name__, code
- )
- try:
- blob = pickle.dumps((_Evil(str(marker)), {0: "id"}), protocol=2)
- # Guard: the payload must actually use an EXT opcode, else this
- # test would pass for the wrong reason.
- op_names = [op.name for op, _, _ in pickletools.genops(blob)]
- assert any(n.startswith("EXT") for n in op_names), op_names
-
- # Warm copyreg._extension_cache for this code. A find_class-only
- # restricted unpickler would now be bypassed on the EXT path.
- pickle.loads(blob) # noqa: S301
- assert marker.exists() # confirms the cache is now warm
- marker.unlink()
-
- with pytest.raises(pickle.UnpicklingError):
- _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
- assert not marker.exists()
- finally:
- copyreg.remove_extension(
- _write_marker.__module__, _write_marker.__name__, code
- )
- # Drop the warmed cache entry so it can't leak into other tests.
- copyreg._extension_cache.pop(code, None)
-
- def test_blocks_disallowed_class_buried_in_metadata(self):
- """The allow-list applies to EVERY global the pickle resolves, not
- just the top-level docstore class. A disallowed class hidden inside a
- Document's metadata (here a benign ``datetime``) must still be
- refused — otherwise an attacker could smuggle a gadget through a
- nested value while the outer objects look legitimate.
- """
- doc = Document(
- page_content="x",
- metadata={"created": datetime.datetime(2026, 1, 1)},
- )
- blob = pickle.dumps((InMemoryDocstore({"id1": doc}), {0: "id1"}))
-
- with pytest.raises(pickle.UnpicklingError, match="datetime"):
- _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
diff --git a/tests/research_library/services/test_index_finalize_self_heal.py b/tests/research_library/services/test_index_finalize_self_heal.py
new file mode 100644
index 0000000000..e83e579919
--- /dev/null
+++ b/tests/research_library/services/test_index_finalize_self_heal.py
@@ -0,0 +1,441 @@
+"""Store-durable-before-DB-commit self-heal tests for the int-id vector store.
+
+``VectorIndex.index()`` (facade.py) runs ``store.apply()`` — DURABLY persisting
+vectors to the on-disk FAISS file — *before* the DB delete/commit that removes
+the source's prior ``DocumentChunk`` rows. That ordering opens a window: if the
+DB side fails/rolls back AFTER ``apply()`` already succeeded, the store and DB
+can disagree (orphan vectors with no row, or resurrected rows with no vector).
+
+Two things are tested against REAL components (a real ``FaissVectorStore``, a
+real in-memory-SQLite-backed SQLAlchemy session, real search):
+
+ (a) ``LibraryRAGService.index_document``'s failure path: when the DB commit
+ fails in that window, ``index_document`` must catch it, roll back, and
+ run the ``#4855`` backstop (``_flag_document_for_reindex``) so the
+ document is left ``indexed=False`` (not silently indexed-but-
+ unsearchable). A plain retry (``index_document`` again, no injected
+ failure) must then self-heal: a real search returns the document's text
+ again. A CONTROL run with the backstop disabled reproduces the
+ pre-#4855 bug (``indexed`` stays True while search returns nothing) —
+ proving the backstop is what makes the difference, not an artifact of
+ the harness.
+
+ (b) The facade's ``_finalize_db`` directly: when the DB-side delete/commit
+ raises after a durable ``store.apply()``, the exception must propagate
+ and the session must be rolled back to a CONSISTENT state (no
+ half-applied DB — the prior row survives, no duplicate/partial row is
+ left), even though the on-disk store now durably disagrees with the DB
+ (an orphan vector with no matching row).
+
+Mirrors the harness pattern in ``tests/vector_stores/test_no_plaintext_production_path.py``:
+a deterministic network-free fake ``Embeddings``, an in-memory SQLite engine +
+sessionmaker over ``local_deep_research.database.models.Base``, monkeypatching
+``get_user_db_session`` (both in the facade module and the RAG service module)
+to a single shared session, and ``LDR_DATA_DIR`` pointed at ``tmp_path`` so the
+real cache/rag_indices tree is used.
+"""
+
+import hashlib
+import threading
+import uuid
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ EmbeddingProvider,
+ RagDocumentStatus,
+ SourceType,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+)
+
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+_FACADE_MOD = "local_deep_research.vector_stores.facade"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings (same recipe as the canonical
+ harness ``test_no_plaintext_production_path.py``)."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _flaky_commit(session, state):
+ """A one-shot failing ``commit`` wrapper: raises exactly once (while
+ ``state["armed"]`` is True), then delegates to the session's real commit
+ for every subsequent call — so a later backstop/reconcile commit in the
+ SAME test still durably persists."""
+ real_commit = session.commit
+
+ def _commit():
+ if state["armed"]:
+ state["armed"] = False
+ raise RuntimeError("simulated DB commit failure")
+ return real_commit()
+
+ return _commit, real_commit
+
+
+# --------------------------------------------------------------------------- #
+# (a) LibraryRAGService.index_document self-heal
+# --------------------------------------------------------------------------- #
+class TestIndexDocumentSelfHeal:
+ @pytest.fixture
+ def rag_env(self, tmp_path, monkeypatch):
+ """Real in-memory DB + real on-disk cache tree, shared across every
+ ``get_user_db_session`` call site the indexing path touches."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ monkeypatch.setattr(f"{_RAG_MOD}.get_user_db_session", _shared_session)
+ monkeypatch.setattr(
+ f"{_FACADE_MOD}.get_user_db_session", _shared_session
+ )
+
+ # Integrity checks live in the encrypted DB via a real manager that
+ # needs real key material; stub it (as the canonical harness does) so
+ # this test stays focused on the store/DB durability-window invariant.
+ fim = MagicMock()
+ fim.verify_file.return_value = (True, None)
+ fim.record_file.return_value = None
+ monkeypatch.setattr(
+ f"{_RAG_MOD}.FileIntegrityManager", lambda *a, **k: fim
+ )
+
+ yield session
+ session.close()
+ engine.dispose()
+
+ @staticmethod
+ def _seed_document(
+ session, source_type_id, *, doc_id, coll_id, text, title
+ ):
+ session.add(Collection(id=coll_id, name=f"Collection {coll_id[:8]}"))
+ session.add(
+ Document(
+ id=doc_id,
+ source_type_id=source_type_id,
+ document_hash=hashlib.sha256(text.encode()).hexdigest(),
+ title=title,
+ text_content=text,
+ original_url="http://example.com/doc",
+ file_size=len(text),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.commit()
+
+ @staticmethod
+ def _make_service(username):
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = _FakeEmbeddings(dim=8)
+ return LibraryRAGService(
+ username=username,
+ db_password="pw", # gitleaks:allow
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ )
+
+ @staticmethod
+ def _source_type(session):
+ st = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(st)
+ session.commit()
+ return st
+
+ def test_self_heals_after_commit_failure(self, rag_env, monkeypatch):
+ session = rag_env
+ source_type = self._source_type(session)
+
+ doc_id = uuid.uuid4().hex
+ coll_id = uuid.uuid4().hex
+ text = "The mitochondria is the powerhouse of the cell. " * 20
+ self._seed_document(
+ session,
+ source_type.id,
+ doc_id=doc_id,
+ coll_id=coll_id,
+ text=text,
+ title="Bio Notes",
+ )
+
+ svc = self._make_service("user-self-heal")
+
+ # 1) First index: real success, real search, real DB rows.
+ result1 = svc.index_document(doc_id, coll_id)
+ assert result1["status"] == "success", result1
+ dc = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .first()
+ )
+ assert dc.indexed is True
+ assert (
+ session.query(RagDocumentStatus)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .first()
+ is not None
+ )
+ hits0 = svc.search("mitochondria powerhouse", coll_id, top_k=3)
+ assert any("mitochondria" in h.text.lower() for h in hits0)
+
+ # 2) Force-reindex with a ONE-SHOT commit failure injected AFTER
+ # store.apply() has already durably replaced the vectors (real apply()
+ # runs for real; only the top-level DB commit inside index_document
+ # is made to fail, exactly the window _flag_document_for_reindex's
+ # docstring describes).
+ state = {"armed": True}
+ flaky, real_commit = _flaky_commit(session, state)
+ monkeypatch.setattr(session, "commit", flaky)
+
+ result2 = svc.index_document(doc_id, coll_id, force_reindex=True)
+ assert result2["status"] == "error", result2
+
+ monkeypatch.setattr(session, "commit", real_commit)
+
+ # Backstop ran: NOT left indexed-but-unsearchable.
+ session.expire_all()
+ dc2 = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .first()
+ )
+ assert dc2.indexed is False, (
+ "backstop did not flag the document NOT indexed after the "
+ "post-apply() commit failure"
+ )
+ assert (
+ session.query(RagDocumentStatus)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .first()
+ is None
+ ), "backstop did not delete the stale RagDocumentStatus row"
+
+ # 3) Reconcile: a normal retry, no injected failure -> real self-heal.
+ result3 = svc.index_document(doc_id, coll_id)
+ assert result3["status"] == "success", result3
+ assert result3.get("chunk_count", 0) > 0
+
+ hits1 = svc.search("mitochondria powerhouse", coll_id, top_k=3)
+ assert any("mitochondria" in h.text.lower() for h in hits1), (
+ "system did not self-heal: search is still empty after the "
+ "reconcile pass"
+ )
+ svc.close()
+
+ def test_control_without_backstop_stays_indexed_and_unsearchable(
+ self, rag_env, monkeypatch
+ ):
+ """Same failure injected, but with the #4855 backstop disabled on this
+ service instance — reproduces the pre-fix bug: ``indexed`` stays True
+ while a real search returns nothing. Proves the assertions in the main
+ test actually bite (they'd fail here) and that the backstop, not some
+ artifact of the harness, is what makes the real test pass.
+ """
+ session = rag_env
+ source_type = self._source_type(session)
+
+ doc_id = uuid.uuid4().hex
+ coll_id = uuid.uuid4().hex
+ text = "Photosynthesis converts sunlight into chemical energy. " * 20
+ self._seed_document(
+ session,
+ source_type.id,
+ doc_id=doc_id,
+ coll_id=coll_id,
+ text=text,
+ title="Bio Notes 2",
+ )
+
+ svc = self._make_service("user-control")
+ # Disable ONLY the backstop for this instance.
+ monkeypatch.setattr(
+ svc, "_flag_document_for_reindex", lambda *a, **k: None
+ )
+
+ result1 = svc.index_document(doc_id, coll_id)
+ assert result1["status"] == "success", result1
+
+ state = {"armed": True}
+ flaky, real_commit = _flaky_commit(session, state)
+ monkeypatch.setattr(session, "commit", flaky)
+
+ result2 = svc.index_document(doc_id, coll_id, force_reindex=True)
+ assert result2["status"] == "error", result2
+
+ monkeypatch.setattr(session, "commit", real_commit)
+
+ session.expire_all()
+ dc = (
+ session.query(DocumentCollection)
+ .filter_by(document_id=doc_id, collection_id=coll_id)
+ .first()
+ )
+ # CONTROL BUG: without the backstop, the doc still claims indexed=True.
+ assert dc.indexed is True, (
+ "control did not reproduce the pre-#4855 staleness (indexed "
+ "should still read True with the backstop disabled)"
+ )
+
+ # ...yet it is NOT actually searchable: apply() already durably
+ # removed the prior vectors before the commit failed, so the
+ # resurrected DB row(s) have no matching vector any more.
+ hits = svc.search(
+ "photosynthesis sunlight chemical energy", coll_id, top_k=5
+ )
+ assert hits == [], (
+ "control expected to demonstrate silent indexed-but-unsearchable "
+ "staleness, but search still returned results — the failure "
+ "scenario this backstop guards against did not reproduce"
+ )
+ svc.close()
+
+
+# --------------------------------------------------------------------------- #
+# (b) VectorIndex.index -> _finalize_db: DB failure after a durable apply()
+# --------------------------------------------------------------------------- #
+class TestFacadeFinalizeDbFailureIsConsistent:
+ def test_finalize_db_failure_propagates_and_db_stays_consistent(
+ self, tmp_path, monkeypatch
+ ):
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ monkeypatch.setattr(
+ f"{_FACADE_MOD}.get_user_db_session", _shared_session
+ )
+
+ index_path = tmp_path / "finalize.faiss"
+ vi = VectorIndex(
+ username="finalize-tester",
+ db_password="pw", # gitleaks:allow
+ embeddings=_FakeEmbeddings(dim=8),
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name="collection_finalize",
+ dimension=8,
+ path=index_path,
+ lock=threading.Lock(),
+ integrity_record=lambda p: None,
+ integrity_verify=lambda p: (True, None),
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+ # 1) First index: real, durable, commits fine (no session passed ->
+ # facade owns the session it gets from the monkeypatched shared one).
+ stats1 = vi.index(
+ source_type="document",
+ source_id="doc-b",
+ chunks=[
+ ChunkInput(text="alpha body one", metadata={"chunk_index": 0})
+ ],
+ )
+ assert stats1.added == 1
+
+ row_a = session.query(DocumentChunk).filter_by(source_id="doc-b").one()
+ chunk_a_id = row_a.id
+
+ def _load_store():
+ return FaissVectorStore.load(
+ index_path,
+ dimension=8,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+ assert chunk_a_id in _load_store().live_ids()
+
+ # 2) Replace-reindex with a commit failure injected for the delete
+ # that _finalize_db issues AFTER store.apply() already durably
+ # removed chunk A's vector and added chunk B's.
+ def _boom():
+ raise RuntimeError("boom-commit")
+
+ monkeypatch.setattr(session, "commit", _boom)
+
+ with pytest.raises(RuntimeError, match="boom-commit"):
+ vi.index(
+ source_type="document",
+ source_id="doc-b",
+ chunks=[
+ ChunkInput(
+ text="beta body two", metadata={"chunk_index": 0}
+ )
+ ],
+ replace=True,
+ )
+
+ # (No manual rollback needed/added here: _finalize_db's except branch
+ # already calls session.rollback() itself when it owns the session —
+ # that is exactly the behavior under test.)
+
+ # (1) DB stays CONSISTENT: the prior row survived (its delete was
+ # rolled back) and no duplicate/second row was left half-applied.
+ rows = session.query(DocumentChunk).filter_by(source_id="doc-b").all()
+ assert len(rows) == 1, (
+ "DB left in a half-applied state after the failed commit: "
+ f"expected exactly the surviving prior row, got {len(rows)}"
+ )
+ assert rows[0].id == chunk_a_id
+
+ # (2) The STORE side is durable and now disagrees with the DB: chunk
+ # A's vector is really gone (removed before the failing commit)...
+ live = _load_store().live_ids()
+ assert chunk_a_id not in live, (
+ "store did not durably remove the old vector even though "
+ "apply() ran before the failing commit"
+ )
+ # ...while exactly one ORPHAN vector (chunk B's, added durably) is
+ # left with no matching DB row (its insert was rolled back).
+ assert len(live) == 1
+ orphan_id = live[0]
+ assert (
+ session.query(DocumentChunk).filter_by(id=orphan_id).first() is None
+ ), "expected an orphan vector with no DocumentChunk row after rollback"
diff --git a/tests/research_library/services/test_library_rag_service.py b/tests/research_library/services/test_library_rag_service.py
index cd6b4c0262..047f62dd23 100644
--- a/tests/research_library/services/test_library_rag_service.py
+++ b/tests/research_library/services/test_library_rag_service.py
@@ -4,7 +4,6 @@ Tests for LibraryRAGService.
from unittest.mock import Mock, MagicMock
from pathlib import Path
-from langchain_core.documents import Document as LangchainDocument
class TestLibraryRAGServiceInit:
@@ -371,7 +370,12 @@ class TestLibraryRAGServiceIndexDocument:
mock_session = MagicMock()
mock_session.__enter__ = Mock(return_value=mock_session)
mock_session.__exit__ = Mock(return_value=False)
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc
+ # 1st .first() = Document lookup; 2nd = prior-chunk probe -> None so the
+ # empty-text branch returns error (no prior chunks to purge).
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_doc,
+ None,
+ ]
mocker.patch(
"local_deep_research.research_library.services.library_rag_service.get_user_db_session",
@@ -587,77 +591,6 @@ class TestLibraryRAGServiceRemoveDocument:
assert "not found" in result["error"].lower()
-class TestLibraryRAGServiceLoadOrCreateFaissIndex:
- """Tests for FAISS index loading/creation."""
-
- def test_load_or_create_faiss_index_creates_new(self, mocker):
- """Creates new FAISS index when none exists."""
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- # Mock embedding manager with dimension
- mock_embedding_manager = Mock()
- mock_embeddings = Mock()
- mock_embeddings.embed_query.return_value = [
- 0.1
- ] * 384 # 384-dim embedding
- mock_embedding_manager.embeddings = mock_embeddings
-
- # Mock text splitter
- mock_splitter = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_text_splitter",
- return_value=mock_splitter,
- )
-
- # Mock integrity manager
- mock_integrity = Mock()
- mock_integrity.verify_file.return_value = (False, "File not found")
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",
- return_value=mock_integrity,
- )
-
- # Mock RAGIndex creation
- mock_rag_index = Mock()
- mock_rag_index.index_path = "/tmp/test.faiss"
- mock_rag_index.embedding_dimension = 384
- mock_rag_index.id = "rag-idx-123"
-
- # Mock FAISS
- mock_faiss = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FAISS",
- return_value=mock_faiss,
- )
-
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- service = LibraryRAGService(
- username="test_user",
- embedding_manager=mock_embedding_manager,
- )
-
- # Mock _get_or_create_rag_index
- service._get_or_create_rag_index = Mock(return_value=mock_rag_index)
-
- # Mock Path.exists to return False (no existing index)
- mocker.patch("pathlib.Path.exists", return_value=False)
-
- result = service.load_or_create_faiss_index("collection-123")
-
- assert result is not None
-
-
class TestLibraryRAGServiceIndexBatch:
"""Tests for batch document indexing."""
@@ -723,179 +656,8 @@ class TestLibraryRAGServiceIndexBatch:
assert "doc-123" in result
-class TestLoadOrCreateFaissIndexEdgeCases:
- """Additional tests for FAISS index loading/creation edge cases."""
-
- def test_load_existing_faiss_index(self, mocker):
- """Loads existing FAISS index from disk when available."""
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
-
- # Mock RAG index record
- mock_rag_index = Mock()
- mock_rag_index.id = "rag-idx-123"
- mock_rag_index.index_path = "/tmp/test.faiss"
- mock_rag_index.embedding_dimension = 384
- mock_rag_index.collection_id = "collection-123"
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_rag_index
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- # Mock embedding manager
- mock_embedding_manager = Mock()
- mock_embeddings = Mock()
- mock_embeddings.embed_query.return_value = [0.1] * 384
- mock_embedding_manager.embeddings = mock_embeddings
-
- # Mock text splitter
- mock_splitter = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_text_splitter",
- return_value=mock_splitter,
- )
-
- # Mock integrity manager - file exists and is valid
- mock_integrity = Mock()
- mock_integrity.verify_file.return_value = (True, "Valid")
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",
- return_value=mock_integrity,
- )
-
- # Mock Path.exists to return True
- mocker.patch("pathlib.Path.exists", return_value=True)
-
- # Mock the safe loader (replaces FAISS.load_local's dangerous
- # deserialization)
- mock_faiss_index = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.safe_load_faiss",
- return_value=mock_faiss_index,
- )
-
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- service = LibraryRAGService(
- username="test_user",
- embedding_manager=mock_embedding_manager,
- )
-
- result = service.load_or_create_faiss_index("collection-123")
-
- # Should return the index loaded via the safe loader (not a fresh one)
- assert result is mock_faiss_index
-
- def test_load_or_create_handles_corrupted_index(self, mocker):
- """Creates new index when existing one is corrupted."""
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
-
- # Mock RAG index that will fail integrity check
- mock_rag_index = Mock()
- mock_rag_index.id = "rag-idx-123"
- mock_rag_index.index_path = "/tmp/test.faiss"
- mock_rag_index.embedding_dimension = 384
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_rag_index
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- # Mock embedding manager
- mock_embedding_manager = Mock()
- mock_embeddings = Mock()
- mock_embeddings.embed_query.return_value = [0.1] * 384
- mock_embedding_manager.embeddings = mock_embeddings
-
- # Mock text splitter
- mock_splitter = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_text_splitter",
- return_value=mock_splitter,
- )
-
- # Mock integrity manager - file is corrupted
- mock_integrity = Mock()
- mock_integrity.verify_file.return_value = (False, "Hash mismatch")
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",
- return_value=mock_integrity,
- )
-
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- service = LibraryRAGService(
- username="test_user",
- embedding_manager=mock_embedding_manager,
- )
-
- # Corrupted index path: SUT quarantines the bad file and falls
- # through to building a fresh FAISS index — must not return None.
- result = service.load_or_create_faiss_index("collection-123")
- assert result is not None
-
- def test_load_index_with_different_embedding_dimension(self, mocker):
- """Handles dimension mismatch between index and current embeddings."""
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
-
- # Mock RAG index with different dimension
- mock_rag_index = Mock()
- mock_rag_index.id = "rag-idx-123"
- mock_rag_index.index_path = "/tmp/test.faiss"
- mock_rag_index.embedding_dimension = 768 # Different from current
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_rag_index
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- # Mock embedding manager with 384 dim
- mock_embedding_manager = Mock()
- mock_embeddings = Mock()
- mock_embeddings.embed_query.return_value = [0.1] * 384
- mock_embedding_manager.embeddings = mock_embeddings
-
- # Mock text splitter
- mock_splitter = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_text_splitter",
- return_value=mock_splitter,
- )
-
- # Mock integrity manager
- mock_integrity = Mock()
- mock_integrity.verify_file.return_value = (True, "Valid")
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",
- return_value=mock_integrity,
- )
-
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- service = LibraryRAGService(
- username="test_user",
- embedding_manager=mock_embedding_manager,
- )
-
- # Dimension mismatch: SUT deletes the stale index, updates the
- # RAGIndex row, and rebuilds — must return a fresh FAISS index.
- result = service.load_or_create_faiss_index("collection-123")
- assert result is not None
+class TestNormalizeVectorsConfig:
+ """Tests for the normalize_vectors constructor option."""
def test_create_index_with_normalize_vectors(self, mocker):
"""Creates index with vector normalization enabled."""
@@ -1002,395 +764,3 @@ class TestIndexAllDocuments:
# force_reindex should be a parameter
assert "force_reindex" in params or len(params) > 2
-
-
-class TestRemoveCollectionFromIndex:
- """Tests for remove_collection_from_index method."""
-
- def test_remove_collection_from_index_method_exists(self, mocker):
- """Verifies remove_collection_from_index method exists."""
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- assert hasattr(LibraryRAGService, "remove_collection_from_index")
- assert callable(
- getattr(LibraryRAGService, "remove_collection_from_index", None)
- )
-
- def test_remove_collection_from_index_signature(self, mocker):
- """Verifies remove_collection_from_index has expected parameters."""
- import inspect
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- sig = inspect.signature(LibraryRAGService.remove_collection_from_index)
- params = list(sig.parameters.keys())
-
- # Should have self and collection_name at minimum
- assert "self" in params
- assert "collection_name" in params
-
- def test_remove_collection_from_index_returns_dict(self, mocker):
- """Verifies remove_collection_from_index returns a dictionary."""
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- # Method should exist and be callable
- assert callable(LibraryRAGService.remove_collection_from_index)
-
- def test_remove_collection_from_index_accepts_collection_name(self, mocker):
- """Verifies remove_collection_from_index accepts collection_name."""
- import inspect
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- sig = inspect.signature(LibraryRAGService.remove_collection_from_index)
- params = list(sig.parameters.keys())
-
- assert "collection_name" in params
-
- def test_remove_collection_has_return_type(self, mocker):
- """Verifies remove_collection_from_index is properly defined."""
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- # Method should have docstring or be properly documented
- method = LibraryRAGService.remove_collection_from_index
- assert method is not None
-
-
-class TestLoadOrCreateFaissIndexCollectionId:
- """Tests that load_or_create_faiss_index receives the correct collection_id.
-
- Fixes a pre-existing bug where remove_collection_from_index called
- load_or_create_faiss_index() without the required collection_id argument.
- """
-
- def _create_service(self, mocker):
- """Create a minimally mocked LibraryRAGService."""
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- mock_embedding_manager = Mock()
- mock_embedding_manager.embeddings = Mock()
- mock_embedding_manager.embeddings.embed_query.return_value = [0.1] * 384
-
- mock_splitter = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_text_splitter",
- return_value=mock_splitter,
- )
-
- mock_integrity = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",
- return_value=mock_integrity,
- )
-
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- service = LibraryRAGService(
- username="test_user",
- embedding_manager=mock_embedding_manager,
- )
- return service
-
- def test_remove_collection_passes_extracted_collection_id(self, mocker):
- """remove_collection_from_index extracts collection_id from collection_name."""
- service = self._create_service(mocker)
-
- # Mock DB session to return chunks — patch at source since method does local import
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
-
- mock_chunk = Mock()
- mock_chunk.id = "chunk-1"
- mock_session.query.return_value.filter_by.return_value.all.return_value = [
- mock_chunk
- ]
-
- mocker.patch(
- "local_deep_research.database.session_context.get_user_db_session",
- return_value=mock_session,
- )
-
- # Mock FAISS index as None to trigger load
- service.faiss_index = None
- mock_faiss_index = MagicMock()
- service.load_or_create_faiss_index = Mock(return_value=mock_faiss_index)
-
- collection_name = "collection_xyz-uuid-456"
- service.remove_collection_from_index(collection_name)
-
- # Verify collection_id was correctly extracted and passed; a write
- # path opts into healing stale index state on a fresh build.
- service.load_or_create_faiss_index.assert_called_once_with(
- "xyz-uuid-456", reset_stale_state=True
- )
-
-
-class TestDeduplicateChunks:
- """Tests for _deduplicate_chunks static method.
-
- This covers the bug fix where duplicate chunk IDs from
- _store_chunks_to_db() caused FAISS add_documents() to reject
- the batch with 'Duplicate ids found in the ids list'.
- """
-
- def test_no_duplicates_passes_all_through(self):
- """All chunks pass through when there are no duplicates."""
- from langchain_core.documents import Document as LangchainDocument
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks = [
- LangchainDocument(page_content="chunk 1"),
- LangchainDocument(page_content="chunk 2"),
- LangchainDocument(page_content="chunk 3"),
- ]
- ids = ["id-1", "id-2", "id-3"]
-
- result_chunks, result_ids = LibraryRAGService._deduplicate_chunks(
- chunks, ids
- )
-
- assert len(result_chunks) == 3
- assert result_ids == ["id-1", "id-2", "id-3"]
-
- def test_batch_duplicates_are_removed(self):
- """Duplicate IDs within a batch keep only the first occurrence."""
- from langchain_core.documents import Document as LangchainDocument
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks = [
- LangchainDocument(page_content="header text"),
- LangchainDocument(page_content="unique content"),
- LangchainDocument(
- page_content="header text"
- ), # same hash -> same ID
- ]
- ids = ["id-dup", "id-unique", "id-dup"]
-
- result_chunks, result_ids = LibraryRAGService._deduplicate_chunks(
- chunks, ids
- )
-
- assert len(result_chunks) == 2
- assert result_ids == ["id-dup", "id-unique"]
- assert result_chunks[0].page_content == "header text"
- assert result_chunks[1].page_content == "unique content"
-
- def test_existing_ids_are_excluded(self):
- """Chunks with IDs already in the FAISS index are filtered out."""
- from langchain_core.documents import Document as LangchainDocument
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks = [
- LangchainDocument(page_content="already indexed"),
- LangchainDocument(page_content="new content"),
- ]
- ids = ["id-old", "id-new"]
- existing = {"id-old"}
-
- result_chunks, result_ids = LibraryRAGService._deduplicate_chunks(
- chunks, ids, existing_ids=existing
- )
-
- assert len(result_chunks) == 1
- assert result_ids == ["id-new"]
-
- def test_batch_duplicates_and_existing_ids_combined(self):
- """Both batch duplicates and existing IDs are filtered."""
- from langchain_core.documents import Document as LangchainDocument
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks = [
- LangchainDocument(page_content="old"),
- LangchainDocument(page_content="new A"),
- LangchainDocument(page_content="new A copy"), # dup of new A
- LangchainDocument(page_content="new B"),
- ]
- ids = ["id-old", "id-a", "id-a", "id-b"]
- existing = {"id-old"}
-
- result_chunks, result_ids = LibraryRAGService._deduplicate_chunks(
- chunks, ids, existing_ids=existing
- )
-
- assert len(result_chunks) == 2
- assert result_ids == ["id-a", "id-b"]
-
- def test_all_duplicates_returns_empty(self):
- """Returns empty lists when all chunks are duplicates."""
- from langchain_core.documents import Document as LangchainDocument
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks = [
- LangchainDocument(page_content="same"),
- LangchainDocument(page_content="same"),
- ]
- ids = ["id-x", "id-x"]
- existing = {"id-x"}
-
- result_chunks, result_ids = LibraryRAGService._deduplicate_chunks(
- chunks, ids, existing_ids=existing
- )
-
- assert len(result_chunks) == 0
- assert len(result_ids) == 0
-
- def test_none_existing_ids_skips_existing_check(self):
- """When existing_ids is None (force_reindex), only batch dedup applies."""
- from langchain_core.documents import Document as LangchainDocument
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks = [
- LangchainDocument(page_content="A"),
- LangchainDocument(page_content="B"),
- LangchainDocument(page_content="A copy"),
- ]
- ids = ["id-1", "id-2", "id-1"]
-
- result_chunks, result_ids = LibraryRAGService._deduplicate_chunks(
- chunks, ids, existing_ids=None
- )
-
- assert len(result_chunks) == 2
- assert result_ids == ["id-1", "id-2"]
-
-
-def _create_rag_service(mocker):
- """Helper to create a minimally-mocked LibraryRAGService."""
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- mock_embedding_manager = Mock()
- mock_embedding_manager.embeddings = Mock()
- mock_embedding_manager.embeddings.embed_query.return_value = [0.1] * 384
-
- mock_splitter = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_text_splitter",
- return_value=mock_splitter,
- )
-
- mock_integrity = Mock()
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FileIntegrityManager",
- return_value=mock_integrity,
- )
-
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- service = LibraryRAGService(
- username="test_user",
- embedding_manager=mock_embedding_manager,
- )
- return service
-
-
-class TestForceReindexDedup:
- """Tests for force_reindex old_chunk_ids deduplication."""
-
- def test_force_reindex_old_chunk_ids_deduplicated_index_document(
- self, mocker
- ):
- """Verify deletion path in index_document uses unique IDs."""
- service = _create_rag_service(mocker)
-
- # Mock document lookup
- mock_doc = Mock()
- mock_doc.id = "doc-1"
- mock_doc.text_content = "Hello world test content"
- mock_doc.title = "Test"
- mock_doc.filename = "test.txt"
- mock_doc.original_url = "http://example.com"
- mock_doc.authors = None
- mock_doc.published_date = None
- mock_doc.doi = None
- mock_doc.arxiv_id = None
-
- mock_doc_collection = Mock()
- mock_doc_collection.indexed = True
- mock_doc_collection.chunk_count = 2
-
- mock_session = MagicMock()
- mock_session.__enter__ = Mock(return_value=mock_session)
- mock_session.__exit__ = Mock(return_value=False)
- # First query: Document lookup, second: DocumentCollection
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc
- mock_session.query.return_value.filter_by.return_value.all.return_value = [
- mock_doc_collection
- ]
-
- mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.get_user_db_session",
- return_value=mock_session,
- )
-
- # Chunks with duplicate IDs (the root cause of #2182)
- chunks = [
- LangchainDocument(page_content="chunk A"),
- LangchainDocument(page_content="chunk B"),
- LangchainDocument(page_content="chunk A dup"),
- ]
- service.text_splitter.split_documents.return_value = chunks
-
- # _store_chunks_to_db returns IDs with duplicates
- duplicate_ids = ["id-1", "id-2", "id-1"]
- service.embedding_manager._store_chunks_to_db.return_value = (
- duplicate_ids
- )
-
- # Setup FAISS mock with existing IDs
- mock_faiss = Mock()
- mock_docstore = Mock()
- mock_docstore._dict = {"id-1": "doc", "id-2": "doc"}
- mock_faiss.docstore = mock_docstore
- service.faiss_index = mock_faiss
-
- mock_rag_index = Mock()
- mock_rag_index.index_path = "/tmp/test.faiss"
- mock_rag_index.id = "rag-1"
- service.rag_index_record = mock_rag_index
-
- service.index_document("doc-1", "coll-1", force_reindex=True)
-
- # Verify delete was called with deduplicated IDs
- delete_call = mock_faiss.delete.call_args[0][0]
- assert len(delete_call) == len(set(delete_call)), (
- "old_chunk_ids passed to FAISS.delete() must not contain duplicates"
- )
diff --git a/tests/research_library/services/test_library_rag_service_coverage.py b/tests/research_library/services/test_library_rag_service_coverage.py
index 0b5ca787fc..4f53e7a2cb 100644
--- a/tests/research_library/services/test_library_rag_service_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_coverage.py
@@ -4,10 +4,7 @@ Coverage tests for LibraryRAGService.
Focuses on logic paths not exercised by the existing test_library_rag_service.py:
- _get_index_hash edge cases
- _get_index_path cache directory details
-- _deduplicate_chunks order preservation and empty input
- _get_or_create_rag_index new vs existing
-- load_or_create_faiss_index HNSW/IVF/L2/IP variants, integrity failure, dimension mismatch,
- load failure, corrupted unlink failure
- index_document chunk indexing, empty text, skip already indexed
- index_all_documents with progress callback, stores settings
"""
@@ -18,7 +15,6 @@ from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
-from langchain_core.documents import Document as LangchainDocument
# ---------------------------------------------------------------------------
# Module-level patch path prefix
@@ -137,94 +133,6 @@ class TestGetIndexPath:
assert isinstance(p, Path)
-# =========================================================================
-# _deduplicate_chunks (static method)
-# =========================================================================
-class TestDeduplicateChunks:
- """Tests for _deduplicate_chunks."""
-
- def _doc(self, text):
- return LangchainDocument(page_content=text)
-
- def test_empty_input_returns_empty(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- chunks, ids = LibraryRAGService._deduplicate_chunks([], [])
- assert chunks == []
- assert ids == []
-
- def test_no_duplicates_preserved(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- d1, d2 = self._doc("a"), self._doc("b")
- chunks, ids = LibraryRAGService._deduplicate_chunks(
- [d1, d2], ["id1", "id2"]
- )
- assert ids == ["id1", "id2"]
- assert chunks == [d1, d2]
-
- def test_duplicate_ids_keeps_first(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- d1, d2, d3 = self._doc("a"), self._doc("b"), self._doc("c")
- chunks, ids = LibraryRAGService._deduplicate_chunks(
- [d1, d2, d3], ["id1", "id1", "id2"]
- )
- assert ids == ["id1", "id2"]
- assert chunks == [d1, d3]
-
- def test_existing_ids_excluded(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- d1, d2 = self._doc("a"), self._doc("b")
- chunks, ids = LibraryRAGService._deduplicate_chunks(
- [d1, d2], ["id1", "id2"], existing_ids={"id1"}
- )
- assert ids == ["id2"]
- assert chunks == [d2]
-
- def test_none_existing_ids_allows_all(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- d1 = self._doc("a")
- chunks, ids = LibraryRAGService._deduplicate_chunks(
- [d1], ["id1"], existing_ids=None
- )
- assert ids == ["id1"]
-
- def test_order_preservation(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- docs = [self._doc(str(i)) for i in range(5)]
- id_list = ["e", "d", "c", "b", "a"]
- chunks, ids = LibraryRAGService._deduplicate_chunks(docs, id_list)
- assert ids == ["e", "d", "c", "b", "a"]
-
- def test_all_existing_returns_empty(self):
- from local_deep_research.research_library.services.library_rag_service import (
- LibraryRAGService,
- )
-
- d1, d2 = self._doc("a"), self._doc("b")
- chunks, ids = LibraryRAGService._deduplicate_chunks(
- [d1, d2], ["id1", "id2"], existing_ids={"id1", "id2"}
- )
- assert chunks == []
- assert ids == []
-
-
# =========================================================================
# _get_or_create_rag_index
# =========================================================================
@@ -298,414 +206,6 @@ class TestGetOrCreateRagIndex:
)
-# =========================================================================
-# load_or_create_faiss_index
-# =========================================================================
-class TestLoadOrCreateFaissIndex:
- """Tests for load_or_create_faiss_index."""
-
- def _patch_get_or_create(self, svc, rag_index):
- """Patch _get_or_create_rag_index on a service instance."""
- svc._get_or_create_rag_index = MagicMock(return_value=rag_index)
- # The fresh-build branch resets stale indexed-state via a DB
- # session, and a missing per-user path probes the legacy cache
- # dir for migration. Both are covered by their own test classes
- # (TestResetIndexStateForRebuild / TestMigrateLegacyIndexFiles);
- # these tests target index construction, so stub them out.
- svc._reset_index_state_for_rebuild = MagicMock()
- svc._migrate_legacy_index_files = MagicMock()
-
- def _make_rag_index(self, index_path="/tmp/test.faiss", dim=384):
- idx = MagicMock()
- idx.index_path = index_path
- idx.embedding_dimension = dim
- idx.id = "rag-idx-1"
- return idx
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_creates_flat_ip_for_cosine(
- self, mock_flat_ip, mock_docstore, mock_faiss
- ):
- svc = _make_service(distance_metric="cosine", index_type="flat")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- mock_flat_ip.assert_called_once_with(384)
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatL2")
- def test_creates_flat_l2_for_l2_metric(
- self, mock_flat_l2, mock_docstore, mock_faiss
- ):
- svc = _make_service(distance_metric="l2", index_type="flat")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- mock_flat_l2.assert_called_once_with(384)
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexHNSWFlat")
- def test_creates_hnsw_index(self, mock_hnsw, mock_docstore, mock_faiss):
- svc = _make_service(index_type="hnsw")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- mock_hnsw.assert_called_once_with(384, 32)
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_read_path_never_resets_index_state(
- self, mock_flat_ip, mock_docstore, mock_faiss
- ):
- """A plain load (the search/read path) reaching the fresh-build
- branch must NOT reset the collection's indexed state — otherwise a
- transient integrity failure during a mere search wipes
- RagDocumentStatus/DocumentCollection.indexed and triggers a full
- re-embed of the collection."""
- svc = _make_service(distance_metric="cosine", index_type="flat")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- svc._reset_index_state_for_rebuild.assert_not_called()
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_write_path_resets_index_state_on_fresh_build(
- self, mock_flat_ip, mock_docstore, mock_faiss
- ):
- """Write callers (index/delete operations) opt in via
- reset_stale_state=True so a lost on-disk index still heals: stale
- DB rows are cleared and the regular re-index rebuilds for real."""
- svc = _make_service(distance_metric="cosine", index_type="flat")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1", reset_stale_state=True)
- svc._reset_index_state_for_rebuild.assert_called_once_with(
- "coll-1", rag_idx
- )
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_ivf_falls_back_to_flat_ip_for_cosine(
- self, mock_flat_ip, mock_docstore, mock_faiss
- ):
- svc = _make_service(index_type="ivf", distance_metric="cosine")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- mock_flat_ip.assert_called_once_with(384)
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatL2")
- def test_ivf_falls_back_to_flat_l2_for_l2(
- self, mock_flat_l2, mock_docstore, mock_faiss
- ):
- svc = _make_service(index_type="ivf", distance_metric="l2")
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- mock_flat_l2.assert_called_once_with(384)
-
- @patch(f"{_MOD}.safe_load_faiss")
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_verified_load_returns_existing_index(
- self, mock_flat_ip, mock_docstore, mock_faiss_cls, mock_safe_load
- ):
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.embedding_manager.embeddings.embed_query.return_value = [0.0] * 384
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
-
- rag_idx = self._make_rag_index(dim=384)
- rag_idx.index_path = "/tmp/existing.faiss"
- self._patch_get_or_create(svc, rag_idx)
-
- mock_loaded = MagicMock()
- mock_safe_load.return_value = mock_loaded
-
- with patch.object(Path, "exists", return_value=True):
- result = svc.load_or_create_faiss_index("coll-1")
-
- # Verified index is loaded via the restricted-unpickler loader,
- # never via the dangerous FAISS.load_local.
- assert result is mock_loaded
- mock_safe_load.assert_called_once()
- mock_faiss_cls.load_local.assert_not_called()
-
- @patch(f"{_MOD}.get_cache_directory")
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_integrity_failure_quarantines_and_creates_new_index(
- self,
- mock_flat_ip,
- mock_docstore,
- mock_faiss_cls,
- mock_cache_dir,
- tmp_path,
- ):
- """Verify-failure path: corrupt .faiss + .pkl are RENAMED to
- .corrupt-<ns>, NOT unlinked. Then fresh index is created.
- Regression for #4197 data-loss bug.
- """
- mock_cache_dir.return_value = tmp_path
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (
- False,
- "hash mismatch",
- )
-
- # The loader recomputes the per-user path from the index hash
- # (ignoring the stored index_path), so the corrupt files must
- # live at the recomputed location. Real on-disk files so
- # .exists() in the quarantine collision check returns False
- # naturally for the .corrupt-* paths, not True-for-everything.
- rag_idx = self._make_rag_index()
- rag_idx.index_hash = "corrupt"
- idx_path = svc._get_index_path("corrupt")
- pkl_path = idx_path.with_suffix(".pkl")
- idx_path.write_bytes(b"faiss-bytes")
- pkl_path.write_bytes(b"pkl-bytes")
- rag_idx.index_path = str(idx_path)
- self._patch_get_or_create(svc, rag_idx)
-
- with patch.object(Path, "unlink") as mock_unlink:
- svc.load_or_create_faiss_index("coll-1")
-
- # Should NOT have unlinked anything in the verify-failure path
- mock_unlink.assert_not_called()
- # Originals quarantined (renamed away from their paths)
- assert not idx_path.exists()
- assert not pkl_path.exists()
- # Both files preserved under .corrupt-<ns> names
- corrupt_faiss = list(idx_path.parent.glob("corrupt.faiss.corrupt-*"))
- corrupt_pkl = list(idx_path.parent.glob("corrupt.pkl.corrupt-*"))
- assert len(corrupt_faiss) == 1
- assert len(corrupt_pkl) == 1
- assert corrupt_faiss[0].read_bytes() == b"faiss-bytes"
- # Should return a new FAISS instance, not load_local
- mock_faiss_cls.load_local.assert_not_called()
- mock_faiss_cls.assert_called_once()
-
- @patch(f"{_MOD}.get_cache_directory")
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_quarantine_rename_oserror_re_raises(
- self,
- mock_flat_ip,
- mock_docstore,
- mock_faiss_cls,
- mock_cache_dir,
- tmp_path,
- ):
- """Disk-full / read-only fs during quarantine MUST propagate.
- Silently falling through would let the next save_local truncate
- the corrupt bytes, recreating the very data loss #4197 fixes.
- """
- mock_cache_dir.return_value = tmp_path
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (False, "bad hash")
-
- rag_idx = self._make_rag_index()
- rag_idx.index_hash = "corrupt"
- idx_path = svc._get_index_path("corrupt")
- idx_path.write_bytes(b"faiss-bytes")
- idx_path.with_suffix(".pkl").write_bytes(b"pkl-bytes")
- rag_idx.index_path = str(idx_path)
- self._patch_get_or_create(svc, rag_idx)
-
- with patch.object(Path, "rename", side_effect=OSError("ENOSPC")):
- with pytest.raises(OSError, match="ENOSPC"):
- svc.load_or_create_faiss_index("coll-1")
-
- # Fresh index must NOT have been created — corrupt bytes are
- # still on disk and creating one would let the next save
- # overwrite them.
- mock_faiss_cls.assert_not_called()
-
- @patch(f"{_MOD}.get_user_db_session")
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_dimension_mismatch_deletes_and_rebuilds(
- self, mock_flat_ip, mock_docstore, mock_faiss_cls, mock_session_ctx
- ):
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- # Current model returns dim 768 but index was stored with 384
- svc.embedding_manager.embeddings.embed_query.return_value = [0.0] * 768
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
-
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
- )
- mock_session_ctx.return_value.__exit__ = MagicMock(return_value=None)
- mock_session.query.return_value.filter_by.return_value.first.return_value = MagicMock()
-
- rag_idx = self._make_rag_index(dim=384)
- rag_idx.index_path = "/tmp/old_dim.faiss"
- self._patch_get_or_create(svc, rag_idx)
-
- with (
- patch.object(Path, "exists", return_value=True),
- patch.object(Path, "unlink") as mock_unlink,
- patch.object(Path, "with_suffix") as mock_with_suffix,
- ):
- mock_pkl = MagicMock()
- mock_pkl.exists.return_value = True
- mock_with_suffix.return_value = mock_pkl
- svc.load_or_create_faiss_index("coll-1")
-
- # The old file should have been unlinked
- mock_unlink.assert_called()
- # A new FAISS should be created (not loaded)
- mock_faiss_cls.assert_called_once()
-
- @patch(f"{_MOD}.safe_load_faiss")
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_load_failure_quarantines_and_creates_new_index(
- self,
- mock_flat_ip,
- mock_docstore,
- mock_faiss_cls,
- mock_safe_load,
- tmp_path,
- ):
- """When the loader raises (torn .pkl, malformed pickle, or a
- rejected/tampered pickle), the .faiss and .pkl are quarantined
- before falling through to a fresh index. Previously the old code
- silently discarded the broken-state files without preserving
- evidence.
- """
- with patch(f"{_MOD}.get_cache_directory", return_value=tmp_path):
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.embedding_manager.embeddings.embed_query.return_value = [
- 0.0
- ] * 384
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
-
- # Files must live at the recomputed per-user path — the
- # loader ignores the stored index_path.
- rag_idx = self._make_rag_index(dim=384)
- rag_idx.index_hash = "broken"
- idx_path = svc._get_index_path("broken")
- pkl_path = idx_path.with_suffix(".pkl")
- idx_path.write_bytes(b"faiss-bytes")
- pkl_path.write_bytes(b"pkl-bytes")
- rag_idx.index_path = str(idx_path)
- self._patch_get_or_create(svc, rag_idx)
-
- # The loader is now safe_load_faiss (not FAISS.load_local); make
- # it raise to drive the quarantine-and-rebuild path.
- mock_safe_load.side_effect = RuntimeError("corrupted file")
-
- svc.load_or_create_faiss_index("coll-1")
-
- # Both files quarantined (renamed away)
- assert not idx_path.exists()
- assert not pkl_path.exists()
- assert len(list(idx_path.parent.glob("broken.faiss.corrupt-*"))) == 1
- assert len(list(idx_path.parent.glob("broken.pkl.corrupt-*"))) == 1
- # Should fall through and create new index
- mock_faiss_cls.assert_called_once()
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_embedding_provider_failure_raises_and_preserves_index(
- self, mock_flat_ip, mock_docstore, mock_faiss_cls, tmp_path
- ):
- """When the embedding provider is unreachable (e.g. Ollama down),
- the dimension-check embed_query raises. That says nothing about
- the index files, so the error must propagate WITHOUT quarantining
- the healthy index or replacing it with an empty one.
- """
- # The loader recomputes the index path from index_hash under the
- # cache dir (per-user scoping), ignoring the stored index_path —
- # so the healthy files must live at the *recomputed* location for
- # index_path.exists() to be True and the probe to run.
- with patch(f"{_MOD}.get_cache_directory", return_value=tmp_path):
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.embedding_manager.embeddings.embed_query.side_effect = (
- ConnectionError("Ollama connection refused")
- )
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
-
- rag_idx = self._make_rag_index(dim=384)
- rag_idx.index_hash = "healthy"
- idx_path = svc._get_index_path("healthy")
- pkl_path = idx_path.with_suffix(".pkl")
- idx_path.write_bytes(b"faiss-bytes")
- pkl_path.write_bytes(b"pkl-bytes")
- # stored == recomputed so no legacy migration fires.
- rag_idx.index_path = str(idx_path)
- self._patch_get_or_create(svc, rag_idx)
-
- with pytest.raises(ConnectionError, match="Ollama"):
- svc.load_or_create_faiss_index("coll-1")
-
- # The healthy index files must be untouched — not quarantined
- assert idx_path.read_bytes() == b"faiss-bytes"
- assert pkl_path.read_bytes() == b"pkl-bytes"
- assert list(idx_path.parent.glob("*.corrupt-*")) == []
- # And no empty replacement index was created
- mock_faiss_cls.load_local.assert_not_called()
- mock_faiss_cls.assert_not_called()
-
- @patch(f"{_MOD}.FAISS")
- @patch(f"{_MOD}.InMemoryDocstore")
- @patch(f"{_MOD}.IndexFlatIP")
- def test_normalize_vectors_passed_to_faiss(
- self, mock_flat_ip, mock_docstore, mock_faiss_cls
- ):
- svc = _make_service(normalize_vectors=False)
- rag_idx = self._make_rag_index(index_path="/nonexistent/test.faiss")
- self._patch_get_or_create(svc, rag_idx)
- svc.embedding_manager = MagicMock()
-
- svc.load_or_create_faiss_index("coll-1")
- call_kwargs = mock_faiss_cls.call_args
- assert call_kwargs[1]["normalize_L2"] is False
-
-
# =========================================================================
# index_document
# =========================================================================
@@ -741,7 +241,12 @@ class TestIndexDocument:
mock_document = MagicMock()
mock_document.text_content = None
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_document
+ # 1st .first() = Document lookup; 2nd = prior-chunk probe -> None so the
+ # empty-text branch returns error (no prior chunks to purge).
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_document,
+ None,
+ ]
mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)
@@ -770,77 +275,6 @@ class TestIndexDocument:
assert result["status"] == "skipped"
assert result["chunk_count"] == 42
- @patch(f"{_MOD}.ensure_in_collection")
- @patch(f"{_MOD}.get_user_db_session")
- def test_reindex_passes_replace_keys_and_prunes_stale_db_rows(
- self, mock_session_ctx, mock_ensure
- ):
- """re-indexing forwards the document/collection
- to the merge step (which derives the FAISS purge from the docstore)
- and prunes this document's stale DB chunk rows (those whose
- embedding id the new content no longer uses) INSIDE the main
- transaction — no fragile pre-commit, no session poisoning."""
- from local_deep_research.database.models.library import DocumentChunk
-
- svc = _make_service()
- mock_session = MagicMock()
- mock_session_ctx.return_value.__enter__ = MagicMock(
- return_value=mock_session
- )
- mock_session_ctx.return_value.__exit__ = MagicMock(return_value=None)
-
- mock_document = MagicMock()
- mock_document.text_content = "new content"
-
- prune_filter = MagicMock()
- notin_filter = MagicMock()
- notin_filter.delete.return_value = 2
- prune_filter.filter.return_value = notin_filter
-
- def _query(arg):
- q = MagicMock()
- if arg is DocumentChunk:
- # The stale-DB-prune query: .filter(...).filter(notin_).delete()
- q.filter.return_value = prune_filter
- else:
- q.filter_by.return_value.first.return_value = (
- mock_document
- if arg.__name__ == "Document"
- else MagicMock()
- if arg.__name__ == "Collection"
- else None
- )
- return q
-
- mock_session.query.side_effect = _query
- mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)
-
- svc.text_splitter = MagicMock()
- svc.text_splitter.split_documents.return_value = [
- LangchainDocument(page_content="new content")
- ]
- svc.embedding_manager = MagicMock()
- svc.embedding_manager._store_chunks_to_db.return_value = ["new-id"]
- svc.faiss_index = MagicMock()
- svc.rag_index_record = MagicMock(index_path="/tmp/x.faiss")
- svc.load_or_create_faiss_index = MagicMock(return_value=svc.faiss_index)
- svc._merge_and_persist_locked = MagicMock(
- return_value={"added": 1, "skipped": 0, "added_ids": ["new-id"]}
- )
-
- result = svc.index_document("doc-1", "coll-1", force_reindex=False)
- assert result["status"] == "success"
-
- # Merge received the document/collection so it can derive the FAISS
- # purge from the docstore (no caller-supplied id snapshot).
- _, kwargs = svc._merge_and_persist_locked.call_args
- assert kwargs["replace_document_id"] == "doc-1"
- assert kwargs["replace_collection_id"] == "coll-1"
- # Stale DB chunk rows pruned (filtered to embedding_id NOT IN new ids),
- # and the work committed once at the end (no separate pre-commit).
- notin_filter.delete.assert_called_once()
- mock_session.commit.assert_called_once()
-
# =========================================================================
# index_all_documents (index_collection in the spec)
@@ -1031,20 +465,21 @@ class TestCorruptionQuarantine:
pkl.write_bytes(b"pkl-bytes")
return idx, pkl
- def test_renames_both_faiss_and_pkl(self, tmp_path):
+ def test_quarantines_faiss_but_deletes_legacy_plaintext_pkl(self, tmp_path):
svc = _make_service()
idx, pkl = self._make_idx(tmp_path)
svc._quarantine_corrupt_index(idx, "test")
# Original files are gone from their paths
assert not idx.exists()
assert not pkl.exists()
- # Both quarantined as .corrupt-*
+ # The .faiss is preserved for recovery (renamed to .corrupt-*)...
corrupted_faiss = list(tmp_path.glob("idx.faiss.corrupt-*"))
- corrupted_pkl = list(tmp_path.glob("idx.pkl.corrupt-*"))
assert len(corrupted_faiss) == 1
- assert len(corrupted_pkl) == 1
assert corrupted_faiss[0].read_bytes() == b"faiss-bytes"
- assert corrupted_pkl[0].read_bytes() == b"pkl-bytes"
+ # ...but the legacy plaintext .pkl is DELETED, not preserved: its text
+ # lives in the encrypted DB, so renaming it aside would needlessly keep
+ # plaintext chunk text on disk.
+ assert list(tmp_path.glob("idx.pkl.corrupt-*")) == []
def test_skips_pkl_when_missing(self, tmp_path):
svc = _make_service()
@@ -1066,6 +501,29 @@ class TestCorruptionQuarantine:
with pytest.raises(OSError, match="EROFS"):
svc._quarantine_corrupt_index(idx, "test")
+ def test_already_quarantined_by_another_process_does_not_raise(
+ self, tmp_path
+ ):
+ """A concurrent worker PROCESS can quarantine the same corrupt index
+ first; our rename then fails because the source is already gone. That
+ is the objective already met, not a failure — return gracefully (so the
+ caller rebuilds fresh) and still purge any lingering plaintext .pkl."""
+ svc = _make_service()
+ idx, pkl = self._make_idx(tmp_path)
+
+ def _steal_then_fail(*args, **kwargs):
+ # Simulate the other process having already moved the .faiss aside.
+ idx.unlink()
+ raise FileNotFoundError(2, "No such file or directory")
+
+ with patch.object(Path, "rename", side_effect=_steal_then_fail):
+ # Must NOT raise — the corrupt file is already gone.
+ svc._quarantine_corrupt_index(idx, "test")
+
+ assert not idx.exists()
+ # The lingering plaintext .pkl is purged even on the race path.
+ assert not pkl.exists()
+
def test_collision_increments_suffix(self, tmp_path):
"""Pre-existing quarantine path → loop increments to -1, -2, ..."""
svc = _make_service()
@@ -1339,6 +797,31 @@ class TestFaissWriteLock:
same_u2 = mod._get_faiss_write_lock("u2", str(tmp_path / "a.faiss"))
assert same_u2 is u2_lock
+ def test_pop_does_not_evict_a_held_lock(self, tmp_path):
+ # A lock held by an in-flight writer must NOT be evicted — otherwise the
+ # next writer would create a fresh lock and race the holder on the same
+ # file. An unheld lock IS evicted.
+ self._reset_locks()
+ mod = _import_module()
+ held = mod._get_faiss_write_lock("u1", str(tmp_path / "a.faiss"))
+ unheld = mod._get_faiss_write_lock("u1", str(tmp_path / "b.faiss"))
+
+ held.acquire()
+ try:
+ mod.pop_faiss_locks_for_user("u1")
+ finally:
+ held.release()
+
+ # Held lock survived: same object -> mutual exclusion preserved.
+ assert (
+ mod._get_faiss_write_lock("u1", str(tmp_path / "a.faiss")) is held
+ )
+ # Unheld lock was evicted: fresh object.
+ assert (
+ mod._get_faiss_write_lock("u1", str(tmp_path / "b.faiss"))
+ is not unheld
+ )
+
def test_concurrent_holders_serialised_for_same_key(self, tmp_path):
"""Two threads acquiring ``_get_faiss_write_lock`` for the same
``(username, index_path)`` MUST observe non-overlapping critical
@@ -1442,691 +925,6 @@ class TestNoWalCheckpointInIndexingPath:
)
-class TestMergeAndPersistLocked:
- """Read-modify-write under the FAISS write lock.
-
- Regression for the AI-review concern on #4200: two workers
- indexing different documents into the same collection used to
- both load on-disk state X, each add their own chunk in memory,
- then save in sequence — last writer wins, the loser's chunks
- were lost from the FAISS file (chunks survived in the DB so a
- rebuild recovered them, but the index file was wrong until then).
-
- The helper reloads from disk under the lock before adding, so
- the second writer sees the first writer's save and merges
- instead of overwriting.
- """
-
- def _reset_locks(self):
- mod = _import_module()
- with mod._faiss_write_locks_lock:
- mod._faiss_write_locks.clear()
-
- def _patch_ownership_session(self, mod, foreign_ids=()):
- """Patch the module's get_user_db_session for the purge's
- exclusive-ownership query. Embedding ids in ``foreign_ids`` read
- as DocumentChunk rows owned by a DIFFERENT document (shared
- chunks the purge must keep); the default empty set means every
- candidate is exclusively owned and purgeable. The shared-text
- survivor query (query().join().filter().first()) finds nothing,
- so it doesn't interfere with the ownership-focused tests."""
- from contextlib import contextmanager
-
- session = MagicMock()
- session.query.return_value.filter.return_value = [
- (fid,) for fid in foreign_ids
- ]
- # The shared-text survivor query streams member text_content via
- # query().join().filter().yield_per(); no other members → empty,
- # so everything stays purgeable.
- (
- session.query.return_value.join.return_value.filter.return_value.yield_per
- ).return_value = []
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield session
-
- return patch.object(mod, "get_user_db_session", fake_session)
-
- def test_reload_picks_up_concurrent_writers_save(self, tmp_path):
- """The merge helper must reload from disk before adding so
- chunks committed by a concurrent writer between the caller's
- in-memory load and this lock acquisition are preserved.
- """
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- # The on-disk file must exist + verify so the helper actually
- # takes the reload branch (not "no on-disk version, keep
- # stale in-memory").
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
-
- # Caller's stale in-memory state knows about no chunks.
- stale_index = MagicMock()
- stale_index.docstore._dict = {}
- svc.faiss_index = stale_index
-
- # Disk state (loaded by the reload step) already has another
- # writer's chunk "concurrent-id".
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {"concurrent-id": MagicMock()}
-
- new_chunk = LangchainDocument(page_content="our new content")
-
- with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
- stats = svc._merge_and_persist_locked(
- index_path,
- [new_chunk],
- ["our-id"],
- force_reindex=False,
- )
-
- # Helper reloaded → svc.faiss_index is now the fresh state
- assert svc.faiss_index is fresh_index
- # Our chunk was added to the fresh state (not the stale one)
- fresh_index.add_documents.assert_called_once()
- added_ids = fresh_index.add_documents.call_args[1]["ids"]
- assert added_ids == ["our-id"]
- # The stale state was NOT mutated (otherwise we'd be saving it)
- stale_index.add_documents.assert_not_called()
- # save_local was called on the fresh (merged) state
- fresh_index.save_local.assert_called_once()
- assert stats["added"] == 1
- assert stats["added_ids"] == ["our-id"]
-
- def test_reload_skips_when_existing_id_now_on_disk(self, tmp_path):
- """If the caller wanted to add id X but a concurrent writer
- already saved X to disk, dedup against the fresh state must
- drop X (idempotent re-index).
- """
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock() # stale, irrelevant
-
- # Disk state already has the same id we're about to add.
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {"shared-id": MagicMock()}
-
- with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
- stats = svc._merge_and_persist_locked(
- index_path,
- [LangchainDocument(page_content="duplicate")],
- ["shared-id"],
- force_reindex=False,
- )
-
- # No add (already on disk); save still happens (idempotent +
- # touches mtime so the integrity record updates).
- fresh_index.add_documents.assert_not_called()
- fresh_index.save_local.assert_called_once()
- assert stats["added"] == 0
- assert stats["skipped"] == 1
-
- def test_force_reindex_deletes_after_reload(self, tmp_path):
- """force_reindex deletes the matching IDs from the FRESH
- on-disk state (not the caller's stale in-memory state)
- before re-adding.
- """
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock() # stale
-
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {"to-update": MagicMock()}
-
- with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
- svc._merge_and_persist_locked(
- index_path,
- [LangchainDocument(page_content="updated")],
- ["to-update"],
- force_reindex=True,
- )
-
- # Old copy removed from FRESH state
- fresh_index.delete.assert_called_once_with(["to-update"])
- # New copy added (no dedup under force_reindex)
- fresh_index.add_documents.assert_called_once()
- added_ids = fresh_index.add_documents.call_args[1]["ids"]
- assert added_ids == ["to-update"]
-
- @staticmethod
- def _doc(document_id, collection_id="coll-1"):
- return LangchainDocument(
- page_content="x",
- metadata={
- "document_id": document_id,
- "collection_id": collection_id,
- },
- )
-
- def test_replace_purges_prior_vectors_by_document_id(self, tmp_path):
- """the document's prior chunk vectors are
- identified from the FRESH docstore by metadata['document_id'] under
- the lock — authoritative + self-healing, not a caller snapshot — so
- an edited document doesn't accumulate stale duplicate vectors and
- orphans from a prior crashed/concurrent indexer are also cleaned."""
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock() # stale
-
- # Disk holds two prior chunks of OUR document plus an unrelated
- # other document's chunk that must be left alone.
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {
- "old-1": self._doc("doc-1"),
- "old-2": self._doc("doc-1"),
- "other": self._doc("doc-2"),
- }
-
- with (
- patch.object(mod, "safe_load_faiss", return_value=fresh_index),
- self._patch_ownership_session(mod),
- ):
- svc._merge_and_persist_locked(
- index_path,
- [self._doc("doc-1")],
- ["new-id"],
- force_reindex=False,
- replace_document_id="doc-1",
- replace_collection_id="coll-1",
- )
-
- # Both of doc-1's prior vectors purged; doc-2's untouched.
- purged = set(fresh_index.delete.call_args[0][0])
- assert purged == {"old-1", "old-2"}
- added_ids = fresh_index.add_documents.call_args[1]["ids"]
- assert added_ids == ["new-id"]
-
- def test_replace_keeps_vector_claimed_by_other_document(self, tmp_path):
- """A purge candidate whose DocumentChunk row is owned by a
- DIFFERENT document is a shared chunk (identical text in two
- documents dedups to one row + one vector per collection, with
- the vector's metadata still naming the first indexer). Deleting
- it would silently drop the other document's content from search;
- it must be kept — the same benign orphan pre-purge code left."""
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock()
-
- # Both vectors carry doc-1 metadata and are absent from the new
- # add set, but "shared" now belongs to doc-2 per its chunk row.
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {
- "shared": self._doc("doc-1"),
- "old-only": self._doc("doc-1"),
- }
-
- with (
- patch.object(mod, "safe_load_faiss", return_value=fresh_index),
- self._patch_ownership_session(mod, foreign_ids={"shared"}),
- ):
- svc._merge_and_persist_locked(
- index_path,
- [self._doc("doc-1")],
- ["new-id"],
- force_reindex=False,
- replace_document_id="doc-1",
- replace_collection_id="coll-1",
- )
-
- purged = set(fresh_index.delete.call_args[0][0])
- assert purged == {"old-only"}, (
- "shared vector owned by doc-2 must survive doc-1's re-index"
- )
-
- def test_replace_keeps_vector_whose_text_another_document_contains(
- self, tmp_path
- ):
- """A SELF-owned purge candidate whose chunk text still appears in
- another current collection member must be kept. Ownership alone
- can't prove a vector unused: chunk rows are deduped per
- (chunk_hash, collection) with one mutable source_id owner, so a
- row can name the re-indexed document while another document's
- identical boilerplate still relies on the vector (e.g. rows
- created before repointing existed, or an A→B→A ownership
- ping-pong). Pre-fix this purge silently dropped the other
- document's content from semantic search while it still showed as
- indexed."""
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock()
-
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {
- "shared-text": self._doc("doc-1"),
- "old-only": self._doc("doc-1"),
- }
-
- captured = {}
-
- def fake_survivors(candidates, collection_id, exclude_document_id):
- captured["candidates"] = candidates
- captured["collection_id"] = collection_id
- captured["exclude_document_id"] = exclude_document_id
- return {"shared-text"}
-
- with (
- patch.object(mod, "safe_load_faiss", return_value=fresh_index),
- self._patch_ownership_session(mod),
- patch.object(
- svc, "_shared_text_survivors", side_effect=fake_survivors
- ),
- ):
- svc._merge_and_persist_locked(
- index_path,
- [self._doc("doc-1")],
- ["new-id"],
- force_reindex=False,
- replace_document_id="doc-1",
- replace_collection_id="coll-1",
- )
-
- purged = set(fresh_index.delete.call_args[0][0])
- assert purged == {"old-only"}, (
- "vector whose text another document still contains must survive"
- )
- # The check received the candidates WITH their chunk texts and the
- # right scoping.
- assert dict(captured["candidates"])["shared-text"] == "x"
- assert captured["collection_id"] == "coll-1"
- assert captured["exclude_document_id"] == "doc-1"
-
- def test_shared_text_survivors_checks_collection_members(self):
- """_shared_text_survivors against a real DB: a candidate whose
- chunk text appears verbatim in another current member of the
- collection survives; text nobody else contains does not; other
- collections' documents don't count."""
- from contextlib import contextmanager
-
- from sqlalchemy import create_engine
- from sqlalchemy.orm import sessionmaker
-
- from local_deep_research.database.models.base import Base
- from local_deep_research.database.models.library import (
- Collection,
- Document,
- DocumentCollection,
- SourceType,
- )
-
- mod = _import_module()
- engine = create_engine("sqlite:///:memory:")
- Base.metadata.create_all(engine)
- session = sessionmaker(bind=engine)()
-
- st = SourceType(id="st-note", name="note", display_name="Note")
- session.add(st)
- session.flush()
- coll = Collection(
- id="coll-1", name="C", collection_type="user_collection"
- )
- other_coll = Collection(
- id="coll-2", name="D", collection_type="user_collection"
- )
- session.add_all([coll, other_coll])
-
- def _doc_row(doc_id, text):
- return Document(
- id=doc_id,
- title=doc_id,
- text_content=text,
- file_type="note",
- file_size=len(text),
- document_hash=f"hash-{doc_id}",
- source_type_id=st.id,
- )
-
- session.add_all(
- [
- _doc_row("doc-a", "the reindexed document"),
- _doc_row("doc-b", "intro SHARED BOILERPLATE outro"),
- _doc_row("doc-c", "elsewhere SHARED BOILERPLATE"),
- ]
- )
- session.add_all(
- [
- DocumentCollection(document_id="doc-a", collection_id="coll-1"),
- DocumentCollection(document_id="doc-b", collection_id="coll-1"),
- # doc-c holds the text but in ANOTHER collection.
- DocumentCollection(document_id="doc-c", collection_id="coll-2"),
- ]
- )
- session.commit()
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield session
-
- svc = _make_service()
- with patch.object(mod, "get_user_db_session", fake_session):
- survivors = svc._shared_text_survivors(
- [
- ("f-shared", "SHARED BOILERPLATE"),
- ("f-unique", "text nobody else has"),
- ("f-empty", None),
- ],
- "coll-1",
- "doc-a",
- )
-
- assert survivors == {"f-shared"}
-
- def test_shared_text_survivors_reads_each_member_once(self):
- """Batched scan: every OTHER member's text_content is read exactly
- once (one decrypt), not once per candidate. Pre-fix this issued
- one full-collection instr() query PER candidate."""
- from contextlib import contextmanager
-
- mod = _import_module()
- svc = _make_service()
-
- # Two members; the survivor query streams their texts via yield_per.
- session = MagicMock()
- yield_calls = {"n": 0}
-
- def _yield_per(_n):
- yield_calls["n"] += 1
- return iter([("alpha SHARED beta",), ("gamma delta",)])
-
- (
- session.query.return_value.join.return_value.filter.return_value.yield_per
- ).side_effect = _yield_per
-
- @contextmanager
- def fake_session(*args, **kwargs):
- yield session
-
- with patch.object(mod, "get_user_db_session", fake_session):
- survivors = svc._shared_text_survivors(
- [("f1", "SHARED"), ("f2", "absent"), ("f3", "delta")],
- "coll-1",
- "doc-a",
- )
-
- assert survivors == {"f1", "f3"}
- # The member stream is consumed once, not per candidate.
- assert yield_calls["n"] == 1
-
- def test_shared_text_survivors_caps_candidate_count(self):
- """Past the candidate cap the check keeps everything (safe: never
- drops a live doc's vector) without scanning — bounding the
- worst-case cost on the deletion path for pathologically large
- documents."""
- mod = _import_module()
- svc = _make_service()
- cap = svc._MAX_SHARED_TEXT_CANDIDATES
-
- # No DB session should be opened past the cap.
- def _boom(*args, **kwargs):
- raise AssertionError("must not open a session past the cap")
-
- candidates = [(f"f{i}", f"text-{i}") for i in range(cap + 1)]
- with patch.object(mod, "get_user_db_session", _boom):
- survivors = svc._shared_text_survivors(
- candidates, "coll-1", "doc-a"
- )
-
- # Everything kept (nothing purged) — the ghost-hit filter covers it.
- assert survivors == {fid for fid, _ in candidates}
-
- def test_replace_keeps_an_id_being_readded(self, tmp_path):
- """A prior vector whose id is ALSO in the new add set (an unchanged
- chunk reusing its row) must not be purged."""
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock()
-
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {
- "shared": self._doc("doc-1"),
- "old-only": self._doc("doc-1"),
- }
-
- with (
- patch.object(mod, "safe_load_faiss", return_value=fresh_index),
- self._patch_ownership_session(mod),
- ):
- svc._merge_and_persist_locked(
- index_path,
- [self._doc("doc-1")],
- ["shared"],
- force_reindex=False,
- replace_document_id="doc-1",
- replace_collection_id="coll-1",
- )
-
- # Only the truly-stale id is purged; "shared" survives.
- fresh_index.delete.assert_called_once_with(["old-only"])
-
- def test_replace_noop_when_document_id_not_passed(self, tmp_path):
- """Without replace_document_id (first-time index) nothing is purged."""
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
- svc.faiss_index = MagicMock()
-
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {"a": self._doc("doc-1")}
-
- with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
- svc._merge_and_persist_locked(
- index_path,
- [self._doc("doc-1")],
- ["new"],
- force_reindex=False,
- )
-
- fresh_index.delete.assert_not_called()
-
- def test_reload_failure_falls_back_to_in_memory(self, tmp_path):
- """If the loader raises (torn write, partial pickle),
- the merge helper keeps the caller's in-memory state instead
- of losing the write entirely.
- """
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=42)
-
- in_memory = MagicMock()
- in_memory.docstore._dict = {}
- svc.faiss_index = in_memory
-
- with patch.object(
- mod, "safe_load_faiss", side_effect=RuntimeError("torn pickle")
- ):
- svc._merge_and_persist_locked(
- index_path,
- [LangchainDocument(page_content="kept")],
- ["kept-id"],
- force_reindex=False,
- )
-
- # Reload failed → kept the in-memory object, added to it,
- # saved it. The write is preserved.
- assert svc.faiss_index is in_memory
- in_memory.add_documents.assert_called_once()
- in_memory.save_local.assert_called_once()
-
- def test_concurrent_writers_both_chunks_survive(self, tmp_path):
- """End-to-end regression: two workers each call
- ``_merge_and_persist_locked`` for the same on-disk index.
- Each starts from a stale in-memory snapshot. After both
- complete, the on-disk state must contain BOTH chunks.
-
- Before the read-modify-write fix, this was last-writer-wins:
- worker A's chunk was overwritten by worker B's save because
- B never reloaded A's write.
- """
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "shared.faiss"
- index_path.touch()
-
- # Single shared "disk state" as a dict — proxies for what
- # would be on disk via FAISS.load_local/save_local.
- disk_state: dict = {}
- disk_lock = threading.Lock()
-
- def make_index_proxy():
- """Each call returns a FAISS-like proxy reading/writing
- the shared disk_state. Mimics a fresh load_local()."""
- ix = MagicMock()
- # Snapshot disk_state at load time (proxy for what
- # FAISS.load_local would return).
- snapshot = dict(disk_state)
- ix.docstore = MagicMock()
- ix.docstore._dict = snapshot
-
- def add(chunks, ids):
- for cid in ids:
- snapshot[cid] = "doc"
-
- def save(_folder, index_name=None):
- # Atomically replace disk_state with this index's
- # current snapshot — mirrors save_local's truncating
- # semantics for the test.
- with disk_lock:
- disk_state.clear()
- disk_state.update(snapshot)
-
- ix.add_documents.side_effect = add
- ix.save_local.side_effect = save
- return ix
-
- def worker(cid: str, start_event: threading.Event):
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- svc.rag_index_record = MagicMock(id=99)
- # Pre-merge in-memory state is stale (empty)
- svc.faiss_index = MagicMock()
- svc.faiss_index.docstore = MagicMock()
- svc.faiss_index.docstore._dict = {}
- start_event.wait() # Race start
- svc._merge_and_persist_locked(
- index_path,
- [LangchainDocument(page_content=f"chunk-{cid}")],
- [cid],
- force_reindex=False,
- )
-
- go = threading.Event()
- t1 = threading.Thread(target=worker, args=("A", go))
- t2 = threading.Thread(target=worker, args=("B", go))
-
- # Patch safe_load_faiss ONCE, around both threads. Patching
- # inside each worker (the original shape) is a hidden race:
- # ``patch.object`` rewrites a module attribute and is not
- # thread-safe — when the first worker's
- # ``with patch.object(...)`` block exits, it restores whatever
- # it captured as "the original" at entry, which can be the
- # second worker's lambda OR the real ``safe_load_faiss``
- # (depending on which thread entered patch first). If the real
- # ``safe_load_faiss`` becomes active mid-test, the second worker's
- # reload step raises on the empty touched ``shared.faiss``,
- # the production code's ``except`` branch falls back to the
- # caller's stale in-memory MagicMock, and the worker's save is
- # a no-op (the setup MagicMock has no ``save_local`` side
- # effect). Result: that worker's chunk never reaches
- # ``disk_state``, the assertion fails, and the test wrongly
- # blames a regression in the production lock. Applying the
- # patch around both threads removes the race entirely — the
- # patched value is the only value visible while either worker
- # runs.
- with patch.object(
- mod,
- "safe_load_faiss",
- side_effect=lambda *a, **kw: make_index_proxy(),
- ):
- t1.start()
- t2.start()
- go.set()
- t1.join(timeout=5.0)
- t2.join(timeout=5.0)
-
- # Both writers' chunks present — read-modify-write under the
- # lock did its job. Without the fix, only one of {A, B} would
- # remain.
- assert "A" in disk_state, (
- f"Worker A's chunk lost; disk_state={disk_state}. "
- f"Read-modify-write race regressed."
- )
- assert "B" in disk_state, (
- f"Worker B's chunk lost; disk_state={disk_state}. "
- f"Read-modify-write race regressed."
- )
-
-
class TestPurgeDocumentVectors:
"""purge_document_vectors: FAISS-side cleanup for deleted documents
(note deletion). Replace-on-reindex can never fire for a deleted id,
@@ -2178,45 +976,6 @@ class TestPurgeDocumentVectors:
with self._make_session_patch(mod, rag_row):
assert svc.purge_document_vectors("doc-1", "coll-1") == 0
- def test_purges_deleted_documents_vectors_and_saves(self, tmp_path):
- self._reset_locks()
- mod = _import_module()
- index_path = tmp_path / "idx.faiss"
- index_path.touch()
-
- svc = _make_service()
- svc.embedding_manager = MagicMock()
- svc.integrity_manager = MagicMock()
- svc.integrity_manager.verify_file.return_value = (True, None)
- rag_row = MagicMock(id=7, index_hash="deadbeef")
- svc._get_index_path = MagicMock(return_value=index_path)
-
- def _doc(document_id):
- d = MagicMock()
- d.metadata = {"document_id": document_id, "collection_id": "coll-1"}
- return d
-
- fresh_index = MagicMock()
- fresh_index.docstore._dict = {
- "note-vec-1": _doc("note-1"),
- "note-vec-2": _doc("note-1"),
- "other-vec": _doc("doc-2"),
- }
-
- with (
- self._make_session_patch(mod, rag_row),
- patch.object(mod, "safe_load_faiss", return_value=fresh_index),
- ):
- purged = svc.purge_document_vectors("note-1", "coll-1")
-
- assert purged == 2
- assert set(fresh_index.delete.call_args[0][0]) == {
- "note-vec-1",
- "note-vec-2",
- }
- # The purge must persist — an in-memory-only delete evaporates.
- fresh_index.save_local.assert_called_once()
-
def test_unverified_index_skips_purge(self, tmp_path):
"""An index failing integrity verification has nothing safely
purgeable; quarantine/rebuild decisions belong to indexing paths."""
@@ -2235,6 +994,53 @@ class TestPurgeDocumentVectors:
assert svc.purge_document_vectors("note-1", "coll-1") == 0
+class TestLazyEmbeddings:
+ """_LazyEmbeddings defers the (expensive) embedding-backend construction
+ until embed_* is actually called, so the delete/purge path — which never
+ embeds — pays nothing for the model load."""
+
+ def test_construction_does_not_touch_manager_embeddings(self):
+ """Building the proxy must NOT access ``manager.embeddings`` (the lazy
+ property that loads a SentenceTransformer / opens Ollama clients)."""
+ mod = _import_module()
+
+ class _Boom:
+ @property
+ def embeddings(self):
+ raise AssertionError(
+ "manager.embeddings accessed at construction — the model "
+ "would load on a delete-only path"
+ )
+
+ # Constructing the proxy must not raise: it never touches .embeddings.
+ proxy = mod._LazyEmbeddings(_Boom())
+ assert proxy is not None
+
+ def test_embed_calls_delegate_to_real_backend(self):
+ mod = _import_module()
+ backend = MagicMock()
+ backend.embed_documents.return_value = [[0.1, 0.2]]
+ backend.embed_query.return_value = [0.3, 0.4]
+
+ accessed = {"count": 0}
+
+ class _Manager:
+ @property
+ def embeddings(self):
+ accessed["count"] += 1
+ return backend
+
+ proxy = mod._LazyEmbeddings(_Manager())
+ # Still nothing accessed until we actually embed.
+ assert accessed["count"] == 0
+
+ assert proxy.embed_documents(["a"]) == [[0.1, 0.2]]
+ assert proxy.embed_query("q") == [0.3, 0.4]
+ backend.embed_documents.assert_called_once_with(["a"])
+ backend.embed_query.assert_called_once_with("q")
+ assert accessed["count"] == 2
+
+
# =========================================================================
# _migrate_legacy_index_files (pre-per-user-scoping upgrade migration)
# =========================================================================
@@ -2270,10 +1076,12 @@ class TestMigrateLegacyIndexFiles:
rag_index = MagicMock(id=3, index_hash="hash1")
svc._migrate_legacy_index_files(legacy, index_path, rag_index)
- # Files relocated (moved, not copied) into the per-user dir.
+ # The .faiss is relocated (moved) into the per-user dir...
assert index_path.read_bytes() == b"faiss-bytes"
- assert index_path.with_suffix(".pkl").read_bytes() == b"pkl-bytes"
assert not legacy.exists()
+ # ...but the legacy plaintext .pkl is DELETED, not relocated (the new
+ # store writes no .pkl; moving it would just carry plaintext along).
+ assert not index_path.with_suffix(".pkl").exists()
assert not (legacy_root / "hash1.pkl").exists()
# DB row repointed + integrity record refreshed for the new path.
assert db_row.index_path == str(index_path)
@@ -2419,3 +1227,212 @@ class TestResetIndexStateForRebuild:
status_q.filter_by.return_value.delete.assert_not_called()
dc_q.filter_by.return_value.update.assert_not_called()
session.commit.assert_not_called()
+
+
+# =========================================================================
+# _preflight_index_path — missing-file self-heal must not wipe healthy state
+# =========================================================================
+class TestPreflightSelfHeal:
+ """When the new per-user index path is absent, the self-heal reset must fire
+ ONLY when the bytes are genuinely gone — not when a transient one-time
+ legacy-path migration failed and the bytes still sit at the stored path
+ (which would wipe a healthy collection's indexed state, even on a search)."""
+
+ def _rag_index(self, legacy):
+ return MagicMock(
+ index_hash="hash",
+ index_path=str(legacy),
+ chunk_count=5,
+ total_documents=1,
+ )
+
+ def test_no_reset_when_legacy_bytes_survive(self, tmp_path):
+ svc = _make_service()
+ new_path = tmp_path / "user" / "hash.faiss" # migration target, absent
+ legacy = tmp_path / "hash.faiss"
+ legacy.write_bytes(b"legacy-faiss") # bytes survive at the old path
+ svc._get_index_path = MagicMock(return_value=new_path)
+ # Simulate a transient relocation failure: no-op, legacy stays put.
+ svc._migrate_legacy_index_files = MagicMock()
+ svc._reset_index_state_for_rebuild = MagicMock()
+
+ # Read path (reset_stale_state=False) — must NOT reset.
+ svc._preflight_index_path(
+ "col-1", self._rag_index(legacy), reset_stale_state=False
+ )
+ svc._reset_index_state_for_rebuild.assert_not_called()
+
+ def test_resets_when_index_gone_at_both_locations(self, tmp_path):
+ svc = _make_service()
+ new_path = tmp_path / "user" / "hash.faiss" # absent
+ legacy = tmp_path / "hash.faiss" # ALSO absent (genuinely gone)
+ svc._get_index_path = MagicMock(return_value=new_path)
+ svc._migrate_legacy_index_files = MagicMock()
+ svc._reset_index_state_for_rebuild = MagicMock()
+
+ svc._preflight_index_path(
+ "col-1", self._rag_index(legacy), reset_stale_state=False
+ )
+ svc._reset_index_state_for_rebuild.assert_called_once()
+
+
+# =========================================================================
+# _preflight_index_path — embedding-dimension-mismatch rebuild (7d9930e84
+# regression family: a reintroduced partial reset must not resurface)
+# =========================================================================
+class TestPreflightDimensionMismatch:
+ """When the stored ``embedding_dimension`` differs from what the current
+ embedding model returns, the write path must delete the stale index AND
+ fully reset DB state via ``_reset_index_state_for_rebuild`` (not just bump
+ the dimension) — a partial reset leaves DocumentCollection.indexed=True,
+ so index_document/index_collection skip everything and search returns []
+ forever while get_rag_stats still reports 100% indexed.
+ """
+
+ def _make_present_index(self, tmp_path, stored_dim=384):
+ index_path = tmp_path / "hash.faiss"
+ index_path.write_bytes(b"faiss-bytes")
+ rag_index = MagicMock(
+ id=42,
+ index_hash="hash",
+ index_path=str(index_path),
+ embedding_dimension=stored_dim,
+ chunk_count=5,
+ total_documents=1,
+ )
+ return index_path, rag_index
+
+ @patch(f"{_MOD}.get_user_db_session")
+ def test_preflight_dimension_mismatch_rebuilds_and_updates_dimension_on_write_path(
+ self, mock_session_ctx, tmp_path
+ ):
+ svc = _make_service()
+ svc._get_index_path = MagicMock(return_value=tmp_path / "hash.faiss")
+ index_path, rag_index = self._make_present_index(
+ tmp_path, stored_dim=384
+ )
+
+ svc.integrity_manager.verify_file.return_value = (True, None)
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager.embeddings.embed_query.return_value = [0.1] * 768
+
+ session = MagicMock()
+ mock_session_ctx.return_value.__enter__.return_value = session
+ db_row = MagicMock(embedding_dimension=384)
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ db_row
+ )
+
+ svc._reset_index_state_for_rebuild = MagicMock()
+
+ svc._preflight_index_path("col-1", rag_index, reset_stale_state=True)
+
+ # Old bytes are gone.
+ assert not index_path.exists()
+ # DB-side dimension bumped to the current model dim.
+ assert db_row.embedding_dimension == 768
+ session.commit.assert_called()
+ # Full state reset (not a hand-rolled partial one) fires. Note: since
+ # unlink() actually removes the file, the immediately-following
+ # missing-file self-heal block (index_path no longer exists) also
+ # sees the passed-in rag_index's stale in-memory chunk_count/
+ # total_documents (this mock isn't refreshed from the DB) and fires a
+ # SECOND, harmless, idempotent reset call — a real DB-backed
+ # RAGIndex row would already read back as zeroed by then, making
+ # that second call a no-op. We assert it fired at least once with
+ # the right args rather than pin the exact count.
+ svc._reset_index_state_for_rebuild.assert_any_call("col-1", rag_index)
+ # In-memory record reflects the new dimension too.
+ assert rag_index.embedding_dimension == 768
+
+ @patch(f"{_MOD}.get_user_db_session")
+ def test_preflight_dimension_mismatch_read_path_raises_without_mutating_state(
+ self, mock_session_ctx, tmp_path
+ ):
+ svc = _make_service()
+ svc._get_index_path = MagicMock(return_value=tmp_path / "hash.faiss")
+ index_path, rag_index = self._make_present_index(
+ tmp_path, stored_dim=384
+ )
+
+ svc.integrity_manager.verify_file.return_value = (True, None)
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager.embeddings.embed_query.return_value = [0.1] * 768
+
+ svc._reset_index_state_for_rebuild = MagicMock()
+
+ with pytest.raises(RuntimeError, match="dimension mismatch"):
+ svc._preflight_index_path(
+ "col-1", rag_index, reset_stale_state=False
+ )
+
+ # A read must not destroy a healthy collection.
+ assert index_path.exists()
+ assert rag_index.embedding_dimension == 384
+ mock_session_ctx.assert_not_called()
+ svc._reset_index_state_for_rebuild.assert_not_called()
+
+ @patch(f"{_MOD}.get_user_db_session")
+ def test_preflight_embed_provider_failure_propagates_without_quarantine_or_rebuild(
+ self, mock_session_ctx, tmp_path
+ ):
+ svc = _make_service()
+ svc._get_index_path = MagicMock(return_value=tmp_path / "hash.faiss")
+ index_path, rag_index = self._make_present_index(
+ tmp_path, stored_dim=384
+ )
+
+ svc.integrity_manager.verify_file.return_value = (True, None)
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager.embeddings.embed_query.side_effect = RuntimeError(
+ "connection refused"
+ )
+
+ svc._reset_index_state_for_rebuild = MagicMock()
+
+ with pytest.raises(RuntimeError, match="connection refused"):
+ svc._preflight_index_path(
+ "col-1", rag_index, reset_stale_state=True
+ )
+
+ # The probe failure must NOT be mistaken for a dimension mismatch:
+ # no unlink, no DB dimension bump, no state reset.
+ assert index_path.exists()
+ assert rag_index.embedding_dimension == 384
+ mock_session_ctx.assert_not_called()
+ svc._reset_index_state_for_rebuild.assert_not_called()
+
+ @patch(f"{_MOD}.get_user_db_session")
+ def test_preflight_dimension_mismatch_continues_rebuild_when_unlink_fails(
+ self, mock_session_ctx, tmp_path
+ ):
+ svc = _make_service()
+ svc._get_index_path = MagicMock(return_value=tmp_path / "hash.faiss")
+ index_path, rag_index = self._make_present_index(
+ tmp_path, stored_dim=384
+ )
+
+ svc.integrity_manager.verify_file.return_value = (True, None)
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager.embeddings.embed_query.return_value = [0.1] * 768
+
+ session = MagicMock()
+ mock_session_ctx.return_value.__enter__.return_value = session
+ db_row = MagicMock(embedding_dimension=384)
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ db_row
+ )
+
+ svc._reset_index_state_for_rebuild = MagicMock()
+
+ with patch.object(Path, "unlink", side_effect=OSError("disk full")):
+ svc._preflight_index_path(
+ "col-1", rag_index, reset_stale_state=True
+ )
+
+ # The swallowed unlink failure must not abort the DB-side reset.
+ assert db_row.embedding_dimension == 768
+ svc._reset_index_state_for_rebuild.assert_called_once_with(
+ "col-1", rag_index
+ )
+ assert rag_index.embedding_dimension == 768
diff --git a/tests/research_library/services/test_library_rag_service_deep_coverage.py b/tests/research_library/services/test_library_rag_service_deep_coverage.py
index 56e8aa50bf..1a556f74e6 100644
--- a/tests/research_library/services/test_library_rag_service_deep_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_deep_coverage.py
@@ -6,7 +6,6 @@ Targets ~146 missing statements not covered by existing test files:
- remove_document_from_rag (success, not-in-collection error, exception path)
- index_documents_batch (not found, already indexed skip, no text, batch exception)
- get_rag_stats (default collection id, with collection, chunk_sample present/absent)
-- remove_collection_from_index (no chunks, has chunks success, faiss delete exception, outer exception)
- close (idempotent second call, clears resources)
- index_document exception path (embedding fails mid-way)
"""
@@ -53,10 +52,8 @@ class TestClose:
def test_close_clears_embedding_manager(self):
svc = _make_service()
svc.embedding_manager = MagicMock()
- svc.faiss_index = MagicMock()
svc.close()
assert svc.embedding_manager is None
- assert svc.faiss_index is None
assert svc.rag_index_record is None
assert svc.integrity_manager is None
assert svc.text_splitter is None
@@ -71,7 +68,6 @@ class TestClose:
def test_close_with_none_resources_does_not_raise(self):
svc = _make_service()
svc.embedding_manager = None
- svc.faiss_index = None
svc.close() # Should not raise
@@ -276,6 +272,54 @@ class TestRemoveDocumentFromRag:
assert mock_doc_collection.indexed is False
assert mock_doc_collection.chunk_count == 0
+ @patch(f"{_MOD}.get_user_db_session")
+ def test_deleted_count_sums_vector_removal_and_backstop(
+ self, mock_session_ctx
+ ):
+ """FIX A (commit daa5e2ebb): deleted_count must be the SUM of the
+ vectors removed by ``remove_documents_from_index`` (rows the FAISS
+ delete already committed) and the disjoint backstop DB sweep from
+ ``embedding_manager._delete_chunks_from_db`` -- not just one or the
+ other. Every pre-existing success-path test mocks (or leaves
+ unmocked-and-swallowed) ``remove_documents_from_index`` so it
+ contributes 0, which can't distinguish the sum from the backstop
+ alone. Here both terms are nonzero and disjoint (4 + 2 = 6) so a
+ revert back to backstop-only (=2) or vectors-only (=4) fails.
+ """
+ svc = _make_service()
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager._delete_chunks_from_db.return_value = 2
+ svc.remove_documents_from_index = MagicMock(return_value=4)
+
+ mock_session = MagicMock()
+ mock_session_ctx.return_value = _make_session_ctx(mock_session)
+
+ mock_doc_collection = MagicMock()
+ mock_collection = MagicMock()
+
+ def query_side_effect(model):
+ q = MagicMock()
+ model_name = getattr(model, "__name__", str(model))
+ if "DocumentCollection" in model_name:
+ q.filter_by.return_value.first.return_value = (
+ mock_doc_collection
+ )
+ elif "Collection" in model_name:
+ q.filter_by.return_value.first.return_value = mock_collection
+ return q
+
+ mock_session.query = MagicMock(side_effect=query_side_effect)
+
+ result = svc.remove_document_from_rag("doc-1", "coll-1")
+
+ svc.remove_documents_from_index.assert_called_once_with(
+ ["doc-1"], "coll-1"
+ )
+ assert result["status"] == "success"
+ assert result["deleted_count"] == 6
+ assert mock_doc_collection.indexed is False
+ assert mock_doc_collection.chunk_count == 0
+
@patch(f"{_MOD}.get_user_db_session")
def test_exception_returns_error(self, mock_session_ctx):
svc = _make_service()
@@ -355,6 +399,10 @@ class TestIndexDocumentsBatch:
@patch(f"{_MOD}.get_user_db_session")
def test_no_text_content_in_batch(self, mock_session_ctx):
+ # Empty text_content is now ROUTED to index_document (which purges any
+ # prior chunks on clear) instead of short-circuited at the batch level,
+ # so stale content can't linger via the bulk path. index_document still
+ # reports "error" when there were no prior chunks to purge.
svc = _make_service()
mock_session = MagicMock()
mock_session_ctx.return_value = _make_session_ctx(mock_session)
@@ -371,8 +419,15 @@ class TestIndexDocumentsBatch:
[mock_doc],
[mock_dc],
]
+ svc.index_document = MagicMock(
+ return_value={
+ "status": "error",
+ "error": "Document has no text content",
+ }
+ )
result = svc.index_documents_batch([("doc-2", "Title")], "coll-1")
+ svc.index_document.assert_called_once_with("doc-2", "coll-1", False)
assert result["doc-2"]["status"] == "error"
assert "no text content" in result["doc-2"]["error"]
@@ -503,118 +558,6 @@ class TestGetRagStats:
assert result["embedding_info"]["model_type"] is None
-# =========================================================================
-# remove_collection_from_index
-# =========================================================================
-# The method re-imports get_user_db_session locally, so we must patch the
-# source module (session_context) rather than the service module attribute.
-_SESSION_CTX_PATH = (
- "local_deep_research.database.session_context.get_user_db_session"
-)
-
-
-class TestRemoveCollectionFromIndex:
- @patch(_SESSION_CTX_PATH)
- def test_no_chunks_returns_success_zero(self, mock_session_ctx):
- svc = _make_service()
- mock_session = MagicMock()
- mock_session_ctx.return_value = _make_session_ctx(mock_session)
- mock_session.query.return_value.filter_by.return_value.all.return_value = []
-
- result = svc.remove_collection_from_index("collection_xyz")
- assert result["status"] == "success"
- assert result["deleted_count"] == 0
-
- @patch(_SESSION_CTX_PATH)
- def test_with_chunks_deletes_and_saves(self, mock_session_ctx, tmp_path):
- svc = _make_service()
- svc.integrity_manager = MagicMock()
-
- mock_session = MagicMock()
- mock_session_ctx.return_value = _make_session_ctx(mock_session)
-
- mock_chunk = MagicMock()
- mock_chunk.id = "chunk-1"
- mock_session.query.return_value.filter_by.return_value.all.return_value = [
- mock_chunk
- ]
-
- mock_faiss = MagicMock()
- svc.faiss_index = mock_faiss
-
- mock_record = MagicMock()
- idx_path = tmp_path / "idx.faiss"
- mock_record.index_path = str(idx_path)
- mock_record.id = "rag-rec-1"
- svc.rag_index_record = mock_record
-
- result = svc.remove_collection_from_index("collection_xyz")
- assert result["status"] == "success"
- assert result["deleted_count"] == 1
- mock_faiss.delete.assert_called_once()
- mock_faiss.save_local.assert_called_once()
-
- @patch(_SESSION_CTX_PATH)
- def test_faiss_delete_exception_still_returns_success(
- self, mock_session_ctx, tmp_path
- ):
- svc = _make_service()
- svc.integrity_manager = MagicMock()
-
- mock_session = MagicMock()
- mock_session_ctx.return_value = _make_session_ctx(mock_session)
-
- mock_chunk = MagicMock()
- mock_chunk.id = "chunk-1"
- mock_session.query.return_value.filter_by.return_value.all.return_value = [
- mock_chunk
- ]
-
- mock_faiss = MagicMock()
- mock_faiss.delete.side_effect = RuntimeError("delete failed")
- svc.faiss_index = mock_faiss
- svc.rag_index_record = None
-
- result = svc.remove_collection_from_index("collection_xyz")
- # Delete failed, but overall status should still be success (warning logged)
- assert result["status"] == "success"
- assert result["deleted_count"] == 1
-
- @patch(_SESSION_CTX_PATH)
- def test_outer_exception_returns_error(self, mock_session_ctx):
- svc = _make_service()
- mock_session_ctx.side_effect = RuntimeError("session blew up")
-
- result = svc.remove_collection_from_index("collection_xyz")
- assert result["status"] == "error"
- # The outer except catches the RuntimeError (or any wrapping exception)
- assert "Error" in result["error"]
-
- @patch(_SESSION_CTX_PATH)
- def test_no_faiss_index_loads_one(self, mock_session_ctx):
- svc = _make_service()
- mock_session = MagicMock()
- mock_session_ctx.return_value = _make_session_ctx(mock_session)
-
- mock_chunk = MagicMock()
- mock_chunk.id = "chunk-9"
- mock_session.query.return_value.filter_by.return_value.all.return_value = [
- mock_chunk
- ]
-
- # faiss_index is None → should call load_or_create_faiss_index
- svc.faiss_index = None
- mock_new_faiss = MagicMock()
- svc.load_or_create_faiss_index = MagicMock(return_value=mock_new_faiss)
- svc.rag_index_record = None
-
- result = svc.remove_collection_from_index("collection_abc123")
- svc.load_or_create_faiss_index.assert_called_once_with(
- "abc123", reset_stale_state=True
- )
- assert result["status"] == "success"
-
-
# =========================================================================
# index_document — exception mid-way
# =========================================================================
@@ -679,7 +622,12 @@ class TestIndexDocumentExceptionPath:
mock_document = MagicMock()
mock_document.text_content = None # triggers error after dc creation
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_document
+ # 1st .first() = Document lookup; 2nd = the empty-text branch's
+ # prior-chunk probe -> None (no prior chunks, so error, not purge).
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_document,
+ None,
+ ]
mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)
diff --git a/tests/research_library/services/test_library_rag_service_index_coverage.py b/tests/research_library/services/test_library_rag_service_index_coverage.py
index 5810297cb5..af78f05604 100644
--- a/tests/research_library/services/test_library_rag_service_index_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_index_coverage.py
@@ -10,8 +10,6 @@ Targets uncovered lines in library_rag_service.py:
from unittest.mock import MagicMock, patch
-from langchain_core.documents import Document as LangchainDocument
-
_MOD = "local_deep_research.research_library.services.library_rag_service"
@@ -104,7 +102,12 @@ class TestIndexDocumentNoTextContent:
mock_doc = _make_document(text_content=None)
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc
+ # 1st .first() = Document lookup -> the doc; 2nd = the prior-chunk probe
+ # in the empty-text branch -> None (no prior chunks, so error, not purge).
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_doc,
+ None,
+ ]
mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)
@@ -124,7 +127,12 @@ class TestIndexDocumentNoTextContent:
mock_doc = _make_document(text_content="")
- mock_session.query.return_value.filter_by.return_value.first.return_value = mock_doc
+ # 1st .first() = Document lookup -> the doc; 2nd = the prior-chunk probe
+ # in the empty-text branch -> None (no prior chunks, so error, not purge).
+ mock_session.query.return_value.filter_by.return_value.first.side_effect = [
+ mock_doc,
+ None,
+ ]
mock_ensure.return_value = MagicMock(indexed=False, chunk_count=0)
@@ -174,137 +182,6 @@ class TestIndexDocumentNoTextContent:
assert result["chunk_count"] == 5
-# ---------------------------------------------------------------------------
-# 2. test_index_document_force_reindex
-# ---------------------------------------------------------------------------
-
-
-class TestIndexDocumentForceReindex:
- """force_reindex=True deletes old FAISS chunks before adding new ones."""
-
- @patch(f"{_MOD}.get_user_db_session")
- def test_force_reindex_calls_faiss_delete_for_existing_ids(
- self, mock_session_ctx
- ):
- svc = _make_service()
- mock_session = MagicMock()
- mock_session_ctx.return_value = _make_session_ctx(mock_session)
-
- existing_chunk_id = "old-chunk-id-1"
-
- # Document with text
- mock_doc = _make_document()
- # DocumentCollection already indexed but force_reindex=True bypasses
- mock_dc = _make_doc_collection(indexed=True, chunk_count=3)
- mock_collection = MagicMock()
-
- def query_side(model):
- q = MagicMock()
- name = getattr(model, "__name__", str(model))
- if "Document" == name:
- q.filter_by.return_value.first.return_value = mock_doc
- elif "DocumentCollection" in name:
- q.filter_by.return_value.all.return_value = [mock_dc]
- q.filter_by.return_value.update = MagicMock()
- elif "Collection" == name:
- q.filter_by.return_value.first.return_value = mock_collection
- elif "RAGIndex" in name:
- q.filter_by.return_value.first.return_value = MagicMock()
- elif "RagDocumentStatus" in name:
- q.filter_by.return_value.first.return_value = None
- return q
-
- mock_session.query = MagicMock(side_effect=query_side)
- mock_session.merge = MagicMock()
- mock_session.execute = MagicMock()
-
- # Chunks from text splitter
- mock_chunk = LangchainDocument(page_content="chunk content")
- svc.text_splitter = MagicMock()
- svc.text_splitter.split_documents.return_value = [mock_chunk]
-
- # Embedding manager returns ID that exists in FAISS docstore
- svc.embedding_manager = MagicMock()
- svc.embedding_manager._store_chunks_to_db.return_value = [
- existing_chunk_id
- ]
-
- # Mock FAISS index with the existing chunk in docstore
- mock_faiss = MagicMock()
- mock_faiss.docstore._dict = {existing_chunk_id: MagicMock()}
- svc.faiss_index = mock_faiss
-
- # Mock rag_index_record
- mock_rag_record = MagicMock()
- mock_rag_record.id = "rag-idx-1"
- mock_rag_record.index_path = "/tmp/test_idx.faiss"
- svc.rag_index_record = mock_rag_record
-
- svc.integrity_manager = MagicMock()
-
- result = svc.index_document("doc-1", "coll-1", force_reindex=True)
-
- # FAISS delete should have been called with the old chunk ID
- mock_faiss.delete.assert_called_once_with([existing_chunk_id])
- # Result should be success
- assert result["status"] == "success"
-
- @patch(f"{_MOD}.get_user_db_session")
- def test_force_reindex_no_existing_ids_skips_delete(self, mock_session_ctx):
- """If there are no matching chunk IDs in FAISS, delete is never called."""
- svc = _make_service()
- mock_session = MagicMock()
- mock_session_ctx.return_value = _make_session_ctx(mock_session)
-
- mock_doc = _make_document()
- mock_dc = _make_doc_collection(indexed=False)
- mock_collection = MagicMock()
-
- def query_side(model):
- q = MagicMock()
- name = getattr(model, "__name__", str(model))
- if "Document" == name:
- q.filter_by.return_value.first.return_value = mock_doc
- elif "DocumentCollection" in name:
- q.filter_by.return_value.all.return_value = [mock_dc]
- q.filter_by.return_value.update = MagicMock()
- elif "Collection" == name:
- q.filter_by.return_value.first.return_value = mock_collection
- elif "RAGIndex" in name:
- q.filter_by.return_value.first.return_value = MagicMock()
- elif "RagDocumentStatus" in name:
- q.filter_by.return_value.first.return_value = None
- return q
-
- mock_session.query = MagicMock(side_effect=query_side)
- mock_session.merge = MagicMock()
- mock_session.execute = MagicMock()
-
- mock_chunk = LangchainDocument(page_content="chunk")
- svc.text_splitter = MagicMock()
- svc.text_splitter.split_documents.return_value = [mock_chunk]
-
- svc.embedding_manager = MagicMock()
- svc.embedding_manager._store_chunks_to_db.return_value = ["new-id-1"]
-
- # FAISS docstore does NOT contain "new-id-1"
- mock_faiss = MagicMock()
- mock_faiss.docstore._dict = {}
- svc.faiss_index = mock_faiss
-
- mock_rag_record = MagicMock()
- mock_rag_record.id = "rag-idx-2"
- mock_rag_record.index_path = "/tmp/idx2.faiss"
- svc.rag_index_record = mock_rag_record
- svc.integrity_manager = MagicMock()
-
- result = svc.index_document("doc-1", "coll-1", force_reindex=True)
-
- # No existing IDs matched → delete not called
- mock_faiss.delete.assert_not_called()
- assert result["status"] == "success"
-
-
# ---------------------------------------------------------------------------
# 3. test_index_documents_batch
# ---------------------------------------------------------------------------
@@ -353,10 +230,13 @@ class TestIndexDocumentsBatch:
assert result["doc-skip"]["chunk_count"] == 4
@patch(f"{_MOD}.get_user_db_session")
- def test_document_without_text_content_returns_error(
+ def test_document_without_text_content_delegates_to_index_document(
self, mock_session_ctx
):
- """Document with no text_content → error in batch result."""
+ """Empty text_content is ROUTED to index_document (which purges prior
+ chunks on clear), not short-circuited with a batch-level error — so the
+ bulk path can't leave a cleared document's stale content searchable.
+ index_document still returns "error" when there were no prior chunks."""
svc = _make_service()
mock_session = MagicMock()
mock_session_ctx.return_value = _make_session_ctx(mock_session)
@@ -368,9 +248,18 @@ class TestIndexDocumentsBatch:
[mock_doc],
[mock_dc],
]
+ svc.index_document = MagicMock(
+ return_value={
+ "status": "error",
+ "error": "Document has no text content",
+ }
+ )
result = svc.index_documents_batch([("doc-notext", "Title")], "coll-1")
+ svc.index_document.assert_called_once_with(
+ "doc-notext", "coll-1", False
+ )
assert result["doc-notext"]["status"] == "error"
assert "no text content" in result["doc-notext"]["error"]
@@ -484,12 +373,13 @@ class TestIndexDocumentsBatch:
[dc_a, dc_b], # DocumentCollection query
]
+ # doc-b (empty text) is now routed to index_document too, which purges
+ # any prior chunks and reports 'cleared' — no longer a batch-level error.
svc.index_document = MagicMock(
- return_value={
- "status": "success",
- "chunk_count": 2,
- "embedding_ids": [],
- }
+ side_effect=[
+ {"status": "success", "chunk_count": 2, "embedding_ids": []},
+ {"status": "cleared", "chunk_count": 0},
+ ]
)
result = svc.index_documents_batch(
@@ -498,8 +388,79 @@ class TestIndexDocumentsBatch:
# doc-a: success (has text)
assert result["doc-a"]["status"] == "success"
- # doc-b: error (no text)
- assert result["doc-b"]["status"] == "error"
+ # doc-b: cleared (empty text → prior chunks purged via index_document)
+ assert result["doc-b"]["status"] == "cleared"
+ assert svc.index_document.call_count == 2
+
+ @patch(f"{_MOD}.get_user_db_session")
+ def test_mixed_outcomes_in_single_call(self, mock_session_ctx):
+ """A single 4-doc batch hitting not-found, already-indexed-skip,
+ raises-mid-processing, and success must process ALL four — the
+ per-iteration try/except must let the loop CONTINUE past the doc
+ that raises so a bulk "Index All" never aborts mid-list — and the
+ returned summary must bucket each outcome correctly."""
+ svc = _make_service()
+ mock_session = MagicMock()
+ mock_session_ctx.return_value = _make_session_ctx(mock_session)
+
+ # doc-notfound is NOT in doc_lookup: it never appears in the first
+ # (Document) query result, so its DocumentCollection is irrelevant.
+ doc_skip = _make_document(doc_id="doc-skip")
+ doc_raise = _make_document(doc_id="doc-raise")
+ doc_ok = _make_document(doc_id="doc-ok")
+
+ dc_skip = _make_doc_collection(
+ doc_id="doc-skip", indexed=True, chunk_count=9
+ )
+ dc_raise = _make_doc_collection(doc_id="doc-raise", indexed=False)
+ dc_ok = _make_doc_collection(doc_id="doc-ok", indexed=False)
+
+ mock_session.query.return_value.filter.return_value.all.side_effect = [
+ [doc_skip, doc_raise, doc_ok], # Document.id.in_(...) query
+ [dc_skip, dc_raise, dc_ok], # DocumentCollection query
+ ]
+
+ # Only doc-raise and doc-ok reach self.index_document (doc-notfound
+ # is filtered out before the call; doc-skip is short-circuited by the
+ # already-indexed check) — in list order.
+ svc.index_document = MagicMock(
+ side_effect=[
+ RuntimeError("boom mid-batch"),
+ {
+ "status": "success",
+ "chunk_count": 3,
+ "embedding_ids": [],
+ },
+ ]
+ )
+
+ result = svc.index_documents_batch(
+ [
+ ("doc-notfound", "Missing"),
+ ("doc-skip", "Skip Me"),
+ ("doc-raise", "Raises"),
+ ("doc-ok", "Good Doc"),
+ ],
+ "coll-1",
+ )
+
+ assert result["doc-notfound"]["status"] == "error"
+ assert "not found" in result["doc-notfound"]["error"]
+
+ assert result["doc-skip"]["status"] == "skipped"
+ assert result["doc-skip"]["chunk_count"] == 9
+
+ assert result["doc-raise"]["status"] == "error"
+ assert "RuntimeError" in result["doc-raise"]["error"]
+
+ # Processing CONTINUED past the raise: doc-ok still got processed
+ # and its success result is present.
+ assert result["doc-ok"]["status"] == "success"
+ assert result["doc-ok"]["chunk_count"] == 3
+
+ # Only the two non-skipped, found documents actually reached
+ # index_document, and skip/not-found never triggered a call.
+ assert svc.index_document.call_count == 2
# ---------------------------------------------------------------------------
diff --git a/tests/research_library/services/test_library_rag_service_index_failure.py b/tests/research_library/services/test_library_rag_service_index_failure.py
index 6de4f7da92..3ab715fea6 100644
--- a/tests/research_library/services/test_library_rag_service_index_failure.py
+++ b/tests/research_library/services/test_library_rag_service_index_failure.py
@@ -1,19 +1,16 @@
-"""Regression test for #4855: a document whose chunk store persisted zero
+"""Regression test for #4855: a document whose vector store persisted zero
embeddings must not be marked ``indexed=True``.
-``LocalEmbeddingManager._store_chunks_to_db`` appends exactly one id per chunk
-on success (a reused id for a pre-existing chunk, a fresh id for a new one), so
-``len(embedding_ids) == len(chunks)``; it returns ``[]`` only when nothing was
-persisted (it caught an exception, or there was no user context). Before this
-fix ``index_document`` ignored that empty return: it ran the FAISS merge (which
-adds zero vectors), then still set ``DocumentCollection.indexed=True`` and
-returned ``status="success"``. The document was silently unsearchable, and the
-background reconciler (which retries only ``indexed.is_(False)`` rows) never
-picked it up again.
-
-Invariant: a document flagged ``indexed=True`` has had its embeddings
-persisted. A failed store must leave it ``indexed=False`` so the reconciler
-retries it.
+Invariant: a document flagged ``indexed=True`` has had its embeddings persisted
+and is searchable. When the store fails to persist (its exception path),
+``index_document`` must leave the row ``indexed=False`` so the background
+reconciler — which only revisits ``indexed.is_(False)`` rows — picks it up and
+re-embeds. Under the int-id vector store the persist runs ``store.apply()``
+(durably mutating the FAISS file) BEFORE the DB commit, so the failure path
+explicitly flags ``indexed=False`` and commits that flag
+(``_flag_document_for_reindex``) rather than relying on an early return — which
+is why this test asserts the row is flagged for retry, not that no commit at
+all occurs.
"""
from unittest.mock import MagicMock, patch
@@ -70,9 +67,10 @@ def _make_doc(text="Long text content for indexing test."):
def test_index_document_not_marked_indexed_when_store_persists_no_embeddings(
mock_get_session, mock_ensure
):
- """The chunk store yields a real chunk set but returns no embedding ids
- (its exception path). index_document must report an error, must not
- commit, and must never flip DocumentCollection.indexed to True."""
+ """A real chunk set is produced but the vector store fails to persist any
+ embeddings. index_document must report an error and must never flip
+ DocumentCollection.indexed to True — it flags the row indexed=False so the
+ reconciler retries it."""
svc = _make_service()
session = MagicMock()
@@ -86,32 +84,39 @@ def test_index_document_not_marked_indexed_when_store_persists_no_embeddings(
svc.text_splitter = MagicMock()
svc.text_splitter.split_documents.return_value = [MagicMock()]
- # ...but the DB store persisted nothing and returned []. The remaining
- # mocks let the *unfixed* code path run all the way to the indexed=True
- # update and a "success" return, so the test proves the guard, not a
- # crash somewhere downstream.
- svc.embedding_manager = MagicMock()
- svc.embedding_manager._store_chunks_to_db.return_value = []
- svc.faiss_index = MagicMock()
svc.rag_index_record = MagicMock()
svc.rag_index_record.index_path = "/tmp/idx-4855"
svc.rag_index_record.id = 1
- svc._merge_and_persist_locked = MagicMock(return_value={"added": 0})
+
+ # ...but the vector store fails to persist it: VectorIndex.index() raises
+ # (its store.apply / embed failure path). index_document must catch that,
+ # roll back, and flag the document indexed=False for retry — NOT mark it
+ # indexed=True. Because the int-id store mutates the FAISS file durably
+ # BEFORE the DB commit, the failure path commits that indexed=False flag
+ # (see _flag_document_for_reindex).
+ vindex = MagicMock()
+ vindex.index.side_effect = RuntimeError("store persisted no embeddings")
+ svc._get_vector_index = MagicMock(return_value=vindex)
result = svc.index_document("doc-1", "coll-1")
assert result["status"] == "error"
- session.commit.assert_not_called()
- indexed_true_updates = [
- c
+ indexed_updates = [
+ c.args[0]
for c in session.mock_calls
if c[0].endswith(".update")
and c.args
and isinstance(c.args[0], dict)
- and c.args[0].get("indexed") is True
+ and "indexed" in c.args[0]
]
- assert indexed_true_updates == [], (
- "index_document set DocumentCollection.indexed=True despite the chunk "
- "store persisting no embeddings"
+ # It flagged the document for retry ...
+ assert indexed_updates, (
+ "index_document neither indexed the document nor flagged it for retry "
+ "after the store persisted no embeddings"
+ )
+ # ... and NEVER marked it indexed=True (the #4855 invariant).
+ assert all(u.get("indexed") is False for u in indexed_updates), (
+ "index_document set DocumentCollection.indexed=True despite the store "
+ "persisting no embeddings"
)
diff --git a/tests/research_library/services/test_library_rag_service_info.py b/tests/research_library/services/test_library_rag_service_info.py
index d2c2e63a82..790840816c 100644
--- a/tests/research_library/services/test_library_rag_service_info.py
+++ b/tests/research_library/services/test_library_rag_service_info.py
@@ -134,14 +134,12 @@ class TestClose:
def test_close_clears_resources(self):
service = _make_service()
# Simulate having resources set
- service.faiss_index = MagicMock()
service.rag_index_record = MagicMock()
service.integrity_manager = MagicMock()
service.close()
assert service.embedding_manager is None
- assert service.faiss_index is None
assert service.rag_index_record is None
assert service.integrity_manager is None
assert service._closed is True
diff --git a/tests/research_library/services/test_library_rag_service_rollback.py b/tests/research_library/services/test_library_rag_service_rollback.py
index 35bc20d034..e44a757019 100644
--- a/tests/research_library/services/test_library_rag_service_rollback.py
+++ b/tests/research_library/services/test_library_rag_service_rollback.py
@@ -132,3 +132,54 @@ def test_remove_document_from_rag_rolls_back_session_on_exception(
assert result["status"] == "error"
session.rollback.assert_called_once()
+
+
+# ---------------------------------------------------------------------------
+# remove_document_from_rag: FAISS pruning is best-effort and must not block
+# the DB cleanup (or turn the overall result into an error).
+# ---------------------------------------------------------------------------
+
+
+@patch(f"{_MOD}.get_user_db_session")
+def test_remove_document_from_rag_faiss_failure_does_not_block_db_cleanup(
+ mock_get_session,
+):
+ """A FAISS pruning failure inside remove_documents_from_index is logged
+ and swallowed. The DB-side cleanup (chunk deletion, DocumentCollection
+ update, RagDocumentStatus row removal, commit) must still happen and the
+ overall status must still be 'success'."""
+ svc = _make_service()
+
+ session = MagicMock()
+ mock_get_session.return_value = _ctx_yielding(session)
+
+ doc_collection = MagicMock(indexed=True, chunk_count=3)
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ doc_collection
+ )
+
+ # The inner FAISS pruning step raises — must be swallowed.
+ svc.remove_documents_from_index = MagicMock(
+ side_effect=RuntimeError("simulated FAISS failure")
+ )
+
+ svc.embedding_manager = MagicMock()
+ svc.embedding_manager._delete_chunks_from_db.return_value = 3
+
+ result = svc.remove_document_from_rag("doc-1", "coll-1")
+
+ # (1) The FAISS exception did not propagate.
+ # (2) DB-only chunk cleanup still ran.
+ svc.embedding_manager._delete_chunks_from_db.assert_called_once_with(
+ collection_name="collection_coll-1", source_id="doc-1"
+ )
+ # (3) DocumentCollection is updated and committed; RagDocumentStatus
+ # row is deleted.
+ assert doc_collection.indexed is False
+ assert doc_collection.chunk_count == 0
+ session.query.return_value.filter_by.return_value.delete.assert_called_once()
+ session.commit.assert_called_once()
+ session.rollback.assert_not_called()
+ # (4) The best-effort contract means this is still a success.
+ assert result["status"] == "success"
+ assert result["deleted_count"] == 3
diff --git a/tests/research_library/services/test_multi_model_switch_revert.py b/tests/research_library/services/test_multi_model_switch_revert.py
new file mode 100644
index 0000000000..73e269f19a
--- /dev/null
+++ b/tests/research_library/services/test_multi_model_switch_revert.py
@@ -0,0 +1,403 @@
+"""Multi-embedding-model SWITCH-AND-REVERT flow, at the LibraryRAGService level.
+
+Drives the real production sequence a user hits when they change the RAG
+embedding model in settings, index, change it again, and then change it BACK:
+
+ 1. Index a collection's document under embedding model A -> search finds it.
+ 2. Switch to model B, force-reindex the SAME document -> a SECOND RAGIndex
+ row (for B) is created and promoted ``is_current``; A's row is demoted.
+ Model A's ``DocumentChunk`` rows must survive (only B's are new/replaced)
+ -- the facade's replace-lookup is scoped by ``embedding_model``, so a
+ same-collection/-source reindex under a new model must not delete the
+ prior model's only copy of the chunk text.
+ 3. A mere SEARCH back under model A (a read path) must NOT silently
+ re-promote A's row to current -- only a write path may do that. This is
+ the "control": it proves the assertions below actually exercise the
+ ``promote_current`` gate rather than something that is always true.
+ 4. Reverting for real (the write path -- ``_get_or_create_rag_index`` with
+ ``promote_current=True``, exactly as ``index_document``/``_get_vector_index``
+ invoke it on a write) must resolve A's ORIGINAL row BY ITS index_hash (not
+ create a third row), re-promote it to current (demoting B), and leave A's
+ stored ``index_type``/``distance_metric``/``normalize_vectors`` exactly as
+ they were created -- NOT re-stamped with B's differing defaults. A search
+ afterwards must return A's original content from A's original, untouched
+ vectors -- proven by an embed_documents call counter that never increments
+ again after step 1's initial index.
+
+Mirrors the real-components harness pattern from
+``tests/vector_stores/test_no_plaintext_production_path.py`` (deterministic
+network-free fake embeddings, an in-memory sqlite engine/session shared across
+every ``get_user_db_session`` call site, ``LDR_DATA_DIR`` pointed at
+``tmp_path`` so the real cache/rag_indices tree is used, and a real
+``LibraryRAGService`` with only the embedding backend faked).
+"""
+
+import uuid
+from contextlib import contextmanager
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentStatus,
+ RAGIndex,
+ SourceType,
+)
+
+SECRET_A = "ZZZ_MODEL_A_ORIGINAL_SECRET_71bc4de0"
+
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings distinguished by model name and
+ dimension. Counts ``embed_documents`` calls (a real "was this re-embedded?"
+ signal, distinct from ``embed_query`` which the dimension-check pre-flight
+ and search both legitimately call without indicating a re-embed of any
+ document)."""
+
+ def __init__(self, name: str, dim: int):
+ self.name = name
+ self.dim = dim
+ self.doc_embed_calls = 0
+ self.query_embed_calls = 0
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash((self.name, text))) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ self.doc_embed_calls += 1
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ self.query_embed_calls += 1
+ return self._vec(text)
+
+
+def shared_world(tmp_path, monkeypatch, mocker):
+ """One in-memory DB shared by every ``get_user_db_session`` call site, and
+ a real on-disk cache tree under ``tmp_path`` (mirrors
+ ``test_no_plaintext_production_path.py``'s service-level fixture)."""
+ from unittest.mock import MagicMock
+
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _shared_session)
+ mocker.patch(
+ "local_deep_research.vector_stores.facade.get_user_db_session",
+ _shared_session,
+ )
+
+ # Integrity records live in the (mocked-away) DB side of this concern;
+ # stub the manager so the test stays focused on the switch/revert
+ # bookkeeping rather than integrity-record plumbing.
+ fim = MagicMock()
+ fim.verify_file.return_value = (True, None)
+ fim.record_file.return_value = None
+ mocker.patch(f"{_RAG_MOD}.FileIntegrityManager", return_value=fim)
+
+ yield session
+
+ session.close()
+ engine.dispose()
+
+
+def seeded_doc(shared_world):
+ """A real Collection + Document (containing SECRET_A) in the shared DB."""
+ session = shared_world
+ collection_id = uuid.uuid4().hex
+ document_id = uuid.uuid4().hex
+
+ source_type = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(source_type)
+ session.add(Collection(id=collection_id, name="Switch/revert collection"))
+
+ import hashlib
+
+ body = (
+ f"This document's original body mentions {SECRET_A} several times. " * 5
+ )
+ session.add(
+ Document(
+ id=document_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(body.encode()).hexdigest(),
+ title="Switch/revert document",
+ text_content=body,
+ original_url="http://example.com/switch-revert",
+ file_size=len(body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.commit()
+ return collection_id, document_id
+
+
+def _make_service(username, db_password, model, dim, **overrides):
+ """Build a real LibraryRAGService with only the embedding backend faked."""
+ from unittest.mock import MagicMock
+
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ emb_mgr = MagicMock()
+ fake = _FakeEmbeddings(name=model, dim=dim)
+ emb_mgr.embeddings = fake
+
+ kwargs = dict(
+ username=username,
+ db_password=db_password,
+ embedding_model=model,
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ index_type="flat",
+ distance_metric="cosine",
+ normalize_vectors=True,
+ )
+ kwargs.update(overrides)
+ svc = LibraryRAGService(**kwargs)
+ return svc, fake
+
+
+def _current_rows(session, collection_name):
+ return (
+ session.query(RAGIndex).filter_by(collection_name=collection_name).all()
+ )
+
+
+class TestMultiModelSwitchAndRevert:
+ def test_switch_to_new_model_then_revert_resolves_and_repromotes_original(
+ self, shared_world, seeded_doc
+ ):
+ session = shared_world
+ collection_id, document_id = seeded_doc
+ collection_name = f"collection_{collection_id}"
+ username = "switchuser"
+ db_password = "pw" # gitleaks:allow
+
+ # ------------------------------------------------------------------
+ # Step 1: index under model A.
+ # ------------------------------------------------------------------
+ svc_a, fake_a = _make_service(
+ username,
+ db_password,
+ "model-A",
+ dim=8,
+ index_type="flat",
+ distance_metric="cosine",
+ normalize_vectors=True,
+ )
+
+ result_a1 = svc_a.index_document(document_id, collection_id)
+ assert result_a1["status"] == "success", result_a1
+ assert result_a1["chunk_count"] > 0
+
+ rows_after_a = _current_rows(session, collection_name)
+ assert len(rows_after_a) == 1, (
+ "expected exactly one RAGIndex row after the first index"
+ )
+ row_a = rows_after_a[0]
+ assert row_a.is_current is True
+ assert row_a.embedding_model == "model-A"
+ index_hash_a = row_a.index_hash
+ row_a_id = row_a.id
+ assert row_a.index_type == "flat"
+ assert row_a.distance_metric == "cosine"
+ assert row_a.normalize_vectors is True
+
+ a_chunks_after_a = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, embedding_model="model-A")
+ .all()
+ )
+ assert len(a_chunks_after_a) == result_a1["chunk_count"]
+
+ hits_a1 = svc_a.search(
+ f"original body {SECRET_A}", collection_id, top_k=5
+ )
+ assert hits_a1, (
+ "search under model A found nothing right after indexing"
+ )
+ assert any(SECRET_A in h.text for h in hits_a1)
+
+ doc_embeds_after_a_index = fake_a.doc_embed_calls
+ assert doc_embeds_after_a_index == 1
+
+ # ------------------------------------------------------------------
+ # Step 2: switch to model B, force-reindex the SAME document/collection.
+ # ------------------------------------------------------------------
+ svc_b, fake_b = _make_service(
+ username,
+ db_password,
+ "model-B",
+ dim=4,
+ index_type="hnsw",
+ distance_metric="l2",
+ normalize_vectors=False,
+ )
+
+ result_b1 = svc_b.index_document(
+ document_id, collection_id, force_reindex=True
+ )
+ assert result_b1["status"] == "success", result_b1
+ assert result_b1["chunk_count"] > 0
+
+ rows_after_b = _current_rows(session, collection_name)
+ assert len(rows_after_b) == 2, (
+ "expected a SECOND RAGIndex row for model B, not a mutation of A's"
+ )
+ current_rows_after_b = [r for r in rows_after_b if r.is_current]
+ assert len(current_rows_after_b) == 1, (
+ "exactly one RAGIndex row must be is_current after switching to B"
+ )
+ row_b = current_rows_after_b[0]
+ assert row_b.embedding_model == "model-B"
+ assert row_b.index_hash != index_hash_a
+
+ # A's row must now be demoted, but NOT deleted/mutated in its own config.
+ row_a_reloaded = session.query(RAGIndex).filter_by(id=row_a_id).first()
+ assert row_a_reloaded.is_current is False
+ assert row_a_reloaded.index_hash == index_hash_a
+ assert row_a_reloaded.index_type == "flat"
+ assert row_a_reloaded.distance_metric == "cosine"
+ assert row_a_reloaded.normalize_vectors is True
+
+ # CORE INVARIANT: model A's chunk rows (its only copy of the chunk
+ # text) must survive model B's reindex of the SAME source/collection
+ # -- the facade's replace-lookup is scoped by embedding_model.
+ a_chunks_after_b = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, embedding_model="model-A")
+ .all()
+ )
+ assert len(a_chunks_after_b) == len(a_chunks_after_a), (
+ "model A's chunk rows were destroyed by the model-B reindex of "
+ "the same document/collection"
+ )
+ b_chunks_after_b = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, embedding_model="model-B")
+ .all()
+ )
+ assert len(b_chunks_after_b) == result_b1["chunk_count"]
+
+ hits_b1 = svc_b.search(
+ f"original body {SECRET_A}", collection_id, top_k=5
+ )
+ assert hits_b1, "search under model B found nothing after reindexing"
+ assert any(SECRET_A in h.text for h in hits_b1)
+
+ # A's own on-disk store was never touched by B's reindex (physically
+ # separate .faiss file/index_hash) -- no re-embed happened for A.
+ assert fake_a.doc_embed_calls == doc_embeds_after_a_index
+
+ # ------------------------------------------------------------------
+ # Step 3 (CONTROL): a mere SEARCH back under model A is a READ path
+ # and must NOT silently re-promote A to current. If this assertion
+ # were vacuously true (e.g. because nothing ever demotes/promotes),
+ # the "exactly one current row flips back to A" assertion in step 4
+ # would prove nothing -- this control shows the read/write gating
+ # actually matters.
+ # ------------------------------------------------------------------
+ hits_a_readonly = svc_a.search(
+ f"original body {SECRET_A}", collection_id, top_k=5
+ )
+ assert hits_a_readonly, (
+ "model A's original vectors must still be searchable via a "
+ "plain read-path search, even while B is current"
+ )
+ assert any(SECRET_A in h.text for h in hits_a_readonly)
+
+ rows_after_readonly_search = _current_rows(session, collection_name)
+ current_after_readonly = [
+ r for r in rows_after_readonly_search if r.is_current
+ ]
+ assert len(current_after_readonly) == 1
+ assert current_after_readonly[0].embedding_model == "model-B", (
+ "a mere search under the reverted model must not steal the "
+ "is_current pointer back from B -- only a write path may repromote"
+ )
+ # And the read-path search did not force any re-embed of A's chunks.
+ assert fake_a.doc_embed_calls == doc_embeds_after_a_index
+
+ # ------------------------------------------------------------------
+ # Step 4: revert for real via the WRITE-path resolution
+ # (_get_or_create_rag_index(..., promote_current=True) -- exactly how
+ # index_document/_get_vector_index invoke it on a write).
+ # ------------------------------------------------------------------
+ resolved = svc_a._get_or_create_rag_index(
+ collection_id, promote_current=True
+ )
+ assert resolved.index_hash == index_hash_a, (
+ "revert must resolve A's ORIGINAL row by index_hash, not create "
+ "a new one"
+ )
+ assert resolved.id == row_a_id
+ assert resolved.is_current is True
+
+ rows_after_revert = _current_rows(session, collection_name)
+ assert len(rows_after_revert) == 2, (
+ "revert must not create a THIRD row -- only two configs exist"
+ )
+ current_after_revert = [r for r in rows_after_revert if r.is_current]
+ assert len(current_after_revert) == 1, (
+ "exactly one RAGIndex row must be is_current after reverting"
+ )
+ assert current_after_revert[0].id == row_a_id
+ assert current_after_revert[0].embedding_model == "model-A"
+
+ # B's row must now be demoted (but intact, not deleted).
+ row_b_reloaded = session.query(RAGIndex).filter_by(id=row_b.id).first()
+ assert row_b_reloaded is not None
+ assert row_b_reloaded.is_current is False
+
+ # A's stored index_type/distance_metric/normalize_vectors must NOT
+ # have been re-stamped with B's differing defaults (hnsw/l2/False)
+ # by the revert/re-promotion.
+ assert resolved.index_type == "flat"
+ assert resolved.distance_metric == "cosine"
+ assert resolved.normalize_vectors is True
+
+ # The revert/re-promotion is pure bookkeeping -- it must not have
+ # re-embedded anything (no new FAISS writes for A).
+ assert fake_a.doc_embed_calls == doc_embeds_after_a_index
+
+ # ------------------------------------------------------------------
+ # Final observable outcome: search under A returns A's ORIGINAL
+ # content, from vectors that were never touched/rebuilt throughout
+ # the whole switch-and-revert sequence.
+ # ------------------------------------------------------------------
+ hits_a_final = svc_a.search(
+ f"original body {SECRET_A}", collection_id, top_k=5
+ )
+ assert hits_a_final, "search under model A after revert found nothing"
+ assert any(SECRET_A in h.text for h in hits_a_final)
+ assert fake_a.doc_embed_calls == doc_embeds_after_a_index, (
+ "search after revert must not have triggered a re-embed of A's "
+ "document -- its original vectors were reused as-is"
+ )
+
+ svc_a.close()
+ svc_b.close()
diff --git a/tests/research_library/test_document_full_lifecycle.py b/tests/research_library/test_document_full_lifecycle.py
new file mode 100644
index 0000000000..ac70ad6c84
--- /dev/null
+++ b/tests/research_library/test_document_full_lifecycle.py
@@ -0,0 +1,422 @@
+"""Large end-to-end test: a single library Document's FULL RAG lifecycle
+through REAL components — index -> reindex-with-edited-text -> delete ->
+reindex-again — driving the production ``LibraryRAGService`` against a real
+on-disk ``FaissVectorStore`` and a real (in-memory) encrypted-DB-shaped
+SQLite session.
+
+Mirrors the real-components harness style of
+``tests/vector_stores/test_no_plaintext_production_path.py``: a deterministic
+network-free ``_FakeEmbeddings``, a real ``Base.metadata.create_all`` sqlite
+engine/session shared across every ``get_user_db_session`` call site,
+``LDR_DATA_DIR`` pointed at ``tmp_path`` so the real ``cache/rag_indices/``
+tree is used, and a stubbed ``FileIntegrityManager`` (integrity bookkeeping is
+orthogonal to the lifecycle invariants under test here).
+
+Each phase asserts on OBSERVABLE real state, never on a mock:
+ 1. index_document(...) -> search finds SECRET_A; .faiss exists
+ 2. index_document(..., force_reindex) -> search finds SECRET_B, NOT SECRET_A;
+ old vectors replaced, not duplicated
+ 3. remove_document_from_rag(...) -> search finds nothing; zero
+ DocumentChunk rows; store count/
+ live_ids drop to 0; .faiss bytes
+ contain neither secret
+ 4. index_document(...) again -> searchable again (delete didn't
+ corrupt the collection)
+"""
+
+import hashlib
+import uuid
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.config.paths import get_cache_directory
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ RAGIndex,
+ SourceType,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+from local_deep_research.vector_stores import get_vector_store_class
+
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+_FACADE_MOD = "local_deep_research.vector_stores.facade"
+
+SECRET_A = "ZZZ_LIFECYCLE_SECRET_A_9d1f3c8e"
+SECRET_B = "ZZZ_LIFECYCLE_SECRET_B_7ab2e410"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings — numeric vectors, so the text
+ markers can never survive into them as raw bytes (keeps on-disk greps
+ sound)."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _grep_all(root, needle: bytes):
+ """Every on-disk file under ``root`` that contains ``needle`` (raw bytes)."""
+ return [
+ str(f)
+ for f in root.rglob("*")
+ if f.is_file() and needle in f.read_bytes()
+ ]
+
+
+def lifecycle_env(tmp_path, monkeypatch, mocker):
+ """Real in-memory DB session shared across every ``get_user_db_session``
+ call site the service/facade use, plus the real on-disk cache tree."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _shared_session)
+ mocker.patch(f"{_FACADE_MOD}.get_user_db_session", _shared_session)
+ # ``remove_documents_from_index`` does its own local
+ # ``from ...database.session_context import get_user_db_session`` inside
+ # the method body, which re-binds the name from the SOURCE module rather
+ # than using ``library_rag_service``'s own module-level import — patching
+ # only the two aliases above leaves that call site hitting the real
+ # (unpatched) session factory. Patch the source directly too so every call
+ # site — regardless of which alias it resolved — sees the shared session.
+ mocker.patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ _shared_session,
+ )
+
+ # Integrity records live in the DB, not the FAISS tree; stub the manager
+ # so the test stays focused on the lifecycle invariants, mirroring
+ # test_no_plaintext_production_path.py.
+ fim = MagicMock()
+ fim.verify_file.return_value = (True, None)
+ fim.record_file.return_value = None
+ mocker.patch(f"{_RAG_MOD}.FileIntegrityManager", return_value=fim)
+
+ yield session
+
+ session.close()
+ engine.dispose()
+
+
+def seeded_document(lifecycle_env):
+ """A real Collection + Document (+ DocumentCollection link) carrying
+ SECRET_A in its text content."""
+ session = lifecycle_env
+
+ collection_id = uuid.uuid4().hex
+ document_id = uuid.uuid4().hex
+ source_type = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(source_type)
+ session.add(Collection(id=collection_id, name="Lifecycle collection"))
+
+ body = f"This document's body mentions {SECRET_A} several times. " * 5
+ session.add(
+ Document(
+ id=document_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(body.encode()).hexdigest(),
+ title="Lifecycle document",
+ text_content=body,
+ original_url="http://example.com/lifecycle",
+ file_size=len(body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.commit()
+
+ # Explicit DocumentCollection link (index_document would create it via
+ # ensure_in_collection anyway, but the task seeds it explicitly so the
+ # membership is unambiguous from the start).
+ session.add(
+ DocumentCollection(
+ document_id=document_id, collection_id=collection_id, indexed=False
+ )
+ )
+ session.commit()
+
+ return {"collection_id": collection_id, "document_id": document_id}
+
+
+def rag_service(lifecycle_env):
+ """Real LibraryRAGService; only the embedding backend is faked (no
+ network/model load), mirroring the canonical harness."""
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = _FakeEmbeddings(dim=8)
+ # ``remove_document_from_rag``'s DB-only backstop sweep
+ # (``_delete_chunks_from_db``) is a real int-returning DB query in
+ # production; in the normal path exercised here every row is already
+ # gone (deleted by ``remove_documents_from_index``) by the time it
+ # runs, so it finds nothing and returns 0. Left as a bare MagicMock it
+ # would return a MagicMock instead of an int, which corrupts the
+ # ``deleted_count = removed_vectors + ...`` arithmetic under test.
+ emb_mgr._delete_chunks_from_db.return_value = 0
+
+ svc = LibraryRAGService(
+ username="lifecycleuser",
+ db_password="pw", # gitleaks:allow
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ )
+ yield svc
+ svc.close()
+
+
+def _faiss_files():
+ rag_root = get_cache_directory() / "rag_indices"
+ return list(rag_root.rglob("*.faiss"))
+
+
+def _load_store(faiss_path, rag_index_row):
+ store_cls = get_vector_store_class()
+ return store_cls.load(
+ faiss_path,
+ dimension=rag_index_row.embedding_dimension,
+ index_type=rag_index_row.index_type or "flat",
+ metric=rag_index_row.distance_metric or "cosine",
+ normalize=(
+ rag_index_row.normalize_vectors
+ if rag_index_row.normalize_vectors is not None
+ else True
+ ),
+ )
+
+
+def _current_rag_index_row(session, collection_id):
+ collection_name = f"collection_{collection_id}"
+ return (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name, is_current=True)
+ .first()
+ )
+
+
+def _chunk_ids_for_source(session, document_id):
+ return [
+ row.id
+ for row in session.query(DocumentChunk.id).filter_by(
+ source_type="document", source_id=document_id
+ )
+ ]
+
+
+class TestDocumentFullLifecycle:
+ def test_index_reindex_delete_reindex_round_trip(
+ self, lifecycle_env, seeded_document, rag_service
+ ):
+ session = lifecycle_env
+ svc = rag_service
+ document_id = seeded_document["document_id"]
+ collection_id = seeded_document["collection_id"]
+
+ # ------------------------------------------------------------ #
+ # Phase 1: initial index — SECRET_A is indexed and searchable.
+ # ------------------------------------------------------------ #
+ result = svc.index_document(document_id, collection_id)
+ assert result["status"] == "success", result
+ assert result["chunk_count"] > 0
+
+ faiss_files = _faiss_files()
+ assert len(faiss_files) == 1, faiss_files
+ faiss_path = faiss_files[0]
+ assert faiss_path.is_file()
+ assert faiss_path.stat().st_size > 0
+
+ hits = svc.search(f"body mentions {SECRET_A}", collection_id, top_k=5)
+ assert hits
+ assert any(SECRET_A in h.text for h in hits)
+
+ rag_index_row = _current_rag_index_row(session, collection_id)
+ assert rag_index_row is not None
+ store = _load_store(faiss_path, rag_index_row)
+ phase1_ids = set(_chunk_ids_for_source(session, document_id))
+ assert phase1_ids, "no DocumentChunk rows were created by indexing"
+ assert set(store.live_ids()) == phase1_ids
+ assert store.count() == len(phase1_ids)
+
+ # ------------------------------------------------------------ #
+ # Phase 2: edit the text to SECRET_B and force-reindex. The old
+ # SECRET_A vectors/rows must be REPLACED, not left as stale
+ # duplicates alongside the new SECRET_B ones.
+ # ------------------------------------------------------------ #
+ document = session.query(Document).filter_by(id=document_id).first()
+ new_body = f"This document's body now mentions {SECRET_B} instead. " * 5
+ document.text_content = new_body
+ document.document_hash = hashlib.sha256(new_body.encode()).hexdigest()
+ session.commit()
+
+ result2 = svc.index_document(
+ document_id, collection_id, force_reindex=True
+ )
+ assert result2["status"] == "success", result2
+ assert result2["chunk_count"] > 0
+
+ hits_b = svc.search(
+ f"body now mentions {SECRET_B}", collection_id, top_k=5
+ )
+ assert hits_b
+ assert any(SECRET_B in h.text for h in hits_b)
+ assert all(SECRET_A not in h.text for h in hits_b), (
+ "stale SECRET_A content resurfaced after a force_reindex with "
+ "edited text"
+ )
+
+ # A broad query that would have matched EITHER version's chunks must
+ # not return any SECRET_A-bearing result either.
+ hits_broad = svc.search("This document's body", collection_id, top_k=10)
+ assert hits_broad
+ assert all(SECRET_A not in h.text for h in hits_broad)
+ assert any(SECRET_B in h.text for h in hits_broad)
+
+ # DB-level: every remaining chunk row for this source carries the NEW
+ # text only — the old rows were deleted, not merely out-ranked.
+ remaining_rows = (
+ session.query(DocumentChunk)
+ .filter_by(source_type="document", source_id=document_id)
+ .all()
+ )
+ assert remaining_rows
+ assert all(SECRET_A not in (r.chunk_text or "") for r in remaining_rows)
+ assert any(SECRET_B in (r.chunk_text or "") for r in remaining_rows)
+
+ rag_index_row = _current_rag_index_row(session, collection_id)
+ store2 = _load_store(faiss_path, rag_index_row)
+ phase2_ids = set(_chunk_ids_for_source(session, document_id))
+ assert phase2_ids, "no DocumentChunk rows after reindex"
+ assert phase2_ids.isdisjoint(phase1_ids), (
+ "reindex reused the OLD chunk ids instead of replacing them with "
+ "fresh rows — the old-vs-new id sets should never overlap here"
+ )
+ assert set(store2.live_ids()) == phase2_ids
+ assert store2.count() == len(phase2_ids)
+
+ # The on-disk .faiss holds no plaintext of either secret (vectors are
+ # pure floats — this is the structural guarantee, reasserted here).
+ leaked = _grep_all(faiss_path.parent, SECRET_A.encode())
+ leaked += _grep_all(faiss_path.parent, SECRET_B.encode())
+ assert leaked == [], f"plaintext marker leaked to disk: {leaked}"
+
+ # ------------------------------------------------------------ #
+ # Phase 3: delete the document from RAG. Search must return
+ # nothing, chunk rows must be gone, and the store must reflect it.
+ # ------------------------------------------------------------ #
+ del_result = svc.remove_document_from_rag(document_id, collection_id)
+ assert del_result["status"] == "success", del_result
+ # Regression guard for FIX A (commit daa5e2ebb): the reported
+ # ``deleted_count`` must reflect the TRUE number of chunks removed —
+ # this is the only real-FAISS path in the suite, so it validates the
+ # count against ground truth (the actual phase-2 chunk id set) rather
+ # than a mock's return value.
+ assert del_result["deleted_count"] == len(phase2_ids), del_result
+
+ hits_after_delete = svc.search(
+ "This document's body", collection_id, top_k=10
+ )
+ assert hits_after_delete == []
+
+ zero_rows = (
+ session.query(DocumentChunk)
+ .filter_by(source_type="document", source_id=document_id)
+ .count()
+ )
+ assert zero_rows == 0
+
+ rag_index_row = _current_rag_index_row(session, collection_id)
+ store3 = _load_store(faiss_path, rag_index_row)
+ assert store3.count() == 0
+ assert store3.live_ids() == []
+
+ leaked_after_delete = _grep_all(faiss_path.parent, SECRET_A.encode())
+ leaked_after_delete += _grep_all(faiss_path.parent, SECRET_B.encode())
+ assert leaked_after_delete == [], (
+ f"plaintext marker leaked to disk after delete: "
+ f"{leaked_after_delete}"
+ )
+
+ # The Document row itself must still exist (this is a RAG-removal,
+ # not a document deletion) — a control for phase 4 below.
+ doc_still_present = (
+ session.query(Document).filter_by(id=document_id).first()
+ )
+ assert doc_still_present is not None
+ assert SECRET_B in doc_still_present.text_content
+
+ # ------------------------------------------------------------ #
+ # Phase 4: re-index the still-present Document -> searchable again.
+ # Proves the delete didn't corrupt the collection/store.
+ # ------------------------------------------------------------ #
+ result3 = svc.index_document(document_id, collection_id)
+ assert result3["status"] == "success", result3
+ assert result3["chunk_count"] > 0
+
+ hits_final = svc.search(
+ f"body now mentions {SECRET_B}", collection_id, top_k=5
+ )
+ assert hits_final
+ assert any(SECRET_B in h.text for h in hits_final)
+
+ rag_index_row = _current_rag_index_row(session, collection_id)
+ store4 = _load_store(faiss_path, rag_index_row)
+ phase4_ids = set(_chunk_ids_for_source(session, document_id))
+ assert phase4_ids
+ assert set(store4.live_ids()) == phase4_ids
+ assert store4.count() == len(phase4_ids)
+
+ def test_control_broad_query_would_have_matched_secret_a_before_reindex(
+ self, lifecycle_env, seeded_document, rag_service
+ ):
+ """Sanity control for phase 2's "no SECRET_A" assertions above: prove
+ the broad query genuinely WOULD surface SECRET_A content when it is
+ still the indexed text — i.e. the "not present after reindex"
+ assertions are not vacuously true because the query never matches
+ anything.
+ """
+ svc = rag_service
+ document_id = seeded_document["document_id"]
+ collection_id = seeded_document["collection_id"]
+
+ result = svc.index_document(document_id, collection_id)
+ assert result["status"] == "success", result
+
+ hits = svc.search("This document's body", collection_id, top_k=10)
+ assert hits
+ assert any(SECRET_A in h.text for h in hits), (
+ "control failed: the broad query does not surface SECRET_A even "
+ "before the reindex — the phase-2 'SECRET_A absent' assertions "
+ "would be vacuous"
+ )
diff --git a/tests/research_library/zotero/test_faiss_cleanup.py b/tests/research_library/zotero/test_faiss_cleanup.py
index 086442fae2..5309394245 100644
--- a/tests/research_library/zotero/test_faiss_cleanup.py
+++ b/tests/research_library/zotero/test_faiss_cleanup.py
@@ -2,8 +2,9 @@
These exercise ``LibraryRAGService.remove_documents_from_index`` (the new
primitive the Zotero removal path uses) without a real FAISS index or
-embedding model: the index is a stub and the RAGIndex existence check is
-stubbed via the session.
+embedding model: the RAGIndex existence check is stubbed via the session, so
+these two cases (no ids / no current index) return before any vector store
+is ever touched.
"""
from contextlib import contextmanager
@@ -14,26 +15,7 @@ from local_deep_research.research_library.services.library_rag_service import (
)
-class _Doc:
- def __init__(self, metadata):
- self.metadata = metadata
-
-
-class _FakeDocstore:
- def __init__(self, store):
- self._dict = store
-
-
-class _FakeIndex:
- def __init__(self, store):
- self.docstore = _FakeDocstore(store)
- self.deleted = []
-
- def delete(self, ids):
- self.deleted.extend(ids)
-
-
-def _svc_with_index(store):
+def _svc():
# Build the service without running __init__ (no embeddings needed).
svc = LibraryRAGService.__new__(LibraryRAGService)
# The db_password setter propagates to these — set them first.
@@ -41,8 +23,7 @@ def _svc_with_index(store):
svc.integrity_manager = None
svc.username = "u"
svc.db_password = "pw" # gitleaks:allow
- svc.faiss_index = _FakeIndex(store)
- svc.rag_index_record = None # -> in-memory delete branch (no save_local)
+ svc.rag_index_record = None
return svc
@@ -61,41 +42,16 @@ def _patch_has_index(monkeypatch, exists: bool):
)
-def test_remove_documents_from_index_selects_by_metadata(monkeypatch):
- store = {
- "c_1": _Doc({"document_id": "D1"}),
- "c_2": _Doc({"document_id": "D1"}),
- "c_3": _Doc({"source_id": "D2"}), # different doc
- "c_4": _Doc({}), # unrelated
- }
- _patch_has_index(monkeypatch, True)
- svc = _svc_with_index(store)
-
- removed = svc.remove_documents_from_index(["D1"], "COLL")
- assert removed == 2
- assert set(svc.faiss_index.deleted) == {"c_1", "c_2"}
-
-
-def test_remove_documents_from_index_matches_source_id_too(monkeypatch):
- store = {"c_3": _Doc({"source_id": "D2"})}
- _patch_has_index(monkeypatch, True)
- svc = _svc_with_index(store)
- assert svc.remove_documents_from_index(["D2"], "COLL") == 1
- assert svc.faiss_index.deleted == ["c_3"]
-
-
def test_remove_documents_from_index_noop_without_index(monkeypatch):
_patch_has_index(monkeypatch, False)
- svc = _svc_with_index({"c_1": _Doc({"document_id": "D1"})})
+ svc = _svc()
assert svc.remove_documents_from_index(["D1"], "COLL") == 0
- assert svc.faiss_index.deleted == []
def test_remove_documents_from_index_empty_ids(monkeypatch):
# No DB hit, no index touched.
- svc = _svc_with_index({"c_1": _Doc({"document_id": "D1"})})
+ svc = _svc()
assert svc.remove_documents_from_index([], "COLL") == 0
- assert svc.faiss_index.deleted == []
def test_remove_document_from_rag_also_clears_vectors(monkeypatch):
diff --git a/tests/security/file_integrity/test_integrity_manager.py b/tests/security/file_integrity/test_integrity_manager.py
index cf965470b4..517398aebb 100644
--- a/tests/security/file_integrity/test_integrity_manager.py
+++ b/tests/security/file_integrity/test_integrity_manager.py
@@ -834,3 +834,248 @@ class TestCleanupAllOldFailures:
mgr = FileIntegrityManager("user", "pass")
result = mgr.cleanup_all_old_failures()
assert result == 0
+
+
+class TestIntegrityWriteNestedMode:
+ """The _integrity_write helper routes the DB write correctly (#11 fix).
+
+ Standalone callers commit immediately; reentrant callers (the vector store
+ during apply(), which holds the caller's just-flushed, uncommitted rows on
+ the SAME thread-local session) run in a SAVEPOINT and DON'T commit, so a
+ failure can't discard the caller's rows and the record commits with the
+ caller's outer transaction. (Real SQLite savepoint isolation is exercised
+ end-to-end by the app's other begin_nested() call sites.)
+ """
+
+ def _mgr(self):
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ):
+ return FileIntegrityManager("user", "pass")
+
+ def test_default_commits_no_savepoint(self):
+ mgr = self._mgr()
+ session = MagicMock()
+ with mgr._integrity_write(session, nested=False):
+ pass
+ session.commit.assert_called_once()
+ session.begin_nested.assert_not_called()
+
+ def test_nested_uses_savepoint_and_never_commits(self):
+ mgr = self._mgr()
+ session = MagicMock()
+ with mgr._integrity_write(session, nested=True):
+ pass
+ session.begin_nested.assert_called_once()
+ session.commit.assert_not_called()
+
+ def test_nested_failure_rolls_back_only_the_savepoint(self):
+ # A failure inside the nested write must propagate WITHOUT the helper
+ # committing or rolling back the caller's session — the savepoint
+ # context manager owns the scoped rollback.
+ mgr = self._mgr()
+ session = MagicMock()
+ with pytest.raises(RuntimeError):
+ with mgr._integrity_write(session, nested=True):
+ raise RuntimeError("transient integrity-write failure")
+ session.commit.assert_not_called()
+ session.rollback.assert_not_called()
+
+
+class TestNestedWriteAvoidsFullRollback:
+ """#7 regression: a failing nested integrity write must NOT let the
+ exception escape record_file's get_user_db_session block — otherwise that
+ context manager's except clause does a FULL session.rollback(), discarding
+ the caller's flushed rows (defeating the SAVEPOINT). The error must still
+ surface (so apply()'s retry/fail logic sees it)."""
+
+ def _mgr_with_verifier(self):
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ):
+ mgr = FileIntegrityManager("user", "pass")
+ verifier = MagicMock()
+ verifier.calculate_checksum.return_value = "abc"
+ verifier.get_algorithm.return_value = "sha256"
+ verifier.get_file_type.return_value = "faiss"
+ verifier.allows_modifications.return_value = False
+ mgr._get_verifier_for_file = Mock(return_value=verifier)
+ return mgr
+
+ def test_nested_failure_does_not_call_full_rollback(self, tmp_path):
+ import contextlib
+
+ f = tmp_path / "idx.faiss"
+ f.write_bytes(b"x")
+
+ mgr = self._mgr_with_verifier()
+
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ None # new-record path
+ )
+ # SAVEPOINT ctx manager that propagates (does not suppress) the error.
+ sp = MagicMock()
+ sp.__enter__ = Mock(return_value=None)
+ sp.__exit__ = Mock(return_value=False)
+ session.begin_nested.return_value = sp
+ # The write inside the SAVEPOINT fails.
+ session.add.side_effect = RuntimeError("integrity write failed")
+
+ full_rollbacks = []
+
+ @contextlib.contextmanager
+ def fake_gus(_u, _p):
+ try:
+ yield session
+ except Exception:
+ session.rollback() # the FULL rollback we must avoid
+ full_rollbacks.append(1)
+ raise
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session",
+ fake_gus,
+ ):
+ with pytest.raises(RuntimeError, match="integrity write failed"):
+ mgr.record_file(f, nested=True)
+
+ # The SAVEPOINT was used, and the outer full rollback NEVER fired.
+ session.begin_nested.assert_called_once()
+ assert full_rollbacks == []
+ session.commit.assert_not_called()
+
+ def test_standalone_failure_still_propagates_for_full_rollback(
+ self, tmp_path
+ ):
+ import contextlib
+
+ f = tmp_path / "idx.faiss"
+ f.write_bytes(b"x")
+ mgr = self._mgr_with_verifier()
+
+ session = MagicMock()
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+ session.commit.side_effect = RuntimeError("commit failed")
+
+ full_rollbacks = []
+
+ @contextlib.contextmanager
+ def fake_gus(_u, _p):
+ try:
+ yield session
+ except Exception:
+ session.rollback()
+ full_rollbacks.append(1)
+ raise
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session",
+ fake_gus,
+ ):
+ with pytest.raises(RuntimeError, match="commit failed"):
+ mgr.record_file(f, nested=False)
+
+ # Standalone: original behavior — the error propagates and the outer
+ # rollback DOES fire (nothing else is pending on that session).
+ assert full_rollbacks == [1]
+
+
+class TestSessionForNestedUsesLiveSession:
+ """#7 regression: in nested mode the integrity op must use the caller's
+ LIVE thread session (get_current_thread_session), NOT get_user_db_session —
+ re-entering the latter in a background context runs a re-acquisition
+ rollback that discards the caller's flushed-but-uncommitted rows."""
+
+ def _mgr(self):
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session"
+ ):
+ return FileIntegrityManager("user", "pass")
+
+ def test_nested_uses_live_session_not_get_user_db_session(self):
+ import contextlib
+
+ mgr = self._mgr()
+ live = MagicMock(name="live_thread_session")
+ gus_calls = []
+
+ @contextlib.contextmanager
+ def fake_gus(_u, _p):
+ gus_calls.append(1)
+ yield MagicMock(name="reacquired")
+
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_current_thread_session",
+ return_value=live,
+ ),
+ patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session",
+ fake_gus,
+ ),
+ ):
+ with mgr._session_for(nested=True) as s:
+ assert s is live
+ # get_user_db_session (the rollback-prone re-acquisition) was NOT used.
+ assert gus_calls == []
+
+ def test_standalone_uses_get_user_db_session(self):
+ import contextlib
+
+ mgr = self._mgr()
+ gus_calls = []
+ sentinel = MagicMock(name="normal_session")
+
+ @contextlib.contextmanager
+ def fake_gus(_u, _p):
+ gus_calls.append(1)
+ yield sentinel
+
+ with patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session",
+ fake_gus,
+ ):
+ with mgr._session_for(nested=False) as s:
+ assert s is sentinel
+ assert gus_calls == [1]
+
+ def test_nested_falls_back_when_no_live_session(self):
+ import contextlib
+
+ mgr = self._mgr()
+ gus_calls = []
+ sentinel = MagicMock(name="fallback_session")
+
+ @contextlib.contextmanager
+ def fake_gus(_u, _p):
+ gus_calls.append(1)
+ yield sentinel
+
+ with (
+ patch(
+ "local_deep_research.database.thread_local_session.get_current_thread_session",
+ return_value=None,
+ ),
+ patch(
+ "local_deep_research.security.file_integrity.integrity_manager.get_user_db_session",
+ fake_gus,
+ ),
+ ):
+ with mgr._session_for(nested=True) as s:
+ assert s is sentinel
+ assert gus_calls == [1]
diff --git a/tests/security/test_password_redaction_invariant.py b/tests/security/test_password_redaction_invariant.py
index a73d92ee9f..4c735fb57b 100644
--- a/tests/security/test_password_redaction_invariant.py
+++ b/tests/security/test_password_redaction_invariant.py
@@ -64,11 +64,17 @@ import local_deep_research.database.library_init as library_init_module
import local_deep_research.database.backup.backup_executor as backup_executor_module
import local_deep_research.web_search_engines.rate_limiting.tracker as rate_limit_tracker_module
import local_deep_research.research_library.search.services.research_history_indexer as research_history_indexer_module
+import local_deep_research.vector_stores.legacy_rekey as legacy_rekey_module
SWEPT_MODULES = [
encrypted_db_module,
background_module,
processor_v2_module,
+ # Phase-2 RAG re-key: rekey_user_indexes(username, db_password) holds the
+ # SQLCipher master password in scope across six failure-logging except
+ # blocks, and runs at every login while a legacy sidecar remains. Each now
+ # drops the traceback + redact_secrets(str(exc), db_password).
+ legacy_rekey_module,
# Consumers of ``DatabaseInitializationError`` that hold the master
# password in scope while logging the catch (#4182 follow-up): the
# raise site redacts, but these callers re-render via the logger.
@@ -141,17 +147,40 @@ def _logger_method_name(call: ast.Call):
def _renders_traceback(call: ast.Call) -> bool:
"""True if *call* is a logger call that renders an exception traceback.
- Matches ``logger.exception(...)`` and any ``logger.<level>(...,
- exc_info=<anything>)`` (including ``logger.bind(...).<level>`` chains).
- A literal ``exc_info=False`` is treated as a violation too — it serves
- no purpose and invites a flip to ``True``.
+ Matches ``logger.exception(...)``; any ``logger.<level>(...,
+ exc_info=<anything>)``; and ``logger.opt(exception=<not-literally-False>)
+ .<level>(...)``. The last form is critical: loguru's
+ ``opt(exception=True).error(...)`` renders the traceback IDENTICALLY to
+ ``logger.exception`` (same frame-locals leak under ``diagnose=True``), but
+ the traceback is attached via ``opt()`` — not an ``exc_info`` kwarg on the
+ final call — so without this it silently evades the check. All three forms
+ (including ``logger.bind(...)``/``logger.opt(...)`` chains) are matched.
+ A literal ``exc_info=False`` is treated as a violation too — it serves no
+ purpose and invites a flip to ``True``.
"""
method = _logger_method_name(call)
if method is None:
return False
if method == "exception":
return True
- return any(kw.arg == "exc_info" for kw in call.keywords)
+ if any(kw.arg == "exc_info" for kw in call.keywords):
+ return True
+ # Walk the receiver chain for a logger.opt(exception=<truthy>) call.
+ node = call.func
+ while isinstance(node, (ast.Attribute, ast.Call)):
+ if isinstance(node, ast.Call):
+ f = node.func
+ if isinstance(f, ast.Attribute) and f.attr == "opt":
+ for kw in node.keywords:
+ if kw.arg == "exception" and not (
+ isinstance(kw.value, ast.Constant)
+ and kw.value.value is False
+ ):
+ return True
+ node = node.func
+ else: # ast.Attribute
+ node = node.value
+ return False
def find_unredacted_traceback_logs(source: str, filename: str) -> list:
diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.js
index b212bb1236..f05bac3f0e 100644
--- a/tests/ui_tests/run_all_tests.js
+++ b/tests/ui_tests/run_all_tests.js
@@ -273,7 +273,7 @@ const tests = [
},
// =====================================================================
- // Shard: library (5 tests)
+ // Shard: library (7 tests)
// =====================================================================
{
name: 'Library Collections CI Tests',
@@ -305,6 +305,24 @@ const tests = [
shard: 'library',
description: 'Tests Zotero page structure, config/status APIs, API-key non-leak contract, unconfigured negative paths'
},
+ {
+ name: 'RAG Index + Semantic Search E2E',
+ file: 'test_rag_index_search_ci.js',
+ shard: 'library',
+ description: 'End-to-end: create collection, upload a doc, index it, and semantic-search it back through the UI'
+ },
+ {
+ name: 'Legacy .pkl RAG Migration E2E',
+ file: 'test_legacy_pkl_migration_ci.js',
+ shard: 'library',
+ description: 'End-to-end: seed legacy plaintext .pkl docstores (2 collections), let the server run phase-1 at startup + phase-2 at login, and assert the .pkl is gone, a text-free sidecar was written, and search still rehydrates the RIGHT seeded content by id',
+ // Requires a Python seed BEFORE the server boots (phase-1 runs only at
+ // startup). Locally: tests/ui_tests/run_legacy_pkl_migration.sh. In CI:
+ // the library-shard seed step in .github/workflows/docker-tests.yml.
+ // The manifest path defaults to <LDR_DATA_DIR>/migtest_manifest.json;
+ // if the manifest is absent the test fails fast asking you to seed.
+ needsSeed: 'legacy_pkl_migration',
+ },
// =====================================================================
// Shard: history-news (3 tests)
diff --git a/tests/ui_tests/run_legacy_pkl_migration.sh b/tests/ui_tests/run_legacy_pkl_migration.sh
new file mode 100755
index 0000000000..907881d837
--- /dev/null
+++ b/tests/ui_tests/run_legacy_pkl_migration.sh
@@ -0,0 +1,84 @@
+#!/bin/bash
+# One-command LOCAL runner for the legacy plaintext-.pkl RAG migration E2E test.
+#
+# Boot ORDER is load-bearing: phase-1 (migrate_legacy_docstores) runs only at
+# server STARTUP (there is no on-demand endpoint), so the legacy `.pkl` fixtures
+# MUST exist on disk BEFORE the server boots. This wrapper encapsulates that:
+#
+# 1. export a disposable LDR_DATA_DIR (default /tmp/ldr-migtest) and WIPE it,
+# 2. run the Python seed (auth user + encrypted DB rows + legacy .faiss/.pkl),
+# 3. boot a THROWAWAY server on a spare port (default 5099) via
+# scripts/dev/restart_server.sh <PORT> --tmp — its startup runs phase-1,
+# 4. run the Puppeteer test (login drives phase-2; then searches),
+# 5. tear the server down.
+#
+# NEVER touches the user's real dev server on 5001 or their real data dir.
+#
+# Usage:
+# bash tests/ui_tests/run_legacy_pkl_migration.sh [PORT]
+#
+# Env overrides:
+# LDR_DATA_DIR disposable data dir (default /tmp/ldr-migtest)
+# PORT (arg 1) throwaway server port (default 5099)
+
+set -u
+
+PORT="${1:-5099}"
+export LDR_DATA_DIR="${LDR_DATA_DIR:-/tmp/ldr-migtest}"
+
+# Resolve repo root from this script's location.
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
+cd "${REPO_ROOT}" || exit 1
+
+if [ "${PORT}" = "5001" ]; then
+ echo "Refusing to run on port 5001 (the user's real dev server)." >&2
+ exit 2
+fi
+
+# shellcheck disable=SC2329 # invoked indirectly via `trap cleanup EXIT` below
+cleanup() {
+ echo ""
+ echo "Tearing down throwaway server on port ${PORT}..."
+ fuser -k "${PORT}/tcp" 2>/dev/null || true
+}
+trap cleanup EXIT
+
+echo "=== 1/4 Wipe disposable LDR_DATA_DIR=${LDR_DATA_DIR} ==="
+rm -rf "${LDR_DATA_DIR}"
+mkdir -p "${LDR_DATA_DIR}"
+
+echo "=== 2/4 Seed legacy .pkl fixtures + encrypted-DB rows (before boot) ==="
+if ! pdm run python tests/ui_tests/seed_legacy_pkl_migration.py; then
+ echo "Seed FAILED" >&2
+ exit 1
+fi
+
+echo "=== 3/4 Boot throwaway server on port ${PORT} (runs phase-1 at startup) ==="
+bash scripts/dev/restart_server.sh "${PORT}" --tmp >/dev/null 2>&1
+
+# Wait for readiness.
+ready=0
+for i in $(seq 1 60); do
+ if curl -fsS --connect-timeout 2 --max-time 5 \
+ "http://127.0.0.1:${PORT}/api/v1/health" >/dev/null 2>&1; then
+ echo "Server ready after ${i}s"
+ ready=1
+ break
+ fi
+ sleep 1
+done
+if [ "${ready}" -ne 1 ]; then
+ echo "Server failed to become ready on port ${PORT}" >&2
+ echo "--- last 40 log lines ---"
+ tail -40 "/tmp/ldr_server_${PORT}.log" 2>/dev/null || true
+ exit 1
+fi
+
+echo "=== 4/4 Run Puppeteer migration test (login drives phase-2) ==="
+LDR_TEST_URL="http://127.0.0.1:${PORT}" \
+ LDR_DATA_DIR="${LDR_DATA_DIR}" \
+ node tests/ui_tests/test_legacy_pkl_migration_ci.js
+rc=$?
+
+exit "${rc}"
diff --git a/tests/ui_tests/seed_legacy_pkl_migration.py b/tests/ui_tests/seed_legacy_pkl_migration.py
new file mode 100644
index 0000000000..a7a6988cfa
--- /dev/null
+++ b/tests/ui_tests/seed_legacy_pkl_migration.py
@@ -0,0 +1,353 @@
+#!/usr/bin/env python3
+"""Seed a REALISTIC legacy plaintext ``.pkl`` RAG docstore (plus the matching
+encrypted-DB rows) so the running server's two-phase migration can be exercised
+end to end by ``test_legacy_pkl_migration_ci.js``.
+
+WHY A PYTHON SEED IS MANDATORY (a pure-Puppeteer test is impossible here):
+
+ 1. A browser cannot build a genuine pre-cutover LangChain-FAISS
+ ``<hash>.faiss`` + plaintext ``<hash>.pkl`` pair — that needs
+ ``langchain_community.vectorstores.FAISS`` + real all-MiniLM-L6-v2
+ embeddings (exactly the ``_make_legacy_index`` recipe the vector_stores
+ unit tests use).
+ 2. A browser cannot seed the per-user encrypted SQLCipher rows
+ (Collection / SourceType / Document / DocumentCollection /
+ RagDocumentStatus / DocumentChunk / RAGIndex) that post-migration search
+ rehydrates chunk text from — that needs the password + the DB manager.
+
+The migration itself is then driven by the REAL server:
+
+ * PHASE 1 — ``migrate_legacy_docstores()`` at web startup
+ (web/app.py). It scans ``<LDR_DATA_DIR>/cache/rag_indices`` and, for each
+ legacy ``<hash>.pkl``, writes a TEXT-FREE ``<hash>.idmap.json`` sidecar and
+ DELETES the ``.pkl``. This is why the seed MUST run BEFORE the server boots.
+ * PHASE 2 — ``rekey_user_indexes(username, password)`` at login. It rebuilds
+ the ``IndexIDMap2`` keyed by ``DocumentChunk.id`` from the sidecar (no
+ re-embed) and removes the sidecar.
+
+This seeds TWO collections so the node test can prove the RIGHT ``.pkl`` was
+extracted into the RIGHT sidecar / index (no cross-contamination):
+
+ * collection A carries the distinctive token SECRET_A,
+ * collection B (the decoy) carries SECRET_B.
+
+Both indexes are built with the SAME real all-MiniLM-L6-v2 (384-dim) model the
+server re-embeds the query with at search time, so cosine similarity is
+meaningful and the rekey dimension guard (``old.d != embedding_dimension``)
+passes.
+
+Env (all optional, sensible defaults):
+ LDR_DATA_DIR disposable data dir shared with the server (REQUIRED in
+ practice; the run wrapper / CI step exports it).
+ LDR_MIGTEST_USER seeded username (default: migtest_user)
+ LDR_MIGTEST_PASS seeded password (default: MigTest!Secure#2026$LDR)
+
+Writes a manifest JSON to ``<LDR_DATA_DIR>/migtest_manifest.json`` (and prints
+it to stdout) for the node test to consume — it shares the filesystem with the
+server, so no path recomputation in JS is needed.
+"""
+
+import hashlib
+import json
+import os
+import sys
+import uuid
+from pathlib import Path
+
+from langchain_community.vectorstores import FAISS
+
+# --------------------------------------------------------------------------
+# Distinctive, unambiguous per-collection content. The tokens are what the
+# node test greps the on-disk sidecars/cache for (must be ABSENT — text-free)
+# and what the post-migration search must return (rehydrated from the DB).
+# --------------------------------------------------------------------------
+SECRET_A = "ZZZ_MIGTEST_ALPHA_LIGHTHOUSE_7a19f0"
+SECRET_B = "ZZZ_MIGTEST_BRAVO_SUBMARINE_3c82e1"
+
+EMBEDDING_MODEL = "all-MiniLM-L6-v2"
+EMBEDDING_PROVIDER = "sentence_transformers" # EmbeddingProvider enum .value
+EMBEDDING_DIM = 384
+
+
+def _make_legacy_index(dir_path: Path, ids, texts, embeddings, index_name):
+ """Write a REAL old-format ``<index_name>.faiss`` + plaintext
+ ``<index_name>.pkl`` pair, exactly as the pre-cutover LangChain-FAISS
+ wrapper did (mirrors tests/vector_stores' ``_make_legacy_index``)."""
+ dir_path.mkdir(parents=True, exist_ok=True)
+ metadatas = [{"chunk": i} for i in range(len(texts))]
+ vs = FAISS.from_texts(texts, embeddings, metadatas=metadatas, ids=ids)
+ vs.save_local(str(dir_path), index_name=index_name)
+
+
+def _index_hash(collection_name: str) -> str:
+ """The EXACT hash LibraryRAGService._get_index_hash computes."""
+ hash_input = f"{collection_name}:{EMBEDDING_MODEL}:{EMBEDDING_PROVIDER}"
+ return hashlib.sha256(hash_input.encode()).hexdigest()
+
+
+def _user_scope(username: str) -> str:
+ """The EXACT per-user subdir LibraryRAGService._get_index_path derives."""
+ return hashlib.sha256(username.encode("utf-8")).hexdigest()[:16]
+
+
+def main() -> int:
+ data_dir = os.environ.get("LDR_DATA_DIR")
+ if not data_dir:
+ print(
+ "FATAL: LDR_DATA_DIR must be set (a disposable dir shared with the "
+ "throwaway server) so phase-1 runs on the seeded .pkl.",
+ file=sys.stderr,
+ )
+ return 2
+ data_dir = Path(data_dir)
+ data_dir.mkdir(parents=True, exist_ok=True)
+ (data_dir / "encrypted_databases").mkdir(parents=True, exist_ok=True)
+
+ username = os.environ.get("LDR_MIGTEST_USER", "migtest_user")
+ password = os.environ.get(
+ "LDR_MIGTEST_PASS", "MigTest!Secure#2026$LDR"
+ ) # pragma: allowlist secret
+
+ # Import after LDR_DATA_DIR is settled so path resolution is correct.
+ from local_deep_research.config.paths import get_cache_directory
+ from local_deep_research.database.auth_db import (
+ get_auth_db_session,
+ init_auth_database,
+ )
+ from local_deep_research.database.encrypted_db import db_manager
+ from local_deep_research.database.models.auth import User
+ from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ EmbeddingProvider,
+ RAGIndex,
+ RagDocumentStatus,
+ SourceType,
+ )
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+ from local_deep_research.embeddings.embeddings_config import get_embeddings
+
+ # ---------------------------------------------------------------------
+ # 1. Auth user + encrypted per-user database (mirrors init_test_database).
+ # MUST run under the same KDF env as the server or login 401s.
+ # ---------------------------------------------------------------------
+ init_auth_database()
+ auth_session = get_auth_db_session()
+ try:
+ existing = auth_session.query(User).filter_by(username=username).first()
+ if existing is None:
+ auth_session.add(User(username=username))
+ auth_session.commit()
+ finally:
+ auth_session.close()
+
+ # Idempotent for a fresh disposable dir; create_user_database is a no-op /
+ # returns the existing DB if already present.
+ db_manager.create_user_database(username, password)
+
+ # Real all-MiniLM-L6-v2 embeddings — same model the server re-embeds the
+ # query with at search time. Building the vectors here also warms the HF
+ # cache the server reuses.
+ embeddings = get_embeddings(
+ provider=EMBEDDING_PROVIDER, model=EMBEDDING_MODEL
+ )
+
+ cache_root = get_cache_directory() / "rag_indices"
+ user_dir = cache_root / _user_scope(username)
+
+ manifest = {
+ "username": username,
+ "password": password,
+ "user_scope": _user_scope(username),
+ "cache_root": str(cache_root),
+ "user_dir": str(user_dir),
+ "collections": {},
+ }
+
+ # Two collections: A (primary, SECRET_A) and B (decoy, SECRET_B).
+ plan = [
+ {
+ "key": "A",
+ "name": "MigTest Alpha",
+ "secret": SECRET_A,
+ "texts": [
+ f"The alpha coastal lighthouse guided fishing vessels through "
+ f"fog for a century. Marker token {SECRET_A} appears here.",
+ f"A second alpha passage about the rotating lens and the "
+ f"keeper's leather-bound storm journal. {SECRET_A}",
+ ],
+ },
+ {
+ "key": "B",
+ "name": "MigTest Bravo",
+ "secret": SECRET_B,
+ "texts": [
+ f"The bravo research submarine mapped deep ocean trenches for "
+ f"decades. Marker token {SECRET_B} appears here.",
+ f"A second bravo passage about sonar arrays and the pressure "
+ f"hull's titanium plating. {SECRET_B}",
+ ],
+ },
+ ]
+
+ with get_user_db_session(username, password) as session:
+ # SourceType is FK'd by Document; get-or-create by unique name.
+ source_type = (
+ session.query(SourceType).filter_by(name="document").first()
+ )
+ if source_type is None:
+ source_type = SourceType(
+ id=uuid.uuid4().hex,
+ name="document",
+ display_name="Document",
+ )
+ session.add(source_type)
+ session.flush()
+
+ for spec in plan:
+ collection_id = uuid.uuid4().hex
+ collection_name = f"collection_{collection_id}"
+ index_hash = _index_hash(collection_name)
+ faiss_path = user_dir / f"{index_hash}.faiss"
+ pkl_path = user_dir / f"{index_hash}.pkl"
+ sidecar_path = user_dir / f"{index_hash}.idmap.json"
+
+ texts = spec["texts"]
+ uuids = [uuid.uuid4().hex for _ in texts]
+
+ # -- encrypted-DB rows --------------------------------------
+ session.add(
+ Collection(
+ id=collection_id,
+ name=spec["name"],
+ collection_type="user_collection",
+ )
+ )
+
+ doc_id = uuid.uuid4().hex
+ body = "\n\n".join(texts)
+ session.add(
+ Document(
+ id=doc_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(
+ f"{collection_id}:{body}".encode()
+ ).hexdigest(),
+ title=f"{spec['name']} document",
+ text_content=body,
+ filename=f"{spec['key'].lower()}_doc.txt",
+ file_size=len(body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+
+ for i, (u, text) in enumerate(zip(uuids, texts)):
+ session.add(
+ DocumentChunk(
+ chunk_hash=hashlib.sha256(
+ f"{u}:{text}".encode()
+ ).hexdigest(),
+ source_type="document",
+ source_id=doc_id,
+ collection_name=collection_name,
+ chunk_text=text,
+ chunk_index=i,
+ start_char=0,
+ end_char=len(text),
+ word_count=len(text.split()),
+ embedding_id=u, # MUST equal the .pkl id for rekey
+ embedding_model=EMBEDDING_MODEL,
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=EMBEDDING_DIM,
+ )
+ )
+
+ rag_index = RAGIndex(
+ collection_name=collection_name,
+ embedding_model=EMBEDDING_MODEL,
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=EMBEDDING_DIM,
+ index_path=str(faiss_path),
+ index_hash=index_hash,
+ chunk_size=1000,
+ chunk_overlap=200,
+ # Pin the physical-build config to the LibraryRAGService
+ # defaults so rekey/search never fall back to settings lookups.
+ index_type="flat",
+ distance_metric="cosine",
+ normalize_vectors=True,
+ is_current=True,
+ )
+ session.add(rag_index)
+ session.flush() # need rag_index.id for RagDocumentStatus
+
+ # DocumentCollection + RagDocumentStatus: without these the real
+ # HTTP search path returns [] before ever touching FAISS
+ # (get_rag_stats()['indexed_documents'] counts RagDocumentStatus).
+ session.add(
+ DocumentCollection(
+ document_id=doc_id,
+ collection_id=collection_id,
+ indexed=True,
+ chunk_count=len(texts),
+ )
+ )
+ session.add(
+ RagDocumentStatus(
+ document_id=doc_id,
+ collection_id=collection_id,
+ rag_index_id=rag_index.id,
+ chunk_count=len(texts),
+ )
+ )
+
+ # -- legacy on-disk .faiss + plaintext .pkl -----------------
+ _make_legacy_index(
+ user_dir, uuids, texts, embeddings, index_name=index_hash
+ )
+
+ # Control: the raw legacy pickle really DOES hold the plaintext
+ # marker (proves the node test's "text is gone" grep is not
+ # vacuously passing on a fixture that never had it).
+ pkl_bytes = pkl_path.read_bytes()
+ assert spec["secret"].encode() in pkl_bytes, (
+ f"fixture control failed: {spec['secret']} not in {pkl_path}"
+ )
+ assert faiss_path.is_file(), f"missing {faiss_path}"
+
+ manifest["collections"][spec["key"]] = {
+ "collection_id": collection_id,
+ "collection_name": collection_name,
+ "index_hash": index_hash,
+ "secret": spec["secret"],
+ "faiss": str(faiss_path),
+ "pkl": str(pkl_path),
+ "sidecar": str(sidecar_path),
+ "document_id": doc_id,
+ "embedding_ids": uuids,
+ }
+
+ session.commit()
+
+ manifest_path = data_dir / "migtest_manifest.json"
+ manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")
+
+ print(json.dumps(manifest, indent=2))
+ print(f"\nSeed complete. Manifest: {manifest_path}", file=sys.stderr)
+ print(
+ f"Legacy fixtures seeded under: {user_dir}\n"
+ f" A (SECRET_A) index_hash={manifest['collections']['A']['index_hash']}\n"
+ f" B (SECRET_B) index_hash={manifest['collections']['B']['index_hash']}",
+ file=sys.stderr,
+ )
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/ui_tests/test_legacy_pkl_migration_ci.js b/tests/ui_tests/test_legacy_pkl_migration_ci.js
new file mode 100644
index 0000000000..49c418129e
--- /dev/null
+++ b/tests/ui_tests/test_legacy_pkl_migration_ci.js
@@ -0,0 +1,370 @@
+/**
+ * Legacy plaintext-.pkl RAG migration — end-to-end UI test (library shard).
+ *
+ * PR #5143 replaced the old LangChain-FAISS wrapper (which pickled chunk TEXT
+ * into a plaintext `<hash>.pkl` docstore on disk, defeating the per-user
+ * SQLCipher DB encryption) with a raw faiss IndexIDMap2 keyed by integer
+ * DocumentChunk.id that keeps text ONLY in the encrypted DB. A two-phase
+ * migration removes the legacy plaintext .pkl:
+ *
+ * PHASE 1 migrate_legacy_docstores() — at WEB STARTUP. For each legacy
+ * `<hash>.pkl` it writes a TEXT-FREE `<hash>.idmap.json` sidecar
+ * (position->uuid map) and DELETES the `.pkl`.
+ * PHASE 2 rekey_user_indexes(user, pw) — at LOGIN. Rebuilds the IndexIDMap2
+ * from the sidecar keyed by DocumentChunk.id (NO re-embed) and
+ * removes the sidecar.
+ *
+ * This test drives the REAL migration through the running server. A Python
+ * pre-step (`seed_legacy_pkl_migration.py`, run BEFORE the server boots) seeds
+ * a realistic legacy `.faiss` + plaintext `.pkl` pair for TWO collections —
+ * primary A (SECRET_A) and decoy B (SECRET_B) — plus the matching encrypted-DB
+ * rows. The server's own startup then runs phase-1 on the seeded `.pkl`s; this
+ * test's login drives phase-2; and a real search proves the seeded content is
+ * still retrievable (text rehydrated from the encrypted DB by id).
+ *
+ * Assertions:
+ * - PHASE 1 (server already booted, before login):
+ * * the plaintext `<hash>.pkl` is GONE for both collections,
+ * * a TEXT-FREE `<hash>.idmap.json` sidecar EXISTS for both (valid JSON,
+ * position->uuid, no SECRET bytes),
+ * * NO file under the RAG cache contains SECRET_A/SECRET_B (plaintext
+ * gone from disk entirely — the `.pkl` held it, nothing else may).
+ * - PHASE 2 (after login triggers rekey):
+ * * both sidecars are consumed (gone).
+ * - END-TO-END search (real HTTP, rehydration by int id):
+ * * searching collection A returns SECRET_A and NOT the decoy SECRET_B,
+ * * searching collection B returns SECRET_B and NOT SECRET_A
+ * — the "extract the RIGHT file" proof (each `.pkl`'s map went into the
+ * correct sidecar, rebuilt into the correct collection's index keyed by
+ * the correct DocumentChunk.ids).
+ *
+ * On-disk assertions require this process to share the filesystem with the
+ * server (true locally, and in CI when the data dir is mounted into the test
+ * container). When the manifest/data dir is NOT accessible they are skipped
+ * with a clear notice and the HTTP search assertions (which need only the
+ * browser + server) still run.
+ *
+ * Registered in the `library` shard (tests/ui_tests/run_all_tests.js). Seed +
+ * boot ordering is handled by tests/ui_tests/run_legacy_pkl_migration.sh
+ * locally and a dedicated seed step in .github/workflows/docker-tests.yml.
+ *
+ * Server base URL: LDR_TEST_URL (default http://127.0.0.1:5000).
+ * Manifest path: LDR_MIGTEST_MANIFEST, else <LDR_DATA_DIR>/migtest_manifest.json.
+ */
+
+const fs = require("fs");
+const path = require("path");
+const puppeteer = require("puppeteer");
+const AuthHelper = require("./auth_helper");
+const {
+ getPuppeteerLaunchOptions,
+ takeScreenshot,
+} = require("./puppeteer_config");
+
+const BASE_URL = process.env.LDR_TEST_URL || "http://127.0.0.1:5000";
+
+function resolveManifestPath() {
+ if (process.env.LDR_MIGTEST_MANIFEST) {
+ return process.env.LDR_MIGTEST_MANIFEST;
+ }
+ const dataDir = process.env.LDR_DATA_DIR || "/tmp/ldr-migtest";
+ return path.join(dataDir, "migtest_manifest.json");
+}
+
+/** Recursively list every file under `dir` (returns [] if dir is missing). */
+function walkFiles(dir) {
+ const out = [];
+ let entries;
+ try {
+ entries = fs.readdirSync(dir, { withFileTypes: true });
+ } catch (_) {
+ return out;
+ }
+ for (const e of entries) {
+ const full = path.join(dir, e.name);
+ if (e.isDirectory()) {
+ out.push(...walkFiles(full));
+ } else if (e.isFile()) {
+ out.push(full);
+ }
+ }
+ return out;
+}
+
+/** Call the app's own API from inside the page (carries the session cookie +
+ * CSRF token read from the page's meta tag). */
+async function apiPost(page, url, payload) {
+ return page.evaluate(
+ async (u, body) => {
+ const meta = document.querySelector('meta[name="csrf-token"]');
+ const csrf = meta ? meta.getAttribute("content") : "";
+ const resp = await fetch(u, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ "X-CSRFToken": csrf,
+ },
+ body: JSON.stringify(body),
+ });
+ let parsed;
+ try {
+ parsed = await resp.json();
+ } catch (_) {
+ parsed = null;
+ }
+ return { ok: resp.ok, httpStatus: resp.status, body: parsed };
+ },
+ url,
+ payload,
+ );
+}
+
+async function runTests() {
+ const manifestPath = resolveManifestPath();
+ let manifest;
+ try {
+ manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
+ } catch (err) {
+ console.log(
+ ` ❌ could not read seed manifest at ${manifestPath}: ${err.message}`,
+ );
+ console.log(
+ " Run the seed (tests/ui_tests/seed_legacy_pkl_migration.py) " +
+ "under the same LDR_DATA_DIR BEFORE the server boots — see " +
+ "tests/ui_tests/run_legacy_pkl_migration.sh.",
+ );
+ process.exit(1);
+ }
+
+ const A = manifest.collections.A;
+ const B = manifest.collections.B;
+ const userDir = manifest.user_dir;
+ const cacheRoot = manifest.cache_root;
+ const SECRET_A = A.secret;
+ const SECRET_B = B.secret;
+
+ // Can this process see the server's on-disk files? (True locally; in CI
+ // only when the data dir is mounted into the test container.)
+ const diskShared = fs.existsSync(userDir) || fs.existsSync(cacheRoot);
+
+ let passed = 0;
+ let failed = 0;
+ const ok = (label) => {
+ passed += 1;
+ console.log(` ✅ ${label}`);
+ };
+ const fail = (label, detail) => {
+ failed += 1;
+ console.log(` ❌ ${label}${detail ? ` — ${detail}` : ""}`);
+ };
+
+ // ---- PHASE 1 on-disk assertions (server already booted) --------------
+ // These MUST be checked BEFORE login (phase-2 consumes the sidecars).
+ if (diskShared) {
+ for (const [key, c] of [
+ ["A", A],
+ ["B", B],
+ ]) {
+ if (fs.existsSync(c.pkl)) {
+ fail(
+ `phase-1: plaintext .pkl for collection ${key} still on disk`,
+ c.pkl,
+ );
+ } else {
+ ok(`phase-1: plaintext .pkl deleted for collection ${key}`);
+ }
+
+ if (!fs.existsSync(c.sidecar)) {
+ fail(
+ `phase-1: text-free sidecar missing for collection ${key}`,
+ c.sidecar,
+ );
+ } else {
+ const raw = fs.readFileSync(c.sidecar, "utf-8");
+ let mapObj;
+ try {
+ mapObj = JSON.parse(raw);
+ } catch (_) {
+ mapObj = null;
+ }
+ const isPosUuidMap =
+ mapObj &&
+ typeof mapObj === "object" &&
+ Object.keys(mapObj).length > 0 &&
+ Object.entries(mapObj).every(
+ ([k, v]) =>
+ /^\d+$/.test(k) &&
+ typeof v === "string" &&
+ /^[0-9a-f]{32}$|^[0-9a-f-]{36}$/i.test(v),
+ );
+ const textFree =
+ !raw.includes(SECRET_A) && !raw.includes(SECRET_B);
+ if (isPosUuidMap && textFree) {
+ ok(
+ `phase-1: text-free position->uuid sidecar written for collection ${key}`,
+ );
+ } else {
+ fail(
+ `phase-1: sidecar for collection ${key} is not a text-free position->uuid map`,
+ `isMap=${isPosUuidMap} textFree=${textFree}`,
+ );
+ }
+ }
+ }
+
+ // Whole-tree grep: NO on-disk artifact under the RAG cache may still
+ // contain the plaintext markers — the .pkl held them, and phase-1's
+ // guarantee is that nothing else does.
+ const leaking = walkFiles(cacheRoot).filter((f) => {
+ let bytes;
+ try {
+ bytes = fs.readFileSync(f);
+ } catch (_) {
+ return false;
+ }
+ return (
+ bytes.includes(Buffer.from(SECRET_A)) ||
+ bytes.includes(Buffer.from(SECRET_B))
+ );
+ });
+ if (leaking.length === 0) {
+ ok("phase-1: no plaintext SECRET bytes anywhere under the RAG cache");
+ } else {
+ fail(
+ "phase-1: plaintext SECRET bytes still present on disk",
+ leaking.join(", "),
+ );
+ }
+ } else {
+ console.log(
+ " ℹ️ data dir not shared with this process — skipping on-disk " +
+ "phase-1/phase-2 assertions; the HTTP search assertions below " +
+ "still prove the migration end to end.",
+ );
+ }
+
+ const browser = await puppeteer.launch(getPuppeteerLaunchOptions());
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1400, height: 900 });
+ page.on("dialog", async (d) => {
+ try {
+ await d.accept();
+ } catch (_) {
+ /* already handled */
+ }
+ });
+ page.on("console", (m) => {
+ if (m.type() === "error") {
+ console.log(" [browser console error]", m.text());
+ }
+ });
+
+ try {
+ // ---- Log in as the SEEDED user -> triggers phase-2 rekey at login --
+ const authHelper = new AuthHelper(page, BASE_URL);
+ await authHelper.login(manifest.username, manifest.password);
+ const activePage = authHelper.getPage();
+ ok(`logged in as seeded user ${manifest.username} (triggers phase-2)`);
+
+ // ---- PHASE 2 on-disk assertion: sidecars consumed by rekey ---------
+ if (diskShared) {
+ // Rekey runs in a post-login background path; give it a moment.
+ const deadline = Date.now() + 30000;
+ let aGone = false;
+ let bGone = false;
+ while (Date.now() < deadline) {
+ aGone = !fs.existsSync(A.sidecar);
+ bGone = !fs.existsSync(B.sidecar);
+ if (aGone && bGone) break;
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ if (aGone && bGone) {
+ ok("phase-2: both sidecars consumed (removed) by login-time rekey");
+ } else {
+ fail(
+ "phase-2: sidecar(s) not consumed after login",
+ `A gone=${aGone} B gone=${bGone}`,
+ );
+ }
+ }
+
+ // ---- END-TO-END search: RIGHT-file / no cross-contamination --------
+ // Navigate to a page with a CSRF meta tag (collection details).
+ await activePage.goto(
+ `${BASE_URL}/library/collections/${A.collection_id}`,
+ { waitUntil: "domcontentloaded", timeout: 30000 },
+ );
+
+ const searchA = await apiPost(
+ activePage,
+ `/library/api/collections/${A.collection_id}/search`,
+ {
+ query: "a coastal lighthouse guiding fishing boats through fog",
+ limit: 5,
+ },
+ );
+ const bodyA = JSON.stringify(searchA.body || {});
+ if (!searchA.ok) {
+ fail(
+ "search A failed",
+ `http ${searchA.httpStatus}: ${bodyA.slice(0, 200)}`,
+ );
+ } else if (bodyA.includes(SECRET_A) && !bodyA.includes(SECRET_B)) {
+ ok(
+ "search collection A returns SECRET_A and NOT the decoy SECRET_B " +
+ "(rehydrated by int id after rekey)",
+ );
+ } else {
+ fail(
+ "search A did not return the RIGHT content",
+ `hasA=${bodyA.includes(SECRET_A)} hasB=${bodyA.includes(
+ SECRET_B,
+ )}`,
+ );
+ }
+
+ const searchB = await apiPost(
+ activePage,
+ `/library/api/collections/${B.collection_id}/search`,
+ {
+ query: "a research submarine mapping deep ocean trenches with sonar",
+ limit: 5,
+ },
+ );
+ const bodyB = JSON.stringify(searchB.body || {});
+ if (!searchB.ok) {
+ fail(
+ "search B failed",
+ `http ${searchB.httpStatus}: ${bodyB.slice(0, 200)}`,
+ );
+ } else if (bodyB.includes(SECRET_B) && !bodyB.includes(SECRET_A)) {
+ ok(
+ "search collection B returns SECRET_B and NOT SECRET_A " +
+ "(the RIGHT .pkl was extracted into the RIGHT index)",
+ );
+ } else {
+ fail(
+ "search B did not return the RIGHT content",
+ `hasB=${bodyB.includes(SECRET_B)} hasA=${bodyB.includes(
+ SECRET_A,
+ )}`,
+ );
+ }
+ } catch (err) {
+ fail(err && err.message ? err.message : String(err));
+ try {
+ await takeScreenshot(page, "/tmp/legacy_pkl_migration_error.png");
+ } catch (_) {
+ /* best effort */
+ }
+ } finally {
+ await browser.close();
+ }
+
+ console.log(
+ `\n📊 Legacy .pkl migration E2E: ${passed} passed, ${failed} failed`,
+ );
+ process.exit(failed > 0 ? 1 : 0);
+}
+
+runTests();
diff --git a/tests/ui_tests/test_rag_index_search_ci.js b/tests/ui_tests/test_rag_index_search_ci.js
new file mode 100644
index 0000000000..9ab78cb634
--- /dev/null
+++ b/tests/ui_tests/test_rag_index_search_ci.js
@@ -0,0 +1,278 @@
+/**
+ * RAG collection: index + semantic-search — end-to-end UI test (library shard).
+ *
+ * Drives a real browser through the full library-RAG happy path against the
+ * live server and real endpoints:
+ *
+ * register/login
+ * -> create a collection (create form, UI)
+ * -> add a .txt document with known text (real upload endpoint)
+ * -> click "Index All Documents" and poll until indexing completes (UI)
+ * -> assert the collection reports >= 1 indexed document and >= 1 chunk (UI)
+ * -> run a semantic search and assert the document comes back (UI).
+ *
+ * This is the first browser-level test of the vector-store cutover's PRODUCTION
+ * path: it exercises embed -> FAISS write -> int-id-keyed store -> query embed
+ * -> rehydrate-by-id -> results, through the real routes and the RAG-specific UI
+ * (the Index button + the semantic-search box). The document-upload FORM UI is
+ * covered by other library-shard tests, so the upload step here hits the real
+ * upload endpoint directly (with the session cookie + CSRF token) to keep the
+ * setup robust and the assertions focused on indexing + search.
+ *
+ * Requires a working embedding provider on the server: the default is
+ * sentence-transformers + all-MiniLM-L6-v2 (a core dependency). The model must
+ * be available — on first use it is fetched from the HuggingFace hub (the
+ * default egress posture permits this); locally it lives in the HF cache. A
+ * one-time model warm-up before the server starts makes CI fast + network-
+ * independent. Indexing has NO embedder-free code path, so success proves the
+ * embedder ran end-to-end.
+ *
+ * Registered in the `library` shard (tests/ui_tests/run_all_tests.js). Server
+ * base URL is overridable via LDR_TEST_URL (defaults to the shard default).
+ */
+
+const puppeteer = require("puppeteer");
+const AuthHelper = require("./auth_helper");
+const {
+ getPuppeteerLaunchOptions,
+ takeScreenshot,
+} = require("./puppeteer_config");
+
+const BASE_URL = process.env.LDR_TEST_URL || "http://127.0.0.1:5000";
+
+// Distinctive, unambiguous content so the search assertion is meaningful.
+const DOC_FILENAME = "zephyrine_lighthouse.txt";
+const DOC_TEXT =
+ "The Zephyrine coastal lighthouse was built in 1887 on a granite " +
+ "headland. Its rotating lens guided fishing vessels safely through the " +
+ "fog for over a century, and the keeper logged every storm in a " +
+ "leather-bound journal.";
+// A semantically related query (NOT a substring) — exercises real embeddings,
+// not keyword matching.
+const SEARCH_QUERY = "a lighthouse guiding boats along the coast";
+// A word present in the indexed chunk text / title — confirms the returned
+// result is actually our document.
+const RESULT_NEEDLE = "lighthouse";
+
+function delay(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+/** Call the app's own API from inside the page (carries the session cookie). */
+async function apiFetch(page, url, options) {
+ return page.evaluate(
+ async (u, opts) => {
+ const resp = await fetch(u, opts || undefined);
+ let body;
+ try {
+ body = await resp.json();
+ } catch (_) {
+ body = null;
+ }
+ return { ok: resp.ok, httpStatus: resp.status, body };
+ },
+ url,
+ options || null,
+ );
+}
+
+/**
+ * Wait until a numeric stat element reads >= `min` (stats start as "-").
+ * Uses only plain comparisons in the page — the app's CSP forbids
+ * unsafe-eval, so no new Function()/eval() may run in page context.
+ */
+async function waitForStatAtLeast(page, selector, min, timeoutMs) {
+ await page.waitForFunction(
+ (sel, m) => {
+ const el = document.querySelector(sel);
+ if (!el) return false;
+ const txt = (el.textContent || "").trim().replace(/,/g, "");
+ return /^\d+$/.test(txt) && Number(txt) >= m;
+ },
+ { timeout: timeoutMs, polling: 500 },
+ selector,
+ min,
+ );
+}
+
+/**
+ * Poll the index status endpoint until the background indexing task reports the
+ * SUCCESS terminal ("completed"). Fails fast on an error terminal. "idle" and
+ * "processing" mean keep waiting ("idle" can appear briefly before the task row
+ * exists), so they are NOT treated as done.
+ */
+async function waitForIndexingComplete(page, collectionId, timeoutMs) {
+ const deadline = Date.now() + timeoutMs;
+ let last = "unknown";
+ while (Date.now() < deadline) {
+ const res = await apiFetch(
+ page,
+ `/library/api/collections/${collectionId}/index/status`,
+ );
+ const status = (res.body && res.body.status) || `http_${res.httpStatus}`;
+ last = status;
+ if (status === "completed") return;
+ if (["failed", "cancelled", "error"].includes(status)) {
+ const msg = (res.body && res.body.progress_message) || "";
+ throw new Error(`indexing ended in "${status}" ${msg}`);
+ }
+ await delay(2000);
+ }
+ throw new Error(
+ `indexing did not complete within ${timeoutMs}ms (last status "${last}")`,
+ );
+}
+
+async function runTests() {
+ const browser = await puppeteer.launch(getPuppeteerLaunchOptions());
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1400, height: 900 });
+
+ // The index button uses confirm(); success/error use alert(). Auto-accept so
+ // a click never blocks on a tab-modal dialog (see collection_details.js).
+ page.on("dialog", async (d) => {
+ try {
+ await d.accept();
+ } catch (_) {
+ /* dialog already handled */
+ }
+ });
+ page.on("console", (m) => {
+ if (m.type() === "error") {
+ console.log(" [browser console error]", m.text());
+ }
+ });
+
+ let passed = 0;
+ let failed = 0;
+ const ok = (label) => {
+ passed += 1;
+ console.log(` ✅ ${label}`);
+ };
+
+ try {
+ // ---- 0. Authenticate ----
+ const authHelper = new AuthHelper(page, BASE_URL);
+ await authHelper.ensureAuthenticated();
+ ok("authenticated");
+
+ // ---- 1. Create a collection via the create form ----
+ await page.goto(`${BASE_URL}/library/collections/create`, {
+ waitUntil: "domcontentloaded",
+ timeout: 30000,
+ });
+ await page.waitForSelector("#collection-name", {
+ visible: true,
+ timeout: 15000,
+ });
+ await page.type("#collection-name", `RAG E2E ${Date.now()}`);
+ await Promise.all([
+ // create posts JSON then redirects to /library/collections/<uuid>
+ page.waitForFunction(
+ () =>
+ /\/library\/collections\/[0-9a-fA-F-]{16,}$/.test(
+ location.pathname,
+ ),
+ { timeout: 30000 },
+ ),
+ page.click("#create-collection-btn"),
+ ]);
+ const collectionId = await page.evaluate(() =>
+ location.pathname.split("/").filter(Boolean).pop(),
+ );
+ if (!collectionId || collectionId === "create") {
+ throw new Error(`no collection id after create (got "${collectionId}")`);
+ }
+ ok(`created collection ${collectionId}`);
+
+ // ---- 2. Add a document via the real upload endpoint (session + CSRF) ----
+ // We're on the collection details page (base.html -> csrf meta present).
+ const uploadRes = await page.evaluate(
+ async (cid, filename, text) => {
+ const meta = document.querySelector('meta[name="csrf-token"]');
+ const csrf = meta ? meta.getAttribute("content") : "";
+ const fd = new FormData();
+ fd.append(
+ "files",
+ new File([text], filename, { type: "text/plain" }),
+ );
+ const r = await fetch(`/library/api/collections/${cid}/upload`, {
+ method: "POST",
+ headers: { "X-CSRFToken": csrf },
+ body: fd,
+ });
+ let body;
+ try {
+ body = await r.json();
+ } catch (_) {
+ body = null;
+ }
+ return { ok: r.ok, httpStatus: r.status, body };
+ },
+ collectionId,
+ DOC_FILENAME,
+ DOC_TEXT,
+ );
+ if (!uploadRes.ok) {
+ throw new Error(
+ `upload failed (http ${uploadRes.httpStatus}): ${JSON.stringify(
+ uploadRes.body,
+ )}`,
+ );
+ }
+ await page.reload({ waitUntil: "domcontentloaded", timeout: 30000 });
+ await waitForStatAtLeast(page, "#stat-total-docs", 1, 30000);
+ ok("document added (total docs >= 1)");
+
+ // ---- 3. Index the collection (UI button) + wait for completion ----
+ await page.waitForSelector("#index-collection-btn", {
+ visible: true,
+ timeout: 15000,
+ });
+ await page.click("#index-collection-btn"); // confirm() auto-accepted
+ await waitForIndexingComplete(page, collectionId, 180000);
+ ok("indexing completed");
+
+ // Stats reflect a real index build (chunk + embed + FAISS write).
+ await page.reload({ waitUntil: "domcontentloaded", timeout: 30000 });
+ await waitForStatAtLeast(page, "#stat-indexed-docs", 1, 30000);
+ await waitForStatAtLeast(page, "#stat-total-chunks", 1, 30000);
+ ok("collection reports >= 1 indexed document and >= 1 chunk");
+
+ // ---- 4. Semantic search returns the document (UI) ----
+ // The search section is revealed once an indexed item exists.
+ await page.waitForSelector("#collection-search-section", {
+ visible: true,
+ timeout: 20000,
+ });
+ await page.click("#collection-search-input");
+ await page.type("#collection-search-input", SEARCH_QUERY);
+ await page.click("#collection-search-btn");
+ // Results render async after the query embed + FAISS search + rehydrate.
+ await page.waitForFunction(
+ (needle) => {
+ const box = document.querySelector("#collection-search-results");
+ if (!box) return false;
+ return (box.innerText || "")
+ .toLowerCase()
+ .includes(needle.toLowerCase());
+ },
+ { timeout: 30000, polling: 500 },
+ RESULT_NEEDLE,
+ );
+ ok(`semantic search returned the document (matched "${RESULT_NEEDLE}")`);
+
+ console.log(`\n📊 RAG index+search UI: ${passed} passed, ${failed} failed`);
+ } catch (err) {
+ failed += 1;
+ console.log(` ❌ ${err && err.message ? err.message : err}`);
+ await takeScreenshot(page, "/tmp/rag_index_search_error.png");
+ console.log(`\n📊 RAG index+search UI: ${passed} passed, ${failed} failed`);
+ } finally {
+ await browser.close();
+ }
+
+ process.exit(failed > 0 ? 1 : 0);
+}
+
+runTests();
diff --git a/tests/utilities/test_close_base_llm.py b/tests/utilities/test_close_base_llm.py
index ffd11f2b42..ca9a561d41 100644
--- a/tests/utilities/test_close_base_llm.py
+++ b/tests/utilities/test_close_base_llm.py
@@ -727,7 +727,6 @@ class TestLibraryRAGServiceCloseOwnership:
svc._closed = False
svc.embedding_manager = external_manager
svc._owns_embedding_manager = False
- svc.faiss_index = None
svc.rag_index_record = None
svc.integrity_manager = None
svc.text_splitter = None
@@ -750,7 +749,6 @@ class TestLibraryRAGServiceCloseOwnership:
svc._closed = False
svc.embedding_manager = owned_manager
svc._owns_embedding_manager = True
- svc.faiss_index = None
svc.rag_index_record = None
svc.integrity_manager = None
svc.text_splitter = None
diff --git a/tests/vector_stores/test_config_provider_resolution.py b/tests/vector_stores/test_config_provider_resolution.py
new file mode 100644
index 0000000000..3a52107398
--- /dev/null
+++ b/tests/vector_stores/test_config_provider_resolution.py
@@ -0,0 +1,43 @@
+"""Protection tests for the vector-store provider registry/factory.
+
+``get_vector_store_class`` (``vector_stores/config.py``) is the single
+resolution entry point callers use to turn a provider key into a
+:class:`BaseVectorStore` subclass. Two invariants matter here:
+
+1. An unknown provider key must raise ``ValueError`` naming the bad key and
+ listing the valid providers — NOT silently fall back to a default class
+ (e.g. via a ``.get(key, FaissVectorStore)`` idiom).
+2. A "dirty" provider value (surrounding whitespace / wrapping quotes / mixed
+ case, as could arrive from a settings/DB value) is normalized the same way
+ ``embeddings_config.get_embeddings`` normalizes provider strings, and an
+ empty-string provider falls through to the default provider.
+"""
+
+import pytest
+
+from local_deep_research.vector_stores.config import (
+ VALID_VECTOR_STORE_PROVIDERS,
+ get_vector_store_class,
+)
+from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+)
+
+
+def test_get_vector_store_class_unknown_provider_raises_valueerror():
+ with pytest.raises(ValueError) as exc_info:
+ get_vector_store_class(provider="not_a_real_provider")
+
+ message = str(exc_info.value)
+ assert "not_a_real_provider" in message
+ for provider in VALID_VECTOR_STORE_PROVIDERS:
+ assert provider in message
+
+
+def test_get_vector_store_class_normalizes_dirty_provider():
+ dirty = ' "FAISS" '
+ assert get_vector_store_class(provider=dirty) is FaissVectorStore
+
+ # Empty-string provider is falsy -> falls through to resolve_provider's
+ # default, not treated as an (invalid) literal empty key.
+ assert get_vector_store_class(provider="") is FaissVectorStore
diff --git a/tests/vector_stores/test_cross_tenant_isolation.py b/tests/vector_stores/test_cross_tenant_isolation.py
new file mode 100644
index 0000000000..78ce8cdec7
--- /dev/null
+++ b/tests/vector_stores/test_cross_tenant_isolation.py
@@ -0,0 +1,300 @@
+"""Cross-TENANT isolation: two independent users, two independent (in-memory)
+DBs, two independent on-disk index directories, and — deliberately — COLLIDING
+integer ``DocumentChunk.id`` values (each user's DB is a fresh autoincrement
+sequence, so user A's first chunk and user B's first chunk both get id=1).
+
+The facade's search-time rehydration (``VectorIndex.search`` in
+``vector_stores/facade.py``) resolves a FAISS hit's int id to text by querying
+the CALLER's own DB session for a ``DocumentChunk`` row. There is no
+username/tenant column in that query — the isolation guarantee is structural:
+each user's ``VectorIndex`` is wired to open (or receive) ONLY that user's own
+DB session, so an id collision across tenants can never resolve to the wrong
+person's text. If a future refactor ever made ``get_user_db_session`` return a
+shared/global session, or made search fall back to some pooled session,
+colliding ids would silently rehydrate the WRONG tenant's secret text — this
+test is built so that regression fails loudly.
+
+Mirrors the real-components fixture style of
+``test_no_plaintext_production_path.py`` (fake deterministic network-free
+embeddings, real ``Base.metadata.create_all`` sqlite engine, real on-disk
+``VectorIndex``/``FaissVectorStore``), but parameterized per user: TWO
+engines/sessions and TWO index directories, with
+``vector_stores.facade.get_user_db_session`` patched to a small router that
+sends each username to its OWN session — exactly mirroring how, in
+production, each user's request is bound to their own SQLCipher-encrypted DB
+file.
+"""
+
+import threading
+from contextlib import contextmanager
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ DocumentChunk,
+ EmbeddingProvider,
+)
+from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+
+# Distinctive secrets, one per tenant. If isolation is broken, user B's search
+# results (or user B's on-disk index files) would contain user A's secret.
+SECRET_A = "ZZZ_TENANT_A_ONLY_SECRET_8f13ad02"
+SECRET_B = "ZZZ_TENANT_B_ONLY_SECRET_c4de9917"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings so the marker can never survive
+ into a vector as raw bytes (keeps any on-disk grep sound)."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _noop(_p):
+ return None
+
+
+def _ok(_p):
+ return (True, None)
+
+
+def _grep_all(root, needle: bytes):
+ """Every on-disk file under ``root`` that contains ``needle`` (raw bytes)."""
+ return [
+ str(f)
+ for f in root.rglob("*")
+ if f.is_file() and needle in f.read_bytes()
+ ]
+
+
+class _Tenant:
+ """One independent user's world: its own in-memory DB/session and its own
+ on-disk index directory, plumbed into a real ``VectorIndex``."""
+
+ def __init__(self, tmp_path, username: str, collection_name: str):
+ self.username = username
+ self.db_password = f"pw-{username}" # gitleaks:allow
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ self.session = sessionmaker(bind=engine)()
+ self.index_dir = tmp_path / username
+ self.index_dir.mkdir()
+ self.vi = VectorIndex(
+ username=username,
+ db_password=self.db_password,
+ embeddings=_FakeEmbeddings(dim=8),
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name=collection_name,
+ dimension=8,
+ path=self.index_dir / f"{collection_name}.faiss",
+ lock=threading.Lock(),
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+
+def tenants(tmp_path, mocker):
+ """Two tenants, SAME logical collection_name (so ids collide), each with
+ its own DB session and its own on-disk directory. ``get_user_db_session``
+ is patched at the facade's import site to route by username to the
+ correct tenant's session — mirroring how production binds a request to
+ the caller's own encrypted per-user DB.
+ """
+ a = _Tenant(tmp_path, "userA", collection_name="c")
+ b = _Tenant(tmp_path, "userB", collection_name="c")
+ by_username = {"userA": a.session, "userB": b.session}
+
+ @contextmanager
+ def _route_session(username=None, password=None):
+ yield by_username[username]
+
+ mocker.patch(
+ "local_deep_research.vector_stores.facade.get_user_db_session",
+ _route_session,
+ )
+
+ yield a, b
+
+ a.session.close()
+ b.session.close()
+
+
+def test_colliding_ids_do_not_cross_tenant_boundary(tenants):
+ """Sanity precondition: both tenants really do get DocumentChunk.id == 1
+ (separate DBs => separate autoincrement sequences). Without this, the
+ "isolation despite colliding ids" claim below would be vacuous."""
+ a, b = tenants
+ a.vi.index(
+ source_type="document",
+ source_id="doc-a",
+ chunks=[ChunkInput(text=f"User A's private note: {SECRET_A}")],
+ )
+ b.vi.index(
+ source_type="document",
+ source_id="doc-b",
+ chunks=[ChunkInput(text=f"User B's private note: {SECRET_B}")],
+ )
+
+ a_row = a.session.query(DocumentChunk).filter_by(source_id="doc-a").one()
+ b_row = b.session.query(DocumentChunk).filter_by(source_id="doc-b").one()
+ assert a_row.id == 1
+ assert b_row.id == 1, (
+ "precondition failed: tenants' chunk ids do not collide, so this "
+ "test cannot exercise the cross-tenant rehydration boundary"
+ )
+
+
+def test_search_in_tenant_b_never_returns_or_rehydrates_tenant_a_secret(
+ tenants,
+):
+ a, b = tenants
+ a.vi.index(
+ source_type="document",
+ source_id="doc-a",
+ chunks=[ChunkInput(text=f"User A's private note: {SECRET_A}")],
+ )
+ b.vi.index(
+ source_type="document",
+ source_id="doc-b",
+ chunks=[ChunkInput(text=f"User B's private note: {SECRET_B}")],
+ )
+ # Confirm the id collision this test is meant to stress.
+ a_row = a.session.query(DocumentChunk).filter_by(source_id="doc-a").one()
+ b_row = b.session.query(DocumentChunk).filter_by(source_id="doc-b").one()
+ assert a_row.id == b_row.id == 1
+
+ # A broad query run entirely inside user B's world (B's VectorIndex, which
+ # is wired only to B's own DB session and B's own on-disk store).
+ results = b.vi.search("private note", top_k=10)
+
+ assert results, "expected user B's own chunk to be found"
+ assert all(SECRET_A not in r.text for r in results), (
+ "user A's secret leaked into user B's search results despite a "
+ "colliding DocumentChunk.id across the two tenants' separate DBs"
+ )
+ assert all(SECRET_B in r.text or r.text == "" for r in results)
+ # And it really did surface user B's own content (the assertion above
+ # isn't vacuously true because search returned nothing relevant).
+ assert any(SECRET_B in r.text for r in results)
+
+ # Sanity check the assertion actually bites: if B's rehydration query were
+ # NOT scoped to B's own session (e.g. searched a shared/global session
+ # containing both rows), asking A's session for the same id DOES return
+ # A's secret-bearing row — proving the guard is doing real work, not
+ # trivially passing because the row doesn't exist anywhere.
+ cross_row = a.session.query(DocumentChunk).filter_by(id=b_row.id).one()
+ assert SECRET_A in cross_row.chunk_text
+
+
+def test_tenant_a_secret_never_appears_on_disk_under_tenant_b_index_dir(
+ tenants,
+):
+ a, b = tenants
+ a.vi.index(
+ source_type="document",
+ source_id="doc-a",
+ chunks=[ChunkInput(text=f"User A's private note: {SECRET_A}")],
+ )
+ b.vi.index(
+ source_type="document",
+ source_id="doc-b",
+ chunks=[ChunkInput(text=f"User B's private note: {SECRET_B}")],
+ )
+ b.vi.search("private note", top_k=10) # exercise B's read path too
+
+ # B's on-disk store directory must contain no trace of A's secret. (The
+ # store only ever holds vectors + int ids regardless of tenant, so this
+ # mainly guards against a future regression that writes text/metadata
+ # sidecars per tenant directory.)
+ leaked = _grep_all(b.index_dir, SECRET_A.encode())
+ assert leaked == [], (
+ f"user A's secret leaked onto disk under user B's index dir: {leaked}"
+ )
+
+ # Sanity: the grep itself is capable of finding a real hit (proves the
+ # helper isn't silently vacuous) — user B's OWN secret is not expected to
+ # be on disk either (store holds no text), but B's index FILE must exist.
+ faiss_file = b.index_dir / "c.faiss"
+ assert faiss_file.is_file()
+ assert faiss_file.stat().st_size > 0
+
+
+def test_delete_ids_cross_tenant_never_deletes_other_tenants_row_on_colliding_id(
+ tenants,
+):
+ """``delete_ids`` is the destructive path a caller uses to batch-clean
+ vectors after already deleting DocumentChunk rows elsewhere (see its
+ docstring in ``facade.py``). It re-runs ``_finalize_db`` -> a raw
+ ``DocumentChunk.id.in_(ids)`` delete with NO tenant/username column in the
+ filter — isolation depends entirely on the routed session (``self._db``)
+ only ever being the CALLING VectorIndex's own session/store. Both tenants'
+ first chunk lands on the SAME numeric id (fresh autoincrement per DB), so
+ if ``delete_ids`` were ever called against the wrong session — or a future
+ refactor made ``get_user_db_session`` return something shared — user B's
+ call would destroy user A's row/vector too.
+ """
+ a, b = tenants
+ a.vi.index(
+ source_type="document",
+ source_id="doc-a",
+ chunks=[ChunkInput(text=f"User A's private note: {SECRET_A}")],
+ )
+ b.vi.index(
+ source_type="document",
+ source_id="doc-b",
+ chunks=[ChunkInput(text=f"User B's private note: {SECRET_B}")],
+ )
+ a_row = a.session.query(DocumentChunk).filter_by(source_id="doc-a").one()
+ b_row = b.session.query(DocumentChunk).filter_by(source_id="doc-b").one()
+ assert a_row.id == b_row.id == 1, (
+ "precondition failed: tenants' chunk ids do not collide, so this "
+ "test cannot exercise the cross-tenant delete_ids boundary"
+ )
+ assert a.vi.count() == 1
+ assert b.vi.count() == 1
+
+ # User B deletes ITS OWN chunk id (which numerically collides with A's).
+ stats = b.vi.delete_ids([b_row.id])
+ assert stats.rows_deleted == 1
+ assert stats.removed == 1
+
+ # B's own row/vector is gone.
+ assert (
+ b.session.query(DocumentChunk).filter_by(id=b_row.id).one_or_none()
+ is None
+ )
+ assert b.vi.count() == 0
+ assert b.vi.search("private note", top_k=10) == []
+
+ # User A's row, with the SAME numeric id, must be completely untouched:
+ # still in A's DB, still text-intact, still vector-searchable, and A's
+ # on-disk store still holds it.
+ surviving_a_row = (
+ a.session.query(DocumentChunk).filter_by(id=a_row.id).one()
+ )
+ assert SECRET_A in surviving_a_row.chunk_text
+ assert a.vi.count() == 1
+ a_results = a.vi.search("private note", top_k=10)
+ assert any(SECRET_A in r.text for r in a_results), (
+ "user B's delete_ids([1]) deleted user A's colliding-id row/vector"
+ )
diff --git a/tests/vector_stores/test_facade.py b/tests/vector_stores/test_facade.py
new file mode 100644
index 0000000000..4f8ab6c93a
--- /dev/null
+++ b/tests/vector_stores/test_facade.py
@@ -0,0 +1,746 @@
+"""Unit tests for ``VectorIndex`` (``vector_stores/facade.py``).
+
+Needs a real DB (in-memory SQLite, ``Base.metadata.create_all``) because the
+facade is the one module that bridges the vector store to ``DocumentChunk``
+rows. Mirrors the DB-session mocking pattern used in
+``tests/research_library/conftest.py`` (``mock_db_session_context``) /
+``tests/research_library/routes/test_rag_routes.py``, but patches
+``get_user_db_session`` at its ``vector_stores.facade`` import site (the
+facade module's own binding), not at ``database.session_context`` — the
+facade imports the name directly, so patching the origin module would not
+affect calls made from inside ``facade.py``.
+"""
+
+import threading
+from contextlib import contextmanager
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ DocumentChunk,
+ EmbeddingProvider,
+)
+from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+
+
+# --------------------------------------------------------------------------
+# DB fixtures (mirrors tests/research_library/conftest.py's
+# library_engine / library_session / mock_db_session_context)
+# --------------------------------------------------------------------------
+def engine():
+ e = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(e)
+ yield e
+ e.dispose()
+
+
+def db_session(engine):
+ session_local = sessionmaker(bind=engine)
+ s = session_local()
+ yield s
+ s.close()
+
+
+def patched_db(db_session, mocker):
+ """Patch ``get_user_db_session`` at the facade's own import site so
+ ``VectorIndex._db()`` (which opens its own session when the caller
+ doesn't pass one) gets our in-memory test session instead of a real
+ encrypted DB connection."""
+
+ @contextmanager
+ def _mock_session(*_args, **_kwargs):
+ yield db_session
+
+ mocker.patch(
+ "local_deep_research.vector_stores.facade.get_user_db_session",
+ _mock_session,
+ )
+ return db_session
+
+
+# --------------------------------------------------------------------------
+# Deterministic fake Embeddings (no model download, no network)
+# --------------------------------------------------------------------------
+class _FakeEmbeddings(Embeddings):
+ """Deterministic per-text vector: hash the text into a small int seed
+ so identical text always embeds identically and different text embeds
+ differently (good enough for exercising store add/search, not for
+ testing embedding *quality*)."""
+
+ def __init__(self, dim: int = 4):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ seed = abs(hash(text)) % (2**32)
+ rng = np.random.default_rng(seed)
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _noop(_p):
+ return None
+
+
+def _ok(_p):
+ return (True, None)
+
+
+def _make_index(
+ tmp_path,
+ *,
+ dimension=4,
+ collection_name="c1",
+ metric="cosine",
+ index_type="flat",
+ normalize=True,
+):
+ return VectorIndex(
+ username="testuser",
+ db_password="pw",
+ embeddings=_FakeEmbeddings(dim=dimension),
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name=collection_name,
+ dimension=dimension,
+ path=tmp_path / f"{collection_name}.faiss",
+ lock=threading.Lock(),
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+
+
+# --------------------------------------------------------------------------
+# index()
+# --------------------------------------------------------------------------
+class TestIndex:
+ def test_index_writes_rows_with_int_pks_and_vectors(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ chunks = [
+ ChunkInput(text="hello world", metadata={"chunk_index": 0}),
+ ChunkInput(text="second chunk", metadata={"chunk_index": 1}),
+ ]
+ stats = vi.index(
+ source_type="document", source_id="doc1", chunks=chunks
+ )
+
+ assert stats.chunks == 2
+ assert stats.added == 2
+ assert stats.removed == 0
+
+ rows = (
+ patched_db.query(DocumentChunk)
+ .filter_by(source_type="document", source_id="doc1")
+ .all()
+ )
+ assert len(rows) == 2
+ assert all(isinstance(r.id, int) for r in rows)
+ assert vi.count() == 2
+ assert set(vi._store.live_ids()) == {r.id for r in rows}
+
+ def test_index_empty_chunks_is_noop(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ stats = vi.index(source_type="document", source_id="d1", chunks=[])
+ assert stats.chunks == 0
+ assert stats.added == 0
+ assert vi.count() == 0
+
+ def test_index_replace_true_purges_prior_chunks(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="old1"), ChunkInput(text="old2")],
+ )
+ assert vi.count() == 2
+
+ stats = vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="new1")],
+ replace=True,
+ )
+ assert stats.removed == 2
+ assert stats.added == 1
+ assert vi.count() == 1
+
+ rows = patched_db.query(DocumentChunk).filter_by(source_id="d1").all()
+ assert len(rows) == 1
+ assert rows[0].chunk_text == "new1"
+
+ def test_index_replace_true_empty_chunks_purges_prior(
+ self, tmp_path, patched_db
+ ):
+ # Re-indexing a source down to ZERO chunks (e.g. a note edited to
+ # whitespace) with replace=True must still remove its prior
+ # vectors/rows — otherwise the cleared content stays searchable.
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="old1"), ChunkInput(text="old2")],
+ )
+ assert vi.count() == 2
+
+ stats = vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[],
+ replace=True,
+ )
+ assert stats.removed == 2
+ assert stats.added == 0
+ assert vi.count() == 0
+ assert (
+ patched_db.query(DocumentChunk).filter_by(source_id="d1").count()
+ == 0
+ )
+
+ def test_index_replace_false_appends(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="a")],
+ )
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="b")],
+ replace=False,
+ )
+ assert vi.count() == 2
+ assert (
+ patched_db.query(DocumentChunk).filter_by(source_id="d1").count()
+ == 2
+ )
+
+ def test_index_replace_does_not_touch_other_sources(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="d1 chunk")],
+ )
+ vi.index(
+ source_type="document",
+ source_id="d2",
+ chunks=[ChunkInput(text="d2 chunk")],
+ replace=True,
+ )
+ assert vi.count() == 2
+ assert (
+ patched_db.query(DocumentChunk).filter_by(source_id="d1").count()
+ == 1
+ )
+
+ def test_index_rolls_back_db_on_apply_failure(
+ self, tmp_path, patched_db, mocker
+ ):
+ """If store.apply() raises, the flushed-but-uncommitted DocumentChunk
+ rows must be rolled back — no row can point at a missing vector."""
+ vi = _make_index(tmp_path)
+ mocker.patch.object(
+ vi._store, "apply", side_effect=RuntimeError("boom")
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="z")],
+ )
+
+ assert patched_db.query(DocumentChunk).count() == 0
+
+ def test_index_duplicate_text_chunks_produce_two_rows_and_vectors(
+ self, tmp_path, patched_db
+ ):
+ """0023 deliberately dropped the ``chunk_hash`` unique constraint so
+ identical text produces one row PER chunk (no cross-document
+ sharing). Guards against a reintroduced unique constraint or an
+ accidental hash-dedup short-circuit in ``index()``/``_build_row``."""
+ vi = _make_index(tmp_path)
+ chunks = [
+ ChunkInput(text="same text"),
+ ChunkInput(text="same text"),
+ ]
+ stats = vi.index(source_type="document", source_id="d1", chunks=chunks)
+
+ assert stats.added == 2
+
+ rows = patched_db.query(DocumentChunk).filter_by(source_id="d1").all()
+ assert len(rows) == 2
+ assert rows[0].chunk_hash == rows[1].chunk_hash
+ assert rows[0].id != rows[1].id
+ assert vi.count() == 2
+
+ def test_index_uses_caller_provided_session_without_committing(
+ self, tmp_path, db_session, mocker
+ ):
+ """When the caller passes its own session, VectorIndex must not
+ commit/rollback it (the caller owns the transaction boundary)."""
+ vi = _make_index(tmp_path)
+ commit_spy = mocker.spy(db_session, "commit")
+
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="a")],
+ session=db_session,
+ )
+
+ commit_spy.assert_not_called()
+ # Row is visible via flush() even though nothing committed yet.
+ assert db_session.query(DocumentChunk).count() == 1
+
+
+# --------------------------------------------------------------------------
+# search()
+# --------------------------------------------------------------------------
+class TestSearch:
+ def test_search_rehydrates_text_and_metadata_from_db(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[
+ ChunkInput(text="alpha text", metadata={"k": "v"}),
+ ChunkInput(text="beta text"),
+ ],
+ )
+
+ results = vi.search("alpha", top_k=5)
+
+ assert len(results) == 2
+ texts = {r.text for r in results}
+ assert texts == {"alpha text", "beta text"}
+ alpha = next(r for r in results if r.text == "alpha text")
+ assert alpha.metadata == {"k": "v"}
+
+ def test_search_skips_orphan_hit_missing_db_row(self, tmp_path, patched_db):
+ """A vector whose DocumentChunk row was deleted out-of-band (DB
+ write succeeded, e.g. a caller cleaned up the row without going
+ through VectorIndex.delete) must be skipped, not crash or fabricate
+ text."""
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[
+ ChunkInput(text="alpha text"),
+ ChunkInput(text="beta text"),
+ ],
+ )
+ orphan_row = (
+ patched_db.query(DocumentChunk)
+ .filter_by(chunk_text="beta text")
+ .one()
+ )
+ patched_db.query(DocumentChunk).filter(
+ DocumentChunk.id == orphan_row.id
+ ).delete()
+ patched_db.commit()
+ # The vector for "beta text" is still live in the store.
+ assert orphan_row.id in vi._store.live_ids()
+
+ results = vi.search("alpha", top_k=5)
+
+ assert len(results) == 1
+ assert results[0].text == "alpha text"
+
+ def test_search_does_not_leak_other_collections_text(
+ self, tmp_path, patched_db
+ ):
+ """A vector in THIS collection's store whose id belongs to a chunk in a
+ DIFFERENT collection (orphan + reused id) must NOT rehydrate that other
+ collection's text — rehydration is scoped to this collection."""
+ c1 = _make_index(tmp_path, collection_name="c1")
+ c2 = _make_index(tmp_path, collection_name="c2")
+ # A chunk indexed into c2.
+ c2.index(
+ source_type="document",
+ source_id="d2",
+ chunks=[ChunkInput(text="c2 SECRET text")],
+ )
+ c2_chunk = (
+ patched_db.query(DocumentChunk)
+ .filter_by(collection_name="c2")
+ .one()
+ )
+ # That SAME id sits as an orphan vector in c1's store (e.g. a
+ # rolled-back insert whose id was later reused by c2).
+ c1._store.apply(
+ add_ids=[c2_chunk.id],
+ add_vectors=np.ones((1, 4), dtype="float32"),
+ )
+ assert c2_chunk.id in c1._store.live_ids()
+
+ results = c1.search("anything", top_k=5)
+ # c2's text must NOT appear in c1's search results.
+ assert all("c2 SECRET" not in r.text for r in results)
+
+ def test_search_top_k_zero_returns_empty(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="a")],
+ )
+ assert vi.search("a", top_k=0) == []
+
+ def test_search_result_metric_matches_collection_metric(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path, metric="l2", normalize=False)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="only")],
+ )
+ results = vi.search("only", top_k=1)
+ assert results[0].metric == "l2"
+
+ def test_search_result_metric_cosine(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path, metric="cosine", normalize=True)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="only")],
+ )
+ results = vi.search("only", top_k=1)
+ assert results[0].metric == "cosine"
+
+ def test_search_preserves_relevance_order_through_rehydration_with_orphan_in_middle(
+ self, tmp_path, patched_db
+ ):
+ """The facade must return hits in the STORE's relevance order (best
+ match first), not in whatever order the DB round-trip happens to
+ yield — a refactor that iterated ``rows.values()`` (an IN-query
+ keyed by id, with no ORDER BY) instead of ``hits`` would silently
+ scramble the result order. ``top_k`` truncates below the chunk
+ count, and the middle-ranked surviving hit's row is deleted
+ out-of-band (orphan) to prove the remaining hits still resolve in
+ relevance order around the gap, with no crash and no leaked text.
+ """
+ import math
+
+ class _AngleEmbeddings(Embeddings):
+ """Deterministic 2-D unit vectors at a fixed angle per text, so
+ cosine similarity to a theta=0 query is exactly ordered by the
+ angle table below — precise, reproducible ranking (no hashing).
+ """
+
+ _ANGLES_DEG = {
+ "sim-high": 0,
+ "sim-2nd": 10,
+ "sim-3rd": 20,
+ "sim-low": 30,
+ }
+
+ def _vec(self, text):
+ theta = math.radians(self._ANGLES_DEG[text])
+ return [math.cos(theta), math.sin(theta)]
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, _text):
+ return [1.0, 0.0]
+
+ vi = VectorIndex(
+ username="testuser",
+ db_password="pw",
+ embeddings=_AngleEmbeddings(),
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name="c-order",
+ dimension=2,
+ path=tmp_path / "c-order.faiss",
+ lock=threading.Lock(),
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ # Insertion order deliberately scrambled relative to similarity
+ # rank, so PK order != relevance order.
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[
+ ChunkInput(text="sim-low"),
+ ChunkInput(text="sim-3rd"),
+ ChunkInput(text="sim-high"),
+ ChunkInput(text="sim-2nd"),
+ ],
+ )
+
+ mid_row = (
+ patched_db.query(DocumentChunk)
+ .filter_by(chunk_text="sim-2nd")
+ .one()
+ )
+ patched_db.query(DocumentChunk).filter(
+ DocumentChunk.id == mid_row.id
+ ).delete()
+ patched_db.commit()
+ # The vector for "sim-2nd" is still live in the store (orphan).
+ assert mid_row.id in vi._store.live_ids()
+
+ results = vi.search("query", top_k=3)
+
+ # "sim-low" (rank 4) is truncated by top_k=3. "sim-2nd" (rank 2, the
+ # middle of the top-3) is the orphan and must be skipped, not
+ # crash/leak. The survivors must come back in the STORE's relevance
+ # order — sim-high then sim-3rd — NOT PK order ("sim-3rd" was
+ # flushed to a lower PK than "sim-high", so a rows.values()-order
+ # bug would emit them reversed).
+ assert [r.text for r in results] == ["sim-high", "sim-3rd"]
+
+ def test_search_carries_source_and_title_fields(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="doc-42",
+ chunks=[ChunkInput(text="titled chunk", metadata={"title": "T"})],
+ )
+ results = vi.search("titled", top_k=1)
+ assert results[0].source_type == "document"
+ assert results[0].source_id == "doc-42"
+ assert results[0].document_title == "T"
+
+
+# --------------------------------------------------------------------------
+# delete()
+# --------------------------------------------------------------------------
+class TestDelete:
+ def test_delete_removes_vectors_and_rows(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="x"), ChunkInput(text="y")],
+ )
+ assert vi.count() == 2
+
+ stats = vi.delete(source_type="document", source_id="d1")
+
+ assert stats.removed == 2
+ assert stats.rows_deleted == 2
+ assert vi.count() == 0
+ assert (
+ patched_db.query(DocumentChunk).filter_by(source_id="d1").count()
+ == 0
+ )
+
+ def test_delete_nonexistent_source_is_zero_noop(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ stats = vi.delete(source_type="document", source_id="missing")
+ assert stats == type(stats)(removed=0, rows_deleted=0)
+
+ def test_delete_rolls_back_db_on_apply_failure(
+ self, tmp_path, patched_db, mocker
+ ):
+ """Mirrors ``test_index_rolls_back_db_on_apply_failure`` for
+ ``delete()``: if ``store.apply()`` raises, the rows targeted for
+ removal must survive (no data loss) and the exception must
+ propagate. Also guards #3827: the owned session must remain usable
+ for later calls, not left broken by the failed rollback."""
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="x"), ChunkInput(text="y")],
+ )
+ assert vi.count() == 2
+
+ mocker.patch.object(
+ vi._store, "apply", side_effect=RuntimeError("boom")
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ vi.delete(source_type="document", source_id="d1")
+
+ # No data loss: both target rows survive the failed delete.
+ assert (
+ patched_db.query(DocumentChunk).filter_by(source_id="d1").count()
+ == 2
+ )
+
+ # #3827: the (shared, thread-local) session VectorIndex owns must
+ # still be usable afterward — not left in a broken transaction
+ # state by the failed rollback. Prove it with an unrelated,
+ # unpatched index() call reusing the same session.
+ vi2 = _make_index(tmp_path, collection_name="c2")
+ stats = vi2.index(
+ source_type="document",
+ source_id="d2",
+ chunks=[ChunkInput(text="z")],
+ )
+ assert stats.added == 1
+ assert (
+ patched_db.query(DocumentChunk).filter_by(source_id="d2").count()
+ == 1
+ )
+
+ def test_delete_with_caller_session_survives_apply_failure(
+ self, tmp_path, db_session, mocker
+ ):
+ """delete()'s except-branch only rolls back ``if owns`` (facade
+ ~470). When the CALLER passes its own session (``owns=False``), a
+ ``store.apply()`` failure must NOT roll back the caller's session —
+ that would wipe the caller's other, unrelated uncommitted work too.
+ A plausible mirror-of-``index()`` refactor that dropped the ``if
+ owns:`` guard (unconditional rollback) would wipe both the
+ unrelated pending row and the still-uncommitted d1 row, failing the
+ assertions below.
+ """
+ vi = _make_index(tmp_path)
+ # Index d1 using the CALLER's own session -> owns=False inside
+ # index(), so it does not commit; the row stays pending.
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="x")],
+ session=db_session,
+ )
+ d1_row = db_session.query(DocumentChunk).filter_by(source_id="d1").one()
+
+ # Unrelated pending row in the SAME caller transaction, simulating
+ # other work the caller is doing that must survive a delete()
+ # failure elsewhere in that same transaction.
+ x_row = DocumentChunk(
+ chunk_hash="x" * 64,
+ source_type="document",
+ source_id="unrelated-x",
+ collection_name=vi.collection_name,
+ chunk_text="unrelated pending row",
+ chunk_index=0,
+ start_char=0,
+ end_char=10,
+ word_count=2,
+ embedding_id="unrelated-x-embedding-id",
+ embedding_model=vi.embedding_model,
+ embedding_model_type=vi.embedding_model_type,
+ embedding_dimension=vi._store.dimension,
+ )
+ db_session.add(x_row)
+ db_session.flush()
+ x_id = x_row.id
+
+ mocker.patch.object(
+ vi._store, "apply", side_effect=RuntimeError("boom")
+ )
+
+ with pytest.raises(RuntimeError, match="boom"):
+ vi.delete(
+ source_type="document", source_id="d1", session=db_session
+ )
+
+ # DATA SURVIVAL, not a rollback spy: both the unrelated pending row
+ # X and the still-uncommitted d1 row must still be queryable in
+ # THIS session -- delete() must not have rolled it back.
+ assert (
+ db_session.query(DocumentChunk).filter_by(id=x_id).one().chunk_text
+ == "unrelated pending row"
+ )
+ assert (
+ db_session.query(DocumentChunk)
+ .filter_by(id=d1_row.id)
+ .one()
+ .chunk_text
+ == "x"
+ )
+
+ def test_index_then_delete_invariant_zero_state(self, tmp_path, patched_db):
+ """After index()-then-delete() of the same source, both the store
+ and the DB must be empty — no leftover vectors or rows."""
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text=f"c{i}") for i in range(5)],
+ )
+ vi.delete(source_type="document", source_id="d1")
+
+ assert vi.count() == 0
+ assert patched_db.query(DocumentChunk).count() == 0
+
+
+class TestDeleteIds:
+ """``delete_ids`` — used by the zotero sync path to remove specific
+ chunk ids whose rows may already be gone by the time it runs."""
+
+ def test_delete_ids_removes_specific_vectors_and_rows(
+ self, tmp_path, patched_db
+ ):
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="a"), ChunkInput(text="b")],
+ )
+ rows = patched_db.query(DocumentChunk).filter_by(source_id="d1").all()
+ ids = sorted(r.id for r in rows)
+
+ stats = vi.delete_ids([ids[0]])
+
+ assert stats.removed == 1
+ assert stats.rows_deleted == 1
+ assert vi.count() == 1
+ assert (
+ patched_db.query(DocumentChunk).filter_by(id=ids[0]).first() is None
+ )
+
+ def test_delete_ids_empty_is_noop(self, tmp_path, patched_db):
+ vi = _make_index(tmp_path)
+ stats = vi.delete_ids([])
+ assert stats.removed == 0
+ assert stats.rows_deleted == 0
+
+ def test_delete_ids_tolerates_rows_already_gone(self, tmp_path, patched_db):
+ """The ids' DocumentChunk rows may already be deleted elsewhere by
+ the time this runs (see the docstring on delete_ids) — the vector
+ removal must still happen."""
+ vi = _make_index(tmp_path)
+ vi.index(
+ source_type="document",
+ source_id="d1",
+ chunks=[ChunkInput(text="a")],
+ )
+ row = patched_db.query(DocumentChunk).filter_by(source_id="d1").one()
+ chunk_id = row.id
+ patched_db.query(DocumentChunk).filter(
+ DocumentChunk.id == chunk_id
+ ).delete()
+ patched_db.commit()
+ assert chunk_id in vi._store.live_ids()
+
+ stats = vi.delete_ids([chunk_id])
+
+ assert stats.removed == 1
+ assert stats.rows_deleted == 0 # row was already gone
+ assert vi.count() == 0
diff --git a/tests/vector_stores/test_facade_load.py b/tests/vector_stores/test_facade_load.py
new file mode 100644
index 0000000000..d4defc3275
--- /dev/null
+++ b/tests/vector_stores/test_facade_load.py
@@ -0,0 +1,63 @@
+"""Regression: VectorIndex must LOAD an existing on-disk index without error.
+
+Guards a real bug where __init__ passed `path` both positionally and via the
+kwargs dict to the store's load(), raising
+`TypeError: got multiple values for argument 'path'` — which broke every search
+and every 2nd index/delete on an existing collection.
+"""
+
+import threading
+
+import numpy as np
+
+from src.local_deep_research.vector_stores import get_vector_store_class
+from src.local_deep_research.vector_stores.facade import VectorIndex
+
+
+def _noop(_p):
+ return None
+
+
+def _ok(_p):
+ return (True, None)
+
+
+def test_vector_index_loads_existing_index(tmp_path):
+ path = tmp_path / "coll.faiss"
+ lock = threading.Lock()
+ dim = 8
+ # Pre-create a real on-disk IndexIDMap2.
+ store = get_vector_store_class().create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ )
+ store.apply(
+ add_ids=[11, 22], add_vectors=np.random.rand(2, dim).astype("float32")
+ )
+ assert path.exists()
+
+ # Construct VectorIndex over the EXISTING file — must load, not raise.
+ vi = VectorIndex(
+ username="u",
+ db_password="pw",
+ embeddings=None,
+ embedding_model="m",
+ embedding_model_type=None,
+ collection_name="c",
+ dimension=dim,
+ path=path,
+ lock=lock,
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert vi._store.count() == 2
+ assert set(vi._store.live_ids()) == {11, 22}
diff --git a/tests/vector_stores/test_faiss_safe_load_security.py b/tests/vector_stores/test_faiss_safe_load_security.py
new file mode 100644
index 0000000000..480beb4384
--- /dev/null
+++ b/tests/vector_stores/test_faiss_safe_load_security.py
@@ -0,0 +1,454 @@
+"""Security tests for the restricted FAISS docstore unpickler.
+
+``local_deep_research.research_library.services.faiss_safe_load`` replaces a
+raw ``pickle.load`` (used by LangChain's dangerous ``FAISS.load_local``) with
+``_RestrictedFaissUnpickler`` — a subclass that only resolves a tiny
+allow-list of (module, name) globals. ``load_index_to_docstore_id`` is the
+public entry point the phase-1 legacy migration
+(``vector_stores/legacy_cleanup.py: _extract_map``) calls to read a
+potentially-tampered on-disk ``.pkl`` BEFORE any login/DB access.
+
+This file proves the anti-RCE guarantee actually bites:
+
+ (a) a crafted pickle whose payload runs code via ``__reduce__`` (calling
+ ``os.system`` / ``subprocess.Popen`` directly, not just an arbitrary
+ helper) is rejected and — provably, via a sentinel file — never
+ executes;
+ (b) a pickle using the PERSID/BINPERSID (persistent id) opcode is rejected;
+ (c) a class with the SAME name as an allow-listed class
+ (``InMemoryDocstore``) but defined in a FOREIGN module is rejected,
+ proving the allow-list keys on the (module, name) tuple, not the bare
+ name;
+ (d) a benign, well-formed ``(docstore, index_to_docstore_id)`` pickle —
+ mirroring exactly what ``FAISS.save_local`` writes and what
+ ``migrate_legacy_docstores`` reads — is accepted by
+ ``load_index_to_docstore_id`` and yields ONLY the position->uuid map,
+ with the chunk text/Document objects discarded and no code executed.
+"""
+
+import copyreg
+import io
+import pickle
+import pickletools
+import subprocess
+import sys
+import types
+
+import pytest
+from langchain_community.docstore.in_memory import InMemoryDocstore
+from langchain_core.documents import Document
+
+from local_deep_research.research_library.services.faiss_safe_load import (
+ _RestrictedFaissUnpickler,
+ load_index_to_docstore_id,
+)
+
+
+# ---------------------------------------------------------------------------
+# (a) __reduce__ payloads that invoke os.system / subprocess directly
+# ---------------------------------------------------------------------------
+class _OsSystemPayload:
+ """Pickling this object, when unpickled, calls ``os.system(cmd)``.
+
+ ``__reduce__`` returns ``(callable, args)``; the (C or pure-Python)
+ unpickler's REDUCE opcode invokes ``callable(*args)`` verbatim. Using
+ ``os.system`` directly (rather than a project helper) proves the guard
+ stops a *real* shell-executing builtin, not just an easily-blocked
+ look-alike.
+ """
+
+ def __init__(self, cmd: str):
+ self.cmd = cmd
+
+ def __reduce__(self):
+ import os
+
+ return (os.system, (self.cmd,))
+
+
+class _SubprocessPayload:
+ """Pickling this object, when unpickled, spawns ``subprocess.Popen``."""
+
+ def __init__(self, args):
+ self.args = args
+
+ def __reduce__(self):
+ return (subprocess.Popen, (self.args,))
+
+
+def _touch_cmd(path) -> str:
+ # A portable one-liner sentinel command (avoids relying on the `touch`
+ # binary existing on every CI image).
+ return f"{sys.executable} -c \"open(r{str(path)!r}, 'w').close()\""
+
+
+class TestMaliciousReduceRejectedWithoutExecution:
+ def test_os_system_payload_is_rejected_and_never_executes(self, tmp_path):
+ sentinel = tmp_path / "os_system.marker"
+ blob = pickle.dumps((_OsSystemPayload(_touch_cmd(sentinel)), {0: "id"}))
+
+ # Sanity check the assertion actually bites: a plain, unrestricted
+ # pickle.load on this exact blob DOES run the command and create the
+ # sentinel. If this stopped being true the test below would pass for
+ # a meaningless reason (e.g. a broken __reduce__ payload).
+ pickle.loads(blob) # noqa: S301 -- intentional, demonstrates the RCE
+ assert sentinel.exists(), "sanity check failed: payload never ran"
+ sentinel.unlink()
+
+ with pytest.raises(pickle.UnpicklingError):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+ assert not sentinel.exists(), (
+ "os.system payload executed under the restricted unpickler"
+ )
+
+ def test_subprocess_popen_payload_is_rejected_and_never_executes(
+ self, tmp_path
+ ):
+ sentinel = tmp_path / "subprocess.marker"
+ args = [
+ sys.executable,
+ "-c",
+ f"open(r{str(sentinel)!r}, 'w').close()",
+ ]
+ blob = pickle.dumps((_SubprocessPayload(args), {0: "id"}))
+
+ proc, _id_map = pickle.loads(blob) # noqa: S301 -- sanity check only
+ proc.wait(timeout=10)
+ assert sentinel.exists(), "sanity check failed: payload never ran"
+ sentinel.unlink()
+
+ with pytest.raises(pickle.UnpicklingError):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+ assert not sentinel.exists(), (
+ "subprocess.Popen payload executed under the restricted unpickler"
+ )
+
+ def test_via_load_index_to_docstore_id_entry_point(self, tmp_path):
+ """The public migration entry point must reject the same payload
+ written to an on-disk ``.pkl`` — this is the exact code path
+ ``legacy_cleanup._extract_map`` calls on a (possibly hostile) file
+ found on disk during startup migration."""
+ sentinel = tmp_path / "entrypoint.marker"
+ pkl_path = tmp_path / "legacy.pkl"
+ pkl_path.write_bytes(
+ pickle.dumps((_OsSystemPayload(_touch_cmd(sentinel)), {0: "id"}))
+ )
+
+ with pytest.raises(pickle.UnpicklingError):
+ load_index_to_docstore_id(str(pkl_path))
+ assert not sentinel.exists()
+
+
+# ---------------------------------------------------------------------------
+# (b) PERSID / BINPERSID (persistent id) opcode rejected
+# ---------------------------------------------------------------------------
+class _HasPersistentRef:
+ """A stand-in object whose pickled form is emitted as a persistent id."""
+
+
+def _make_persistent_id_blob(protocol: int) -> bytes:
+ """Build a pickle whose top-level object round-trips through
+ ``persistent_id``/``persistent_load`` — i.e. it contains a genuine
+ PERSID (protocol 0) or BINPERSID (protocol >= 1) opcode.
+ """
+
+ buf = io.BytesIO()
+
+ class _PersistentPickler(pickle.Pickler):
+ def persistent_id(self, obj):
+ if isinstance(obj, _HasPersistentRef):
+ # Persistent ids must be strings for PERSID (protocol 0);
+ # any object is fine for BINPERSID (protocol >= 1). Use a
+ # string so it is valid across both.
+ return "attacker-controlled-persistent-ref"
+ return None
+
+ _PersistentPickler(buf, protocol=protocol).dump(
+ (_HasPersistentRef(), {0: "id"})
+ )
+ return buf.getvalue()
+
+
+class TestPersistentIdRejected:
+ @pytest.mark.parametrize("protocol", [0, 2, 4])
+ def test_persistent_id_opcode_is_rejected(self, protocol):
+ blob = _make_persistent_id_blob(protocol)
+
+ # Guard: confirm the blob really contains a PERSID/BINPERSID opcode,
+ # not some other encoding, so the test fails for the right reason if
+ # pickle's wire format ever changes.
+ import pickletools
+
+ op_names = [op.name for op, _, _ in pickletools.genops(blob)]
+ assert any("PERSID" in n for n in op_names), op_names
+
+ # Sanity: a pickler with a matching persistent_load DOES resolve it
+ # (proves this is a real, working persistent-id pickle).
+ class _PersistentUnpickler(pickle.Unpickler):
+ def persistent_load(self, pid):
+ return _HasPersistentRef()
+
+ obj, id_map = _PersistentUnpickler(io.BytesIO(blob)).load()
+ assert isinstance(obj, _HasPersistentRef)
+ assert id_map == {0: "id"}
+
+ with pytest.raises(pickle.UnpicklingError):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+
+ def test_persistent_id_rejected_via_load_index_to_docstore_id(
+ self, tmp_path
+ ):
+ pkl_path = tmp_path / "legacy.pkl"
+ pkl_path.write_bytes(_make_persistent_id_blob(protocol=2))
+
+ with pytest.raises(pickle.UnpicklingError):
+ load_index_to_docstore_id(str(pkl_path))
+
+
+# ---------------------------------------------------------------------------
+# (b2) copyreg extension (EXT1/EXT2/EXT4) opcode rejected via get_extension
+# ---------------------------------------------------------------------------
+def _install_extension_sentinel_module():
+ """Register a fake, importable module holding a ``sentinel_fn`` that
+ records its args when called. Returns ``(module_name, calls)`` where
+ ``calls`` is the list ``sentinel_fn`` appends to if ever invoked.
+ """
+ mod_name = "ldr_test_ext_sentinel_module"
+ mod = types.ModuleType(mod_name)
+ calls: list = []
+
+ def sentinel_fn(cmd):
+ calls.append(cmd)
+
+ # Pickle's save_global resolves globals by (__module__, __qualname__) and
+ # requires the attribute to round-trip back via sys.modules, exactly like
+ # the foreign-module trick above.
+ sentinel_fn.__module__ = mod_name
+ sentinel_fn.__qualname__ = "sentinel_fn"
+ mod.sentinel_fn = sentinel_fn
+ sys.modules[mod_name] = mod
+ return mod_name, calls
+
+
+def _make_copyreg_extension_blob(mod_name: str) -> bytes:
+ """Build a protocol-2 pickle whose REDUCE payload calls ``sentinel_fn``,
+ where ``sentinel_fn`` is registered as a ``copyreg`` extension so the
+ pickler emits an EXT opcode (not GLOBAL/STACK_GLOBAL) to reference it.
+
+ ``copyreg.add_extension(module, name, code)`` makes
+ ``Pickler.save_global`` write EXT1/EXT2/EXT4 instead of a GLOBAL opcode
+ whenever it would otherwise pickle a reference to ``module.name`` --this
+ is a *second*, independent way to obtain an attacker-chosen callable that
+ completely bypasses ``find_class``/GLOBAL, which is why the restricted
+ unpickler must also override ``get_extension``.
+ """
+ sentinel_fn = sys.modules[mod_name].sentinel_fn
+
+ # An extension code unregistered by anything else in the process. Any
+ # value in the EXT4 range (> 0xffff) is fine; a genuinely unique code
+ # keeps this test independent of other tests/processes touching the
+ # shared copyreg extension registry.
+ code = 999_999
+ copyreg.add_extension(mod_name, "sentinel_fn", code)
+
+ class _ExtensionPayload:
+ def __reduce__(self):
+ return (sentinel_fn, ("boom",))
+
+ return pickle.dumps((_ExtensionPayload(), {0: "id"}), protocol=2)
+
+
+class TestCopyregExtensionOpcodeRejected:
+ def setup_method(self):
+ self.mod_name, self.calls = _install_extension_sentinel_module()
+
+ def teardown_method(self):
+ sys.modules.pop(self.mod_name, None)
+ copyreg._inverted_registry.pop(999_999, None)
+ copyreg._extension_registry.pop((self.mod_name, "sentinel_fn"), None)
+ copyreg._extension_cache.pop(999_999, None)
+
+ def test_copyreg_extension_opcode_is_rejected_and_never_executes(self):
+ blob = _make_copyreg_extension_blob(self.mod_name)
+
+ # Guard: confirm the blob really contains an EXT opcode (not a plain
+ # GLOBAL/STACK_GLOBAL reference), so the test fails for the right
+ # reason if pickle's extension-registry wiring ever changes.
+ op_names = [op.name for op, _, _ in pickletools.genops(blob)]
+ assert any(n.startswith("EXT") for n in op_names), op_names
+
+ # Sanity check the assertion actually bites: a plain, unrestricted
+ # pickle.load on this exact blob DOES resolve the extension code and
+ # invoke sentinel_fn.
+ pickle.loads(blob) # noqa: S301 -- intentional, demonstrates the bypass
+ assert self.calls == ["boom"], "sanity check failed: payload never ran"
+ self.calls.clear()
+
+ with pytest.raises(pickle.UnpicklingError):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+ assert self.calls == [], (
+ "copyreg extension payload executed under the restricted unpickler"
+ )
+
+
+# ---------------------------------------------------------------------------
+# (c) Same class NAME, foreign module -> rejected (module, name)-tuple check
+# ---------------------------------------------------------------------------
+def _install_foreign_module_with_lookalikes():
+ """Register a fake module (not the real langchain one) that defines
+ classes literally named ``InMemoryDocstore`` and ``Document`` — the same
+ bare names the allow-list permits, but from a different module path.
+ Returns the module so its classes can be instantiated/pickled.
+ """
+ mod_name = "ldr_test_foreign_lookalike_module"
+ mod = types.ModuleType(mod_name)
+
+ class InMemoryDocstore: # noqa: N801 -- deliberately shadows the real name
+ def __init__(self, d):
+ self._dict = d
+
+ class Document: # noqa: N801
+ def __init__(self, page_content="", metadata=None):
+ self.page_content = page_content
+ self.metadata = metadata or {}
+
+ # Pickle's default __reduce_ex__ (copyreg) resolves globals by
+ # (__module__, __qualname__) and requires
+ # ``getattr(sys.modules[__module__], __qualname__)`` to round-trip back
+ # to the class -- a qualname still tagged with the enclosing function's
+ # ``<locals>`` would fail to pickle at all. Overwrite both so these
+ # classes present exactly as a real top-level ``module.ClassName``
+ # class would (module attribute lookup below makes this true).
+ InMemoryDocstore.__module__ = mod_name
+ InMemoryDocstore.__qualname__ = "InMemoryDocstore"
+ Document.__module__ = mod_name
+ Document.__qualname__ = "Document"
+ mod.InMemoryDocstore = InMemoryDocstore
+ mod.Document = Document
+ sys.modules[mod_name] = mod
+ return mod
+
+
+class TestForeignModuleSameNameRejected:
+ def setup_method(self):
+ self.mod = _install_foreign_module_with_lookalikes()
+
+ def teardown_method(self):
+ sys.modules.pop("ldr_test_foreign_lookalike_module", None)
+
+ def test_foreign_in_memory_docstore_lookalike_rejected(self):
+ foreign_docstore = self.mod.InMemoryDocstore({"id1": "not a Document"})
+ blob = pickle.dumps((foreign_docstore, {0: "id1"}))
+
+ # Sanity: a plain pickle.load happily resolves the foreign class —
+ # confirms the blob is well-formed and the class is genuinely
+ # reachable by (module, name), i.e. this isn't rejected for some
+ # unrelated reason (e.g. a pickling error).
+ obj, _ = pickle.loads(blob) # noqa: S301
+ assert type(obj).__name__ == "InMemoryDocstore"
+ assert type(obj).__module__ == "ldr_test_foreign_lookalike_module"
+
+ with pytest.raises(
+ pickle.UnpicklingError,
+ match="ldr_test_foreign_lookalike_module",
+ ):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+
+ def test_foreign_document_lookalike_rejected(self):
+ # Real, allow-listed InMemoryDocstore, but its stored "Document" is
+ # the foreign look-alike class -- the allow-list must be checked for
+ # EVERY resolved global, not just the outermost one.
+ foreign_doc = self.mod.Document(page_content="hello", metadata={})
+ docstore = InMemoryDocstore({"id1": foreign_doc})
+ blob = pickle.dumps((docstore, {0: "id1"}))
+
+ obj, _ = pickle.loads(blob) # noqa: S301 -- sanity: it is well-formed
+ assert type(obj._dict["id1"]).__module__ == (
+ "ldr_test_foreign_lookalike_module"
+ )
+
+ with pytest.raises(
+ pickle.UnpicklingError,
+ match="ldr_test_foreign_lookalike_module",
+ ):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+
+ def test_load_index_to_docstore_id_rejects_foreign_lookalike(
+ self, tmp_path
+ ):
+ foreign_docstore = self.mod.InMemoryDocstore({"id1": "x"})
+ pkl_path = tmp_path / "legacy.pkl"
+ pkl_path.write_bytes(pickle.dumps((foreign_docstore, {0: "id1"})))
+
+ with pytest.raises(pickle.UnpicklingError):
+ load_index_to_docstore_id(str(pkl_path))
+
+
+# ---------------------------------------------------------------------------
+# (d) Benign, well-formed docstore/id-map pickle -> accepted, text-free
+# ---------------------------------------------------------------------------
+def _build_benign_legacy_pkl(tmp_path):
+ """Build a ``.pkl`` byte-for-byte in the shape ``FAISS.save_local``
+ writes and ``migrate_legacy_docstores``/``_extract_map`` reads: a
+ 2-tuple of ``(InMemoryDocstore, index_to_docstore_id)`` where the
+ docstore maps uuid keys to real ``Document`` objects (chunk text +
+ metadata) and ``index_to_docstore_id`` maps FAISS integer position to
+ that same uuid key.
+ """
+ uuid_a = "11111111-1111-1111-1111-111111111111"
+ uuid_b = "22222222-2222-2222-2222-222222222222"
+ docstore = InMemoryDocstore(
+ {
+ uuid_a: Document(
+ page_content="the quick brown fox",
+ metadata={"source": "a.pdf", "page": 1},
+ ),
+ uuid_b: Document(
+ page_content="jumps over the lazy dog",
+ metadata={"source": "a.pdf", "page": 2},
+ ),
+ }
+ )
+ index_to_docstore_id = {0: uuid_a, 1: uuid_b}
+ pkl_path = tmp_path / "legacy.pkl"
+ pkl_path.write_bytes(pickle.dumps((docstore, index_to_docstore_id)))
+ return pkl_path, index_to_docstore_id, {uuid_a, uuid_b}
+
+
+class TestBenignDocstoreAccepted:
+ def test_load_index_to_docstore_id_returns_only_the_id_map(self, tmp_path):
+ pkl_path, expected_map, _uuids = _build_benign_legacy_pkl(tmp_path)
+
+ result = load_index_to_docstore_id(str(pkl_path))
+
+ assert result == expected_map
+ # Exactly the position -> uuid map: no Document objects, no chunk
+ # text, and no extra/missing entries leaked through.
+ assert set(result.keys()) == {0, 1}
+ for pos, key in result.items():
+ assert isinstance(pos, int)
+ assert isinstance(key, str)
+ # The chunk text itself must not appear anywhere in the returned
+ # value's repr (it must be a plain int->str map, nothing else).
+ assert "quick brown fox" not in repr(result)
+ assert "lazy dog" not in repr(result)
+
+ def test_restricted_unpickler_directly_accepts_the_same_payload(
+ self, tmp_path
+ ):
+ """Cross-check at the unpickler layer: the SAME allow-listed classes
+ that ``load_index_to_docstore_id`` relies on are exactly what a real
+ ``FAISS.save_local``-shaped payload needs -- nothing more, nothing
+ less."""
+ pkl_path, expected_map, uuids = _build_benign_legacy_pkl(tmp_path)
+
+ with open(pkl_path, "rb") as f:
+ docstore, index_to_docstore_id = _RestrictedFaissUnpickler(f).load()
+
+ assert index_to_docstore_id == expected_map
+ assert set(docstore._dict.keys()) == uuids
+ contents = {d.page_content for d in docstore._dict.values()}
+ assert contents == {
+ "the quick brown fox",
+ "jumps over the lazy dog",
+ }
diff --git a/tests/vector_stores/test_faiss_store.py b/tests/vector_stores/test_faiss_store.py
new file mode 100644
index 0000000000..42d861cc1b
--- /dev/null
+++ b/tests/vector_stores/test_faiss_store.py
@@ -0,0 +1,1410 @@
+"""Unit tests for ``FaissVectorStore`` (``vector_stores/implementations/faiss_store.py``).
+
+No DB is needed here — this module is DB-agnostic (ids + vectors only, see
+the "SECURITY INVARIANT" block in ``vector_stores/base.py``). Persistence
+resources (path / lock / integrity hooks) are injected fakes: a ``tmp_path``,
+a real ``threading.Lock()``, and no-op integrity callables.
+"""
+
+import threading
+
+import faiss
+import numpy as np
+import pytest
+
+from src.local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+)
+
+
+# --------------------------------------------------------------------------
+# Fakes / helpers
+# --------------------------------------------------------------------------
+def _noop_record(_path):
+ return None
+
+
+def _ok_verify(_path):
+ return (True, None)
+
+
+def _make_store(
+ tmp_path,
+ *,
+ dimension=4,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ bind=True,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ lock=None,
+):
+ kwargs = dict(
+ dimension=dimension,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+ if bind:
+ kwargs.update(
+ path=tmp_path / "coll.faiss",
+ lock=lock or threading.Lock(),
+ integrity_record=integrity_record,
+ integrity_verify=integrity_verify,
+ )
+ return FaissVectorStore.create(**kwargs)
+
+
+def _vecs(n, dim=4, seed=0):
+ rng = np.random.default_rng(seed)
+ return rng.random((n, dim)).astype("float32")
+
+
+# --------------------------------------------------------------------------
+# create / add / count / live_ids
+# --------------------------------------------------------------------------
+class TestCreateAddCount:
+ def test_create_empty_store(self, tmp_path):
+ store = _make_store(tmp_path)
+ assert store.count() == 0
+ assert store.live_ids() == []
+
+ def test_add_increases_count_and_live_ids(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([10, 20, 30], _vecs(3))
+ assert store.count() == 3
+ assert set(store.live_ids()) == {10, 20, 30}
+
+ def test_add_empty_ids_is_noop(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([], np.empty((0, 4), dtype="float32"))
+ assert store.count() == 0
+
+ def test_add_ids_vectors_length_mismatch_raises(self, tmp_path):
+ store = _make_store(tmp_path)
+ with pytest.raises(ValueError, match="length mismatch"):
+ store.add([1, 2, 3], _vecs(2))
+
+ def test_add_dimension_mismatch_raises(self, tmp_path):
+ """Guards the python -O silent-corruption case: faiss's own C++
+ assert on dimension is stripped under -O, so the store must
+ validate explicitly (see the comment in ``_prepare``)."""
+ store = _make_store(tmp_path, dimension=4)
+ with pytest.raises(ValueError, match="vector dimension"):
+ store.add([1], _vecs(1, dim=8))
+
+ def test_int64_ids_beyond_int32(self, tmp_path):
+ big_id = 5_000_000_000 # > 2**31, would overflow int32
+ store = _make_store(tmp_path)
+ store.add([big_id], _vecs(1))
+ assert store.live_ids() == [big_id]
+ hits = store.search(_vecs(1)[0], 1)
+ assert hits[0][0] == big_id
+
+
+# --------------------------------------------------------------------------
+# search: cosine vs l2 ordering
+# --------------------------------------------------------------------------
+class TestSearchOrdering:
+ def test_cosine_orders_by_descending_similarity(self, tmp_path):
+ store = _make_store(
+ tmp_path, dimension=2, metric="cosine", normalize=True
+ )
+ # query points along +x axis. id 1 is near-parallel (high cosine
+ # sim), id 2 is near-orthogonal (low), id 3 points away (negative).
+ store.add(
+ [1, 2, 3],
+ np.array([[1.0, 0.05], [0.05, 1.0], [-1.0, 0.05]], dtype="float32"),
+ )
+ hits = store.search(np.array([1.0, 0.0], dtype="float32"), 3)
+ ids = [i for i, _ in hits]
+ assert ids == [1, 2, 3]
+ # inner product on normalized vectors: higher is more similar,
+ # so scores must be descending.
+ scores = [d for _, d in hits]
+ assert scores == sorted(scores, reverse=True)
+
+ def test_l2_orders_by_ascending_distance(self, tmp_path):
+ store = _make_store(tmp_path, dimension=2, metric="l2", normalize=False)
+ store.add(
+ [1, 2, 3],
+ np.array([[0.1, 0.1], [5.0, 5.0], [1.0, 1.0]], dtype="float32"),
+ )
+ hits = store.search(np.array([0.0, 0.0], dtype="float32"), 3)
+ ids = [i for i, _ in hits]
+ assert ids == [1, 3, 2] # nearest (0.1,0.1) -> (1,1) -> (5,5)
+ dists = [d for _, d in hits]
+ assert dists == sorted(dists)
+
+ def test_search_k_le_zero_returns_empty(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ assert store.search(_vecs(1)[0], 0) == []
+ assert store.search(_vecs(1)[0], -1) == []
+
+ def test_search_empty_index_returns_empty(self, tmp_path):
+ store = _make_store(tmp_path)
+ assert store.search(_vecs(1)[0], 5) == []
+
+ def test_search_fewer_hits_than_k_drops_empty_slots(self, tmp_path):
+ """faiss returns -1 for empty slots when fewer than k neighbors
+ exist; those must be filtered out, not surfaced as id -1."""
+ store = _make_store(tmp_path)
+ store.add([7], _vecs(1))
+ hits = store.search(_vecs(1)[0], 5)
+ assert len(hits) == 1
+ assert hits[0][0] == 7
+
+ def test_search_k_less_than_total_returns_nearest_k_in_order(
+ self, tmp_path
+ ):
+ # Existing ordering tests use k>=ntotal; this covers k strictly less
+ # than ntotal, where faiss must still return only the k CLOSEST hits
+ # (not an arbitrary k-subset) in ranked order.
+ store = _make_store(tmp_path, dimension=2, metric="l2", normalize=False)
+ store.add(
+ [1, 2, 3, 4, 5],
+ np.array(
+ [
+ [0.1, 0.1],
+ [5.0, 5.0],
+ [1.0, 1.0],
+ [2.0, 2.0],
+ [10.0, 10.0],
+ ],
+ dtype="float32",
+ ),
+ )
+ hits = store.search(np.array([0.0, 0.0], dtype="float32"), 2)
+ assert len(hits) == 2
+ ids = [i for i, _ in hits]
+ # Two nearest to the origin: (0.1,0.1) then (1,1).
+ assert ids == [1, 3]
+ dists = [d for _, d in hits]
+ assert dists == sorted(dists)
+
+
+# --------------------------------------------------------------------------
+# delete / live_ids / count / reconstruct
+# --------------------------------------------------------------------------
+class TestDeleteLiveIdsReconstruct:
+ def test_delete_removes_and_returns_count(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1, 2, 3], _vecs(3))
+ removed = store.delete([2, 3])
+ assert removed == 2
+ assert store.live_ids() == [1]
+ assert store.count() == 1
+
+ def test_delete_empty_list_is_noop(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ assert store.delete([]) == 0
+ assert store.count() == 1
+
+ def test_delete_none_entries_filtered(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ assert store.delete([None, None]) == 0
+
+ def test_reconstruct_missing_id_returns_none(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ assert store.reconstruct(999) is None
+
+ def test_reconstruct_existing_id_returns_vector(self, tmp_path):
+ store = _make_store(tmp_path, dimension=3, metric="l2", normalize=False)
+ vec = np.array([[1.0, 2.0, 3.0]], dtype="float32")
+ store.add([5], vec)
+ out = store.reconstruct(5)
+ assert out is not None
+ np.testing.assert_allclose(np.asarray(out), vec[0], atol=1e-5)
+
+ def test_reconstruct_after_delete_returns_none(self, tmp_path):
+ # Distinct from a never-added id: this id WAS live, then removed via
+ # remove_ids -- the Optional contract _rebuild_dropping/integrity
+ # re-embed rely on must hold for a removed id too, not just an absent one.
+ store = _make_store(tmp_path, dimension=3, metric="l2", normalize=False)
+ store.add([1, 2], _vecs(2, dim=3))
+ removed = store.delete([1])
+ assert removed == 1
+ assert store.reconstruct(1) is None
+ assert store.reconstruct(999) is None # never-added id, for contrast
+ assert (
+ store.reconstruct(2) is not None
+ ) # untouched id still reconstructs
+
+ def test_supports_delete_false_for_hnsw(self, tmp_path):
+ store = _make_store(tmp_path, index_type="hnsw")
+ assert store.supports_delete is False
+
+ def test_hnsw_delete_raises_clear_runtime_error(self, tmp_path):
+ store = _make_store(tmp_path, index_type="hnsw")
+ store.add([1], _vecs(1))
+ with pytest.raises(RuntimeError, match="hnsw"):
+ store.delete([1])
+
+ def test_hnsw_apply_remove_ids_rebuilds(self, tmp_path):
+ # apply() must NOT raise for HNSW removals: faiss HNSW has no
+ # remove_ids, so apply() drops-by-rebuild (_rebuild_dropping) instead.
+ store = _make_store(tmp_path, index_type="hnsw")
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3))
+ stats = store.apply(add_ids=[], add_vectors=None, remove_ids=[2])
+ assert stats["removed"] == 1
+ assert set(store.live_ids()) == {1, 3}
+ assert store.count() == 2
+
+ def test_hnsw_apply_replace_same_id_rebuilds(self, tmp_path):
+ # remove + add of the SAME id (a "replace", used by re-index) must
+ # succeed for HNSW via the rebuild path — the original crash repro.
+ store = _make_store(tmp_path, index_type="hnsw")
+ store.apply(add_ids=[1, 2], add_vectors=_vecs(2))
+ newvec = _vecs(1, seed=99)
+ store.apply(add_ids=[1], add_vectors=newvec, remove_ids=[1])
+ assert set(store.live_ids()) == {1, 2}
+
+ def test_hnsw_apply_remove_all_and_absent(self, tmp_path):
+ store = _make_store(tmp_path, index_type="hnsw")
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3))
+ # Absent id: leniently ignored, nothing removed.
+ assert (
+ store.apply(add_ids=[], add_vectors=None, remove_ids=[999])[
+ "removed"
+ ]
+ == 0
+ )
+ # Remove every id: empties to 0 without crashing.
+ stats = store.apply(add_ids=[], add_vectors=None, remove_ids=[1, 2, 3])
+ assert stats["removed"] == 3
+ assert store.count() == 0
+
+ def test_hnsw_rebuild_survives_reload(self, tmp_path):
+ # The rebuilt index must persist and reload as a valid IndexIDMap2.
+ store = _make_store(tmp_path, index_type="hnsw")
+ store.apply(add_ids=[1, 2, 3, 4], add_vectors=_vecs(4))
+ store.apply(add_ids=[], add_vectors=None, remove_ids=[2, 4])
+ reloaded = FaissVectorStore.load(
+ tmp_path / "coll.faiss",
+ dimension=4,
+ index_type="hnsw",
+ metric="cosine",
+ normalize=True,
+ )
+ assert set(reloaded.live_ids()) == {1, 3}
+
+
+# --------------------------------------------------------------------------
+# persist / load
+# --------------------------------------------------------------------------
+class TestPersistLoad:
+ def test_persist_is_atomic_no_tmp_left(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1, 2], _vecs(2))
+ path = tmp_path / "out.faiss"
+ store.persist(path)
+ assert path.exists()
+ leftover_tmp = list(tmp_path.glob("*.tmp"))
+ assert leftover_tmp == []
+
+ def test_persist_write_index_failure_leaves_original_file_untouched_and_no_tmp(
+ self, tmp_path, monkeypatch
+ ):
+ """A failure INSIDE the real write (the module-level ``write_index``
+ imported ~line 37) must never corrupt or replace the last-good
+ durable file: persist()'s temp+rename means ``write_index`` raising
+ happens strictly before ``os.replace``, so the original bytes must
+ be untouched, and the temp file must be cleaned up by persist()'s
+ own ``finally`` block rather than left dangling as ``*.tmp`` litter.
+
+ Existing persist-failure tests mock the whole ``store.persist``
+ method; this exercises the real mid-write sequence, which those
+ leave uncovered.
+ """
+ store = _make_store(tmp_path)
+ store.add([1, 2], _vecs(2))
+ path = tmp_path / "out.faiss"
+ store.persist(path)
+ assert path.exists()
+ original_bytes = path.read_bytes()
+
+ def _boom(index, filename):
+ raise RuntimeError("simulated write_index failure")
+
+ monkeypatch.setattr(
+ "src.local_deep_research.vector_stores.implementations."
+ "faiss_store.write_index",
+ _boom,
+ )
+
+ # Mutate the in-memory index further so a torn overwrite (if it
+ # happened) would be detectably different from the captured bytes.
+ store.add([3], _vecs(1, seed=5))
+
+ with pytest.raises(RuntimeError, match="simulated write_index failure"):
+ store.persist(path)
+
+ assert path.read_bytes() == original_bytes # no torn overwrite
+ assert list(tmp_path.glob("*.tmp")) == [] # temp cleaned up
+
+ def test_persist_writes_no_pkl_companion(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ path = tmp_path / "out.faiss"
+ store.persist(path)
+ assert list(tmp_path.glob("*.pkl")) == []
+
+ def test_apply_reload_rejects_dimension_mismatch(self, tmp_path):
+ # A store bound to a path whose on-disk index has a DIFFERENT dimension
+ # (embedding model/config changed) must fail closed on apply()'s
+ # reload-under-lock, not silently add a wrong-width vector (which faiss
+ # would only catch with an assert stripped under `python -O`).
+ first = _make_store(tmp_path, dimension=4)
+ first.apply(add_ids=[1], add_vectors=_vecs(1, dim=4))
+
+ mismatched = _make_store(tmp_path, dimension=8) # same default path
+ with pytest.raises(RuntimeError, match="dimension"):
+ mismatched.apply(add_ids=[2], add_vectors=_vecs(1, dim=8))
+
+ def test_persist_chmods_parent_private(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ d = tmp_path / "sub" / "out.faiss"
+ store.persist(d)
+ mode = d.parent.stat().st_mode & 0o777
+ assert mode == 0o700
+
+ def test_load_round_trip(self, tmp_path):
+ store = _make_store(
+ tmp_path, dimension=4, metric="cosine", normalize=True
+ )
+ store.add([1, 2, 3], _vecs(3))
+ path = tmp_path / "rt.faiss"
+ store.persist(path)
+
+ loaded = FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert set(loaded.live_ids()) == {1, 2, 3}
+ assert loaded.count() == 3
+
+ def test_load_raises_on_non_idmap2_file(self, tmp_path):
+ """post-migration every on-disk index must be IndexIDMap2; a raw
+ base index means pre-migration or corruption and must surface."""
+ path = tmp_path / "raw.faiss"
+ raw = faiss.IndexFlatL2(4)
+ faiss.write_index(raw, str(path))
+
+ with pytest.raises(ValueError, match="not IndexIDMap2"):
+ FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type="flat",
+ metric="l2",
+ normalize=False,
+ )
+
+ def test_load_raises_on_dimension_mismatch(self, tmp_path):
+ store = _make_store(tmp_path, dimension=4)
+ store.add([1], _vecs(1, dim=4))
+ path = tmp_path / "dim.faiss"
+ store.persist(path)
+
+ with pytest.raises(ValueError, match="dimension"):
+ FaissVectorStore.load(
+ path,
+ dimension=8,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+
+# --------------------------------------------------------------------------
+# apply(): add / dedup / replace / purge / empty
+# --------------------------------------------------------------------------
+class TestApply:
+ def test_apply_requires_persistence_binding(self, tmp_path):
+ store = _make_store(tmp_path, bind=False)
+ with pytest.raises(RuntimeError, match="persistence binding"):
+ store.apply(add_ids=[1], add_vectors=_vecs(1))
+
+ def test_apply_add_ids_without_vectors_raises(self, tmp_path):
+ store = _make_store(tmp_path)
+ with pytest.raises(ValueError, match="add_vectors"):
+ store.apply(add_ids=[1], add_vectors=None)
+
+ def test_apply_basic_add(self, tmp_path):
+ store = _make_store(tmp_path)
+ stats = store.apply(add_ids=[1, 2], add_vectors=_vecs(2))
+ assert stats == {"added": 2, "removed": 0}
+ assert set(store.live_ids()) == {1, 2}
+
+ def test_apply_dedup_within_batch(self, tmp_path):
+ store = _make_store(tmp_path)
+ # id 1 repeated in the same batch -> only the first occurrence kept.
+ stats = store.apply(add_ids=[1, 1, 2], add_vectors=_vecs(3))
+ assert stats["added"] == 2
+ assert set(store.live_ids()) == {1, 2}
+
+ def test_apply_replaces_live_id_not_skips(self, tmp_path):
+ # An id already live is REPLACED (removed then re-added), NOT skipped:
+ # the new vector must win (reused-id safety — SQLite recycles
+ # AUTOINCREMENT ids on ROLLBACK, so a live id may carry a stale orphan).
+ store = _make_store(tmp_path)
+ store.apply(add_ids=[1], add_vectors=_vecs(1))
+ stats = store.apply(add_ids=[1, 2], add_vectors=_vecs(2))
+ assert stats["added"] == 2 # id 1 replaced + id 2 added
+ assert stats["removed"] == 1 # stale id 1 removed first
+ assert set(store.live_ids()) == {1, 2}
+ assert store.count() == 2 # no duplicate id 1
+
+ def test_apply_replace_on_collision_is_unconditional(self, tmp_path):
+ """Replace-on-collision runs even with dedup=False: a live id is
+ removed before re-add, so IndexIDMap2 never accrues a duplicate key
+ (which would cause phantom hits and the reused-id text leak)."""
+ store = _make_store(tmp_path)
+ store.apply(add_ids=[1], add_vectors=_vecs(1))
+ store.apply(add_ids=[1], add_vectors=_vecs(1), dedup=False)
+ assert store.count() == 1 # replaced, not duplicated
+
+ def test_apply_replace_same_id(self, tmp_path):
+ store = _make_store(tmp_path, dimension=3, metric="l2", normalize=False)
+ v1 = np.array([[1.0, 0.0, 0.0]], dtype="float32")
+ store.apply(add_ids=[1], add_vectors=v1)
+
+ v2 = np.array([[9.0, 9.0, 9.0]], dtype="float32")
+ stats = store.apply(add_ids=[1], add_vectors=v2, remove_ids=[1])
+ assert stats == {"added": 1, "removed": 1}
+ assert store.live_ids() == [1]
+ np.testing.assert_allclose(
+ np.asarray(store.reconstruct(1)), v2[0], atol=1e-5
+ )
+
+ def test_apply_purge(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3))
+ stats = store.apply(add_ids=[], add_vectors=None, remove_ids=[1, 2, 3])
+ assert stats["removed"] == 3
+ assert store.count() == 0
+
+ def test_apply_empty_is_noop_but_persists(self, tmp_path):
+ store = _make_store(tmp_path)
+ stats = store.apply(add_ids=[], add_vectors=None, remove_ids=[])
+ assert stats == {"added": 0, "removed": 0}
+ assert store._path.exists()
+ assert store.count() == 0
+
+
+# --------------------------------------------------------------------------
+# Cross-instance reload-under-lock (#4200 guarantee)
+# --------------------------------------------------------------------------
+class TestCrossInstanceReloadUnderLock:
+ def test_second_instance_absorbs_first_instances_write(self, tmp_path):
+ """Two stores share the same path + lock (as the service layer's
+ cached-instance-per-collection model does). Instance A adds+persists
+ first; instance B was constructed independently (its in-memory index
+ does NOT yet know about A's write). B.apply() must reload the
+ on-disk file under the lock and merge onto it — losing A's write
+ here would be exactly the #4200 regression."""
+ path = tmp_path / "shared.faiss"
+ lock = threading.Lock()
+ dim = 4
+
+ store_a = FaissVectorStore.create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+ store_b = FaissVectorStore.create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+
+ store_a.apply(add_ids=[1, 2], add_vectors=_vecs(2, dim=dim))
+ assert path.exists()
+
+ store_b.apply(add_ids=[3], add_vectors=_vecs(1, dim=dim, seed=99))
+
+ assert set(store_b.live_ids()) == {1, 2, 3}
+ reloaded = FaissVectorStore.load(
+ path,
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert set(reloaded.live_ids()) == {1, 2, 3}
+
+ def test_reload_fails_closed_on_bad_integrity(self, tmp_path):
+ """If the on-disk file exists but integrity_verify says it can't be
+ trusted, apply() must refuse to overwrite it (fail closed) rather
+ than silently clobbering a concurrent writer's committed save."""
+ path = tmp_path / "shared.faiss"
+ lock = threading.Lock()
+ dim = 4
+
+ store_a = FaissVectorStore.create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+ store_a.apply(add_ids=[1], add_vectors=_vecs(1, dim=dim))
+
+ def _bad_verify(_path):
+ return (False, "checksum mismatch")
+
+ store_b = FaissVectorStore.create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_bad_verify,
+ )
+ with pytest.raises(RuntimeError, match="Refusing to overwrite"):
+ store_b.apply(add_ids=[2], add_vectors=_vecs(1, dim=dim))
+
+ def test_apply_reload_fails_closed_on_unreadable_ondisk_file_and_does_not_clobber(
+ self, tmp_path
+ ):
+ """If the on-disk file exists, integrity_verify says it's fine, but
+ read_index itself fails (corruption), apply()'s reload-under-lock must
+ fail closed (raise) rather than silently overwrite the corrupt/foreign
+ bytes with our in-memory copy -- that would clobber whatever a
+ concurrent writer had committed there."""
+ path = tmp_path / "shared.faiss"
+ lock = threading.Lock()
+ dim = 4
+
+ store_a = FaissVectorStore.create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify, # isolates the read_index branch
+ )
+ store_a.apply(add_ids=[1], add_vectors=_vecs(1, dim=dim))
+
+ # Corrupt the on-disk bytes so read_index() itself raises.
+ path.write_bytes(b"not a valid faiss index" * 8)
+ corrupted_bytes = path.read_bytes()
+
+ store_b = FaissVectorStore.create(
+ dimension=dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+ with pytest.raises(RuntimeError, match="failed to reload"):
+ store_b.apply(add_ids=[2], add_vectors=_vecs(1, dim=dim, seed=2))
+
+ # Fail-closed: the corrupt bytes must be untouched, not overwritten.
+ assert path.read_bytes() == corrupted_bytes
+
+
+# --------------------------------------------------------------------------
+# _read_guard: poisoned instance refuses reads
+# --------------------------------------------------------------------------
+class TestReadGuardPoisoned:
+ def test_poisoned_unlocked_instance_refuses_count(self, tmp_path):
+ store = _make_store(tmp_path, bind=False)
+ store._poisoned = True
+ with pytest.raises(RuntimeError, match="poisoned"):
+ store.count()
+
+ def test_poisoned_locked_instance_refuses_search(self, tmp_path):
+ store = _make_store(tmp_path)
+ store._poisoned = True
+ with pytest.raises(RuntimeError, match="poisoned"):
+ store.search(_vecs(1)[0], 1)
+
+ def test_poisoned_refuses_live_ids_and_reconstruct(self, tmp_path):
+ store = _make_store(tmp_path)
+ store._poisoned = True
+ with pytest.raises(RuntimeError, match="poisoned"):
+ store.live_ids()
+ with pytest.raises(RuntimeError, match="poisoned"):
+ store.reconstruct(1)
+
+
+# --------------------------------------------------------------------------
+# integrity_record: retry then raise
+# --------------------------------------------------------------------------
+class TestIntegrityRecordRetry:
+ def test_record_integrity_retries_then_raises(self, tmp_path):
+ calls = []
+
+ def _always_fails(_path):
+ calls.append(1)
+ raise OSError("db hiccup")
+
+ store = _make_store(
+ tmp_path,
+ integrity_record=_always_fails,
+ integrity_verify=_ok_verify,
+ )
+ with pytest.raises(RuntimeError, match="failed to record"):
+ store.apply(add_ids=[1], add_vectors=_vecs(1))
+
+ assert len(calls) == 3 # default attempts=3
+ # The vectors WERE persisted (persist() ran before the integrity
+ # failure); a resync from disk keeps the in-memory state honest
+ # rather than poisoning the instance over a checksum-recording bug.
+ assert store.count() == 1
+ assert store._poisoned is False
+
+ def test_record_integrity_succeeds_on_second_attempt(self, tmp_path):
+ calls = []
+
+ def _fails_once(_path):
+ calls.append(1)
+ if len(calls) < 2:
+ raise OSError("transient")
+
+ store = _make_store(
+ tmp_path, integrity_record=_fails_once, integrity_verify=_ok_verify
+ )
+ store.apply(add_ids=[1], add_vectors=_vecs(1))
+ assert len(calls) == 2
+ assert store.count() == 1
+
+ def test_no_integrity_record_hook_is_noop(self, tmp_path):
+ store = _make_store(tmp_path, integrity_record=None)
+ # Must not raise despite no integrity hook.
+ store.apply(add_ids=[1], add_vectors=_vecs(1))
+ assert store.count() == 1
+
+
+class TestNonFiniteVectorRejection:
+ def test_nan_vector_rejected(self, tmp_path):
+ store = _make_store(tmp_path)
+ bad = np.full((1, 4), np.nan, dtype="float32")
+ with pytest.raises(ValueError, match="non-finite"):
+ store.add([1], bad)
+
+ def test_inf_vector_rejected(self, tmp_path):
+ store = _make_store(tmp_path)
+ bad = np.array([[np.inf, 0.0, 0.0, 0.0]], dtype="float32")
+ with pytest.raises(ValueError, match="non-finite"):
+ store.add([1], bad)
+
+ def test_zero_vector_rejected_under_normalize(self, tmp_path):
+ # faiss normalize_L2 maps a zero-magnitude vector to all-zeros (not NaN),
+ # so it would silently be indexed as a degenerate, unsearchable vector.
+ # _prepare rejects it explicitly instead.
+ store = _make_store(tmp_path, normalize=True)
+ with pytest.raises(ValueError, match="zero-magnitude"):
+ store.add([1], np.zeros((1, 4), dtype="float32"))
+ assert store.count() == 0
+
+ def test_zero_vector_allowed_without_normalize(self, tmp_path):
+ # Without L2 normalization a zero vector is a valid (if degenerate)
+ # entry — no NaN, no silent unsearchability from normalize — so it is
+ # accepted rather than rejected.
+ store = _make_store(tmp_path, normalize=False)
+ store.add([1], np.zeros((1, 4), dtype="float32"))
+ assert store.count() == 1
+
+ def test_nan_query_rejected(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ with pytest.raises(ValueError, match="non-finite"):
+ store.search(np.full((1, 4), np.nan, dtype="float32"), 1)
+
+
+class TestReplaceOnIdCollision:
+ """A reused DocumentChunk.id (SQLite recycles AUTOINCREMENT ids on ROLLBACK)
+ must get the NEW vector, never silently keep a stale orphan vector under
+ that id — otherwise search rehydrates the WRONG document's text."""
+
+ def test_flat_collision_new_vector_wins(self, tmp_path):
+ store = _make_store(tmp_path, dimension=3, metric="l2", normalize=False)
+ store.apply(
+ add_ids=[7],
+ add_vectors=np.array([[1.0, 0.0, 0.0]], dtype="float32"),
+ )
+ new = np.array([[0.0, 1.0, 0.0]], dtype="float32")
+ store.apply(add_ids=[7], add_vectors=new) # same id, different vector
+ assert store.count() == 1 # not duplicated
+ np.testing.assert_allclose(
+ np.asarray(store.reconstruct(7)), new[0], atol=1e-5
+ )
+
+ def test_hnsw_collision_new_vector_wins(self, tmp_path):
+ store = _make_store(
+ tmp_path,
+ dimension=3,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ )
+ store.apply(
+ add_ids=[7, 8],
+ add_vectors=np.array(
+ [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]], dtype="float32"
+ ),
+ )
+ new = np.array([[0.0, 1.0, 0.0]], dtype="float32")
+ store.apply(add_ids=[7], add_vectors=new)
+ assert set(store.live_ids()) == {7, 8}
+ np.testing.assert_allclose(
+ np.asarray(store.reconstruct(7)), new[0], atol=1e-5
+ )
+
+
+class TestHnswOffLockRebuild:
+ """The HNSW rebuild builds the new graph OFF the write lock, so a
+ concurrent search() is not blocked for the (expensive) O(collection)
+ rebuild — only for the fast snapshot + the final swap."""
+
+ def test_offlock_rebuild_correctness(self, tmp_path):
+ store = _make_store(
+ tmp_path,
+ index_type="hnsw",
+ dimension=3,
+ metric="l2",
+ normalize=False,
+ )
+ store.apply(
+ add_ids=[1, 2, 3],
+ add_vectors=np.array(
+ [[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]], dtype="float32"
+ ),
+ )
+ # Remove id 2 AND replace id 1 with a new vector in one apply().
+ newv = np.array([[9.0, 9.0, 9.0]], dtype="float32")
+ stats = store.apply(add_ids=[1], add_vectors=newv, remove_ids=[2])
+ assert stats["removed"] >= 1
+ assert set(store.live_ids()) == {1, 3}
+ np.testing.assert_allclose(
+ np.asarray(store.reconstruct(1)), newv[0], atol=1e-5
+ )
+ reloaded = FaissVectorStore.load(
+ tmp_path / "coll.faiss",
+ dimension=3,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ )
+ assert set(reloaded.live_ids()) == {1, 3}
+
+ def test_search_not_blocked_during_rebuild(self, tmp_path):
+ import threading
+ import time
+
+ store = _make_store(
+ tmp_path,
+ index_type="hnsw",
+ dimension=4,
+ metric="l2",
+ normalize=False,
+ )
+ store.apply(add_ids=[1, 2, 3, 4], add_vectors=_vecs(4, dim=4))
+
+ build_started = threading.Event()
+ reader_done = threading.Event()
+ real_build = store._build_base_index # staticmethod -> plain function
+
+ def slow_build(dimension, index_type, metric):
+ # Phase 2 runs OFF the lock; block here until the reader finishes.
+ build_started.set()
+ reader_done.wait(timeout=5)
+ return real_build(dimension, index_type, metric)
+
+ store._build_base_index = slow_build # instance-shadow the staticmethod
+
+ results = {}
+
+ def do_rebuild():
+ results["r"] = store.apply(
+ add_ids=[], add_vectors=None, remove_ids=[2]
+ )
+
+ t = threading.Thread(target=do_rebuild)
+ t.start()
+ assert build_started.wait(timeout=5), "rebuild never reached Phase 2"
+
+ # The off-lock build is blocked. A search must return WITHOUT waiting on
+ # it (under the old under-lock design this would deadlock on the lock,
+ # timing out the join below).
+ t0 = time.monotonic()
+ hits = store.search(_vecs(1, dim=4)[0], 4)
+ elapsed = time.monotonic() - t0
+ assert elapsed < 1.0, f"search blocked {elapsed:.2f}s during rebuild"
+ # search saw the pre-swap (old) index, which still had id 2.
+ assert 2 in {i for i, _ in hits}
+
+ reader_done.set()
+ t.join(timeout=5)
+ assert not t.is_alive()
+ assert results["r"]["removed"] == 1
+ assert set(store.live_ids()) == {1, 3, 4}
+
+
+class TestHnswOffLockRace:
+ """A concurrent write during the off-lock rebuild bumps the version; the
+ rebuild's swap must detect that and fall back to a fully-locked rebuild
+ rather than clobbering the concurrent write (no lost update)."""
+
+ def test_concurrent_add_during_rebuild_not_lost(self, tmp_path):
+ import threading
+
+ store = _make_store(
+ tmp_path,
+ index_type="hnsw",
+ dimension=4,
+ metric="l2",
+ normalize=False,
+ )
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3, dim=4))
+
+ build_started = threading.Event()
+ concurrent_done = threading.Event()
+ real_build = store._build_base_index
+
+ def slow_build(dimension, index_type, metric):
+ build_started.set()
+ concurrent_done.wait(timeout=5)
+ return real_build(dimension, index_type, metric)
+
+ store._build_base_index = slow_build
+
+ def do_rebuild():
+ store.apply(add_ids=[], add_vectors=None, remove_ids=[2])
+
+ t = threading.Thread(target=do_rebuild)
+ t.start()
+ assert build_started.wait(timeout=5)
+
+ # Concurrent pure-add of id 9 while the rebuild is off-lock building.
+ # (Pure add takes no rebuild path, so it does not hit slow_build.)
+ store.apply(add_ids=[9], add_vectors=_vecs(1, dim=4, seed=9))
+ concurrent_done.set()
+ t.join(timeout=5)
+ assert not t.is_alive()
+
+ # The rebuild removed 2; the concurrent add of 9 survived -> {1,3,9}.
+ assert set(store.live_ids()) == {1, 3, 9}
+ reloaded = FaissVectorStore.load(
+ tmp_path / "coll.faiss",
+ dimension=4,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ )
+ assert set(reloaded.live_ids()) == {1, 3, 9}
+
+
+class TestHnswOffLockRetryExhaustion:
+ """The off-lock rebuild retries a bounded number of times on a stale
+ snapshot, then gives up and falls back to a fully-locked rebuild. Guards
+ both the >1 retry-count guard (an off-by-one would either give up
+ prematurely or recurse forever) and the fallback call itself, which
+ re-acquires ``self._lock`` -- a non-reentrant ``threading.Lock`` -- from
+ OUTSIDE any held lock, so it must not deadlock."""
+
+ def test_hnsw_apply_gives_up_after_retries_and_falls_back_to_locked_rebuild(
+ self, tmp_path
+ ):
+ store = _make_store(tmp_path, index_type="hnsw", dimension=4)
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3, dim=4))
+
+ # Force the staleness check to ALWAYS see a mismatch: an ever-changing
+ # fingerprint differs between the Phase-1 snapshot and the Phase-3
+ # recheck on every attempt, no matter how many retries run.
+ counter = [0]
+
+ def always_changing_fingerprint():
+ counter[0] += 1
+ return (counter[0],)
+
+ store._file_fingerprint = always_changing_fingerprint
+
+ # Spy on the fallback so we can confirm it actually ran (and exactly
+ # once), not just that the final result happens to look right.
+ orig_apply_locked = store._apply_locked
+ fallback_calls = []
+
+ def spy_apply_locked(*args, **kwargs):
+ fallback_calls.append(1)
+ return orig_apply_locked(*args, **kwargs)
+
+ store._apply_locked = spy_apply_locked
+
+ stats = store.apply(add_ids=[], add_vectors=None, remove_ids=[2])
+
+ assert fallback_calls == [
+ 1
+ ] # fell back to the locked rebuild exactly once
+ assert stats["removed"] == 1
+ assert stats["added"] == 0
+ assert set(store.live_ids()) == {1, 3}
+ assert store.count() == 2
+
+
+class TestApplyFailureRecovery:
+ """apply()'s failure paths (_restore_from_disk / _reload_under_lock's
+ poison-discard branch) must never surface a partial in-memory mutation as
+ if it were durable, and must never dangle in a rebuilt-but-unpersisted
+ state. Failures here are driven through REAL code paths (a stubbed
+ ``persist()`` that genuinely raises) rather than by poking ``_poisoned``
+ by hand, so the assertions exercise the actual recovery logic."""
+
+ def test_first_ever_apply_failure_poisons_then_next_apply_discards_stale_mutation(
+ self, tmp_path
+ ):
+ store = _make_store(tmp_path, dimension=4)
+
+ # Simulate a genuine write failure (e.g. disk full) AFTER add() has
+ # already mutated the in-memory index but BEFORE anything durable is
+ # written -- no .faiss file exists yet at all.
+ def failing_persist(_path):
+ raise OSError("simulated disk failure on first-ever write")
+
+ store.persist = failing_persist
+
+ with pytest.raises(OSError, match="simulated disk failure"):
+ store.apply(add_ids=[1], add_vectors=_vecs(1, dim=4))
+
+ assert store._poisoned is True
+ assert not store._path.exists() # first write never landed
+
+ # Restore real persistence and drive a second, unrelated successful
+ # apply(). The never-persisted id 1 must NOT resurrect here.
+ store.persist = FaissVectorStore.persist.__get__(store)
+ stats = store.apply(add_ids=[2], add_vectors=_vecs(1, dim=4, seed=2))
+
+ assert stats == {"added": 1, "removed": 0}
+ assert store.live_ids() == [2]
+ assert store._poisoned is False
+
+ def test_restore_from_disk_poisons_store_when_disk_unreadable_after_failed_write(
+ self, tmp_path
+ ):
+ store = _make_store(tmp_path, dimension=4)
+ store.apply(
+ add_ids=[1], add_vectors=_vecs(1, dim=4)
+ ) # real durable file
+
+ # Simulate a torn/corrupting write: the persist call itself corrupts
+ # the on-disk bytes before failing, so _restore_from_disk()'s own
+ # re-read of disk (not a hand-set flag) is what discovers it can't
+ # recover and poisons the store.
+ path = store._path
+
+ def corrupt_then_fail(_path):
+ path.write_bytes(b"corrupted mid-write garbage")
+ raise OSError("simulated write failure mid-persist")
+
+ store.persist = corrupt_then_fail
+
+ with pytest.raises(
+ OSError, match="simulated write failure mid-persist"
+ ):
+ store.apply(add_ids=[2], add_vectors=_vecs(1, dim=4, seed=2))
+
+ assert store._poisoned is True
+
+ def test_hnsw_rebuild_persist_failure_reverts_to_disk_not_dangling_graph(
+ self, tmp_path
+ ):
+ store = _make_store(tmp_path, index_type="hnsw", dimension=4)
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3, dim=4))
+ pre_rebuild_ids = set(store.live_ids())
+
+ # Fail persist() ITSELF, right after Phase 3 has already swapped
+ # self._index to the rebuilt (post-removal) graph but before the new
+ # graph reaches disk -- disk still holds the pre-rebuild file.
+ def failing_persist(_path):
+ raise OSError("simulated persist failure mid hnsw rebuild")
+
+ store.persist = failing_persist
+
+ with pytest.raises(
+ OSError, match="simulated persist failure mid hnsw rebuild"
+ ):
+ store.apply(add_ids=[], add_vectors=None, remove_ids=[2])
+
+ # Reverted to the durable (pre-rebuild) state, not left dangling on
+ # the new, unpersisted, in-memory-only graph.
+ assert set(store.live_ids()) == pre_rebuild_ids
+ assert store._poisoned is False
+
+ def test_reload_under_lock_file_exists_branch_clears_poison_on_adopt(
+ self, tmp_path
+ ):
+ """REGRESSION for fix B (daa5e2ebb): the file-exists branch of
+ ``_reload_under_lock`` must clear ``self._poisoned`` (~line 678)
+ after adopting the verified on-disk index -- otherwise a store that
+ was poisoned by some earlier, unrelated failure stays permanently
+ poisoned even after it has successfully reloaded a known-good file,
+ and every subsequent read keeps raising the "poisoned" RuntimeError
+ forever, with no way to recover short of constructing a fresh
+ instance.
+
+ CRITICAL (tautology trap): this calls ``_reload_under_lock()``
+ DIRECTLY rather than going through ``apply()`` -- ``_apply_locked``
+ and ``_apply_hnsw`` ALSO clear ``_poisoned`` at their own tail
+ (~lines 865/926/980), so asserting on the result of a full apply()
+ would pass even with fix B reverted and prove nothing.
+ """
+ store = _make_store(tmp_path, dimension=4)
+ store.apply(add_ids=[1, 2], add_vectors=_vecs(2, dim=4))
+ assert store._path.exists() # a verified, matching-config file
+
+ # Poison the instance directly (the same acceptable-fallback
+ # approach the existing read-guard tests use) to isolate the
+ # file-exists branch of _reload_under_lock from however the
+ # poisoning originally happened.
+ store._poisoned = True
+
+ store._reload_under_lock()
+
+ assert store._poisoned is False
+ # Reads must actually succeed now (not raise the poisoned
+ # RuntimeError) and reflect the adopted on-disk state.
+ assert store.count() == 2
+ assert set(store.live_ids()) == {1, 2}
+ hits = store.search(_vecs(1, dim=4)[0], 2)
+ assert {i for i, _ in hits} == {1, 2}
+
+
+class TestPersistLoadRoundtripSearch:
+ """A real persist() -> load() cycle must be invisible to a caller: search
+ results (ids, order, scores) must be identical before and after, and for
+ HNSW, reconstruct() of every id must match what was actually indexed."""
+
+ @pytest.mark.parametrize("index_type", ["flat", "hnsw"])
+ def test_persist_load_roundtrip_preserves_search_ranking(
+ self, tmp_path, index_type
+ ):
+ store = _make_store(
+ tmp_path,
+ dimension=4,
+ index_type=index_type,
+ metric="cosine",
+ normalize=True,
+ )
+ ids = [10, 20, 30, 40, 50]
+ vecs = _vecs(5, dim=4, seed=7)
+ store.add(ids, vecs)
+ query = _vecs(1, dim=4, seed=99)[0]
+ before = store.search(query, 3)
+ assert before # sanity: got hits before persisting at all
+
+ path = tmp_path / f"rt_{index_type}.faiss"
+ store.persist(path)
+ loaded = FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type=index_type,
+ metric="cosine",
+ normalize=True,
+ )
+ after = loaded.search(query, 3)
+
+ assert [i for i, _ in after] == [i for i, _ in before]
+ for (id_before, score_before), (id_after, score_after) in zip(
+ before, after
+ ):
+ assert id_after == id_before
+ assert score_after == pytest.approx(score_before, abs=1e-5)
+
+ if index_type == "hnsw":
+ normalized = vecs.copy()
+ faiss.normalize_L2(normalized)
+ for vid, expected in zip(ids, normalized):
+ recon = loaded.reconstruct(vid)
+ assert recon is not None
+ np.testing.assert_allclose(
+ np.asarray(recon), expected, atol=1e-4
+ )
+
+
+class TestMetricIndexTypeCanonicalization:
+ """index_type/metric are canonicalized (strip + lower) so a caller who
+ passes mixed case or stray whitespace still gets the SAME physical index
+ every construction path builds -- otherwise 'COSINE' would build inner
+ product but a later 'cosine' comparison could mismatch it as L2."""
+
+ def test_uppercase_and_whitespace_metric_persist_reload_roundtrip(
+ self, tmp_path
+ ):
+ store = _make_store(
+ tmp_path,
+ dimension=4,
+ index_type=" Flat ",
+ metric=" COSINE ",
+ normalize=True,
+ )
+ # Canonicalized immediately at construction time.
+ assert store.metric == "cosine"
+ assert store.index_type == "flat"
+
+ store.add([1, 2], _vecs(2, dim=4))
+ path = tmp_path / "canon.faiss"
+ store.persist(path)
+
+ # load() with the canonical spelling must NOT raise: create() and
+ # _physical_config_reason() must canonicalize identically.
+ loaded = FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert loaded.count() == 2
+ assert loaded.metric == "cosine"
+ assert loaded.index_type == "flat"
+
+ # The physical index really is inner-product -- non-canonical input
+ # did not silently fall through to the L2 default.
+ base = faiss.downcast_index(loaded._index.index)
+ assert base.metric_type == faiss.METRIC_INNER_PRODUCT
+
+
+class TestPersistTempSweep:
+ def test_persist_sweeps_stale_temp_files(self, tmp_path):
+ import os
+ import time
+
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ path = tmp_path / "out.faiss"
+ # A stale temp left by a hard-killed prior write, backdated well past
+ # the sweep age threshold so it is recognized as a genuine orphan.
+ stale = tmp_path / "out.faiss.deadbeef.tmp"
+ stale.write_bytes(b"garbage")
+ old = time.time() - 4000
+ os.utime(stale, (old, old))
+ assert stale.exists()
+ store.persist(path)
+ assert path.exists()
+ assert not stale.exists() # swept
+ assert list(tmp_path.glob("*.tmp")) == []
+
+ def test_persist_leaves_recent_temp_untouched(self, tmp_path):
+ # A just-created temp may belong to a concurrent (multi-process) writer
+ # for the SAME path whose rename hasn't landed yet — the age gate must
+ # not sweep it, or that writer crashes with FileNotFoundError.
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ path = tmp_path / "out.faiss"
+ recent = tmp_path / "out.faiss.inflight.tmp"
+ recent.write_bytes(b"another writer's in-flight bytes")
+ store.persist(path)
+ assert path.exists()
+ assert recent.exists() # too recent to be treated as an orphan
+
+ def test_persist_leaves_sibling_index_temp_untouched(self, tmp_path):
+ store = _make_store(tmp_path)
+ store.add([1], _vecs(1))
+ path = tmp_path / "out.faiss"
+ sibling = tmp_path / "other.faiss.abc.tmp" # a different index's temp
+ sibling.write_bytes(b"x")
+ store.persist(path)
+ assert sibling.exists() # scoped to path.name, sibling untouched
+
+
+class TestHnswOffLockRaceMultiInstance:
+ """The off-lock rebuild's staleness check must be PER-FILE, not
+ per-instance: production builds a FRESH FaissVectorStore per operation and
+ shares only the write lock, so a concurrent writer is a different Python
+ object. A per-instance counter would never see it; the on-disk fingerprint
+ does."""
+
+ def test_concurrent_write_from_other_instance_not_lost(self, tmp_path):
+ import threading
+
+ lock = threading.Lock()
+ path = tmp_path / "coll.faiss"
+ # Instance A seeds the index.
+ a = FaissVectorStore.create(
+ dimension=4,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ path=path,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+ a.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3, dim=4))
+
+ # Instance B — a SEPARATE object loaded from the same file, same lock.
+ b = FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ lock=lock,
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+
+ build_started = threading.Event()
+ concurrent_done = threading.Event()
+ real_build = b._build_base_index
+
+ def slow_build(dimension, index_type, metric):
+ build_started.set()
+ concurrent_done.wait(timeout=5)
+ return real_build(dimension, index_type, metric)
+
+ b._build_base_index = slow_build
+
+ def b_rebuild():
+ b.apply(add_ids=[], add_vectors=None, remove_ids=[2])
+
+ t = threading.Thread(target=b_rebuild)
+ t.start()
+ assert build_started.wait(timeout=5)
+
+ # Instance A (different object) persists a concurrent add of id 9 while
+ # B is mid off-lock rebuild. B must detect the file changed underneath
+ # (fingerprint), fall back, and preserve id 9.
+ a.apply(add_ids=[9], add_vectors=_vecs(1, dim=4, seed=9))
+ concurrent_done.set()
+ t.join(timeout=6)
+ assert not t.is_alive()
+
+ final = FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ )
+ # id 9 (A's write) survived; id 2 (B's removal) is gone. A per-instance
+ # counter would have let B clobber A -> {1,3}, losing id 9.
+ assert set(final.live_ids()) == {1, 3, 9}
+
+
+class TestLoadConfigValidation:
+ """load() must verify the PHYSICAL index matches the caller-declared
+ index_type/metric, not trust the label — a stale/foreign file adopted under
+ a mismatched config either crashes .delete() or silently rebuilds the file.
+ """
+
+ def _persist(self, tmp_path, *, index_type, metric, normalize):
+ store = _make_store(
+ tmp_path,
+ dimension=4,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ )
+ # apply() persists under the lock, leaving a real .faiss on disk.
+ store.apply(add_ids=[1, 2], add_vectors=_vecs(2, dim=4), remove_ids=[])
+ return tmp_path / "coll.faiss"
+
+ def _load(self, path, *, index_type, metric, normalize):
+ return FaissVectorStore.load(
+ path,
+ dimension=4,
+ index_type=index_type,
+ metric=metric,
+ normalize=normalize,
+ lock=threading.Lock(),
+ integrity_record=_noop_record,
+ integrity_verify=_ok_verify,
+ )
+
+ def test_hnsw_file_loaded_as_flat_raises(self, tmp_path):
+ path = self._persist(
+ tmp_path, index_type="hnsw", metric="l2", normalize=False
+ )
+ with pytest.raises(ValueError, match="index_type"):
+ self._load(path, index_type="flat", metric="l2", normalize=False)
+
+ def test_flat_file_loaded_as_hnsw_raises(self, tmp_path):
+ path = self._persist(
+ tmp_path, index_type="flat", metric="cosine", normalize=True
+ )
+ with pytest.raises(ValueError, match="index_type"):
+ self._load(path, index_type="hnsw", metric="cosine", normalize=True)
+
+ def test_metric_family_mismatch_raises(self, tmp_path):
+ # cosine builds METRIC_INNER_PRODUCT; loading as l2 (METRIC_L2) mismatches.
+ path = self._persist(
+ tmp_path, index_type="flat", metric="cosine", normalize=True
+ )
+ with pytest.raises(ValueError, match="metric"):
+ self._load(path, index_type="flat", metric="l2", normalize=False)
+
+ def test_matching_config_loads(self, tmp_path):
+ path = self._persist(
+ tmp_path, index_type="flat", metric="cosine", normalize=True
+ )
+ store = self._load(
+ path, index_type="flat", metric="cosine", normalize=True
+ )
+ assert store.count() == 2
+
+ def test_cosine_and_dot_product_are_interchangeable(self, tmp_path):
+ # Both map to METRIC_INNER_PRODUCT — same physical index, so loading a
+ # cosine file as dot_product must NOT raise (compare metric FAMILY).
+ path = self._persist(
+ tmp_path, index_type="flat", metric="cosine", normalize=True
+ )
+ store = self._load(
+ path, index_type="flat", metric="dot_product", normalize=True
+ )
+ assert store.count() == 2
+
+ def test_reload_rejects_wrong_type_file(self, tmp_path):
+ """apply()'s reload-under-lock must enforce the SAME physical-type check
+ as load(): a wrong-typed file swapped in at the path (a concurrent
+ writer / stale leftover) must be refused, not silently adopted — which
+ would misroute the delete (HNSW-as-flat raises; flat-as-hnsw rebuilds)."""
+ import faiss
+
+ store = _make_store(
+ tmp_path,
+ dimension=4,
+ index_type="flat",
+ metric="l2",
+ normalize=False,
+ )
+ store.apply(add_ids=[1], add_vectors=_vecs(1, dim=4), remove_ids=[])
+
+ # Swap the on-disk file for an HNSW IndexIDMap2 of the same dimension.
+ hnsw = faiss.IndexIDMap2(faiss.IndexHNSWFlat(4, 32, faiss.METRIC_L2))
+ hnsw.add_with_ids(_vecs(2, dim=4), np.array([10, 11], dtype="int64"))
+ faiss.write_index(hnsw, str(tmp_path / "coll.faiss"))
+
+ # The next apply() reloads under the lock and must refuse the wrong type.
+ with pytest.raises(RuntimeError, match="physical index"):
+ store.apply(add_ids=[2], add_vectors=_vecs(1, dim=4), remove_ids=[])
diff --git a/tests/vector_stores/test_full_migration_lifecycle.py b/tests/vector_stores/test_full_migration_lifecycle.py
new file mode 100644
index 0000000000..450b0574f3
--- /dev/null
+++ b/tests/vector_stores/test_full_migration_lifecycle.py
@@ -0,0 +1,492 @@
+"""Full legacy-migration lifecycle test at the SHARED (pre-per-user-scoping)
+cache path -- the real production upgrade order, end to end in one chain.
+
+Before this file, each phase of the cutover had isolated coverage (phase-1 in
+``test_legacy_cleanup_no_plaintext.py``, the per-user relocation in
+``test_migrate_legacy_index_files.py``, phase-2 in
+``test_legacy_rekey_orchestrator.py``) but nothing drove the FULL upgrade
+sequence a real deployment hits: a pre-cutover install has its FAISS index
+sitting directly under the shared ``cache/rag_indices/`` root (no per-user
+subdirectory existed yet), and the very first thing that happens after
+upgrading is, in order:
+
+ 1. server startup runs phase-1 (``migrate_legacy_docstores``) against the
+ SHARED root -- extracting sidecars, deleting plaintext ``.pkl``s;
+ 2. the first per-user touch (search/index) relocates that shared-root index
+ into the new per-user subdirectory
+ (``LibraryRAGService._migrate_legacy_index_files``, invoked via
+ ``_preflight_index_path``);
+ 3. login-time phase-2 (``rekey_user_indexes``) converts the relocated
+ (still old-format) ``.faiss`` into a real ``IndexIDMap2`` keyed by
+ ``DocumentChunk.id``, without re-embedding;
+ 4. ordinary indexing/search then has to keep working against that
+ migrated-in-place index -- a new document must MERGE into it (not
+ create a second, duplicate ``RAGIndex`` row), and old content must
+ still be searchable, rehydrated from the DB by id;
+ 5. (if the harness allows) deleting the collection's index must leave
+ nothing at either the legacy OR the relocated path.
+
+A ``_CountingEmbeddings`` fake proves the "no re-embed" guarantee the same
+way ``test_legacy_rekey_orchestrator.py`` does: ``embed_documents_calls``
+stays pinned at 1 (the original legacy build) through the ENTIRE migrate ->
+relocate -> rekey -> search chain, and only increments by exactly 1 when a
+genuinely NEW document is indexed afterward. A whole-tmp_path plaintext grep
+(mirroring ``test_no_plaintext_production_path.py``) is re-run after every
+stage, so a regression that lets the SECRET marker leak into any on-disk
+artifact (not just the ``.faiss``/sidecar) is caught immediately.
+"""
+
+import hashlib
+import uuid
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import faiss
+import pytest
+from langchain_community.vectorstores import FAISS
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentStatus,
+ EmbeddingProvider,
+ RAGIndex,
+ SourceType,
+)
+from local_deep_research.utilities.db_utils import get_settings_manager
+from local_deep_research.vector_stores import get_vector_store_class
+from local_deep_research.vector_stores.legacy_cleanup import (
+ _rag_cache_root,
+ migrate_legacy_docstores,
+)
+from local_deep_research.vector_stores.legacy_rekey import (
+ REKEY_MARKER_SETTING,
+ rekey_user_indexes,
+)
+
+SECRET = "ZZZ_FULL_LIFECYCLE_MARKER_9c31f0"
+FRESH_MARKER = "FRESH_DOC_MARKER_5b7e"
+
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+_FACADE_MOD = "local_deep_research.vector_stores.facade"
+_REKEY_MOD = "local_deep_research.vector_stores.legacy_rekey"
+_DELETE_MOD = (
+ "local_deep_research.research_library.deletion.services.collection_deletion"
+)
+
+
+class _CountingEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings that COUNT calls, so the test
+ can assert the migrated chunks are never re-embedded (mirrors
+ ``test_legacy_rekey_orchestrator.py``'s harness)."""
+
+ def __init__(self, dim: int = 2):
+ self.dim = dim
+ self.embed_documents_calls = 0
+ self.embed_query_calls = 0
+
+ def _vec(self, text: str):
+ h = abs(hash(text))
+ return [float((h >> (8 * i)) % 97) for i in range(self.dim)]
+
+ def embed_documents(self, texts):
+ self.embed_documents_calls += 1
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ self.embed_query_calls += 1
+ return self._vec(text)
+
+
+def _make_legacy_index(dir_path, ids, texts, embeddings, *, index_name):
+ """Write a REAL old-format ``<index_name>.faiss`` + ``.pkl`` pair,
+ exactly as the pre-cutover LangChain-FAISS wrapper did, directly under
+ the given (SHARED, pre-per-user-scoping) directory."""
+ dir_path.mkdir(parents=True, exist_ok=True)
+ metadatas = [{"chunk": i} for i in range(len(texts))]
+ vs = FAISS.from_texts(texts, embeddings, metadatas=metadatas, ids=ids)
+ vs.save_local(str(dir_path), index_name=index_name)
+
+
+def _grep_all(root, needle: bytes):
+ """Every on-disk file under ``root`` that contains ``needle``."""
+ return [
+ str(f)
+ for f in root.rglob("*")
+ if f.is_file() and needle in f.read_bytes()
+ ]
+
+
+@contextmanager
+def _session_ctx(session):
+ yield session
+
+
+def db_session():
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ yield session
+ session.close()
+ engine.dispose()
+
+
+def patched_sites(db_session, mocker):
+ """Route every ``get_user_db_session`` call-site this lifecycle touches
+ to ONE shared in-memory session (facade, the RAG service, phase-2 rekey,
+ and collection deletion), and stub the orthogonal file-integrity
+ bookkeeping -- mirrors ``test_no_plaintext_production_path.py`` and
+ ``test_legacy_rekey_orchestrator.py``'s harness style."""
+
+ def _ctx(*_a, **_k):
+ return _session_ctx(db_session)
+
+ mocker.patch(f"{_FACADE_MOD}.get_user_db_session", _ctx)
+ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _ctx)
+ mocker.patch(f"{_REKEY_MOD}.get_user_db_session", _ctx)
+ mocker.patch(f"{_DELETE_MOD}.get_user_db_session", _ctx)
+
+ fim = MagicMock()
+ fim.verify_file.return_value = (True, None)
+ fim.record_file.return_value = None
+ mocker.patch(f"{_RAG_MOD}.FileIntegrityManager", return_value=fim)
+ # legacy_rekey constructs its own FileIntegrityManager; patch the class
+ # itself (no return_value) so every attribute access on an instance is a
+ # harmless MagicMock -- integrity bookkeeping is orthogonal to the
+ # migration invariants under test here.
+ mocker.patch(f"{_REKEY_MOD}.FileIntegrityManager")
+
+ return db_session
+
+
+def _add_chunk(
+ session,
+ *,
+ embedding_id: str,
+ chunk_text: str,
+ collection_name: str,
+ source_id: str,
+ chunk_index: int,
+ embedding_model: str,
+ embedding_dim: int = 2,
+) -> int:
+ chunk = DocumentChunk(
+ chunk_hash=f"hash-{embedding_id}",
+ source_type="document",
+ source_id=source_id,
+ collection_name=collection_name,
+ chunk_text=chunk_text,
+ chunk_index=chunk_index,
+ start_char=0,
+ end_char=len(chunk_text),
+ word_count=len(chunk_text.split()),
+ embedding_id=embedding_id,
+ embedding_model=embedding_model,
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=embedding_dim,
+ )
+ session.add(chunk)
+ session.flush()
+ return chunk.id
+
+
+def _marker_is_set(session, username: str) -> bool:
+ settings = get_settings_manager(db_session=session, username=username)
+ return settings.get_bool_setting(REKEY_MARKER_SETTING, False)
+
+
+class TestFullMigrationLifecycle:
+ def test_shared_legacy_index_migrate_relocate_rekey_merge_delete(
+ self, tmp_path, monkeypatch, patched_sites, mocker
+ ):
+ session = patched_sites
+ username = "erin"
+ db_password = "pw"
+ embedding_model = "fake-model"
+ embedding_provider = "sentence_transformers"
+
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ collection_id = uuid.uuid4().hex
+ collection_name = f"collection_{collection_id}"
+ # The EXACT hash `_get_index_hash` computes -- so the RAGIndex row we
+ # seed below is the one `_get_or_create_rag_index` finds (not a fresh
+ # one it would otherwise create).
+ index_hash = hashlib.sha256(
+ f"{collection_name}:{embedding_model}:{embedding_provider}".encode()
+ ).hexdigest()
+
+ # =====================================================================
+ # Step 1: a REALISTIC LEGACY index directly at the SHARED (NOT
+ # per-user) cache/rag_indices root, with a RAGIndex row whose
+ # index_path points there, and DocumentChunk rows carrying a SECRET
+ # marker (chunk TEXT lives only in the DB -- never the .faiss/.pkl
+ # bytes are trusted to hold it, but the pre-cutover .pkl format did).
+ # =====================================================================
+ legacy_root = _rag_cache_root()
+ emb = _CountingEmbeddings(dim=2)
+ legacy_uuids = [uuid.uuid4().hex for _ in range(2)]
+ legacy_texts = [
+ f"legacy chunk one mentioning {SECRET}",
+ f"legacy chunk two also mentioning {SECRET}",
+ ]
+ _make_legacy_index(
+ legacy_root, legacy_uuids, legacy_texts, emb, index_name=index_hash
+ )
+ legacy_faiss = legacy_root / f"{index_hash}.faiss"
+ legacy_pkl = legacy_root / f"{index_hash}.pkl"
+ legacy_sidecar = legacy_root / f"{index_hash}.idmap.json"
+ assert legacy_faiss.is_file()
+ assert legacy_pkl.is_file()
+ # Control: the raw legacy pickle docstore really DOES hold the
+ # plaintext marker -- proves the grep-based assertions below are not
+ # vacuously passing on a fixture that never had it.
+ assert SECRET.encode() in legacy_pkl.read_bytes()
+
+ session.add(Collection(id=collection_id, name="Legacy collection"))
+ source_type = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(source_type)
+ session.commit()
+
+ legacy_source_id = "legacy-doc-1"
+ legacy_ids = [
+ _add_chunk(
+ session,
+ embedding_id=u,
+ chunk_text=t,
+ collection_name=collection_name,
+ source_id=legacy_source_id,
+ chunk_index=i,
+ embedding_model=embedding_model,
+ )
+ for i, (u, t) in enumerate(zip(legacy_uuids, legacy_texts))
+ ]
+
+ rag_index = RAGIndex(
+ collection_name=collection_name,
+ embedding_model=embedding_model,
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ index_path=str(legacy_faiss), # the SHARED, pre-scoping path
+ index_hash=index_hash,
+ chunk_size=500,
+ chunk_overlap=50,
+ # Pin the physical-build config so nothing here falls back to
+ # (possibly DB-dependent) local_search_* settings lookups.
+ index_type="flat",
+ distance_metric="cosine",
+ normalize_vectors=False,
+ is_current=True,
+ )
+ session.add(rag_index)
+ session.commit()
+ session.refresh(rag_index)
+
+ assert emb.embed_documents_calls == 1 # only the original legacy build
+
+ # =====================================================================
+ # Step 2 (phase-1): migrate_legacy_docstores() extracts the text-free
+ # sidecar and deletes the plaintext .pkl.
+ # =====================================================================
+ migrate_result = migrate_legacy_docstores()
+ assert migrate_result["extracted"] == 1
+ assert not legacy_pkl.exists()
+ assert legacy_sidecar.exists()
+ assert SECRET.encode() not in legacy_sidecar.read_bytes()
+ # Whole-tree grep: plaintext is gone from disk after phase-1 alone
+ # (the DB is in-memory, so every on-disk artifact is fair game).
+ assert _grep_all(tmp_path, SECRET.encode()) == []
+
+ # =====================================================================
+ # Step 3: trigger the per-user relocation. In production this is
+ # invoked automatically by `_preflight_index_path` (called from every
+ # `_get_vector_index` — i.e. every search/index) the first time a
+ # user touches this collection after upgrading; we call the SAME
+ # method directly here to isolate this phase from the load/embedding
+ # machinery a full search/index call would also exercise.
+ # =====================================================================
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = emb
+
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ svc = LibraryRAGService(
+ username=username,
+ db_password=db_password,
+ embedding_model=embedding_model,
+ embedding_provider=embedding_provider,
+ distance_metric="cosine",
+ normalize_vectors=False,
+ index_type="flat",
+ embedding_manager=emb_mgr,
+ )
+
+ index_path = svc._get_index_path(index_hash)
+ assert index_path != legacy_faiss
+ assert not index_path.exists()
+
+ svc._migrate_legacy_index_files(legacy_faiss, index_path, rag_index)
+
+ assert index_path.exists()
+ assert not legacy_faiss.exists()
+ new_sidecar = index_path.with_name(index_path.stem + ".idmap.json")
+ assert new_sidecar.exists()
+ assert not legacy_sidecar.exists()
+ session.refresh(rag_index)
+ assert rag_index.index_path == str(index_path)
+
+ # The relocated .faiss is STILL the raw legacy format -- relocation
+ # is a pure file move; rekey (phase-2, next) hasn't run yet.
+ raw = faiss.read_index(str(index_path))
+ assert not isinstance(raw, faiss.IndexIDMap2)
+ assert emb.embed_documents_calls == 1 # relocation never re-embeds
+
+ # =====================================================================
+ # Step 3 (phase-2): rekey_user_indexes() converts the relocated index
+ # into a real IndexIDMap2 keyed by DocumentChunk.id, marker set.
+ # =====================================================================
+ stats = rekey_user_indexes(username, db_password)
+ assert stats["checked"] == 1
+ assert stats["rekeyed"] == 1
+ assert stats["quarantined"] == 0
+ assert not new_sidecar.exists()
+ assert _marker_is_set(session, username) is True
+
+ raw2 = faiss.read_index(str(index_path))
+ assert isinstance(raw2, faiss.IndexIDMap2)
+
+ store_cls = get_vector_store_class()
+ store = store_cls.load(
+ index_path,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ )
+ assert set(store.live_ids()) == set(legacy_ids)
+
+ # THE core "no re-embed" invariant: migrate + relocate + rekey never
+ # called embed_documents again -- only the ORIGINAL legacy build did.
+ assert emb.embed_documents_calls == 1
+ assert emb.embed_query_calls == 0
+ assert _grep_all(tmp_path, SECRET.encode()) == []
+
+ # =====================================================================
+ # Step 4: SEARCH through the real VectorIndex facade (via the
+ # service) rehydrates the SECRET text from the DB by id -- the store
+ # itself never held it -- and still doesn't re-embed the chunks.
+ # =====================================================================
+ hits = svc.search(f"legacy chunk {SECRET}", collection_id, top_k=5)
+ assert hits
+ assert any(SECRET in h.text for h in hits)
+ assert emb.embed_documents_calls == 1 # search never re-embeds chunks
+ assert emb.embed_query_calls > 0 # the query itself WAS embedded
+
+ # =====================================================================
+ # Step 5: a NEW document indexed normally MERGES into the relocated +
+ # rekeyed index (searchable both ways), with NO duplicate RAGIndex
+ # row created for this collection.
+ # =====================================================================
+ new_document_id = uuid.uuid4().hex
+ new_body = (
+ f"Brand new document body, unrelated content, mentions "
+ f"{FRESH_MARKER} exactly once."
+ )
+ session.add(
+ Document(
+ id=new_document_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(new_body.encode()).hexdigest(),
+ title="New doc",
+ text_content=new_body,
+ original_url="http://example.com/new",
+ file_size=len(new_body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.commit()
+
+ docs_before = emb.embed_documents_calls
+ result = svc.index_document(new_document_id, collection_id)
+ assert result["status"] == "success", result
+ assert result["chunk_count"] > 0
+
+ # Exactly ONE more embed_documents call -- for the NEW doc's chunks
+ # only. The migrated legacy content is still never re-embedded.
+ assert emb.embed_documents_calls == docs_before + 1
+
+ rag_rows = (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .all()
+ )
+ assert len(rag_rows) == 1, "a duplicate RAGIndex row was created"
+ assert rag_rows[0].id == rag_index.id
+
+ merged_store = store_cls.load(
+ index_path,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ )
+ new_chunk_ids = {
+ row.id
+ for row in session.query(DocumentChunk).filter_by(
+ source_type="document", source_id=new_document_id
+ )
+ }
+ assert new_chunk_ids
+ assert set(merged_store.live_ids()) == set(legacy_ids) | new_chunk_ids
+
+ old_hits = svc.search(f"legacy chunk {SECRET}", collection_id, top_k=5)
+ assert any(SECRET in h.text for h in old_hits)
+ new_hits = svc.search(FRESH_MARKER, collection_id, top_k=5)
+ assert any(FRESH_MARKER in h.text for h in new_hits)
+ # Cross-check: a query for the NEW marker must not accidentally
+ # resolve to the OLD document (sanity that the merge kept both
+ # sources distinct, not that search merely returns everything).
+ assert all(
+ SECRET not in h.text for h in new_hits if FRESH_MARKER in h.text
+ )
+
+ assert _grep_all(tmp_path, SECRET.encode()) == []
+ assert _grep_all(tmp_path, FRESH_MARKER.encode()) == []
+
+ # =====================================================================
+ # Step 6 (if feasible): deleting the collection's index leaves
+ # NOTHING at either the legacy or the relocated path.
+ # =====================================================================
+ from local_deep_research.research_library.deletion.services.collection_deletion import (
+ CollectionDeletionService,
+ )
+
+ deleter = CollectionDeletionService(username)
+ delete_result = deleter.delete_collection_index_only(collection_id)
+ assert delete_result["deleted"] is True
+ assert delete_result["indices_deleted"] == 1
+
+ assert not index_path.exists()
+ assert not legacy_faiss.exists()
+ assert not new_sidecar.exists()
+ assert not legacy_sidecar.exists()
+ assert (
+ session.query(RAGIndex)
+ .filter_by(collection_name=collection_name)
+ .count()
+ == 0
+ )
+
+ svc.close()
diff --git a/tests/vector_stores/test_integrity_tamper_lifecycle.py b/tests/vector_stores/test_integrity_tamper_lifecycle.py
new file mode 100644
index 0000000000..b3a25bb52e
--- /dev/null
+++ b/tests/vector_stores/test_integrity_tamper_lifecycle.py
@@ -0,0 +1,424 @@
+"""Integrity-tamper recovery lifecycle, end to end, with a REAL
+``FileIntegrityManager`` + REAL faiss (no fake checksum functions).
+
+This drives the actual production wiring: ``LibraryRAGService`` constructs a
+real ``FileIntegrityManager`` (registered with the real ``FAISSIndexVerifier``)
+in its ``__init__`` — this test does NOT stub that class out, only its DB
+session dependency (routed to a shared in-memory sqlite session, mirroring
+``test_no_plaintext_production_path.py`` / ``test_legacy_rekey_orchestrator.py``).
+The on-disk ``.faiss`` file and the ``FileIntegrityRecord`` checksum it is
+checked against are both real.
+
+Flow covered:
+
+ 1. Index a collection through the real service -> a real ``.faiss`` is
+ written AND its checksum is recorded by the real integrity manager.
+ Search returns the secret content.
+ 2. TAMPER: flip bytes in the on-disk ``.faiss`` so its checksum no longer
+ matches the recorded one.
+ 3. WRITE-PATH recovery (``force_reindex=True`` -> ``reset_stale_state=True``):
+ the tamper is DETECTED (``checksum_mismatch``), the file is quarantined
+ to ``<path>.corrupt-*``, the index is rebuilt from the encrypted DB (the
+ ``DocumentChunk`` rows), and search works again afterwards.
+ 4. READ-PATH fails closed (plain ``search()`` -> ``reset_stale_state=False``):
+ with a freshly tampered file, search RAISES without renaming/deleting the
+ file and without mutating the collection's indexed DB state -- a mere
+ read must never destructively quarantine (a byte-flip cost-amplification
+ vector: an attacker who can flip one bit of a world-adjacent file must
+ not be able to force a full, expensive re-embed merely by triggering a
+ search).
+
+Each test below includes a CONTROL proving the assertion actually bites (not
+a tautology): #3 checks no quarantine file exists on the healthy baseline
+before tampering; #4 checks the pre-tamper search succeeds fine, so the
+post-tamper raise is caused by the tamper, not some other test artifact.
+"""
+
+import hashlib
+import os
+import time
+import uuid
+from contextlib import contextmanager
+from unittest.mock import MagicMock
+
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.file_integrity import (
+ FileIntegrityRecord,
+)
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ RAGIndex,
+ RagDocumentStatus,
+ SourceType,
+)
+
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+_FACADE_MOD = "local_deep_research.vector_stores.facade"
+_INTEGRITY_MOD = "local_deep_research.security.file_integrity.integrity_manager"
+_THREAD_MOD = "local_deep_research.database.thread_local_session"
+
+SECRET = "ZZZ_TAMPER_LIFECYCLE_MARKER_9f13cd"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings (mirrors the canonical harness)."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ import numpy as np
+
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+@contextmanager
+def _session_ctx(session):
+ yield session
+
+
+def _sha256(path) -> str:
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(4096), b""):
+ h.update(block)
+ return h.hexdigest()
+
+
+def _tamper(path) -> None:
+ """Flip a byte in the middle of the file so its checksum changes, and
+ force the mtime to be observably different (some filesystems have coarse
+ mtime granularity that could otherwise make a same-second rewrite look
+ unchanged to the smart-verification mtime check)."""
+ data = bytearray(path.read_bytes())
+ assert len(data) > 4, "index file too small to tamper meaningfully"
+ mid = len(data) // 2
+ data[mid] ^= 0xFF
+ path.write_bytes(bytes(data))
+ future = time.time() + 5
+ os.utime(path, (future, future))
+
+
+class _Rig:
+ def __init__(self, svc, session, collection_id, document_id):
+ self.svc = svc
+ self.session = session
+ self.collection_id = collection_id
+ self.document_id = document_id
+ self.collection_name = f"collection_{collection_id}"
+
+ def rag_index_row(self):
+ return (
+ self.session.query(RAGIndex)
+ .filter_by(collection_name=self.collection_name, is_current=True)
+ .first()
+ )
+
+ def index_path(self):
+ row = self.rag_index_row()
+ assert row is not None
+ from pathlib import Path
+
+ return Path(row.index_path)
+
+ def integrity_record(self, path):
+ return (
+ self.session.query(FileIntegrityRecord)
+ .filter_by(file_path=str(path.resolve()))
+ .first()
+ )
+
+
+def rig(tmp_path, monkeypatch, mocker):
+ """Real service, real FileIntegrityManager, real on-disk faiss index, a
+ shared in-memory sqlite session standing in for the (encrypted, in
+ production) per-user DB, and a real Document+Collection seeded with a
+ secret marker -- already indexed once before the test body runs."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ def _shared(*_a, **_k):
+ return _session_ctx(session)
+
+ # Route every get_user_db_session call site involved in this flow --
+ # the service, the facade, AND the real FileIntegrityManager -- to the
+ # SAME shared session so integrity records/verifications and RAGIndex/
+ # DocumentChunk rows agree with each other.
+ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _shared)
+ mocker.patch(f"{_FACADE_MOD}.get_user_db_session", _shared)
+ mocker.patch(f"{_INTEGRITY_MOD}.get_user_db_session", _shared)
+ # Force the nested-integrity-write path to fall back to
+ # get_user_db_session (patched above) rather than a real thread-local
+ # session (there is none outside a Flask/background-worker context here).
+ mocker.patch(f"{_THREAD_MOD}.get_current_thread_session", return_value=None)
+
+ username = "tamperuser"
+ collection_id = uuid.uuid4().hex
+ document_id = uuid.uuid4().hex
+ source_type = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(source_type)
+ session.add(Collection(id=collection_id, name="Tamper test collection"))
+ body = (
+ f"This document's confidential body mentions {SECRET} several times. "
+ * 5
+ )
+ session.add(
+ Document(
+ id=document_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(body.encode()).hexdigest(),
+ title=f"Secret doc {SECRET}",
+ text_content=body,
+ original_url="http://example.com/secret",
+ file_size=len(body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.commit()
+
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = _FakeEmbeddings(dim=8)
+
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ svc = LibraryRAGService(
+ username=username,
+ db_password="pw",
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ )
+
+ # Real FileIntegrityManager, not a mock/stub.
+ from local_deep_research.security.file_integrity import FileIntegrityManager
+
+ assert isinstance(svc.integrity_manager, FileIntegrityManager)
+
+ result = svc.index_document(document_id, collection_id)
+ assert result["status"] == "success", result
+ assert result["chunk_count"] > 0
+
+ r = _Rig(svc, session, collection_id, document_id)
+
+ index_path = r.index_path()
+ assert index_path.is_file(), "indexing did not write a real .faiss file"
+
+ record = r.integrity_record(index_path)
+ assert record is not None, (
+ "the real FileIntegrityManager did not record an integrity checksum "
+ "for the freshly indexed .faiss file"
+ )
+ assert record.checksum == _sha256(index_path)
+
+ hits = svc.search(f"confidential body {SECRET}", collection_id, top_k=3)
+ assert hits and any(SECRET in h.text for h in hits), (
+ "baseline search did not return the indexed secret content"
+ )
+
+ yield r
+ svc.close()
+
+
+def _quarantine_files(index_path):
+ return list(index_path.parent.glob(f"{index_path.name}.corrupt-*"))
+
+
+class TestWritePathRecoversFromTamper:
+ def test_reindex_detects_quarantines_and_rebuilds(self, rig):
+ index_path = rig.index_path()
+ record = rig.integrity_record(index_path)
+ baseline_checksum = record.checksum
+
+ # CONTROL: no quarantine artifact exists on the healthy baseline --
+ # proves the assertion below is detecting the tamper, not some
+ # pre-existing/incidental file from indexing itself.
+ assert _quarantine_files(index_path) == []
+
+ _tamper(index_path)
+ tampered_checksum = _sha256(index_path)
+ assert tampered_checksum != baseline_checksum, (
+ "tamper helper did not actually change the file's checksum"
+ )
+
+ baseline_chunk_count = rig.rag_index_row().chunk_count
+ assert baseline_chunk_count > 0
+
+ # WRITE-path operation: force_reindex=True drives
+ # _get_vector_index(reset_stale_state=True), which is the only path
+ # authorized to quarantine + rebuild.
+ result = rig.svc.index_document(
+ rig.document_id, rig.collection_id, force_reindex=True
+ )
+ assert result["status"] == "success", result
+
+ # 1) Detected + quarantined: a .corrupt-* file now exists holding the
+ # TAMPERED bytes (not deleted -- preserved for inspection).
+ quarantined = _quarantine_files(index_path)
+ assert len(quarantined) == 1, (
+ f"expected exactly one quarantined file, got {quarantined}"
+ )
+ assert _sha256(quarantined[0]) == tampered_checksum
+
+ # 2) Rebuilt: a FRESH, valid .faiss now lives at the original path.
+ assert index_path.is_file()
+ rebuilt_checksum = _sha256(index_path)
+ assert rebuilt_checksum != tampered_checksum
+ # Real faiss IndexIDMap2, not a corrupt/foreign blob.
+ import faiss as faiss_mod
+
+ raw = faiss_mod.read_index(str(index_path))
+ assert isinstance(raw, faiss_mod.IndexIDMap2)
+ assert raw.ntotal > 0
+
+ # 3) The rebuilt file's checksum was re-recorded by the real
+ # integrity manager (not left pointing at stale/tampered bytes).
+ new_record = rig.integrity_record(index_path)
+ assert new_record.checksum == rebuilt_checksum
+
+ # 4) Rebuilt FROM THE ENCRYPTED DB: the DocumentChunk rows for this
+ # document/collection still hold the secret text (the store itself
+ # never held it), and the vector ids in the rebuilt index match the
+ # DB's live chunk ids exactly.
+ chunk_rows = (
+ rig.session.query(DocumentChunk)
+ .filter_by(
+ source_type="document",
+ source_id=rig.document_id,
+ collection_name=rig.collection_name,
+ )
+ .all()
+ )
+ assert chunk_rows
+ assert any(SECRET in c.chunk_text for c in chunk_rows)
+
+ from local_deep_research.vector_stores import get_vector_store_class
+
+ store_cls = get_vector_store_class()
+ rebuilt_dim = rig.rag_index_row().embedding_dimension
+ store = store_cls.load(
+ index_path,
+ dimension=rebuilt_dim,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert set(store.live_ids()) == {c.id for c in chunk_rows}
+
+ # 5) Search works again on the rebuilt content.
+ hits = rig.svc.search(
+ f"confidential body {SECRET}", rig.collection_id, top_k=3
+ )
+ assert hits and any(SECRET in h.text for h in hits), (
+ "search did not recover the secret content after rebuild"
+ )
+
+
+class TestReadPathFailsClosed:
+ def test_search_raises_without_quarantine_or_db_mutation(self, rig):
+ index_path = rig.index_path()
+ record_before = rig.integrity_record(index_path)
+ baseline_checksum = record_before.checksum
+
+ # CONTROL: the pre-tamper baseline search already succeeded in the
+ # fixture -- re-run it here too, immediately before tampering, so the
+ # post-tamper raise below is attributable to the tamper itself, not a
+ # search path that always raises regardless of file state.
+ hits = rig.svc.search(
+ f"confidential body {SECRET}", rig.collection_id, top_k=3
+ )
+ assert hits and any(SECRET in h.text for h in hits)
+
+ # Snapshot the DB state a mere read must not mutate.
+ rag_row = rig.rag_index_row()
+ chunk_count_before = rag_row.chunk_count
+ total_docs_before = rag_row.total_documents
+ doc_collection_before = (
+ rig.session.query(DocumentCollection)
+ .filter_by(
+ document_id=rig.document_id, collection_id=rig.collection_id
+ )
+ .first()
+ )
+ assert doc_collection_before.indexed is True
+ rag_status_before = (
+ rig.session.query(RagDocumentStatus)
+ .filter_by(
+ document_id=rig.document_id, collection_id=rig.collection_id
+ )
+ .first()
+ )
+ assert rag_status_before is not None
+
+ _tamper(index_path)
+ tampered_checksum = _sha256(index_path)
+ assert tampered_checksum != baseline_checksum
+
+ # READ-path operation: plain search() -> reset_stale_state=False.
+ with pytest.raises(RuntimeError, match="checksum_mismatch"):
+ rig.svc.search(
+ f"confidential body {SECRET}", rig.collection_id, top_k=3
+ )
+
+ # 1) NOT quarantined: no .corrupt-* file was created.
+ assert _quarantine_files(index_path) == [], (
+ "a read-path search destructively quarantined the file -- a "
+ "byte-flip cost-amplification vector"
+ )
+
+ # 2) NOT renamed/deleted: the (tampered) bytes are still at the
+ # original path, unchanged by the failed read.
+ assert index_path.is_file()
+ assert _sha256(index_path) == tampered_checksum
+
+ # 3) DB state (chunk counts / indexed flags / status row) is
+ # untouched -- a mere read must never reset indexed state.
+ rag_row_after = rig.rag_index_row()
+ assert rag_row_after.chunk_count == chunk_count_before
+ assert rag_row_after.total_documents == total_docs_before
+ doc_collection_after = (
+ rig.session.query(DocumentCollection)
+ .filter_by(
+ document_id=rig.document_id, collection_id=rig.collection_id
+ )
+ .first()
+ )
+ assert doc_collection_after.indexed is True
+ rag_status_after = (
+ rig.session.query(RagDocumentStatus)
+ .filter_by(
+ document_id=rig.document_id, collection_id=rig.collection_id
+ )
+ .first()
+ )
+ assert rag_status_after is not None
+
+ # 4) The integrity record's baseline checksum is unchanged (a failed
+ # verification records a FAILURE in the audit trail, but must not
+ # silently adopt the tampered bytes as the new "good" checksum).
+ record_after = rig.integrity_record(index_path)
+ assert record_after.checksum == baseline_checksum
diff --git a/tests/vector_stores/test_legacy_cleanup_no_plaintext.py b/tests/vector_stores/test_legacy_cleanup_no_plaintext.py
new file mode 100644
index 0000000000..4ebfd98586
--- /dev/null
+++ b/tests/vector_stores/test_legacy_cleanup_no_plaintext.py
@@ -0,0 +1,776 @@
+"""Security regression test: the legacy-docstore migration leaves NO plaintext
+chunk text or metadata on disk.
+
+Builds a REAL legacy LangChain-FAISS index (``.faiss`` + pickled ``.pkl``
+docstore) containing a known secret marker in both the chunk text and the
+metadata, runs the startup migration, and then greps every file under the RAG
+cache to prove the marker is gone — while the text-free ``.idmap.json`` sidecar
+(needed for the no-re-embed re-key) survives.
+
+Uses ``LDR_DATA_DIR`` -> ``tmp_path`` so it can never touch real data.
+"""
+
+import json
+import uuid
+
+import pytest
+from langchain_community.vectorstores import FAISS
+from langchain_core.embeddings import Embeddings
+
+from src.local_deep_research.vector_stores.legacy_cleanup import (
+ migrate_legacy_docstores,
+ _rag_cache_root,
+)
+
+# Distinctive marker that must not survive anywhere on disk after migration.
+SECRET = "ZZZ_PLAINTEXT_CHUNK_SECRET_9f3a1c"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic 2-D embeddings — no model download, no network."""
+
+ def embed_documents(self, texts):
+ return [[float(len(t) % 7), 1.0] for t in texts]
+
+ def embed_query(self, query):
+ return [1.0, 0.0]
+
+
+def cache_root(tmp_path, monkeypatch):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ return _rag_cache_root()
+
+
+def _make_legacy_index(dir_path, ids, texts, *, index_name="idx"):
+ """Write a real old-format ``<index_name>.faiss`` + ``.pkl`` pair."""
+ dir_path.mkdir(parents=True, exist_ok=True)
+ metadatas = [{"document_title": f"secret-title-{SECRET}"} for _ in texts]
+ vs = FAISS.from_texts(
+ texts, _FakeEmbeddings(), metadatas=metadatas, ids=ids
+ )
+ vs.save_local(str(dir_path), index_name=index_name)
+
+
+def _grep_all(root, needle: bytes):
+ return [
+ str(f)
+ for f in root.rglob("*")
+ if f.is_file() and needle in f.read_bytes()
+ ]
+
+
+def test_migration_refuses_symlinked_cache_root(cache_root, tmp_path):
+ """A SYMLINKED rag_indices/ root would make os.walk + root.chmod + the
+ .pkl-delete pass operate OUTSIDE the intended tree (os.walk and Path.chmod
+ both follow a symlinked TOP-LEVEL path; followlinks=False only guards
+ symlinked CHILDREN). Migration must refuse and flag it, not transparently
+ follow it — chmod'ing and pattern-deleting files it does not own."""
+ import os
+
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ foreign_pkl = outside / "abc123.pkl"
+ foreign_pkl.write_bytes(b"not ours")
+ # Intentionally world-readable to prove the migration does NOT chmod it
+ # (the symlinked-root refusal must leave out-of-tree files untouched).
+ os.chmod(outside, 0o755) # noqa: S103
+
+ # cache_root = <data>/cache/rag_indices — make it a symlink to `outside`.
+ cache_root.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ os.symlink(outside, cache_root, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ result = migrate_legacy_docstores()
+
+ # Refused + flagged, nothing deleted.
+ assert result["scan_errors"] >= 1
+ assert result["deleted"] == 0
+ # The foreign .pkl outside the tree survives AND its dir mode is unchanged
+ # (root.chmod never followed the symlink).
+ assert foreign_pkl.exists()
+ assert (os.stat(outside).st_mode & 0o777) == 0o755
+
+
+def test_migration_reports_scan_errors_for_unreadable_subdir(cache_root):
+ """An unreadable subdirectory hides its .pkl from BOTH the delete pass and
+ the re-scan, so migrate must NOT report clean success — it must surface the
+ scan error (else a plaintext .pkl silently survives)."""
+ import os
+
+ if os.geteuid() == 0:
+ pytest.skip("running as root bypasses directory permissions")
+
+ blocked = cache_root / "blockeduser"
+ ids = [uuid.uuid4().hex]
+ _make_legacy_index(blocked, ids, [f"hidden {SECRET}"])
+ assert (blocked / "idx.pkl").exists()
+
+ os.chmod(blocked, 0o000) # make the subdir unscannable
+ try:
+ result = migrate_legacy_docstores()
+ # The blocked .pkl is invisible to the scan, so `remaining` reads 0 —
+ # but scan_errors must flag the incomplete migration.
+ assert result["scan_errors"] >= 1
+ finally:
+ os.chmod(blocked, 0o700) # restore so tmp cleanup can run
+
+
+def test_migration_reports_scan_errors_for_symlinked_subdir(
+ cache_root, tmp_path
+):
+ """os.walk does not descend into a symlinked subdir (followlinks=False) and
+ does not call onerror for it, so a .pkl inside would be silently missed. The
+ migration must flag the symlinked dir as an unscanned (incomplete) case."""
+ import os
+
+ # Real directory (outside the walked tree) holding a legacy .pkl.
+ target = tmp_path / "real_target"
+ ids = [uuid.uuid4().hex]
+ _make_legacy_index(target, ids, [f"behind-symlink {SECRET}"])
+ assert (target / "idx.pkl").exists()
+
+ # Symlink it under the RAG cache root — os.walk will skip it silently.
+ cache_root.mkdir(parents=True, exist_ok=True)
+ link = cache_root / "linked"
+ try:
+ os.symlink(target, link, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ result = migrate_legacy_docstores()
+ assert result["scan_errors"] >= 1
+
+
+def test_migration_flags_symlinked_pkl_and_spares_real_target(
+ cache_root, tmp_path
+):
+ """A .pkl that is a symlink is a trap: unlink() would remove only the link,
+ leaving the real plaintext target intact while the run logs clean success.
+ The migration must flag it (scan_errors) and NOT touch the real file."""
+ import os
+
+ # Real plaintext docstore OUTSIDE the cache root.
+ real = tmp_path / "outside"
+ _make_legacy_index(real, [uuid.uuid4().hex], [f"outside {SECRET}"])
+ real_pkl = real / "idx.pkl"
+ assert SECRET.encode() in real_pkl.read_bytes()
+
+ # A symlink to it under the RAG cache root.
+ cache_root.mkdir(parents=True, exist_ok=True)
+ link = cache_root / "linked.pkl"
+ try:
+ os.symlink(real_pkl, link)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks not supported on this platform")
+
+ result = migrate_legacy_docstores()
+
+ # Flagged as incomplete, and the real plaintext file is untouched.
+ assert result["scan_errors"] >= 1
+ assert real_pkl.exists()
+ assert SECRET.encode() in real_pkl.read_bytes()
+
+
+def test_migration_leaves_no_plaintext_on_disk(cache_root):
+ userdir = cache_root / "userhash1"
+ # Real embedding_id format: uuid4().hex (what _store_chunks_to_db writes).
+ ids = [uuid.uuid4().hex for _ in range(3)]
+ texts = [f"one {SECRET} x", f"two {SECRET}", "three plain"]
+ _make_legacy_index(userdir, ids, texts)
+
+ pkl = userdir / "idx.pkl"
+ # Precondition: the plaintext really is in the legacy .pkl before migration.
+ assert SECRET.encode() in pkl.read_bytes()
+
+ result = migrate_legacy_docstores()
+
+ assert result["extracted"] == 1
+ assert result["deleted"] == 1
+ assert result["remaining"] == 0
+ assert not pkl.exists()
+ assert (userdir / "idx.faiss").exists() # vectors kept for the re-key
+
+ # The core assertion: the secret marker (text AND metadata) is gone from
+ # EVERY file under the RAG cache — nothing plaintext left on disk.
+ assert _grep_all(cache_root, SECRET.encode()) == []
+
+ # The sidecar preserves exactly the text-free position->uuid map.
+ sidecar = userdir / "idx.idmap.json"
+ assert sidecar.exists()
+ assert SECRET not in sidecar.read_text()
+ idmap = json.loads(sidecar.read_text())
+ assert set(idmap.values()) == set(ids)
+
+
+def test_quarantined_pkl_is_deleted(cache_root):
+ userdir = cache_root / "userhash2"
+ _make_legacy_index(userdir, ["u1", "u2"], [f"q {SECRET}", "plain"])
+ # Simulate the quarantine rename the old code does on a corrupt index.
+ (userdir / "idx.pkl").rename(userdir / "idx.pkl.corrupt-123456789")
+
+ result = migrate_legacy_docstores()
+
+ assert result["deleted"] == 1
+ assert result["remaining"] == 0
+ # Quarantined docstores also hold plaintext -> must be gone, no sidecar.
+ assert _grep_all(cache_root, SECRET.encode()) == []
+ assert not list(userdir.glob("*.pkl*"))
+
+
+def test_unreadable_pkl_deleted_and_flagged_for_reindex(cache_root):
+ userdir = cache_root / "userhash3"
+ userdir.mkdir(parents=True)
+ # A .pkl that is not a valid pickle -> extraction fails.
+ bad = userdir / "idx.pkl"
+ bad.write_bytes(b"not a pickle " + SECRET.encode())
+
+ result = migrate_legacy_docstores()
+
+ assert result["reindex_fallback"] == 1
+ assert result["deleted"] == 1
+ assert result["remaining"] == 0
+ assert not bad.exists() # deleted anyway -> plaintext removed
+ assert _grep_all(cache_root, SECRET.encode()) == []
+ assert not (userdir / "idx.idmap.json").exists() # no map to preserve
+
+
+def test_idempotent_on_clean_tree(cache_root):
+ cache_root.mkdir(parents=True, exist_ok=True)
+ assert migrate_legacy_docstores()["found"] == 0
+ # Second run on an already-clean tree is a no-op, not an error.
+ assert migrate_legacy_docstores()["found"] == 0
+
+
+def test_second_migration_run_after_real_migration_preserves_sidecar_and_is_noop(
+ cache_root,
+):
+ """Phase-1 run on a REAL legacy .pkl writes the .idmap.json sidecar that
+ phase-2 (login-time rekey) depends on. A second phase-1 run — startup
+ always re-runs it — must find nothing left to migrate (the .pkl is already
+ gone) and must NOT touch the sidecar bytes; phase-2 reads that exact
+ position->uuid map, so clobbering or rewriting it here would corrupt the
+ no-re-embed re-key."""
+ userdir = cache_root / "userF"
+ ids = [uuid.uuid4().hex for _ in range(2)]
+ _make_legacy_index(userdir, ids, [f"one {SECRET}", "two"])
+
+ first = migrate_legacy_docstores()
+ assert first["extracted"] == 1
+ assert first["deleted"] == 1
+
+ sidecar = userdir / "idx.idmap.json"
+ assert sidecar.exists()
+ sidecar_bytes = sidecar.read_bytes()
+
+ second = migrate_legacy_docstores()
+
+ # Nothing left to migrate: the .pkl is already gone.
+ assert second["found"] == 0
+ assert second["extracted"] == 0
+ assert second["deleted"] == 0
+ # Byte-identical: the sidecar phase-2 needs was not touched, let alone
+ # rewritten, by the no-op second run.
+ assert sidecar.read_bytes() == sidecar_bytes
+
+
+def test_extract_map_sweeps_stale_tmp_but_spares_fresh_concurrent_tmp(
+ cache_root,
+):
+ """``_write_sidecar_atomic``'s stale-``.tmp`` sweep must remove an orphaned
+ temp left by a hard-killed prior migration run, but never touch a FRESH
+ concurrent worker's still-in-flight temp for the same sidecar (gunicorn
+ -w N can start phase-1 in two workers at once). Creates both temps with
+ the REAL ``tempfile.mkstemp`` prefix/suffix the production write uses, so
+ this fails outright if the sweep's glob and the write's own mkstemp call
+ ever drift apart."""
+ import os
+ import tempfile
+ import time
+ from pathlib import Path
+
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ _STALE_TMP_AGE_SECONDS,
+ _write_sidecar_atomic,
+ )
+
+ userdir = cache_root / "userG"
+ userdir.mkdir(parents=True)
+ sidecar = userdir / "idx.idmap.json"
+
+ # Stale sibling temp: same prefix/suffix the real write uses, backdated
+ # past the age threshold -> must be swept.
+ stale_fd, stale_name = tempfile.mkstemp(
+ dir=str(userdir), prefix=f"{sidecar.name}.", suffix=".tmp"
+ )
+ os.close(stale_fd)
+ stale = Path(stale_name)
+ old_time = time.time() - _STALE_TMP_AGE_SECONDS - 60
+ os.utime(stale, (old_time, old_time))
+
+ # Fresh concurrent temp: identical naming, just created -> must be spared.
+ fresh_fd, fresh_name = tempfile.mkstemp(
+ dir=str(userdir), prefix=f"{sidecar.name}.", suffix=".tmp"
+ )
+ os.close(fresh_fd)
+ fresh = Path(fresh_name)
+
+ _write_sidecar_atomic(sidecar, {"0": uuid.uuid4().hex})
+
+ assert not stale.exists()
+ assert fresh.exists()
+
+
+def _write_raw_pkl(dir_path, index_to_docstore_id, *, index_name="idx"):
+ """Write a ``.pkl`` with an arbitrary (restricted-unpickler-compatible) map
+ + a matching fake ``.faiss`` so it looks like a real index pair."""
+ import pickle
+
+ from langchain_community.docstore.in_memory import InMemoryDocstore
+
+ dir_path.mkdir(parents=True, exist_ok=True)
+ with open(dir_path / f"{index_name}.pkl", "wb") as f:
+ pickle.dump((InMemoryDocstore({}), index_to_docstore_id), f)
+ (dir_path / f"{index_name}.faiss").write_bytes(b"fake-vectors")
+
+
+def test_malformed_idmap_does_not_crash_and_others_processed(cache_root):
+ # A tampered .pkl whose id-map is a list, not a dict — must not crash the
+ # whole run (else other users' plaintext would never be removed).
+ _write_raw_pkl(cache_root / "userA", ["not", "a", "dict"])
+ _make_legacy_index(
+ cache_root / "userB",
+ [uuid.uuid4().hex, uuid.uuid4().hex],
+ [f"real {SECRET}", "x"],
+ )
+
+ result = migrate_legacy_docstores() # must NOT raise
+
+ assert not (cache_root / "userA" / "idx.pkl").exists() # deleted anyway
+ assert not (cache_root / "userA" / "idx.idmap.json").exists() # no sidecar
+ assert result["reindex_fallback"] >= 1
+ # userB was still reached and processed despite userA's bad file.
+ assert not (cache_root / "userB" / "idx.pkl").exists()
+ assert (cache_root / "userB" / "idx.idmap.json").exists()
+ assert result["remaining"] == 0
+ assert _grep_all(cache_root, SECRET.encode()) == []
+
+
+def test_non_uuid_values_never_reach_the_sidecar(cache_root):
+ smuggled = "EXFIL_SECRET_TEXT_LOOKALIKE_zzzzz"
+ # One smuggled value + one real uuid — a single bad entry rejects the map.
+ _write_raw_pkl(
+ cache_root / "userC",
+ {0: smuggled, 1: "0123456789abcdef0123456789abcdef"},
+ )
+
+ result = migrate_legacy_docstores()
+
+ assert not (cache_root / "userC" / "idx.pkl").exists()
+ assert not (cache_root / "userC" / "idx.idmap.json").exists()
+ assert result["reindex_fallback"] >= 1
+ # The smuggled text never lands anywhere on disk.
+ assert _grep_all(cache_root, smuggled.encode()) == []
+
+
+def test_non_string_idmap_value_is_rejected_without_str_coercion(cache_root):
+ # A tampered .pkl whose id-map VALUE is a non-string object (here a nested
+ # list) must be rejected outright, never coerced via str(). str() on a
+ # maliciously deep/shared structure is a pickle "billion laughs"
+ # amplification that could hang/OOM the whole startup migration.
+ _write_raw_pkl(
+ cache_root / "userD",
+ {
+ 0: ["not", "a", ["uuid", "string"]],
+ 1: "0123456789abcdef0123456789abcdef",
+ },
+ )
+
+ # Must complete quickly and without raising; the bad entry rejects the map.
+ result = migrate_legacy_docstores()
+
+ assert not (cache_root / "userD" / "idx.pkl").exists() # deleted anyway
+ assert not (cache_root / "userD" / "idx.idmap.json").exists() # no sidecar
+ assert result["reindex_fallback"] >= 1
+ assert result["remaining"] == 0
+
+
+def test_full_migration_round_trip_no_reembed(cache_root):
+ """old LangChain FAISS -> extract sidecar -> re-key to IndexIDMap2 by int id,
+ without re-embedding; search returns the int ids; orphans dropped."""
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+ from src.local_deep_research.vector_stores import get_vector_store_class
+
+ userdir = cache_root / "u"
+ uuids = [uuid.uuid4().hex for _ in range(4)]
+ _make_legacy_index(userdir, uuids, [f"t{i}" for i in range(4)])
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+
+ migrate_legacy_docstores()
+ assert sidecar.exists() and not (userdir / "idx.pkl").exists()
+
+ # DB map uuid -> DocumentChunk.id; drop uuids[3] to simulate a deleted chunk.
+ uuid_to_id = {uuids[0]: 100, uuids[1]: 200, uuids[2]: 300}
+ res = rekey_index_file(
+ faiss_p,
+ sidecar,
+ uuid_to_id,
+ dimension=2, # _FakeEmbeddings is 2-D
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert res == {"reconstructed": 4, "kept": 3, "orphaned": 1}
+ # rekey_index_file no longer deletes the sidecar — the caller does that only
+ # after recording integrity (crash-consistency), so it survives here.
+ assert sidecar.exists()
+
+ # The re-keyed index is IndexIDMap2 keyed by the int DocumentChunk.ids.
+ store = get_vector_store_class().load(
+ faiss_p,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert set(store.live_ids()) == {100, 200, 300}
+ hits = store.search([0.5, 0.5], 3)
+ assert all(cid in {100, 200, 300} for cid, _ in hits)
+ # No plaintext anywhere on disk after the full migration.
+ assert not any(str(f).endswith(".pkl") for f in cache_root.rglob("*"))
+
+
+def test_rekey_already_migrated_tolerates_concurrently_deleted_sidecar(
+ cache_root,
+):
+ """Cross-process rekey race: a winning worker finalizes (rebuilds the
+ IndexIDMap2, then deletes the sidecar as its completion signal). A losing
+ worker re-enters rekey_index_file for the same index; its already-migrated
+ short-circuit must treat the now-missing sidecar as 'already finalized' and
+ report success — NOT raise FileNotFoundError, which makes the caller
+ destructively quarantine a perfectly healthy, just-rekeyed index.
+ """
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ uuids = [uuid.uuid4().hex for _ in range(3)]
+ _make_legacy_index(userdir, uuids, [f"t{i}" for i in range(3)])
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+ migrate_legacy_docstores()
+
+ uuid_to_id = {uuids[0]: 100, uuids[1]: 200, uuids[2]: 300}
+ params = dict(
+ dimension=2, index_type="flat", metric="cosine", normalize=True
+ )
+
+ # Winner: re-key to IndexIDMap2, then delete the sidecar (Phase B signal).
+ rekey_index_file(faiss_p, sidecar, uuid_to_id, **params)
+ sidecar.unlink()
+ assert not sidecar.exists()
+
+ # Loser: re-enter with the sidecar already gone — must NOT raise, and must
+ # report the already-migrated index as kept.
+ res = rekey_index_file(faiss_p, sidecar, uuid_to_id, **params)
+ assert res["kept"] == 3
+ assert res["orphaned"] == 0
+
+
+def test_rekey_fresh_build_tolerates_concurrent_migration(cache_root, mocker):
+ """Fresh-rebuild path cross-process race: worker B loads the OLD-format
+ index, and before B reads the sidecar, worker A finishes its own rekey
+ (persists the new IndexIDMap2, deletes the shared sidecar). B's sidecar read
+ then raises FileNotFoundError; B must re-read the file, see it is already an
+ IndexIDMap2, and report success — NOT raise (which makes the caller quarantine
+ a perfectly good, just-migrated index).
+ """
+ import faiss
+ import numpy as np
+
+ import src.local_deep_research.vector_stores.legacy_cleanup as lc
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ userdir.mkdir(parents=True, exist_ok=True)
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json" # deliberately never created → gone
+
+ raw = faiss.IndexFlatL2(2)
+ raw.add(np.random.rand(3, 2).astype("float32"))
+ migrated = faiss.IndexIDMap2(faiss.IndexFlatL2(2))
+ migrated.add_with_ids(
+ np.random.rand(3, 2).astype("float32"),
+ np.array([100, 200, 300], dtype="int64"),
+ )
+ # First read_index() (line 444) → the OLD raw index; the except-block re-read
+ # → the IndexIDMap2 the concurrent worker just wrote.
+ mocker.patch.object(lc, "read_index", side_effect=[raw, migrated])
+
+ res = rekey_index_file(
+ faiss_p,
+ sidecar,
+ {"0": "x"},
+ dimension=2,
+ index_type="flat",
+ metric="l2",
+ normalize=False,
+ )
+ assert res["kept"] == 3
+ assert res["orphaned"] == 0
+
+
+def test_rekey_on_plain_indexidmap_raises_not_aborts(cache_root):
+ """A plain faiss.IndexIDMap (our format's superclass, but NOT IndexIDMap2)
+ on disk must raise a CATCHABLE ValueError, never fall through to
+ reconstruct_n — which aborts the whole process (SIGABRT) uncatchably. If
+ this test process survives and sees a ValueError, the guard works.
+ """
+ import faiss
+ import numpy as np
+
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ userdir.mkdir(parents=True, exist_ok=True)
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+
+ idmap = faiss.IndexIDMap(faiss.IndexFlatL2(2)) # plain IndexIDMap, not *2
+ idmap.add_with_ids(
+ np.random.rand(2, 2).astype("float32"),
+ np.array([10, 20], dtype="int64"),
+ )
+ faiss.write_index(idmap, str(faiss_p))
+ sidecar.write_text(json.dumps({"0": "0" * 32}))
+
+ with pytest.raises(ValueError):
+ rekey_index_file(
+ faiss_p,
+ sidecar,
+ {"0" * 32: 10},
+ dimension=2,
+ index_type="flat",
+ metric="l2",
+ normalize=False,
+ )
+
+
+def test_rekey_rejects_duplicate_ids_from_sidecar(cache_root):
+ """Two legacy positions resolving to the SAME DocumentChunk.id must be
+ refused (would bake an id-collision the set()-based read-back can't see)."""
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ uuids = [uuid.uuid4().hex, uuid.uuid4().hex]
+ _make_legacy_index(userdir, uuids, ["a", "b"])
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+ migrate_legacy_docstores()
+
+ # Both uuids resolve to the SAME int id -> duplicate.
+ with pytest.raises(ValueError, match="duplicate"):
+ rekey_index_file(
+ faiss_p,
+ sidecar,
+ {uuids[0]: 100, uuids[1]: 100},
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+
+def test_rekey_on_already_migrated_index_does_not_crash(cache_root):
+ """Crash-consistency: if the process died after rekey persisted the new
+ IndexIDMap2 but BEFORE it deleted the sidecar, the next login re-runs
+ rekey_index_file on an already-migrated file. That must NOT reconstruct
+ (which aborts the process via an untranslated C++ faiss exception, or
+ silently reconstructs wrong vectors) — it must detect the new format,
+ drop the stale sidecar, and leave the index intact.
+ """
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+ from src.local_deep_research.vector_stores import get_vector_store_class
+
+ userdir = cache_root / "u"
+ uuids = [uuid.uuid4().hex for _ in range(3)]
+ _make_legacy_index(userdir, uuids, [f"t{i}" for i in range(3)])
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+ uuid_to_id = {uuids[0]: 100, uuids[1]: 200, uuids[2]: 300}
+
+ # First rekey converts to IndexIDMap2 (leaves the sidecar for the caller).
+ migrate_legacy_docstores()
+ rekey_index_file(
+ faiss_p,
+ sidecar,
+ uuid_to_id,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert sidecar.exists()
+
+ # The interrupted-before-finalize window: the FULL original sidecar (all
+ # three positions) survives next to the already-migrated IndexIDMap2 file,
+ # so the guard's id cross-check matches the on-disk ids.
+ sidecar.write_text(
+ json.dumps({"0": uuids[0], "1": uuids[1], "2": uuids[2]})
+ )
+
+ # Re-run on the already-migrated file: must return cleanly (no process
+ # abort) and leave the index + sidecar intact (rekey_index_file no longer
+ # deletes the sidecar — the caller finalizes).
+ res = rekey_index_file(
+ faiss_p,
+ sidecar,
+ uuid_to_id,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert res["kept"] == 3
+ assert sidecar.exists()
+ store = get_vector_store_class().load(
+ faiss_p,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+ assert set(store.live_ids()) == {100, 200, 300}
+
+
+def test_rekey_rejects_already_migrated_with_mismatched_ids(cache_root):
+ """An already-migrated IndexIDMap2 whose on-disk ids disagree with the
+ current sidecar+DB resolution (stale / foreign / cross-tenant file) must be
+ REFUSED — silently adopting it would rehydrate the wrong document's text."""
+ import faiss
+ import numpy as np
+
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ userdir.mkdir(parents=True, exist_ok=True)
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+
+ # On-disk IndexIDMap2 with ids [7777, 8888].
+ idx = faiss.IndexIDMap2(faiss.IndexFlatL2(2))
+ idx.add_with_ids(
+ np.random.rand(2, 2).astype("float32"),
+ np.array([7777, 8888], dtype="int64"),
+ )
+ faiss.write_index(idx, str(faiss_p))
+
+ # But the sidecar + uuid_to_id resolve to DIFFERENT ids [1, 2].
+ u0, u1 = "a" * 32, "b" * 32
+ sidecar.write_text(json.dumps({"0": u0, "1": u1}))
+ with pytest.raises(ValueError, match="do not match"):
+ rekey_index_file(
+ faiss_p,
+ sidecar,
+ {u0: 1, u1: 2},
+ dimension=2,
+ index_type="flat",
+ metric="l2",
+ normalize=False,
+ )
+
+
+def test_rekey_rejects_foreign_faiss_class_without_segfault(cache_root):
+ """A non-base faiss class at the index path (disk corruption / tamper /
+ foreign file) must raise a CATCHABLE ValueError, not reach reconstruct_n —
+ which segfaults the process uncatchably and, on the login rekey path,
+ crash-loops the worker. The test completing (not crashing) is the proof."""
+ import faiss
+ import numpy as np
+
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ userdir.mkdir(parents=True, exist_ok=True)
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+
+ # IndexLSH is a valid, serializable faiss index that is neither an
+ # IndexIDMap family member nor a reconstruct-safe base index.
+ lsh = faiss.IndexLSH(8, 16)
+ lsh.add(np.random.rand(2, 8).astype("float32"))
+ faiss.write_index(lsh, str(faiss_p))
+ u0, u1 = "a" * 32, "b" * 32
+ sidecar.write_text(json.dumps({"0": u0, "1": u1}))
+
+ with pytest.raises(ValueError, match="reconstruct-safe|foreign"):
+ rekey_index_file(
+ faiss_p,
+ sidecar,
+ {u0: 1, u1: 2},
+ dimension=8,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+
+def test_rekey_rejects_already_migrated_with_duplicate_ids(cache_root):
+ """An already-migrated IndexIDMap2 carrying a DUPLICATE id must be refused,
+ even though its id *set* matches the expected resolution. A set comparison
+ dedupes and cannot see the duplicate (which double-counts/mis-scores that
+ chunk in search); the guard must compare multiplicities, mirroring the
+ fresh-build path's duplicate check."""
+ import faiss
+ import numpy as np
+
+ from src.local_deep_research.vector_stores.legacy_cleanup import (
+ rekey_index_file,
+ )
+
+ userdir = cache_root / "u"
+ userdir.mkdir(parents=True, exist_ok=True)
+ faiss_p = userdir / "idx.faiss"
+ sidecar = userdir / "idx.idmap.json"
+
+ # On-disk IndexIDMap2 with ids [5, 5, 6] — id 5 is duplicated. Its *set*
+ # is {5, 6}, so a set-only comparison would silently adopt this file.
+ idx = faiss.IndexIDMap2(faiss.IndexFlatL2(2))
+ idx.add_with_ids(
+ np.random.rand(3, 2).astype("float32"),
+ np.array([5, 5, 6], dtype="int64"),
+ )
+ faiss.write_index(idx, str(faiss_p))
+
+ # Sidecar + uuid_to_id resolve to the SAME set {5, 6} (two uuids -> id 5),
+ # so only the multiplicity check can catch the corruption.
+ u0, u1, u2 = "a" * 32, "b" * 32, "c" * 32
+ sidecar.write_text(json.dumps({"0": u0, "1": u1, "2": u2}))
+ with pytest.raises(ValueError, match="duplicate"):
+ rekey_index_file(
+ faiss_p,
+ sidecar,
+ {u0: 5, u1: 5, u2: 6},
+ dimension=2,
+ index_type="flat",
+ metric="l2",
+ normalize=False,
+ )
diff --git a/tests/vector_stores/test_legacy_rekey_orchestrator.py b/tests/vector_stores/test_legacy_rekey_orchestrator.py
new file mode 100644
index 0000000000..8b460d1a80
--- /dev/null
+++ b/tests/vector_stores/test_legacy_rekey_orchestrator.py
@@ -0,0 +1,846 @@
+"""Integration tests for ``rekey_user_indexes`` (phase-2 orchestrator) in
+``local_deep_research.vector_stores.legacy_rekey``.
+
+Before this file, ``rekey_user_indexes`` itself had zero direct coverage —
+only its ``_quarantine_and_reset`` helper was pinned (see
+``test_legacy_rekey_quarantine.py``). These tests drive the orchestrator loop
+end to end with a REAL in-memory SQLite DB (the same ``Base`` schema used in
+production), a REAL on-disk legacy FAISS+pickle pair (built the same way the
+old LangChain wrapper wrote it), and a deterministic network-free embeddings
+fake — mirroring ``test_no_plaintext_production_path.py``'s harness style.
+
+Three invariants are locked:
+
+ (a) ``rekey_user_indexes`` sweeps EVERY ``RAGIndex`` row for the user, not
+ just the ``is_current=True`` one — a stale historical row (left behind
+ by an embedding-model switch) is still reachable via
+ ``index_hash``-lookup if the model setting is ever reverted, so an
+ un-rekeyed old-format ``.faiss`` there would hard-fail search.
+ (b) If a legacy plaintext ``.pkl`` survives phase-1 and cannot be deleted,
+ the per-user completion marker (``REKEY_MARKER_SETTING``) must NOT be
+ set — this is the guarantee that phase-2 never gates a user "done"
+ while plaintext still sits on disk.
+ (c) The full round trip (phase-1 ``migrate_legacy_docstores`` -> phase-2
+ ``rekey_user_indexes``) removes the ``.pkl``, persists a real
+ ``IndexIDMap2`` keyed by ``DocumentChunk.id``, and a search through the
+ production ``VectorIndex`` facade rehydrates the correct text —
+ without ever re-embedding the original chunks. A second run is a
+ no-op (marker short-circuit).
+"""
+
+import json
+import os
+import threading
+import uuid
+from contextlib import contextmanager
+
+import faiss as faiss_mod
+import numpy as np
+import pytest
+from langchain_community.vectorstores import FAISS
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ DocumentChunk,
+ DocumentCollection,
+ EmbeddingProvider,
+ RAGIndex,
+)
+from local_deep_research.utilities.db_utils import get_settings_manager
+from local_deep_research.vector_stores import get_vector_store_class
+from local_deep_research.vector_stores.legacy_cleanup import (
+ migrate_legacy_docstores,
+ _rag_cache_root,
+)
+from local_deep_research.vector_stores.legacy_rekey import (
+ REKEY_MARKER_SETTING,
+ rekey_user_indexes,
+)
+
+_REKEY_MOD = "local_deep_research.vector_stores.legacy_rekey"
+_FACADE_MOD = "local_deep_research.vector_stores.facade"
+
+
+class _CountingEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings that COUNT how many times each
+ method is called, so a test can assert re-keying never re-embeds."""
+
+ def __init__(self, dim: int = 2):
+ self.dim = dim
+ self.embed_documents_calls = 0
+ self.embed_query_calls = 0
+
+ def _vec(self, text: str):
+ # Cheap deterministic vector: stable across runs, no RNG/model.
+ h = abs(hash(text))
+ return [float((h >> (8 * i)) % 97) for i in range(self.dim)]
+
+ def embed_documents(self, texts):
+ self.embed_documents_calls += 1
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ self.embed_query_calls += 1
+ return self._vec(text)
+
+
+def _make_legacy_index(dir_path, ids, texts, embeddings, *, index_name="idx"):
+ """Write a REAL old-format ``<index_name>.faiss`` + ``.pkl`` pair, exactly
+ as the pre-cutover LangChain-FAISS wrapper did."""
+ dir_path.mkdir(parents=True, exist_ok=True)
+ metadatas = [{"chunk": i} for i in range(len(texts))]
+ vs = FAISS.from_texts(texts, embeddings, metadatas=metadatas, ids=ids)
+ vs.save_local(str(dir_path), index_name=index_name)
+
+
+@contextmanager
+def _session_ctx(session):
+ yield session
+
+
+def db_session():
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ yield session
+ session.close()
+ engine.dispose()
+
+
+def patched_rekey_db(db_session, mocker):
+ """Route every ``get_user_db_session`` call inside legacy_rekey (and the
+ FileIntegrityManager it constructs) to the SAME in-memory session."""
+ mocker.patch(
+ f"{_REKEY_MOD}.get_user_db_session",
+ lambda *a, **k: _session_ctx(db_session),
+ )
+ # FileIntegrityManager pulls in its own get_user_db_session (a different
+ # module) purely for integrity bookkeeping, which is orthogonal to the
+ # invariants under test here -- stub it out like
+ # test_no_plaintext_production_path.py does, so a real integrity DB isn't
+ # needed to exercise the re-key loop.
+ mocker.patch(f"{_REKEY_MOD}.FileIntegrityManager")
+ return db_session
+
+
+def _add_chunk(
+ session,
+ *,
+ embedding_id: str,
+ chunk_text: str,
+ collection_name: str,
+ source_id: str = "doc-1",
+ chunk_index: int = 0,
+) -> int:
+ chunk = DocumentChunk(
+ chunk_hash=f"hash-{embedding_id}",
+ source_type="document",
+ source_id=source_id,
+ collection_name=collection_name,
+ chunk_text=chunk_text,
+ chunk_index=chunk_index,
+ start_char=0,
+ end_char=len(chunk_text),
+ word_count=len(chunk_text.split()),
+ embedding_id=embedding_id,
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ )
+ session.add(chunk)
+ session.flush()
+ return chunk.id
+
+
+def _add_rag_index(
+ session,
+ *,
+ collection_name: str,
+ embedding_model: str,
+ index_path: str,
+ index_hash: str,
+ is_current: bool,
+ dimension: int = 2,
+) -> RAGIndex:
+ row = RAGIndex(
+ collection_name=collection_name,
+ embedding_model=embedding_model,
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=dimension,
+ index_path=index_path,
+ index_hash=index_hash,
+ chunk_size=500,
+ chunk_overlap=50,
+ # Pin the physical-build config explicitly so _resolve_index_params
+ # never has to fall back to the (possibly heavy / DB-dependent)
+ # local_search_* settings lookups -- keeps these tests focused on the
+ # orchestrator's row-sweep / marker logic.
+ index_type="flat",
+ distance_metric="cosine",
+ normalize_vectors=False,
+ is_current=is_current,
+ )
+ session.add(row)
+ session.flush()
+ return row
+
+
+def _marker_is_set(session, username: str) -> bool:
+ settings = get_settings_manager(db_session=session, username=username)
+ return settings.get_bool_setting(REKEY_MARKER_SETTING, False)
+
+
+# --------------------------------------------------------------------------
+# (a) All-rows sweep: both the current AND a stale historical row are re-keyed
+# --------------------------------------------------------------------------
+class TestAllRowsSwept:
+ def test_stale_and_current_rows_both_rekeyed(
+ self, tmp_path, monkeypatch, patched_rekey_db
+ ):
+ session = patched_rekey_db
+ username = "alice"
+ collection_name = "collection_c1"
+
+ # Real phase-1 (migrate_legacy_docstores) writes the sidecars this
+ # test needs -- point the RAG cache root at tmp_path so it runs
+ # against an isolated tree.
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ userdir = _rag_cache_root() / "alice_indices"
+
+ emb = _CountingEmbeddings(dim=2)
+
+ current_uuids = [uuid.uuid4().hex for _ in range(2)]
+ stale_uuids = [uuid.uuid4().hex for _ in range(2)]
+ _make_legacy_index(
+ userdir,
+ current_uuids,
+ ["current chunk A", "current chunk B"],
+ emb,
+ index_name="current",
+ )
+ _make_legacy_index(
+ userdir,
+ stale_uuids,
+ ["stale chunk A", "stale chunk B"],
+ emb,
+ index_name="stale",
+ )
+
+ current_faiss = userdir / "current.faiss"
+ stale_faiss = userdir / "stale.faiss"
+ current_sidecar = userdir / "current.idmap.json"
+ stale_sidecar = userdir / "stale.idmap.json"
+
+ migrate_result = migrate_legacy_docstores()
+ assert migrate_result["extracted"] == 2
+ assert current_sidecar.exists() and stale_sidecar.exists()
+
+ # DocumentChunk rows resolving each uuid -> a real int id.
+ current_ids = [
+ _add_chunk(
+ session,
+ embedding_id=u,
+ chunk_text=f"text for current {u}",
+ collection_name=collection_name,
+ )
+ for u in current_uuids
+ ]
+ stale_ids = [
+ _add_chunk(
+ session,
+ embedding_id=u,
+ chunk_text=f"text for stale {u}",
+ collection_name=collection_name,
+ )
+ for u in stale_uuids
+ ]
+
+ _add_rag_index(
+ session,
+ collection_name=collection_name,
+ embedding_model="model-new",
+ index_path=str(current_faiss),
+ index_hash="hash-current",
+ is_current=True,
+ )
+ _add_rag_index(
+ session,
+ collection_name=collection_name,
+ embedding_model="model-old",
+ index_path=str(stale_faiss),
+ index_hash="hash-stale",
+ is_current=False,
+ )
+ session.commit()
+
+ stats = rekey_user_indexes(username, "pw")
+
+ # THE CORE INVARIANT: both rows were visited and re-keyed, not just
+ # the current one. A regression to `.filter_by(is_current=True)`
+ # would make checked/rekeyed == 1 and leave the stale sidecar behind.
+ assert stats["checked"] == 2
+ assert stats["rekeyed"] == 2
+ assert stats["quarantined"] == 0
+
+ assert not current_sidecar.exists()
+ assert not stale_sidecar.exists()
+
+ from local_deep_research.vector_stores import get_vector_store_class
+
+ store_cls = get_vector_store_class()
+ current_store = store_cls.load(
+ current_faiss,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ )
+ stale_store = store_cls.load(
+ stale_faiss,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ )
+ assert set(current_store.live_ids()) == set(current_ids)
+ assert set(stale_store.live_ids()) == set(stale_ids)
+
+ # Never re-embedded -- rekey works purely from the legacy vectors +
+ # the sidecar/DB id resolution.
+ assert emb.embed_documents_calls == 2 # only the two ORIGINAL builds
+
+ # Completion marker set: every row was resolved.
+ assert _marker_is_set(session, username) is True
+
+
+# --------------------------------------------------------------------------
+# (b) Orphaned sidecar + un-removable plaintext .pkl withholds the marker
+# --------------------------------------------------------------------------
+class TestOrphanedSidecarWithholdsMarker:
+ def test_unremovable_surviving_pkl_withholds_completion_marker(
+ self, tmp_path, patched_rekey_db
+ ):
+ session = patched_rekey_db
+ username = "bob"
+
+ locked_dir = tmp_path / "locked"
+ locked_dir.mkdir()
+ faiss_path = locked_dir / "orphan.faiss" # deliberately never created
+ sidecar_path = locked_dir / "orphan.idmap.json"
+ pkl_path = locked_dir / "orphan.pkl"
+
+ sidecar_path.write_text(json.dumps({"0": uuid.uuid4().hex}))
+ pkl_path.write_bytes(b"legacy plaintext docstore bytes")
+ assert pkl_path.exists()
+
+ _add_rag_index(
+ session,
+ collection_name="collection_c2",
+ embedding_model="model-x",
+ index_path=str(faiss_path),
+ index_hash="hash-orphan",
+ is_current=True,
+ )
+ session.commit()
+
+ if os.geteuid() == 0:
+ pytest.skip("running as root bypasses directory permissions")
+
+ # Make the .pkl (and its sidecar) genuinely un-removable: unlink()
+ # needs WRITE permission on the containing directory, not the file
+ # itself, so lock the directory down.
+ os.chmod(locked_dir, 0o500)
+ try:
+ stats = rekey_user_indexes(username, "pw")
+ finally:
+ os.chmod(locked_dir, 0o700) # restore so tmp_path cleanup works
+
+ assert stats["checked"] == 1
+ assert stats["skipped_no_faiss"] == 1
+
+ # The plaintext .pkl is STILL on disk -- the unlink genuinely failed.
+ assert pkl_path.exists()
+ assert pkl_path.read_bytes() == b"legacy plaintext docstore bytes"
+
+ # THE CORE INVARIANT: the per-user completion marker must NOT be set
+ # while plaintext survives on disk -- phase-2 must retry next login
+ # rather than silently gating the user "done".
+ assert _marker_is_set(session, username) is False
+
+ def test_marker_sanity_check_bites_on_clean_run(
+ self, tmp_path, patched_rekey_db
+ ):
+ """Sanity check that ``_marker_is_set`` actually detects the marker
+ being set in the ordinary (nothing-to-do) case -- proving the
+ assertion above is not vacuously always False."""
+ session = patched_rekey_db
+ username = "carol"
+
+ # No RAGIndex rows at all -> the empty-indexes fast path sets the
+ # marker immediately.
+ stats = rekey_user_indexes(username, "pw")
+ assert stats["checked"] == 0
+ assert _marker_is_set(session, username) is True
+
+
+# --------------------------------------------------------------------------
+# (c) End-to-end: phase-1 -> phase-2 -> search rehydrates via the DB, with
+# no re-embedding, and a second run is idempotent.
+# --------------------------------------------------------------------------
+class TestFullRoundTrip:
+ def test_migrate_then_rekey_then_search_no_reembed_and_idempotent(
+ self, tmp_path, monkeypatch, patched_rekey_db, mocker
+ ):
+ session = patched_rekey_db
+ username = "dave"
+ collection_name = "collection_c3"
+ SECRET = "ZZZ_REKEY_ROUNDTRIP_MARKER_71a0"
+
+ # Real phase-1: point the cache root at tmp_path and build a REAL
+ # legacy LangChain-FAISS pair under it.
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ cache_root = _rag_cache_root()
+ userdir = cache_root / "dave_indices"
+
+ emb = _CountingEmbeddings(dim=2)
+ uuids = [uuid.uuid4().hex for _ in range(3)]
+ texts = [
+ f"alpha chunk mentioning {SECRET}",
+ "beta chunk, unrelated",
+ "gamma chunk, also unrelated",
+ ]
+ _make_legacy_index(userdir, uuids, texts, emb, index_name="idx")
+
+ faiss_path = userdir / "idx.faiss"
+ sidecar_path = userdir / "idx.idmap.json"
+ pkl_path = userdir / "idx.pkl"
+ assert pkl_path.exists()
+
+ migrate_result = migrate_legacy_docstores()
+ assert migrate_result["extracted"] == 1
+ assert not pkl_path.exists()
+ assert sidecar_path.exists()
+
+ # Seed the DB rows phase-2 needs: DocumentChunk per uuid (the ONLY
+ # place chunk text lives) + a matching RAGIndex row.
+ ids = [
+ _add_chunk(
+ session,
+ embedding_id=u,
+ chunk_text=t,
+ collection_name=collection_name,
+ source_id="doc-dave-1",
+ chunk_index=i,
+ )
+ for i, (u, t) in enumerate(zip(uuids, texts))
+ ]
+ _add_rag_index(
+ session,
+ collection_name=collection_name,
+ embedding_model="fake-model",
+ index_path=str(faiss_path),
+ index_hash="hash-dave",
+ is_current=True,
+ )
+ session.commit()
+
+ assert emb.embed_documents_calls == 1 # only the original build so far
+
+ stats = rekey_user_indexes(username, "pw")
+ assert stats["checked"] == 1
+ assert stats["rekeyed"] == 1
+ assert not sidecar_path.exists()
+ assert not pkl_path.exists()
+ assert _marker_is_set(session, username) is True
+
+ # No re-embedding happened during the whole migrate+rekey round trip.
+ assert emb.embed_documents_calls == 1
+ assert emb.embed_query_calls == 0
+
+ # The .faiss now loads as a real IndexIDMap2 keyed by DocumentChunk.id.
+ import faiss as faiss_mod
+
+ raw = faiss_mod.read_index(str(faiss_path))
+ assert isinstance(raw, faiss_mod.IndexIDMap2)
+
+ from local_deep_research.vector_stores import get_vector_store_class
+
+ store_cls = get_vector_store_class()
+ store = store_cls.load(
+ faiss_path,
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ )
+ assert set(store.live_ids()) == set(ids)
+
+ # Search through the REAL production facade rehydrates the right text
+ # from the DB by id -- the store itself never held any text.
+ mocker.patch(
+ f"{_FACADE_MOD}.get_user_db_session",
+ lambda *a, **k: _session_ctx(session),
+ )
+ from local_deep_research.vector_stores.facade import VectorIndex
+
+ vi = VectorIndex(
+ username=username,
+ db_password="pw",
+ embeddings=emb,
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name=collection_name,
+ dimension=2,
+ path=faiss_path,
+ lock=threading.Lock(),
+ integrity_record=lambda _p: None,
+ integrity_verify=lambda _p: (True, None),
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ )
+ results = vi.search(f"looking for {SECRET}", top_k=3, session=session)
+ assert results
+ assert any(SECRET in r.text for r in results)
+
+ # Search embeds the QUERY exactly once; the original chunks are still
+ # never re-embedded.
+ assert emb.embed_query_calls == 1
+ assert emb.embed_documents_calls == 1
+
+ # Idempotent: a second run is a fast no-op (marker short-circuit).
+ stats2 = rekey_user_indexes(username, "pw")
+ assert stats2 == {
+ "checked": 0,
+ "rekeyed": 0,
+ "quarantined": 0,
+ "skipped_no_sidecar": 0,
+ "skipped_no_faiss": 0,
+ }
+
+
+# --------------------------------------------------------------------------
+# (d) No-sidecar branch dispatch: "not yet migrated" (defer) vs. "already
+# migrated, .pkl leftover" (purge) vs. "unreadable" (defer) must not be
+# confused with each other -- see ``_is_idmap2``'s docstring.
+# --------------------------------------------------------------------------
+class TestNoSidecarBranchDispatch:
+ def test_no_sidecar_old_format_with_surviving_pkl_defers_instead_of_quarantining(
+ self, tmp_path, patched_rekey_db
+ ):
+ """A pre-phase-1 index (old format, no sidecar, .pkl still present)
+ must be DEFERRED, not quarantined -- phase-1 (which runs every
+ startup) simply hasn't reached this collection yet. Quarantining it
+ would force a needless full re-embed of a perfectly healthy index and
+ delete an intact docstore out from under phase-1."""
+ session = patched_rekey_db
+ username = "erin"
+ collection_name = "collection_c4"
+
+ emb = _CountingEmbeddings(dim=2)
+ ids = [uuid.uuid4().hex for _ in range(2)]
+ _make_legacy_index(
+ tmp_path,
+ ids,
+ ["old chunk A", "old chunk B"],
+ emb,
+ index_name="old",
+ )
+ faiss_path = tmp_path / "old.faiss"
+ pkl_path = tmp_path / "old.pkl"
+ sidecar_path = tmp_path / "old.idmap.json"
+ assert faiss_path.exists() and pkl_path.exists()
+ assert not sidecar_path.exists() # phase-1 never touched this one
+
+ session.add(
+ DocumentCollection(
+ document_id="doc-c4",
+ collection_id="c4",
+ indexed=True,
+ )
+ )
+ _add_rag_index(
+ session,
+ collection_name=collection_name,
+ embedding_model="model-x",
+ index_path=str(faiss_path),
+ index_hash="hash-c4",
+ is_current=True,
+ )
+ session.commit()
+
+ stats = rekey_user_indexes(username, "pw")
+
+ assert stats["checked"] == 1
+ assert stats["quarantined"] == 0
+
+ # No quarantine side effects whatsoever: files intact, no .corrupt-*
+ # debris left on disk.
+ assert faiss_path.exists()
+ assert pkl_path.exists()
+ assert not list(tmp_path.glob("*.corrupt-*"))
+
+ # Marker withheld -- retried next login once phase-1 has caught up.
+ assert _marker_is_set(session, username) is False
+
+ # The healthy collection's indexed state was NOT collaterally reset
+ # by a quarantine that should never have happened.
+ dc = (
+ session.query(DocumentCollection)
+ .filter_by(collection_id="c4")
+ .first()
+ )
+ assert dc.indexed is True
+
+ def test_already_migrated_no_sidecar_purges_surviving_pkl_and_completes(
+ self, tmp_path, patched_rekey_db
+ ):
+ """An index that is ALREADY a real ``IndexIDMap2`` (fully migrated)
+ with no sidecar, but a leftover full-chunk-text ``.pkl`` beside it (a
+ phase-1/phase-2 unlink that failed after the sidecar was already
+ consumed), must have that redundant ``.pkl`` PURGED and complete
+ normally -- the at-rest plaintext leak this whole module exists to
+ close."""
+ session = patched_rekey_db
+ username = "frank"
+ collection_name = "collection_c5"
+
+ faiss_path = tmp_path / "mig.faiss"
+ pkl_path = tmp_path / "mig.pkl"
+
+ store_cls = get_vector_store_class()
+ store = store_cls.create(
+ dimension=2,
+ index_type="flat",
+ metric="cosine",
+ normalize=False,
+ path=faiss_path,
+ lock=threading.Lock(),
+ integrity_record=lambda _p: None,
+ integrity_verify=lambda _p: (True, None),
+ )
+ store.add(
+ [101, 102],
+ np.array([[1.0, 2.0], [3.0, 4.0]], dtype="float32"),
+ )
+ store.persist(faiss_path)
+
+ # A leftover full-chunk-text .pkl -- exactly the at-rest plaintext
+ # leak `_purge_redundant_pkl` backstops.
+ pkl_path.write_bytes(b"full chunk text that must never linger on disk")
+
+ raw = faiss_mod.read_index(str(faiss_path))
+ assert isinstance(
+ raw, faiss_mod.IndexIDMap2
+ ) # sanity: real IndexIDMap2
+
+ _add_rag_index(
+ session,
+ collection_name=collection_name,
+ embedding_model="model-y",
+ index_path=str(faiss_path),
+ index_hash="hash-c5",
+ is_current=True,
+ )
+ session.commit()
+
+ stats = rekey_user_indexes(username, "pw")
+
+ assert stats["checked"] == 1
+ assert stats["skipped_no_sidecar"] == 1
+ assert stats["quarantined"] == 0
+
+ # THE SECURITY INVARIANT: the redundant plaintext .pkl is gone.
+ assert not pkl_path.exists()
+
+ # Every index resolved cleanly -- the completion marker IS set.
+ assert _marker_is_set(session, username) is True
+
+ def test_unreadable_faiss_in_no_sidecar_branch_withholds_marker_without_quarantine(
+ self, tmp_path, patched_rekey_db
+ ):
+ """A ``.faiss`` that cannot even be READ (so ``_is_idmap2`` returns
+ ``None`` -- a transient IO hiccup, NOT a definite old format) must be
+ DEFERRED exactly like the old-format+surviving-.pkl case -- ``None``
+ must never be treated the same as a definite ``False``."""
+ session = patched_rekey_db
+ username = "grace"
+ collection_name = "collection_c6"
+
+ faiss_path = tmp_path / "garbage.faiss"
+ garbage = b"not a real faiss index, just garbage bytes"
+ faiss_path.write_bytes(garbage)
+
+ _add_rag_index(
+ session,
+ collection_name=collection_name,
+ embedding_model="model-z",
+ index_path=str(faiss_path),
+ index_hash="hash-c6",
+ is_current=True,
+ )
+ session.commit()
+
+ stats = rekey_user_indexes(username, "pw")
+
+ assert stats["checked"] == 1
+ assert stats["quarantined"] == 0
+
+ # File untouched, no quarantine debris.
+ assert faiss_path.exists()
+ assert faiss_path.read_bytes() == garbage
+ assert not list(tmp_path.glob("*.corrupt-*"))
+
+ # Marker withheld -- a transient read failure must not gate the user
+ # "done" while the index was never actually re-keyed.
+ assert _marker_is_set(session, username) is False
+
+
+# --------------------------------------------------------------------------
+# (e) ``_resolve_index_params`` settings-fallback + ``_persist_rekeyed_config``
+# NULL-only overwrite guard, reached via the main rekey path. Every other
+# test in this file uses ``_add_rag_index``, which pins
+# index_type/distance_metric/normalize_vectors explicitly precisely so it
+# never has to exercise this fallback/guard -- these two tests build
+# ``RAGIndex`` rows directly instead, to reach it.
+# --------------------------------------------------------------------------
+class TestSettingsFallbackAndPersistGuard:
+ def test_legacy_row_with_null_config_columns_falls_back_to_settings_and_pins_only_null_fields(
+ self, tmp_path, monkeypatch, patched_rekey_db
+ ):
+ session = patched_rekey_db
+ username = "heidi"
+ collection_name_null = "collection_c7"
+ collection_name_pinned = "collection_c8"
+
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ userdir = _rag_cache_root() / "heidi_indices"
+
+ emb = _CountingEmbeddings(dim=2)
+
+ null_uuids = [uuid.uuid4().hex for _ in range(2)]
+ pinned_uuids = [uuid.uuid4().hex for _ in range(2)]
+ _make_legacy_index(
+ userdir,
+ null_uuids,
+ ["null-cfg chunk A", "null-cfg chunk B"],
+ emb,
+ index_name="nullcfg",
+ )
+ _make_legacy_index(
+ userdir,
+ pinned_uuids,
+ ["pinned-cfg chunk A", "pinned-cfg chunk B"],
+ emb,
+ index_name="pinnedcfg",
+ )
+
+ migrate_result = migrate_legacy_docstores()
+ assert migrate_result["extracted"] == 2
+
+ null_faiss = userdir / "nullcfg.faiss"
+ pinned_faiss = userdir / "pinnedcfg.faiss"
+ assert (userdir / "nullcfg.idmap.json").exists()
+ assert (userdir / "pinnedcfg.idmap.json").exists()
+
+ for u in null_uuids:
+ _add_chunk(
+ session,
+ embedding_id=u,
+ chunk_text=f"null-cfg text {u}",
+ collection_name=collection_name_null,
+ )
+ for u in pinned_uuids:
+ _add_chunk(
+ session,
+ embedding_id=u,
+ chunk_text=f"pinned-cfg text {u}",
+ collection_name=collection_name_pinned,
+ )
+
+ # Row (a): index_type/distance_metric/normalize_vectors ALL NULL --
+ # predates those columns, exactly like a legacy row would.
+ null_row = RAGIndex(
+ collection_name=collection_name_null,
+ embedding_model="model-null-cfg",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ index_path=str(null_faiss),
+ index_hash="hash-null-cfg",
+ chunk_size=500,
+ chunk_overlap=50,
+ index_type=None,
+ distance_metric=None,
+ normalize_vectors=None,
+ is_current=True,
+ )
+ # Row (b): already has explicit, non-default values pinned -- the
+ # settings-fallback path must never be consulted for these columns,
+ # let alone overwrite them.
+ pinned_row = RAGIndex(
+ collection_name=collection_name_pinned,
+ embedding_model="model-pinned-cfg",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=2,
+ index_path=str(pinned_faiss),
+ index_hash="hash-pinned-cfg",
+ chunk_size=500,
+ chunk_overlap=50,
+ index_type="ivf",
+ distance_metric="dot_product",
+ normalize_vectors=True,
+ is_current=True,
+ )
+ session.add_all([null_row, pinned_row])
+ session.commit()
+
+ # Non-default settings available for row (a) to fall back to. Chosen
+ # to differ from BOTH the library defaults (flat/cosine/True) AND
+ # row (b)'s already-pinned values (ivf/dot_product/True) -- so a
+ # clobber of row (b) in either direction would be caught.
+ settings = get_settings_manager(db_session=session, username=username)
+ settings.set_setting("local_search_index_type", "hnsw")
+ settings.set_setting("local_search_distance_metric", "l2")
+ settings.set_setting("local_search_normalize_vectors", False)
+ session.commit()
+
+ stats = rekey_user_indexes(username, "pw")
+
+ assert stats["checked"] == 2
+ assert stats["rekeyed"] == 2
+ assert stats["quarantined"] == 0
+
+ session.expire_all()
+ refreshed_null = (
+ session.query(RAGIndex).filter_by(index_hash="hash-null-cfg").one()
+ )
+ refreshed_pinned = (
+ session.query(RAGIndex)
+ .filter_by(index_hash="hash-pinned-cfg")
+ .one()
+ )
+
+ # THE FALLBACK INVARIANT: every NULL column on row (a) was pinned FROM
+ # the live settings (not left NULL, not defaulted independently of
+ # settings).
+ assert refreshed_null.index_type == "hnsw"
+ assert refreshed_null.distance_metric == "l2"
+ assert refreshed_null.normalize_vectors is False
+
+ # THE GUARD INVARIANT: row (b)'s explicit, already-non-default values
+ # are UNCHANGED, even though the live settings disagree on all three
+ # columns. Dropping the is-None guard in ``_persist_rekeyed_config``
+ # would clobber this user's pinned config with the later global
+ # default, and the existing .faiss would silently be reinterpreted
+ # under the wrong index_type/metric/normalize on the next load.
+ assert refreshed_pinned.index_type == "ivf"
+ assert refreshed_pinned.distance_metric == "dot_product"
+ assert refreshed_pinned.normalize_vectors is True
+
+ # Marker set -- both rows resolved cleanly.
+ assert _marker_is_set(session, username) is True
diff --git a/tests/vector_stores/test_legacy_rekey_quarantine.py b/tests/vector_stores/test_legacy_rekey_quarantine.py
new file mode 100644
index 0000000000..0ae9ae43cf
--- /dev/null
+++ b/tests/vector_stores/test_legacy_rekey_quarantine.py
@@ -0,0 +1,96 @@
+"""Regression tests for legacy_rekey._quarantine_and_reset's ``is_current`` guard.
+
+Round-1 review changed ``rekey_user_indexes`` to re-key ALL ``RAGIndex`` rows
+(not just ``is_current=True``): reverting the embedding model re-resolves a
+search to a stale row by ``index_hash``, and an un-rekeyed old-format ``.faiss``
+would hard-fail search. To keep a STALE row's re-key FAILURE from collaterally
+wiping the healthy CURRENT index's ``indexed`` state (which would force a
+needless full re-embed of the whole collection), ``_quarantine_and_reset`` now
+resets the collection-wide ``DocumentCollection.indexed`` flag ONLY when the
+quarantined row is ``is_current``.
+
+These tests lock that guard so a future refactor cannot silently reintroduce the
+"stale-row quarantine re-embeds the whole collection" regression. The function
+that previously had zero behavioral coverage now has its core invariant pinned.
+"""
+
+import threading
+from unittest.mock import MagicMock, patch
+
+_MOD = "local_deep_research.vector_stores.legacy_rekey"
+
+
+def _run_quarantine(tmp_path, *, is_current):
+ """Invoke _quarantine_and_reset with a fully mocked user DB session.
+
+ Returns (doc_collection_query, rag_status_query, idx) so callers can assert
+ which DB mutations ran. The .faiss/.idmap paths are non-existent so the
+ file-rename branches are skipped — the DB reset logic is what we're pinning.
+ """
+ from local_deep_research.vector_stores.legacy_rekey import (
+ _quarantine_and_reset,
+ )
+
+ rag_index = MagicMock()
+ rag_index.id = 7
+ rag_index.collection_name = "collection_abc"
+
+ # The freshly-queried idx carries the authoritative is_current the guard reads.
+ idx = MagicMock()
+ idx.id = 7
+ idx.is_current = is_current
+
+ q_ragindex = MagicMock()
+ q_ragindex.filter_by.return_value.first.return_value = idx
+ q_status = MagicMock()
+ q_doccoll = MagicMock()
+
+ # Route session.query(Model) by class name so the test is robust to import
+ # path / class identity.
+ routes = {
+ "RAGIndex": q_ragindex,
+ "RagDocumentStatus": q_status,
+ "DocumentCollection": q_doccoll,
+ }
+ session = MagicMock()
+ session.query.side_effect = lambda model: routes[model.__name__]
+
+ ctx = MagicMock()
+ ctx.__enter__ = MagicMock(return_value=session)
+ ctx.__exit__ = MagicMock(return_value=False)
+
+ faiss_path = tmp_path / "idx.faiss" # does not exist -> rename skipped
+ sidecar_path = tmp_path / "idx.idmap.json"
+
+ with patch(f"{_MOD}.get_user_db_session", return_value=ctx):
+ _quarantine_and_reset(
+ "user", "pw", rag_index, faiss_path, sidecar_path, threading.Lock()
+ )
+ return q_doccoll, q_status, idx
+
+
+def test_current_row_quarantine_resets_collection_indexed(tmp_path):
+ """Quarantining the CURRENT index flips the collection's live indexed flag
+ (so the collection rebuilds) and clears this row's RagDocumentStatus."""
+ q_doccoll, q_status, idx = _run_quarantine(tmp_path, is_current=True)
+
+ q_doccoll.filter_by.return_value.update.assert_called_once()
+ payload = q_doccoll.filter_by.return_value.update.call_args[0][0]
+ assert payload.get("indexed") is False
+
+ q_status.filter_by.return_value.delete.assert_called_once()
+ assert idx.chunk_count == 0
+ assert idx.total_documents == 0
+
+
+def test_stale_row_quarantine_leaves_collection_indexed_untouched(tmp_path):
+ """Quarantining a STALE (is_current=False) row must NOT flip the collection's
+ live indexed flag -- the current index is still healthy and serving searches
+ -- but it still clears this stale row's own RagDocumentStatus."""
+ q_doccoll, q_status, idx = _run_quarantine(tmp_path, is_current=False)
+
+ q_doccoll.filter_by.return_value.update.assert_not_called()
+
+ q_status.filter_by.return_value.delete.assert_called_once()
+ assert idx.chunk_count == 0
+ assert idx.total_documents == 0
diff --git a/tests/vector_stores/test_migrate_legacy_index_files.py b/tests/vector_stores/test_migrate_legacy_index_files.py
new file mode 100644
index 0000000000..1c19924a2e
--- /dev/null
+++ b/tests/vector_stores/test_migrate_legacy_index_files.py
@@ -0,0 +1,401 @@
+"""Unit tests for ``LibraryRAGService._migrate_legacy_index_files``.
+
+Before per-user path scoping, FAISS indexes lived directly under the shared
+``cache/rag_indices/`` directory. ``_migrate_legacy_index_files`` is the
+one-time migration that relocates such a legacy index into the new per-user
+subdirectory the rest of the service now reads/writes.
+
+Two invariants are pinned here:
+
+(a) A legacy ``.faiss`` + its phase-1 ``.idmap.json`` sidecar are BOTH
+ relocated to the per-user path, while any legacy plaintext ``.pkl``
+ companion is DELETED (never relocated) — the new store keeps chunk text
+ only in the encrypted per-user DB, so carrying the old pickle docstore
+ forward would leak plaintext into the new location.
+
+(b) Ordering/idempotency: the method moves the sidecar first and the
+ ``.faiss`` last specifically so that the re-entry guard (which keys only
+ on ``index_path`` — the ``.faiss`` — already existing) cannot leave the
+ sidecar orphaned at the legacy path after a crash between the two
+ renames. We simulate that exact partial state (sidecar already moved,
+ ``.faiss`` still legacy) and assert re-invocation converges to a single,
+ correctly-placed sidecar with no duplication and no data loss — without
+ needing to touch the embeddings/re-embed path at all.
+
+Both tests build real on-disk files (a tiny valid ``faiss.IndexIDMap2``, a
+JSON sidecar, a legacy ``.pkl``) and a real in-memory SQLite session for the
+``RAGIndex`` row the method updates; only the embedding-manager-heavy
+``LibraryRAGService.__init__`` is bypassed (via ``__new__``) since the method
+under test never touches embeddings.
+"""
+
+import json
+from contextlib import contextmanager
+from pathlib import Path
+
+import faiss
+import numpy as np
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ EmbeddingProvider,
+ RAGIndex,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+
+_MOD = "local_deep_research.research_library.services.library_rag_service"
+
+
+# ---------------------------------------------------------------------------
+# Helpers / fixtures
+# ---------------------------------------------------------------------------
+def _write_tiny_faiss(path, dim: int = 4) -> None:
+ """A minimal but genuinely valid IndexIDMap2 file — real faiss bytes,
+ not a stub — so a rename/load round-trip is meaningful."""
+ index = faiss.IndexIDMap2(faiss.IndexFlatL2(dim))
+ index.add_with_ids(
+ np.zeros((1, dim), dtype="float32"), np.array([1], dtype="int64")
+ )
+ faiss.write_index(index, str(path))
+
+
+def _make_service(
+ username: str = "alice", db_password: str = "pw"
+) -> LibraryRAGService:
+ """Construct a LibraryRAGService without running __init__.
+
+ __init__ builds a real embedding manager, a settings snapshot from the
+ DB, and runs egress-policy checks — none of which
+ ``_migrate_legacy_index_files`` touches. It only reads
+ ``self.username``, ``self.db_password`` (via ``self._db_password``),
+ and ``self.integrity_manager.record_file``. Bypassing __init__ with
+ ``__new__`` keeps the test scoped to the method under test while every
+ file/DB interaction inside it is still the real thing.
+ """
+ svc = LibraryRAGService.__new__(LibraryRAGService)
+ svc.username = username
+ svc._db_password = db_password
+ svc.integrity_manager = _RecordingIntegrityManager()
+ return svc
+
+
+class _RecordingIntegrityManager:
+ """Minimal stand-in for FileIntegrityManager.record_file.
+
+ Not a MagicMock: we want a real assertable call log without pretending
+ the mock itself proves anything, and without pulling in the full
+ integrity-manager machinery (DB-backed hashing) that isn't part of the
+ invariant under test here.
+ """
+
+ def __init__(self):
+ self.recorded = []
+
+ def record_file(self, path, **kwargs):
+ self.recorded.append(path)
+
+
+def db_session():
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ yield session
+ session.close()
+ engine.dispose()
+
+
+def patched_db(db_session, mocker):
+ @contextmanager
+ def _mock_session(*_a, **_k):
+ yield db_session
+
+ mocker.patch(f"{_MOD}.get_user_db_session", _mock_session)
+ return db_session
+
+
+def _make_rag_index(session, index_path) -> RAGIndex:
+ idx = RAGIndex(
+ collection_name="collection_c1",
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ embedding_dimension=4,
+ index_path=str(index_path),
+ index_hash="a" * 64,
+ chunk_size=500,
+ chunk_overlap=50,
+ status="active",
+ is_current=True,
+ )
+ session.add(idx)
+ session.commit()
+ session.refresh(idx)
+ return idx
+
+
+# ---------------------------------------------------------------------------
+# (a) Relocation: .faiss + sidecar move, .pkl is deleted not relocated
+# ---------------------------------------------------------------------------
+class TestRelocatesFaissAndSidecarDeletesPkl:
+ def test_migration_moves_faiss_and_sidecar_deletes_pkl(
+ self, tmp_path, monkeypatch, patched_db
+ ):
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ from local_deep_research.config.paths import get_cache_directory
+
+ legacy_root = get_cache_directory() / "rag_indices"
+ legacy_root.mkdir(parents=True, exist_ok=True)
+ legacy_path = legacy_root / "deadbeef.faiss"
+ legacy_sidecar = legacy_root / "deadbeef.idmap.json"
+ legacy_pkl = legacy_root / "deadbeef.pkl"
+
+ _write_tiny_faiss(legacy_path)
+ legacy_sidecar.write_text(json.dumps({"1": 101}))
+ legacy_pkl.write_bytes(b"legacy plaintext docstore bytes")
+
+ new_dir = get_cache_directory() / "rag_indices" / "userscope"
+ new_dir.mkdir(parents=True, exist_ok=True)
+ index_path = new_dir / "deadbeef.faiss"
+
+ rag_index = _make_rag_index(patched_db, index_path)
+ svc = _make_service()
+
+ svc._migrate_legacy_index_files(legacy_path, index_path, rag_index)
+
+ # The .faiss landed at the new per-user path...
+ assert index_path.exists()
+ assert not legacy_path.exists()
+ # It really is a valid, loadable IndexIDMap2 (not just bytes moved
+ # around) — proves we moved the real file, not a placeholder.
+ reloaded = faiss.read_index(str(index_path))
+ assert faiss.downcast_index(reloaded).ntotal == 1
+
+ # ...the sidecar moved alongside it...
+ new_sidecar = new_dir / "deadbeef.idmap.json"
+ assert new_sidecar.exists()
+ assert not legacy_sidecar.exists()
+ assert json.loads(new_sidecar.read_text()) == {"1": 101}
+
+ # ...and the legacy plaintext .pkl was DELETED, not relocated: the
+ # core no-plaintext-at-rest invariant for this migration path.
+ assert not legacy_pkl.exists()
+ new_pkl = new_dir / "deadbeef.pkl"
+ assert not new_pkl.exists()
+
+ # The DB row was repointed at the new location.
+ patched_db.refresh(rag_index)
+ assert rag_index.index_path == str(index_path)
+
+ # And the integrity record was refreshed under the NEW path (the old
+ # record, keyed by the legacy path, no longer applies).
+ assert svc.integrity_manager.recorded == [index_path]
+
+ def test_no_sidecar_no_pkl_just_moves_faiss(
+ self, tmp_path, monkeypatch, patched_db
+ ):
+ """Bare legacy .faiss with neither companion still migrates cleanly
+ (sidecar/​pkl handling must not assume they exist)."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ from local_deep_research.config.paths import get_cache_directory
+
+ legacy_root = get_cache_directory() / "rag_indices"
+ legacy_root.mkdir(parents=True, exist_ok=True)
+ legacy_path = legacy_root / "cafe1234.faiss"
+ _write_tiny_faiss(legacy_path)
+
+ new_dir = legacy_root / "userscope"
+ new_dir.mkdir(parents=True, exist_ok=True)
+ index_path = new_dir / "cafe1234.faiss"
+
+ rag_index = _make_rag_index(patched_db, index_path)
+ svc = _make_service()
+
+ svc._migrate_legacy_index_files(legacy_path, index_path, rag_index)
+
+ assert index_path.exists()
+ assert not legacy_path.exists()
+ assert list(new_dir.glob("*.idmap.json")) == []
+ assert list(new_dir.glob("*.pkl")) == []
+
+
+# ---------------------------------------------------------------------------
+# (b) Crash-recovery ordering / idempotency
+# ---------------------------------------------------------------------------
+class TestCrashRecoveryOrderingIdempotency:
+ def test_reentry_after_sidecar_moved_but_faiss_not_yet_converges(
+ self, tmp_path, monkeypatch, patched_db
+ ):
+ """Simulates a crash landing exactly between the two renames the
+ method performs: the sidecar already sits at the NEW path, but the
+ .faiss is still at the legacy path (the guard — ``index_path.exists()``
+ — is keyed only on the .faiss, so it is still False and re-entry is
+ NOT short-circuited). Re-invocation must:
+
+ * still relocate the (only-remaining-at-legacy) .faiss,
+ * leave exactly ONE sidecar at the new path (no duplicate, no
+ clobber-with-empty, no loss),
+ * NOT require re-embedding anything (this whole path is a pure
+ file move; asserting the sidecar's bytes are byte-identical to
+ the pre-crash content is the proxy for "no re-embed happened").
+ """
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ from local_deep_research.config.paths import get_cache_directory
+
+ legacy_root = get_cache_directory() / "rag_indices"
+ legacy_root.mkdir(parents=True, exist_ok=True)
+ legacy_path = legacy_root / "feedface.faiss"
+ _write_tiny_faiss(legacy_path)
+ # NOTE: no legacy sidecar left on disk — it already "moved" below,
+ # simulating the crash point being AFTER the first rename.
+
+ new_dir = legacy_root / "userscope"
+ new_dir.mkdir(parents=True, exist_ok=True)
+ index_path = new_dir / "feedface.faiss"
+ new_sidecar = new_dir / "feedface.idmap.json"
+ sidecar_payload = {"1": 101, "2": 202}
+ new_sidecar.write_text(json.dumps(sidecar_payload))
+
+ rag_index = _make_rag_index(patched_db, index_path)
+ svc = _make_service()
+
+ # Re-entry: the guard only checks index_path.exists(), which is
+ # still False (the .faiss never made it across before the "crash"),
+ # so the method must run again rather than no-op.
+ svc._migrate_legacy_index_files(legacy_path, index_path, rag_index)
+
+ assert index_path.exists()
+ assert not legacy_path.exists()
+
+ # Exactly one sidecar at the new location, contents untouched —
+ # not duplicated, not overwritten with something empty/new, and no
+ # re-embed occurred (the payload is byte-for-byte the pre-crash one).
+ sidecars = list(new_dir.glob("*.idmap.json"))
+ assert len(sidecars) == 1
+ assert json.loads(new_sidecar.read_text()) == sidecar_payload
+
+ patched_db.refresh(rag_index)
+ assert rag_index.index_path == str(index_path)
+
+ def test_sidecar_is_renamed_strictly_before_the_faiss(
+ self, tmp_path, monkeypatch, patched_db
+ ):
+ """Directly pins the ORDER of the two renames (not just an end
+ state): the sidecar rename must complete before the .faiss rename is
+ even attempted. This is the concrete mechanism the source comment
+ relies on for crash-safety — the re-entry guard checks only
+ ``index_path.exists()`` (the .faiss), so if a future refactor moved
+ the .faiss FIRST, a crash between the two renames would leave the
+ guard satisfied (.faiss present) while the sidecar sits orphaned at
+ the legacy path forever, with no way for re-entry to ever repair it.
+ Recording actual ``Path.rename`` call order catches that reversal
+ directly, independent of any specific crash-state fixture.
+ """
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ from local_deep_research.config.paths import get_cache_directory
+
+ legacy_root = get_cache_directory() / "rag_indices"
+ legacy_root.mkdir(parents=True, exist_ok=True)
+ legacy_path = legacy_root / "0rder1ng.faiss"
+ legacy_sidecar = legacy_root / "0rder1ng.idmap.json"
+ _write_tiny_faiss(legacy_path)
+ legacy_sidecar.write_text(json.dumps({"1": 101}))
+
+ new_dir = legacy_root / "userscope"
+ new_dir.mkdir(parents=True, exist_ok=True)
+ index_path = new_dir / "0rder1ng.faiss"
+
+ rag_index = _make_rag_index(patched_db, index_path)
+ svc = _make_service()
+
+ rename_order = []
+ original_rename = Path.rename
+
+ def _recording_rename(self_path, target):
+ rename_order.append(self_path.name)
+ return original_rename(self_path, target)
+
+ monkeypatch.setattr(Path, "rename", _recording_rename)
+
+ svc._migrate_legacy_index_files(legacy_path, index_path, rag_index)
+
+ # Both renames happened...
+ assert "0rder1ng.idmap.json" in rename_order
+ assert "0rder1ng.faiss" in rename_order
+ # ...and the sidecar's rename was recorded strictly before the
+ # .faiss's -- reversing this would silently reintroduce an
+ # unrecoverable-orphan crash window (see docstring above).
+ assert rename_order.index("0rder1ng.idmap.json") < rename_order.index(
+ "0rder1ng.faiss"
+ )
+
+ def test_reentry_once_faiss_already_migrated_is_a_pure_noop(
+ self, tmp_path, monkeypatch, patched_db
+ ):
+ """Once the .faiss has already landed at index_path (migration fully
+ completed), the guard must short-circuit: calling again must not
+ touch the DB row a second time, must not error even though the
+ legacy path is long gone, and must leave the already-migrated files
+ alone."""
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+ from local_deep_research.config.paths import get_cache_directory
+
+ legacy_root = get_cache_directory() / "rag_indices"
+ legacy_root.mkdir(parents=True, exist_ok=True)
+ legacy_path = legacy_root / "0ff1ce00.faiss"
+ # Legacy path does not exist any more — full prior migration.
+
+ new_dir = legacy_root / "userscope"
+ new_dir.mkdir(parents=True, exist_ok=True)
+ index_path = new_dir / "0ff1ce00.faiss"
+ _write_tiny_faiss(index_path)
+ new_sidecar = new_dir / "0ff1ce00.idmap.json"
+ new_sidecar.write_text(json.dumps({"1": 101}))
+
+ rag_index = _make_rag_index(patched_db, index_path)
+ # Simulate the row having already been repointed by a prior run and
+ # sanity-checked since (bump last_updated implicitly via commit).
+ original_path_value = rag_index.index_path
+
+ svc = _make_service()
+ svc._migrate_legacy_index_files(legacy_path, index_path, rag_index)
+
+ # Nothing changed: no integrity re-record, DB row untouched, files
+ # exactly as they were.
+ assert svc.integrity_manager.recorded == []
+ patched_db.refresh(rag_index)
+ assert rag_index.index_path == original_path_value
+ assert index_path.exists()
+ assert json.loads(new_sidecar.read_text()) == {"1": 101}
+
+
+# ---------------------------------------------------------------------------
+# Sanity check that the assertions above actually bite: a deliberately-wrong
+# "migration" (delete-then-recreate instead of rename) would corrupt the
+# faiss payload identity check, and a naive "always overwrite sidecar" would
+# fail the byte-identity check in the crash-recovery test. We don't need to
+# monkeypatch the method to prove this: the .idmap.json equality assertions
+# and the faiss ntotal check are only meaningful if they can fail, which the
+# following demonstrates on deliberately corrupted fixtures.
+# ---------------------------------------------------------------------------
+class TestAssertionsAreNotTautological:
+ def test_ntotal_check_would_fail_on_empty_index(self, tmp_path):
+ empty_index = faiss.IndexIDMap2(faiss.IndexFlatL2(4))
+ path = tmp_path / "empty.faiss"
+ faiss.write_index(empty_index, str(path))
+ reloaded = faiss.read_index(str(path))
+ assert faiss.downcast_index(reloaded).ntotal == 0
+ # i.e. this would NOT satisfy `== 1` as asserted against the real
+ # migrated file above -- the check is discriminating, not vacuous.
+
+ def test_sidecar_equality_check_would_fail_on_altered_payload(
+ self, tmp_path
+ ):
+ sidecar = tmp_path / "s.idmap.json"
+ sidecar.write_text(json.dumps({"1": 101, "2": 202}))
+ assert json.loads(sidecar.read_text()) != {"1": 999}
diff --git a/tests/vector_stores/test_no_plaintext_production_path.py b/tests/vector_stores/test_no_plaintext_production_path.py
new file mode 100644
index 0000000000..6205d44303
--- /dev/null
+++ b/tests/vector_stores/test_no_plaintext_production_path.py
@@ -0,0 +1,357 @@
+"""Security integration test: indexing through the PRODUCTION vector-store path
+leaves NO plaintext chunk text on disk.
+
+The whole point of the ``vector_stores/`` cutover is that chunk TEXT lives only
+in the (per-user, SQLCipher-encrypted) DB, while the on-disk FAISS index holds
+ONLY vectors + int ``DocumentChunk.id``s. These tests drive the real indexing
+path — the ``VectorIndex`` facade over a real on-disk ``FaissVectorStore``, and
+the full ``LibraryRAGService.index_document`` service path — with a distinctive
+secret marker in the chunk text, title, and metadata, then recursively grep
+every file under the RAG cache for that marker. It must appear NOWHERE on disk.
+
+Complements ``test_legacy_cleanup_no_plaintext.py``, which covers the one-time
+migration path; this covers ordinary indexing as production actually uses it.
+
+The DB is an in-memory SQLite here (no on-disk file to grep), which is the right
+target: the invariant under test is that the FAISS STORE is text-free. In
+production the DB additionally lives inside an encrypted SQLCipher file.
+"""
+
+import threading
+import uuid
+from contextlib import contextmanager
+
+import numpy as np
+import pytest
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ DocumentChunk,
+ EmbeddingProvider,
+)
+from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+
+# Distinctive marker that must never appear in any on-disk file after indexing.
+SECRET = "ZZZ_ON_DISK_PLAINTEXT_MARKER_5ea71c9d"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings. Vectors are numeric, so the text
+ marker can never survive into them as raw bytes — the grep stays sound."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _grep_all(root, needle: bytes):
+ """Every on-disk file under ``root`` that contains ``needle`` (raw bytes)."""
+ return [
+ str(f)
+ for f in root.rglob("*")
+ if f.is_file() and needle in f.read_bytes()
+ ]
+
+
+def _noop(_p):
+ return None
+
+
+def _ok(_p):
+ return (True, None)
+
+
+# ---------------------------------------------------------------------------
+# Facade-level: the single bridge from the vector store to DocumentChunk text.
+# ---------------------------------------------------------------------------
+class TestFacadeIndexingLeavesNoPlaintext:
+ @pytest.fixture
+ def db_session(self):
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ yield session
+ session.close()
+ engine.dispose()
+
+ @pytest.fixture
+ def patched_facade_db(self, db_session, mocker):
+ @contextmanager
+ def _mock_session(*_a, **_k):
+ yield db_session
+
+ mocker.patch(
+ "local_deep_research.vector_stores.facade.get_user_db_session",
+ _mock_session,
+ )
+ return db_session
+
+ def test_faiss_file_holds_no_chunk_text(self, tmp_path, patched_facade_db):
+ vi = VectorIndex(
+ username="testuser",
+ db_password="pw",
+ embeddings=_FakeEmbeddings(dim=8),
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name="collection_secret",
+ dimension=8,
+ path=tmp_path / "collection_secret.faiss",
+ lock=threading.Lock(),
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+ # Put the marker everywhere text/metadata flows to the DB row.
+ chunks = [
+ ChunkInput(
+ text=f"The confidential note body contains {SECRET} inline.",
+ metadata={
+ "document_title": f"Secret title {SECRET}",
+ "title": f"Secret title {SECRET}",
+ "author": f"agent {SECRET}",
+ "chunk_index": 0,
+ },
+ ),
+ ChunkInput(
+ text=f"A second chunk, also mentioning {SECRET} again.",
+ metadata={"chunk_index": 1},
+ ),
+ ]
+ stats = vi.index(
+ source_type="document", source_id="doc-secret-1", chunks=chunks
+ )
+ assert stats.added == 2
+
+ # The .faiss file exists and was actually written.
+ faiss_file = tmp_path / "collection_secret.faiss"
+ assert faiss_file.is_file()
+ assert faiss_file.stat().st_size > 0
+
+ # CORE INVARIANT: the secret is nowhere on disk under the index dir.
+ assert _grep_all(tmp_path, SECRET.encode()) == []
+
+ # Proof the marker really WAS indexed (not silently dropped): it lives
+ # in the DocumentChunk rows (the DB — encrypted in production).
+ rows = (
+ patched_facade_db.query(DocumentChunk)
+ .filter_by(source_id="doc-secret-1")
+ .all()
+ )
+ assert len(rows) == 2
+ assert any(SECRET in r.chunk_text for r in rows)
+ assert any(
+ r.document_title and SECRET in r.document_title for r in rows
+ )
+
+ # And it is retrievable by semantic search, rehydrated from the DB.
+ results = vi.search(
+ f"confidential note {SECRET}", top_k=2, session=patched_facade_db
+ )
+ assert results
+ assert any(SECRET in r.text for r in results)
+
+ def _store(self, tmp_path, patched_facade_db, model, path_name):
+ return VectorIndex(
+ username="testuser",
+ db_password="pw",
+ embeddings=_FakeEmbeddings(dim=8),
+ embedding_model=model,
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ # Same LOGICAL collection across both models — collection_name is
+ # identical per model; only the .faiss path / index_hash differ.
+ collection_name="collection_shared",
+ dimension=8,
+ path=tmp_path / path_name,
+ lock=threading.Lock(),
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+ def test_reindex_under_new_model_keeps_prior_model_chunks(
+ self, tmp_path, patched_facade_db
+ ):
+ """Reindexing a source under a NEW embedding model must NOT delete the
+ OLD model's chunk rows (their only copy of the text). Both models share
+ collection_name; the replace-lookup must be scoped by embedding_model.
+ """
+ session = patched_facade_db
+ chunks = [
+ ChunkInput(text=f"body {SECRET}", metadata={"chunk_index": 0})
+ ]
+
+ # Index doc-1 under model A, then replace-reindex doc-1 under model B
+ # (a physically separate store, same collection_name).
+ self._store(tmp_path, session, "model-A", "a.faiss").index(
+ source_type="document", source_id="doc-1", chunks=chunks
+ )
+ self._store(tmp_path, session, "model-B", "b.faiss").index(
+ source_type="document",
+ source_id="doc-1",
+ chunks=chunks,
+ replace=True,
+ )
+
+ # Model A's rows must survive B's reindex — A's index is kept for revert.
+ a_rows = (
+ session.query(DocumentChunk)
+ .filter_by(source_id="doc-1", embedding_model="model-A")
+ .all()
+ )
+ b_rows = (
+ session.query(DocumentChunk)
+ .filter_by(source_id="doc-1", embedding_model="model-B")
+ .all()
+ )
+ assert len(a_rows) == 1, (
+ "model A's chunk text was destroyed by a model-B reindex"
+ )
+ assert len(b_rows) == 1
+
+
+# ---------------------------------------------------------------------------
+# Service-level: the real LibraryRAGService.index_document production path,
+# writing to the real on-disk cache/rag_indices/<user>/<hash>.faiss layout.
+# ---------------------------------------------------------------------------
+_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
+
+
+class TestServiceIndexDocumentLeavesNoPlaintext:
+ def test_index_document_writes_no_plaintext_to_disk(
+ self, tmp_path, monkeypatch, mocker
+ ):
+ from unittest.mock import MagicMock
+
+ from local_deep_research.config.paths import get_cache_directory
+ from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentStatus,
+ SourceType,
+ )
+
+ # Redirect the whole cache/rag_indices tree into tmp (real path logic).
+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
+
+ # One shared in-memory session behind every get_user_db_session site
+ # (mirrors test_facade.py) — avoids SQLite's per-connection :memory: DBs.
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ @contextmanager
+ def _shared_session(*_a, **_k):
+ yield session
+
+ mocker.patch(f"{_RAG_MOD}.get_user_db_session", _shared_session)
+ mocker.patch(
+ "local_deep_research.vector_stores.facade.get_user_db_session",
+ _shared_session,
+ )
+ # Integrity records live in the DB, not the FAISS tree; stub the manager
+ # so the test stays focused on the on-disk-plaintext invariant.
+ fim = MagicMock()
+ fim.verify_file.return_value = (True, None)
+ fim.record_file.return_value = None
+ mocker.patch(f"{_RAG_MOD}.FileIntegrityManager", return_value=fim)
+
+ # Seed a real Collection + Document carrying the secret in text + title.
+ collection_id = uuid.uuid4().hex
+ document_id = uuid.uuid4().hex
+ source_type = SourceType(
+ id=uuid.uuid4().hex, name="document", display_name="Document"
+ )
+ session.add(source_type)
+ session.add(
+ Collection(id=collection_id, name=f"Secret collection {SECRET}")
+ )
+ import hashlib
+
+ body = (
+ f"This document's confidential body mentions {SECRET} "
+ "several times. " * 5
+ )
+ session.add(
+ Document(
+ id=document_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(body.encode()).hexdigest(),
+ title=f"Secret document title {SECRET}",
+ text_content=body,
+ original_url="http://example.com/secret",
+ file_size=len(body),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.commit()
+
+ # Real service, only the embedding model faked (no network/model load).
+ emb_mgr = MagicMock()
+ emb_mgr.embeddings = _FakeEmbeddings(dim=8)
+
+ from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ )
+
+ svc = LibraryRAGService(
+ username="produser",
+ db_password="pw",
+ embedding_model="fake-model",
+ embedding_provider="sentence_transformers",
+ embedding_manager=emb_mgr,
+ )
+
+ result = svc.index_document(document_id, collection_id)
+ assert result["status"] == "success", result
+ assert result.get("chunk_count", 0) > 0
+
+ # The real production index path wrote a .faiss under cache/rag_indices.
+ rag_root = get_cache_directory() / "rag_indices"
+ faiss_files = list(rag_root.rglob("*.faiss"))
+ assert faiss_files, "no .faiss index was written to the cache tree"
+
+ # CORE INVARIANT: the secret is NOWHERE on disk under the ENTIRE data
+ # dir. The DB is in-memory (no file), so every on-disk artifact the
+ # index path produced is fair game — chunk text/title/metadata must live
+ # only in the DB (encrypted in production), never in a file.
+ leaked = _grep_all(tmp_path, SECRET.encode())
+ assert leaked == [], f"plaintext marker leaked to disk: {leaked}"
+ # And no companion file is written by the new store (no .pkl / .json /
+ # .idmap sidecar) — a regression to the old pickle wrapper surfaces here.
+ assert list(rag_root.rglob("*.pkl")) == []
+ assert list(rag_root.rglob("*.json")) == []
+
+ # Proof it really indexed: the secret IS in the DocumentChunk rows.
+ rows = (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id, source_type="document")
+ .all()
+ )
+ assert rows
+ assert any(SECRET in r.chunk_text for r in rows)
+
+ # Full production round-trip: semantic search via the service returns the
+ # content, rehydrated from the DB by int id (the store never held text).
+ hits = svc.search(f"confidential body {SECRET}", collection_id, top_k=3)
+ assert hits
+ assert any(SECRET in h.text for h in hits)
+
+ svc.close()
diff --git a/tests/vector_stores/test_no_plaintext_property.py b/tests/vector_stores/test_no_plaintext_property.py
new file mode 100644
index 0000000000..05431a433a
--- /dev/null
+++ b/tests/vector_stores/test_no_plaintext_property.py
@@ -0,0 +1,221 @@
+"""Property-based generalization of ``test_no_plaintext_production_path.py``.
+
+That test proves the core invariant — chunk TEXT lives only in the (per-user,
+SQLCipher-encrypted) DB, while the on-disk FAISS index holds only vectors +
+int ``DocumentChunk.id``s — for one fixed secret string. Here we fuzz the
+chunk TEXT itself with Hypothesis over arbitrary unicode: empty strings,
+non-BMP codepoints, NUL/other control characters, and large bodies. For every
+generated example we drive the REAL ``VectorIndex`` facade over a REAL
+on-disk ``FaissVectorStore`` (a real ``faiss.IndexIDMap2``, real
+``faiss.write_index`` bytes on disk) with a deterministic, network-free
+``_FakeEmbeddings``, then recursively grep every file under the index
+directory (the persisted ``.faiss`` plus any transient temp-file bytes) for
+the exact text. It must appear NOWHERE on disk.
+
+The text is embedded behind a distinctive per-test marker (rather than
+grepped for on its own) so the check stays sound even for tiny/degenerate
+examples (e.g. a single space or digit) that would otherwise be near-certain
+to occur *by coincidence* inside arbitrary binary index bytes.
+"""
+
+import shutil
+import tempfile
+import threading
+import uuid
+from contextlib import contextmanager
+from pathlib import Path
+from unittest import mock
+
+import numpy as np
+from hypothesis import HealthCheck, given, settings
+from hypothesis import strategies as st
+from langchain_core.embeddings import Embeddings
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ DocumentChunk,
+ EmbeddingProvider,
+)
+from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+
+# Distinctive marker prefix. Random-looking and long enough (30+ chars) that
+# it cannot plausibly occur by chance inside the binary bytes of a faiss
+# index file, so its absence is a meaningful signal rather than luck.
+MARKER = "ZZZ_PROPERTY_ON_DISK_MARKER_7c19be4a"
+
+
+class _FakeEmbeddings(Embeddings):
+ """Deterministic, network-free embeddings. Vectors are numeric, so the
+ text marker can never survive into them as raw bytes -- the grep stays
+ sound regardless of what text is drawn."""
+
+ def __init__(self, dim: int = 8):
+ self.dim = dim
+
+ def _vec(self, text: str):
+ rng = np.random.default_rng(abs(hash(text)) % (2**32))
+ return rng.random(self.dim).tolist()
+
+ def embed_documents(self, texts):
+ return [self._vec(t) for t in texts]
+
+ def embed_query(self, text):
+ return self._vec(text)
+
+
+def _grep_all(root: Path, needle: bytes):
+ """Every on-disk file under ``root`` that contains ``needle`` (raw bytes)."""
+ return [
+ str(f)
+ for f in root.rglob("*")
+ if f.is_file() and needle in f.read_bytes()
+ ]
+
+
+def _noop(_p):
+ return None
+
+
+def _ok(_p):
+ return (True, None)
+
+
+# ---------------------------------------------------------------------------
+# Text strategies: unicode incl. non-BMP, control/NUL characters, empty, and
+# large bodies. Plain ``st.text()`` already draws from the full codepoint
+# range (hypothesis excludes lone surrogates so ``str.encode()`` never
+# raises), but we bias the mix toward the specific edges the migration must
+# survive so a modest example budget reliably hits them.
+_control_chars = st.characters(min_codepoint=0x00, max_codepoint=0x1F)
+_non_bmp_chars = st.characters(min_codepoint=0x10000, max_codepoint=0x10FFFF)
+
+_arbitrary_chunk_text = st.one_of(
+ st.just(""),
+ st.text(min_size=0, max_size=50),
+ st.text(alphabet=_control_chars, min_size=1, max_size=20),
+ st.text(alphabet=_non_bmp_chars, min_size=1, max_size=10),
+ st.text(min_size=2000, max_size=4000),
+)
+
+
+@contextmanager
+def _isolated_store(text_for_chunk: str):
+ """Build a throwaway (tmp dir + in-memory DB + VectorIndex) sandbox for
+ one Hypothesis example and index a single chunk containing
+ ``text_for_chunk``. Yields ``(tmp_root, session, source_id, combined)``.
+
+ Fully self-contained per call (own tempdir/engine/session) rather than
+ reusing pytest's ``tmp_path``/``mocker`` fixtures, since those are
+ function-scoped and Hypothesis re-invokes the test body many times per
+ test function call -- sharing them across examples would let state and
+ on-disk files pile up between examples.
+ """
+ tmp_root = Path(tempfile.mkdtemp(prefix="ldr_prop_no_plaintext_"))
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+ try:
+
+ @contextmanager
+ def _mock_session(*_a, **_k):
+ yield session
+
+ with mock.patch(
+ "local_deep_research.vector_stores.facade.get_user_db_session",
+ _mock_session,
+ ):
+ vi = VectorIndex(
+ username="testuser",
+ db_password="pw",
+ embeddings=_FakeEmbeddings(dim=8),
+ embedding_model="fake-model",
+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,
+ collection_name="collection_prop",
+ dimension=8,
+ path=tmp_root / "collection_prop.faiss",
+ lock=threading.Lock(),
+ integrity_record=_noop,
+ integrity_verify=_ok,
+ index_type="flat",
+ metric="cosine",
+ normalize=True,
+ )
+
+ # Embed the drawn text behind the distinctive marker so an exact
+ # on-disk match is never a coincidence, even for trivial/short
+ # drawn text (empty string, a single space, "0", ...).
+ combined = f"{MARKER}::{text_for_chunk}::{MARKER}"
+ source_id = f"doc-{uuid.uuid4().hex}"
+
+ stats = vi.index(
+ source_type="document",
+ source_id=source_id,
+ chunks=[ChunkInput(text=combined, metadata={"chunk_index": 0})],
+ )
+ assert stats.added == 1
+
+ yield tmp_root, session, source_id, combined
+ finally:
+ session.close()
+ engine.dispose()
+ shutil.rmtree(tmp_root, ignore_errors=True)
+
+
+@settings(
+ max_examples=40, deadline=None, suppress_health_check=[HealthCheck.too_slow]
+)
+@given(text=_arbitrary_chunk_text)
+def test_arbitrary_chunk_text_never_leaks_to_disk(text):
+ with _isolated_store(text) as (tmp_root, session, source_id, combined):
+ # The .faiss file was actually written.
+ faiss_file = tmp_root / "collection_prop.faiss"
+ assert faiss_file.is_file()
+ assert faiss_file.stat().st_size > 0
+
+ # CORE INVARIANT: neither the raw marker nor the full marker-wrapped
+ # chunk text (which contains the arbitrary drawn text verbatim)
+ # appears anywhere on disk under the index directory -- this also
+ # sweeps up any transient temp-file bytes left behind by a persist().
+ leaked_marker = _grep_all(tmp_root, MARKER.encode())
+ assert leaked_marker == [], f"marker leaked to disk: {leaked_marker}"
+
+ leaked_combined = _grep_all(tmp_root, combined.encode())
+ assert leaked_combined == [], (
+ f"chunk text leaked to disk: {leaked_combined}"
+ )
+
+ # No companion docstore/sidecar file of any kind -- the store is
+ # pure faiss binary (write_index/read_index), no pickle/json/idmap.
+ assert list(tmp_root.rglob("*.pkl")) == []
+ assert list(tmp_root.rglob("*.json")) == []
+ assert list(tmp_root.rglob("*.tmp")) == []
+
+ # Proof the text really WAS indexed (not silently dropped/truncated):
+ # its only copy lives in the DocumentChunk row (the DB -- encrypted
+ # in production).
+ rows = session.query(DocumentChunk).filter_by(source_id=source_id).all()
+ assert len(rows) == 1
+ assert rows[0].chunk_text == combined
+
+
+def test_grep_helper_actually_bites():
+ """Sanity check that ``_grep_all`` isn't vacuously passing: plant the
+ marker in a file under a directory and confirm it IS detected. Without
+ this, a bug that made the main property test's grep silently a no-op
+ (e.g. an empty root, a typo'd needle) would let every example pass for
+ the wrong reason.
+ """
+ tmp_root = Path(tempfile.mkdtemp(prefix="ldr_prop_grep_check_"))
+ try:
+ planted = tmp_root / "planted.bin"
+ planted.write_bytes(f"prefix {MARKER} suffix".encode())
+
+ hits = _grep_all(tmp_root, MARKER.encode())
+ assert hits == [str(planted)]
+
+ # And a needle that truly isn't present is correctly reported absent.
+ assert _grep_all(tmp_root, b"NOT_PRESENT_AT_ALL_xyz") == []
+ finally:
+ shutil.rmtree(tmp_root, ignore_errors=True)
diff --git a/tests/web/test_app_coverage.py b/tests/web/test_app_coverage.py
index 536528f279..05b9f4c3bd 100644
--- a/tests/web/test_app_coverage.py
+++ b/tests/web/test_app_coverage.py
@@ -21,6 +21,7 @@ MODULE = "local_deep_research.web.app"
_CLEANUP_MOD = "local_deep_research.web.auth.connection_cleanup"
_SESSION_MOD = "local_deep_research.web.auth.session_manager"
_DB_MOD = "local_deep_research.database.encrypted_db"
+_LEGACY_CLEANUP_MOD = "local_deep_research.vector_stores.legacy_cleanup"
@pytest.fixture(autouse=True)
@@ -33,6 +34,20 @@ def _stub_log_queue_daemon():
yield
[email protected](autouse=True)
+def _stub_legacy_docstore_migration():
+ """Prevent main() from touching the real (non-isolated) RAG cache dir.
+
+ main() calls migrate_legacy_docstores() (via a local import) at startup,
+ which scans/deletes files under get_cache_directory() -- this test module
+ doesn't use the `app`/temp_data_dir fixtures that set LDR_DATA_DIR, so
+ without this stub it would run against this machine's real cache
+ directory on every test in this file.
+ """
+ with patch(f"{_LEGACY_CLEANUP_MOD}.migrate_legacy_docstores"):
+ yield
+
+
def _handler_by_name(captured, name):
"""Locate an atexit handler by function name (order-independent)."""
for fn in captured:
diff --git a/tests/web/test_app_main_coverage.py b/tests/web/test_app_main_coverage.py
index e083435c48..c3266bdfb3 100644
--- a/tests/web/test_app_main_coverage.py
+++ b/tests/web/test_app_main_coverage.py
@@ -26,6 +26,7 @@ MODULE = "local_deep_research.web.app"
_CLEANUP_MOD = "local_deep_research.web.auth.connection_cleanup"
_SESSION_MOD = "local_deep_research.web.auth.session_manager"
_DB_MOD = "local_deep_research.database.encrypted_db"
+_LEGACY_CLEANUP_MOD = "local_deep_research.vector_stores.legacy_cleanup"
@pytest.fixture(autouse=True)
@@ -38,6 +39,20 @@ def _stub_log_queue_daemon():
yield
[email protected](autouse=True)
+def _stub_legacy_docstore_migration():
+ """Prevent main() from touching the real (non-isolated) RAG cache dir.
+
+ main() calls migrate_legacy_docstores() (via a local import) at startup,
+ which scans/deletes files under get_cache_directory() -- this test module
+ doesn't use the `app`/temp_data_dir fixtures that set LDR_DATA_DIR, so
+ without this stub it would run against this machine's real cache
+ directory on every test in this file.
+ """
+ with patch(f"{_LEGACY_CLEANUP_MOD}.migrate_legacy_docstores"):
+ yield
+
+
def _handler_by_name(captured, name):
"""Locate an atexit handler by function name (order-independent)."""
for fn in captured:
diff --git a/tests/web_search_engines/engines/test_embedding_manager_coverage.py b/tests/web_search_engines/engines/test_embedding_manager_coverage.py
index b9774e7023..31659fb917 100644
--- a/tests/web_search_engines/engines/test_embedding_manager_coverage.py
+++ b/tests/web_search_engines/engines/test_embedding_manager_coverage.py
@@ -5,18 +5,20 @@ Covers:
- close() resource cleanup and idempotency
- Context manager (__enter__ / __exit__)
- Lazy initialization via the embeddings property
-- _store_chunks_to_db() including deduplication and edge cases
- _delete_chunks_from_db()
- Provider selection logic in _initialize_embeddings()
+
+NOTE: ``_store_chunks_to_db()`` was deleted from the source (see the
+NOTE(cutover) comment in ``local_embedding_manager.py``) — its callers now
+write chunk rows via ``vector_stores.facade.VectorIndex.index`` instead. The
+tests that exercised it were removed with it.
"""
-import hashlib
import threading
from contextlib import contextmanager
from unittest.mock import MagicMock, Mock, patch
import pytest
-from langchain_core.documents import Document
from local_deep_research.web_search_engines.engines.local_embedding_manager import (
LocalEmbeddingManager,
@@ -58,11 +60,6 @@ class TestClose:
manager.close()
assert manager._embeddings is None
- def test_close_clears_vector_stores(self, manager):
- manager.vector_stores["col1"] = Mock()
- manager.close()
- assert manager.vector_stores == {}
-
def test_close_is_idempotent(self, manager):
"""Calling close() multiple times must not raise."""
manager._embeddings = Mock()
@@ -290,352 +287,6 @@ class TestInitializeEmbeddings:
assert len(calls) == 1
-# ---------------------------------------------------------------------------
-# _store_chunks_to_db
-# ---------------------------------------------------------------------------
-
-
-def _make_doc(text, metadata=None):
- return Document(page_content=text, metadata=metadata or {})
-
-
-class TestStoreChunksToDb:
- def test_no_username_returns_empty(self, manager):
- """Without a username the method should bail out early."""
- result = manager._store_chunks_to_db(
- [_make_doc("hello")], "collection_abc"
- )
- assert result == []
-
- def test_stores_new_chunks(self, manager_with_user):
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ):
- docs = [_make_doc("chunk one"), _make_doc("chunk two")]
- ids = manager_with_user._store_chunks_to_db(docs, "col1")
-
- assert len(ids) == 2
- assert mock_session.add.call_count == 2
- mock_session.commit.assert_called_once()
-
- def test_deduplication_reuses_existing_chunk(self, manager_with_user):
- existing = MagicMock()
- existing.embedding_id = "existing-id-123"
- existing.last_accessed = None
-
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = existing
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ):
- ids = manager_with_user._store_chunks_to_db(
- [_make_doc("duplicate text")], "col1"
- )
-
- assert ids == ["existing-id-123"]
- # Should NOT add a new row
- mock_session.add.assert_not_called()
- mock_session.commit.assert_called_once()
- # last_accessed should be updated
- assert existing.last_accessed is not None
-
- def test_dedup_lookup_is_scoped_to_collection(self, manager_with_user):
- """The existing-chunk lookup must mirror the schema's
- uix_chunk_collection UNIQUE (chunk_hash, collection_name) — a
- hash-only lookup reused rows and embedding ids ACROSS collections,
- mis-attributing collection_name and sharing one embedding id
- between different collections' FAISS indexes."""
- mock_session = MagicMock()
- filter_by_kwargs = []
-
- def capture_filter_by(**kwargs):
- filter_by_kwargs.append(kwargs)
- mock_filter = MagicMock()
- mock_filter.first.return_value = None
- return mock_filter
-
- mock_session.query.return_value.filter_by = capture_filter_by
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ):
- manager_with_user._store_chunks_to_db([_make_doc("text")], "col1")
-
- assert filter_by_kwargs, "dedup lookup did not run"
- assert filter_by_kwargs[0].get("collection_name") == "col1"
- assert "chunk_hash" in filter_by_kwargs[0]
-
- def test_reuse_repoints_ownership_to_current_document(
- self, manager_with_user
- ):
- """Identical text in two documents of one collection shares a
- single chunk row (schema UNIQUE). The row's source_id is the
- authoritative owner record for the re-index purge; on reuse by a
- different document it must be re-pointed so the purge knows the
- chunk is still in use when the original indexer edits it away."""
- existing = MagicMock()
- existing.embedding_id = "shared-id"
- existing.source_id = "doc-A"
- existing.source_type = "document"
-
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = existing
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ):
- ids = manager_with_user._store_chunks_to_db(
- [_make_doc("shared paragraph")],
- "col1",
- source_id="doc-B",
- source_type="document",
- )
-
- assert ids == ["shared-id"]
- mock_session.add.assert_not_called()
- assert existing.source_id == "doc-B", (
- "reused chunk row must be re-pointed to the latest claimant"
- )
-
- def test_mixed_new_and_existing(self, manager_with_user):
- existing = MagicMock()
- existing.embedding_id = "old-id"
-
- call_count = 0
-
- def side_effect(**kwargs):
- nonlocal call_count
- call_count += 1
- mock_filter = MagicMock()
- if call_count == 1:
- mock_filter.first.return_value = existing
- else:
- mock_filter.first.return_value = None
- return mock_filter
-
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by = side_effect
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ):
- docs = [_make_doc("existing text"), _make_doc("new text")]
- ids = manager_with_user._store_chunks_to_db(docs, "col1")
-
- assert len(ids) == 2
- assert ids[0] == "old-id"
- assert mock_session.add.call_count == 1
-
- def test_metadata_extraction(self, manager_with_user):
- """Chunk metadata (filename, start_char, end_char) is forwarded."""
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- added_objects = []
- mock_session.add.side_effect = lambda obj: added_objects.append(obj)
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with (
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ),
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
- ) as MockChunk,
- ):
- MockChunk.side_effect = lambda **kw: MagicMock(**kw)
- meta = {"filename": "notes.txt", "start_char": 10, "end_char": 50}
- manager_with_user._store_chunks_to_db(
- [_make_doc("text", metadata=meta)],
- "col1",
- source_path="/tmp/notes.txt",
- source_id=42,
- source_type="local_file",
- )
- _, kwargs = MockChunk.call_args
- assert kwargs["document_title"] == "notes.txt"
- assert kwargs["start_char"] == 10
- assert kwargs["end_char"] == 50
- assert kwargs["source_path"] == "/tmp/notes.txt"
- assert kwargs["source_id"] == 42
-
- def test_title_falls_back_to_title_key(self, manager_with_user):
- """If 'filename' missing, document_title falls back to 'title'."""
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with (
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ),
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
- ) as MockChunk,
- ):
- MockChunk.side_effect = lambda **kw: MagicMock(**kw)
- meta = {"title": "My Paper"}
- manager_with_user._store_chunks_to_db(
- [_make_doc("text", metadata=meta)], "col1"
- )
- _, kwargs = MockChunk.call_args
- assert kwargs["document_title"] == "My Paper"
-
- def test_title_defaults_to_unknown(self, manager_with_user):
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with (
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ),
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
- ) as MockChunk,
- ):
- MockChunk.side_effect = lambda **kw: MagicMock(**kw)
- manager_with_user._store_chunks_to_db([_make_doc("text")], "col1")
- _, kwargs = MockChunk.call_args
- assert kwargs["document_title"] == "Unknown"
-
- def test_db_exception_returns_empty(self, manager_with_user):
- """If the DB session raises, return []."""
-
- @contextmanager
- def exploding_session(u, p):
- raise RuntimeError("DB down")
- yield # noqa: unreachable
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=exploding_session,
- ):
- result = manager_with_user._store_chunks_to_db(
- [_make_doc("text")], "col1"
- )
- assert result == []
-
- def test_empty_chunks_list(self, manager_with_user):
- mock_session = MagicMock()
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ):
- ids = manager_with_user._store_chunks_to_db([], "col1")
-
- assert ids == []
- mock_session.add.assert_not_called()
- mock_session.commit.assert_called_once()
-
- def test_chunk_hash_uses_sha256(self, manager_with_user):
- """Verify the chunk hash is computed as SHA256 of page_content."""
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- filter_by_calls = []
- original_filter_by = mock_session.query.return_value.filter_by
-
- def capture_filter_by(**kwargs):
- filter_by_calls.append(kwargs)
- return original_filter_by(**kwargs)
-
- mock_session.query.return_value.filter_by = capture_filter_by
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- text = "hello world"
- expected_hash = hashlib.sha256(text.encode()).hexdigest()
-
- with (
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ),
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
- ) as MockChunk,
- ):
- MockChunk.side_effect = lambda **kw: MagicMock(**kw)
- manager_with_user._store_chunks_to_db([_make_doc(text)], "col1")
-
- assert any(
- c.get("chunk_hash") == expected_hash for c in filter_by_calls
- )
-
- def test_word_count_calculation(self, manager_with_user):
- mock_session = MagicMock()
- mock_session.query.return_value.filter_by.return_value.first.return_value = None
-
- @contextmanager
- def fake_session(u, p):
- yield mock_session
-
- with (
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.get_user_db_session",
- side_effect=fake_session,
- ),
- patch(
- "local_deep_research.web_search_engines.engines.local_embedding_manager.DocumentChunk"
- ) as MockChunk,
- ):
- MockChunk.side_effect = lambda **kw: MagicMock(**kw)
- manager_with_user._store_chunks_to_db(
- [_make_doc("one two three four")], "col1"
- )
- _, kwargs = MockChunk.call_args
- assert kwargs["word_count"] == 4
-
-
# ---------------------------------------------------------------------------
# _delete_chunks_from_db
# ---------------------------------------------------------------------------
@@ -718,7 +369,6 @@ class TestInitialization:
assert mgr.username is None
assert mgr.db_password is None
assert mgr._closed is False
- assert mgr.vector_stores == {}
def test_settings_snapshot_none_defaults_to_empty_dict(self):
mgr = LocalEmbeddingManager(settings_snapshot=None)
diff --git a/tests/web_search_engines/engines/test_local_search_coverage.py b/tests/web_search_engines/engines/test_local_search_coverage.py
index 16c1e91210..9bc93f19d1 100644
--- a/tests/web_search_engines/engines/test_local_search_coverage.py
+++ b/tests/web_search_engines/engines/test_local_search_coverage.py
@@ -14,6 +14,8 @@ Covers:
from unittest.mock import Mock, MagicMock, patch
import pytest
+from local_deep_research.vector_stores.facade import SearchResult
+
# ---------------------------------------------------------------------------
# Common patch paths
# ---------------------------------------------------------------------------
@@ -67,6 +69,24 @@ def _mock_rag_index(
return idx
+def _sr(doc, distance, metric="l2"):
+ """Build a ``SearchResult`` (the new ``rag_service.search()`` shape) from
+ an old-style fake Document (``page_content`` + ``metadata``) + a raw
+ distance. ``document_title``/``source_id``/``source_type`` are left
+ unset so the engine's metadata-fallback chain is exercised exactly like
+ it was pre-rewrite (values came only from the metadata dict)."""
+ return SearchResult(
+ chunk_id=1,
+ text=doc.page_content,
+ distance=distance,
+ metric=metric,
+ metadata=doc.metadata,
+ document_title=None,
+ source_id=None,
+ source_type=None,
+ )
+
+
# ---------------------------------------------------------------------------
# Init / Configuration
# ---------------------------------------------------------------------------
@@ -163,9 +183,7 @@ class TestTitleFallbacks:
# RAG service context manager
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.1)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.1)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -213,9 +231,7 @@ class TestSnippetTruncation:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.1)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.1)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -265,9 +281,7 @@ class TestRelevanceScore:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, distance)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, distance)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -323,17 +337,11 @@ class TestMultiCollectionSorting:
def rag_enter(self_rag):
inst = Mock()
inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
if call_count[0] == 0:
- vs.similarity_search_with_score.return_value = [
- (doc_far, 5.0)
- ]
+ inst.search.return_value = [_sr(doc_far, 5.0)]
else:
- vs.similarity_search_with_score.return_value = [
- (doc_close, 0.2)
- ]
+ inst.search.return_value = [_sr(doc_close, 0.2)]
call_count[0] += 1
- inst.load_or_create_faiss_index.return_value = vs
return inst
rag_svc.return_value.__enter__ = rag_enter
@@ -368,11 +376,9 @@ class TestMultiCollectionSorting:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 5}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [
- (docs[i], float(i)) for i in range(5)
+ rag_inst.search.return_value = [
+ _sr(docs[i], float(i)) for i in range(5)
]
- rag_inst.load_or_create_faiss_index.return_value = vs
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -442,11 +448,7 @@ class TestPerCollectionErrors:
inst.get_rag_stats.return_value = {"indexed_documents": 0}
else:
inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [
- (good_doc, 0.1)
- ]
- inst.load_or_create_faiss_index.return_value = vs
+ inst.search.return_value = [_sr(good_doc, 0.1)]
rag_call[0] += 1
return inst
@@ -551,9 +553,7 @@ class TestDocumentURL:
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.5)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.5)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -586,9 +586,7 @@ class TestDocumentURL:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.1)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.1)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -617,9 +615,7 @@ class TestDocIdFallback:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.1)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.1)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -660,9 +656,7 @@ class TestResultMetadata:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.1)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.1)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -688,9 +682,7 @@ class TestResultMetadata:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.1)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.1)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
@@ -782,9 +774,7 @@ class TestResultStructure:
db_sess.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = _mock_rag_index()
rag_inst = Mock()
rag_inst.get_rag_stats.return_value = {"indexed_documents": 1}
- vs = Mock()
- vs.similarity_search_with_score.return_value = [(doc, 0.5)]
- rag_inst.load_or_create_faiss_index.return_value = vs
+ rag_inst.search.return_value = [_sr(doc, 0.5)]
rag_svc.return_value.__enter__.return_value = rag_inst
rag_svc.return_value.__exit__.return_value = None
diff --git a/tests/web_search_engines/engines/test_search_engine_collection.py b/tests/web_search_engines/engines/test_search_engine_collection.py
index a2210c3413..f067385098 100644
--- a/tests/web_search_engines/engines/test_search_engine_collection.py
+++ b/tests/web_search_engines/engines/test_search_engine_collection.py
@@ -11,6 +11,8 @@ Tests cover:
from unittest.mock import Mock, patch
+from local_deep_research.vector_stores.facade import SearchResult
+
class TestCollectionSearchEngineInit:
"""Tests for CollectionSearchEngine initialization."""
@@ -376,11 +378,18 @@ class TestSearch:
mock_rag_instance.get_rag_stats.return_value = {
"indexed_documents": 1
}
- mock_vector_store = Mock()
- mock_vector_store.similarity_search_with_score.return_value = [
- (mock_doc, 0.5)
+ mock_rag_instance.search.return_value = [
+ SearchResult(
+ chunk_id=1,
+ text=mock_doc.page_content,
+ distance=0.5,
+ metric="l2",
+ metadata=mock_doc.metadata,
+ document_title=None,
+ source_id=None,
+ source_type=None,
+ )
]
- mock_rag_instance.load_or_create_faiss_index.return_value = mock_vector_store
mock_rag_service.return_value.__enter__.return_value = (
mock_rag_instance
)
@@ -443,9 +452,7 @@ class TestSearch:
mock_rag_instance.get_rag_stats.return_value = {
"indexed_documents": 1
}
- mock_vector_store = Mock()
- mock_vector_store.similarity_search_with_score.return_value = []
- mock_rag_instance.load_or_create_faiss_index.return_value = mock_vector_store
+ mock_rag_instance.search.return_value = []
mock_rag_service.return_value.__enter__.return_value = (
mock_rag_instance
)
@@ -621,125 +628,6 @@ class TestGetDocumentUrl:
assert url == "/library/document/doc123/pdf"
-class TestRelevanceFromFaissScore:
- """Regression tests for #4963: relevance_score must increase with true
- similarity and stay in [0, 1] for every FAISS index metric.
-
- ``similarity_search_with_score`` returns the raw score of the underlying
- index. For the default ``cosine`` (and ``dot_product``) metric that index
- is ``IndexFlatIP``, whose score is an inner product where *larger is
- nearer*; the old ``1 / (1 + score)`` mapping inverted that ranking and
- divided by zero for an anti-correlated pair.
- """
-
- def _fixed_embeddings(self, mapping):
- """A deterministic Embeddings that returns a preset vector per text."""
- from langchain_core.embeddings import Embeddings
-
- class _FixedEmbeddings(Embeddings):
- def __init__(self, table):
- self._table = table
-
- def embed_documents(self, texts):
- return [list(self._table[t]) for t in texts]
-
- def embed_query(self, text):
- return list(self._table[text])
-
- return _FixedEmbeddings(mapping)
-
- def _build_store(self, metric_index, mapping, texts, normalize):
- from langchain_community.docstore.in_memory import InMemoryDocstore
- from langchain_community.vectorstores import FAISS
-
- store = FAISS(
- self._fixed_embeddings(mapping),
- index=metric_index,
- docstore=InMemoryDocstore(),
- index_to_docstore_id={},
- normalize_L2=normalize,
- )
- store.add_texts(texts)
- return store
-
- def test_inner_product_index_keeps_ranking_and_bounds(self):
- """Cosine/IP index: nearest gets the highest relevance, all in [0, 1]."""
- import faiss
-
- from local_deep_research.web_search_engines.engines.search_engine_collection import (
- _relevance_from_faiss_score,
- )
-
- # 2D unit-ish vectors; query == "near" (cosine 1.0), "mid" ~0.6,
- # "far" is anti-correlated (cosine -1.0 -> old code divides by zero).
- mapping = {
- "query": (1.0, 0.0),
- "near": (1.0, 0.0),
- "mid": (0.6, 0.8),
- "far": (-1.0, 0.0),
- }
- store = self._build_store(
- faiss.IndexFlatIP(2),
- mapping,
- ["near", "mid", "far"],
- normalize=True,
- )
- docs_with_scores = store.similarity_search_with_score("query", k=3)
- rel = {
- doc.page_content: _relevance_from_faiss_score(store, score)
- for doc, score in docs_with_scores
- }
-
- assert all(0.0 <= r <= 1.0 for r in rel.values())
- # Monotonic in true similarity: near > mid > far. On main the mapping
- # inverts this (near 0.5 < mid ~0.62) and "far" raises ZeroDivisionError.
- assert rel["near"] > rel["mid"] > rel["far"]
-
- def test_l2_index_preserves_distance_mapping(self):
- """L2 index: unchanged 1/(1+distance), nearest highest, in (0, 1]."""
- import faiss
-
- from local_deep_research.web_search_engines.engines.search_engine_collection import (
- _relevance_from_faiss_score,
- )
-
- mapping = {
- "query": (0.0, 0.0),
- "near": (0.1, 0.0),
- "far": (5.0, 0.0),
- }
- store = self._build_store(
- faiss.IndexFlatL2(2),
- mapping,
- ["near", "far"],
- normalize=False,
- )
- docs_with_scores = store.similarity_search_with_score("query", k=2)
- rel = {
- doc.page_content: _relevance_from_faiss_score(store, score)
- for doc, score in docs_with_scores
- }
-
- assert all(0.0 < r <= 1.0 for r in rel.values())
- assert rel["near"] > rel["far"]
-
- def test_anticorrelated_ip_score_does_not_divide_by_zero(self):
- """A raw IP score of -1 maps to 0.0, not a ZeroDivisionError."""
- from unittest.mock import Mock
-
- import faiss
-
- from local_deep_research.web_search_engines.engines.search_engine_collection import (
- _relevance_from_faiss_score,
- )
-
- store = Mock()
- store.index.metric_type = faiss.METRIC_INNER_PRODUCT
- assert _relevance_from_faiss_score(store, -1.0) == 0.0
- assert _relevance_from_faiss_score(store, 1.0) == 1.0
- assert _relevance_from_faiss_score(store, 0.0) == 0.5
-
-
class TestClassAttributes:
"""Tests for class attributes."""
diff --git a/tests/web_search_engines/engines/test_search_engine_library.py b/tests/web_search_engines/engines/test_search_engine_library.py
index b07f106dab..820e8240e8 100644
--- a/tests/web_search_engines/engines/test_search_engine_library.py
+++ b/tests/web_search_engines/engines/test_search_engine_library.py
@@ -10,6 +10,8 @@ Tests cover:
from unittest.mock import Mock, patch
+from local_deep_research.vector_stores.facade import SearchResult
+
class TestLibraryRAGSearchEngineInit:
"""Tests for LibraryRAGSearchEngine initialization."""
@@ -198,11 +200,18 @@ class TestSearch:
mock_rag_instance.get_rag_stats.return_value = {
"indexed_documents": 1
}
- mock_vector_store = Mock()
- mock_vector_store.similarity_search_with_score.return_value = [
- (mock_doc, 0.5)
+ mock_rag_instance.search.return_value = [
+ SearchResult(
+ chunk_id=1,
+ text=mock_doc.page_content,
+ distance=0.5,
+ metric="l2",
+ metadata=mock_doc.metadata,
+ document_title=None,
+ source_id=None,
+ source_type=None,
+ )
]
- mock_rag_instance.load_or_create_faiss_index.return_value = mock_vector_store
# Configure context manager behavior
mock_rag_service.return_value.__enter__.return_value = mock_rag_instance
mock_rag_service.return_value.__exit__.return_value = None
diff --git a/tests/web_search_engines/engines/test_search_engine_library_coverage.py b/tests/web_search_engines/engines/test_search_engine_library_coverage.py
index bf8358b32d..e20d89bc6d 100644
--- a/tests/web_search_engines/engines/test_search_engine_library_coverage.py
+++ b/tests/web_search_engines/engines/test_search_engine_library_coverage.py
@@ -11,6 +11,8 @@ Covers:
from unittest.mock import MagicMock, Mock, patch
+from local_deep_research.vector_stores.facade import SearchResult
+
MODULE = "local_deep_research.web_search_engines.engines.search_engine_library"
@@ -133,20 +135,22 @@ class TestSearch:
mock_session.query.return_value.filter_by.return_value.first.return_value = mock_rag_index
# col1 fails when its RAG service is created; col2 succeeds
- mock_doc = MagicMock()
- mock_doc.metadata = {}
- mock_doc.page_content = "matching text from collection 2"
- mock_vector_store = MagicMock()
- mock_vector_store.similarity_search_with_score.return_value = [
- (mock_doc, 0.5)
- ]
mock_rag_service = MagicMock()
mock_rag_service.__enter__ = Mock(return_value=mock_rag_service)
mock_rag_service.__exit__ = Mock(return_value=False)
mock_rag_service.get_rag_stats.return_value = {"indexed_documents": 1}
- mock_rag_service.load_or_create_faiss_index.return_value = (
- mock_vector_store
- )
+ mock_rag_service.search.return_value = [
+ SearchResult(
+ chunk_id=1,
+ text="matching text from collection 2",
+ distance=0.5,
+ metric="l2",
+ metadata={},
+ document_title=None,
+ source_id=None,
+ source_type=None,
+ )
+ ]
with patch(f"{MODULE}.LibraryService", return_value=mock_service):
with patch(