~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test(vector_stores): cover legacy rekey and cleanup failure branches (#6146)
LearningCircuitda217aeed6b6
diff --git a/tests/vector_stores/test_legacy_cleanup_edge_failures.py b/tests/vector_stores/test_legacy_cleanup_edge_failures.pynew file mode 100644index 0000000000..f63c62206f--- /dev/null+++ b/tests/vector_stores/test_legacy_cleanup_edge_failures.py@@ -0,0 +1,194 @@+"""Failure-path coverage for plaintext cleanup and low-level legacy re-keying."""++from pathlib import Path+from unittest.mock import MagicMock++import faiss+import pytest+from pytest_mock import MockerFixture++import local_deep_research.vector_stores.legacy_cleanup as cleanup+++def test_find_legacy_docstores_returns_empty_for_absent_root(tmp_path):+ assert cleanup._find_legacy_docstores(tmp_path / "missing") == ([], [])+++def test_find_legacy_docstores_records_walk_error(tmp_path, mocker):+ error = OSError("denied")+ error.filename = str(tmp_path / "blocked")++ def _walk(_root, *, onerror):+ onerror(error)+ return iter(())++ mocker.patch.object(cleanup.os, "walk", _walk)++ assert cleanup._find_legacy_docstores(tmp_path) == ([], [error.filename])+++def test_delete_file_retries_read_only_file_after_chmod(mocker):+ path = MagicMock()+ path.unlink.side_effect = [PermissionError("readonly"), None]+ chmod = mocker.patch.object(cleanup.os, "chmod")++ cleanup._delete_file(path)++ chmod.assert_called_once_with(+ path, cleanup.stat.S_IWRITE | cleanup.stat.S_IREAD+ )+ assert path.unlink.call_count == 2+++def test_delete_file_ignores_chmod_failure_before_final_retry(mocker):+ path = MagicMock()+ path.unlink.side_effect = [PermissionError("readonly"), None]+ mocker.patch.object(cleanup.os, "chmod", side_effect=OSError("unsupported"))++ cleanup._delete_file(path)++ assert path.unlink.call_count == 2+++def test_write_sidecar_continues_when_directory_fsync_is_unsupported(+ tmp_path, mocker+):+ sidecar = tmp_path / "index.idmap.json"+ mocker.patch.object(+ cleanup.os, "fsync", side_effect=[None, OSError("unsupported")]+ )++ cleanup._write_sidecar_atomic(sidecar, {"0": "a" * 32})++ assert sidecar.read_text(encoding="utf-8") == '{"0": "' + "a" * 32 + '"}'+++def test_extract_map_treats_sidecar_write_error_as_reindex_fallback(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ pkl_path = tmp_path / "legacy.pkl"+ pkl_path.write_bytes(b"placeholder")+ mocker.patch.object(+ cleanup, "load_index_to_docstore_id", return_value={0: "a" * 32}+ )+ mocker.patch.object(+ cleanup, "_write_sidecar_atomic", side_effect=OSError("full")+ )++ assert cleanup._extract_map(pkl_path) is False+++def test_migration_reports_delete_failure_and_remaining_plaintext(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ pkl_path = tmp_path / "legacy.pkl"+ pkl_path.write_bytes(b"plaintext")+ mocker.patch.object(cleanup, "_rag_cache_root", return_value=tmp_path)+ mocker.patch.object(cleanup, "_extract_map", return_value=True)+ mocker.patch.object(cleanup, "_delete_file", side_effect=OSError("locked"))++ result = cleanup.migrate_legacy_docstores()++ assert result["found"] == 1+ assert result["deleted"] == 0+ assert result["remaining"] == 1+++def test_migration_survives_root_chmod_failure(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ pkl_path = tmp_path / "legacy.pkl"+ pkl_path.write_bytes(b"plaintext")+ mocker.patch.object(cleanup, "_rag_cache_root", return_value=tmp_path)+ chmod = mocker.patch.object(+ Path, "chmod", side_effect=OSError("unsupported")+ )+ mocker.patch.object(cleanup, "_extract_map", return_value=False)++ result = cleanup.migrate_legacy_docstores()++ # Positive control: the root-hardening chmod was actually attempted (with+ # the process bound as `self`, so the mock only observes the mode arg —+ # see cleanup._rag_cache_root and the `root.chmod(0o700)` call it feeds).+ # Without it, deleting the hardening block at legacy_cleanup.py:377-381+ # would leave this test green for the wrong reason.+ chmod.assert_called_once_with(0o700)+ assert result["deleted"] == 1+ assert not pkl_path.exists()+++def test_rekey_rejects_dimension_mismatch_before_reconstruction(+ tmp_path: Path,+) -> None:+ faiss_path = tmp_path / "legacy.faiss"+ sidecar = tmp_path / "legacy.idmap.json"+ faiss.write_index(faiss.IndexFlatL2(2), str(faiss_path))+ sidecar.write_text("{}", encoding="utf-8")++ with pytest.raises(ValueError, match="dim 2 != expected 3"):+ cleanup.rekey_index_file(+ faiss_path,+ sidecar,+ {},+ dimension=3,+ index_type="flat",+ metric="l2",+ normalize=False,+ )+++def test_rekey_empty_index_and_failed_readback_are_detected(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path = tmp_path / "legacy.faiss"+ sidecar = tmp_path / "legacy.idmap.json"+ sidecar.write_text("{}", encoding="utf-8")+ old = faiss.IndexFlatL2(2)+ mocker.patch.object(cleanup, "read_index", return_value=old)+ store = MagicMock()+ verify = MagicMock()+ verify.live_ids.return_value = {99}+ verify.count.return_value = 1+ store_class = MagicMock()+ store_class.create.return_value = store+ store_class.load.return_value = verify+ mocker.patch(+ "local_deep_research.vector_stores.implementations.faiss_store."+ "FaissVectorStore",+ store_class,+ )++ with pytest.raises(RuntimeError, match="read-back verify failed"):+ cleanup.rekey_index_file(+ faiss_path,+ sidecar,+ {},+ dimension=2,+ index_type="flat",+ metric="l2",+ normalize=False,+ )++ assert store.add.call_count == 0+++def test_missing_sidecar_reraises_when_concurrent_probe_is_not_migrated(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path = tmp_path / "legacy.faiss"+ faiss_path.write_bytes(b"placeholder")+ old = faiss.IndexFlatL2(2)+ mocker.patch.object(+ cleanup, "read_index", side_effect=[old, OSError("partial")]+ )++ with pytest.raises(FileNotFoundError):+ cleanup.rekey_index_file(+ faiss_path,+ tmp_path / "missing.idmap.json",+ {},+ dimension=2,+ index_type="flat",+ metric="l2",+ normalize=False,+ )diff --git a/tests/vector_stores/test_legacy_rekey_edge_failures.py b/tests/vector_stores/test_legacy_rekey_edge_failures.pynew file mode 100644index 0000000000..1568c97ed6--- /dev/null+++ b/tests/vector_stores/test_legacy_rekey_edge_failures.py@@ -0,0 +1,345 @@+"""Failure-path coverage for phase-2 legacy index re-keying.++These tests isolate retries and quarantine decisions so transient failures never+turn into destructive reindexing or a completion marker hiding plaintext.+"""++import threading+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path+from unittest.mock import MagicMock++from pytest_mock import MockerFixture++import pytest++import local_deep_research.vector_stores.legacy_rekey as rekey+++@contextmanager+def _session_context(session: MagicMock) -> Iterator[MagicMock]:+ yield session+++def _one_index_harness(+ mocker: MockerFixture, tmp_path: Path, *, sidecar: bool = True+) -> tuple[Path, Path, MagicMock, MagicMock]:+ faiss_path = tmp_path / "legacy.faiss"+ sidecar_path = tmp_path / "legacy.idmap.json"+ if sidecar:+ sidecar_path.write_text('{"0": "a"}', encoding="utf-8")++ rag_index = MagicMock()+ rag_index.id = 17+ rag_index.index_path = str(faiss_path)+ rag_index.collection_name = "collection_edge"+ rag_index.embedding_dimension = 2+ rag_index.index_type = "flat"+ rag_index.distance_metric = "l2"+ rag_index.normalize_vectors = False++ settings = MagicMock()+ settings.get_bool_setting.return_value = False+ session = MagicMock()+ session.query.return_value.all.return_value = [rag_index]+ mocker.patch.object(+ rekey,+ "get_user_db_session",+ # One fresh context manager per call: the orchestrator opens a+ # second session when persisting rekeyed config (legacy_rekey.py:146).+ side_effect=lambda *args, **kwargs: _session_context(session),+ )+ mocker.patch.object(rekey, "get_settings_manager", return_value=settings)+ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service."+ "_get_faiss_write_lock",+ # Head returns a _TrackedRLock (an RLock wrapper); RLock() here+ # matches its reentrancy instead of a plain, non-reentrant Lock().+ return_value=threading.RLock(),+ )+ return faiss_path, sidecar_path, rag_index, settings+++def test_persist_rekeyed_config_ignores_deleted_rag_index(+ mocker: MockerFixture,+) -> None:+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = None+ mocker.patch.object(+ rekey,+ "get_user_db_session",+ return_value=_session_context(session),+ )++ rekey._persist_rekeyed_config("alice", "password", 12, {})++ # Pin the query path the guard depends on, not just its outcome.+ session.query.return_value.filter_by.assert_called_once_with(id=12)+ session.commit.assert_not_called()+++def test_persist_rekeyed_config_skips_commit_and_preserves_fields_when_unchanged(+ mocker: MockerFixture,+) -> None:+ """Pins the `if changed:` gate (legacy_rekey.py:160-161) independently of+ the `row is None` guard above: the row IS found, but every column is+ already non-NULL, so `changed` never flips True. A revert that commits+ unconditionally would only be caught here, and a revert that stopped+ checking each field individually before assigning would be caught by the+ sentinel values below staying untouched (never override an explicit+ stored value, per _persist_rekeyed_config's docstring)."""+ row = MagicMock()+ row.index_type = "flat"+ row.distance_metric = "l2"+ row.normalize_vectors = False+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = row+ mocker.patch.object(+ rekey,+ "get_user_db_session",+ return_value=_session_context(session),+ )++ rekey._persist_rekeyed_config(+ "alice",+ "password",+ 12,+ {"index_type": "hnsw", "metric": "cosine", "normalize": True},+ )++ session.commit.assert_not_called()+ assert row.index_type == "flat"+ assert row.distance_metric == "l2"+ assert row.normalize_vectors is False+++def test_purge_redundant_pkl_returns_false_when_unlink_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ faiss_path = tmp_path / "legacy.faiss"+ pkl_path = faiss_path.with_suffix(".pkl")+ pkl_path.write_bytes(b"plaintext")++ def _fail_unlink(path, *args, **kwargs):+ if path == pkl_path:+ raise OSError("locked")+ return original_unlink(path, *args, **kwargs)++ original_unlink = Path.unlink+ monkeypatch.setattr(Path, "unlink", _fail_unlink)++ assert rekey._purge_redundant_pkl(faiss_path, "password") is False+ assert pkl_path.exists()+++def test_quarantine_renames_pair_and_deletes_plaintext(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path = tmp_path / "legacy.faiss"+ sidecar_path = tmp_path / "legacy.idmap.json"+ pkl_path = tmp_path / "legacy.pkl"+ faiss_path.write_bytes(b"index")+ sidecar_path.write_text("{}", encoding="utf-8")+ pkl_path.write_bytes(b"plaintext")+ rag_index = MagicMock(id=7, collection_name="collection_edge")+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = (+ MagicMock(is_current=False)+ )+ mocker.patch.object(+ rekey,+ "get_user_db_session",+ return_value=_session_context(session),+ )++ rekey._quarantine_and_reset(+ "alice",+ "password",+ rag_index,+ faiss_path,+ sidecar_path,+ threading.Lock(),+ )++ assert not faiss_path.exists()+ assert not sidecar_path.exists()+ assert not pkl_path.exists()+ assert len(list(tmp_path.glob("*.corrupt-*"))) == 2+++def test_old_format_without_sidecar_quarantines_when_phase_one_gave_up(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, _sidecar, _row, settings = _one_index_harness(+ mocker, tmp_path, sidecar=False+ )+ faiss_path.write_bytes(b"old index")+ mocker.patch.object(rekey, "_is_idmap2", return_value=False)+ quarantine = mocker.patch.object(rekey, "_quarantine_and_reset")++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["quarantined"] == 1+ quarantine.assert_called_once()+ settings.set_setting.assert_called_once_with(+ rekey.REKEY_MARKER_SETTING, True+ )+++def test_failed_quarantine_withholds_marker_for_old_format_orphan(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, _sidecar, _row, settings = _one_index_harness(+ mocker, tmp_path, sidecar=False+ )+ faiss_path.write_bytes(b"old index")+ mocker.patch.object(rekey, "_is_idmap2", return_value=False)+ mocker.patch.object(+ rekey, "_quarantine_and_reset", side_effect=OSError("full")+ )++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["quarantined"] == 0+ settings.set_setting.assert_not_called()+++def test_mixed_batch_one_unresolved_index_withholds_marker_for_whole_batch(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ """`all_resolved` (legacy_rekey.py:342) is an accumulator over the WHOLE+ per-user sweep, not a per-index flag: it is initialised once before the+ `for rag_index in indexes:` loop and only ever flipped False, so one+ unresolved index withholds the marker even when a LATER index in the+ same call resolves cleanly. A revert that re-initialises+ `all_resolved = True` inside the loop body (resetting it every+ iteration) would let this second, successful index silently erase the+ first index's failure and set the marker anyway -- caught below by+ `settings.set_setting.assert_not_called()`.+ """+ unresolved_path = tmp_path / "legacy_unresolved.faiss"+ unresolved_path.write_bytes(b"old index")+ resolved_path = tmp_path / "legacy_resolved.faiss"+ resolved_path.write_bytes(b"old index")++ unresolved_row = MagicMock(id=1, index_path=str(unresolved_path))+ resolved_row = MagicMock(id=2, index_path=str(resolved_path))++ settings = MagicMock()+ settings.get_bool_setting.return_value = False+ session = MagicMock()+ session.query.return_value.all.return_value = [+ unresolved_row,+ resolved_row,+ ]+ mocker.patch.object(+ rekey,+ "get_user_db_session",+ side_effect=lambda *args, **kwargs: _session_context(session),+ )+ mocker.patch.object(rekey, "get_settings_manager", return_value=settings)+ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service."+ "_get_faiss_write_lock",+ return_value=threading.RLock(),+ )+ mocker.patch.object(rekey, "_is_idmap2", return_value=False)+ quarantine = mocker.patch.object(+ rekey,+ "_quarantine_and_reset",+ # First index (unresolved): quarantine itself fails. Second index+ # (resolved): quarantine succeeds. Order matters -- the failure must+ # come first so a per-iteration reset would be masked by the later+ # success.+ side_effect=[OSError("full"), None],+ )++ stats = rekey.rekey_user_indexes("alice", "password")++ assert quarantine.call_count == 2+ assert stats["quarantined"] == 1+ settings.set_setting.assert_not_called()+++def test_orphan_sidecar_unlink_failure_withholds_marker(+ tmp_path: Path, mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch+) -> None:+ _faiss, sidecar, _row, settings = _one_index_harness(mocker, tmp_path)+ mocker.patch.object(rekey, "_purge_redundant_pkl", return_value=True)++ original_unlink = Path.unlink++ def _fail_sidecar_unlink(path, *args, **kwargs):+ if path == sidecar:+ raise OSError("locked")+ return original_unlink(path, *args, **kwargs)++ monkeypatch.setattr(Path, "unlink", _fail_sidecar_unlink)++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["skipped_no_faiss"] == 1+ assert sidecar.exists()+ settings.set_setting.assert_not_called()++[email protected]("failure_site", ["persist", "resolve"])+def test_transient_pre_rekey_failures_do_not_quarantine(+ tmp_path: Path, mocker: MockerFixture, failure_site: str+) -> None:+ faiss_path, _sidecar, _row, settings = _one_index_harness(mocker, tmp_path)+ faiss_path.write_bytes(b"old index")+ quarantine = mocker.patch.object(rekey, "_quarantine_and_reset")+ if failure_site == "persist":+ mocker.patch.object(+ rekey, "_persist_rekeyed_config", side_effect=OSError("db")+ )+ else:+ mocker.patch.object(+ rekey, "_load_uuid_to_id", side_effect=OSError("db")+ )++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["quarantined"] == 0+ quarantine.assert_not_called()+ settings.set_setting.assert_not_called()+++def test_rekey_failure_with_failed_quarantine_withholds_marker(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, _sidecar, _row, settings = _one_index_harness(mocker, tmp_path)+ faiss_path.write_bytes(b"old index")+ mocker.patch.object(rekey, "_load_uuid_to_id", return_value={"a": 1})+ mocker.patch.object(+ rekey, "rekey_index_file", side_effect=ValueError("corrupt")+ )+ mocker.patch.object(+ rekey, "_quarantine_and_reset", side_effect=OSError("full")+ )++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["quarantined"] == 0+ settings.set_setting.assert_not_called()+++def test_finalization_failure_leaves_sidecar_and_withholds_marker(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, sidecar, _row, settings = _one_index_harness(mocker, tmp_path)+ faiss_path.write_bytes(b"old index")+ mocker.patch.object(rekey, "_load_uuid_to_id", return_value={"a": 1})+ mocker.patch.object(rekey, "rekey_index_file")+ manager = MagicMock()+ manager.record_file.side_effect = OSError("integrity database unavailable")+ mocker.patch.object(rekey, "FileIntegrityManager", return_value=manager)++ stats = rekey.rekey_user_indexes("alice", "password")++ manager.record_file.assert_called_once()+ assert stats["rekeyed"] == 0+ assert sidecar.exists()+ settings.set_setting.assert_not_called()diff --git a/tests/vector_stores/test_legacy_rekey_finalization_edges.py b/tests/vector_stores/test_legacy_rekey_finalization_edges.pynew file mode 100644index 0000000000..a849bbce2a--- /dev/null+++ b/tests/vector_stores/test_legacy_rekey_finalization_edges.py@@ -0,0 +1,108 @@+"""Completion-marker edge tests for phase-2 legacy re-keying.++The tests cover branches where apparently completed work must remain retryable+because a legacy plaintext companion or a quarantine/finalization step failed.+"""++import threading+from collections.abc import Iterator+from contextlib import contextmanager+from pathlib import Path+from unittest.mock import MagicMock++from pytest_mock import MockerFixture++import local_deep_research.vector_stores.legacy_rekey as rekey+++@contextmanager+def _session_context(session: MagicMock) -> Iterator[MagicMock]:+ yield session+++def _one_index_harness(+ mocker: MockerFixture, tmp_path: Path, *, sidecar: bool = True+) -> tuple[Path, MagicMock]:+ faiss_path = tmp_path / "legacy.faiss"+ sidecar_path = tmp_path / "legacy.idmap.json"+ if sidecar:+ sidecar_path.write_text('{"0": "a"}', encoding="utf-8")+ rag_index = MagicMock()+ rag_index.id = 17+ rag_index.index_path = str(faiss_path)+ rag_index.collection_name = "collection_edge"+ rag_index.embedding_dimension = 2+ rag_index.index_type = "flat"+ rag_index.distance_metric = "l2"+ rag_index.normalize_vectors = False+ settings = MagicMock()+ settings.get_bool_setting.return_value = False+ session = MagicMock()+ session.query.return_value.all.return_value = [rag_index]+ mocker.patch.object(+ rekey,+ "get_user_db_session",+ # One fresh context manager per call: the orchestrator opens a+ # second session when persisting rekeyed config (legacy_rekey.py:146).+ side_effect=lambda *args, **kwargs: _session_context(session),+ )+ mocker.patch.object(rekey, "get_settings_manager", return_value=settings)+ mocker.patch(+ "local_deep_research.research_library.services.library_rag_service."+ "_get_faiss_write_lock",+ # Head returns a _TrackedRLock (an RLock wrapper); RLock() here+ # matches its reentrancy instead of a plain, non-reentrant Lock().+ return_value=threading.RLock(),+ )+ return faiss_path, settings+++def test_already_migrated_index_with_unremovable_plaintext_withholds_marker(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, settings = _one_index_harness(mocker, tmp_path, sidecar=False)+ faiss_path.write_bytes(b"migrated index")+ mocker.patch.object(rekey, "_is_idmap2", return_value=True)+ mocker.patch.object(rekey, "_purge_redundant_pkl", return_value=False)++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["skipped_no_sidecar"] == 1+ settings.set_setting.assert_not_called()+++def test_rekey_failure_with_successful_quarantine_counts_resolution(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, settings = _one_index_harness(mocker, tmp_path)+ faiss_path.write_bytes(b"old index")+ mocker.patch.object(rekey, "_load_uuid_to_id", return_value={"a": 1})+ mocker.patch.object(+ rekey, "rekey_index_file", side_effect=ValueError("corrupt")+ )+ quarantine = mocker.patch.object(rekey, "_quarantine_and_reset")++ stats = rekey.rekey_user_indexes("alice", "password")++ assert stats["quarantined"] == 1+ quarantine.assert_called_once()+ settings.set_setting.assert_called_once_with(+ rekey.REKEY_MARKER_SETTING, True+ )+++def test_rekeyed_index_with_unremovable_plaintext_remains_retryable(+ tmp_path: Path, mocker: MockerFixture+) -> None:+ faiss_path, settings = _one_index_harness(mocker, tmp_path)+ faiss_path.write_bytes(b"old index")+ mocker.patch.object(rekey, "_load_uuid_to_id", return_value={"a": 1})+ successful_rekey = mocker.patch.object(rekey, "rekey_index_file")+ mocker.patch.object(rekey, "_purge_redundant_pkl", return_value=False)+ mocker.patch.object(rekey, "FileIntegrityManager")++ stats = rekey.rekey_user_indexes("alice", "password")++ successful_rekey.assert_called_once()+ assert stats["rekeyed"] == 1+ settings.set_setting.assert_not_called()