Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(rag): bound FAISS writes and clean up orphan vectors (#7646)

LearningCircuit32d7d0adb1dc
diff --git a/.github/workflows/rag-index-scale.yml b/.github/workflows/rag-index-scale.yml
new file mode 100644
index 0000000000..90f09999f6
--- /dev/null
+++ b/.github/workflows/rag-index-scale.yml
@@ -0,0 +1,88 @@
+name: RAG Index Scale
+
+# The large synthetic PDF corpus is a release-only shard. The script defaults
+# to a small offline workload for local development.
+on:
+ workflow_call:
+ workflow_dispatch:
+
+permissions: {}
+
+jobs:
+ rag-index-scale:
+ name: Synthetic PDFs (${{ matrix.index-type }})
+ runs-on: ubuntu-latest
+ timeout-minutes: 35
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ index-type: [flat, hnsw]
+ env:
+ OMP_NUM_THREADS: '2'
+ OPENBLAS_NUM_THREADS: '2'
+ HF_HUB_OFFLINE: '1'
+ TRANSFORMERS_OFFLINE: '1'
+ RAG_INDEX_TYPE: ${{ matrix.index-type }}
+
+ steps:
+ - name: Harden runner
+ uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1
+ with:
+ egress-policy: audit
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ - name: Set up PDM
+ uses: pdm-project/setup-pdm@544d7237314ee09c256785bd360f6b30add38b37 # v4.6
+ with:
+ python-version: '3.12'
+ version: 2.26.2
+ cache: true
+ cache-restore-exact-match: true
+ - name: Install SQLCipher
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libsqlcipher-dev
+ - name: Install dependencies
+ run: pdm sync -d --clean
+ - name: Exercise the synthetic PDF corpus
+ id: workload
+ shell: bash
+ run: |
+ mkdir -p test-results
+ pdm run python scripts/ci/rag_index_workload.py \
+ --documents 128 --pages 16 --dimension 1024 \
+ --index-type "$RAG_INDEX_TYPE" --max-rss-mib 768 \
+ --report "test-results/rag-scale-$RAG_INDEX_TYPE.json" \
+ 2>&1 | tee "test-results/rag-scale-$RAG_INDEX_TYPE.log"
+ - name: Require a completed scale run
+ if: always()
+ shell: bash
+ run: |
+ python - <<'PYTHON'
+ import json
+ import os
+ from pathlib import Path
+ report = Path("test-results") / ("rag-scale-" + os.environ["RAG_INDEX_TYPE"] + ".json")
+ result = json.loads(report.read_text())
+ assert result["document_count"] == 128
+ assert result["pages_per_document"] == 16
+ assert result["dimension"] == 1024
+ assert result["initial_vectors"] >= 80000
+ assert result["rebuilt_vectors"] == result["remaining_vectors"]
+ assert result["segments"] >= 3
+ assert result["largest_segment_vectors"] <= 4096
+ assert result["remaining_vectors"] > 0
+ assert result["peak_rss_mib"] <= 768
+ print(json.dumps(result, indent=2))
+ PYTHON
+ - name: Upload scale diagnostics
+ if: always()
+ uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ with:
+ name: rag-index-scale-${{ matrix.index-type }}
+ path: test-results/rag-scale-*
+ retention-days: 14
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 837c5e1d87..936d853abb 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -222,6 +222,15 @@ jobs:
permissions:
contents: read
+ # Required release workload: generated PDFs, encrypted storage, bounded
+ # FAISS segments, search, reconfiguration and deletion with fake embeddings.
+ rag-index-scale-gate:
+ needs: [version-check]
+ if: needs.version-check.outputs.should_release == 'true'
+ uses: $/.github/workflows/rag-index-scale.yml
+ permissions:
+ contents: read
+
# ============================================================================
# RESPONSIVE TEST GATE (Advisory) - Responsive UI tests across viewports
# ============================================================================
@@ -282,11 +291,23 @@ jobs:
contents: read
build:
- needs: [version-check, release-gate, ci-gate, test-gate, e2e-test-gate, notes-test-gate, notes-concurrency-gate, responsive-test-gate, compat-test-gate, compose-integration-gate, vulture-gate]
+ needs: [version-check, release-gate, ci-gate, test-gate, e2e-test-gate, notes-test-gate, notes-concurrency-gate, rag-index-scale-gate, responsive-test-gate, compat-test-gate, compose-integration-gate, vulture-gate]
# test-gate (Playwright WebKit), responsive-test-gate, and vulture-gate are advisory
- # release-gate, ci-gate, e2e-test-gate, notes-test-gate, notes-concurrency-gate, compat-test-gate, and compose-integration-gate are required
+ # release-gate, ci-gate, e2e-test-gate, notes-test-gate, notes-concurrency-gate, rag-index-scale-gate, compat-test-gate, and compose-integration-gate are required
# A dry_run rehearsal stops here; every publishing job depends on build.
- if: ${{ !cancelled() && !inputs.dry_run && needs.release-gate.result == 'success' && needs.ci-gate.result == 'success' && needs.e2e-test-gate.result == 'success' && needs.notes-test-gate.result == 'success' && needs.notes-concurrency-gate.result == 'success' && needs.compat-test-gate.result == 'success' && needs.compose-integration-gate.result == 'success' }}
+ if: >-
+ ${{
+ !cancelled() &&
+ !inputs.dry_run &&
+ needs.release-gate.result == 'success' &&
+ needs.ci-gate.result == 'success' &&
+ needs.e2e-test-gate.result == 'success' &&
+ needs.notes-test-gate.result == 'success' &&
+ needs.notes-concurrency-gate.result == 'success' &&
+ needs.rag-index-scale-gate.result == 'success' &&
+ needs.compat-test-gate.result == 'success' &&
+ needs.compose-integration-gate.result == 'success'
+ }}
runs-on: ubuntu-latest
outputs:
version: ${{ steps.version.outputs.version }}
diff --git a/changelog.d/7646.breaking.md b/changelog.d/7646.breaking.md
new file mode 100644
index 0000000000..9c8c80047f
--- /dev/null
+++ b/changelog.d/7646.breaking.md
@@ -0,0 +1 @@
+Store FAISS collections in bounded vector-only segments, preserving encrypted chunk ownership across configuration changes and cleaning orphan vectors. Retain the previous generation on database rollback and recover interrupted writes against committed checksums. Batch history deletion by collection, preserve valid partial documents during reconciliation, and refill search results around orphan hits while loading full records only for requested results. Continue index-family and segment cleanup across individual component errors and report incomplete removal. Retire abandoned checkpoint copies with their index family. Recover damaged vector components on indexing writes and retire complete quarantined generations. Existing native indexes convert on their next write without re-embedding; older application versions require an index rebuild to read converted collections. Add required offline synthetic-PDF release shards for flat and HNSW indexes.
diff --git a/docs/ci/workflow-status.md b/docs/ci/workflow-status.md
index 8a58291180..862757f71d 100644
--- a/docs/ci/workflow-status.md
+++ b/docs/ci/workflow-status.md
@@ -193,3 +193,12 @@ the table above.
`osv-scanner.yml` and `osv-scanner-scheduled.yml`. Verifies the native
scanner binary and complete scan results before artifact and SARIF uploads.
Its status is reported in the calling workflows.
+
+- `rag-index-scale.yml` — required synthetic-PDF scale gate called by
+ `release.yml`, with manual dispatch available. Separate flat and HNSW
+ shards check bounded index writes, memory, search, rollback, deletion,
+ staged rebuilding and encrypted storage using deterministic embeddings.
+ The large workloads never run on pull requests. They run only through
+ `release.yml` — on pushes to `main` or `v*.*.*` tags and on manual release
+ dispatches, gated on `should_release` (a `main` push whose version already
+ has a release skips them) — or through this workflow's own manual dispatch.
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index 969f200da9..650351f685 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -488,9 +488,78 @@ Uses OpenAI's embedding API.
### Memory Issues
-- Reduce chunk size
-- Index fewer documents at once
-- Use a lighter embedding model
+FAISS indexes use segments of at most 4,096 vectors. Appends rewrite the
+partially filled segment and write new segments; they do not rewrite the whole
+collection. Searches visit segments sequentially and merge their best matches.
+Searches also re-verify (hash) every segment file against the authenticated
+manifest on each query. Full chunk records are loaded only for the requested
+results after their IDs are selected. This bounds the vector working set, at the
+cost of reading multiple segments for a large collection. Embedding models, PDF
+extraction, individual document preparation, and reconciliation metadata still
+contribute to memory use.
+
+Existing native `.faiss` files remain readable and convert on their next write
+without re-embedding. Conversion reads the old payload through read-only memory
+mapping, so mapped pages can contribute to RSS while remaining reclaimable.
+Conversion temporarily needs disk space for both formats. The new root `.faiss`
+file is an authenticated manifest; its companion `.faiss.segments/` directory
+contains vectors, numeric IDs, and no document text. Back up the complete index
+directory together with the encrypted database. Older application versions
+cannot read the segmented format and require rebuilding their indexes from the
+encrypted documents after a downgrade.
+
+Chunk ownership includes the full physical index configuration. Incremental
+indexing replaces only that configuration's chunks, and document deletion purges
+every retained configuration. A successful full collection rebuild replaces the
+previous published configurations. Writes and reconciliation remove
+unowned vectors; surviving chunks from partially indexed documents are retained
+and reported separately. A rollback checkpoint preserves the previous vector
+generation until the database commits. Crash recovery restores a checkpoint
+only when it matches the checksum in the encrypted database.
+
+Search refuses corrupt vector components. An indexing write can quarantine the
+damaged generation and retry the document once; other documents are marked for
+re-indexing. Quarantine retention removes vector segments together with their
+manifests, including payloads left by older cleanup attempts.
+
+Index coordination retains the application's single-process scope. Segmentation
+does not add coordination between independent server processes.
+
+Use a smaller embedding dimension or reduce concurrent document preparation if
+the embedding model or a single document exceeds available memory. Reducing
+chunk size can **increase** the total vector count and index size.
+
+### Synthetic PDF scale test
+
+Generate and index a small offline corpus from the checkout:
+
+```bash
+pdm run python scripts/ci/rag_index_workload.py --report /tmp/rag-scale.json
+```
+
+PDFs are generated in memory using repeated words and unique page markers. The
+test uses deterministic fake embeddings, real PDF extraction and chunking,
+real SQLCipher storage, and real FAISS indexing, search, configuration changes,
+rollback recovery, bulk deletion, and staged collection rebuilding. No embedding
+server, API credentials, model download, or
+external documents are needed.
+
+The required **RAG Index Scale** release workflow runs separate flat and HNSW
+shards, each with 128 PDFs of 16 pages and 1,024-dimensional embeddings:
+
+```bash
+OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 pdm run python scripts/ci/rag_index_workload.py \
+ --documents 128 --pages 16 --dimension 1024 --index-type hnsw \
+ --max-rss-mib 768 --report /tmp/rag-scale-hnsw.json
+```
+
+The report includes vector/segment counts, peak process RSS, elapsed time, and
+bytes written. The workload fails on oversized segment writes, excessive append
+write volume, orphan vectors, incorrect search/deletion results, plaintext
+document persistence, or an exceeded RSS budget. It tests storage behavior, not
+embedding quality or the memory requirements of a real embedding model. The
+large shards run on releases or manual workflow requests; focused lifecycle
+regressions and the small PDF generator test run in the regular pytest suite.
---
diff --git a/scripts/ci/rag_index_workload.py b/scripts/ci/rag_index_workload.py
new file mode 100644
index 0000000000..4cfd6047bb
--- /dev/null
+++ b/scripts/ci/rag_index_workload.py
@@ -0,0 +1,11 @@
+"""Run the opt-in synthetic PDF release workload from a source checkout."""
+
+from pathlib import Path
+import sys
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+from tests.performance.rag_index_workload import main # noqa: E402
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/local_deep_research/database/migrations/versions/0042_chunk_vector_index_owner.py b/src/local_deep_research/database/migrations/versions/0042_chunk_vector_index_owner.py
new file mode 100644
index 0000000000..09c3486bd5
--- /dev/null
+++ b/src/local_deep_research/database/migrations/versions/0042_chunk_vector_index_owner.py
@@ -0,0 +1,106 @@
+"""Track the physical index owning each encrypted chunk row.
+
+Revision ID: 0042
+Revises: 0034
+
+The backfill sets the key only when exactly one rag_indices row matches the
+chunk's collection, embedding model and embedding provider. Zero or several
+matches remain NULL and are adopted later from actual vector membership.
+"""
+
+from alembic import op
+import sqlalchemy as sa
+
+revision = "0042"
+down_revision = "0034"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+ if not inspector.has_table("document_chunks"):
+ return
+ if "vector_index_key" not in {
+ column["name"] for column in inspector.get_columns("document_chunks")
+ }:
+ op.add_column(
+ "document_chunks", sa.Column("vector_index_key", sa.String(64))
+ )
+ op.create_index(
+ "ix_document_chunks_vector_index_key",
+ "document_chunks",
+ ["vector_index_key"],
+ )
+ if inspector.has_table("rag_indices"):
+ bind.execute(
+ sa.text("""
+ UPDATE document_chunks SET vector_index_key = CASE WHEN (
+ SELECT COUNT(*) FROM rag_indices r
+ WHERE r.collection_name = document_chunks.collection_name
+ AND r.embedding_model = document_chunks.embedding_model
+ AND r.embedding_model_type = document_chunks.embedding_model_type
+ ) = 1 THEN (
+ SELECT MIN(r.index_hash) FROM rag_indices r
+ WHERE r.collection_name = document_chunks.collection_name
+ AND r.embedding_model = document_chunks.embedding_model
+ AND r.embedding_model_type = document_chunks.embedding_model_type
+ ) END WHERE vector_index_key IS NULL
+ """)
+ )
+
+
+def downgrade():
+ bind = op.get_bind()
+ inspector = sa.inspect(bind)
+ if not inspector.has_table("document_chunks"):
+ return
+ if "vector_index_key" in {
+ column["name"] for column in inspector.get_columns("document_chunks")
+ }:
+ # The batch rebuild restarts the AUTOINCREMENT counter at the highest
+ # surviving id; restore it so deleted chunk ids are never reused.
+ sequence = _chunk_sequence(bind)
+ has_index = "ix_document_chunks_vector_index_key" in {
+ index["name"] for index in inspector.get_indexes("document_chunks")
+ }
+ with op.batch_alter_table(
+ "document_chunks", table_kwargs={"sqlite_autoincrement": True}
+ ) as batch:
+ if has_index:
+ batch.drop_index("ix_document_chunks_vector_index_key")
+ batch.drop_column("vector_index_key")
+ if sequence is not None:
+ rebuilt = _chunk_sequence(bind)
+ if rebuilt is None:
+ bind.execute(
+ sa.text(
+ "INSERT INTO sqlite_sequence (name, seq) "
+ "VALUES ('document_chunks', :seq)"
+ ),
+ {"seq": sequence},
+ )
+ elif rebuilt < sequence:
+ bind.execute(
+ sa.text(
+ "UPDATE sqlite_sequence SET seq = :seq "
+ "WHERE name = 'document_chunks'"
+ ),
+ {"seq": sequence},
+ )
+
+
+def _chunk_sequence(bind):
+ if not bind.execute(
+ sa.text(
+ "SELECT 1 FROM sqlite_master "
+ "WHERE type = 'table' AND name = 'sqlite_sequence'"
+ )
+ ).first():
+ return None
+ return bind.execute(
+ sa.text(
+ "SELECT seq FROM sqlite_sequence WHERE name = 'document_chunks'"
+ )
+ ).scalar()
diff --git a/src/local_deep_research/database/models/library.py b/src/local_deep_research/database/models/library.py
index 53fe182c46..28aea6c692 100644
--- a/src/local_deep_research/database/models/library.py
+++ b/src/local_deep_research/database/models/library.py
@@ -630,6 +630,9 @@ class DocumentChunk(Base):
nullable=False,
)
embedding_dimension = Column(Integer, nullable=True) # Vector dimension
+ # Physical index generation/configuration, not just the embedding model.
+ # NULL denotes a legacy row whose ownership has not yet been recovered.
+ vector_index_key = Column(String(64), nullable=True, index=True)
# Document metadata (for context)
document_title = Column(Text, nullable=True) # Title of source document
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 924def92de..fcb04253db 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
@@ -105,6 +105,8 @@ class DocumentDeletionService:
self, targets: List[Tuple[str, List[str]]]
) -> None:
"""Purge vectors and residual chunks after research deletion commits."""
+ groups: Dict[str, set[str]] = {}
+ deleted_documents: set[str] = set()
for document_id, collection_ids in targets:
# The pre-delete snapshot also contains documents transferred to
# surviving research by the cascade. Only a missing document may
@@ -127,9 +129,40 @@ class DocumentDeletionService:
f"{'s' if len(collection_ids) != 1 else ''})"
)
continue
- self._purge_document_rag(
- document_id, collection_ids, full_delete=True
- )
+ deleted_documents.add(document_id)
+ for collection_id in collection_ids:
+ groups.setdefault(collection_id, set()).add(document_id)
+
+ from ...services.rag_service_factory import get_rag_service
+
+ for collection_id, document_ids in groups.items():
+ try:
+ with get_rag_service(
+ self.username,
+ collection_id=collection_id,
+ db_password=capture_request_db_password(self.username),
+ ) as rag:
+ rag.purge_documents_vectors(
+ sorted(document_ids), collection_id
+ )
+ except Exception:
+ logger.opt(exception=True).warning(
+ "Deferred research vector cleanup"
+ )
+ # Preserve the deletion privacy backstop even if a vector file was
+ # unavailable. Its unresolvable vectors are collected on reconciliation.
+ if deleted_documents:
+ try:
+ with get_user_db_session(self.username) as session:
+ for document_id in deleted_documents:
+ CascadeHelper.delete_document_chunks(
+ session, document_id
+ )
+ session.commit()
+ except Exception:
+ logger.opt(exception=True).warning(
+ "Could not sweep deleted research chunks"
+ )
def delete_document(self, document_id: str) -> Dict[str, Any]:
"""Delete one document, serializing duplicate in-process requests."""
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 e6cffbb03a..f4d73d09a3 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
@@ -450,7 +450,10 @@ class CascadeHelper:
symlink-escape rationale.
Returns:
- True if files were deleted, False otherwise
+ True if the family was fully deleted, False if nothing was
+ deleted or some component refused cleanup (e.g. a foreign child
+ in the segments directory) — every removable member is still
+ removed in that case, but the incomplete cleanup is reported.
"""
if not index_path:
return False
@@ -465,45 +468,71 @@ class CascadeHelper:
return False
deleted_any = False
+ cleanup_incomplete = False
- # FAISS index file
- faiss_file = path.with_suffix(".faiss")
- if faiss_file.is_symlink():
- logger.warning(
- f"Refusing to delete symlinked FAISS index file: {faiss_file}"
- )
- elif faiss_file.is_file():
- # nosemgrep: semgrep.rules.path-traversal-risk, reason: The index base passed the resolved root check and this .faiss leaf is not a symlink
- faiss_file.unlink()
- logger.debug(f"Deleted FAISS index file: {faiss_file}")
- deleted_any = True
+ from ....vector_stores.segment_files import (
+ checkpoint_path,
+ delete_segment_files,
+ )
- # Pickle file for metadata (legacy pre-cutover format)
+ checkpoint = checkpoint_path(path.with_suffix(".faiss"))
+ faiss_file = path.with_suffix(".faiss")
pkl_file = path.with_suffix(".pkl")
- if pkl_file.is_symlink():
- logger.warning(
- f"Refusing to delete symlinked FAISS pkl file: {pkl_file}"
- )
- elif pkl_file.is_file():
- # nosemgrep: semgrep.rules.path-traversal-risk, reason: The index base passed the resolved root check and this .pkl leaf is not a symlink
- 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_symlink():
- logger.warning(
- f"Refusing to delete symlinked FAISS idmap sidecar: {idmap_file}"
- )
- elif idmap_file.is_file():
- # nosemgrep: semgrep.rules.path-traversal-risk, reason: The index base passed the resolved root check and this id-map leaf is not a symlink
- idmap_file.unlink()
- logger.debug(f"Deleted FAISS idmap sidecar: {idmap_file}")
- deleted_any = True
+ for member, label in (
+ (checkpoint, "rollback checkpoint"),
+ (faiss_file, "index file"),
+ (pkl_file, "pkl file"),
+ (idmap_file, "idmap sidecar"),
+ ):
+ try:
+ if member.is_symlink():
+ cleanup_incomplete = True
+ logger.warning(
+ f"Refusing to delete symlinked FAISS {label}: {member}"
+ )
+ elif member.is_file():
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Each fixed-suffix family member derives from the root-checked index base and symlink leaves are refused above
+ member.unlink()
+ logger.debug(f"Deleted FAISS {label}: {member}")
+ deleted_any = True
+ except FileNotFoundError:
+ continue
+ except OSError:
+ cleanup_incomplete = True
+ logger.warning(f"Could not remove FAISS {label}: {member}")
+
+ # Segments go only AFTER the manifest root, never leaving a
+ # manifest pointing at deleted segments (a later write at this
+ # path would refuse it and quarantine the collection). A root
+ # that could not be removed keeps its segments.
+ # Contained per component: one foreign or unexpected child in the
+ # segments directory (e.g. a .DS_Store dropped by a file manager
+ # into a directory docs/library-and-rag.md tells users to back up)
+ # must not abort removal of the rest of the family — especially
+ # the plaintext .pkl above. delete_segment_files still refuses to
+ # delete anything it does not recognize. The refusal is still
+ # REPORTED: the family delete returns False (cleanup incomplete)
+ # even though every removable member is removed.
+ # Fail closed: a root whose state cannot be read (Path.exists()
+ # re-raises EACCES/ENAMETOOLONG on Python < 3.14) keeps its
+ # segments and must not abort the quarantine sweep below.
+ try:
+ root_present = faiss_file.is_symlink() or faiss_file.exists()
+ except (OSError, ValueError):
+ root_present = True
+ if root_present:
+ cleanup_incomplete = True
+ else:
+ try:
+ if delete_segment_files(faiss_file):
+ deleted_any = True
+ except (OSError, ValueError):
+ cleanup_incomplete = True
+ logger.warning(
+ f"Could not fully retire vector segment files for "
+ f"{index_path}"
+ )
# Sweep crash-orphaned temp files (persist writes <name>.*.tmp) and
# quarantined siblings (<name>.corrupt-<ns>) for the whole family,
@@ -523,6 +552,7 @@ class CascadeHelper:
for stray in parent.glob(f"{base.name}.*.tmp"):
try:
if stray.is_symlink():
+ cleanup_incomplete = True
logger.warning(
f"Refusing to remove symlinked stray index file: {stray}"
)
@@ -536,7 +566,15 @@ class CascadeHelper:
except FileNotFoundError:
# Raced a concurrent writer's os.replace() — already gone.
continue
+ except ValueError:
+ # A guard refusal must not abort the family delete,
+ # but it is still reported (the delete returns False).
+ cleanup_incomplete = True
+ logger.warning(
+ f"Could not remove stray index file {stray}"
+ )
except OSError:
+ cleanup_incomplete = True
logger.warning(
f"Could not remove stray index file {stray}"
)
@@ -546,22 +584,43 @@ class CascadeHelper:
for stray in parent.glob(f"{base.name}.corrupt-*"):
try:
if stray.is_symlink():
+ cleanup_incomplete = True
logger.warning(
f"Refusing to remove symlinked stray index file: {stray}"
)
continue
+ if stray.is_dir() and stray.name.endswith(".segments"):
+ delete_segment_files(
+ Path(str(stray).removesuffix(".segments"))
+ )
+ deleted_any = True
+ continue
# nosemgrep: semgrep.rules.path-traversal-risk, reason: Only files from the bounded quarantine glob reach this unlink; symlink leaves are skipped
stray.unlink()
logger.debug(f"Removed quarantined index file: {stray}")
deleted_any = True
except FileNotFoundError:
continue
+ except ValueError:
+ # delete_segment_files refuses foreign/symlinked
+ # children — one stray must not abort the family
+ # delete (the plaintext .pkl removal is not optional),
+ # but the refusal is still reported (the delete
+ # returns False).
+ cleanup_incomplete = True
+ logger.warning(
+ f"Could not remove stray index file {stray}"
+ )
except OSError:
+ cleanup_incomplete = True
logger.warning(
f"Could not remove stray index file {stray}"
)
- return deleted_any
+ # A contained refusal (e.g. a foreign segment child) is reported
+ # as an incomplete delete even though every removable member was
+ # removed.
+ return deleted_any and not cleanup_incomplete
except Exception:
logger.exception(f"Failed to delete FAISS files for: {index_path}")
return False
diff --git a/src/local_deep_research/research_library/services/collection_rebuild.py b/src/local_deep_research/research_library/services/collection_rebuild.py
index adcaac1cc7..f3d61c066a 100644
--- a/src/local_deep_research/research_library/services/collection_rebuild.py
+++ b/src/local_deep_research/research_library/services/collection_rebuild.py
@@ -229,6 +229,9 @@ class CollectionRebuild:
self.vector_index = self.service._get_vector_index(
self.stage_id, self.stage_name
)
+ # Private chunks belong to the original collection's members;
+ # the temporary generation has no DocumentCollection rows.
+ self.vector_index.membership_collection_id = self.collection_id
self.index_id = self.service.rag_index_record.id
with self._session() as session:
try:
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 635f6fe72c..6380442754 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
@@ -71,6 +71,7 @@ from ...web_search_engines.engines.local_embedding_manager import (
from ...security.directory_creation import create_directory
from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifier
from ...security.file_integrity.integrity_manager import NO_INTEGRITY_RECORD
+from ...vector_stores.base import VectorStoreIntegrityError
from ...vector_stores.facade import VectorIndex, ChunkInput, SearchResult
from .collection_rebuild import (
CollectionRebuild,
@@ -922,7 +923,15 @@ class LibraryRAGService:
if not new_sidecar.exists():
# nosemgrep: semgrep.rules.path-traversal-risk, reason: The legacy parent and hash filename are checked above; both fixed-suffix sidecars derive from that path and the service-generated per-user index path
legacy_sidecar.rename(new_sidecar)
- legacy_path.rename(index_path)
+ from ...vector_stores.segment_files import relocate_segments
+
+ moved_segments = relocate_segments(legacy_path, index_path)
+ try:
+ legacy_path.rename(index_path)
+ except OSError:
+ if moved_segments:
+ relocate_segments(index_path, legacy_path)
+ raise
# 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
@@ -1187,6 +1196,19 @@ class LibraryRAGService:
try:
# nosemgrep: semgrep.rules.path-traversal-risk, reason: Callers supply the index path recomputed by _preflight_index_path; quarantine appends only a generated timestamp and collision counter in the same directory
index_path.rename(faiss_target)
+ from ...vector_stores.segment_files import relocate_segments
+
+ try:
+ relocate_segments(index_path, faiss_target)
+ except ValueError:
+ # Same containment as the delete sweep: the relocation guard
+ # (or a poisoned/colliding companion directory) must not abort
+ # the quarantine mid-way — the root is already quarantined and
+ # the plaintext .pkl removal below is not optional.
+ logger.warning(
+ f"Could not relocate vector segments for quarantined "
+ f"index {index_path} to {faiss_target}"
+ )
logger.warning(
f"Quarantined corrupted FAISS index to {faiss_target} "
f"(reason: {reason}). Searches against this collection "
@@ -1290,10 +1312,11 @@ class LibraryRAGService:
return (ns, suffix_n)
def _prune_old_quarantined_files(self, index_path: Path) -> None:
- """Keep only the ``_QUARANTINE_KEEP_RECENT`` most-recent
- ``.corrupt-*`` files for ``index_path`` and its ``.pkl``
- companion. Sweeps the two sides independently — pairs share
- the same ``-<ns>`` suffix so they're ordered identically.
+ """Keep the newest quarantined generations and their segment payloads.
+
+ A root and its companion directory count as one generation. Remove
+ payloads whose roots an older retention sweep already deleted. Legacy
+ ``.pkl`` siblings retain their independent file-based retention.
Ordering uses the embedded ``-<ns>`` from the quarantine
filename, not ``st_mtime``: file systems with 1-2s timestamp
@@ -1305,17 +1328,14 @@ class LibraryRAGService:
"""
parent = index_path.parent
pkl_path = index_path.with_suffix(".pkl")
+ from ...vector_stores.segment_files import delete_segment_files
for base in (index_path, pkl_path):
pattern = f"{base.name}.corrupt-*"
try:
# Sort newest-first by the embedded -<ns>; everything
# past the keep window is stale.
- candidates = sorted(
- parent.glob(pattern),
- key=self._corrupt_sort_key,
- reverse=True,
- )
+ candidates = list(parent.glob(pattern))
except OSError:
logger.warning(
f"Failed to enumerate {pattern} in {parent} for "
@@ -1323,11 +1343,38 @@ class LibraryRAGService:
)
continue
- for stale in candidates[_QUARANTINE_KEEP_RECENT:]:
+ roots = []
+ for candidate in candidates:
try:
+ if candidate.is_symlink():
+ continue
+ if candidate.is_file():
+ roots.append(candidate)
+ elif (
+ base == index_path
+ and candidate.name.endswith(".segments")
+ and candidate.is_dir()
+ ):
+ root = candidate.with_suffix("")
+ if (
+ self._corrupt_sort_key(root) != (-1, -1)
+ and not root.is_symlink()
+ and not root.exists()
+ ):
+ delete_segment_files(root)
+ except (OSError, ValueError):
+ logger.warning(
+ f"Failed to prune quarantined payload {candidate}; continuing"
+ )
+
+ roots.sort(key=self._corrupt_sort_key, reverse=True)
+ for stale in roots[_QUARANTINE_KEEP_RECENT:]:
+ try:
+ if base == index_path:
+ delete_segment_files(stale)
stale.unlink()
logger.info(f"Pruned old quarantined file: {stale}")
- except OSError:
+ except (OSError, ValueError):
logger.warning(
f"Failed to prune quarantined file {stale}; continuing"
)
@@ -1490,10 +1537,19 @@ class LibraryRAGService:
f"Deleting old index and rebuilding."
)
try:
+ from ...vector_stores.segment_files import (
+ delete_segment_files,
+ )
+
+ # Remove the manifest first: if segment cleanup
+ # then refuses a foreign file, only unreferenced
+ # segments remain, never a manifest pointing at
+ # deleted segments.
index_path.unlink()
pkl_path = index_path.with_suffix(".pkl")
if pkl_path.exists():
pkl_path.unlink()
+ delete_segment_files(index_path)
logger.info(
f"Deleted old index files at {index_path}"
)
@@ -1642,6 +1698,8 @@ class LibraryRAGService:
"embedding_model": self.embedding_model,
"embedding_model_type": EmbeddingProvider(self.embedding_provider),
"collection_name": collection_name,
+ "index_key": rag_index.index_hash,
+ "require_document_membership": True,
"dimension": rag_index.embedding_dimension,
"path": index_path,
"lock": lock,
@@ -2085,166 +2143,129 @@ class LibraryRAGService:
def _write_prepared_document(
self, prepared: _PreparedDocument
) -> Dict[str, Any]:
- """Serialize chunk rows, FAISS mutation, status updates, and commit."""
+ """Publish prepared work, recovering confirmed component corruption once."""
+ scope_error = _indexing_scope_error()
+ if scope_error is not None:
+ return scope_error
+ # Recovery resets indexed/status snapshots. Re-read and prepare the
+ # source on retry rather than publishing the now-stale prepared work.
+ return self._run_vector_write(
+ prepared.collection_id,
+ lambda retry: (
+ self._index_document_locked(
+ prepared.document_id, prepared.collection_id, True
+ )
+ if retry
+ else self._write_prepared_document_once(prepared)
+ ),
+ )
+
+ def _write_prepared_document_once(
+ self, prepared: _PreparedDocument
+ ) -> Dict[str, Any]:
+ """Write prepared work while the caller holds the collection lock."""
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
document_id = prepared.document_id
collection_id = prepared.collection_id
chunks = prepared.chunk_inputs
- with self._collection_transaction_lock(collection_id):
- with get_user_db_session(
- self.username, self.db_password
- ) as session:
- # Embedding runs outside the collection lock. A complete
- # rebuild may have published a different configuration while
- # this document was being prepared. Reject that stale work
- # before any write or recovery flag can touch the new index.
- if prepared.source_fingerprint is not None:
- document = session.get(Document, document_id)
- if (
- document is None
- or document_fingerprint(document)
- != prepared.source_fingerprint
- ):
- return {
- "status": "error",
- "error": "Document changed; retry indexing",
- }
- if prepared.collection_configuration is not None:
- collection = session.get(Collection, collection_id)
- if (
- collection is None
- or collection_configuration(collection)
- != prepared.collection_configuration
- or (
- collection.embedding_model is not None
- and not self._matches_collection_configuration(
- collection
- )
- )
- ):
- return {
- "status": "error",
- "error": "Collection configuration changed; retry indexing",
- }
- try:
- # Phase 3 Revalidation Gate: verify collection link, content, and indexed status.
- # The membership check runs unconditionally so legacy
- # prepared objects without a content_hash snapshot still
- # get first-time vs concurrent-unlink handling instead of
- # skipping the gate entirely.
- link = (
- session.query(DocumentCollection)
- .filter_by(
- document_id=document_id,
- collection_id=collection_id,
+ with get_user_db_session(self.username, self.db_password) as session:
+ # Embedding runs outside the collection lock. A complete
+ # rebuild may have published a different configuration while
+ # this document was being prepared. Reject that stale work
+ # before any write or recovery flag can touch the new index.
+ if prepared.source_fingerprint is not None:
+ document = session.get(Document, document_id)
+ if (
+ document is None
+ or document_fingerprint(document)
+ != prepared.source_fingerprint
+ ):
+ return {
+ "status": "error",
+ "error": "Document changed; retry indexing",
+ }
+ if prepared.collection_configuration is not None:
+ collection = session.get(Collection, collection_id)
+ if (
+ collection is None
+ or collection_configuration(collection)
+ != prepared.collection_configuration
+ or (
+ collection.embedding_model is not None
+ and not self._matches_collection_configuration(
+ collection
)
- .first()
)
- if link is None:
- if not getattr(prepared, "had_collection_link", None):
- # Reconciler case (b): research orphans have
- # no membership at prepare. Create it now
- # rather than treating absence as a concurrent
- # unlink. A missing snapshot (None) preserves
- # main's unconditional-create behavior.
- link = ensure_in_collection(
- session, document_id, collection_id
- )
- session.flush()
- else:
- logger.info(
- f"Document {document_id} was removed from collection {collection_id} "
- "during embedding; aborting Phase 3 persist."
- )
- self._flag_document_for_reindex(
- session, document_id, collection_id
- )
- return {
- "status": "skipped",
- "message": "Document removed from collection during embedding",
- }
-
- current_doc = (
- session.query(Document)
- .filter_by(id=document_id)
- .first()
+ ):
+ return {
+ "status": "error",
+ "error": "Collection configuration changed; retry indexing",
+ }
+ try:
+ # Phase 3 Revalidation Gate: verify collection link, content, and indexed status.
+ # The membership check runs unconditionally so legacy
+ # prepared objects without a content_hash snapshot still
+ # get first-time vs concurrent-unlink handling instead of
+ # skipping the gate entirely.
+ link = (
+ session.query(DocumentCollection)
+ .filter_by(
+ document_id=document_id,
+ collection_id=collection_id,
)
- if not current_doc:
+ .first()
+ )
+ if link is None:
+ if not getattr(prepared, "had_collection_link", None):
+ # Reconciler case (b): research orphans have
+ # no membership at prepare. Create it now
+ # rather than treating absence as a concurrent
+ # unlink. A missing snapshot (None) preserves
+ # main's unconditional-create behavior.
+ link = ensure_in_collection(
+ session, document_id, collection_id
+ )
+ session.flush()
+ else:
logger.info(
- f"Document {document_id} was deleted during embedding; "
- "aborting Phase 3 persist."
+ f"Document {document_id} was removed from collection {collection_id} "
+ "during embedding; aborting Phase 3 persist."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
- "status": "error",
- "error": "Document deleted during indexing",
+ "status": "skipped",
+ "message": "Document removed from collection during embedding",
}
- if isinstance(getattr(prepared, "content_hash", None), str):
- current_hash = hashlib.sha256(
- (current_doc.text_content or "").encode("utf-8")
- ).hexdigest()
- if current_hash != prepared.content_hash:
- logger.info(
- f"Document {document_id} content changed during embedding; "
- "aborting persist and flagging for reindex."
- )
- self._flag_document_for_reindex(
- session, document_id, collection_id
- )
- return {
- "status": "stale",
- "message": "Document modified during indexing, flagged for reindex",
- }
-
- current_status_exists = (
- session.query(RagDocumentStatus)
- .filter_by(
- document_id=document_id,
- collection_id=collection_id,
- rag_index_id=self.rag_index_record.id,
- )
- .first()
- is not None
- if self.rag_index_record
- else False
- )
- if (
- isinstance(prepared.initial_indexed, bool)
- and isinstance(link.indexed, bool)
- and link.indexed != prepared.initial_indexed
- ) or (
- isinstance(prepared.status_exists, bool)
- and current_status_exists != prepared.status_exists
- ):
- logger.info(
- f"Document {document_id} indexing status modified during embedding; "
- "aborting persist and flagging for reindex."
- )
- self._flag_document_for_reindex(
- session, document_id, collection_id
- )
- return {
- "status": "stale",
- "message": "Document indexed state changed during indexing, flagged for reindex",
- }
-
- collection_name = f"collection_{collection_id}"
- observed_text = current_doc.text_content
- observed_hash = current_doc.document_hash
- vindex = self._get_vector_index(
- collection_id, collection_name, reset_stale_state=True
+ current_doc = (
+ session.query(Document).filter_by(id=document_id).first()
+ )
+ if not current_doc:
+ logger.info(
+ f"Document {document_id} was deleted during embedding; "
+ "aborting Phase 3 persist."
)
- if (
- _claim_document_snapshot(
- session, document_id, observed_text, observed_hash
+ self._flag_document_for_reindex(
+ session, document_id, collection_id
+ )
+ return {
+ "status": "error",
+ "error": "Document deleted during indexing",
+ }
+
+ if isinstance(getattr(prepared, "content_hash", None), str):
+ current_hash = hashlib.sha256(
+ (current_doc.text_content or "").encode("utf-8")
+ ).hexdigest()
+ if current_hash != prepared.content_hash:
+ logger.info(
+ f"Document {document_id} content changed during embedding; "
+ "aborting persist and flagging for reindex."
)
- == 0
- ):
self._flag_document_for_reindex(
session, document_id, collection_id
)
@@ -2252,17 +2273,8 @@ class LibraryRAGService:
"status": "stale",
"message": "Document modified during indexing, flagged for reindex",
}
- stats = vindex.index_prepared(
- source_type="document",
- source_id=document_id,
- chunks=chunks,
- vectors=prepared.vectors,
- replace=True,
- session=session,
- )
- timestamp = datetime.now(UTC)
- existing = (
+ current_status_exists = (
session.query(RagDocumentStatus)
.filter_by(
document_id=document_id,
@@ -2270,83 +2282,146 @@ class LibraryRAGService:
rag_index_id=self.rag_index_record.id,
)
.first()
+ is not None
+ if self.rag_index_record
+ else False
)
- old_chunks = existing.chunk_count if existing else 0
- session.merge(
- RagDocumentStatus(
- document_id=document_id,
- collection_id=collection_id,
- rag_index_id=self.rag_index_record.id,
- chunk_count=len(chunks),
- indexed_at=timestamp,
- )
- )
- updated_rows = (
- session.query(DocumentCollection)
- .filter_by(
- document_id=document_id,
- collection_id=collection_id,
- )
- .update(
- {
- "indexed": True,
- "chunk_count": len(chunks),
- "last_indexed_at": timestamp,
- }
- )
- )
- if isinstance(updated_rows, int) and updated_rows == 0:
- # An unlink committed between the Phase-3 gate query
- # and these persist writes (the unlink DB phase does
- # not hold the FAISS lock). Rolling back avoids
- # re-creating status/aggregate rows for a non-member
- # and leaves phantom vectors to the unlink's purge.
+ if (
+ isinstance(prepared.initial_indexed, bool)
+ and isinstance(link.indexed, bool)
+ and link.indexed != prepared.initial_indexed
+ ) or (
+ isinstance(prepared.status_exists, bool)
+ and current_status_exists != prepared.status_exists
+ ):
logger.info(
- f"Document {document_id} was removed from collection {collection_id} "
- "during persist; aborting Phase 3 commit."
- )
- safe_rollback(
- session,
- "library_rag_service._write_prepared_document link vanished",
+ f"Document {document_id} indexing status modified during embedding; "
+ "aborting persist and flagging for reindex."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
- "status": "skipped",
- "message": "Document removed from collection during embedding",
+ "status": "stale",
+ "message": "Document indexed state changed during indexing, flagged for reindex",
}
- rag_index = (
- session.query(RAGIndex)
- .filter_by(id=self.rag_index_record.id)
- .first()
+
+ collection_name = f"collection_{collection_id}"
+ observed_text = current_doc.text_content
+ observed_hash = current_doc.document_hash
+ vindex = self._get_vector_index(
+ collection_id, collection_name, reset_stale_state=True
+ )
+ if (
+ _claim_document_snapshot(
+ session, document_id, observed_text, observed_hash
)
- if rag_index:
- rag_index.chunk_count += len(chunks) - old_chunks
- if existing is None:
- rag_index.total_documents += 1
- rag_index.last_updated_at = timestamp
- session.commit()
+ == 0
+ ):
+ self._flag_document_for_reindex(
+ session, document_id, collection_id
+ )
+ return {
+ "status": "stale",
+ "message": "Document modified during indexing, flagged for reindex",
+ }
+ stats = vindex.index_prepared(
+ source_type="document",
+ source_id=document_id,
+ chunks=chunks,
+ vectors=prepared.vectors,
+ replace=True,
+ session=session,
+ )
+
+ timestamp = datetime.now(UTC)
+ existing = (
+ session.query(RagDocumentStatus)
+ .filter_by(
+ document_id=document_id,
+ collection_id=collection_id,
+ rag_index_id=self.rag_index_record.id,
+ )
+ .first()
+ )
+ old_chunks = existing.chunk_count if existing else 0
+ session.merge(
+ RagDocumentStatus(
+ document_id=document_id,
+ collection_id=collection_id,
+ rag_index_id=self.rag_index_record.id,
+ chunk_count=len(chunks),
+ indexed_at=timestamp,
+ )
+ )
+ updated_rows = (
+ session.query(DocumentCollection)
+ .filter_by(
+ document_id=document_id,
+ collection_id=collection_id,
+ )
+ .update(
+ {
+ "indexed": True,
+ "chunk_count": len(chunks),
+ "last_indexed_at": timestamp,
+ }
+ )
+ )
+ if isinstance(updated_rows, int) and updated_rows == 0:
+ # An unlink committed between the Phase-3 gate query
+ # and these persist writes (the unlink DB phase does
+ # not hold the FAISS lock). Rolling back avoids
+ # re-creating status/aggregate rows for a non-member
+ # and leaves phantom vectors to the unlink's purge.
logger.info(
- f"Persisted prepared document {document_id}: "
- f"{stats.added} vectors added"
+ f"Document {document_id} was removed from collection {collection_id} "
+ "during persist; aborting Phase 3 commit."
)
- return {"status": "success", "chunk_count": len(chunks)}
- except Exception as exc:
safe_rollback(
session,
- "library_rag_service._write_prepared_document",
+ "library_rag_service._write_prepared_document link vanished",
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
- logger.exception(
- f"Error writing prepared document {document_id}"
- )
return {
- "status": "error",
- "error": f"Operation failed: {type(exc).__name__}",
+ "status": "skipped",
+ "message": "Document removed from collection during embedding",
}
+ rag_index = (
+ session.query(RAGIndex)
+ .filter_by(id=self.rag_index_record.id)
+ .first()
+ )
+ if rag_index:
+ rag_index.chunk_count += len(chunks) - old_chunks
+ if existing is None:
+ rag_index.total_documents += 1
+ rag_index.last_updated_at = timestamp
+ session.commit()
+ logger.info(
+ f"Persisted prepared document {document_id}: "
+ f"{stats.added} vectors added"
+ )
+ return {"status": "success", "chunk_count": len(chunks)}
+ except Exception as exc:
+ safe_rollback(
+ session,
+ "library_rag_service._write_prepared_document",
+ )
+ if isinstance(exc, VectorStoreIntegrityError):
+ raise
+ self._flag_document_for_reindex(
+ session, document_id, collection_id
+ )
+ logger.exception(
+ f"Error writing prepared document {document_id}"
+ )
+ return {
+ "status": "error",
+ "error": f"Operation failed: {type(exc).__name__}",
+ }
def index_document(
self, document_id: str, collection_id: str, force_reindex: bool = False
@@ -2356,10 +2431,74 @@ class LibraryRAGService:
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
+ return self._run_vector_write(
+ collection_id,
+ lambda retry: self._index_document_locked(
+ document_id, collection_id, force_reindex or retry
+ ),
+ )
+
+ def _run_vector_write(
+ self,
+ collection_id: str,
+ operation: Callable[[bool], Dict[str, Any]],
+ ) -> Dict[str, Any]:
+ """Retry a write after its failed transaction has completely unwound.
+
+ Component checks remain lazy: appends never load or deserialise the
+ complete FAISS corpus (only the segments a write touches are opened),
+ while the per-write membership cleanup does hash every segment id
+ file. Only confirmed checksum/membership failures reach recovery;
+ ordinary I/O and embedding errors retain their existing behavior.
+ The collection lock covers rollback, quarantine and the fresh retry.
+ """
with self._collection_transaction_lock(collection_id):
- return self._index_document_locked(
- document_id, collection_id, force_reindex
- )
+ for retry in (False, True):
+ try:
+ return operation(retry)
+ except VectorStoreIntegrityError:
+ self.rag_index_record = None
+ if retry:
+ return {
+ "status": "error",
+ "error": "Operation failed: VectorStoreIntegrityError",
+ }
+ try:
+ # Rollback expires ORM records and the failed scope may
+ # close its session. Reload instead of dereferencing
+ # self.rag_index_record from that failed transaction.
+ with get_user_db_session(
+ self.username, self.db_password
+ ) as session:
+ rag_index = self._resolve_index_for_config(
+ session, collection_id
+ )
+ if rag_index is None:
+ return {
+ "status": "error",
+ "error": "Operation failed: VectorStoreIntegrityError",
+ }
+ index_path = self._get_index_path(
+ rag_index.index_hash
+ )
+ lock = _get_faiss_write_lock(
+ self.username, str(index_path)
+ )
+ with lock:
+ self._quarantine_corrupt_index(
+ index_path,
+ "vector_segment_integrity_failed",
+ )
+ self._reset_index_state_for_rebuild(
+ collection_id, rag_index
+ )
+ except Exception as exc:
+ logger.exception("Could not recover vector components")
+ return {
+ "status": "error",
+ "error": f"Operation failed: {type(exc).__name__}",
+ }
+ raise AssertionError("Vector write retry did not return")
def _index_one(
self, document_id: str, collection_id: str, force_reindex: bool
@@ -2513,6 +2652,8 @@ class LibraryRAGService:
session,
"library_rag_service.index_document cleared",
)
+ if isinstance(e, VectorStoreIntegrityError):
+ raise
self._flag_document_for_reindex(
session, document_id, collection_id
)
@@ -2664,6 +2805,8 @@ 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")
+ if isinstance(e, VectorStoreIntegrityError):
+ raise
# 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
@@ -2967,6 +3110,8 @@ 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")
+ if isinstance(e, VectorStoreIntegrityError):
+ raise
# 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
@@ -3328,22 +3473,45 @@ class LibraryRAGService:
Returns the number of vectors removed.
"""
+ return self.purge_documents_vectors([document_id], collection_id)
+
+ def purge_documents_vectors(
+ self, document_ids: List[str], collection_id: str
+ ) -> int:
+ """Purge every historical configuration, once per physical index."""
+ if not document_ids:
+ return 0
+ # Verification can recover an interrupted vector checkpoint. Wait for
+ # an active writer's database commit before deciding recovery is needed,
+ # just as single-document deletion and search do.
+ with _hold_collection_lock(
+ self.username, collection_id, purpose="transaction"
+ ):
+ return self._purge_documents_vectors_locked(
+ document_ids, collection_id
+ )
+
+ def _purge_documents_vectors_locked(
+ self, document_ids: List[str], collection_id: str
+ ) -> int:
collection_name = f"collection_{collection_id}"
- index_hash = self._get_index_hash(
- collection_name, self.embedding_model, self.embedding_provider
- )
with get_user_db_session(self.username, self.db_password) as session:
- rag_index = self._find_matching_rag_index(
- session, collection_name, index_hash
+ indices = (
+ session.query(RAGIndex)
+ .filter_by(
+ collection_name=collection_name,
+ )
+ .all()
)
- if rag_index is None:
- # Collection was never indexed with this configuration —
- # no vectors to purge. Deliberately NOT
- # _get_or_create_rag_index: a deletion path must not
- # create index records (or probe the embedding provider).
- return 0
- self.rag_index_record = rag_index
+ return sum(
+ self._purge_index_documents(index, document_ids)
+ for index in indices
+ )
+ def _purge_index_documents(
+ self, rag_index: RAGIndex, document_ids: List[str]
+ ) -> int:
+ collection_name = rag_index.collection_name
# 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
@@ -3367,7 +3535,7 @@ class LibraryRAGService:
# Leave quarantine/rebuild decisions to the indexing paths;
# an unreadable index has nothing purgeable right now.
logger.warning(
- f"Skipping vector purge for document {document_id}: index "
+ "Skipping document vector purge: index "
f"{index_path} fails verification ({reason})"
)
return 0
@@ -3400,9 +3568,13 @@ class LibraryRAGService:
# 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),
+ embedding_model=rag_index.embedding_model,
+ embedding_model_type=EmbeddingProvider(
+ rag_index.embedding_model_type
+ ),
collection_name=collection_name,
+ index_key=rag_index.index_hash,
+ require_document_membership=True,
dimension=rag_index.embedding_dimension,
path=index_path,
lock=lock,
@@ -3420,16 +3592,18 @@ class LibraryRAGService:
else self.normalize_vectors
),
)
- stats = vindex.delete(source_type="document", source_id=document_id)
+ stats = vindex.delete_sources(
+ source_type="document", source_ids=document_ids
+ )
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.
+ # proceed; the next write or reconciliation removes orphan vectors.
logger.warning(
- f"Skipping vector purge for document {document_id}: could "
+ "Skipping document vector purge: could "
f"not load or update index {index_path}"
)
return 0
@@ -4036,7 +4210,7 @@ class LibraryRAGService:
session.query(RAGIndex).filter_by(id=rag_index_id).update(
{RAGIndex.id: rag_index_id}, synchronize_session=False
)
- rows = (
+ chunk_query = (
session.query(
DocumentChunk.id,
DocumentChunk.source_id,
@@ -4058,27 +4232,22 @@ class LibraryRAGService:
.filter(
exists().where(Document.id == DocumentChunk.source_id)
)
- .all()
)
- ids_by_document: Dict[str, Set[int]] = {}
- invalidated_documents: Set[str] = set()
- for chunk_id, source_id, metadata in rows:
- if source_id is not None:
- ids_by_document.setdefault(str(source_id), set()).add(
- int(chunk_id)
- )
- if (metadata or {}).get("_ldr_text_invalidated"):
- invalidated_documents.add(str(source_id))
-
# Refuse-to-shrink guard: a transient empty live_ids while
# chunk rows exist would otherwise mass-clear every indexed
# flag and RagDocumentStatus row, silently killing search
# for every document in the collection. Treat as a
# reconciliation failure; the worker surfaces the skip.
- if not live_ids and ids_by_document:
+ if (
+ not live_ids
+ and chunk_query.filter(
+ *vindex.ownership_filter(include_legacy=True)
+ ).first()
+ is not None
+ ):
logger.warning(
"reconcile_collection_index: live_ids empty but "
- f"{len(ids_by_document)} document(s) have chunk rows; "
+ "document chunk rows exist; "
"refusing to clear indexed flags"
)
return {
@@ -4094,6 +4263,23 @@ class LibraryRAGService:
"orphan_vectors": 0,
}
+ orphan_count = vindex.compact_orphans(session=session)
+ if orphan_count:
+ live_ids = set(vindex.live_ids())
+ # Cleanup adopts legacy rows using actual vector membership.
+ # Only then count this index's chunks: another configuration's
+ # still-NULL rows must not make a healthy document incomplete.
+ rows = chunk_query.filter(*vindex.ownership_filter()).all()
+ ids_by_document: Dict[str, Set[int]] = {}
+ invalidated_documents: Set[str] = set()
+ for chunk_id, source_id, metadata in rows:
+ if source_id is not None:
+ ids_by_document.setdefault(str(source_id), set()).add(
+ int(chunk_id)
+ )
+ if (metadata or {}).get("_ldr_text_invalidated"):
+ invalidated_documents.add(str(source_id))
+ owned_ids = {i for ids in ids_by_document.values() for i in ids}
durable = {
doc_id: chunk_ids
for doc_id, chunk_ids in ids_by_document.items()
@@ -4157,7 +4343,11 @@ class LibraryRAGService:
"indexed_documents": len(durable),
"indexed_chunks": len(durable_ids),
"live_vectors": len(live_ids),
- "orphan_vectors": len(live_ids - durable_ids),
+ "orphan_vectors": len(live_ids - owned_ids),
+ "orphan_vectors_removed": orphan_count,
+ "partial_document_vectors": len(
+ (live_ids & owned_ids) - durable_ids
+ ),
}
def has_indexed_documents(self, collection_id: str) -> bool:
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 e3d4cbd70b..6f72421ee1 100644
--- a/src/local_deep_research/security/file_integrity/integrity_manager.py
+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py
@@ -295,6 +295,17 @@ class FileIntegrityManager:
)
return False, NO_INTEGRITY_RECORD
+ if not nested and file_path.suffix == ".faiss":
+ # Callers must hold the collection transaction lock: run
+ # between a vector apply and its DB commit, this would
+ # restore the checkpoint over the in-flight manifest.
+ from ...vector_stores.segment_files import recover_checkpoint
+
+ if recover_checkpoint(
+ file_path, record.checksum, record.algorithm or "sha256"
+ ):
+ force = True
+
# Check if verification needed
if not force and not self._needs_verification(record, file_path):
logger.debug(
diff --git a/src/local_deep_research/vector_stores/base.py b/src/local_deep_research/vector_stores/base.py
index f331c50d10..7856be288c 100644
--- a/src/local_deep_research/vector_stores/base.py
+++ b/src/local_deep_research/vector_stores/base.py
@@ -58,6 +58,10 @@ IntegrityRecord = Callable[[Path], None]
IntegrityVerify = Callable[[Path], Tuple[bool, Optional[str]]]
+class VectorStoreIntegrityError(ValueError):
+ """An authenticated index references corrupt or missing component data."""
+
+
class WriteLock(Protocol):
"""Minimal lock capability used to guard a vector store's file writes.
@@ -203,6 +207,12 @@ class BaseVectorStore(ABC):
def live_ids(self) -> List[int]:
"""Return every id currently stored (the authoritative membership)."""
+ def iter_id_batches(self):
+ """Stream membership for cleanup without retaining a corpus-sized list."""
+ ids = self.live_ids()
+ for start in range(0, len(ids), 500):
+ yield ids[start : start + 500]
+
@abstractmethod
def count(self) -> int:
"""Return the number of vectors currently stored."""
diff --git a/src/local_deep_research/vector_stores/config.py b/src/local_deep_research/vector_stores/config.py
index d2930d29dc..027a4c2f0b 100644
--- a/src/local_deep_research/vector_stores/config.py
+++ b/src/local_deep_research/vector_stores/config.py
@@ -37,9 +37,11 @@ _PROVIDER_CLASSES: Dict[str, Type[BaseVectorStore]] = {}
def _load_provider_classes() -> Dict[str, Type[BaseVectorStore]]:
if not _PROVIDER_CLASSES:
- from .implementations.faiss_store import FaissVectorStore
+ from .implementations.segmented_faiss import SegmentedFaissStore
- _PROVIDER_CLASSES[FaissVectorStore.provider_key] = FaissVectorStore
+ _PROVIDER_CLASSES[SegmentedFaissStore.provider_key] = (
+ SegmentedFaissStore
+ )
return _PROVIDER_CLASSES
diff --git a/src/local_deep_research/vector_stores/facade.py b/src/local_deep_research/vector_stores/facade.py
index 340c46f919..3941ab1942 100644
--- a/src/local_deep_research/vector_stores/facade.py
+++ b/src/local_deep_research/vector_stores/facade.py
@@ -37,15 +37,65 @@ from typing import (
import numpy as np
from langchain_core.embeddings import Embeddings
from loguru import logger
-from sqlalchemy import select
+from sqlalchemy import event, exists, or_, select
from sqlalchemy.orm import Session
-from ..database.models.library import DocumentChunk
+from ..database.models.library import (
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+)
from ..database.session_context import get_user_db_session
-from .base import IntegrityRecord, IntegrityVerify, WriteLock
+from .base import (
+ IntegrityRecord,
+ IntegrityVerify,
+ VectorStoreIntegrityError,
+ WriteLock,
+)
from .config import get_vector_store_class
+def _settle_vectors(session: Session, committed: bool):
+ if session.in_nested_transaction():
+ return
+ pending = session.info.pop("ldr_vector_transactions", {})
+ for store in pending.values():
+ try:
+ store.end_transaction(committed=committed)
+ except VectorStoreIntegrityError:
+ # A settle failure of this class means the published vector
+ # generation failed validation — surface it instead of letting it
+ # vanish behind a log line while the caller reports success.
+ raise
+ except (OSError, ValueError):
+ # The rollback checkpoint is unlinked only AFTER the replacement
+ # generation validates, so a failed settle leaves the pre-image in
+ # place. On the rollback path the DB still records the pre-image
+ # checksum, so the checksum-gated restore (verify_file ->
+ # recover_checkpoint) can still recover it. After a commit the DB
+ # already records the NEW checksum: the stale checkpoint no longer
+ # matches and is never restored (the next begin unlinks it), so
+ # loads rely on the new root verifying. Either way, any
+ # checkpoint that does not match the committed checksum is
+ # refused, and a symlinked checkpoint is rejected (by
+ # SegmentedFaissStore._end_transaction_locked and by
+ # recover_checkpoint).
+ logger.exception("Could not finish vector generation cleanup")
+
+
+def _commit_vectors(session: Session):
+ _settle_vectors(session, True)
+
+
+def _rollback_vectors(session: Session):
+ _settle_vectors(session, False)
+
+
+def _close_vectors(session: Session, transaction):
+ if transaction.parent is None:
+ _settle_vectors(session, False)
+
+
class _BindKwargs(TypedDict):
"""Keyword arguments forwarded to ``store_cls.create()``/``.load()``.
@@ -137,6 +187,8 @@ class VectorIndex:
metric: str = "cosine",
normalize: bool = True,
provider: str = "faiss",
+ index_key: Optional[str] = None,
+ require_document_membership: bool = False,
) -> None:
self.username = username
self.db_password = db_password # gitleaks:allow
@@ -144,6 +196,15 @@ class VectorIndex:
self.embedding_model = embedding_model
self.embedding_model_type = embedding_model_type
self.collection_name = collection_name
+ self._path = Path(path)
+ self.index_key = (
+ index_key
+ or hashlib.sha256(str(Path(path).resolve()).encode()).hexdigest()
+ )
+ self.require_document_membership = require_document_membership
+ self.membership_collection_id = collection_name.removeprefix(
+ "collection_"
+ )
# 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.
@@ -191,6 +252,101 @@ class VectorIndex:
with get_user_db_session(self.username, self.db_password) as s:
yield s, True
+ def ownership_filter(self, *, include_legacy: bool = False):
+ """Encrypted chunk ownership must match the physical index."""
+ owner = DocumentChunk.vector_index_key == self.index_key
+ if include_legacy:
+ owner = or_(owner, DocumentChunk.vector_index_key.is_(None))
+ return (
+ DocumentChunk.collection_name == self.collection_name,
+ DocumentChunk.embedding_model == self.embedding_model,
+ DocumentChunk.embedding_model_type == self.embedding_model_type,
+ owner,
+ )
+
+ def _apply(self, session: Session, **kwargs):
+ """Settle vector checkpoints with the caller's outer DB transaction."""
+ from .implementations.segmented_faiss import SegmentedFaissStore
+
+ if isinstance(self._store, SegmentedFaissStore):
+ if session.in_nested_transaction():
+ raise RuntimeError(
+ "Vector writes require an outer database transaction"
+ )
+ pending = session.info.setdefault("ldr_vector_transactions", {})
+ key = str(self._path.resolve())
+ self._store.begin_transaction(first=key not in pending)
+ pending[key] = self._store
+ if not session.info.get("ldr_vector_transaction_listeners"):
+ event.listen(session, "after_commit", _commit_vectors)
+ event.listen(session, "after_rollback", _rollback_vectors)
+ event.listen(session, "after_transaction_end", _close_vectors)
+ session.info["ldr_vector_transaction_listeners"] = True
+ return self._store.apply(**kwargs)
+
+ def _membership_filter(self):
+ if not self.require_document_membership:
+ return True
+ return or_(
+ DocumentChunk.source_type != "document",
+ exists().where(
+ Document.id == DocumentChunk.source_id,
+ DocumentCollection.document_id == Document.id,
+ DocumentCollection.collection_id
+ == self.membership_collection_id,
+ ),
+ )
+
+ def _prepare_cleanup(self, session: Session) -> tuple[list[int], list[int]]:
+ """Discover real orphans before allocating IDs that a rollback reused.
+
+ Partial documents remain owned: completeness is a status concern, not
+ a garbage-collection criterion. Legacy ownership is recovered only
+ from membership in this physical index. Queries use bounded IN lists.
+ """
+ orphan_vectors: list[int] = []
+ orphan_rows: list[int] = []
+ for ids in self._store.iter_id_batches():
+ session.query(DocumentChunk).filter(
+ DocumentChunk.id.in_(ids),
+ *self.ownership_filter(include_legacy=True),
+ DocumentChunk.vector_index_key.is_(None),
+ ).update(
+ {DocumentChunk.vector_index_key: self.index_key},
+ synchronize_session="fetch",
+ )
+ owned = set(
+ session.scalars(
+ select(DocumentChunk.id).where(
+ DocumentChunk.id.in_(ids),
+ *self.ownership_filter(),
+ )
+ )
+ )
+ valid = set(
+ session.scalars(
+ select(DocumentChunk.id).where(
+ DocumentChunk.id.in_(ids),
+ *self.ownership_filter(),
+ self._membership_filter(),
+ )
+ )
+ )
+ orphan_vectors.extend(set(ids) - valid)
+ orphan_rows.extend(owned - valid)
+ return orphan_vectors, orphan_rows
+
+ def compact_orphans(self, session: Optional[Session] = None) -> int:
+ """Remove only unowned vectors; retain every valid partial document."""
+ with self._db(session) as (sess, owns):
+ vectors, rows = self._prepare_cleanup(sess)
+ if vectors:
+ self._apply(
+ sess, add_ids=[], add_vectors=None, remove_ids=vectors
+ )
+ self._finalize_db(sess, owns, rows, "compact orphan vectors")
+ return len(vectors)
+
def index_prepared(
self,
*,
@@ -220,6 +376,7 @@ class VectorIndex:
sid = str(source_id) if source_id is not None else None
with self._db(session) as (sess, owns):
+ orphan_vectors, orphan_rows = self._prepare_cleanup(sess)
prior_ids: List[int] = []
if replace and sid is not None:
prior_ids = list(
@@ -230,6 +387,7 @@ class VectorIndex:
collection_name=self.collection_name,
embedding_model=self.embedding_model,
embedding_model_type=self.embedding_model_type,
+ vector_index_key=self.index_key,
)
)
)
@@ -240,17 +398,21 @@ class VectorIndex:
sess.flush()
new_ids = [row.id for row in rows]
try:
- stats = self._store.apply(
+ stats = self._apply(
+ sess,
add_ids=new_ids,
add_vectors=vectors,
- remove_ids=prior_ids,
+ remove_ids=prior_ids + orphan_vectors,
)
except Exception:
if owns:
sess.rollback()
raise
self._finalize_db(
- sess, owns, prior_ids, f"index prepared {source_type}/{sid}"
+ sess,
+ owns,
+ prior_ids + orphan_rows,
+ f"index prepared {source_type}/{sid}",
)
return IndexStats(
@@ -279,10 +441,11 @@ class VectorIndex:
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.
+ Segmented FAISS retains a checkpoint until the database transaction
+ commits; a rollback restores the prior generation. The next write or
+ explicit reconciliation also removes legacy orphan vectors before
+ allocating replacement IDs. When ``session`` is passed the caller
+ owns the transaction boundary.
``replace=True`` removes this source's PRIOR chunks/vectors first;
``False`` appends.
@@ -305,6 +468,7 @@ class VectorIndex:
sid = str(source_id) if source_id is not None else None
with self._db(session) as (sess, owns):
+ orphan_vectors, orphan_rows = self._prepare_cleanup(sess)
prior_ids: List[int] = []
if replace and sid is not None:
# Scope the prior-chunk lookup to THIS store's embedding-model
@@ -327,6 +491,7 @@ class VectorIndex:
collection_name=self.collection_name,
embedding_model=self.embedding_model,
embedding_model_type=self.embedding_model_type,
+ vector_index_key=self.index_key,
)
)
)
@@ -338,10 +503,11 @@ class VectorIndex:
new_ids = [row.id for row in rows]
try:
- stats = self._store.apply(
+ stats = self._apply(
+ sess,
add_ids=new_ids,
add_vectors=vectors,
- remove_ids=prior_ids,
+ remove_ids=prior_ids + orphan_vectors,
)
except Exception:
# apply() failed without a durable change (fail-closed reload /
@@ -353,7 +519,10 @@ class VectorIndex:
# 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}"
+ sess,
+ owns,
+ prior_ids + orphan_rows,
+ f"index {source_type}/{sid}",
)
return IndexStats(
@@ -362,8 +531,8 @@ class VectorIndex:
removed=stats["removed"],
)
- @staticmethod
def _finalize_db(
+ self,
session: Session,
owns: bool,
delete_ids: List[int],
@@ -371,11 +540,10 @@ class VectorIndex:
) -> 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.
+ Covers the whole post-apply DB window in one place. If the row delete
+ or commit fails, roll back when we own the session, restoring the
+ segmented-store checkpoint. Other providers' unowned vectors are
+ removed by the next write or reconciliation.
``synchronize_session="fetch"`` keeps the reused thread-local session's
identity map from serving stale, already-deleted objects. Returns the
number of rows deleted.
@@ -383,17 +551,23 @@ class VectorIndex:
deleted = 0
try:
if delete_ids:
- deleted = (
- session.query(DocumentChunk)
- .filter(DocumentChunk.id.in_(delete_ids))
- .delete(synchronize_session="fetch")
- )
+ for start in range(0, len(delete_ids), 500):
+ deleted += (
+ session.query(DocumentChunk)
+ .filter(
+ DocumentChunk.id.in_(
+ delete_ids[start : start + 500]
+ ),
+ *self.ownership_filter(include_legacy=True),
+ )
+ .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"
+ f"{what}: database update failed after vector persistence; "
+ "the owning transaction must roll back"
)
if owns:
session.rollback()
@@ -421,6 +595,7 @@ class VectorIndex:
embedding_model=self.embedding_model,
embedding_model_type=self.embedding_model_type,
embedding_dimension=self._store.dimension,
+ vector_index_key=self.index_key,
document_title=meta.get("document_title") or meta.get("title"),
document_metadata=meta or None,
)
@@ -444,11 +619,10 @@ class VectorIndex:
query_vec = np.asarray(
self.embeddings.embed_query(query), dtype="float32"
)
- hits = self._store.search(query_vec, top_k) # [(chunk_id, distance)]
+ requested = top_k
+ hits = self._store.search(query_vec, requested)
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
@@ -457,16 +631,51 @@ class VectorIndex:
# 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 = {
- row.id: row
- for row in sess.query(DocumentChunk).filter(
- DocumentChunk.id.in_(ids),
- DocumentChunk.collection_name == self.collection_name,
+ while True:
+ selected_hits = []
+ for start in range(0, len(hits), 500):
+ batch = hits[start : start + 500]
+ eligible = set(
+ sess.scalars(
+ select(DocumentChunk.id).where(
+ DocumentChunk.id.in_([cid for cid, _ in batch]),
+ *self.ownership_filter(include_legacy=True),
+ self._membership_filter(),
+ )
+ )
+ )
+ for hit in batch:
+ if hit[0] in eligible:
+ selected_hits.append(hit)
+ if len(selected_hits) == top_k:
+ break
+ if len(selected_hits) == top_k:
+ break
+ if len(selected_hits) >= top_k or len(hits) < requested:
+ break
+ count = self._store.count()
+ if requested >= count:
+ break
+ requested = min(count, requested * 2)
+ hits = self._store.search(query_vec, requested)
+
+ # Materialize full records only after selecting their ranked IDs.
+ ids = [cid for cid, _ in selected_hits]
+ rows = {}
+ for start in range(0, len(ids), 500):
+ rows.update(
+ {
+ row.id: row
+ for row in sess.query(DocumentChunk).filter(
+ DocumentChunk.id.in_(ids[start : start + 500]),
+ *self.ownership_filter(include_legacy=True),
+ self._membership_filter(),
+ )
+ }
)
- }
results: List[SearchResult] = []
- for chunk_id, distance in hits:
+ for chunk_id, distance in selected_hits:
row = rows.get(chunk_id)
if row is None:
logger.debug(
@@ -490,7 +699,7 @@ class VectorIndex:
source_type=cast(Optional[str], row.source_type),
)
)
- return results
+ return results[:top_k]
# ------------------------------------------------------------------ #
# delete
@@ -513,35 +722,56 @@ class VectorIndex:
deleted those rows elsewhere, this finds nothing to do; use
:meth:`delete_ids` instead with the ids captured before deletion.
"""
- sid = str(source_id)
+ return self.delete_sources(
+ source_type=source_type, source_ids=[source_id], session=session
+ )
+
+ def delete_sources(
+ self,
+ *,
+ source_type: str,
+ source_ids: Sequence[str],
+ session: Optional[Session] = None,
+ ) -> DeleteStats:
+ """Purge a batch of sources with one durable operation for this index."""
+ source_ids = list({str(source_id) for source_id in source_ids})
+ if not source_ids:
+ return DeleteStats(removed=0, rows_deleted=0)
with self._db(session) as (sess, owns):
- ids = list(
- sess.scalars(
- select(DocumentChunk.id).filter_by(
- source_type=source_type,
- source_id=sid,
- collection_name=self.collection_name,
+ orphan_vectors, orphan_rows = self._prepare_cleanup(sess)
+ ids: list[int] = []
+ for start in range(0, len(source_ids), 500):
+ ids.extend(
+ sess.scalars(
+ select(DocumentChunk.id).where(
+ DocumentChunk.source_type == source_type,
+ DocumentChunk.source_id.in_(
+ source_ids[start : start + 500]
+ ),
+ *self.ownership_filter(),
+ )
)
)
- )
- if not ids:
+ removed = sorted(set(ids) | set(orphan_vectors))
+ if not removed:
return DeleteStats(removed=0, rows_deleted=0)
-
try:
- stats = self._store.apply(
- add_ids=[], add_vectors=None, remove_ids=ids
+ stats = self._apply(
+ sess,
+ add_ids=[],
+ add_vectors=None,
+ remove_ids=removed,
)
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}"
+ sess,
+ owns,
+ sorted(set(ids) | set(orphan_rows)),
+ "delete sources",
)
-
return DeleteStats(removed=stats["removed"], rows_deleted=rows_deleted)
def delete_ids(
@@ -570,8 +800,8 @@ class VectorIndex:
with self._db(session) as (sess, owns):
try:
- stats = self._store.apply(
- add_ids=[], add_vectors=None, remove_ids=wanted
+ stats = self._apply(
+ sess, add_ids=[], add_vectors=None, remove_ids=wanted
)
except Exception:
if owns:
diff --git a/src/local_deep_research/vector_stores/implementations/faiss_store.py b/src/local_deep_research/vector_stores/implementations/faiss_store.py
index f562fa1ce6..c47f44de17 100644
--- a/src/local_deep_research/vector_stores/implementations/faiss_store.py
+++ b/src/local_deep_research/vector_stores/implementations/faiss_store.py
@@ -994,6 +994,14 @@ class FaissVectorStore(BaseVectorStore):
# (bounded), then give up racing and rebuild fully locked (correct, just
# blocks reads for that attempt).
if stale:
+ # Recursive retries must not retain rejected O(N * dimension)
+ # snapshots and graphs while the next attempt builds another.
+ del new_index, base, keep_vecs, new_vecs
+ if final_ids:
+ del final_vecs
+ del live, keep, final_ids, new_ids, remove_set
+ if add_ids:
+ del seen, rows
if _attempts > 1:
logger.debug(
f"HNSW rebuild snapshot stale (concurrent write); "
diff --git a/src/local_deep_research/vector_stores/implementations/segmented_faiss.py b/src/local_deep_research/vector_stores/implementations/segmented_faiss.py
new file mode 100644
index 0000000000..401f5b782d
--- /dev/null
+++ b/src/local_deep_research/vector_stores/implementations/segmented_faiss.py
@@ -0,0 +1,793 @@
+"""Copy-on-write FAISS segments with a small authenticated root manifest.
+
+Only vectors and integer IDs reach these files. Each operation opens at most
+one bounded FAISS segment at a time. Unchanged segments are reused on writes;
+the manifest is the atomic publication point and is covered by the existing
+encrypted-database integrity record. Segment and ID-file hashes are covered by
+that manifest. Text, titles and document metadata remain in SQLCipher.
+
+Like the existing FAISS store, coordination is per-process. All readers reopen
+the manifest under the injected index lock, so a successful writer can retire
+superseded files without invalidating a reader's snapshot.
+
+Crash safety additionally assumes that every writer of a published
+generation, and every non-nested ``verify_file()`` / ``recover_checkpoint``
+caller, holds the collection transaction lock
+(``_hold_collection_lock(purpose="transaction")``) from apply through the
+owning DB commit, or is the sole, serial writer of a private rebuild stage
+generation (which holds only the ``purpose="rebuild"`` lock). The store does
+not enforce this: a concurrent non-nested verify between apply and commit
+would restore the checkpoint over the in-flight manifest, and a second
+writer's ``begin_transaction`` would clobber the first writer's checkpoint.
+File deleters (``CascadeHelper.delete_faiss_index_files``) run only after the
+owning rows are committed away: rebuild publication retires old paths under
+the transaction lock, stage cleanup under the rebuild lock, while
+``CollectionDeletionService`` deletes hold no collection lock.
+"""
+
+from __future__ import annotations
+
+from contextlib import contextmanager, nullcontext
+import hashlib
+import json
+import os
+from pathlib import Path
+import re
+import shutil
+import tempfile
+import uuid
+
+import faiss
+import numpy as np
+from loguru import logger
+
+from ...security.directory_creation import create_directory
+from ..base import (
+ BaseVectorStore,
+ IntegrityRecord,
+ IntegrityVerify,
+ VectorStoreIntegrityError,
+ WriteLock,
+)
+from ..segment_files import (
+ GENERATED_SEGMENT_NAME,
+ checkpoint_path,
+ segment_directory,
+)
+from .faiss_store import FaissVectorStore
+
+MAGIC = b"LDR-FAISS-SEGMENTS-1\n"
+SEGMENT_VECTORS = 4096
+_NAME = re.compile(r"[0-9a-f]{32}\.faiss\Z")
+_HASH = re.compile(r"[0-9a-f]{64}\Z")
+_MAX_MANIFEST_BYTES = 16 * 1024 * 1024
+
+
+def is_segmented(path: Path) -> bool:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Internal rekey probe reads a fixed magic header from the authenticated user's application-generated RAGIndex path; no request filename is accepted
+ with Path(path).open("rb") as stream:
+ return stream.read(len(MAGIC)) == MAGIC
+
+
+def _digest(path: Path) -> str:
+ with path.open("rb") as stream:
+ return hashlib.file_digest(stream, "sha256").hexdigest()
+
+
+def _validate_entries(entries) -> None:
+ """Reject any generation that later reads would refuse.
+
+ This is the exact contract ``_state`` enforces per entry: unique segment
+ names, well-formed checksums, and ``0 < count <= SEGMENT_VECTORS`` with
+ ``0 <= min_id <= max_id <= int64max``. Both the manifest reader and the
+ publisher run it, so an unloadable generation can never be published (or
+ authenticated) as a success.
+ """
+ seen = set()
+ for entry in entries:
+ if not isinstance(entry, dict):
+ raise ValueError("Invalid vector segment entry")
+ name = entry.get("file")
+ if (
+ not isinstance(name, str)
+ or not _NAME.fullmatch(name)
+ or name in seen
+ ):
+ raise ValueError("Invalid or duplicate vector segment name")
+ seen.add(name)
+ if not all(
+ isinstance(entry.get(key), str) and _HASH.fullmatch(entry[key])
+ for key in ("sha256", "ids_sha256")
+ ):
+ raise ValueError("Invalid vector segment checksum")
+ if (
+ not all(
+ type(entry.get(key)) is int
+ for key in ("count", "min_id", "max_id")
+ )
+ or not 0 < entry["count"] <= SEGMENT_VECTORS
+ or not 0
+ <= entry["min_id"]
+ <= entry["max_id"]
+ <= np.iinfo(np.int64).max
+ ):
+ raise ValueError("Invalid vector segment bounds")
+
+
+def _sync_directory(path: Path) -> None:
+ try:
+ descriptor = os.open(path, os.O_RDONLY)
+ try:
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ except OSError:
+ pass # Unsupported on some platforms, as in the monolithic store.
+
+
+def _atomic_write(path: Path, data: bytes) -> None:
+ descriptor, temporary = (
+ tempfile.mkstemp( # Safe: vector IDs and manifest only, no document content
+ dir=path.parent, prefix=path.name + ".", suffix=".tmp"
+ )
+ )
+ try:
+ with os.fdopen(
+ descriptor, "wb"
+ ) as stream: # Safe: vector IDs and manifest only
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Source is the exact mkstemp result; destination is an internal manifest or checkpoint or generated UUID ID leaf in the store directory
+ os.replace(temporary, path)
+ _sync_directory(path.parent)
+ finally:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Deletes only the exact private mkstemp result created above; no request-supplied path is used
+ Path(temporary).unlink(missing_ok=True)
+
+
+class SegmentedFaissStore(BaseVectorStore):
+ """FAISS implementation used by the facade; accepts legacy .faiss files."""
+
+ provider_key = "faiss"
+ provider_name = "FAISS"
+ supports_reconstruct = True
+ index_type: str
+ metric: str
+ normalize: bool
+ _path: Path
+ _lock: WriteLock | None
+ _record: IntegrityRecord | None
+ _verify: IntegrityVerify | None
+
+ @classmethod
+ def create(
+ cls,
+ *,
+ dimension,
+ index_type,
+ metric,
+ normalize,
+ path=None,
+ lock=None,
+ integrity_record=None,
+ integrity_verify=None,
+ ):
+ if path is None:
+ raise ValueError("Segmented FAISS requires a persistence path")
+ store = cls()
+ store.dimension = dimension
+ store.index_type = (index_type or "flat").strip().lower()
+ store.metric = (metric or "cosine").strip().lower()
+ store.normalize = normalize
+ store._path = Path(path)
+ store._lock = lock
+ store._record = integrity_record
+ store._verify = integrity_verify
+ store._defer_retirement = False
+ # Validate construction before creating any files.
+ store._empty()
+ return store
+
+ @classmethod
+ def load(cls, path, **kwargs):
+ if not Path(path).is_file():
+ raise RuntimeError("Vector index file is missing")
+ store = cls.create(path=path, **kwargs)
+ with store._guard():
+ state = store._state()
+ if state is None:
+ # Map the legacy payload read-only, never a mutable heap copy.
+ # This also validates its physical type and dimension.
+ store._legacy()
+ return store
+
+ def _guard(self):
+ return self._lock if self._lock is not None else nullcontext()
+
+ def _empty(self):
+ return FaissVectorStore.create(
+ dimension=self.dimension,
+ index_type=self.index_type,
+ metric=self.metric,
+ normalize=self.normalize,
+ )
+
+ def _state(self, *, verify=True):
+ if not self._path.exists():
+ return []
+ if verify and self._verify is not None:
+ verified, reason = self._verify(self._path)
+ if not verified:
+ raise RuntimeError(
+ f"Vector index integrity verification failed: {reason}"
+ )
+ with self._path.open("rb") as stream:
+ if stream.read(len(MAGIC)) != MAGIC:
+ return None
+ encoded = stream.read(_MAX_MANIFEST_BYTES + 1)
+ if len(encoded) > _MAX_MANIFEST_BYTES:
+ raise ValueError("Vector index manifest exceeds its metadata limit")
+ state = json.loads(encoded)
+ if not isinstance(state, dict):
+ raise ValueError("Invalid vector index manifest")
+ expected = (
+ self.dimension,
+ self.index_type,
+ self.metric,
+ self.normalize,
+ )
+ actual = tuple(
+ state.get(key)
+ for key in ("dimension", "index_type", "metric", "normalize")
+ )
+ if actual != expected:
+ raise ValueError(
+ "Vector index configuration does not match its manifest"
+ )
+ entries = state.get("segments")
+ if not isinstance(entries, list):
+ raise ValueError("Invalid vector segment list")
+ _validate_entries(entries)
+ return entries
+
+ def begin_transaction(self, *, first=True):
+ """Retain the prior root and its segments until the owning DB settles."""
+ with self._guard():
+ self._begin_transaction_locked(first=first)
+
+ def _begin_transaction_locked(self, *, first):
+ if first:
+ create_directory(
+ self._path.parent, context="vector checkpoint", mode=0o700
+ )
+ backup = checkpoint_path(self._path)
+ backup.unlink(missing_ok=True)
+ if self._path.exists():
+ if self._path.is_symlink():
+ raise ValueError("Refusing a symlinked vector index")
+ try:
+ os.link(self._path, backup)
+ except OSError:
+ # The legacy file can be gigabytes: stream a private copy
+ # if the filesystem cannot create a hard link.
+ descriptor, temporary = (
+ tempfile.mkstemp( # Safe: checkpoint of vectors and IDs only
+ dir=self._path.parent,
+ prefix=self._path.name + ".",
+ suffix=".tmp",
+ )
+ )
+ try:
+ with (
+ os.fdopen(
+ descriptor, "wb"
+ ) as target, # Safe: private vector checkpoint
+ self._path.open("rb") as source,
+ ):
+ shutil.copyfileobj( # Safe: copies only vectors and IDs
+ source, target
+ )
+ target.flush()
+ os.fsync(target.fileno())
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Source is the exact mkstemp result in the injected index directory; destination is that index's fixed rollback companion
+ os.replace(temporary, backup)
+ finally:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Deletes only the exact private mkstemp result created for this vector checkpoint copy
+ Path(temporary).unlink(missing_ok=True)
+ else:
+ _atomic_write(backup, b"LDR-EMPTY\n")
+ _sync_directory(self._path.parent)
+ self._defer_retirement = True
+
+ def end_transaction(self, *, committed):
+ with self._guard():
+ self._end_transaction_locked(committed=committed)
+
+ def _end_transaction_locked(self, *, committed):
+ backup = checkpoint_path(self._path)
+ settled = committed
+ if backup.exists():
+ if backup.is_symlink():
+ raise ValueError("Refusing a symlinked vector checkpoint")
+ if committed:
+ # Validate the replacement generation BEFORE the checkpoint —
+ # the only copy of the legacy pre-image — can be destroyed.
+ # A published generation that later reads reject must roll
+ # back to the pre-image and surface, never be reported as a
+ # success with the pre-image already gone.
+ try:
+ self._state(verify=False)
+ except Exception:
+ settled = False
+ if settled:
+ backup.unlink()
+ else:
+ with backup.open("rb") as stream:
+ empty = stream.read(10) == b"LDR-EMPTY\n"
+ if empty:
+ self._path.unlink(missing_ok=True)
+ backup.unlink()
+ else:
+ os.replace(backup, self._path)
+ if committed:
+ # A rejected publish must leave the rollback
+ # checkpoint AND the pre-image bytes intact and
+ # unreplaced: the restore above normally consumed
+ # the checkpoint's name, so re-link the restored
+ # pre-image back onto it. A plain rollback
+ # (committed=False) usually consumes it too, but if
+ # nothing was published since begin the checkpoint
+ # is a hard link to the same inode, os.replace is a
+ # no-op and the name survives until the next begin
+ # unlinks it (its bytes still match the root). Same
+ # link-then-copy fallback as
+ # _begin_transaction_locked.
+ try:
+ os.link(self._path, backup)
+ except OSError:
+ descriptor, temporary = (
+ tempfile.mkstemp( # Safe: checkpoint of vectors and IDs only
+ dir=self._path.parent,
+ prefix=self._path.name + ".",
+ suffix=".tmp",
+ )
+ )
+ try:
+ with (
+ os.fdopen(
+ descriptor, "wb"
+ ) as target, # Safe: private vector checkpoint
+ self._path.open("rb") as source,
+ ):
+ shutil.copyfileobj( # Safe: copies only vectors and IDs
+ source, target
+ )
+ target.flush()
+ os.fsync(target.fileno())
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Source is the exact mkstemp result in the injected index directory; destination is the restored index's fixed rollback companion
+ os.replace(temporary, backup)
+ finally:
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: Deletes the exact private mkstemp result retained through checkpoint-copy cleanup
+ Path(temporary).unlink(missing_ok=True)
+ _sync_directory(self._path.parent)
+ self._defer_retirement = False
+ try:
+ entries = self._state(verify=False)
+ except Exception as exc:
+ raise VectorStoreIntegrityError(
+ "Vector generation failed settle validation"
+ ) from exc
+ retained = {entry["file"] for entry in entries or []}
+ directory = segment_directory(self._path)
+ if directory.is_dir() and not directory.is_symlink():
+ for path in directory.iterdir():
+ if (
+ not path.is_symlink()
+ and path.is_file()
+ and GENERATED_SEGMENT_NAME.fullmatch(path.name)
+ and (
+ path.suffix == ".tmp"
+ or path.name[:32] + ".faiss" not in retained
+ )
+ ):
+ path.unlink(missing_ok=True)
+ if committed and not settled:
+ raise VectorStoreIntegrityError(
+ "The published vector generation failed settle validation; "
+ "the previous generation was restored"
+ )
+
+ def _legacy(self):
+ index = faiss.read_index(
+ str(self._path), faiss.IO_FLAG_MMAP_IFC | faiss.IO_FLAG_READ_ONLY
+ )
+ if (
+ not isinstance(index, faiss.IndexIDMap2)
+ or index.d != self.dimension
+ ):
+ raise ValueError(
+ "Legacy vector index has the wrong type or dimension"
+ )
+ mismatch = FaissVectorStore._physical_config_reason(
+ index, self.index_type, self.metric
+ )
+ if mismatch:
+ raise ValueError(mismatch)
+ return index
+
+ def _file(self, entry, *, ids=False):
+ directory = segment_directory(self._path)
+ if directory.is_symlink():
+ raise ValueError("Refusing a symlinked vector segment directory")
+ path = directory / entry["file"]
+ if ids:
+ path = path.with_suffix(".ids")
+ if path.is_symlink() or not path.is_file():
+ raise VectorStoreIntegrityError(
+ "Missing or symlinked vector segment"
+ )
+ expected = entry["ids_sha256" if ids else "sha256"]
+ if _digest(path) != expected:
+ raise VectorStoreIntegrityError("Vector segment checksum mismatch")
+ return path
+
+ def _ids(self, entry):
+ path = self._file(entry, ids=True)
+ if path.stat().st_size != entry["count"] * 8:
+ raise VectorStoreIntegrityError("Vector segment ID count mismatch")
+ ids = np.frombuffer(path.read_bytes(), dtype="<i8").tolist()
+ if (
+ len(set(ids)) != len(ids)
+ or min(ids) != entry["min_id"]
+ or max(ids) != entry["max_id"]
+ ):
+ raise VectorStoreIntegrityError("Vector segment ID bounds mismatch")
+ return ids
+
+ def _read(self, entry):
+ store = FaissVectorStore.load(
+ self._file(entry),
+ dimension=self.dimension,
+ index_type=self.index_type,
+ metric=self.metric,
+ normalize=self.normalize,
+ )
+ if store.live_ids() != self._ids(entry):
+ raise VectorStoreIntegrityError(
+ "Vector segment membership mismatch"
+ )
+ return store
+
+ def _write(self, store):
+ directory = segment_directory(self._path)
+ if directory.is_symlink():
+ raise ValueError("Refusing a symlinked vector segment directory")
+ create_directory(directory, context="vector segments", mode=0o700)
+ directory.chmod(0o700)
+ path = directory / (uuid.uuid4().hex + ".faiss")
+ ids = store.live_ids()
+ if not 0 < len(ids) <= SEGMENT_VECTORS:
+ raise ValueError("Vector segment exceeds its size bound")
+ # A generated segment must satisfy the contract _ids()/_state()
+ # enforce on every later read — never publish one that reads reject.
+ if (
+ len(set(ids)) != len(ids)
+ or min(ids) < 0
+ or max(ids) > np.iinfo(np.int64).max
+ ):
+ raise ValueError(
+ "Vector segment IDs must be unique nonnegative int64 values"
+ )
+ store.persist(path)
+ ids_path = path.with_suffix(".ids")
+ _atomic_write(ids_path, np.asarray(ids, dtype="<i8").tobytes())
+ return {
+ "file": path.name,
+ "sha256": _digest(path),
+ "ids_sha256": _digest(ids_path),
+ "count": len(ids),
+ "min_id": min(ids),
+ "max_id": max(ids),
+ }
+
+ def _publish(self, entries):
+ # Publish only a generation every later read accepts: this is the
+ # exact validation _state() applies, run BEFORE the manifest is
+ # written and authenticated.
+ _validate_entries(entries)
+ create_directory(
+ self._path.parent, context="vector manifest", mode=0o700
+ )
+ self._path.parent.chmod(0o700)
+ manifest = {
+ "dimension": self.dimension,
+ "index_type": self.index_type,
+ "metric": self.metric,
+ "normalize": self.normalize,
+ "segments": entries,
+ }
+ data = json.dumps(manifest, separators=(",", ":")).encode()
+ if len(data) > _MAX_MANIFEST_BYTES:
+ raise ValueError("Vector index manifest exceeds its metadata limit")
+ _atomic_write(self._path, MAGIC + data)
+ if self._record is not None:
+ for attempt in range(3):
+ try:
+ self._record(self._path)
+ break
+ except Exception:
+ if attempt == 2:
+ raise
+
+ def iter_id_batches(self):
+ with self._guard():
+ entries = self._state()
+ if entries is None:
+ index = self._legacy()
+ ids = faiss.vector_to_array(index.id_map)
+ for start in range(0, len(ids), 500):
+ yield ids[start : start + 500].tolist()
+ else:
+ for entry in entries:
+ ids = self._ids(entry)
+ for start in range(0, len(ids), 500):
+ yield ids[start : start + 500]
+
+ def live_ids(self):
+ return [value for batch in self.iter_id_batches() for value in batch]
+
+ def count(self):
+ with self._guard():
+ entries = self._state()
+ return (
+ int(self._legacy().ntotal)
+ if entries is None
+ else sum(entry["count"] for entry in entries)
+ )
+
+ def reconstruct(self, id):
+ with self._guard():
+ entries = self._state()
+ if entries is None:
+ try:
+ return self._legacy().reconstruct(int(id))
+ except RuntimeError:
+ return None
+ for entry in entries:
+ if entry["min_id"] <= id <= entry["max_id"] and id in self._ids(
+ entry
+ ):
+ return self._read(entry).reconstruct(id)
+ return None
+
+ def search(self, query_vector, k):
+ if k <= 0:
+ return []
+ # Validate shape, dimension and finite values even for an empty store.
+ self._empty().search(query_vector, k)
+ with self._guard():
+ entries = self._state()
+ if entries is None:
+ store = FaissVectorStore(
+ self._legacy(),
+ dimension=self.dimension,
+ index_type=self.index_type,
+ metric=self.metric,
+ normalize=self.normalize,
+ )
+ return store.search(query_vector, k)
+ hits = []
+ for entry in entries:
+ store = self._read(entry)
+ hits.extend(store.search(query_vector, k))
+ del store
+ hits.sort(key=lambda hit: hit[1], reverse=self.metric != "l2")
+ del hits[k:]
+ return hits
+
+ @property
+ def supports_delete(self):
+ return True
+
+ def add(self, ids, vectors):
+ self.apply(add_ids=ids, add_vectors=vectors)
+
+ def delete(self, ids):
+ return self.apply(add_ids=[], add_vectors=None, remove_ids=ids)[
+ "removed"
+ ]
+
+ def persist(self, path):
+ if Path(path) != self._path:
+ raise ValueError(
+ "A segmented index must be persisted at its bound path"
+ )
+ with self._guard():
+ entries = self._state()
+ if entries is not None:
+ self._publish(entries)
+
+ @contextmanager
+ def _mutation(self):
+ with self._guard():
+ previous = self._state()
+ standalone = not self._defer_retirement
+ if standalone:
+ self._begin_transaction_locked(first=True)
+ try:
+ yield previous
+ except Exception:
+ if standalone:
+ self._end_transaction_locked(committed=False)
+ raise
+ else:
+ if standalone:
+ try:
+ self._end_transaction_locked(committed=True)
+ except OSError:
+ logger.warning(
+ "Deferred retirement of superseded vector segments"
+ )
+
+ def apply(self, *, add_ids, add_vectors, remove_ids=(), dedup=True):
+ if self._lock is None or self._record is None or self._verify is None:
+ raise RuntimeError(
+ "Vector writes require lock and integrity callbacks"
+ )
+ # Validate everything before allocating files or changing durable state.
+ validator = self._empty()
+ if add_ids:
+ checked = validator._prepare(add_vectors)
+ if len(add_ids) != len(checked):
+ raise ValueError("Vector count does not match ID count")
+ positions: dict[int, int] = {}
+ for position, value in enumerate(add_ids):
+ value = int(value)
+ if value < 0 or value > np.iinfo(np.int64).max:
+ raise ValueError(
+ "Vector IDs must be nonnegative int64 values"
+ )
+ positions.setdefault(value, position)
+ add_ids = list(positions)
+ checked = checked[list(positions.values())]
+ else:
+ checked = np.empty((0, self.dimension), dtype="float32")
+ removals = set(map(int, remove_ids)) | set(add_ids)
+ removed = 0
+ with self._mutation() as previous:
+ if previous is None:
+ # Legacy conversion. The id map is normalized with the same
+ # discipline as the add path before anything is written, so a
+ # converted generation always satisfies the contract _ids()/
+ # _state() enforce (unique ids, 0 <= id <= int64max, counts
+ # consistent) and can never brick later reads:
+ # * ids outside [0, int64max] are unrepresentable in a
+ # generated segment (pre-fix writer artifacts) and are
+ # skipped with a warning — they are not addressable by the
+ # current add path either;
+ # * duplicate ids (a pre-#4200 stale orphan under a reused
+ # chunk id) keep their FIRST map position only, while the
+ # vector written is the legacy store's own reconstruct(id)
+ # — last-writer-wins, so the NEW vector survives;
+ # * if a non-empty id map can yield nothing keepable and
+ # nothing was explicitly removed, the file cannot be
+ # converted safely: refuse loudly and non-destructively
+ # (the mutation rollback restores the legacy pre-image).
+ # The refusal surfaces as VectorStoreIntegrityError — the
+ # class whose established recovery policy for an
+ # unconvertible legacy input is refuse + quarantine +
+ # reindex (legacy_cleanup.py's treatment of id-collided /
+ # foreign indexes), so healthy data is never silently
+ # committed, destroyed, or force-re-embedded.
+ index = self._legacy()
+ ids = faiss.vector_to_array(index.id_map)
+ legacy_rows = len(ids)
+ entries = []
+ seen: set[int] = set()
+ removed_ids: set[int] = set()
+ kept = 0
+ skipped = 0
+ duplicates = 0
+ for start in range(0, len(ids), SEGMENT_VECTORS):
+ original = [
+ int(value)
+ for value in ids[start : start + SEGMENT_VECTORS]
+ ]
+ keep = []
+ for value in original:
+ if not 0 <= value <= np.iinfo(np.int64).max:
+ skipped += 1
+ continue
+ if value in seen:
+ duplicates += 1
+ continue
+ seen.add(value)
+ if value in removals:
+ removed_ids.add(value)
+ continue
+ keep.append(value)
+ kept += len(keep)
+ if keep:
+ try:
+ vectors = np.asarray(
+ [index.reconstruct(value) for value in keep],
+ dtype="float32",
+ )
+ except RuntimeError as exc:
+ raise VectorStoreIntegrityError(
+ "Legacy vector index row cannot be "
+ "reconstructed; refusing to convert"
+ ) from exc
+ store = self._empty()
+ store._index.add_with_ids(
+ vectors, np.asarray(keep, dtype="int64")
+ )
+ entries.append(self._write(store))
+ del store, vectors
+ del index, ids
+ if skipped or duplicates:
+ logger.warning(
+ f"Legacy vector conversion repaired the id map: "
+ f"dropped {duplicates} duplicate and {skipped} "
+ f"unrepresentable id(s)"
+ )
+ if legacy_rows and not kept and not removed_ids:
+ # A non-empty id map that yields nothing keepable and
+ # nothing explicitly removed cannot be converted safely:
+ # refuse loudly (the mutation rollback keeps the legacy
+ # bytes intact) instead of silently publishing an empty
+ # generation. VectorStoreIntegrityError routes the
+ # established refuse + quarantine + reindex recovery.
+ raise VectorStoreIntegrityError(
+ "Legacy vector index rows cannot be represented as "
+ "generated segments; refusing to convert"
+ )
+ removed = len(removed_ids)
+ else:
+ entries = []
+ for entry in previous:
+ candidates = {
+ value
+ for value in removals
+ if entry["min_id"] <= value <= entry["max_id"]
+ }
+ actual = (
+ candidates.intersection(self._ids(entry))
+ if candidates
+ else set()
+ )
+ if not actual:
+ entries.append(entry)
+ continue
+ removed += len(actual)
+ store = self._read(entry)
+ if store.supports_delete:
+ store.delete(list(actual))
+ else:
+ store._rebuild_dropping(actual)
+ if store.count():
+ entries.append(self._write(store))
+ del store
+ position = 0
+ if add_ids and entries and entries[-1]["count"] < SEGMENT_VECTORS:
+ tail = self._read(entries.pop())
+ position = min(len(add_ids), SEGMENT_VECTORS - tail.count())
+ tail._index.add_with_ids(
+ checked[:position],
+ np.asarray(add_ids[:position], dtype="int64"),
+ )
+ entries.append(self._write(tail))
+ del tail
+ while position < len(add_ids):
+ end = position + SEGMENT_VECTORS
+ store = self._empty()
+ store._index.add_with_ids(
+ checked[position:end],
+ np.asarray(add_ids[position:end], dtype="int64"),
+ )
+ entries.append(self._write(store))
+ del store
+ position = end
+ self._publish(entries)
+ return {"added": len(add_ids), "removed": removed}
diff --git a/src/local_deep_research/vector_stores/legacy_rekey.py b/src/local_deep_research/vector_stores/legacy_rekey.py
index 92baf247a1..bc92c0badf 100644
--- a/src/local_deep_research/vector_stores/legacy_rekey.py
+++ b/src/local_deep_research/vector_stores/legacy_rekey.py
@@ -81,10 +81,23 @@ def _is_idmap2(faiss_path: Path) -> Optional[bool]:
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
+ from faiss import (
+ IndexIDMap2,
+ IO_FLAG_MMAP_IFC,
+ IO_FLAG_READ_ONLY,
+ read_index,
+ )
+
+ from .implementations.segmented_faiss import is_segmented
try:
- index = read_index(str(faiss_path))
+ if is_segmented(faiss_path):
+ return True
+ # Detection must not heap-load a whole legacy corpus before its
+ # bounded, vector-preserving conversion can even begin.
+ index = read_index(
+ str(faiss_path), IO_FLAG_MMAP_IFC | IO_FLAG_READ_ONLY
+ )
except Exception:
return None
return isinstance(index, IndexIDMap2)
diff --git a/src/local_deep_research/vector_stores/segment_files.py b/src/local_deep_research/vector_stores/segment_files.py
new file mode 100644
index 0000000000..b4ee0ba705
--- /dev/null
+++ b/src/local_deep_research/vector_stores/segment_files.py
@@ -0,0 +1,132 @@
+"""Filesystem lifecycle for vector-only segment directories (no FAISS import)."""
+
+from pathlib import Path
+import hashlib
+import os
+import re
+import stat
+
+GENERATED_SEGMENT_NAME = re.compile(
+ r"[0-9a-f]{32}\.(?:faiss|ids)(?:\.[A-Za-z0-9_-]+\.tmp)?\Z"
+)
+
+
+def segment_directory(path: Path) -> Path:
+ return Path(str(path) + ".segments")
+
+
+def checkpoint_path(path: Path) -> Path:
+ return Path(str(path) + ".rollback")
+
+
+def recover_checkpoint(
+ path: Path, checksum: str, algorithm: str = "sha256"
+) -> bool:
+ """Restore only bytes authenticated by the committed encrypted DB record.
+
+ Never adopt the checkpoint's own checksum as a new baseline. A completed
+ commit keeps the new root; an interrupted/rolled-back commit can recover
+ the old one. Call outside an active vector write, under its index lock.
+ """
+ backup = checkpoint_path(path)
+ if not backup.is_file() or backup.is_symlink() or path.is_symlink():
+ return False
+ if path.exists():
+ with path.open("rb") as stream:
+ if hashlib.file_digest(stream, algorithm).hexdigest() == checksum:
+ return False
+ with backup.open("rb") as stream:
+ if hashlib.file_digest(stream, algorithm).hexdigest() != checksum:
+ return False
+ os.replace(backup, path)
+ return True
+
+
+def index_storage_size(path: Path) -> int | None:
+ """Bytes held by an index root plus every regular file beside it.
+
+ A segmented root is only a small manifest, so this adds every regular,
+ non-symlink child of the segment directory (live segments, but also
+ in-flight ``.tmp`` files, not-yet-retired segments and foreign files).
+ Legacy single-file indexes have no segment directory. Readers hold no
+ lock, so children (or the root) vanishing mid-scan are skipped rather
+ than raised; returns None when the root itself is gone or unreadable.
+ """
+ try:
+ size = path.stat().st_size
+ except (OSError, ValueError):
+ # Gone, or a corrupted path (ENOTDIR, ELOOP, ENAMETOOLONG, NUL).
+ return None
+ directory = segment_directory(path)
+ if directory.is_symlink():
+ return size
+ try:
+ with os.scandir(directory) as entries:
+ for entry in entries:
+ try:
+ info = entry.stat(follow_symlinks=False)
+ except FileNotFoundError:
+ continue
+ if stat.S_ISREG(info.st_mode):
+ size += info.st_size
+ except OSError:
+ # Missing, not a directory, or unreadable: report the root alone.
+ pass
+ return size
+
+
+def delete_segment_files(path: Path) -> bool:
+ """Retire generated files only; callers must validate the index root.
+
+ Refuse foreign, symlinked or unexpected children and report unavailable
+ components after attempting every removable generated sibling.
+ """
+ directory = segment_directory(path)
+ if not directory.exists():
+ return False
+ if directory.is_symlink() or not directory.is_dir():
+ raise ValueError(
+ "Refusing a symlinked or invalid vector segment directory"
+ )
+ refused = False
+ cleanup_error: OSError | None = None
+ for child in directory.iterdir():
+ try:
+ # lstat: a symlink is never a regular file. A child that a
+ # concurrent settle just retired is neither foreign nor an error.
+ info = child.lstat()
+ if not stat.S_ISREG(
+ info.st_mode
+ ) or not GENERATED_SEGMENT_NAME.fullmatch(child.name):
+ refused = True
+ continue
+ child.unlink()
+ except FileNotFoundError:
+ continue
+ except OSError as exc:
+ if cleanup_error is None:
+ cleanup_error = exc
+ if cleanup_error is not None:
+ raise cleanup_error
+ if refused:
+ raise ValueError("Refusing an unexpected vector segment file")
+ # A file a concurrent writer added mid-walk makes this raise ENOTEMPTY,
+ # which callers already report as incomplete cleanup.
+ directory.rmdir()
+ return True
+
+
+def relocate_segments(source: Path, destination: Path) -> bool:
+ """Move the companion directory with a relocated or quarantined root."""
+ source_dir = segment_directory(source)
+ if not source_dir.exists():
+ return False
+ if source_dir.is_symlink() or not source_dir.is_dir():
+ raise ValueError(
+ "Refusing a symlinked or invalid vector segment directory"
+ )
+ destination_dir = segment_directory(destination)
+ if destination_dir.exists() or destination_dir.is_symlink():
+ raise ValueError("Vector segment relocation destination already exists")
+ source_dir.rename(destination_dir)
+ return True
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 1da56c3590..a30fed22d0 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -3208,9 +3208,12 @@ def get_collection_documents(
if rag_index and rag_index.index_path:
from pathlib import Path
- index_path = Path(rag_index.index_path)
- if index_path.exists():
- size_bytes = index_path.stat().st_size
+ from ...vector_stores.segment_files import index_storage_size
+
+ # The helper tolerates files vanishing under a concurrent
+ # writer and returns None if the root itself is gone.
+ size_bytes = index_storage_size(Path(rag_index.index_path))
+ if size_bytes is not None:
index_file_size_bytes = size_bytes
# Format as human-readable
if size_bytes < 1024:
@@ -4154,6 +4157,8 @@ def _client_indexing_result(result: Any) -> Optional[dict]:
"durable_indexed_chunks",
"live_vectors",
"orphan_vectors",
+ "orphan_vectors_removed",
+ "partial_document_vectors",
):
value = result.get(key)
if type(value) is int and value >= 0:
@@ -4454,6 +4459,12 @@ def _background_index_worker(
"durable_indexed_chunks": durable_chunks,
"live_vectors": reconciliation["live_vectors"],
"orphan_vectors": reconciliation["orphan_vectors"],
+ "orphan_vectors_removed": reconciliation.get(
+ "orphan_vectors_removed", 0
+ ),
+ "partial_document_vectors": reconciliation.get(
+ "partial_document_vectors", 0
+ ),
"errors": _sanitized_indexing_errors(results),
}
has_failures = results["failed"] > 0
diff --git a/tests/chat/test_chat_attempt_delete_retry.py b/tests/chat/test_chat_attempt_delete_retry.py
index 04cbdb1f02..bee93afa35 100644
--- a/tests/chat/test_chat_attempt_delete_retry.py
+++ b/tests/chat/test_chat_attempt_delete_retry.py
@@ -364,7 +364,9 @@ class TestDeleteAttemptService:
def __exit__(self, *_args):
return False
- def purge_document_vectors(self, doc_id, coll_id):
+ def purge_documents_vectors(self, doc_ids, coll_id):
+ assert doc_ids == [document_id]
+ doc_id = doc_ids[0]
with SessionLocal() as db:
assert db.query(Document).filter_by(id=doc_id).count() == 0
assert (
@@ -373,10 +375,7 @@ class TestDeleteAttemptService:
.count()
== 1
)
- events.append(("vectors", doc_id, coll_id))
-
- def purge_document_chunks(self, doc_id, coll_id):
- events.append(("chunks", doc_id, coll_id))
+ events.append(("vectors", doc_ids, coll_id))
@contextmanager
def _document_db(*_args, **_kwargs):
@@ -406,10 +405,9 @@ class TestDeleteAttemptService:
db.query(DocumentChunk).filter_by(source_id=document_id).count()
== 0
)
- assert events == [
- ("vectors", document_id, collection_id),
- ("chunks", document_id, collection_id),
- ]
+ # The vector callback observed the committed document deletion with
+ # its chunk still present. The real DB backstop then removed the chunk.
+ assert events == [("vectors", [document_id], collection_id)]
def test_delete_attempt_failed_no_assistant_removes_user_msg(
self, setup_database_for_all_tests
diff --git a/tests/ci/test_rag_scale_release_gate.py b/tests/ci/test_rag_scale_release_gate.py
new file mode 100644
index 0000000000..b25f5ec287
--- /dev/null
+++ b/tests/ci/test_rag_scale_release_gate.py
@@ -0,0 +1,53 @@
+"""A failed or missing corpus workload must block release publication."""
+
+from pathlib import Path
+import yaml
+
+WORKFLOWS = Path(__file__).resolve().parents[2] / ".github" / "workflows"
+
+
+def load(name):
+ result = yaml.safe_load((WORKFLOWS / name).read_text())
+ if True in result:
+ result["on"] = result.pop(True)
+ return result
+
+
+def test_release_requires_successful_rag_scale_shards():
+ jobs = load("release.yml")["jobs"]
+ assert (
+ jobs["rag-index-scale-gate"]["uses"]
+ == "$/.github/workflows/rag-index-scale.yml"
+ )
+ assert jobs["rag-index-scale-gate"]["needs"] == ["version-check"]
+ assert "rag-index-scale-gate" in jobs["build"]["needs"]
+ condition = jobs["build"]["if"]
+ assert "needs.rag-index-scale-gate.result == 'success'" in condition
+ assert "||" not in condition
+
+
+def test_corpus_is_release_only_and_failures_cannot_be_hidden():
+ workflow = load("rag-index-scale.yml")
+ assert set(workflow["on"]) == {"workflow_call", "workflow_dispatch"}
+ job = workflow["jobs"]["rag-index-scale"]
+ assert set(job["strategy"]["matrix"]["index-type"]) == {"flat", "hnsw"}
+ assert not job.get("continue-on-error")
+ steps = job["steps"]
+ workload = next(step for step in steps if step.get("id") == "workload")
+ assert workload["shell"] == "bash" # Actions enables -e -o pipefail.
+ assert not workload.get("continue-on-error")
+ assert "scripts/ci/rag_index_workload.py" in workload["run"]
+ assert "--documents 128 --pages 16 --dimension 1024" in workload["run"]
+ assert "--max-rss-mib 768" in workload["run"]
+ required_report = next(
+ step
+ for step in steps
+ if step["name"] == "Require a completed scale run"
+ )
+ assert required_report["if"] == "always()"
+ assert not required_report.get("continue-on-error")
+ assert any(
+ step.get("if") == "always()"
+ and "actions/upload-artifact@" in step.get("uses", "")
+ for step in steps
+ )
diff --git a/tests/database/test_migration_0042_chunk_vector_index_owner.py b/tests/database/test_migration_0042_chunk_vector_index_owner.py
new file mode 100644
index 0000000000..f138b70a30
--- /dev/null
+++ b/tests/database/test_migration_0042_chunk_vector_index_owner.py
@@ -0,0 +1,185 @@
+"""Legacy ownership recovery must not guess between physical configurations."""
+
+from alembic import command
+import pytest
+from sqlalchemy import create_engine, inspect, text
+
+from local_deep_research.database.alembic_runner import (
+ get_alembic_config,
+ stamp_database,
+)
+
+
+ "encrypted", [False, True], ids=["sqlite", "sqlcipher"]
+)
+def test_upgrade_preserves_ambiguous_rows_and_downgrade_preserves_ids(
+ tmp_path, encrypted
+):
+ kwargs = {}
+ if encrypted:
+ from sqlcipher3 import dbapi2
+
+ kwargs["module"] = dbapi2
+
+ def connect():
+ connection = dbapi2.connect(str(tmp_path / "ownership.db"))
+ connection.execute("PRAGMA key='test-only'") # gitleaks:allow
+ return connection
+
+ kwargs["creator"] = connect
+ engine = create_engine(f"sqlite:///{tmp_path / 'ownership.db'}", **kwargs)
+ try:
+ with engine.begin() as connection:
+ connection.execute(
+ text(
+ "CREATE TABLE document_chunks (id INTEGER PRIMARY KEY AUTOINCREMENT, collection_name TEXT, embedding_model TEXT, embedding_model_type TEXT, chunk_text TEXT)"
+ )
+ )
+ connection.execute(
+ text(
+ "CREATE TABLE rag_indices (collection_name TEXT, embedding_model TEXT, embedding_model_type TEXT, index_hash TEXT)"
+ )
+ )
+ # Each "*-mismatch" collection has exactly one index, but for a
+ # different model or provider, so it must stay NULL.
+ for name, model, provider, hashes in (
+ ("unique", "model", "sentence_transformers", ["one"]),
+ ("ambiguous", "model", "sentence_transformers", ["old", "new"]),
+ ("missing", "model", "sentence_transformers", []),
+ ("model-mismatch", "other", "sentence_transformers", ["x"]),
+ ("provider-mismatch", "model", "ollama", ["y"]),
+ ):
+ connection.execute(
+ text(
+ "INSERT INTO document_chunks (collection_name, embedding_model, embedding_model_type, chunk_text) VALUES (:name, :model, :provider, 'preserved')"
+ ),
+ {"name": name, "model": model, "provider": provider},
+ )
+ for value in hashes:
+ connection.execute(
+ text(
+ "INSERT INTO rag_indices VALUES (:name, 'model', 'sentence_transformers', :value)"
+ ),
+ {"name": name, "value": value},
+ )
+ stamp_database(engine, "0034")
+ config = get_alembic_config(engine)
+ with engine.begin() as connection:
+ config.attributes["connection"] = connection
+ command.upgrade(config, "0042")
+ values = dict(
+ connection.execute(
+ text(
+ "SELECT collection_name, vector_index_key FROM document_chunks"
+ )
+ ).all()
+ )
+ assert values == {
+ "unique": "one",
+ "ambiguous": None,
+ "missing": None,
+ "model-mismatch": None,
+ "provider-mismatch": None,
+ }
+ assert (
+ connection.execute(
+ text(
+ "SELECT COUNT(*) FROM document_chunks WHERE chunk_text='preserved'"
+ )
+ ).scalar_one()
+ == 5
+ )
+ with engine.begin() as connection:
+ config.attributes["connection"] = connection
+ # Delete the highest id BEFORE the downgrade rebuilds the table, so
+ # a rebuilt AUTOINCREMENT counter would restart below it.
+ connection.execute(text("DELETE FROM document_chunks WHERE id=5"))
+ sequence = connection.execute(
+ text(
+ "SELECT seq FROM sqlite_sequence WHERE name='document_chunks'"
+ )
+ ).scalar_one()
+ assert sequence == 5
+ command.downgrade(config, "0034")
+ assert "vector_index_key" not in {
+ column["name"]
+ for column in inspect(connection).get_columns("document_chunks")
+ }
+ connection.execute(
+ text("INSERT INTO document_chunks (chunk_text) VALUES ('new')")
+ )
+ assert (
+ connection.execute(
+ text(
+ "SELECT id FROM document_chunks WHERE chunk_text='new'"
+ )
+ ).scalar_one()
+ > sequence
+ )
+ assert (
+ connection.execute(
+ text(
+ "SELECT COUNT(*) FROM document_chunks WHERE chunk_text='preserved'"
+ )
+ ).scalar_one()
+ == 4
+ )
+ finally:
+ engine.dispose()
+
+
+def test_upgrade_keeps_existing_owner_and_downgrade_tolerates_missing_index(
+ tmp_path,
+):
+ """A key already recorded is never overwritten by the backfill, and a
+ column without its index (e.g. a hand-repaired database) downgrades."""
+ engine = create_engine(f"sqlite:///{tmp_path / 'preset.db'}")
+ try:
+ with engine.begin() as connection:
+ connection.execute(
+ text(
+ "CREATE TABLE document_chunks (id INTEGER PRIMARY KEY AUTOINCREMENT, collection_name TEXT, embedding_model TEXT, embedding_model_type TEXT, chunk_text TEXT, vector_index_key VARCHAR(64))"
+ )
+ )
+ connection.execute(
+ text(
+ "CREATE TABLE rag_indices (collection_name TEXT, embedding_model TEXT, embedding_model_type TEXT, index_hash TEXT)"
+ )
+ )
+ connection.execute(
+ text(
+ "INSERT INTO document_chunks (collection_name, embedding_model, embedding_model_type, chunk_text, vector_index_key) VALUES ('unique', 'model', 'sentence_transformers', 'preserved', 'adopted')"
+ )
+ )
+ connection.execute(
+ text(
+ "INSERT INTO rag_indices VALUES ('unique', 'model', 'sentence_transformers', 'one')"
+ )
+ )
+ stamp_database(engine, "0034")
+ config = get_alembic_config(engine)
+ with engine.begin() as connection:
+ config.attributes["connection"] = connection
+ command.upgrade(config, "0042")
+ assert (
+ connection.execute(
+ text("SELECT vector_index_key FROM document_chunks")
+ ).scalar_one()
+ == "adopted"
+ )
+ with engine.begin() as connection:
+ config.attributes["connection"] = connection
+ command.downgrade(config, "0034")
+ assert "vector_index_key" not in {
+ column["name"]
+ for column in inspect(connection).get_columns("document_chunks")
+ }
+ assert (
+ connection.execute(
+ text("SELECT chunk_text FROM document_chunks")
+ ).scalar_one()
+ == "preserved"
+ )
+ finally:
+ engine.dispose()
diff --git a/tests/database/test_research_retry_rag_cleanup.py b/tests/database/test_research_retry_rag_cleanup.py
index 467394c0c6..5ca03ae773 100644
--- a/tests/database/test_research_retry_rag_cleanup.py
+++ b/tests/database/test_research_retry_rag_cleanup.py
@@ -47,7 +47,11 @@ def observe_actual_purge(monkeypatch, database, events):
def __exit__(self, *_args):
return False
- def purge_document_vectors(self, document_id, collection_id):
+ def purge_documents_vectors(self, document_ids, collection_id):
+ for document_id in document_ids:
+ self._check_document(document_id, collection_id)
+
+ def _check_document(self, document_id, collection_id):
# A fresh connection observes the committed delete and the IDs
# needed by the real vector operation, not a dirty ORM identity map.
with Session(database) as verification:
@@ -156,7 +160,7 @@ def test_combined_retry_never_purges_before_commit(
assert events == [
(kind, "canonical", collection)
for collection in ("library", "selected")
- for kind in ("vectors", "chunks")
+ for kind in ("vectors",)
]
@@ -215,7 +219,7 @@ def test_combined_retry_refreshes_collection_targets(
assert events == [
(kind, "canonical", collection)
for collection in ("added", "library", "selected")
- for kind in ("vectors", "chunks")
+ for kind in ("vectors",)
]
with Session(database) as verification:
assert verification.get(ResearchHistory, "owner") is None
@@ -309,7 +313,7 @@ def test_target_discovery_shares_the_cascade_snapshot(
("canonical", "selected"),
("late-document", "late"),
)
- for kind in ("vectors", "chunks")
+ for kind in ("vectors",)
]
@@ -376,15 +380,15 @@ def test_purge_isolates_per_collection_failures(database, monkeypatch):
def failing_once(*args, **kwargs):
observer = observed(*args, **kwargs)
- real_vectors = observer.purge_document_vectors
+ real_vectors = observer.purge_documents_vectors
- def purge(document_id, collection_id):
+ def purge(document_ids, collection_id):
seen.append(collection_id)
if collection_id == "library":
raise RuntimeError("vector store unavailable")
- return real_vectors(document_id, collection_id)
+ return real_vectors(document_ids, collection_id)
- observer.purge_document_vectors = purge
+ observer.purge_documents_vectors = purge
return observer
monkeypatch.setattr(rag_service_factory, "get_rag_service", failing_once)
@@ -395,5 +399,13 @@ def test_purge_isolates_per_collection_failures(database, monkeypatch):
# The failing collection did not stop the next one.
assert seen == ["library", "selected"]
- assert ("vectors", "canonical", "selected") in events
- assert ("chunks", "canonical", "selected") in events
+ assert events == [("vectors", "canonical", "selected")]
+ # The residual sweep removes encrypted text even for the collection
+ # whose vector file was unavailable.
+ with Session(database) as verification:
+ assert (
+ verification.query(DocumentChunk)
+ .filter_by(source_id="canonical")
+ .count()
+ == 0
+ )
diff --git a/tests/document_loaders/test_synthetic_pdf.py b/tests/document_loaders/test_synthetic_pdf.py
new file mode 100644
index 0000000000..f1af5dab02
--- /dev/null
+++ b/tests/document_loaders/test_synthetic_pdf.py
@@ -0,0 +1,19 @@
+"""The release corpus must be real, extractable PDFs with known contents."""
+
+from local_deep_research.document_loaders.bounded_pdf import load_bounded_pdf
+from tests.fixtures.synthetic_pdf import synthetic_pdf
+
+
+def test_repeated_text_pdf_roundtrips_every_page_marker():
+ pdf = synthetic_pdf(7, pages=3, lines=5, words=4)
+ assert pdf.startswith(b"%PDF-")
+ documents = load_bounded_pdf(pdf, "synthetic.pdf")
+ assert len(documents) == 3
+ for page, document in enumerate(documents):
+ for line in range(5):
+ assert (
+ f"synthetic-document-000007-page-{page:04d}-line-{line:03d}"
+ in document.page_content
+ )
+ assert document.page_content.count("vector research alpha beta") == 20
+ assert not document.metadata.get("truncated")
diff --git a/tests/fixtures/synthetic_pdf.py b/tests/fixtures/synthetic_pdf.py
new file mode 100644
index 0000000000..a6dc1c2517
--- /dev/null
+++ b/tests/fixtures/synthetic_pdf.py
@@ -0,0 +1,45 @@
+"""Generate deterministic text PDFs in memory without extra dependencies."""
+
+from io import BytesIO
+
+from pypdf import PdfWriter
+from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject
+
+
+def synthetic_pdf(
+ document: int, *, pages: int = 2, lines: int = 40, words: int = 24
+) -> bytes:
+ """Repeated words create bulk; page/line markers make loss detectable."""
+ if not 1 <= pages <= 500 or not 1 <= lines <= 100 or not 1 <= words <= 1000:
+ raise ValueError("Synthetic PDF size is outside the test limits")
+ writer = PdfWriter()
+ font = DictionaryObject(
+ {
+ NameObject("/Type"): NameObject("/Font"),
+ NameObject("/Subtype"): NameObject("/Type1"),
+ NameObject("/BaseFont"): NameObject("/Helvetica"),
+ }
+ )
+ for number in range(pages):
+ page = writer.add_blank_page(width=612, height=792)
+ page[NameObject("/Resources")] = DictionaryObject(
+ {
+ NameObject("/Font"): DictionaryObject(
+ {NameObject("/F1"): writer._add_object(font)}
+ ),
+ }
+ )
+ content = ["BT /F1 8 Tf 10 TL 24 768 Td"]
+ for line in range(lines):
+ marker = f"synthetic-document-{document:06d}-page-{number:04d}-line-{line:03d}"
+ text = marker + " " + "vector research alpha beta " * words
+ content.append(f"({text}) Tj T*")
+ content.append("ET")
+ stream = DecodedStreamObject()
+ stream.set_data("\n".join(content).encode("ascii"))
+ page[NameObject("/Contents")] = writer._add_object(stream)
+ with BytesIO() as output:
+ writer.write(output)
+ result = output.getvalue()
+ writer.close()
+ return result
diff --git a/tests/performance/rag_index_workload.py b/tests/performance/rag_index_workload.py
new file mode 100644
index 0000000000..0ae7aa0d8a
--- /dev/null
+++ b/tests/performance/rag_index_workload.py
@@ -0,0 +1,421 @@
+"""Offline release probe for synthetic PDF ingestion and bounded FAISS writes.
+
+Run from the checkout with the project's test dependencies installed. The PDF
+bytes stay in memory; document content and metadata use a real encrypted
+SQLCipher database. Only deterministic embeddings and session routing are
+substituted. Extraction, chunking, index IO, integrity checks, search and
+reconciliation use production code. The report contains numeric diagnostics.
+"""
+
+from __future__ import annotations
+
+import argparse
+from contextlib import contextmanager, ExitStack
+import hashlib
+import json
+import os
+from pathlib import Path
+import resource
+import sys
+import tempfile
+import time
+from unittest.mock import patch
+
+import numpy as np
+from langchain_core.embeddings import Embeddings
+from loguru import logger
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from sqlcipher3 import dbapi2
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import (
+ Collection,
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ DocumentStatus,
+ SourceType,
+)
+from local_deep_research.document_loaders.bounded_pdf import load_bounded_pdf
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+)
+from local_deep_research.vector_stores.implementations import (
+ faiss_store,
+ segmented_faiss,
+)
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+from tests.fixtures.synthetic_pdf import synthetic_pdf # noqa: E402
+
+
+def require(condition, detail):
+ if not condition:
+ raise AssertionError(detail)
+
+
+class SyntheticEmbeddings(Embeddings):
+ def __init__(self, dimension):
+ self.dimension = dimension
+
+ def embed_query(self, text):
+ seed = int.from_bytes(hashlib.sha256(text.encode()).digest()[:8], "big")
+ return np.random.default_rng(seed).random(self.dimension).tolist()
+
+ def embed_documents(self, texts):
+ return [self.embed_query(text) for text in texts]
+
+
+class EmbeddingManager:
+ def __init__(self, dimension):
+ self.embeddings = SyntheticEmbeddings(dimension)
+
+
+def run(args, root):
+ os.environ["LDR_DATA_DIR"] = str(root)
+ logger.disable("local_deep_research")
+ db_path = root / "documents.encrypted.db"
+
+ def connect():
+ connection = dbapi2.connect(str(db_path))
+ # Random raw test key: no production credentials or password KDF cost.
+ connection.execute(f'''PRAGMA key = "x'{key}'"''')
+ connection.execute("PRAGMA foreign_keys=ON")
+ connection.execute("PRAGMA cache_size=-4096")
+ return connection
+
+ key = os.urandom(32).hex()
+ engine = create_engine("sqlite://", creator=connect, module=dbapi2)
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ @contextmanager
+ def shared_session(*_args, **_kwargs):
+ yield session
+
+ metrics = {
+ "faiss_bytes_written": 0,
+ "metadata_bytes_written": 0,
+ "largest_segment_vectors": 0,
+ "document_count": args.documents,
+ "pages_per_document": args.pages,
+ "dimension": args.dimension,
+ "index_type": args.index_type,
+ }
+ original_write = faiss_store.write_index
+ original_atomic = segmented_faiss._atomic_write
+
+ def write_index(index, path):
+ metrics["largest_segment_vectors"] = max(
+ metrics["largest_segment_vectors"], int(index.ntotal)
+ )
+ require(
+ index.ntotal <= segmented_faiss.SEGMENT_VECTORS,
+ "Workload check failed: index.ntotal <= segmented_faiss.SEGMENT_VECTORS",
+ )
+ result = original_write(index, path)
+ metrics["faiss_bytes_written"] += Path(path).stat().st_size
+ return result
+
+ def atomic_write(path, data):
+ metrics["metadata_bytes_written"] += len(data)
+ return original_atomic(path, data)
+
+ started = time.monotonic()
+ with ExitStack() as stack:
+ stack.callback(engine.dispose)
+ stack.callback(session.close)
+ for module in (
+ "research_library.services.library_rag_service",
+ "vector_stores.facade",
+ "security.file_integrity.integrity_manager",
+ ):
+ stack.enter_context(
+ patch(
+ f"local_deep_research.{module}.get_user_db_session",
+ shared_session,
+ )
+ )
+ stack.enter_context(
+ patch(
+ "local_deep_research.database.thread_local_session.get_current_thread_session",
+ return_value=session,
+ )
+ )
+ stack.enter_context(
+ patch.object(faiss_store, "write_index", write_index)
+ )
+ stack.enter_context(
+ patch.object(segmented_faiss, "_atomic_write", atomic_write)
+ )
+ source = SourceType(
+ id="synthetic-source",
+ name="document",
+ display_name="Synthetic PDFs",
+ )
+ collection = Collection(
+ id="synthetic-corpus", name="Synthetic PDF workload"
+ )
+ session.add_all([source, collection])
+ session.commit()
+
+ def service(chunk_size=1000):
+ return LibraryRAGService(
+ username="synthetic",
+ db_password=key,
+ embedding_model="synthetic-sha256",
+ embedding_provider="sentence_transformers",
+ embedding_manager=EmbeddingManager(args.dimension),
+ chunk_size=chunk_size,
+ chunk_overlap=200,
+ index_type=args.index_type,
+ distance_metric="cosine",
+ normalize_vectors=True,
+ )
+
+ rag = service()
+ stack.callback(rag.close)
+ document_ids = []
+ for number in range(args.documents):
+ pages = load_bounded_pdf(
+ synthetic_pdf(number, pages=args.pages), "synthetic.pdf"
+ )
+ require(
+ len(pages) == args.pages,
+ "Workload check failed: len(pages) == args.pages",
+ )
+ for page_number, page in enumerate(pages):
+ require(
+ not page.metadata.get("truncated"),
+ 'Workload check failed: not page.metadata.get("truncated")',
+ )
+ require(
+ f"synthetic-document-{number:06d}-page-{page_number:04d}"
+ in page.page_content,
+ 'Workload check failed: f"synthetic-document-{number:06d}-page-{page_number:04d}" in page.page_content',
+ )
+ text = "\n\n".join(page.page_content for page in pages)
+ document_id = f"synthetic-{number:06d}"
+ document_ids.append(document_id)
+ session.add(
+ Document(
+ id=document_id,
+ source_type_id=source.id,
+ title="Synthetic PDF",
+ document_hash=hashlib.sha256(text.encode()).hexdigest(),
+ text_content=text,
+ file_type="pdf",
+ file_size=len(text),
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.add(
+ DocumentCollection(
+ document_id=document_id, collection_id=collection.id
+ )
+ )
+ session.commit()
+ before = metrics["faiss_bytes_written"]
+ outcome = rag.index_document(document_id, collection.id)
+ require(outcome["status"] == "success", outcome)
+ # An append rewrites at most the bounded tail plus new segments.
+ written = metrics["faiss_bytes_written"] - before
+ bound = (
+ outcome["chunk_count"] + segmented_faiss.SEGMENT_VECTORS
+ ) * (4 * args.dimension + 1024)
+ require(written <= bound, (written, bound))
+ session.expire_all()
+ if (number + 1) % 16 == 0:
+ print(json.dumps({"indexed_documents": number + 1}), flush=True)
+
+ name = f"collection_{collection.id}"
+ index = rag._get_vector_index(collection.id, name)
+ metrics["initial_vectors"] = index.count()
+ metrics["segments"] = len(index._store._state())
+ require(
+ metrics["initial_vectors"] > args.documents,
+ 'Workload check failed: metrics["initial_vectors"] > args.documents',
+ )
+ for document_id in (
+ document_ids[0],
+ document_ids[len(document_ids) // 2],
+ document_ids[-1],
+ ):
+ chunk = (
+ session.query(DocumentChunk)
+ .filter_by(
+ source_id=document_id, vector_index_key=index.index_key
+ )
+ .first()
+ )
+ require(
+ chunk is not None, "Workload check failed: chunk is not None"
+ )
+ hits = rag.search(chunk.chunk_text, collection.id, top_k=3)
+ require(
+ any(hit.chunk_id == chunk.id for hit in hits),
+ "Workload check failed: any(hit.chunk_id == chunk.id for hit in hits)",
+ )
+
+ # Roll back a replacement against the fully populated corpus, then
+ # reopen the store: its previous searchable generation must survive.
+ from local_deep_research.vector_stores.facade import ChunkInput
+
+ before_rollback = set(index.live_ids())
+ index.index(
+ source_type="document",
+ source_id=document_ids[0],
+ chunks=[ChunkInput(text="synthetic uncommitted replacement")],
+ session=session,
+ )
+ session.rollback()
+ index = rag._get_vector_index(collection.id, name)
+ require(
+ set(index.live_ids()) == before_rollback,
+ "Rollback changed corpus membership",
+ )
+ del before_rollback
+
+ # Full-configuration A -> B -> A must preserve the other index's rows.
+ alternate = service(1200)
+ stack.callback(alternate.close)
+ for configured in (alternate, rag):
+ result = configured.index_document(
+ document_ids[0], collection.id, force_reindex=True
+ )
+ require(result["status"] == "success", result)
+ for configured in (rag, alternate):
+ current = configured._get_vector_index(collection.id, name)
+ owned = {
+ row.id
+ for row in session.query(DocumentChunk.id)
+ .filter_by(vector_index_key=current.index_key)
+ .yield_per(500)
+ }
+ require(
+ set(current.live_ids()) == owned,
+ "Workload check failed: set(current.live_ids()) == owned",
+ )
+
+ # Bulk deletion purges both configurations, preserving unrelated docs.
+ removed = document_ids[: max(1, len(document_ids) // 4)]
+ require(
+ rag.purge_documents_vectors(removed, collection.id) > 0,
+ "Workload check failed: rag.purge_documents_vectors(removed, collection.id) > 0",
+ )
+ require(
+ session.query(DocumentChunk)
+ .filter(DocumentChunk.source_id.in_(removed))
+ .count()
+ == 0,
+ "Workload check failed: session.query(DocumentChunk).filter(DocumentChunk.source_id.in_(removed)).count() == 0",
+ )
+ for configured in (rag, alternate):
+ current = configured._get_vector_index(collection.id, name)
+ owned = {
+ row.id
+ for row in session.query(DocumentChunk.id)
+ .filter_by(vector_index_key=current.index_key)
+ .yield_per(500)
+ }
+ require(
+ set(current.live_ids()) == owned,
+ "Workload check failed: set(current.live_ids()) == owned",
+ )
+ reconciled = rag.reconcile_collection_index(collection.id)
+ require(
+ reconciled["orphan_vectors"] == 0,
+ 'Workload check failed: reconciled["orphan_vectors"] == 0',
+ )
+ metrics["remaining_vectors"] = reconciled["live_vectors"]
+ # Finish the synthetic document deletion before rebuilding survivors.
+ session.query(DocumentCollection).filter(
+ DocumentCollection.document_id.in_(removed)
+ ).delete(synchronize_session=False)
+ session.query(Document).filter(Document.id.in_(removed)).delete(
+ synchronize_session=False
+ )
+ session.commit()
+ document_ids = [value for value in document_ids if value not in removed]
+ index = rag._get_vector_index(collection.id, name)
+ # Rebuild through the production private-generation protocol. The
+ # old index stays searchable while every synthetic PDF is staged.
+ from local_deep_research.research_library.services.collection_rebuild import (
+ CollectionRebuild,
+ )
+
+ with CollectionRebuild(
+ rag,
+ collection.id,
+ [(value, "Synthetic PDF") for value in document_ids],
+ session_factory=shared_session,
+ ) as rebuild:
+ for completed, document_id in enumerate(document_ids, 1):
+ prepared = rebuild.prepare(document_id)
+ require(prepared["status"] == "prepared", prepared)
+ rebuild.write(prepared["prepared"])
+ if completed % 16 == 0:
+ print(
+ json.dumps({"staged_documents": completed}), flush=True
+ )
+ require(
+ index.count() == metrics["remaining_vectors"],
+ "Staging changed the published corpus",
+ )
+ rebuild.publish()
+ index = rag._get_vector_index(collection.id, name)
+ metrics["rebuilt_vectors"] = index.count()
+ require(
+ metrics["rebuilt_vectors"] == metrics["remaining_vectors"],
+ "Rebuild lost vectors",
+ )
+
+ metrics["elapsed_seconds"] = round(time.monotonic() - started, 3)
+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
+ metrics["peak_rss_mib"] = round(
+ peak / (1024 * 1024 if sys.platform == "darwin" else 1024), 2
+ )
+ require(metrics["peak_rss_mib"] <= args.max_rss_mib, metrics)
+ # No generated PDF or plaintext chunk cache may have reached disk.
+ for path in root.rglob("*"):
+ if path.is_file():
+ with path.open("rb") as stream:
+ overlap = b""
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ require(
+ b"synthetic-document-" not in overlap + block, path
+ )
+ overlap = block[-32:]
+ with db_path.open("rb") as stream:
+ require(
+ stream.read(16) != b"SQLite format 3\x00",
+ "Document database is plaintext",
+ )
+ return metrics
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--documents", type=int, default=4)
+ parser.add_argument("--pages", type=int, default=2)
+ parser.add_argument("--dimension", type=int, default=128)
+ parser.add_argument(
+ "--index-type", choices=("flat", "hnsw"), default="hnsw"
+ )
+ parser.add_argument("--max-rss-mib", type=int, default=768)
+ parser.add_argument("--report", type=Path, required=True)
+ args = parser.parse_args()
+ if not 2 <= args.documents <= 10000 or not 1 <= args.dimension <= 4096:
+ parser.error("Invalid workload size")
+ with tempfile.TemporaryDirectory(prefix="ldr-rag-workload-") as temporary:
+ metrics = run(args, Path(temporary))
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(
+ json.dumps(metrics, indent=2) + "\n", encoding="utf-8"
+ )
+ print(json.dumps(metrics), flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/research_library/deletion/services/test_collection_deletion_flow.py b/tests/research_library/deletion/services/test_collection_deletion_flow.py
index 22aca39418..6935c97425 100644
--- a/tests/research_library/deletion/services/test_collection_deletion_flow.py
+++ b/tests/research_library/deletion/services/test_collection_deletion_flow.py
@@ -632,11 +632,11 @@ class TestCrossCollectionSafety:
# 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,
+ from local_deep_research.vector_stores.implementations.segmented_faiss import (
+ SegmentedFaissStore,
)
- store_b = FaissVectorStore.load(
+ store_b = SegmentedFaissStore.load(
faiss_b,
dimension=8,
index_type=rag_rows_b[0].index_type or "flat",
diff --git a/tests/research_library/deletion/utils/test_cascade_family_delete_containment.py b/tests/research_library/deletion/utils/test_cascade_family_delete_containment.py
new file mode 100644
index 0000000000..ad6d294ef7
--- /dev/null
+++ b/tests/research_library/deletion/utils/test_cascade_family_delete_containment.py
@@ -0,0 +1,299 @@
+"""One foreign child must not abort the index-family delete.
+
+Regression pins for the family-deletion invariant: the plaintext ``.pkl``
+removal is "not optional" (see ``library_rag_service``'s quarantine path), so
+an unexpected entry inside ``<index>.faiss.segments`` — e.g. a ``.DS_Store``
+dropped by a file manager into the directory ``docs/library-and-rag.md`` tells
+users to back up — must never prevent removal of the rest of the family. The
+refusal guards stand: foreign, symlinked or unexpected entries are still never
+deleted.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+)
+from local_deep_research.vector_stores.segment_files import (
+ checkpoint_path,
+ delete_segment_files,
+ segment_directory,
+)
+
+
+def _family(tmp_path):
+ """A minimal index family with generated segments beside it."""
+ base = tmp_path / "rag_indices" / "user_hash" / "index"
+ base.parent.mkdir(parents=True)
+ faiss_file = base.with_suffix(".faiss")
+ pkl_file = base.with_suffix(".pkl")
+ idmap_file = base.with_suffix(".idmap.json")
+ faiss_file.write_bytes(b"synthetic manifest")
+ pkl_file.write_bytes(b"legacy plaintext docstore")
+ idmap_file.write_text("{}")
+ segments = segment_directory(faiss_file)
+ segments.mkdir()
+ for name in ("a" * 32 + ".faiss", "a" * 32 + ".ids"):
+ (segments / name).write_bytes(b"generated segment")
+ return base, faiss_file, pkl_file, idmap_file, segments
+
+
+def test_foreign_entry_does_not_abort_family_delete(tmp_path):
+ base, faiss_file, pkl_file, idmap_file, segments = _family(tmp_path)
+ foreign = segments / ".DS_Store"
+ foreign.write_bytes(b"file-manager droppings")
+
+ result = CascadeHelper.delete_faiss_index_files(str(base))
+
+ # Honest reporting: every removable member is gone, but the segment
+ # cleanup was refused, so the delete reports False (incomplete).
+ assert result is False
+ assert not faiss_file.exists()
+ assert not pkl_file.exists() # plaintext removal is not optional
+ assert not idmap_file.exists()
+ # Every generated sibling is retired; only the refused foreign entry
+ # remains, and it is never deleted.
+ assert [child.name for child in segments.iterdir()] == [".DS_Store"]
+ assert foreign.read_bytes() == b"file-manager droppings"
+
+
+def test_symlinked_entry_is_still_refused_but_family_removed(tmp_path):
+ base, faiss_file, pkl_file, idmap_file, segments = _family(tmp_path)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ sentinel = outside / "payload.faiss"
+ sentinel.write_bytes(b"do not delete me")
+ link = segments / ("b" * 32 + ".faiss")
+ link.symlink_to(sentinel)
+
+ result = CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert result is False # the refusal is contained but still reported
+ assert not faiss_file.exists()
+ assert not pkl_file.exists()
+ assert link.is_symlink() # the refusal guard is not weakened
+ assert sentinel.read_bytes() == b"do not delete me"
+
+
+def test_poisoned_quarantine_payload_does_not_abort_plaintext_sweep(tmp_path):
+ """The per-stray handler for quarantined ``.segments`` payloads swallows
+ the refusal: a poisoned quarantine must not strand the plaintext
+ ``.pkl.corrupt-*`` sweep that runs later in the same family delete."""
+ base = tmp_path / "index"
+ faiss_file = base.with_suffix(".faiss")
+ pkl_file = base.with_suffix(".pkl")
+ faiss_file.write_bytes(b"synthetic manifest")
+ pkl_file.write_bytes(b"legacy plaintext docstore")
+ poisoned = tmp_path / "index.faiss.corrupt-111.segments"
+ poisoned.mkdir()
+ (poisoned / ("d" * 32 + ".faiss")).write_bytes(b"generated segment")
+ (poisoned / "surprise.bin").write_bytes(b"user file")
+ pkl_quarantine = tmp_path / "index.pkl.corrupt-222"
+ pkl_quarantine.write_bytes(b"quarantined PLAINTEXT")
+
+ result = CascadeHelper.delete_faiss_index_files(str(base))
+
+ assert result is False # the refusal is contained but still reported
+ assert not pkl_file.exists()
+ assert not pkl_quarantine.exists()
+ assert (poisoned / "surprise.bin").read_bytes() == b"user file"
+
+
+def test_delete_segment_files_retires_generated_siblings_before_refusing(
+ tmp_path, monkeypatch
+):
+ """The refusal raises only after every generated sibling is retired, so
+ the iteration order of the directory cannot strand generated files behind
+ a foreign one. The test forces the foreign entry to be seen first."""
+ faiss_file = tmp_path / "index.faiss"
+ faiss_file.write_bytes(b"synthetic manifest")
+ segments = segment_directory(faiss_file)
+ segments.mkdir()
+ generated = segments / ("c" * 32 + ".faiss")
+ generated.write_bytes(b"generated segment")
+ foreign = segments / "surprise.txt"
+ foreign.write_bytes(b"user file")
+
+ real_iterdir = Path.iterdir
+
+ def foreign_first(self):
+ children = list(real_iterdir(self))
+ if self == segments:
+ children.sort(key=lambda child: child.name != "surprise.txt")
+ return iter(children)
+
+ monkeypatch.setattr(Path, "iterdir", foreign_first)
+
+ with pytest.raises(ValueError, match="unexpected"):
+ delete_segment_files(faiss_file)
+
+ assert not generated.exists()
+ assert foreign.read_bytes() == b"user file"
+ assert segments.is_dir()
+
+
+ "unavailable", ["checkpoint", "index", "metadata", "ids", "quarantine"]
+)
+def test_family_cleanup_continues_after_component_error(
+ tmp_path, monkeypatch, unavailable
+):
+ base, faiss_file, pkl_file, idmap_file, segments = _family(tmp_path)
+ checkpoint = checkpoint_path(faiss_file)
+ checkpoint.write_bytes(b"sample checkpoint")
+ members = {
+ "checkpoint": checkpoint,
+ "index": faiss_file,
+ "metadata": pkl_file,
+ "ids": idmap_file,
+ }
+ quarantined = pkl_file.with_name(pkl_file.name + ".corrupt-123")
+ quarantined.write_bytes(b"sample metadata")
+ members["quarantine"] = quarantined
+ real_unlink = Path.unlink
+
+ def unlink(path, *args, **kwargs):
+ if path == members[unavailable]:
+ raise PermissionError("Component unavailable")
+ return real_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", unlink)
+
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is False
+ assert members[unavailable].is_file()
+ assert all(
+ not member.exists()
+ for name, member in members.items()
+ if name != unavailable
+ )
+ if unavailable == "index":
+ # A manifest that could not be removed keeps the segments it names,
+ # so a later write at this path never meets a dangling manifest.
+ assert sorted(child.name for child in segments.iterdir()) == [
+ "a" * 32 + ".faiss",
+ "a" * 32 + ".ids",
+ ]
+ else:
+ assert not segments.exists()
+
+
+def test_unreadable_root_keeps_segments_and_still_sweeps_quarantine(
+ tmp_path, monkeypatch
+):
+ base, faiss_file, pkl_file, idmap_file, segments = _family(tmp_path)
+ quarantined = pkl_file.with_name(pkl_file.name + ".corrupt-123")
+ quarantined.write_bytes(b"sample metadata")
+ real_unlink = Path.unlink
+ real_exists = Path.exists
+
+ def unlink(path, *args, **kwargs):
+ if path == faiss_file:
+ raise PermissionError("Component unavailable")
+ return real_unlink(path, *args, **kwargs)
+
+ def exists(path, *args, **kwargs):
+ # Python < 3.14 re-raises EACCES from Path.exists().
+ if path == faiss_file:
+ raise PermissionError("Permission denied")
+ return real_exists(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "unlink", unlink)
+ monkeypatch.setattr(Path, "exists", exists)
+
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is False
+ assert sorted(child.name for child in segments.iterdir()) == [
+ "a" * 32 + ".faiss",
+ "a" * 32 + ".ids",
+ ]
+ assert not pkl_file.exists()
+ assert not real_exists(quarantined) # plaintext removal is not optional
+
+
[email protected]("suffix", [".faiss", ".ids"])
+def test_family_cleanup_continues_after_segment_error(
+ tmp_path, monkeypatch, suffix
+):
+ base, faiss_file, pkl_file, idmap_file, segments = _family(tmp_path)
+ unavailable = segments / ("a" * 32 + suffix)
+ real_unlink = Path.unlink
+ real_iterdir = Path.iterdir
+
+ def unavailable_first(directory):
+ children = list(real_iterdir(directory))
+ if directory == segments:
+ children.sort(key=lambda child: child != unavailable)
+ return iter(children)
+
+ def unlink(path, *args, **kwargs):
+ if path == unavailable:
+ raise PermissionError("Component unavailable")
+ return real_unlink(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "iterdir", unavailable_first)
+ monkeypatch.setattr(Path, "unlink", unlink)
+
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is False
+ assert not faiss_file.exists()
+ assert not pkl_file.exists()
+ assert not idmap_file.exists()
+ assert list(segments.iterdir()) == [unavailable]
+ assert unavailable.read_bytes() == b"generated segment"
+
+
+def test_family_cleanup_accepts_a_disappearing_segment(tmp_path, monkeypatch):
+ base, faiss_file, pkl_file, idmap_file, segments = _family(tmp_path)
+ disappearing = segments / ("a" * 32 + ".faiss")
+ real_unlink = Path.unlink
+ real_iterdir = Path.iterdir
+
+ def disappearing_first(directory):
+ children = list(real_iterdir(directory))
+ if directory == segments:
+ children.sort(key=lambda child: child != disappearing)
+ return iter(children)
+
+ def unlink(path, *args, **kwargs):
+ result = real_unlink(path, *args, **kwargs)
+ if path == disappearing:
+ raise FileNotFoundError("Component already removed")
+ return result
+
+ monkeypatch.setattr(Path, "iterdir", disappearing_first)
+ monkeypatch.setattr(Path, "unlink", unlink)
+
+ assert CascadeHelper.delete_faiss_index_files(str(base)) is True
+ assert not faiss_file.exists()
+ assert not pkl_file.exists()
+ assert not idmap_file.exists()
+ assert not segments.exists()
+
+
+def test_delete_segment_files_skips_a_child_retired_mid_walk(
+ tmp_path, monkeypatch
+):
+ """A segment a concurrent settle retires after the directory is listed
+ is neither foreign nor an error: the walk completes and the directory
+ is removed."""
+ faiss_file = tmp_path / "index.faiss"
+ faiss_file.write_bytes(b"synthetic manifest")
+ segments = segment_directory(faiss_file)
+ segments.mkdir()
+ kept = segments / ("c" * 32 + ".faiss")
+ kept.write_bytes(b"generated segment")
+ retired = segments / ("d" * 32 + ".faiss")
+ retired.write_bytes(b"generated segment")
+
+ real_iterdir = Path.iterdir
+
+ def retire_after_listing(self):
+ children = list(real_iterdir(self))
+ if self == segments:
+ retired.unlink()
+ return iter(children)
+
+ monkeypatch.setattr(Path, "iterdir", retire_after_listing)
+
+ assert delete_segment_files(faiss_file) is True
+ assert not segments.exists()
diff --git a/tests/research_library/routes/test_rag_routes_upload_main_port.py b/tests/research_library/routes/test_rag_routes_upload_main_port.py
index 4df9784c36..db2e07755d 100644
--- a/tests/research_library/routes/test_rag_routes_upload_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_upload_main_port.py
@@ -2187,3 +2187,61 @@ class TestGetCollectionDocuments:
assert data["collection"]["index_file_size_bytes"] == mb2
finally:
Path(tmp_path).unlink(missing_ok=True)
+
+ def test_collection_documents_index_size_includes_segments(self, tmp_path):
+ """A segmented index root is only a small manifest: the reported size
+ must include the vectors in its ``.segments`` directory."""
+ mock_coll = Mock(
+ id="coll-seg",
+ description=None,
+ embedding_model=None,
+ embedding_model_type=None,
+ embedding_dimension=None,
+ chunk_size=None,
+ chunk_overlap=None,
+ splitter_type=None,
+ distance_metric=None,
+ index_type=None,
+ normalize_vectors=None,
+ collection_type="user_uploads",
+ )
+ mock_coll.name = "Segmented Collection"
+ root = tmp_path / "index.faiss"
+ root.write_bytes(b"m" * 100)
+ segments = tmp_path / "index.faiss.segments"
+ segments.mkdir()
+ (segments / ("a" * 32 + ".faiss")).write_bytes(b"v" * 4000)
+ mock_rag_index = Mock(index_path=str(root))
+
+ db_session = _make_db_session()
+ call_count = {"n": 0}
+
+ def query_side_effect(*args):
+ call_count["n"] += 1
+ q = _build_mock_query()
+ if call_count["n"] == 1:
+ q.first.return_value = mock_coll
+ elif call_count["n"] == 2:
+ q.filter_by.return_value = q
+ q.first.return_value = None
+ elif call_count["n"] == 3:
+ q.all.return_value = []
+ elif call_count["n"] == 4:
+ q.first.return_value = mock_rag_index
+ return q
+
+ db_session.query = Mock(side_effect=query_side_effect)
+ status, data = _get_collection_documents(db_session, "coll-seg")
+ assert status == 200
+ assert data["collection"]["index_file_size_bytes"] == 4100
+ assert data["collection"]["index_file_size_bytes"] > root.stat().st_size
+ assert data["collection"]["index_file_size"] == "4.0 KB"
+
+ # A root retired by a concurrent writer is reported as unknown, not
+ # a failed details page.
+ root.unlink()
+ call_count["n"] = 0
+ db_session.query = Mock(side_effect=query_side_effect)
+ status, data = _get_collection_documents(db_session, "coll-seg")
+ assert status == 200
+ assert data["collection"]["index_file_size_bytes"] is None
diff --git a/tests/research_library/services/test_collection_rebuild.py b/tests/research_library/services/test_collection_rebuild.py
index 02b78f9716..c42d736610 100644
--- a/tests/research_library/services/test_collection_rebuild.py
+++ b/tests/research_library/services/test_collection_rebuild.py
@@ -316,6 +316,9 @@ def test_complete_rebuild_switches_generation_only_after_all_documents(
assert after["model"] == model
assert after["indices"][0][0] != before["indices"][0][0]
assert all(not Path(path).exists() for path in before["files"])
+ assert all(
+ not Path(path + ".segments").exists() for path in before["files"]
+ )
world.assert_searchable(model)
world.assert_no_staging()
# Subsequent ordinary writes must reopen the published generation path.
diff --git a/tests/research_library/services/test_index_finalize_self_heal.py b/tests/research_library/services/test_index_finalize_self_heal.py
index b4c042d5bb..bbefb0f463 100644
--- a/tests/research_library/services/test_index_finalize_self_heal.py
+++ b/tests/research_library/services/test_index_finalize_self_heal.py
@@ -1,38 +1,8 @@
-"""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.
+"""A failed database commit must preserve the previous searchable generation.
+
+Real FAISS files and SQLite transactions exercise both the service retry
+backstop and the facade checkpoint. The checkpoint protects prior vectors
+independently of the service's conservative reindex flag.
"""
import hashlib
@@ -63,8 +33,8 @@ 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,
+from local_deep_research.vector_stores.implementations.segmented_faiss import (
+ SegmentedFaissStore,
)
_RAG_MOD = "local_deep_research.research_library.services.library_rag_service"
@@ -314,15 +284,10 @@ class TestIndexDocumentSelfHeal:
assert rag_index.total_documents == 1
svc.close()
- def test_control_without_backstop_stays_indexed_and_unsearchable(
+ def test_checkpoint_preserves_search_without_the_reindex_backstop(
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.
- """
+ """Vector rollback protects search even with the retry flag disabled."""
session = rag_env
source_type = self._source_type(session)
@@ -362,23 +327,11 @@ class TestIndexDocumentSelfHeal:
.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.
+ assert dc.indexed is True
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"
- )
+ assert hits and all(hit.source_id == doc_id for hit in hits)
svc.close()
@@ -434,7 +387,7 @@ class TestFacadeFinalizeDbFailureIsConsistent:
chunk_a_id = row_a.id
def _load_store():
- return FaissVectorStore.load(
+ return SegmentedFaissStore.load(
index_path,
dimension=8,
index_type="flat",
@@ -477,17 +430,8 @@ class TestFacadeFinalizeDbFailureIsConsistent:
)
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"
+ # The checkpoint restores the same vector ID as the rolled-back row.
+ assert _load_store().live_ids() == [chunk_a_id]
+ assert vi.search("alpha body one", top_k=1)[0].text == "alpha body one"
+ session.close()
+ engine.dispose()
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 e4b7b790a6..6f8860ed8e 100644
--- a/tests/research_library/services/test_library_rag_service_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_coverage.py
@@ -1699,6 +1699,46 @@ class TestPreflightDimensionMismatch:
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_removes_manifest_despite_foreign_segment_file(
+ self, mock_session_ctx, tmp_path
+ ):
+ """A refused foreign file must not leave a manifest pointing at
+ deleted segments while the DB row is reset."""
+ from local_deep_research.vector_stores.segment_files import (
+ segment_directory,
+ )
+
+ 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
+ )
+ directory = segment_directory(index_path)
+ directory.mkdir()
+ segment = directory / ("a" * 32 + ".faiss")
+ segment.write_bytes(b"vectors")
+ (directory / ".DS_Store").write_bytes(b"foreign")
+
+ 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)
+
+ assert not segment.exists()
+ assert not index_path.exists()
+ assert db_row.embedding_dimension == 768
+
@patch(f"{_MOD}.get_user_db_session")
def test_preflight_dimension_mismatch_continues_rebuild_when_unlink_fails(
self, mock_session_ctx, tmp_path
diff --git a/tests/research_library/services/test_rag_segment_recovery.py b/tests/research_library/services/test_rag_segment_recovery.py
new file mode 100644
index 0000000000..1318929a15
--- /dev/null
+++ b/tests/research_library/services/test_rag_segment_recovery.py
@@ -0,0 +1,415 @@
+"""Upgrade and component recovery through real FAISS and integrity checks."""
+
+import pytest
+
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+)
+from local_deep_research.research_library.services.library_rag_service import (
+ LibraryRAGService,
+ _QUARANTINE_KEEP_RECENT,
+)
+from local_deep_research.vector_stores.base import VectorStoreIntegrityError
+from local_deep_research.vector_stores.facade import VectorIndex
+from local_deep_research.vector_stores.implementations import segmented_faiss
+from local_deep_research.vector_stores.segment_files import segment_directory
+from tests.vector_stores import test_integrity_tamper_lifecycle as harness
+
+rig = harness.rig
+
+
+def test_reconciliation_adopts_legacy_ownership_before_counting_chunks(rig):
+ """A different legacy chunking configuration must not disable search."""
+ with LibraryRAGService(
+ username=rig.svc.username,
+ db_password="pw",
+ embedding_model=rig.svc.embedding_model,
+ embedding_provider=rig.svc.embedding_provider,
+ embedding_manager=rig.svc.embedding_manager,
+ chunk_size=80,
+ chunk_overlap=10,
+ ) as alternate:
+ alternate._get_vector_index(rig.collection_id, rig.collection_name)
+ # Migration 0042 cannot assign rows when two physical configurations
+ # exist for the same model. This is its deliberate upgrade result.
+ rig.session.query(DocumentChunk).update(
+ {DocumentChunk.vector_index_key: None}
+ )
+ rig.session.commit()
+ legacy_ids = {row.id for row in rig.session.query(DocumentChunk).all()}
+ result = alternate.index_document(
+ rig.document_id, rig.collection_id, force_reindex=True
+ )
+ assert result["status"] == "success", result
+ index = alternate._get_vector_index(
+ rig.collection_id, rig.collection_name
+ )
+ live_ids = set(index.live_ids())
+ assert live_ids and live_ids.isdisjoint(legacy_ids)
+ assert alternate.integrity_manager.verify_file(index._path, force=True)[
+ 0
+ ]
+ assert alternate.has_indexed_documents(rig.collection_id)
+
+ report = alternate.reconcile_collection_index(rig.collection_id)
+
+ assert report["indexed_documents"] == 1
+ assert report["indexed_chunks"] == len(live_ids)
+ assert report["partial_document_vectors"] == 0
+ assert report["orphan_vectors"] == 0
+ assert alternate.has_indexed_documents(rig.collection_id)
+ link = (
+ rig.session.query(DocumentCollection)
+ .filter_by(
+ document_id=rig.document_id, collection_id=rig.collection_id
+ )
+ .one()
+ )
+ assert link.indexed and link.chunk_count == len(live_ids)
+ assert alternate.search(harness.SECRET, rig.collection_id, top_k=1)
+ # The other configuration's encrypted text survives without guessed
+ # ownership. A normal search can still hydrate its legacy vectors.
+ assert {
+ row.id
+ for row in rig.session.query(DocumentChunk).filter(
+ DocumentChunk.vector_index_key.is_(None)
+ )
+ } == legacy_ids
+ assert rig.svc.search(harness.SECRET, rig.collection_id, top_k=1)
+
+
[email protected]("suffix", [".faiss", ".ids"])
[email protected]("damage", ["corrupt", "missing"])
[email protected]("writer", ["serial", "prepared", "cleared"])
+def test_write_recovers_component_damage_after_rollback(
+ rig, suffix, damage, writer, mocker
+):
+ path = rig.index_path()
+ original_root = path.read_bytes()
+ original_ids = {row.id for row in rig.session.query(DocumentChunk)}
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ entry = index._store._state()[0]
+ component = (segment_directory(path) / entry["file"]).with_suffix(suffix)
+ if writer == "prepared":
+ prepared = rig.svc._prepare_document(
+ rig.document_id, rig.collection_id, True
+ )
+ assert prepared["status"] == "prepared", prepared
+ if damage == "missing":
+ component.unlink()
+ else:
+ component.write_bytes(component.read_bytes() + b"synthetic corruption")
+
+ # Reads refuse bad data without altering the root or indexed state.
+ with pytest.raises(VectorStoreIntegrityError):
+ rig.svc.search(harness.SECRET, rig.collection_id, top_k=1)
+ assert path.read_bytes() == original_root
+ assert rig.svc.has_indexed_documents(rig.collection_id)
+ assert not list(path.parent.glob(path.name + ".corrupt-*"))
+ quarantine = rig.svc._quarantine_corrupt_index
+
+ def after_rollback(*args, **kwargs):
+ assert not rig.session.info.get("ldr_vector_transactions")
+ assert path.read_bytes() == original_root
+ assert {
+ row.id for row in rig.session.query(DocumentChunk)
+ } == original_ids
+ return quarantine(*args, **kwargs)
+
+ mocker.patch.object(
+ rig.svc, "_quarantine_corrupt_index", side_effect=after_rollback
+ )
+ if writer == "cleared":
+ document = rig.session.get(Document, rig.document_id)
+ document.text_content = ""
+ rig.session.commit()
+ result = (
+ rig.svc._write_prepared_document(prepared["prepared"])
+ if writer == "prepared"
+ else rig.svc.index_document(
+ rig.document_id, rig.collection_id, force_reindex=True
+ )
+ )
+ assert result["status"] == (
+ "cleared" if writer == "cleared" else "success"
+ ), result
+ rig.svc._quarantine_corrupt_index.assert_called_once()
+ roots = [
+ candidate
+ for candidate in path.parent.glob(path.name + ".corrupt-*")
+ if candidate.is_file()
+ ]
+ assert len(roots) == 1
+ assert segment_directory(roots[0]).is_dir()
+ assert roots[0].read_bytes() == original_root
+ current = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ rows = {row.id for row in rig.session.query(DocumentChunk)}
+ assert set(current.live_ids()) == rows
+ assert rows.isdisjoint(original_ids)
+ assert rig.svc.integrity_manager.verify_file(path, force=True)[0]
+ hits = rig.svc.search(harness.SECRET, rig.collection_id, top_k=1)
+ assert bool(hits) == (writer != "cleared")
+ assert not rig.session.info.get("ldr_vector_transactions")
+
+
+def test_component_io_failure_preserves_the_index(rig, monkeypatch, mocker):
+ path = rig.index_path()
+ original = path.read_bytes()
+ rows = {row.id for row in rig.session.query(DocumentChunk)}
+ quarantine = mocker.spy(rig.svc, "_quarantine_corrupt_index")
+
+ def unavailable(_path):
+ raise OSError("transient component I/O failure")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(segmented_faiss, "_digest", unavailable)
+ result = rig.svc.index_document(
+ rig.document_id, rig.collection_id, force_reindex=True
+ )
+ assert result == {"status": "error", "error": "Operation failed: OSError"}
+ quarantine.assert_not_called()
+ assert path.read_bytes() == original
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ assert set(index.live_ids()) == rows
+ assert rig.svc.search(harness.SECRET, rig.collection_id, top_k=1)
+
+
+def test_component_recovery_retries_only_once(rig, monkeypatch, mocker):
+ attempts = []
+
+ def corrupt(_index, _session):
+ attempts.append(True)
+ raise VectorStoreIntegrityError("persistent component failure")
+
+ monkeypatch.setattr(VectorIndex, "_prepare_cleanup", corrupt)
+ quarantine = mocker.spy(rig.svc, "_quarantine_corrupt_index")
+ result = rig.svc.index_document(
+ rig.document_id, rig.collection_id, force_reindex=True
+ )
+ assert result == {
+ "status": "error",
+ "error": "Operation failed: VectorStoreIntegrityError",
+ }
+ assert len(attempts) == 2
+ quarantine.assert_called_once()
+
+
+def test_prepared_recovery_reloads_the_source(rig, mocker):
+ prepared = rig.svc._prepare_document(
+ rig.document_id, rig.collection_id, True
+ )
+ assert prepared["status"] == "prepared", prepared
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ entry = index._store._state()[0]
+ component = segment_directory(rig.index_path()) / entry["file"]
+ component.write_bytes(component.read_bytes() + b"corruption")
+ reset = rig.svc._reset_index_state_for_rebuild
+ replacement = "Updated source text during component recovery"
+
+ def change_after_reset(*args):
+ reset(*args)
+ rig.session.get(Document, rig.document_id).text_content = replacement
+ rig.session.commit()
+
+ mocker.patch.object(
+ rig.svc,
+ "_reset_index_state_for_rebuild",
+ side_effect=change_after_reset,
+ )
+ result = rig.svc._write_prepared_document(prepared["prepared"])
+
+ assert result["status"] == "success", result
+ hits = rig.svc.search(replacement, rig.collection_id, top_k=1)
+ assert hits and hits[0].text == replacement
+ assert all(
+ harness.SECRET not in row.chunk_text
+ for row in rig.session.query(DocumentChunk)
+ )
+
+
+def test_empty_live_membership_preserves_unknown_legacy_rows(rig, mocker):
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ rig.session.query(DocumentChunk).update(
+ {DocumentChunk.vector_index_key: None}
+ )
+ rig.session.commit()
+ mocker.patch.object(rig.svc, "_get_vector_index", return_value=index)
+ mocker.patch.object(index, "live_ids", return_value=[])
+ cleanup = mocker.spy(index, "compact_orphans")
+
+ result = rig.svc.reconcile_collection_index(rig.collection_id)
+
+ assert result["reconciliation_skipped"] is True
+ cleanup.assert_not_called()
+ assert rig.svc.has_indexed_documents(rig.collection_id)
+ assert rig.session.query(DocumentChunk).count() > 0
+ assert all(
+ row.vector_index_key is None for row in rig.session.query(DocumentChunk)
+ )
+
+
[email protected]("writer", ["serial", "prepared"])
+def test_component_recovery_reloads_metadata_in_encrypted_sessions(
+ tmp_path, monkeypatch, writer
+):
+ from tests.research_library.services.test_collection_rebuild import (
+ RebuildWorld,
+ )
+
+ world = RebuildWorld(
+ tmp_path, monkeypatch, encrypted=True, real_integrity=True
+ )
+ try:
+ with world.service() as service:
+ document_id = world.doc_info[0][0]
+ index = service._get_vector_index(
+ world.collection_id, world.collection_name
+ )
+ if writer == "prepared":
+ prepared = service._prepare_document(
+ document_id, world.collection_id, True
+ )
+ assert prepared["status"] == "prepared", prepared
+ entry = index._store._state()[0]
+ component = segment_directory(index._path) / entry["file"]
+ component.write_bytes(component.read_bytes() + b"corruption")
+
+ result = (
+ service._write_prepared_document(prepared["prepared"])
+ if writer == "prepared"
+ else service.index_document(
+ document_id, world.collection_id, force_reindex=True
+ )
+ )
+
+ assert result["status"] == "success", result
+ assert service.search("Original text", world.collection_id, top_k=1)
+ assert service.integrity_manager.verify_file(
+ index._path, force=True
+ )[0]
+ finally:
+ world.engine.dispose()
+
+
+def _payload(root):
+ directory = segment_directory(root)
+ directory.mkdir()
+ for suffix in (".faiss", ".ids"):
+ (directory / ("a" * 32 + suffix)).write_bytes(b"synthetic vectors")
+ return directory
+
+
+def test_quarantine_retention_removes_complete_generations(tmp_path):
+ service = LibraryRAGService.__new__(LibraryRAGService)
+ path = tmp_path / "index.faiss"
+ for _ in range(_QUARANTINE_KEEP_RECENT + 2):
+ path.write_bytes(b"synthetic manifest")
+ _payload(path)
+ service._quarantine_corrupt_index(path, "synthetic review")
+ roots = {
+ candidate
+ for candidate in tmp_path.glob("index.faiss.corrupt-*")
+ if candidate.is_file()
+ }
+ payloads = set(tmp_path.glob("index.faiss.corrupt-*.segments"))
+ assert len(roots) == _QUARANTINE_KEEP_RECENT
+ assert payloads == {segment_directory(root) for root in roots}
+
+
+def test_retention_sweeps_orphan_payloads_and_refuses_symlinks(tmp_path):
+ service = LibraryRAGService.__new__(LibraryRAGService)
+ path = tmp_path / "index.faiss"
+ orphan = _payload(tmp_path / "index.faiss.corrupt-1")
+ unrelated = _payload(tmp_path / "other.faiss.corrupt-1")
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ sentinel = outside / ("a" * 32 + ".faiss")
+ sentinel.write_bytes(b"unrelated vectors")
+ link = tmp_path / "index.faiss.corrupt-2.segments"
+ link.symlink_to(outside, target_is_directory=True)
+ guarded = _payload(tmp_path / "index.faiss.corrupt-3")
+ (guarded / "unrelated.txt").write_text("keep")
+
+ service._prune_old_quarantined_files(path)
+
+ assert not orphan.exists()
+ assert unrelated.is_dir()
+ assert link.is_symlink()
+ assert sentinel.read_bytes() == b"unrelated vectors"
+ assert (guarded / "unrelated.txt").read_text() == "keep"
+
+
+def test_quarantine_completes_when_segment_relocation_is_refused(tmp_path):
+ """A ValueError from ``relocate_segments`` (its refusal guard) must not
+ abort the quarantine mid-way: the corrupt root is preserved under its
+ quarantine name and the plaintext ``.pkl`` removal is still not optional.
+ """
+ service = LibraryRAGService.__new__(LibraryRAGService)
+ path = tmp_path / "index.faiss"
+ path.write_bytes(b"synthetic manifest")
+ pkl_path = path.with_suffix(".pkl")
+ pkl_path.write_bytes(b"legacy plaintext docstore")
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ sentinel = outside / ("a" * 32 + ".faiss")
+ sentinel.write_bytes(b"sentinel vectors")
+ # A symlinked segments directory trips relocate_segments' refusal guard —
+ # the exact ValueError that used to abort the quarantine mid-way.
+ link = segment_directory(path)
+ link.symlink_to(outside, target_is_directory=True)
+
+ service._quarantine_corrupt_index(path, "synthetic review")
+
+ roots = [
+ candidate
+ for candidate in tmp_path.glob("index.faiss.corrupt-*")
+ if candidate.is_file()
+ ]
+ assert [root.read_bytes() for root in roots] == [b"synthetic manifest"]
+ assert not pkl_path.exists() # plaintext removal is not optional
+ # The refusal guard itself is not weakened: nothing behind the link moved.
+ assert link.is_symlink()
+ assert sentinel.read_bytes() == b"sentinel vectors"
+
+
+def test_quarantine_removes_plaintext_when_relocation_destination_exists(
+ tmp_path, monkeypatch
+):
+ """A pre-existing relocation destination trips ``relocate_segments``'
+ "Vector segment relocation destination already exists" ValueError — the
+ exact escape that used to abort the quarantine mid-way and skip the
+ plaintext ``.pkl`` removal ("Plaintext removal is not optional").
+ """
+ import time as time_module
+
+ service = LibraryRAGService.__new__(LibraryRAGService)
+ path = tmp_path / "index.faiss"
+ path.write_bytes(b"synthetic manifest")
+ pkl_path = path.with_suffix(".pkl")
+ pkl_path.write_bytes(b"legacy plaintext docstore")
+ segments = segment_directory(path)
+ segments.mkdir()
+ (segments / ("a" * 32 + ".faiss")).write_bytes(b"generated segment")
+ # Freeze the quarantine timestamp so the collision is deterministic: a
+ # manually placed destination directory already exists at exactly the
+ # name the quarantine would pick.
+ monkeypatch.setattr(time_module, "time_ns", lambda: 123456789)
+ collision = segment_directory(tmp_path / "index.faiss.corrupt-123456789")
+ collision.mkdir()
+
+ service._quarantine_corrupt_index(path, "synthetic review")
+
+ roots = [
+ candidate
+ for candidate in tmp_path.glob("index.faiss.corrupt-*")
+ if candidate.is_file()
+ ]
+ assert [root.read_bytes() for root in roots] == [b"synthetic manifest"]
+ assert not pkl_path.exists() # plaintext removal is not optional
+ # The refused relocation left the segment payloads in place (never lost).
+ assert (
+ segments / ("a" * 32 + ".faiss")
+ ).read_bytes() == b"generated segment"
+ assert collision.is_dir()
diff --git a/tests/research_library/services/test_rag_vector_lifecycle.py b/tests/research_library/services/test_rag_vector_lifecycle.py
new file mode 100644
index 0000000000..4de44ade53
--- /dev/null
+++ b/tests/research_library/services/test_rag_vector_lifecycle.py
@@ -0,0 +1,436 @@
+"""Index ownership and cleanup regressions using real SQLite and FAISS."""
+
+import json
+import threading
+
+import faiss
+import numpy as np
+import pytest
+from local_deep_research.database.models.library import (
+ Document,
+ DocumentChunk,
+ DocumentCollection,
+ EmbeddingProvider,
+ RagDocumentStatus,
+)
+from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+
+from tests.research_library.services import (
+ test_rag_stats_index_scope as harness,
+)
+
+shared_world = harness.shared_world
+seeded_collection = harness.seeded_collection
+faiss.omp_set_num_threads(2)
+
+
+def report(name, **values):
+ print(json.dumps({"scenario": name, **values}))
+
+
+def make_index(tmp_path):
+ return VectorIndex(
+ username="synthetic",
+ db_password="",
+ embeddings=harness._FakeEmbeddings("synthetic", 4),
+ embedding_model="synthetic",
+ embedding_model_type=EmbeddingProvider.OLLAMA,
+ collection_name="collection_synthetic",
+ dimension=4,
+ path=tmp_path / "rollback.faiss",
+ lock=threading.RLock(),
+ integrity_record=lambda path: None,
+ integrity_verify=lambda path: (True, None),
+ index_type="hnsw",
+ metric="cosine",
+ normalize=True,
+ )
+
+
+def test_shorter_retry_cleans_rollback_orphans(tmp_path, shared_world):
+ session = shared_world
+ index = make_index(tmp_path)
+ index.index(
+ source_type="document",
+ source_id="one-document",
+ chunks=[ChunkInput(text="original")],
+ session=session,
+ )
+ session.commit()
+ index.index(
+ source_type="document",
+ source_id="one-document",
+ chunks=[ChunkInput(text=f"uncommitted {i}") for i in range(4)],
+ session=session,
+ )
+ session.rollback() # The vector file has already been durably replaced.
+ index.index(
+ source_type="document",
+ source_id="one-document",
+ chunks=[ChunkInput(text="successful smaller retry")],
+ session=session,
+ )
+ session.commit()
+ rows = {row.id for row in session.query(DocumentChunk)}
+ live = set(index.live_ids())
+ assert len(rows) == 1
+ assert live == rows
+ report(
+ "rollback_then_shorter_retry",
+ database_rows=len(rows),
+ vectors=len(live),
+ unresolved_vectors=len(live - rows),
+ )
+
+
+def test_successful_delete_purges_historical_model_vectors(
+ shared_world, seeded_collection
+):
+ session = shared_world
+ collection, document, _ = seeded_collection
+ service_a = harness._make_service(
+ "model-A", 8, index_type="hnsw", chunk_size=80, chunk_overlap=10
+ )
+ service_b = harness._make_service(
+ "model-B", 8, index_type="hnsw", chunk_size=80, chunk_overlap=10
+ )
+ for service in [service_a, service_b]:
+ result = service.index_document(
+ document, collection, force_reindex=True
+ )
+ assert result["status"] == "success", result
+ name = f"collection_{collection}"
+ index_a = service_a._get_vector_index(collection, name)
+ before = index_a.count()
+ removed = service_b.purge_document_vectors(document, collection)
+ remaining_rows = (
+ session.query(DocumentChunk).filter_by(source_id=document).count()
+ )
+ assert removed > 0 and before > 0
+ assert remaining_rows == 0
+ index_a = service_a._get_vector_index(collection, name)
+ assert index_a.count() == 0
+ report(
+ "successful_delete_current_model",
+ current_vectors_removed=removed,
+ database_rows_remaining=remaining_rows,
+ historical_orphan_vectors=index_a.count(),
+ )
+
+
+def test_same_model_configuration_roundtrip_preserves_ownership(
+ shared_world, seeded_collection
+):
+ session = shared_world
+ collection, document, _ = seeded_collection
+ services = [
+ harness._make_service(
+ "same-model",
+ 8,
+ index_type="hnsw",
+ chunk_size=size,
+ chunk_overlap=10,
+ )
+ for size in [80, 120]
+ ]
+ name = f"collection_{collection}"
+ history = []
+ for step, service in enumerate([services[0], services[1], services[0]]):
+ result = service.index_document(
+ document, collection, force_reindex=True
+ )
+ assert result["status"] == "success", result
+ index = service._get_vector_index(collection, name)
+ rows = {
+ row.id
+ for row in session.query(DocumentChunk).filter_by(
+ source_id=document, vector_index_key=index.index_key
+ )
+ }
+ live = set(index.live_ids())
+ history.append(
+ dict(
+ step=step,
+ chunk_size=service.chunk_size,
+ database_rows=len(rows),
+ vectors=len(live),
+ orphan_vectors=len(live - rows),
+ )
+ )
+ assert history[-1]["orphan_vectors"] == 0
+ assert history[-1]["vectors"] == history[0]["vectors"] > 0
+ report("same_model_configuration_A_B_A", history=history)
+
+
+def test_reconciliation_preserves_valid_partial_document(
+ shared_world, seeded_collection
+):
+ session = shared_world
+ collection, document, _ = seeded_collection
+ service = harness._make_service(
+ "same-model", 8, index_type="hnsw", chunk_size=80, chunk_overlap=10
+ )
+ result = service.index_document(document, collection, force_reindex=True)
+ assert result["status"] == "success", result
+ index = service._get_vector_index(collection, f"collection_{collection}")
+ ids = index.live_ids()
+ assert len(ids) > 1
+ index._store.apply(add_ids=[], add_vectors=None, remove_ids=[ids[0]])
+ result = service.reconcile_collection_index(collection)
+ live = set(index.live_ids())
+ rows = {
+ row.id
+ for row in session.query(DocumentChunk).filter_by(
+ source_id=document, vector_index_key=index.index_key
+ )
+ }
+ assert live and live.issubset(rows)
+ assert result["orphan_vectors"] == 0
+ assert result["partial_document_vectors"] == len(live)
+ assert (
+ set(
+ service._get_vector_index(
+ collection, f"collection_{collection}"
+ ).live_ids()
+ )
+ == live
+ )
+ assert result["indexed_documents"] == 0
+ report(
+ "partial_document_orphan_metric",
+ **result,
+ actual_vectors_without_chunk_rows=len(live - rows),
+ )
+
+
+def test_bulk_delete_applies_once_per_historical_index(
+ shared_world, seeded_collection, monkeypatch
+):
+ from local_deep_research.vector_stores.implementations.segmented_faiss import (
+ SegmentedFaissStore,
+ )
+
+ collection, first, second = seeded_collection
+ services = [
+ harness._make_service(
+ model, 8, index_type="hnsw", chunk_size=80, chunk_overlap=10
+ )
+ for model in ("model-A", "model-B")
+ ]
+ for service in services:
+ for document in (first, second):
+ assert (
+ service.index_document(
+ document, collection, force_reindex=True
+ )["status"]
+ == "success"
+ )
+ calls = []
+ original = SegmentedFaissStore.apply
+
+ def observed(store, **kwargs):
+ calls.append(store._path)
+ return original(store, **kwargs)
+
+ monkeypatch.setattr(SegmentedFaissStore, "apply", observed)
+ assert services[0].purge_documents_vectors([first, second], collection) > 0
+ assert len(calls) == len(set(calls)) == 2
+ assert shared_world.query(DocumentChunk).count() == 0
+
+
+def test_cleanup_repairs_orphans_from_older_writers_before_id_reuse(
+ tmp_path, shared_world
+):
+ index = make_index(tmp_path)
+ index.index(
+ source_type="document",
+ source_id="one",
+ chunks=[ChunkInput(text="committed")],
+ )
+ # Simulate an older writer/process exit that persisted IDs with no rows.
+ index._store.apply(
+ add_ids=[2, 3, 4], add_vectors=np.ones((3, 4), dtype="float32")
+ )
+ index.index(
+ source_type="document",
+ source_id="one",
+ chunks=[ChunkInput(text="replacement")],
+ )
+ rows = {row.id for row in shared_world.query(DocumentChunk)}
+ assert set(index.live_ids()) == rows
+ assert len(rows) == 1
+
+
[email protected]("delete_parent", [False, True])
+def test_reconciliation_collects_deleted_or_unlinked_documents(
+ shared_world, seeded_collection, delete_parent
+):
+ session = shared_world
+ collection, first, second = seeded_collection
+ service = harness._make_service(
+ "same-model", 8, index_type="hnsw", chunk_size=80, chunk_overlap=10
+ )
+ for document in (first, second):
+ assert (
+ service.index_document(document, collection)["status"] == "success"
+ )
+ index = service._get_vector_index(collection, f"collection_{collection}")
+ original = index.count()
+ survivor_ids = {
+ row.id
+ for row in session.query(DocumentChunk).filter_by(source_id=second)
+ }
+ # Reproduce the best-effort post-delete purge being unavailable.
+ session.query(RagDocumentStatus).filter_by(document_id=first).delete()
+ session.query(DocumentCollection).filter_by(
+ document_id=first, collection_id=collection
+ ).delete()
+ if delete_parent:
+ session.query(Document).filter_by(id=first).delete()
+ session.commit()
+ result = service.reconcile_collection_index(collection)
+ assert set(index.live_ids()) == survivor_ids
+ assert session.query(DocumentChunk).filter_by(source_id=first).count() == 0
+ assert result["orphan_vectors"] == 0
+ assert result["orphan_vectors_removed"] == original - len(survivor_ids) > 0
+ assert result["indexed_documents"] == 1
+
+
+def test_bulk_cleanup_respects_sqlite_parameter_limit(tmp_path, shared_world):
+ import sqlite3
+
+ index = make_index(tmp_path)
+ index.index(
+ source_type="file",
+ source_id="batch",
+ chunks=[ChunkInput(text=f"chunk {i}") for i in range(1100)],
+ )
+ for row in shared_world.query(DocumentChunk):
+ row.source_id = str(row.id)
+ shared_world.commit()
+ connection = shared_world.connection().connection.driver_connection
+ previous = connection.setlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, 999)
+ try:
+ ids = [str(value) for value in index.live_ids()]
+ removed = index.delete_sources(source_type="file", source_ids=ids)
+ assert removed.rows_deleted == removed.removed == 1100
+ assert index.count() == shared_world.query(DocumentChunk).count() == 0
+ finally:
+ connection.setlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER, previous)
+
+
[email protected]("settle", ["commit", "rollback"])
+def test_bulk_purge_waits_for_writer_before_checkpoint_recovery(
+ tmp_path, monkeypatch, settle
+):
+ """An active writer's checkpoint must never look like crash recovery."""
+ from local_deep_research.research_library.services import (
+ library_rag_service,
+ )
+ from local_deep_research.security.file_integrity.integrity_manager import (
+ FileIntegrityManager,
+ )
+ from tests.research_library.services.test_collection_rebuild import (
+ RebuildWorld,
+ )
+
+ world = RebuildWorld(
+ tmp_path, monkeypatch, encrypted=True, real_integrity=True
+ )
+ survivor, deleted = [doc_id for doc_id, _ in world.doc_info]
+ attempted = threading.Event()
+ writer_settled = threading.Event()
+ verification_before_settlement = []
+ errors = []
+ removed = []
+ lock = library_rag_service._get_collection_lock(
+ "rebuild-user", world.collection_id, purpose="transaction"
+ )
+ original_acquire = type(lock).acquire
+ original_verify = FileIntegrityManager.verify_file
+
+ def observe_acquire(candidate, *args, **kwargs):
+ if candidate is lock and threading.current_thread() is worker:
+ attempted.set()
+ return original_acquire(candidate, *args, **kwargs)
+
+ def observe_verify(manager, *args, **kwargs):
+ if threading.current_thread() is worker:
+ verification_before_settlement.append(not writer_settled.is_set())
+ try:
+ return original_verify(manager, *args, **kwargs)
+ finally:
+ # Also wake the test if the collection lock is missing.
+ attempted.set()
+ return original_verify(manager, *args, **kwargs)
+
+ def purge():
+ try:
+ with world.service() as service:
+ removed.append(
+ service.purge_documents_vectors(
+ [deleted], world.collection_id
+ )
+ )
+ except BaseException as exc:
+ errors.append(exc)
+
+ worker = threading.Thread(target=purge)
+ monkeypatch.setattr(type(lock), "acquire", observe_acquire)
+ monkeypatch.setattr(FileIntegrityManager, "verify_file", observe_verify)
+ try:
+ with (
+ world.service() as service,
+ library_rag_service._hold_collection_lock(
+ service.username, world.collection_id, purpose="transaction"
+ ),
+ world.session() as session,
+ ):
+ index = service._get_vector_index(
+ world.collection_id, world.collection_name
+ )
+ old_ids = {
+ row.id
+ for row in session.query(DocumentChunk).filter_by(
+ source_id=survivor
+ )
+ }
+ index.index(
+ source_type="document",
+ source_id=survivor,
+ chunks=[ChunkInput(text="Replacement survivor text")],
+ session=session,
+ )
+ new_ids = {
+ row.id
+ for row in session.query(DocumentChunk).filter_by(
+ source_id=survivor
+ )
+ }
+ assert new_ids and new_ids.isdisjoint(old_ids)
+ pending_manifest = index._path.read_bytes()
+ worker.start()
+ assert attempted.wait(10), "Bulk purge did not start"
+ assert not verification_before_settlement
+ assert index._path.read_bytes() == pending_manifest
+ getattr(session, settle)()
+ writer_settled.set()
+ worker.join(timeout=10)
+ assert not worker.is_alive()
+ assert not errors
+ assert removed and removed[0] > 0
+ assert verification_before_settlement
+ assert not any(verification_before_settlement)
+ with world.service() as service, world.session() as session:
+ rows = {row.id for row in session.query(DocumentChunk)}
+ expected = new_ids if settle == "commit" else old_ids
+ assert rows == expected
+ index = service._get_vector_index(
+ world.collection_id, world.collection_name
+ )
+ assert set(index.live_ids()) == expected
+ assert service.integrity_manager.verify_file(index._path)[0]
+ finally:
+ if worker.ident is not None and worker.is_alive():
+ worker.join(timeout=10)
+ world.engine.dispose()
diff --git a/tests/research_library/services/test_reconcile_collection_index.py b/tests/research_library/services/test_reconcile_collection_index.py
index 706d7edcca..cca5582eb4 100644
--- a/tests/research_library/services/test_reconcile_collection_index.py
+++ b/tests/research_library/services/test_reconcile_collection_index.py
@@ -65,6 +65,7 @@ def _build_query_mock(*, all_rows=None, first_row=None):
q.delete.return_value = q
if all_rows is not None:
q.all.return_value = all_rows
+ q.first.return_value = all_rows[0] if all_rows else None
if first_row is not None:
q.first.return_value = first_row
return q
diff --git a/tests/research_library/services/test_text_index_invalidation.py b/tests/research_library/services/test_text_index_invalidation.py
index 0bc4ff4c1f..8a83d35a53 100644
--- a/tests/research_library/services/test_text_index_invalidation.py
+++ b/tests/research_library/services/test_text_index_invalidation.py
@@ -1,7 +1,7 @@
"""Text replacement and index persistence serialize across real SQLite sessions."""
from contextlib import nullcontext
-from types import MethodType, SimpleNamespace
+from types import SimpleNamespace
import pytest
from sqlalchemy import event
@@ -39,6 +39,11 @@ class MemoryVectors:
def live_ids(self):
return list(self.ids)
+ def iter_id_batches(self):
+ ids = self.live_ids()
+ for start in range(0, len(ids), 500):
+ yield ids[start : start + 500]
+
def apply(self, *, add_ids, add_vectors, remove_ids):
self.ids.difference_update(remove_ids)
self.ids.update(add_ids)
@@ -48,10 +53,10 @@ class MemoryVectors:
def indexer_for(case, collection="library"):
with case.sessions() as session:
- index_id = (
- session.query(RAGIndex.id)
+ index_id, index_key = (
+ session.query(RAGIndex.id, RAGIndex.index_hash)
.filter_by(collection_name=f"collection_{collection}")
- .scalar()
+ .one()
)
chunk_ids = [
row[0]
@@ -61,12 +66,16 @@ def indexer_for(case, collection="library"):
]
backend = VectorIndex.__new__(VectorIndex)
backend.collection_name = f"collection_{collection}"
+ backend.index_key = index_key
+ backend.require_document_membership = True
+ backend.membership_collection_id = collection
backend.embedding_model = "test"
backend.embedding_model_type = EmbeddingProvider.SENTENCE_TRANSFORMERS
backend._store = MemoryVectors(chunk_ids)
- obj = SimpleNamespace(
+ obj = LibraryRAGService.__new__(LibraryRAGService)
+ obj.__dict__.update(
username=case.service.username,
- db_password=case.service.password,
+ _db_password=case.service.password,
rag_index_record=SimpleNamespace(id=index_id),
embedding_model="test",
embedding_provider="sentence_transformers",
@@ -84,9 +93,6 @@ def indexer_for(case, collection="library"):
)
),
)
- obj._flag_document_for_reindex = MethodType(
- LibraryRAGService._flag_document_for_reindex, obj
- )
return obj, backend
diff --git a/tests/research_library/test_document_full_lifecycle.py b/tests/research_library/test_document_full_lifecycle.py
index ac70ad6c84..876fc4493d 100644
--- a/tests/research_library/test_document_full_lifecycle.py
+++ b/tests/research_library/test_document_full_lifecycle.py
@@ -1,7 +1,7 @@
"""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
+on-disk FAISS backend and a real (in-memory) encrypted-DB-shaped
SQLite session.
Mirrors the real-components harness style of
@@ -27,6 +27,7 @@ Each phase asserts on OBSERVABLE real state, never on a mock:
import hashlib
import uuid
from contextlib import contextmanager
+from pathlib import Path
from unittest.mock import MagicMock
import numpy as np
@@ -35,7 +36,6 @@ 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,
@@ -197,11 +197,6 @@ def rag_service(lifecycle_env):
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(
@@ -251,9 +246,18 @@ class TestDocumentFullLifecycle:
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]
+ # One registered index may contain multiple immutable segment files.
+ # Resolve its public path from the DB rather than counting every
+ # native .faiss file beneath the storage directory.
+ assert (
+ session.query(RAGIndex)
+ .filter_by(collection_name=f"collection_{collection_id}")
+ .count()
+ == 1
+ )
+ rag_index_row = _current_rag_index_row(session, collection_id)
+ assert rag_index_row is not None
+ faiss_path = Path(rag_index_row.index_path)
assert faiss_path.is_file()
assert faiss_path.stat().st_size > 0
@@ -261,8 +265,6 @@ class TestDocumentFullLifecycle:
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"
diff --git a/tests/security/test_library_rag_security_fastapi.py b/tests/security/test_library_rag_security_fastapi.py
index d9f2e35e89..b5672cfab4 100644
--- a/tests/security/test_library_rag_security_fastapi.py
+++ b/tests/security/test_library_rag_security_fastapi.py
@@ -1079,6 +1079,7 @@ class TestSanitizedIndexingErrors:
_WITHHELD_SERVICE_ERRORS = frozenset(
{
"Operation failed: {}",
+ "Operation failed: VectorStoreIntegrityError",
"Indexing failed: {}",
"Worker crashed: {}",
"Indexing must run outside an existing database session",
diff --git a/tests/vector_stores/test_config_provider_resolution.py b/tests/vector_stores/test_config_provider_resolution.py
index 3a52107398..c469a7079d 100644
--- a/tests/vector_stores/test_config_provider_resolution.py
+++ b/tests/vector_stores/test_config_provider_resolution.py
@@ -19,8 +19,8 @@ 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,
+from local_deep_research.vector_stores.implementations.segmented_faiss import (
+ SegmentedFaissStore,
)
@@ -36,8 +36,8 @@ def test_get_vector_store_class_unknown_provider_raises_valueerror():
def test_get_vector_store_class_normalizes_dirty_provider():
dirty = ' "FAISS" '
- assert get_vector_store_class(provider=dirty) is FaissVectorStore
+ assert get_vector_store_class(provider=dirty) is SegmentedFaissStore
# 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
+ assert get_vector_store_class(provider="") is SegmentedFaissStore
diff --git a/tests/vector_stores/test_facade.py b/tests/vector_stores/test_facade.py
index 9c00a3e43e..140db6d8ed 100644
--- a/tests/vector_stores/test_facade.py
+++ b/tests/vector_stores/test_facade.py
@@ -17,7 +17,7 @@ from contextlib import contextmanager
import numpy as np
import pytest
from langchain_core.embeddings import Embeddings
-from sqlalchemy import create_engine
+from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from local_deep_research.database.models import Base
@@ -25,7 +25,12 @@ from local_deep_research.database.models.library import (
DocumentChunk,
EmbeddingProvider,
)
-from local_deep_research.vector_stores.facade import ChunkInput, VectorIndex
+from local_deep_research.vector_stores.base import VectorStoreIntegrityError
+from local_deep_research.vector_stores.facade import (
+ ChunkInput,
+ VectorIndex,
+ _settle_vectors,
+)
# --------------------------------------------------------------------------
@@ -655,13 +660,9 @@ class TestSearch:
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"]
+ # The orphan must not consume a result slot. Fetch the next valid
+ # result while preserving the store's relevance order across the gap.
+ assert [r.text for r in results] == ["sim-high", "sim-3rd", "sim-low"]
def test_search_carries_source_and_title_fields(self, tmp_path, patched_db):
vi = _make_index(tmp_path)
@@ -675,6 +676,41 @@ class TestSearch:
assert results[0].source_id == "doc-42"
assert results[0].document_title == "T"
+ @pytest.mark.parametrize("top_k", [1, 3, 501])
+ def test_search_materializes_only_requested_rows(
+ self, tmp_path, patched_db, mocker, top_k
+ ):
+ vi = _make_index(tmp_path, metric="l2", normalize=False)
+ count = 512
+ vi.index_prepared(
+ source_type="file",
+ source_id="sample",
+ chunks=[ChunkInput(text=f"sample chunk {i}") for i in range(count)],
+ vectors=np.ones((count, 4), dtype="float32"),
+ )
+ vi._store.apply(
+ add_ids=list(range(100_000, 100_000 + count)),
+ add_vectors=np.zeros((count, 4), dtype="float32"),
+ )
+ patched_db.expunge_all()
+ mocker.patch.object(
+ vi.embeddings, "embed_query", return_value=[0.0] * 4
+ )
+ materialized = set()
+
+ def on_load(row, _context):
+ materialized.add(row.id)
+
+ event.listen(DocumentChunk, "load", on_load)
+ try:
+ results = vi.search("sample", top_k=top_k)
+ finally:
+ event.remove(DocumentChunk, "load", on_load)
+
+ assert len(results) == top_k
+ assert all(result.source_id == "sample" for result in results)
+ assert materialized == {result.chunk_id for result in results}
+
# --------------------------------------------------------------------------
# delete()
@@ -887,3 +923,46 @@ class TestDeleteIds:
assert stats.removed == 1
assert stats.rows_deleted == 0 # row was already gone
assert vi.count() == 0
+
+
+# --------------------------------------------------------------------------
+# Settle wrapper: an unloadable-generation failure must surface, while a
+# recoverable cleanup failure stays contained
+# --------------------------------------------------------------------------
+class _FakeSession:
+ def __init__(self):
+ self.info = {}
+
+ def in_nested_transaction(self):
+ return False
+
+
+class _FailingStore:
+ def __init__(self, exc):
+ self._exc = exc
+
+ def end_transaction(self, *, committed):
+ raise self._exc
+
+
+def test_settle_surfaces_integrity_failures_not_swallow_them():
+ """A settle failure that indicates an unloadable vector generation must
+ not vanish behind the log line used for recoverable cleanup failures —
+ the caller must not report success over it."""
+ session = _FakeSession()
+ session.info["ldr_vector_transactions"] = {
+ "x": _FailingStore(VectorStoreIntegrityError("unloadable generation"))
+ }
+ with pytest.raises(VectorStoreIntegrityError):
+ _settle_vectors(session, True)
+ assert "ldr_vector_transactions" not in session.info
+
+
+def test_settle_still_contains_recoverable_cleanup_failures():
+ """A plain cleanup failure (the checkpoint remains recoverable against
+ the committed checksum) is logged, not raised."""
+ session = _FakeSession()
+ session.info["ldr_vector_transactions"] = {
+ "x": _FailingStore(OSError("simulated disk failure"))
+ }
+ _settle_vectors(session, True)
diff --git a/tests/vector_stores/test_faiss_store.py b/tests/vector_stores/test_faiss_store.py
index f375e76e7b..0bc5e668a9 100644
--- a/tests/vector_stores/test_faiss_store.py
+++ b/tests/vector_stores/test_faiss_store.py
@@ -1001,6 +1001,34 @@ class TestHnswOffLockRetryExhaustion:
assert set(store.live_ids()) == {1, 3}
assert store.count() == 2
+ def test_rejected_survivor_buffers_are_released_before_retry(
+ self, tmp_path, monkeypatch
+ ):
+ import itertools
+ import weakref
+
+ store = _make_store(tmp_path, index_type="hnsw", dimension=4)
+ store.apply(add_ids=[1, 2, 3], add_vectors=_vecs(3, dim=4))
+ generations = itertools.count()
+ monkeypatch.setattr(
+ store, "_file_fingerprint", lambda: (next(generations),)
+ )
+ original = np.empty
+ buffers = []
+
+ def allocate(shape, *args, **kwargs):
+ if shape == (2, 4):
+ assert all(reference() is None for reference in buffers)
+ result = original(shape, *args, **kwargs)
+ if shape == (2, 4):
+ buffers.append(weakref.ref(result))
+ return result
+
+ monkeypatch.setattr(np, "empty", allocate)
+ store.apply(add_ids=[], add_vectors=None, remove_ids=[2])
+ assert len(buffers) == 4 # Three rejected attempts and the fallback.
+ assert set(store.live_ids()) == {1, 3}
+
class TestApplyFailureRecovery:
"""apply()'s failure paths (_restore_from_disk / _reload_under_lock's
diff --git a/tests/vector_stores/test_full_migration_lifecycle.py b/tests/vector_stores/test_full_migration_lifecycle.py
index 6c1565bde2..1148d94028 100644
--- a/tests/vector_stores/test_full_migration_lifecycle.py
+++ b/tests/vector_stores/test_full_migration_lifecycle.py
@@ -53,6 +53,7 @@ from local_deep_research.database.models.library import (
Collection,
Document,
DocumentChunk,
+ DocumentCollection,
DocumentStatus,
EmbeddingProvider,
RAGIndex,
@@ -258,6 +259,26 @@ class TestFullMigrationLifecycle:
session.commit()
legacy_source_id = "legacy-doc-1"
+ session.add(
+ Document(
+ id=legacy_source_id,
+ source_type_id=source_type.id,
+ document_hash=hashlib.sha256(
+ "".join(legacy_texts).encode()
+ ).hexdigest(),
+ title="Legacy document",
+ text_content="\n".join(legacy_texts),
+ file_size=sum(map(len, legacy_texts)),
+ file_type="txt",
+ status=DocumentStatus.COMPLETED,
+ )
+ )
+ session.add(
+ DocumentCollection(
+ document_id=legacy_source_id, collection_id=collection_id
+ )
+ )
+ session.commit()
legacy_ids = [
_add_chunk(
session,
diff --git a/tests/vector_stores/test_integrity_tamper_lifecycle.py b/tests/vector_stores/test_integrity_tamper_lifecycle.py
index 63a2f95048..1fcaab4fdc 100644
--- a/tests/vector_stores/test_integrity_tamper_lifecycle.py
+++ b/tests/vector_stores/test_integrity_tamper_lifecycle.py
@@ -247,7 +247,11 @@ def rig(tmp_path, monkeypatch, mocker, request):
def _quarantine_files(index_path):
- return list(index_path.parent.glob(f"{index_path.name}.corrupt-*"))
+ return [
+ path
+ for path in index_path.parent.glob(f"{index_path.name}.corrupt-*")
+ if path.is_file()
+ ]
class TestWritePathRecoversFromTamper:
@@ -290,12 +294,12 @@ class TestWritePathRecoversFromTamper:
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
+ # The authenticated segmented root must reopen through the provider.
+ from local_deep_research.vector_stores.implementations.segmented_faiss import (
+ is_segmented,
+ )
- raw = faiss_mod.read_index(str(index_path))
- assert isinstance(raw, faiss_mod.IndexIDMap2)
- assert raw.ntotal > 0
+ assert is_segmented(index_path)
# 3) The rebuilt file's checksum was re-recorded by the real
# integrity manager (not left pointing at stale/tampered bytes).
@@ -424,3 +428,107 @@ class TestReadPathFailsClosed:
# silently adopt the tampered bytes as the new "good" checksum).
record_after = rig.integrity_record(index_path)
assert record_after.checksum == baseline_checksum
+
+
+ "interrupted", [False, True], ids=["rollback", "process-exit"]
+)
+def test_uncommitted_manifest_recovers_the_previous_searchable_generation(
+ rig, interrupted
+):
+ from local_deep_research.vector_stores.facade import ChunkInput
+ from local_deep_research.vector_stores.segment_files import checkpoint_path
+
+ path = rig.index_path()
+ original = path.read_bytes()
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ original_ids = set(index.live_ids())
+ index.index(
+ source_type="document",
+ source_id=rig.document_id,
+ chunks=[ChunkInput(text="uncommitted replacement")],
+ session=rig.session,
+ )
+ assert path.read_bytes() != original
+ assert checkpoint_path(path).is_file()
+ if interrupted:
+ # Simulate a process exit: SQLite rolls back, Python callbacks do not run.
+ rig.session.info.pop("ldr_vector_transactions")
+ rig.session.rollback()
+ hits = rig.svc.search(SECRET, rig.collection_id, top_k=5)
+ assert hits and any(SECRET in hit.text for hit in hits)
+ assert path.read_bytes() == original
+ assert (
+ set(
+ rig.svc._get_vector_index(
+ rig.collection_id, rig.collection_name
+ ).live_ids()
+ )
+ == original_ids
+ )
+ assert not checkpoint_path(path).exists()
+ assert _quarantine_files(path) == []
+
+
+def test_committed_manifest_is_not_reverted_by_an_old_checkpoint(rig):
+ from local_deep_research.vector_stores.facade import ChunkInput
+ from local_deep_research.vector_stores.segment_files import checkpoint_path
+
+ path = rig.index_path()
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ index.index(
+ source_type="document",
+ source_id=rig.document_id,
+ chunks=[ChunkInput(text="committed replacement")],
+ session=rig.session,
+ )
+ new_manifest = path.read_bytes()
+ rig.session.info.pop("ldr_vector_transactions")
+ rig.session.commit() # Simulate exit after commit but before retirement.
+ assert checkpoint_path(path).exists()
+ hits = rig.svc.search("committed replacement", rig.collection_id, top_k=5)
+ assert [hit.text for hit in hits] == ["committed replacement"]
+ assert path.read_bytes() == new_manifest
+
+
+def test_recovery_refuses_a_checkpoint_not_authenticated_by_the_database(rig):
+ from local_deep_research.vector_stores.facade import ChunkInput
+ from local_deep_research.vector_stores.segment_files import checkpoint_path
+
+ path = rig.index_path()
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ index.index(
+ source_type="document",
+ source_id=rig.document_id,
+ chunks=[ChunkInput(text="uncommitted")],
+ session=rig.session,
+ )
+ rig.session.info.pop("ldr_vector_transactions")
+ rig.session.rollback()
+ checkpoint_path(path).write_bytes(b"untrusted replacement")
+ new_manifest = path.read_bytes()
+ with pytest.raises(RuntimeError, match="Integrity"):
+ rig.svc.search(SECRET, rig.collection_id, top_k=5)
+ assert path.read_bytes() == new_manifest
+
+
+def test_nested_write_is_refused_before_changing_vector_files(rig):
+ from local_deep_research.vector_stores.facade import ChunkInput
+
+ path = rig.index_path()
+ original = path.read_bytes()
+ index = rig.svc._get_vector_index(rig.collection_id, rig.collection_name)
+ with pytest.raises(RuntimeError, match="outer database transaction"):
+ with rig.session.begin_nested():
+ index.index(
+ source_type="document",
+ source_id=rig.document_id,
+ chunks=[ChunkInput(text="nested replacement")],
+ session=rig.session,
+ )
+ rig.session.commit()
+ assert path.read_bytes() == original
+ assert any(
+ SECRET in hit.text
+ for hit in rig.svc.search(SECRET, rig.collection_id, top_k=5)
+ )
diff --git a/tests/vector_stores/test_legacy_rekey_orchestrator.py b/tests/vector_stores/test_legacy_rekey_orchestrator.py
index 8b460d1a80..c6ab664622 100644
--- a/tests/vector_stores/test_legacy_rekey_orchestrator.py
+++ b/tests/vector_stores/test_legacy_rekey_orchestrator.py
@@ -290,8 +290,6 @@ class TestAllRowsSwept:
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,
@@ -468,8 +466,6 @@ class TestFullRoundTrip:
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,
@@ -613,7 +609,11 @@ class TestNoSidecarBranchDispatch:
faiss_path = tmp_path / "mig.faiss"
pkl_path = tmp_path / "mig.pkl"
- store_cls = get_vector_store_class()
+ from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+ )
+
+ store_cls = FaissVectorStore
store = store_cls.create(
dimension=2,
index_type="flat",
diff --git a/tests/vector_stores/test_segmented_faiss.py b/tests/vector_stores/test_segmented_faiss.py
new file mode 100644
index 0000000000..f0110204f1
--- /dev/null
+++ b/tests/vector_stores/test_segmented_faiss.py
@@ -0,0 +1,414 @@
+"""Real native FAISS persistence, bounded mutation, and recovery contracts."""
+
+import hashlib
+import json
+import os
+from pathlib import Path
+import threading
+import time
+
+import numpy as np
+import pytest
+
+from local_deep_research.vector_stores.implementations import (
+ segmented_faiss as module,
+)
+from local_deep_research.vector_stores.implementations.faiss_store import (
+ FaissVectorStore,
+)
+
+
+def binding(tmp_path):
+ checksums = {}
+
+ def record(path):
+ checksums[str(path)] = hashlib.sha256(path.read_bytes()).digest()
+
+ def verify(path):
+ return (
+ checksums.get(str(path))
+ == hashlib.sha256(path.read_bytes()).digest(),
+ "checksum",
+ )
+
+ return dict(
+ path=tmp_path / "index.faiss",
+ dimension=8,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ lock=threading.RLock(),
+ integrity_record=record,
+ integrity_verify=verify,
+ )
+
+
+def vectors(n, seed=5):
+ return np.random.default_rng(seed).random((n, 8), dtype=np.float32)
+
+
+def state(path):
+ return json.loads(path.read_bytes()[len(module.MAGIC) :])["segments"]
+
+
+def test_append_reuses_full_segments_and_searches_all(binding, monkeypatch):
+ monkeypatch.setattr(module, "SEGMENT_VECTORS", 4)
+ store = module.SegmentedFaissStore.create(**binding)
+ original = vectors(12)
+ store.apply(add_ids=list(range(1, 13)), add_vectors=original)
+ before = state(binding["path"])
+ store.apply(add_ids=[13], add_vectors=vectors(1, 13))
+ after = state(binding["path"])
+ assert after[:3] == before
+ assert all(entry["count"] <= 4 for entry in after)
+ fresh = module.SegmentedFaissStore.load(**binding)
+ assert fresh.count() == 13
+ for position in (0, 4, 11):
+ assert fresh.search(original[position], 1)[0][0] == position + 1
+ assert fresh.search(vectors(1, 13)[0], 1)[0][0] == 13
+
+
[email protected]("index_type", ["flat", "hnsw"])
+def test_replace_delete_and_legacy_conversion(binding, monkeypatch, index_type):
+ monkeypatch.setattr(module, "SEGMENT_VECTORS", 4)
+ binding["index_type"] = index_type
+ old = FaissVectorStore.create(**binding)
+ original = vectors(11)
+ old.apply(add_ids=list(range(1, 12)), add_vectors=original)
+ from local_deep_research.vector_stores.legacy_rekey import _is_idmap2
+
+ native_read = module.faiss.read_index
+
+ def mapped_read(path, flags=0):
+ assert flags & module.faiss.IO_FLAG_MMAP_IFC
+ assert flags & module.faiss.IO_FLAG_READ_ONLY
+ return native_read(path, flags)
+
+ with monkeypatch.context() as check:
+ check.setattr(module.faiss, "read_index", mapped_read)
+ assert _is_idmap2(binding["path"]) is True
+ store = module.SegmentedFaissStore.load(**binding)
+ assert store.count() == 11
+ assert store.search(original[6], 1)[0][0] == 7
+ replacement = vectors(1, 41)
+ result = store.apply(
+ add_ids=[7], add_vectors=replacement, remove_ids=[1, 4]
+ )
+ assert result == {"added": 1, "removed": 3}
+ fresh = module.SegmentedFaissStore.load(**binding)
+ assert set(fresh.live_ids()) == set(range(1, 12)) - {1, 4}
+ np.testing.assert_allclose(fresh.reconstruct(7), replacement[0])
+ np.testing.assert_allclose(fresh.reconstruct(10), original[9])
+ assert fresh.reconstruct(1) is None
+
+
+def test_failure_before_publication_preserves_old_generation(
+ binding, monkeypatch
+):
+ monkeypatch.setattr(module, "SEGMENT_VECTORS", 4)
+ store = module.SegmentedFaissStore.create(**binding)
+ store.apply(add_ids=list(range(1, 10)), add_vectors=vectors(9))
+ before = binding["path"].read_bytes()
+ original = store._write
+ calls = 0
+
+ def fail_after_one_segment(index):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise OSError("simulated disk failure")
+ return original(index)
+
+ monkeypatch.setattr(store, "_write", fail_after_one_segment)
+ with pytest.raises(OSError, match="disk failure"):
+ store.apply(add_ids=[10, 11, 12, 13, 14], add_vectors=vectors(5))
+ assert binding["path"].read_bytes() == before
+ assert set(module.SegmentedFaissStore.load(**binding).live_ids()) == set(
+ range(1, 10)
+ )
+
+
[email protected]("suffix", [".faiss", ".ids"])
+def test_segment_tampering_is_refused(binding, suffix):
+ store = module.SegmentedFaissStore.create(**binding)
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+ entry = state(binding["path"])[0]
+ path = (
+ module.segment_directory(binding["path"]) / entry["file"]
+ ).with_suffix(suffix)
+ path.write_bytes(path.read_bytes() + b"tamper")
+ with pytest.raises(ValueError, match="checksum"):
+ store.search(vectors(1)[0], 1)
+
+
+def test_fresh_instances_merge_writes_and_purge_once(binding, monkeypatch):
+ monkeypatch.setattr(module, "SEGMENT_VECTORS", 4)
+ a = module.SegmentedFaissStore.create(**binding)
+ a.apply(add_ids=[1, 2, 3, 4], add_vectors=vectors(4))
+ b = module.SegmentedFaissStore.load(**binding)
+ a.apply(add_ids=[5, 6, 7, 8], add_vectors=vectors(4, 8))
+ b.apply(add_ids=[9], add_vectors=vectors(1, 9), remove_ids=[1, 6])
+ assert set(a.live_ids()) == {2, 3, 4, 5, 7, 8, 9}
+ retained = {entry["file"] for entry in state(binding["path"])}
+ assert {
+ path.name
+ for path in module.segment_directory(binding["path"]).glob("*.faiss")
+ } == retained
+
+
[email protected]("initial", [False, True])
+def test_integrity_record_failure_restores_previous_root(binding, initial):
+ # A plain Lock also proves checkpoint coordination never re-enters it.
+ binding["lock"] = threading.Lock()
+ store = module.SegmentedFaissStore.create(**binding)
+ if initial:
+ store.apply(add_ids=[1, 2], add_vectors=vectors(2))
+ before = binding["path"].read_bytes() if initial else None
+
+ def fail_record(_path):
+ raise OSError("checksum database write failed")
+
+ store._record = fail_record
+ with pytest.raises(OSError, match="checksum database"):
+ store.apply(add_ids=[3], add_vectors=vectors(1, 3))
+ if initial:
+ assert binding["path"].read_bytes() == before
+ assert module.SegmentedFaissStore.load(**binding).live_ids() == [1, 2]
+ else:
+ assert not binding["path"].exists()
+ assert not module.checkpoint_path(binding["path"]).exists()
+ retained = (
+ {entry["file"] for entry in state(binding["path"])}
+ if initial
+ else set()
+ )
+ assert {
+ path.name
+ for path in module.segment_directory(binding["path"]).glob("*.faiss")
+ } == retained
+
+
+ "manifest",
+ [[], {}, {"segments": None}, {"segments": [{}]}, {"segments": ["bad"]}],
+)
+def test_malformed_manifest_raises_value_error(binding, manifest):
+ if isinstance(manifest, dict):
+ manifest.update(
+ dimension=8, index_type="hnsw", metric="l2", normalize=False
+ )
+ binding["path"].write_bytes(module.MAGIC + json.dumps(manifest).encode())
+ binding["integrity_record"](binding["path"])
+ with pytest.raises(ValueError):
+ module.SegmentedFaissStore.load(**binding)
+
+
+def test_empty_store_validates_query_vector(binding):
+ store = module.SegmentedFaissStore.create(**binding)
+ with pytest.raises(ValueError, match="dimension"):
+ store.search(np.zeros(9, dtype="float32"), 1)
+ with pytest.raises(ValueError, match="finite"):
+ store.search(np.full(8, np.nan, dtype="float32"), 1)
+
+
+def test_next_write_retires_interrupted_segment_files_only(binding):
+ store = module.SegmentedFaissStore.create(**binding)
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+ directory = module.segment_directory(binding["path"])
+ abandoned = [
+ directory / ("0" * 32 + suffix)
+ for suffix in (".faiss", ".ids", ".faiss.random.tmp", ".ids.random.tmp")
+ ]
+ for path in abandoned:
+ path.write_bytes(b"interrupted vector write")
+ unexpected = directory / "unrelated.txt"
+ unexpected.write_bytes(b"keep")
+ store.apply(add_ids=[2], add_vectors=vectors(1, 2))
+ assert store.live_ids() == [1, 2]
+ assert all(not path.exists() for path in abandoned)
+ assert unexpected.read_bytes() == b"keep"
+
+
[email protected]("operation", ["begin", "settle"])
+def test_family_cleanup_retires_abandoned_checkpoint_copies(
+ binding, monkeypatch, operation
+):
+ from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+ )
+
+ store = module.SegmentedFaissStore.create(**binding)
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+ if operation == "settle":
+ store.begin_transaction()
+ store.apply(add_ids=[2], add_vectors=vectors(1, 2))
+
+ copies = []
+ real_mkstemp = module.tempfile.mkstemp
+ real_replace = os.replace
+ real_unlink = Path.unlink
+
+ def mkstemp(*args, **kwargs):
+ descriptor, temporary = real_mkstemp(*args, **kwargs)
+ copies.append(Path(temporary))
+ return descriptor, temporary
+
+ def unavailable_link(*args, **kwargs):
+ raise OSError("Hard links unavailable")
+
+ def replace(source, destination):
+ if Path(source) in copies:
+ raise OSError("Checkpoint publication unavailable")
+ return real_replace(source, destination)
+
+ def unlink(path, *args, **kwargs):
+ if path in copies:
+ raise PermissionError("Temporary component unavailable")
+ return real_unlink(path, *args, **kwargs)
+
+ def reject_generation(*args, **kwargs):
+ raise ValueError("Generation unavailable")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(module.tempfile, "mkstemp", mkstemp)
+ patch.setattr(os, "link", unavailable_link)
+ patch.setattr(os, "replace", replace)
+ patch.setattr(Path, "unlink", unlink)
+ if operation == "settle":
+ patch.setattr(store, "_state", reject_generation)
+ with pytest.raises(OSError, match="Temporary component unavailable"):
+ if operation == "begin":
+ store.begin_transaction()
+ else:
+ store.end_transaction(committed=True)
+
+ assert len(copies) == 1 and copies[0].is_file()
+ old = time.time() - 7200
+ os.utime(copies[0], (old, old))
+ unrelated = binding["path"].parent / "unrelated.tmp"
+ unrelated.write_bytes(b"keep")
+
+ assert CascadeHelper.delete_faiss_index_files(str(binding["path"]))
+ assert not binding["path"].exists()
+ assert not module.segment_directory(binding["path"]).exists()
+ assert not copies[0].exists()
+ assert unrelated.read_bytes() == b"keep"
+
+
+def test_index_storage_size_counts_segments_not_just_manifest(tmp_path):
+ """Collection details must report vector bytes, not the manifest size."""
+ from local_deep_research.vector_stores.segment_files import (
+ index_storage_size,
+ segment_directory,
+ )
+
+ legacy = tmp_path / "legacy.faiss"
+ legacy.write_bytes(b"x" * 100)
+ assert index_storage_size(legacy) == 100
+
+ root = tmp_path / "index.faiss"
+ root.write_bytes(b"m" * 10)
+ directory = segment_directory(root)
+ directory.mkdir()
+ (directory / ("a" * 32 + ".faiss")).write_bytes(b"v" * 1000)
+ (directory / ("a" * 32 + ".ids")).write_bytes(b"i" * 50)
+ outside = tmp_path / "outside.bin"
+ outside.write_bytes(b"o" * 7000)
+ (directory / "link.faiss").symlink_to(outside)
+ assert index_storage_size(root) == 1060
+
+ # A corrupted recorded path reports an unknown size instead of raising.
+ loop = tmp_path / "loop.faiss"
+ loop.symlink_to(loop)
+ for corrupted in (
+ legacy / "under-a-file.faiss", # ENOTDIR
+ loop, # ELOOP
+ tmp_path / ("x" * 4096 + ".faiss"), # ENAMETOOLONG
+ Path(str(tmp_path / "nul") + "\0.faiss"), # ValueError
+ ):
+ assert index_storage_size(corrupted) is None
+
+
+def test_index_storage_size_tolerates_unreadable_segment_directory(
+ tmp_path, monkeypatch
+):
+ from local_deep_research.vector_stores import segment_files
+
+ root = tmp_path / "index.faiss"
+ root.write_bytes(b"x" * 10)
+ segment_files.segment_directory(root).mkdir()
+
+ def denied(path):
+ raise PermissionError("Permission denied")
+
+ monkeypatch.setattr(segment_files.os, "scandir", denied)
+
+ assert segment_files.index_storage_size(root) == 10
+
+
+def test_index_storage_size_skips_files_retired_mid_scan(tmp_path, monkeypatch):
+ """A writer retiring a segment while the details page sums sizes must
+ not raise (readers hold no lock); vanished entries are skipped."""
+ from local_deep_research.vector_stores import segment_files
+
+ root = tmp_path / "index.faiss"
+ root.write_bytes(b"m" * 10)
+ directory = segment_files.segment_directory(root)
+ directory.mkdir()
+ (directory / ("a" * 32 + ".faiss")).write_bytes(b"v" * 1000)
+ victim = directory / ("b" * 32 + ".faiss")
+ victim.write_bytes(b"r" * 500)
+
+ # Retire the victim after it is listed but before it is stat'ed, for
+ # both a scandir-based and a Path.iterdir/is_file-based scan.
+ real_scandir = os.scandir
+
+ class _RetiringScan:
+ def __init__(self, target):
+ self._scan = real_scandir(target)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self._scan.close()
+
+ def __iter__(self):
+ for entry in self._scan:
+ yield _RetiringEntry(entry)
+
+ class _RetiringEntry:
+ def __init__(self, entry):
+ self._entry = entry
+
+ def __getattr__(self, name):
+ return getattr(self._entry, name)
+
+ def __fspath__(self):
+ return self._entry.path
+
+ def stat(self, **kwargs):
+ if self._entry.name == victim.name:
+ victim.unlink(missing_ok=True)
+ return self._entry.stat(**kwargs)
+
+ real_is_file = Path.is_file
+
+ def retiring_is_file(self):
+ result = real_is_file(self)
+ if self == victim:
+ victim.unlink(missing_ok=True)
+ return result
+
+ monkeypatch.setattr(segment_files.os, "scandir", _RetiringScan)
+ monkeypatch.setattr(Path, "is_file", retiring_is_file)
+ assert segment_files.index_storage_size(root) == 1010
+ monkeypatch.undo()
+
+ # The segment directory or the root itself vanishing is not an error.
+ victim.write_bytes(b"r")
+ segment_files.delete_segment_files(root)
+ assert segment_files.index_storage_size(root) == 10
+ root.unlink()
+ assert segment_files.index_storage_size(root) is None
diff --git a/tests/vector_stores/test_segmented_legacy_conversion.py b/tests/vector_stores/test_segmented_legacy_conversion.py
new file mode 100644
index 0000000000..0d69b47775
--- /dev/null
+++ b/tests/vector_stores/test_segmented_legacy_conversion.py
@@ -0,0 +1,258 @@
+"""Legacy conversion must never publish a generation later reads reject.
+
+Regression pins for the documented pre-fix legacy population (see the #4200
+comment in ``faiss_store.py``): pre-fix writers can leave duplicate ids — a
+stale orphan vector under an id a later, unrelated chunk reuses — in a legacy
+``.faiss`` id map, and such files must convert on their next write without
+re-embedding. Conversion normalizes the id map with the same discipline as the
+add path (drop duplicates deterministically, skip unrepresentable values,
+fail loudly and non-destructively when no safe conversion exists), and settle
+must never destroy the legacy pre-image before the replacement generation has
+validated.
+
+Only the legacy reader is faked (an id map of raw, unchecked ids exactly as a
+pre-fix writer could persist them); every write, publication, validation and
+settle step runs the real machinery.
+"""
+
+import json
+import threading
+
+import numpy as np
+import pytest
+
+from local_deep_research.vector_stores.base import VectorStoreIntegrityError
+from local_deep_research.vector_stores.implementations import (
+ segmented_faiss as module,
+)
+from local_deep_research.vector_stores.segment_files import checkpoint_path
+
+
+def binding(tmp_path):
+ checksums = {}
+
+ def record(path):
+ checksums[str(path)] = path.read_bytes()
+
+ def verify(path):
+ return (
+ checksums.get(str(path)) == path.read_bytes(),
+ "checksum",
+ )
+
+ return dict(
+ path=tmp_path / "index.faiss",
+ dimension=8,
+ index_type="hnsw",
+ metric="l2",
+ normalize=False,
+ lock=threading.RLock(),
+ integrity_record=record,
+ integrity_verify=verify,
+ )
+
+
+def vectors(n, seed=5):
+ return np.random.default_rng(seed).random((n, 8), dtype=np.float32)
+
+
+def write_legacy(binding):
+ """Persist legacy bytes and adopt them into the integrity record, as the
+ service's preflight does for an existing legacy file."""
+ binding["path"].write_bytes(b"LEGACY")
+ binding["integrity_record"](binding["path"])
+
+
+class FakeLegacy:
+ """Stand-in for the mmap'd legacy reader: an id map carrying raw ids with
+ no bounds or uniqueness checks, as a pre-fix writer could persist."""
+
+ def __init__(self, ids, dimension=8):
+ self.id_map = list(ids)
+ self.d = dimension
+ self._vectors = {
+ int(value): np.full(dimension, float(value), dtype="float32")
+ for value in ids
+ }
+
+ def reconstruct(self, i):
+ return self._vectors[int(i)]
+
+ @property
+ def ntotal(self):
+ return len(self.id_map)
+
+
+def legacy(monkeypatch):
+ def install(ids):
+ fake = FakeLegacy(ids)
+ monkeypatch.setattr(
+ module.faiss,
+ "vector_to_array",
+ lambda values: np.asarray(values, dtype="int64"),
+ )
+ monkeypatch.setattr(
+ module.SegmentedFaissStore, "_legacy", lambda self: fake
+ )
+ monkeypatch.setattr(module, "SEGMENT_VECTORS", 4)
+ return fake
+
+ return install
+
+
+def test_conversion_deduplicates_reused_ids(binding, legacy):
+ """A pre-#4200 stale orphan (duplicate ids, within and across segment
+ windows) must convert to one row per id instead of producing a generation
+ that _ids()/count() reject — or that serves the same chunk twice."""
+ fake = legacy([7, 5, 5, 1001, 1002, 1003, 7])
+ write_legacy(binding)
+ store = module.SegmentedFaissStore.load(**binding)
+
+ result = store.apply(add_ids=[], add_vectors=None, remove_ids=[999])
+
+ # Deduplication is a repair, not a removal: only explicitly removed ids
+ # count as removed.
+ assert result == {"added": 0, "removed": 0}
+ fresh = module.SegmentedFaissStore.load(**binding)
+ assert sorted(fresh.live_ids()) == [5, 7, 1001, 1002, 1003]
+ assert fresh.count() == 5
+ hits = fresh.search(np.ones(8, dtype="float32"), 10)
+ assert [hit[0] for hit in hits].count(7) == 1
+ np.testing.assert_allclose(fresh.reconstruct(7), fake.reconstruct(7))
+
+
+def test_conversion_repairs_unrepresentable_ids(binding, legacy):
+ """A negative legacy id (unrepresentable in a generated segment) is
+ skipped with the rest of the file surviving — such files must keep working
+ after their next write instead of being bricked."""
+ legacy([-3, 5, 8])
+ write_legacy(binding)
+ store = module.SegmentedFaissStore.load(**binding)
+
+ result = store.apply(add_ids=[1], add_vectors=vectors(1))
+
+ assert result == {"added": 1, "removed": 0}
+ fresh = module.SegmentedFaissStore.load(**binding)
+ assert sorted(fresh.live_ids()) == [1, 5, 8]
+ assert fresh.count() == 3
+ assert fresh.reconstruct(-3) is None
+
+
+def test_conversion_fails_loudly_and_keeps_the_legacy_pre_image(
+ binding, legacy
+):
+ """A file whose rows cannot be represented at all is refused loudly and
+ non-destructively: no empty generation is published, the legacy bytes stay
+ readable, and the refusal surfaces as the integrity error whose established
+ recovery policy is refuse + quarantine + reindex (never a silent commit, a
+ destroyed pre-image, or a forced re-embed of healthy data)."""
+ fake = legacy([-3, -7])
+ write_legacy(binding)
+ original = binding["path"].read_bytes()
+ store = module.SegmentedFaissStore.load(**binding)
+
+ with pytest.raises(
+ VectorStoreIntegrityError, match="cannot be represented"
+ ):
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+
+ # Non-destructive: the legacy pre-image is byte-identical and still loads.
+ assert binding["path"].read_bytes() == original
+ fresh = module.SegmentedFaissStore.load(**binding)
+ assert fresh.count() == fake.ntotal # still the legacy file, intact
+
+
+def test_publish_refuses_an_unloadable_generation(binding, monkeypatch):
+ """_publish validates before writing and authenticating: an entry that
+ later reads reject can never become the published generation."""
+ store = module.SegmentedFaissStore.create(**binding)
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+ before = binding["path"].read_bytes()
+ original = store._write
+
+ def corrupt_entry(index):
+ entry = original(index)
+ entry["min_id"] = -3 # a legacy artifact reaching publication
+ return entry
+
+ monkeypatch.setattr(store, "_write", corrupt_entry)
+ with pytest.raises(ValueError):
+ store.apply(add_ids=[2], add_vectors=vectors(1, 21))
+
+ # Nothing unloadable was published: the previous generation is intact.
+ assert binding["path"].read_bytes() == before
+ assert module.SegmentedFaissStore.load(**binding).count() == 1
+
+
+def test_settle_restores_the_pre_image_when_the_generation_is_unloadable(
+ binding,
+):
+ """Settle validates the replacement generation BEFORE the checkpoint — the
+ only copy of the pre-image — is destroyed, and an unloadable generation is
+ surfaced and rolled back rather than reported as success."""
+ # Structural pin only: the checksum record is not under test here.
+ binding["integrity_verify"] = lambda path: (True, None)
+ store = module.SegmentedFaissStore.create(**binding)
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+ generation_zero = binding["path"].read_bytes()
+ store.begin_transaction(first=True)
+ store.apply(add_ids=[2], add_vectors=vectors(1, 21))
+ # Corrupt the published generation between publish and settle — exactly
+ # the window the checkpoint ordering protects.
+ manifest = json.loads(binding["path"].read_bytes()[len(module.MAGIC) :])
+ manifest["segments"][0]["min_id"] = -3
+ binding["path"].write_bytes(
+ module.MAGIC + json.dumps(manifest, separators=(",", ":")).encode()
+ )
+
+ with pytest.raises(VectorStoreIntegrityError):
+ store.end_transaction(committed=True)
+
+ # The rejected publish left the pre-image intact and unreplaced at the
+ # path AND kept the rollback checkpoint holding the same bytes: neither
+ # copy is destroyed by a settle that refuses the generation.
+ assert binding["path"].read_bytes() == generation_zero
+ checkpoint = checkpoint_path(binding["path"])
+ assert checkpoint.exists() and not checkpoint.is_symlink()
+ assert checkpoint.read_bytes() == generation_zero
+ assert module.SegmentedFaissStore.load(**binding).count() == 1
+
+
+def test_rejected_publish_leaves_legacy_pre_image_and_checkpoint_intact(
+ binding, legacy
+):
+ """A settle that rejects the published generation must leave BOTH copies
+ of the legacy pre-image intact and unreplaced — the rollback checkpoint
+ and the restored bytes at the path — exactly the B1 data-loss chain
+ (invalid manifest committed, legacy bytes gone, checkpoint gone) run in
+ reverse: nothing is destroyed, and the failure is surfaced."""
+ binding["integrity_verify"] = lambda path: (True, None)
+ legacy([4, 5])
+ write_legacy(binding)
+ original = binding["path"].read_bytes()
+ store = module.SegmentedFaissStore.load(**binding)
+ store.begin_transaction(first=True)
+ store.apply(add_ids=[1], add_vectors=vectors(1))
+ # Tamper the published generation between publish and settle — the window
+ # the checkpoint ordering protects.
+ manifest = json.loads(binding["path"].read_bytes()[len(module.MAGIC) :])
+ manifest["segments"][0]["min_id"] = -3
+ binding["path"].write_bytes(
+ module.MAGIC + json.dumps(manifest, separators=(",", ":")).encode()
+ )
+
+ with pytest.raises(VectorStoreIntegrityError):
+ store.end_transaction(committed=True)
+
+ checkpoint = checkpoint_path(binding["path"])
+ # The legacy bytes are intact and unreplaced at the path, and the rollback
+ # checkpoint is left in place holding the same pre-image.
+ assert binding["path"].read_bytes() == original
+ assert checkpoint.exists() and not checkpoint.is_symlink()
+ assert checkpoint.read_bytes() == original
+ # The store still serves reads from the preserved pre-image.
+ fresh = module.SegmentedFaissStore.load(**binding)
+ assert fresh.count() == 2
+ assert sorted(fresh.live_ids()) == [4, 5]
diff --git a/tests/web/routers/test_delete_research_cascade.py b/tests/web/routers/test_delete_research_cascade.py
index 49ac74e015..2b5f6e1a19 100644
--- a/tests/web/routers/test_delete_research_cascade.py
+++ b/tests/web/routers/test_delete_research_cascade.py
@@ -331,22 +331,21 @@ def _patch_real_rag_purge(session, events):
def __exit__(self, *_args):
return False
- def purge_document_vectors(self, document_id, collection_id):
+ def purge_documents_vectors(self, document_ids, collection_id):
# Vector deletion must see the committed parent deletion while
# chunk rows still exist to resolve their FAISS IDs.
- assert (
- session.query(Document).filter_by(id=document_id).count() == 0
- )
- assert (
- session.query(DocumentChunk)
- .filter_by(source_id=document_id)
- .count()
- == 1
- )
- events.append(("vectors", document_id, collection_id))
-
- def purge_document_chunks(self, document_id, collection_id):
- events.append(("chunks", document_id, collection_id))
+ for document_id in document_ids:
+ assert (
+ session.query(Document).filter_by(id=document_id).count()
+ == 0
+ )
+ assert (
+ session.query(DocumentChunk)
+ .filter_by(source_id=document_id)
+ .count()
+ == 1
+ )
+ events.append(("vectors", document_ids, collection_id))
with (
patch(
@@ -863,7 +862,12 @@ class TestResearchRagPurgeRoutes:
"get_user_db_session",
side_effect=RuntimeError("database unavailable"),
),
- patch.object(service, "_purge_document_rag") as purge,
+ patch(
+ "local_deep_research.research_library.services.rag_service_factory.get_rag_service"
+ ) as rag,
+ patch.object(
+ document_deletion.CascadeHelper, "delete_document_chunks"
+ ) as purge_chunks,
loguru_caplog.at_level("WARNING"),
):
service.purge_deleted_research_documents(
@@ -872,7 +876,8 @@ class TestResearchRagPurgeRoutes:
("fedcba9876543210-second", ["one", "two"]),
]
)
- purge.assert_not_called()
+ rag.assert_not_called()
+ purge_chunks.assert_not_called()
# The skip is actionable: every warning names the document and how
# many collections were left behind (#7501).
skips = [
@@ -986,10 +991,7 @@ class TestResearchRagPurgeRoutes:
.count()
== 0
)
- assert events == [
- ("vectors", document_id, collection_id),
- ("chunks", document_id, collection_id),
- ]
+ assert events == [("vectors", [document_id], collection_id)]
def test_single_delete_purges_owned_chunks_after_commit(
self, authenticated_client, db_with_fk
@@ -1021,10 +1023,7 @@ class TestResearchRagPurgeRoutes:
.count()
== 0
), "deleted research retained its private chunk text"
- assert events == [
- ("vectors", document_id, collection_id),
- ("chunks", document_id, collection_id),
- ]
+ assert events == [("vectors", [document_id], collection_id)]
def test_clear_history_purges_only_deleted_research_chunks(
self, authenticated_client, db_with_fk
@@ -1065,10 +1064,7 @@ class TestResearchRagPurgeRoutes:
db_with_fk.query(DocumentChunk).filter_by(source_id=live_id).count()
== 1
)
- assert events == [
- ("vectors", done_id, done_collection_id),
- ("chunks", done_id, done_collection_id),
- ]
+ assert events == [("vectors", [done_id], done_collection_id)]
def test_unavailable_rag_credentials_still_sweep_private_chunks(
self, authenticated_client, db_with_fk
diff --git a/tests/web/routers/test_rag_indexing_pipeline.py b/tests/web/routers/test_rag_indexing_pipeline.py
index 48b349e783..e3cffdb7ea 100644
--- a/tests/web/routers/test_rag_indexing_pipeline.py
+++ b/tests/web/routers/test_rag_indexing_pipeline.py
@@ -1091,6 +1091,8 @@ class TestIndexStatusErrorDisclosure:
"durable_indexed_chunks": 12,
"live_vectors": 12,
"orphan_vectors": 0,
+ "orphan_vectors_removed": 7,
+ "partial_document_vectors": 3,
"errors": [
{
"doc_id": "doc-1",
@@ -1108,6 +1110,8 @@ class TestIndexStatusErrorDisclosure:
assert status["status"] == "completed"
assert status["result"]["durable_indexed_documents"] == 2
assert status["result"]["durable_indexed_chunks"] == 12
+ assert status["result"]["orphan_vectors_removed"] == 7
+ assert status["result"]["partial_document_vectors"] == 3
assert status["result"]["errors"][0]["error"] == (
"Document deleted during indexing"
)