Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

feat(faiss): add native vector deletion support (#1507)

Sameer Kadam07c74cc54422
diff --git a/semantica/context/erasure.py b/semantica/context/erasure.py
index 42fb2f51..8bcf7105 100644
--- a/semantica/context/erasure.py
+++ b/semantica/context/erasure.py
@@ -14,13 +14,15 @@ not. It *composes* the existing public APIs; nothing in ``context_graph.py`` or
``agent_memory.py`` changes, and ``ContextGraph`` keeps its graph-scope
contract.
-The property that matters is honest partial reporting. FAISS exposes no delete
-at all -- a flat FAISS index cannot remove individual vectors without a full
-rebuild -- so erasure is genuinely not completable on it today. Milvus and
-Weaviate now expose ``delete_vectors`` and are fully supported. The receipt
-says ``unsupported`` for FAISS rather than reporting a success it did not
-achieve -- a receipt that reads
-"graph: erased, memory: 14 erased, vectors: unsupported on faiss" is
+The property that matters is honest partial reporting. FAISS Flat indices now
+expose ``delete_vectors`` backed by native ``remove_ids``, so erasure is
+completable on them. FAISS IVF indices explicitly reject deletion because
+their internal labels are not compacted after ``remove_ids``, which would
+desynchronize search results from the ``vector_ids`` mapping. HNSW does not
+implement ``remove_ids`` at all. Both IVF and HNSW report ``unsupported``.
+Milvus and Weaviate are also fully supported. The receipt says ``unsupported``
+rather than reporting a success it did not achieve -- a receipt that reads
+"graph: erased, memory: 14 erased, vectors: unsupported on faiss/hnsw" is
actionable; a bare ``True`` is a compliance liability.
Example:
@@ -379,8 +381,9 @@ class ErasureCoordinator:
method_name, target = _vector_delete_capability(self.vector_store)
if method_name is None:
- # FAISS exposes no delete at all; it cannot remove vectors from a
- # flat index without a full rebuild.
+ # FAISS HNSW does not implement remove_ids and FAISS IVF
+ # does not compact labels after remove_ids. Only Flat indices
+ # currently support deletion via this code path.
self.logger.warning(
"Vector backend %r exposes no delete; %d vector id(s) for %r "
"were not erased",
diff --git a/semantica/vector_store/faiss_store.py b/semantica/vector_store/faiss_store.py
index 717b9e6e..f02595ec 100644
--- a/semantica/vector_store/faiss_store.py
+++ b/semantica/vector_store/faiss_store.py
@@ -128,6 +128,11 @@ class FAISSIndex:
self.index_type = index_type
self.vector_ids: List[str] = []
self.metadata: Dict[str, Dict[str, Any]] = {}
+ # Monotonic counter for default ID generation, mirroring FAISSStore._next_id.
+ # Persisted in the .meta.json sidecar so that load_index restores the
+ # correct value rather than deriving it from ntotal (which underestimates
+ # when vectors have been deleted and sparse gaps exist).
+ self.next_id: int = 0
def add_vectors(self, vectors: np.ndarray, ids: Optional[List[str]] = None):
"""
@@ -199,6 +204,98 @@ class FAISSIndex:
"""Get metadata by ID."""
return self.metadata.get(vector_id)
+ def delete_vectors(self, vector_ids_to_delete: List[str]) -> Dict[str, Any]:
+ """Remove vectors by their external string IDs.
+
+ Translates each requested external ID to its sequential internal FAISS
+ position, calls ``index.remove_ids`` with an ``IDSelectorBatch`` of
+ those positions, then updates ``vector_ids`` and ``metadata`` to match
+ the compacted index. The invariant ``len(self.vector_ids) ==
+ self.index.ntotal`` is re-checked after the operation.
+
+ **Persistence:** the deletion is in-memory only. Call
+ :meth:`FAISSStore.save_index` afterwards to write the updated state to
+ disk; without that call the deleted vectors will reappear on the next
+ process restart.
+
+ Args:
+ vector_ids_to_delete: External string IDs to remove. Unknown IDs
+ are silently ignored. Duplicate entries are deduplicated.
+
+ Returns:
+ ``{"delete_count": N}`` where *N* is the number of vectors
+ actually removed from the FAISS index (0 if none existed).
+
+ Raises:
+ NotImplementedError: If the underlying FAISS index type does not
+ support ``remove_ids`` (e.g. ``IndexHNSWFlat``). No state is
+ mutated before this is raised.
+ ProcessingError: For any other unexpected FAISS error.
+ """
+ if not vector_ids_to_delete:
+ return {"delete_count": 0}
+
+ delete_set = set(vector_ids_to_delete)
+
+ # Map external string IDs to sequential internal FAISS positions.
+ positions = [
+ pos
+ for pos, vid in enumerate(self.vector_ids)
+ if vid in delete_set
+ ]
+ if not positions:
+ return {"delete_count": 0}
+
+ # IVF-family indices (IndexIVFFlat, etc.) do NOT compact their internal
+ # labels after remove_ids: the surviving vectors keep their original
+ # sequential labels. The current architecture interprets search-result
+ # labels as offsets into vector_ids, so a non-compacting removal would
+ # silently return wrong external IDs and cause IndexError on labels
+ # beyond the compacted list length. Raise NotImplementedError here so
+ # callers get STATUS_UNSUPPORTED rather than silent data corruption.
+ # (Flat and PQ indices DO compact labels, so they are safe.)
+ if FAISS_AVAILABLE and isinstance(self.index, faiss.IndexIVF):
+ raise NotImplementedError(
+ f"The underlying FAISS index type ({type(self.index).__name__}) "
+ "does not compact internal labels after remove_ids, which would "
+ "desynchronize search labels from the vector_ids mapping. Use a "
+ "Flat index for deletion support, or rebuild the IVF index without "
+ "the deleted vectors."
+ )
+
+ sel = faiss.IDSelectorBatch(np.array(positions, dtype=np.int64))
+ try:
+ removed = self.index.remove_ids(sel)
+ except RuntimeError as exc:
+ if "not implemented" in str(exc).lower():
+ # HNSW and a handful of other index types do not implement
+ # remove_ids. Raise NotImplementedError so callers (and the
+ # ErasureCoordinator) can distinguish "unsupported" from a
+ # transient failure worth retrying.
+ raise NotImplementedError(
+ f"The underlying FAISS index type "
+ f"({type(self.index).__name__}) does not support "
+ "remove_ids(). Use a Flat index for deletion support, "
+ "or rebuild the index without the deleted vectors."
+ ) from exc
+ raise ProcessingError(f"FAISS remove_ids failed: {exc}") from exc
+
+ # Keep state consistent: update the Python-side list and metadata
+ # dict to mirror the now-compacted FAISS array. The list comprehension
+ # cannot raise, so the index and its metadata are always updated
+ # together (no partial-mutation window).
+ self.vector_ids = [vid for vid in self.vector_ids if vid not in delete_set]
+ for vid in delete_set:
+ self.metadata.pop(vid, None)
+
+ if len(self.vector_ids) != self.index.ntotal:
+ raise ProcessingError(
+ f"FAISSIndex invariant broken after delete_vectors: "
+ f"vector_ids={len(self.vector_ids)}, ntotal={self.index.ntotal}. "
+ "This indicates a bug in FAISS remove_ids or the deletion logic."
+ )
+ return {"delete_count": removed}
+
def save(self, path: Union[str, Path]):
"""Save index to disk.
@@ -223,6 +320,7 @@ class FAISSIndex:
"metadata": self.metadata,
"dimension": self.dimension,
"index_type": self.index_type,
+ "next_id": self.next_id,
},
cls=_LosslessJSONEncoder,
)
@@ -262,6 +360,12 @@ class FAISSIndex:
if persisted_index_type is not None:
index_type = persisted_index_type
+ # Restore the monotonic ID counter. Older sidecar files written
+ # before this field was added will not have the key; fall back to
+ # ntotal, which equals the counter value for stores that have never
+ # had a deletion (no gaps in label space).
+ persisted_next_id = data.get("next_id")
+
# Check for vector count vs sidecar ID count mismatch
if len(vector_ids) != index.ntotal:
raise ProcessingError(
@@ -279,10 +383,28 @@ class FAISSIndex:
)
vector_ids = []
metadata = {}
+ persisted_next_id = None
obj = cls(index, dimension, index_type)
obj.vector_ids = vector_ids
obj.metadata = metadata
+ # Restore the monotonic counter. Always clamp to at least the
+ # highest inferred vec_N ID, so a stale or corrupted persisted value
+ # (e.g. written before a deletion that shifted the gap) cannot cause
+ # future default IDs to collide with existing vector IDs.
+ _vec_nums = [
+ int(v[4:]) + 1
+ for v in vector_ids
+ if v.startswith("vec_") and v[4:].isdigit()
+ ]
+ _inferred = max(_vec_nums) if _vec_nums else index.ntotal
+ if persisted_next_id is not None:
+ # Trust the persisted value but never go below the inferred minimum
+ # (guards against stale/corrupted sidecars).
+ obj.next_id = max(int(persisted_next_id), _inferred)
+ else:
+ # Older sidecar files lack this field. Use the inferred value.
+ obj.next_id = _inferred
return obj
@@ -315,7 +437,7 @@ class FAISSSearch:
results = []
for i, (dist, idx) in enumerate(zip(distances[0], indices[0])):
- if idx < len(self.index.vector_ids):
+ if idx < len(self.index.vector_ids) and idx >= 0:
vector_id = self.index.vector_ids[idx]
dist_val = float(dist)
@@ -422,6 +544,12 @@ class FAISSStore:
self.index: Optional[FAISSIndex] = None
self.index_builder = FAISSIndexBuilder(dimension)
self.search_engine: Optional[FAISSSearch] = None
+ # Path remembered by load_index so delete_vectors can auto-save.
+ self._index_path: Optional[Path] = None
+ # Monotonic counter for default ID generation. Incremented on every
+ # successful add, never decremented on deletion, so ids generated by
+ # consecutive add_vectors calls can never collide with surviving IDs.
+ self._next_id: int = 0
# Check FAISS availability
if not FAISS_AVAILABLE:
@@ -498,13 +626,25 @@ class FAISSStore:
vectors = vectors.astype(np.float32)
- # Generate IDs if not provided
+ # Generate IDs if not provided. Use a monotonic counter so
+ # that default IDs never collide with surviving IDs after a
+ # deletion (len(vector_ids) would decrease, potentially reusing
+ # a label that still exists in the index).
if ids is None:
- ids = [
- f"vec_{len(self.index.vector_ids) + i}" for i in range(len(vectors))
- ]
-
- # Store metadata
+ _existing = set(self.index.vector_ids)
+ generated: List[str] = []
+ while len(generated) < len(vectors):
+ cand = f"vec_{self._next_id}"
+ self._next_id += 1
+ if cand not in _existing:
+ generated.append(cand)
+ _existing.add(cand)
+ ids = generated
+ # Sync FAISSIndex.next_id so save() persists the correct value.
+ self.index.next_id = self._next_id
+
+ # Assign metadata before the duplicate-skip filter so callers
+ # always get up-to-date metadata even for already-present ids.
if metadata:
self.progress_tracker.update_tracking(
tracking_id, message="Storing metadata..."
@@ -625,6 +765,12 @@ class FAISSStore:
self.index = FAISSIndex.load(path, self.dimension, index_type)
self.search_engine = FAISSSearch(self.index)
+ # Remember the path so delete_vectors can auto-save to the same location.
+ self._index_path = path
+ # Restore the monotonic counter from the sidecar (via FAISSIndex.next_id)
+ # rather than using ntotal. After a deletion ntotal is smaller than the
+ # highest generated ID, so ntotal would cause ID collisions on the next add.
+ self._next_id = self.index.next_id
self.logger.info(f"Loaded FAISS index from {path}")
return self.index
@@ -735,10 +881,62 @@ class FAISSStore:
"""Return the number of vectors currently tracked in this store.
Returns the length of the ``vector_ids`` list maintained by
- ``FAISSIndex``. FAISSStore does not implement vector deletion, so
- this list is strictly append-only and is always consistent with the
- underlying FAISS index (``index.ntotal``).
+ ``FAISSIndex``. This list is always kept consistent with the
+ underlying FAISS index (``index.ntotal``), including after deletions.
"""
if self.index is None:
return 0
return len(self.index.vector_ids)
+
+ def delete_vectors(self, vector_ids: List[str], **options) -> Dict[str, Any]:
+ """Delete vectors by their external string IDs.
+
+ Delegates to :meth:`FAISSIndex.delete_vectors`. When the store was
+ loaded from disk via :meth:`load_index`, the updated index and sidecar
+ are written back to disk before this method returns, so the deletion is
+ durable across process restarts without the caller needing a separate
+ :meth:`save_index` call. Note: only the ``.meta.json`` sidecar write
+ is atomic (temp-file + rename); the ``.faiss`` binary is written in
+ place. A process crash between those two writes would leave the files
+ inconsistent, but the mismatch guard in :meth:`FAISSIndex.load` would
+ detect it on the next load rather than silently returning wrong data.
+
+ No-op deletions (all requested IDs unknown, or empty input) do not
+ trigger a disk write.
+
+ When the store was created in memory (no :meth:`load_index` call), the
+ deletion is in-memory only and the caller must invoke
+ :meth:`save_index` to persist it.
+
+ IVF indices do not support deletion because their internal labels do
+ not compact after ``remove_ids``, which would desynchronize search
+ labels from the ``vector_ids`` mapping. HNSW indices also do not
+ support ``remove_ids``. Both raise ``NotImplementedError``, which the
+ :class:`ErasureCoordinator` translates to ``STATUS_UNSUPPORTED``.
+
+ Args:
+ vector_ids: External string IDs to delete. Unknown IDs are
+ silently ignored. Duplicates are deduplicated.
+ **options: Accepted for API parity with other backends; unused.
+
+ Returns:
+ ``{"delete_count": N}``
+
+ Raises:
+ ProcessingError: If no index has been initialized.
+ NotImplementedError: If the underlying index type (IVF or HNSW)
+ does not support safe deletion.
+ """
+ if self.index is None:
+ raise ProcessingError(
+ "Index not initialized. Call create_index() first."
+ )
+ result = self.index.delete_vectors(vector_ids)
+ # If the store was loaded from disk (load_index recorded the path),
+ # persist the deletion so that the vectors cannot be resurrected by a
+ # process restart. Only write when something was actually removed:
+ # a no-op deletion (all IDs unknown or empty list) must not trigger
+ # a full index rewrite.
+ if self._index_path is not None and result.get("delete_count", 0) > 0:
+ self.index.save(self._index_path)
+ return result
diff --git a/tests/vector_store/test_faiss_delete_vectors.py b/tests/vector_store/test_faiss_delete_vectors.py
new file mode 100644
index 00000000..5c98cd11
--- /dev/null
+++ b/tests/vector_store/test_faiss_delete_vectors.py
@@ -0,0 +1,662 @@
+"""Tests for FAISSIndex.delete_vectors and FAISSStore.delete_vectors (#1374)."""
+
+import numpy as np
+import pytest
+
+from semantica.context.erasure import (
+ STATUS_ERASED,
+ STATUS_UNSUPPORTED,
+ ErasureCoordinator,
+)
+from semantica.utils.exceptions import ProcessingError
+from semantica.vector_store import VectorStore
+from semantica.vector_store.faiss_store import FAISSIndex, FAISSStore
+
+
+# ---------------------------------------------------------------------------
+# Fixtures and helpers
+# ---------------------------------------------------------------------------
+
+
+def _flat_index(dim: int = 3) -> "faiss.IndexFlatL2": # noqa: F821
+ faiss = pytest.importorskip("faiss")
+ return faiss.IndexFlatL2(dim)
+
+
+def _populated_store(
+ dim: int = 3,
+ ids=("a", "b", "c", "d", "e"),
+ meta=None,
+):
+ """Return an FAISSStore with *ids* already inserted (random unit vectors)."""
+ faiss = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=dim)
+ n = len(ids)
+ rng = np.random.default_rng(seed=42)
+ vectors = rng.random((n, dim)).astype(np.float32)
+ metadata = meta or [{} for _ in ids]
+ store.add_vectors(vectors, ids=list(ids), metadata=metadata)
+ return store
+
+
+def _populated_index(dim: int = 3, ids=("a", "b", "c", "d", "e")):
+ """Return a bare FAISSIndex with *ids* inserted (random unit vectors)."""
+ faiss = pytest.importorskip("faiss")
+ idx = FAISSIndex(faiss.IndexFlatL2(dim), dimension=dim)
+ n = len(ids)
+ rng = np.random.default_rng(seed=42)
+ vectors = rng.random((n, dim)).astype(np.float32)
+ idx.add_vectors(vectors, ids=list(ids))
+ return idx
+
+
+# ---------------------------------------------------------------------------
+# FAISSIndex-level unit tests
+# ---------------------------------------------------------------------------
+
+
+class TestFAISSIndexDeleteVectors:
+ def test_delete_single_existing_id(self):
+ idx = _populated_index()
+ result = idx.delete_vectors(["b"])
+ assert result == {"delete_count": 1}
+ assert "b" not in idx.vector_ids
+ assert idx.index.ntotal == len(idx.vector_ids) == 4
+
+ def test_delete_multiple_existing_ids(self):
+ idx = _populated_index()
+ result = idx.delete_vectors(["b", "d"])
+ assert result == {"delete_count": 2}
+ assert "b" not in idx.vector_ids
+ assert "d" not in idx.vector_ids
+ assert sorted(idx.vector_ids) == ["a", "c", "e"]
+ assert idx.index.ntotal == 3
+
+ def test_delete_nonexistent_id_is_noop(self):
+ idx = _populated_index()
+ result = idx.delete_vectors(["z"])
+ assert result == {"delete_count": 0}
+ assert len(idx.vector_ids) == 5
+ assert idx.index.ntotal == 5
+
+ def test_delete_empty_list_is_noop(self):
+ idx = _populated_index()
+ result = idx.delete_vectors([])
+ assert result == {"delete_count": 0}
+ assert len(idx.vector_ids) == 5
+
+ def test_delete_duplicate_ids_in_request_only_removes_once(self):
+ idx = _populated_index()
+ result = idx.delete_vectors(["b", "b", "b"])
+ assert result == {"delete_count": 1}
+ assert "b" not in idx.vector_ids
+ assert len(idx.vector_ids) == 4
+
+ def test_delete_count_reflects_actual_removal(self):
+ idx = _populated_index()
+ # "z" doesn't exist; only "a" and "c" do
+ result = idx.delete_vectors(["a", "c", "z"])
+ assert result == {"delete_count": 2}
+
+ def test_metadata_removed_for_deleted_id(self):
+ faiss = pytest.importorskip("faiss")
+ idx = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ vectors = np.eye(3, dtype=np.float32)[:2]
+ idx.add_vectors(vectors, ids=["x", "y"])
+ idx.metadata = {"x": {"val": 1}, "y": {"val": 2}}
+ idx.delete_vectors(["x"])
+ assert "x" not in idx.metadata
+ assert "y" in idx.metadata
+
+ def test_vector_ids_list_stays_parallel_to_faiss_ntotal(self):
+ idx = _populated_index(ids=["a", "b", "c"])
+ idx.delete_vectors(["b"])
+ assert len(idx.vector_ids) == idx.index.ntotal == 2
+
+ def test_search_does_not_return_deleted_id(self):
+ """After deletion, similarity search must not return the deleted ID."""
+ faiss = pytest.importorskip("faiss")
+ idx = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ vectors = np.array(
+ [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=np.float32
+ )
+ idx.add_vectors(vectors, ids=["a", "b", "c"])
+ idx.delete_vectors(["b"])
+
+ query = np.array([[0.0, 1.0, 0.0]], dtype=np.float32)
+ distances, indices = idx.search(query, k=3)
+ # Filter both negative sentinels (-1) and out-of-range indices.
+ returned_ids = [
+ idx.vector_ids[i]
+ for i in indices[0]
+ if 0 <= i < len(idx.vector_ids)
+ ]
+ assert "b" not in returned_ids
+
+ def test_get_vector_returns_none_after_deletion(self):
+ faiss = pytest.importorskip("faiss")
+ idx = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ vectors = np.eye(3, dtype=np.float32)
+ idx.add_vectors(vectors, ids=["a", "b", "c"])
+ idx.delete_vectors(["b"])
+ assert idx.get_vector("b") is None
+
+ def test_get_metadata_returns_none_after_deletion(self):
+ faiss = pytest.importorskip("faiss")
+ idx = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ idx.add_vectors(np.eye(3, dtype=np.float32)[:2], ids=["a", "b"])
+ idx.metadata = {"a": {"k": 1}, "b": {"k": 2}}
+ idx.delete_vectors(["b"])
+ assert idx.get_metadata("b") is None
+
+ def test_add_vectors_after_deletion_works(self):
+ """Inserting new vectors after deletion maintains correct position mapping."""
+ idx = _populated_index(ids=["a", "b", "c"])
+ idx.delete_vectors(["b"])
+ new_vecs = np.array([[0.5, 0.5, 0.0]], dtype=np.float32)
+ idx.add_vectors(new_vecs, ids=["new"])
+ assert "new" in idx.vector_ids
+ assert len(idx.vector_ids) == idx.index.ntotal == 3
+
+ def test_save_load_after_deletion_preserves_state(self, tmp_path):
+ """Deletion persists correctly through save/load round-trip."""
+ _ = pytest.importorskip("faiss")
+ idx = _populated_index(ids=["a", "b", "c"])
+ idx.delete_vectors(["b"])
+
+ path = tmp_path / "idx.faiss"
+ idx.save(path)
+ loaded = FAISSIndex.load(path, dimension=3)
+
+ assert "b" not in loaded.vector_ids
+ assert sorted(loaded.vector_ids) == ["a", "c"]
+ assert loaded.index.ntotal == 2
+
+ def test_hnsw_delete_raises_not_implemented(self):
+ """HNSW does not support remove_ids; must raise NotImplementedError."""
+ faiss = pytest.importorskip("faiss")
+ hnsw = FAISSIndex(faiss.IndexHNSWFlat(4, 16), dimension=4)
+ vecs = np.random.rand(5, 4).astype(np.float32)
+ hnsw.add_vectors(vecs, ids=["a", "b", "c", "d", "e"])
+ with pytest.raises(NotImplementedError):
+ hnsw.delete_vectors(["a"])
+ # Python-side state must be untouched
+ assert len(hnsw.vector_ids) == 5
+
+ def test_ivf_delete_raises_not_implemented(self):
+ """IVF does not compact labels after remove_ids; raise NotImplementedError.
+
+ IVF surviving labels stay sparse (0,2,4 not 0,1,2), so the list-compact
+ approach used by Flat would desynchronize search labels from vector_ids.
+ """
+ faiss = pytest.importorskip("faiss")
+ dim = 4
+ train = np.random.rand(80, dim).astype(np.float32)
+ q = faiss.IndexFlatL2(dim)
+ ivf = faiss.IndexIVFFlat(q, dim, 2)
+ ivf.train(train)
+ idx = FAISSIndex(ivf, dimension=dim)
+ vecs = np.random.rand(5, dim).astype(np.float32)
+ idx.add_vectors(vecs, ids=["a", "b", "c", "d", "e"])
+ with pytest.raises(NotImplementedError):
+ idx.delete_vectors(["b"])
+ # Python-side state must be completely untouched
+ assert idx.vector_ids == ["a", "b", "c", "d", "e"]
+
+
+# ---------------------------------------------------------------------------
+# FAISSStore-level unit tests
+# ---------------------------------------------------------------------------
+
+
+class TestFAISSStoreDeleteVectors:
+ def test_delete_uninitialized_index_raises_processing_error(self):
+ store = FAISSStore(dimension=3)
+ with pytest.raises(ProcessingError, match="Index not initialized"):
+ store.delete_vectors(["a"])
+
+ def test_delete_existing_id_returns_dict(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b", "c"])
+ result = store.delete_vectors(["b"])
+ assert result == {"delete_count": 1}
+
+ def test_delete_reduces_count(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b", "c"])
+ assert store.count() == 3
+ store.delete_vectors(["b"])
+ assert store.count() == 2
+
+ def test_delete_multiple_ids(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b", "c", "d"])
+ result = store.delete_vectors(["a", "c"])
+ assert result == {"delete_count": 2}
+ assert store.count() == 2
+
+ def test_delete_empty_input_is_noop(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b"])
+ result = store.delete_vectors([])
+ assert result == {"delete_count": 0}
+ assert store.count() == 2
+
+ def test_delete_nonexistent_id_is_zero(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b"])
+ result = store.delete_vectors(["z"])
+ assert result == {"delete_count": 0}
+ assert store.count() == 2
+
+ def test_duplicate_ids_in_request(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b"])
+ result = store.delete_vectors(["a", "a"])
+ assert result == {"delete_count": 1}
+ assert store.count() == 1
+
+ def test_metadata_cleaned_up(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(
+ ids=["a", "b"],
+ meta=[{"owner": "alice"}, {"owner": "bob"}],
+ )
+ store.delete_vectors(["a"])
+ assert store.get_metadata("a") is None
+ assert store.get_metadata("b") == {"owner": "bob"}
+
+ def test_get_vector_returns_none_after_deletion(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b"])
+ store.delete_vectors(["a"])
+ assert store.get_vector("a") is None
+
+ def test_search_excludes_deleted_vector(self):
+ """search_similar must not return a deleted vector's ID."""
+ faiss = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vectors = np.array(
+ [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], dtype=np.float32
+ )
+ store.add_vectors(vectors, ids=["a", "b", "c"])
+ store.delete_vectors(["b"])
+ query = np.array([0.0, 1.0, 0.0], dtype=np.float32)
+ results = store.search_similar(query, k=3)
+ returned_ids = [r["id"] for r in results]
+ assert "b" not in returned_ids
+
+ def test_add_vectors_after_deletion(self):
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b", "c"])
+ store.delete_vectors(["b"])
+ vecs = np.array([[0.5, 0.5, 0.0]], dtype=np.float32)
+ store.add_vectors(vecs, ids=["new"])
+ assert store.count() == 3
+ assert store.get_vector("new") is not None
+
+ def test_save_load_after_deletion(self, tmp_path):
+ """Deleted vectors do not reappear after save/load."""
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b", "c"])
+ store.delete_vectors(["b"])
+
+ path = tmp_path / "store.faiss"
+ store.save_index(path)
+
+ fresh = FAISSStore(dimension=3)
+ fresh.load_index(path)
+
+ assert fresh.count() == 2
+ assert "b" not in fresh.index.vector_ids
+ assert fresh.get_vector("b") is None
+
+ def test_options_kwarg_is_accepted_and_ignored(self):
+ """delete_vectors(**options) must not crash even with extra kwargs."""
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a"])
+ result = store.delete_vectors(["a"], unused_option=True)
+ assert result["delete_count"] == 1
+
+ def test_hnsw_raises_not_implemented(self):
+ """FAISSStore.delete_vectors on HNSW must propagate NotImplementedError."""
+ faiss = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=4)
+ store.create_index(index_type="hnsw", metric="L2")
+ vecs = np.random.rand(5, 4).astype(np.float32)
+ store.add_vectors(vecs, ids=["a", "b", "c", "d", "e"])
+ with pytest.raises(NotImplementedError):
+ store.delete_vectors(["a"])
+ # Count must be unchanged
+ assert store.count() == 5
+
+ def test_ivf_raises_not_implemented(self):
+ """FAISSStore.delete_vectors on IVF must raise NotImplementedError.
+
+ IVF remove_ids preserves original labels rather than compacting them,
+ which would desynchronize search labels from vector_ids.
+ """
+ faiss = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=4)
+ # nlist=2 so we only need >= 2*39 = 78 training points
+ store.create_index(index_type="ivf", metric="L2", nlist=2)
+ train = np.random.rand(80, 4).astype(np.float32)
+ store.index.index.train(train)
+ store.add_vectors(train[:5], ids=["a", "b", "c", "d", "e"])
+ with pytest.raises(NotImplementedError):
+ store.delete_vectors(["a"])
+ # State must be completely unchanged
+ assert store.count() == 5
+
+ def test_delete_with_loaded_index_auto_saves(self, tmp_path):
+ """Deletion on a store loaded from disk auto-saves without explicit save_index."""
+ _ = pytest.importorskip("faiss")
+ # Create, populate, save
+ store = _populated_store(ids=["a", "b", "c"])
+ path = tmp_path / "store.faiss"
+ store.save_index(path)
+
+ # Load into a fresh store and delete
+ loaded = FAISSStore(dimension=3)
+ loaded.load_index(path)
+ loaded.delete_vectors(["b"])
+
+ # Reload without any additional save call — deletion must have persisted
+ reloaded = FAISSStore(dimension=3)
+ reloaded.load_index(path)
+ assert reloaded.count() == 2
+ assert "b" not in reloaded.index.vector_ids
+
+ def test_default_id_no_collision_after_deletion(self):
+ """Default vec_N IDs must not reuse a surviving ID after deletion."""
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["vec_0", "vec_1", "vec_2"])
+ # Delete the middle one; len(vector_ids) drops to 2
+ store.delete_vectors(["vec_1"])
+ assert store.count() == 2
+
+ # Add a new vector — without the monotonic counter, the default ID
+ # would be vec_2 which already exists and would be silently skipped.
+ new_vecs = np.random.rand(1, 3).astype(np.float32)
+ returned_ids = store.add_vectors(new_vecs)
+ # The returned ID must not be an existing one
+ assert returned_ids[0] not in {"vec_0", "vec_2"}, (
+ f"Default ID {returned_ids[0]} collides with a surviving ID"
+ )
+ # And the vector must actually have been inserted
+ assert store.count() == 3
+
+ def test_default_id_skip_past_explicit_id(self):
+ """Blocker: default IDs must skip over explicit IDs already in the store.
+
+ If a user inserts an explicit ``"vec_N"`` and then adds two vectors
+ without IDs, the generator must skip ``"vec_N"`` rather than
+ producing it and losing the second vector silently.
+ """
+ _ = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+
+ # Explicit vec_1 first
+ store.add_vectors(np.ones((1, 3), dtype=np.float32), ids=["vec_1"])
+
+ # 2 default vectors — one would collide with vec_1 if not skipped
+ store.add_vectors(np.ones((2, 3), dtype=np.float32))
+
+ # 1 more default vector — must get a fresh ID, not re-generate a used one
+ original_meta = {vid: {"original": vid} for vid in store.index.vector_ids}
+ for vid, m in original_meta.items():
+ store.index.metadata[vid] = m
+ count_before = store.count()
+
+ ret = store.add_vectors(
+ np.ones((1, 3), dtype=np.float32), metadata=[{"new": True}]
+ )
+ new_id = ret[0]
+
+ assert store.count() == count_before + 1, (
+ f"Vector was silently skipped; count stayed {store.count()}"
+ )
+ assert new_id not in original_meta, (
+ f"Generated ID {new_id!r} collides with an already-existing ID"
+ )
+ # Surviving IDs' metadata must not be overwritten
+ for vid, m in original_meta.items():
+ assert store.index.metadata.get(vid) == m, (
+ f"Metadata for surviving {vid!r} was overwritten"
+ )
+
+ def test_stale_persisted_next_id_is_clamped_to_inferred_minimum(self, tmp_path):
+ """Regression: a stale ``next_id`` in the sidecar must be clamped to
+ at least ``max(vec_N)+1`` so that auto-save after deletion cannot
+ propagate the stale value and cause future ID collisions.
+ """
+ import json as _json
+ _ = pytest.importorskip("faiss")
+ rng = np.random.default_rng(seed=3)
+ store = FAISSStore(dimension=3)
+ store.add_vectors(rng.random((5, 3)).astype(np.float32))
+ # IDs are vec_0..vec_4, next_id=5
+ path = tmp_path / "s.faiss"
+ store.save_index(path)
+
+ # Corrupt the sidecar: set next_id to a stale low value
+ meta = _json.loads((tmp_path / "s.faiss.meta.json").read_text())
+ meta["next_id"] = 2 # stale — vec_2, vec_3, vec_4 still exist
+ (tmp_path / "s.faiss.meta.json").write_text(_json.dumps(meta))
+
+ # Load and immediately delete one vector (auto-save fires)
+ s2 = FAISSStore(dimension=3)
+ s2.load_index(path)
+ assert s2._next_id == 5, f"Stale next_id should be clamped to 5, got {s2._next_id}"
+ s2.delete_vectors(["vec_3"]) # triggers auto-save
+
+ # The sidecar must not carry the stale value forward
+ persisted = _json.loads((tmp_path / "s.faiss.meta.json").read_text())
+ assert persisted["next_id"] >= 5, (
+ f"Auto-save propagated stale next_id={persisted['next_id']} (expected >= 5)"
+ )
+
+ def test_search_does_not_return_phantom_id_when_k_exceeds_ntotal(self):
+ """Regression: when k > ntotal, FAISS returns -1 sentinel values.
+ ``-1 < len(vector_ids)`` is always True in Python, so without an
+ explicit non-negative guard ``-1`` maps to ``vector_ids[-1]``,
+ making the last vector appear as a spurious extra result.
+ """
+ faiss = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vecs = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float32)
+ store.add_vectors(vecs, ids=["only_a", "only_b"])
+
+ # Ask for 10 neighbors but only 2 exist
+ results = store.search_similar(
+ np.array([0.0, 1.0, 0.0], dtype=np.float32), k=10
+ )
+ returned_ids = [r["id"] for r in results]
+ assert len(results) == 2, (
+ f"Expected exactly 2 results, got {len(results)}: {returned_ids}"
+ )
+ assert returned_ids.count("only_b") == 1, (
+ f"only_b appears {returned_ids.count('only_b')} time(s) — "
+ "sentinel -1 is mapping to vector_ids[-1]"
+ )
+
+ def test_next_id_persisted_across_delete_save_reload(self, tmp_path):
+ """Regression test for critical bug: delete → auto-save → reload → add.
+
+ Without persisting ``next_id`` in the sidecar, ``load_index`` would
+ set ``_next_id = ntotal`` (4 after one deletion from 5 vectors), which
+ would generate ``"vec_4"`` as the next default ID. That ID is still
+ present in the surviving vector list, so the insertion would be
+ silently skipped, the count would not increase, and the old vector's
+ metadata would be overwritten by the new metadata.
+
+ This test pins the full lifecycle so any regression is caught
+ immediately.
+ """
+ _ = pytest.importorskip("faiss")
+ rng = np.random.default_rng(seed=7)
+ dim = 4
+
+ # Step 1: create vec_0 .. vec_4, record their embeddings
+ store1 = FAISSStore(dimension=dim)
+ vecs = rng.random((5, dim)).astype(np.float32)
+ store1.add_vectors(vecs)
+ for vid in store1.index.vector_ids:
+ store1.index.metadata[vid] = {"original": vid}
+ path = tmp_path / "idx.faiss"
+ store1.save_index(path)
+
+ # Step 2: reload → delete vec_2 (auto-saves) → reload again
+ store2 = FAISSStore(dimension=dim)
+ store2.load_index(path)
+ store2.delete_vectors(["vec_2"]) # ntotal drops to 4; auto-save triggered
+
+ store3 = FAISSStore(dimension=dim)
+ store3.load_index(path)
+
+ # Step 3: add a new vector without an explicit ID
+ new_vec = rng.random((1, dim)).astype(np.float32)
+ count_before = store3.count()
+ returned_ids = store3.add_vectors(new_vec, metadata=[{"new": True}])
+
+ # The generated ID must not collide with any surviving ID
+ surviving = set(store3.index.vector_ids[:count_before])
+ new_id = returned_ids[0]
+ assert new_id not in surviving, (
+ f"Generated ID {new_id!r} collides with surviving ID "
+ f"(surviving={sorted(surviving)})"
+ )
+
+ # The new vector must actually have been inserted
+ assert store3.count() == count_before + 1, (
+ f"Count did not increase: was {count_before}, still {store3.count()}"
+ )
+
+ # The new vector must be retrievable
+ assert store3.get_vector(new_id) is not None, (
+ f"New vector with ID {new_id!r} is not retrievable"
+ )
+
+ # The surviving vec_4's embedding must be unchanged
+ original_vec4 = vecs[4]
+ loaded_vec4 = store3.get_vector("vec_4")
+ assert loaded_vec4 is not None
+ np.testing.assert_allclose(loaded_vec4, original_vec4, atol=1e-5,
+ err_msg="vec_4 embedding was corrupted by the new add")
+
+ # The surviving vec_4's metadata must be unchanged
+ assert store3.index.metadata.get("vec_4") == {"original": "vec_4"}, (
+ f"vec_4 metadata was overwritten: {store3.index.metadata.get('vec_4')}"
+ )
+
+ # The new vector's metadata must be the new value
+ assert store3.index.metadata.get(new_id) == {"new": True}
+
+ def test_no_op_delete_does_not_rewrite_disk(self, tmp_path):
+ """A deletion of only nonexistent IDs must not call FAISSIndex.save().
+
+ Uses a spy on ``FAISSIndex.save`` rather than filesystem mtime so the
+ assertion is deterministic regardless of filesystem timestamp resolution.
+ """
+ from unittest.mock import patch
+ _ = pytest.importorskip("faiss")
+ store = _populated_store(ids=["a", "b", "c"])
+ path = tmp_path / "idx.faiss"
+ store.save_index(path)
+
+ loaded = FAISSStore(dimension=3)
+ loaded.load_index(path)
+
+ with patch.object(loaded.index, "save", wraps=loaded.index.save) as mock_save:
+ loaded.delete_vectors(["z"]) # nonexistent → delete_count 0
+ loaded.delete_vectors([]) # empty list → delete_count 0
+ assert mock_save.call_count == 0, (
+ f"save() called {mock_save.call_count} time(s) for a no-op deletion"
+ )
+
+ # A real deletion must still trigger save()
+ loaded.delete_vectors(["b"])
+ assert mock_save.call_count == 1, (
+ f"save() was not called after a real deletion (calls={mock_save.call_count})"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Facade delegation test
+# ---------------------------------------------------------------------------
+
+
+class TestFAISSFacadeDelegation:
+ def test_vector_store_facade_delegates_to_faiss_store(self):
+ """VectorStore(backend='faiss').delete_vectors() must call FAISSStore."""
+ _ = pytest.importorskip("faiss")
+ vs = VectorStore(backend="faiss", config={"dimension": 3})
+ vecs = np.eye(3, dtype=np.float32)
+ vs.store_vectors(list(vecs), metadata=[{}, {}, {}])
+ # Count before
+ assert vs._backend_store.count() == 3
+
+ result = vs.delete_vectors(["vec_0"])
+
+ assert result == {"delete_count": 1}
+ assert vs._backend_store.count() == 2
+
+
+# ---------------------------------------------------------------------------
+# ErasureCoordinator integration tests
+# ---------------------------------------------------------------------------
+
+
+class TestFAISSErasureCoordinator:
+ def _faiss_vector_store(self, dim: int = 3) -> VectorStore:
+ _ = pytest.importorskip("faiss")
+ vs = VectorStore(backend="faiss", config={"dimension": dim})
+ vecs = np.eye(dim, dtype=np.float32)
+ vs.store_vectors(list(vecs), metadata=[{}, {}, {}])
+ return vs
+
+ def test_erasure_reports_status_erased(self):
+ vs = self._faiss_vector_store()
+ # store_vectors assigns ids "vec_0", "vec_1", "vec_2"
+ vector_ids = vs._backend_store.index.vector_ids
+ coord = ErasureCoordinator(vector_store=vs)
+ receipt = coord.erase_entity(vector_ids[0], vector_ids=[vector_ids[0]])
+ assert receipt.stores["vectors"]["status"] == STATUS_ERASED
+
+ def test_erasure_backend_name_is_faiss(self):
+ vs = self._faiss_vector_store()
+ coord = ErasureCoordinator(vector_store=vs)
+ receipt = coord.erase_entity("vec_0", vector_ids=["vec_0"])
+ assert receipt.stores["vectors"]["backend"] == "faiss"
+
+ def test_erasure_receipt_is_complete_after_deletion(self):
+ vs = self._faiss_vector_store()
+ coord = ErasureCoordinator(vector_store=vs)
+ receipt = coord.erase_entity("vec_0", vector_ids=["vec_0"])
+ assert receipt.complete
+
+ def test_erasure_hnsw_reports_unsupported(self):
+ """HNSW deletion raises NotImplementedError; coordinator must report unsupported."""
+ faiss = pytest.importorskip("faiss")
+ vs = VectorStore(backend="faiss", config={"dimension": 4})
+ vs._backend_store.create_index(index_type="hnsw", metric="L2")
+ vecs = np.random.rand(5, 4).astype(np.float32)
+ vs._backend_store.add_vectors(vecs, ids=["a", "b", "c", "d", "e"])
+ coord = ErasureCoordinator(vector_store=vs)
+ receipt = coord.erase_entity("a", vector_ids=["a"])
+ assert receipt.stores["vectors"]["status"] == STATUS_UNSUPPORTED
+ assert not receipt.complete
+
+ def test_erasure_ivf_reports_unsupported(self):
+ """IVF deletion raises NotImplementedError; coordinator must report unsupported."""
+ faiss = pytest.importorskip("faiss")
+ dim = 4
+ vs = VectorStore(backend="faiss", config={"dimension": dim})
+ vs._backend_store.create_index(index_type="ivf", metric="L2", nlist=2)
+ train = np.random.rand(80, dim).astype(np.float32)
+ vs._backend_store.index.index.train(train)
+ vs._backend_store.add_vectors(train[:5], ids=["a", "b", "c", "d", "e"])
+ coord = ErasureCoordinator(vector_store=vs)
+ receipt = coord.erase_entity("a", vector_ids=["a"])
+ assert receipt.stores["vectors"]["status"] == STATUS_UNSUPPORTED
+ assert not receipt.complete