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(security): close FAISS pickle-deserialization RCE with a restricted unpickler (#4632)

LearningCircuit45b779723571
diff --git a/changelog.d/4632.security.md b/changelog.d/4632.security.md
new file mode 100644
index 0000000000..cf990de0f3
--- /dev/null
+++ b/changelog.d/4632.security.md
@@ -0,0 +1 @@
+FAISS RAG indexes are now loaded through a restricted unpickler that only permits the two classes a legitimate docstore contains, instead of `FAISS.load_local(..., allow_dangerous_deserialization=True)`. A tampered `index.pkl` (the docstore pickle that is actually deserialized) can no longer execute arbitrary code on load — closing the pickle-deserialization RCE for every case, including a first-encounter index with no integrity record and a `.pkl`-only swap that leaves the `.faiss` checksum unchanged. The fix needs no integrity record, schema change, or re-indexing. The loader is fail-closed: if a future LangChain/Pydantic upgrade changes the docstore pickle format to use other classes, affected indexes raise `UnpicklingError` on load (and are quarantined and rebuilt) rather than silently deserializing — recover by re-indexing the affected collection, or by widening the loader's allow-list to the new class.
diff --git a/src/local_deep_research/research_library/services/faiss_safe_load.py b/src/local_deep_research/research_library/services/faiss_safe_load.py
new file mode 100644
index 0000000000..e07ce2bd44
--- /dev/null
+++ b/src/local_deep_research/research_library/services/faiss_safe_load.py
@@ -0,0 +1,143 @@
+"""Safe loading of on-disk FAISS indexes.
+
+LangChain's ``FAISS.load_local(..., allow_dangerous_deserialization=True)``
+deserializes the ``<index>.pkl`` docstore companion with a raw
+``pickle.load`` (see ``langchain_community/vectorstores/faiss.py``). Pickle
+executes arbitrary code during deserialization, so a tampered ``.pkl``
+dropped into the index directory yields arbitrary code execution when the
+index is next loaded.
+
+The ``.faiss`` and ``.pkl`` files are loaded independently with no
+cross-check, so a content checksum over only the ``.faiss`` file (which is
+what the file-integrity system records) provides **no** protection against a
+``.pkl``-only swap. Rather than gate the dangerous load behind a checksum,
+this module removes the dangerous deserialization entirely: it replicates
+``load_local`` but unpickles the docstore through a restricted unpickler that
+only permits the two classes a legitimate FAISS docstore contains
+(:class:`InMemoryDocstore` and :class:`Document`). Any other global
+(``os.system``, ``subprocess.Popen``, a crafted ``__reduce__`` payload, …)
+raises :class:`pickle.UnpicklingError` before it can execute.
+
+The payload is the 2-tuple ``(docstore, index_to_docstore_id)`` written by
+``FAISS.save_local``; the metadata it carries is plain JSON-ish scalars
+(str/int/float/bool/None/list/dict), none of which require a class global to
+unpickle. If a future LangChain/Pydantic version changes the on-disk format
+to need additional classes, loading fails closed (a clear error) rather than
+silently — and the round-trip test in
+``tests/research_library/services/test_faiss_safe_load.py`` will catch it so
+the allow-list can be widened deliberately.
+"""
+
+import pickle
+from pathlib import Path
+from typing import Any
+
+from langchain_community.vectorstores import FAISS
+from langchain_community.vectorstores.faiss import dependable_faiss_import
+from langchain_core.embeddings import Embeddings
+
+# (module, qualname) pairs that a legitimate FAISS docstore pickle resolves
+# via ``Unpickler.find_class``. Determined empirically by round-tripping a
+# real ``save_local`` payload with varied metadata; only these two appear.
+_ALLOWED_GLOBALS = frozenset(
+ {
+ ("langchain_community.docstore.in_memory", "InMemoryDocstore"),
+ ("langchain_core.documents.base", "Document"),
+ }
+)
+
+
+# Subclass the PURE-PYTHON unpickler (``pickle._Unpickler``), NOT the default
+# C ``pickle.Unpickler``. We need to override ``get_extension`` to refuse the
+# copyreg extension opcodes (EXT1/EXT2/EXT4), and only the pure-Python unpickler
+# routes those opcodes through an overridable ``get_extension`` method — the C
+# unpickler resolves them internally. (Why ``get_extension`` and not just
+# ``find_class``: both unpicklers normally route EXT through ``find_class`` on a
+# cold cache, but ``get_extension`` short-circuits on a warm process-global
+# ``copyreg._extension_cache`` and skips ``find_class`` entirely. Refusing
+# ``get_extension`` outright closes that path regardless of cache/registry
+# state, instead of relying on the extension registry happening to be empty.)
+# ``_Unpickler`` has been the stable pure-Python name since Python 3.0; if a
+# future runtime drops it, this fails loudly at import (caught by tests) rather
+# than silently falling back to the C unpickler.
+class _RestrictedFaissUnpickler(pickle._Unpickler):
+ """Unpickler that only resolves the classes a FAISS docstore contains.
+
+ Defense is by construction: a malicious pickle can never obtain an
+ attacker-chosen callable to invoke, because every opcode that resolves a
+ global or callable is refused or allow-listed:
+
+ - ``find_class`` (GLOBAL/STACK_GLOBAL/INST/OBJ, then REDUCE/NEWOBJ/BUILD)
+ allow-lists only ``InMemoryDocstore`` and ``Document`` — both inert.
+ - ``get_extension`` (copyreg EXT1/EXT2/EXT4) is refused outright; a
+ legitimate FAISS docstore pickle never uses copyreg extensions.
+ - ``persistent_load`` (PERSID/BINPERSID) is refused outright; ``save_local``
+ never emits persistent ids.
+ """
+
+ def find_class(self, module: str, name: str) -> Any:
+ if (module, name) in _ALLOWED_GLOBALS:
+ return super().find_class(module, name)
+ raise pickle.UnpicklingError(
+ f"Refusing to unpickle disallowed object '{module}.{name}' from "
+ f"FAISS docstore (possible tampering)."
+ )
+
+ def get_extension(self, code: int) -> Any:
+ raise pickle.UnpicklingError(
+ f"Refusing to resolve copyreg extension code {code} from FAISS "
+ f"docstore (possible tampering)."
+ )
+
+ def persistent_load(self, pid: Any) -> Any:
+ raise pickle.UnpicklingError(
+ "Refusing to resolve a persistent id from FAISS docstore "
+ "(possible tampering)."
+ )
+
+
+def safe_load_faiss(
+ folder_path: str,
+ embeddings: Embeddings,
+ *,
+ index_name: str,
+ normalize_L2: bool = False,
+) -> FAISS:
+ """Load a FAISS index from disk without dangerous deserialization.
+
+ Drop-in replacement for ``FAISS.load_local(...,
+ allow_dangerous_deserialization=True)`` for the index/docstore layout
+ this project writes via ``FAISS.save_local``.
+
+ Args:
+ folder_path: Directory containing ``<index_name>.faiss`` and
+ ``<index_name>.pkl``.
+ embeddings: Embeddings used for subsequent queries.
+ index_name: Base name of the index files (the ``.faiss`` stem).
+ normalize_L2: Whether vectors are L2-normalized (must match how the
+ index was built).
+
+ Returns:
+ A :class:`FAISS` vector store.
+
+ Raises:
+ pickle.UnpicklingError: If the ``.pkl`` references any class outside
+ the allow-list (tampering or an unexpected format change).
+ """
+ path = Path(folder_path)
+
+ # The .faiss file is a binary FAISS index (not pickle); read it as usual.
+ faiss = dependable_faiss_import()
+ index = faiss.read_index(str(path / f"{index_name}.faiss"))
+
+ # The .pkl is the only attack surface — unpickle it under restriction.
+ with open(path / f"{index_name}.pkl", "rb") as f:
+ docstore, index_to_docstore_id = _RestrictedFaissUnpickler(f).load()
+
+ return FAISS(
+ embeddings,
+ index,
+ docstore,
+ index_to_docstore_id,
+ normalize_L2=normalize_L2,
+ )
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 41dd709b9a..f86caffb75 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
@@ -40,6 +40,7 @@ import hashlib
from faiss import IndexFlatL2, IndexFlatIP, IndexHNSWFlat
from langchain_community.vectorstores import FAISS
from langchain_community.docstore.in_memory import InMemoryDocstore
+from .faiss_safe_load import safe_load_faiss
from ...constants import DEFAULT_SEARCH_TOOL
@@ -624,11 +625,14 @@ class LibraryRAGService:
)
if verified:
try:
- self.faiss_index = FAISS.load_local(
+ # safe_load_faiss replaces load_local's dangerous
+ # pickle deserialization with a restricted unpickler
+ # (see faiss_safe_load) so a tampered .pkl cannot
+ # execute code on load.
+ self.faiss_index = safe_load_faiss(
str(index_path.parent),
self.embedding_manager.embeddings,
index_name=index_path.stem,
- allow_dangerous_deserialization=True,
normalize_L2=True,
)
except Exception:
@@ -792,12 +796,14 @@ class LibraryRAGService:
rag_index.embedding_dimension = current_dim
# Fall through to create new index below
else:
- # Dimensions match (or no stored dimension), load index
- faiss_index = FAISS.load_local(
+ # Dimensions match (or no stored dimension), load
+ # index via the restricted-unpickler loader (see
+ # faiss_safe_load) instead of load_local, so a
+ # tampered .pkl cannot execute code on load.
+ faiss_index = safe_load_faiss(
str(index_path.parent),
self.embedding_manager.embeddings,
index_name=index_path.stem,
- allow_dangerous_deserialization=True,
normalize_L2=True,
)
logger.info(
diff --git a/tests/research_library/services/test_faiss_safe_load.py b/tests/research_library/services/test_faiss_safe_load.py
new file mode 100644
index 0000000000..8b9e742e35
--- /dev/null
+++ b/tests/research_library/services/test_faiss_safe_load.py
@@ -0,0 +1,184 @@
+"""Tests for the restricted-unpickler FAISS loader (faiss_safe_load).
+
+Covers:
+- A real ``FAISS.save_local`` index round-trips through ``safe_load_faiss``
+ (proves the restricted unpickler accepts legitimate docstore payloads).
+- A malicious pickle that would execute code under a plain ``pickle.load`` is
+ rejected before execution (proves the RCE is actually closed, including the
+ realistic ".pkl-only swap" where the .faiss is left byte-identical).
+"""
+
+import datetime
+import io
+import pickle
+from pathlib import Path
+
+import pytest
+from langchain_community.docstore.in_memory import InMemoryDocstore
+from langchain_community.vectorstores import FAISS
+from langchain_core.documents import Document
+
+from local_deep_research.research_library.services.faiss_safe_load import (
+ _RestrictedFaissUnpickler,
+ safe_load_faiss,
+)
+
+try: # location varies across langchain versions
+ from langchain_community.embeddings import FakeEmbeddings
+except Exception: # pragma: no cover
+ from langchain_core.embeddings import FakeEmbeddings
+
+
+def _build_and_save(
+ dir_path: Path, index_name: str = "index"
+) -> FakeEmbeddings:
+ """Create a small real FAISS index on disk and return its embeddings."""
+ emb = FakeEmbeddings(size=16)
+ texts = ["alpha chunk", "beta chunk", "gamma chunk"]
+ # Metadata mirrors what the RAG service attaches: plain scalars + lists.
+ metas = [
+ {"source": "a.pdf", "page": 1, "word_count": 2, "authors": None},
+ {"source": "b.pdf", "page": 2, "tags": ["x", "y"]},
+ {"source": "c.pdf", "score": 0.9, "nested": {"k": 1}},
+ ]
+ vs = FAISS.from_texts(texts, emb, metadatas=metas)
+ vs.save_local(str(dir_path), index_name=index_name)
+ return emb
+
+
+class TestSafeLoadRoundTrip:
+ def test_loads_real_index(self, tmp_path):
+ emb = _build_and_save(tmp_path)
+ vs = safe_load_faiss(
+ str(tmp_path), emb, index_name="index", normalize_L2=True
+ )
+ contents = {d.page_content for d in vs.docstore._dict.values()}
+ assert contents == {"alpha chunk", "beta chunk", "gamma chunk"}
+ assert len(vs.index_to_docstore_id) == 3
+ # Metadata (scalars, list, nested dict) survives the restricted load.
+ metas = [d.metadata for d in vs.docstore._dict.values()]
+ assert any(m.get("tags") == ["x", "y"] for m in metas)
+ # normalize_L2 is threaded into the FAISS constructor by hand — guard
+ # it, since a silent drop would corrupt cosine-distance search.
+ assert vs._normalize_L2 is True
+
+ def test_normalize_l2_defaults_false(self, tmp_path):
+ emb = _build_and_save(tmp_path)
+ vs = safe_load_faiss(str(tmp_path), emb, index_name="index")
+ assert vs._normalize_L2 is False
+
+ def test_search_works_after_safe_load(self, tmp_path):
+ emb = _build_and_save(tmp_path)
+ vs = safe_load_faiss(str(tmp_path), emb, index_name="index")
+ results = vs.similarity_search("alpha", k=1)
+ assert len(results) == 1
+
+
+# Module-level helpers so pickle can reference them by qualified name. The
+# payload writes a marker file instead of doing real harm, so the test can
+# prove (a) it WOULD run under plain pickle and (b) it does NOT under the
+# restricted unpickler.
+def _write_marker(path: str):
+ Path(path).write_text("EXECUTED")
+ return InMemoryDocstore({})
+
+
+class _Evil:
+ def __init__(self, marker: str):
+ self._marker = marker
+
+ def __reduce__(self):
+ return (_write_marker, (self._marker,))
+
+
+class TestSafeLoadBlocksMalicious:
+ def test_restricted_unpickler_blocks_and_does_not_execute(self, tmp_path):
+ marker = tmp_path / "marker.txt"
+ blob = pickle.dumps((_Evil(str(marker)), {0: "id"}))
+
+ # Sanity: a plain pickle.load DOES execute the payload. This
+ # unsafe call is the point of the test — it demonstrates the very
+ # RCE that safe_load_faiss prevents, on a benign marker payload.
+ pickle.loads(blob) # noqa: S301
+ assert marker.read_text() == "EXECUTED"
+ marker.unlink()
+
+ # The restricted unpickler refuses and never runs the payload.
+ with pytest.raises(pickle.UnpicklingError):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+ assert not marker.exists()
+
+ def test_safe_load_faiss_rejects_pkl_only_swap(self, tmp_path):
+ """The realistic attack: leave .faiss byte-identical, swap the .pkl."""
+ emb = _build_and_save(tmp_path) # valid .faiss + .pkl
+ marker = tmp_path / "marker.txt"
+ faiss_before = (tmp_path / "index.faiss").read_bytes()
+
+ (tmp_path / "index.pkl").write_bytes(
+ pickle.dumps((_Evil(str(marker)), {0: "id"}))
+ )
+
+ with pytest.raises(pickle.UnpicklingError):
+ safe_load_faiss(str(tmp_path), emb, index_name="index")
+ assert not marker.exists()
+ # We did not touch the .faiss (mirrors the attack precondition).
+ assert (tmp_path / "index.faiss").read_bytes() == faiss_before
+
+ def test_blocks_copyreg_extension_opcode_even_when_cache_warm(
+ self, tmp_path
+ ):
+ """copyreg EXT1/EXT2/EXT4 opcodes resolve a callable via the extension
+ registry. ``find_class`` alone is NOT enough: ``get_extension``
+ short-circuits on the process-global ``copyreg._extension_cache`` and
+ skips ``find_class`` once a code has been resolved. So this test WARMS
+ the cache first (a plain ``pickle.loads`` that runs the payload), which
+ is exactly the state in which a ``find_class``-only guard would be
+ bypassed — then asserts the restricted unpickler still refuses (proving
+ the ``get_extension`` override, not ``find_class``, does the blocking).
+ """
+ import copyreg
+ import pickletools
+
+ marker = tmp_path / "marker.txt"
+ code = 0xC0DE
+ copyreg.add_extension(
+ _write_marker.__module__, _write_marker.__name__, code
+ )
+ try:
+ blob = pickle.dumps((_Evil(str(marker)), {0: "id"}), protocol=2)
+ # Guard: the payload must actually use an EXT opcode, else this
+ # test would pass for the wrong reason.
+ op_names = [op.name for op, _, _ in pickletools.genops(blob)]
+ assert any(n.startswith("EXT") for n in op_names), op_names
+
+ # Warm copyreg._extension_cache for this code. A find_class-only
+ # restricted unpickler would now be bypassed on the EXT path.
+ pickle.loads(blob) # noqa: S301
+ assert marker.exists() # confirms the cache is now warm
+ marker.unlink()
+
+ with pytest.raises(pickle.UnpicklingError):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
+ assert not marker.exists()
+ finally:
+ copyreg.remove_extension(
+ _write_marker.__module__, _write_marker.__name__, code
+ )
+ # Drop the warmed cache entry so it can't leak into other tests.
+ copyreg._extension_cache.pop(code, None)
+
+ def test_blocks_disallowed_class_buried_in_metadata(self):
+ """The allow-list applies to EVERY global the pickle resolves, not
+ just the top-level docstore class. A disallowed class hidden inside a
+ Document's metadata (here a benign ``datetime``) must still be
+ refused — otherwise an attacker could smuggle a gadget through a
+ nested value while the outer objects look legitimate.
+ """
+ doc = Document(
+ page_content="x",
+ metadata={"created": datetime.datetime(2026, 1, 1)},
+ )
+ blob = pickle.dumps((InMemoryDocstore({"id1": doc}), {0: "id1"}))
+
+ with pytest.raises(pickle.UnpicklingError, match="datetime"):
+ _RestrictedFaissUnpickler(io.BytesIO(blob)).load()
diff --git a/tests/research_library/services/test_library_rag_service.py b/tests/research_library/services/test_library_rag_service.py
index 282bfbe81f..4571499827 100644
--- a/tests/research_library/services/test_library_rag_service.py
+++ b/tests/research_library/services/test_library_rag_service.py
@@ -765,10 +765,11 @@ class TestLoadOrCreateFaissIndexEdgeCases:
# Mock Path.exists to return True
mocker.patch("pathlib.Path.exists", return_value=True)
- # Mock FAISS.load_local
+ # Mock the safe loader (replaces FAISS.load_local's dangerous
+ # deserialization)
mock_faiss_index = Mock()
mocker.patch(
- "local_deep_research.research_library.services.library_rag_service.FAISS.load_local",
+ "local_deep_research.research_library.services.library_rag_service.safe_load_faiss",
return_value=mock_faiss_index,
)
@@ -783,8 +784,8 @@ class TestLoadOrCreateFaissIndexEdgeCases:
result = service.load_or_create_faiss_index("collection-123")
- # Should return the loaded index
- assert result is not None
+ # Should return the index loaded via the safe loader (not a fresh one)
+ assert result is mock_faiss_index
def test_load_or_create_handles_corrupted_index(self, mocker):
"""Creates new index when existing one is corrupted."""
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 2826452e08..c6223ec672 100644
--- a/tests/research_library/services/test_library_rag_service_coverage.py
+++ b/tests/research_library/services/test_library_rag_service_coverage.py
@@ -368,11 +368,12 @@ class TestLoadOrCreateFaissIndex:
svc.load_or_create_faiss_index("coll-1")
mock_flat_l2.assert_called_once_with(384)
+ @patch(f"{_MOD}.safe_load_faiss")
@patch(f"{_MOD}.FAISS")
@patch(f"{_MOD}.InMemoryDocstore")
@patch(f"{_MOD}.IndexFlatIP")
def test_verified_load_returns_existing_index(
- self, mock_flat_ip, mock_docstore, mock_faiss_cls
+ self, mock_flat_ip, mock_docstore, mock_faiss_cls, mock_safe_load
):
svc = _make_service()
svc.embedding_manager = MagicMock()
@@ -385,12 +386,16 @@ class TestLoadOrCreateFaissIndex:
self._patch_get_or_create(svc, rag_idx)
mock_loaded = MagicMock()
- mock_faiss_cls.load_local.return_value = mock_loaded
+ mock_safe_load.return_value = mock_loaded
with patch.object(Path, "exists", return_value=True):
result = svc.load_or_create_faiss_index("coll-1")
+ # Verified index is loaded via the restricted-unpickler loader,
+ # never via the dangerous FAISS.load_local.
assert result is mock_loaded
+ mock_safe_load.assert_called_once()
+ mock_faiss_cls.load_local.assert_not_called()
@patch(f"{_MOD}.FAISS")
@patch(f"{_MOD}.InMemoryDocstore")
@@ -512,16 +517,23 @@ class TestLoadOrCreateFaissIndex:
# A new FAISS should be created (not loaded)
mock_faiss_cls.assert_called_once()
+ @patch(f"{_MOD}.safe_load_faiss")
@patch(f"{_MOD}.FAISS")
@patch(f"{_MOD}.InMemoryDocstore")
@patch(f"{_MOD}.IndexFlatIP")
def test_load_failure_quarantines_and_creates_new_index(
- self, mock_flat_ip, mock_docstore, mock_faiss_cls, tmp_path
+ self,
+ mock_flat_ip,
+ mock_docstore,
+ mock_faiss_cls,
+ mock_safe_load,
+ tmp_path,
):
- """When load_local raises (torn .pkl, malformed pickle), the
- .faiss and .pkl are quarantined before falling through to a
- fresh index. Previously the old code silently discarded the
- broken-state files without preserving evidence.
+ """When the loader raises (torn .pkl, malformed pickle, or a
+ rejected/tampered pickle), the .faiss and .pkl are quarantined
+ before falling through to a fresh index. Previously the old code
+ silently discarded the broken-state files without preserving
+ evidence.
"""
svc = _make_service()
svc.embedding_manager = MagicMock()
@@ -538,7 +550,7 @@ class TestLoadOrCreateFaissIndex:
rag_idx.index_path = str(idx_path)
self._patch_get_or_create(svc, rag_idx)
- mock_faiss_cls.load_local.side_effect = RuntimeError("corrupted file")
+ mock_safe_load.side_effect = RuntimeError("corrupted file")
svc.load_or_create_faiss_index("coll-1")
@@ -1321,7 +1333,7 @@ class TestMergeAndPersistLocked:
new_chunk = LangchainDocument(page_content="our new content")
- with patch.object(mod.FAISS, "load_local", return_value=fresh_index):
+ with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
stats = svc._merge_and_persist_locked(
index_path,
[new_chunk],
@@ -1363,7 +1375,7 @@ class TestMergeAndPersistLocked:
fresh_index = MagicMock()
fresh_index.docstore._dict = {"shared-id": MagicMock()}
- with patch.object(mod.FAISS, "load_local", return_value=fresh_index):
+ with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
stats = svc._merge_and_persist_locked(
index_path,
[LangchainDocument(page_content="duplicate")],
@@ -1398,7 +1410,7 @@ class TestMergeAndPersistLocked:
fresh_index = MagicMock()
fresh_index.docstore._dict = {"to-update": MagicMock()}
- with patch.object(mod.FAISS, "load_local", return_value=fresh_index):
+ with patch.object(mod, "safe_load_faiss", return_value=fresh_index):
svc._merge_and_persist_locked(
index_path,
[LangchainDocument(page_content="updated")],
@@ -1414,7 +1426,7 @@ class TestMergeAndPersistLocked:
assert added_ids == ["to-update"]
def test_reload_failure_falls_back_to_in_memory(self, tmp_path):
- """If FAISS.load_local raises (torn write, partial pickle),
+ """If the loader raises (torn write, partial pickle),
the merge helper keeps the caller's in-memory state instead
of losing the write entirely.
"""
@@ -1434,7 +1446,7 @@ class TestMergeAndPersistLocked:
svc.faiss_index = in_memory
with patch.object(
- mod.FAISS, "load_local", side_effect=RuntimeError("torn pickle")
+ mod, "safe_load_faiss", side_effect=RuntimeError("torn pickle")
):
svc._merge_and_persist_locked(
index_path,
@@ -1517,15 +1529,15 @@ class TestMergeAndPersistLocked:
t1 = threading.Thread(target=worker, args=("A", go))
t2 = threading.Thread(target=worker, args=("B", go))
- # Patch FAISS.load_local ONCE, around both threads. Patching
+ # Patch safe_load_faiss ONCE, around both threads. Patching
# inside each worker (the original shape) is a hidden race:
- # ``patch.object`` rewrites a module attribute on the FAISS
- # class and is not thread-safe — when the first worker's
+ # ``patch.object`` rewrites a module attribute and is not
+ # thread-safe — when the first worker's
# ``with patch.object(...)`` block exits, it restores whatever
# it captured as "the original" at entry, which can be the
- # second worker's lambda OR the real ``load_local`` (depending
- # on which thread entered patch first). If the real
- # ``load_local`` becomes active mid-test, the second worker's
+ # second worker's lambda OR the real ``safe_load_faiss``
+ # (depending on which thread entered patch first). If the real
+ # ``safe_load_faiss`` becomes active mid-test, the second worker's
# reload step raises on the empty touched ``shared.faiss``,
# the production code's ``except`` branch falls back to the
# caller's stale in-memory MagicMock, and the worker's save is
@@ -1537,8 +1549,8 @@ class TestMergeAndPersistLocked:
# patched value is the only value visible while either worker
# runs.
with patch.object(
- mod.FAISS,
- "load_local",
+ mod,
+ "safe_load_faiss",
side_effect=lambda *a, **kw: make_index_proxy(),
):
t1.start()