Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix(vector_store): persist vector_ids and metadata across FAISS index save/load (#1272) (#1314)

Ahmad Bilal170b4215a621
diff --git a/semantica/vector_store/faiss_store.py b/semantica/vector_store/faiss_store.py
index dffe1507..717b9e6e 100644
--- a/semantica/vector_store/faiss_store.py
+++ b/semantica/vector_store/faiss_store.py
@@ -26,7 +26,7 @@ Example Usage:
>>> vector_ids = store.add_vectors(vectors, ids, metadata)
>>> results = store.search_similar(query_vector, k=10)
>>> store.save_index("index.faiss")
- >>>
+ >>>
>>> from semantica.vector_store import FAISSIndexBuilder
>>> builder = FAISSIndexBuilder(dimension=768)
>>> index = builder.build_index(index_type="ivf", metric="L2", nlist=100)
@@ -35,8 +35,13 @@ Author: Semantica Contributors
License: MIT
"""
+import base64
+import json
+import warnings
+from datetime import date, datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
+from uuid import UUID
import numpy as np
@@ -44,6 +49,60 @@ from ..utils.exceptions import ProcessingError, ValidationError
from ..utils.logging import get_logger
from ..utils.progress_tracker import get_progress_tracker
+
+class _LosslessJSONEncoder(json.JSONEncoder):
+ """JSON encoder that preserves types that are not natively JSON-serializable.
+
+ - ``bytes`` are base64-encoded under a ``__bytes__`` wrapper.
+ - sets are serialized as sorted lists under a ``__set__`` wrapper.
+ - NumPy integers and floats are converted to native Python int/float.
+ - NumPy arrays are converted to lists.
+ - ``datetime`` and ``date`` objects are serialized under ``__datetime__`` /
+ ``__date__`` wrappers with ISO-8601 strings.
+ - ``UUID`` objects are serialized under ``__uuid__`` wrapper.
+ """
+
+ def default(self, obj: Any) -> Any:
+ if isinstance(obj, bytes):
+ return {"__bytes__": base64.b64encode(obj).decode("ascii")}
+ if isinstance(obj, set):
+ return {"__set__": sorted(obj, key=str)}
+ if isinstance(obj, np.integer):
+ return int(obj)
+ if isinstance(obj, np.floating):
+ return float(obj)
+ if isinstance(obj, np.ndarray):
+ return obj.tolist()
+ if isinstance(obj, datetime):
+ return {"__datetime__": obj.isoformat()}
+ if isinstance(obj, date):
+ return {"__date__": obj.isoformat()}
+ if isinstance(obj, UUID):
+ return {"__uuid__": str(obj)}
+ return super().default(obj)
+
+
+def _lossless_object_hook(dct: Dict[str, Any]) -> Any:
+ """Object hook for ``json.loads`` that restores types encoded by
+ ``_LosslessJSONEncoder``.
+
+ Tagged dicts are checked with an exact-schema guard (``len(dct) == 1``)
+ so that dicts sharing a key name with a wrapper but carrying additional
+ keys are passed through unchanged.
+ """
+ if len(dct) == 1:
+ if "__bytes__" in dct:
+ return base64.b64decode(dct["__bytes__"])
+ if "__set__" in dct:
+ return set(dct["__set__"])
+ if "__datetime__" in dct:
+ return datetime.fromisoformat(dct["__datetime__"])
+ if "__date__" in dct:
+ return date.fromisoformat(dct["__date__"])
+ if "__uuid__" in dct:
+ return UUID(dct["__uuid__"])
+ return dct
+
# Optional FAISS import
try:
import faiss
@@ -54,6 +113,11 @@ except (ImportError, OSError):
faiss = None
+def _metadata_path(index_path: Union[str, Path]) -> Path:
+ """Get the metadata file path for a given index path."""
+ return Path(str(index_path) + ".meta.json")
+
+
class FAISSIndex:
"""FAISS index wrapper."""
@@ -136,20 +200,90 @@ class FAISSIndex:
return self.metadata.get(vector_id)
def save(self, path: Union[str, Path]):
- """Save index to disk."""
- if FAISS_AVAILABLE:
- faiss.write_index(self.index, str(path))
- else:
+ """Save index to disk.
+
+ Serializes ``vector_ids``, ``metadata``, ``dimension`` and
+ ``index_type`` *before* touching any files so that a serialization
+ error (e.g. unsupported metadata type) never leaves an orphaned
+ FAISS binary without its companion ``.meta.json``.
+
+ The companion file is written atomically (temp file + rename) so a
+ partially written JSON never leaves a corrupt state on disk.
+ """
+ if not FAISS_AVAILABLE:
raise ProcessingError("FAISS not available")
+ path = Path(path)
+ path.parent.mkdir(parents=True, exist_ok=True)
+
+ meta_path = _metadata_path(path)
+ payload = json.dumps(
+ {
+ "vector_ids": self.vector_ids,
+ "metadata": self.metadata,
+ "dimension": self.dimension,
+ "index_type": self.index_type,
+ },
+ cls=_LosslessJSONEncoder,
+ )
+
+ faiss.write_index(self.index, str(path))
+
+ meta_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_meta = meta_path.with_suffix(meta_path.suffix + ".tmp")
+ tmp_meta.write_text(payload)
+ tmp_meta.replace(meta_path)
+
@classmethod
def load(cls, path: Union[str, Path], dimension: int, index_type: str = "flat"):
- """Load index from disk."""
+ """Load index from disk.
+
+ Restores ``vector_ids`` and ``metadata`` from the companion
+ ``.meta.json`` file when present. When the companion file exists, its
+ persisted ``dimension`` and ``index_type`` take precedence over the
+ caller-supplied values so the loaded wrapper faithfully reflects what
+ was originally saved.
+ """
if not FAISS_AVAILABLE:
raise ProcessingError("FAISS not available")
+ path = Path(path)
index = faiss.read_index(str(path))
- return cls(index, dimension, index_type)
+
+ meta_path = _metadata_path(path)
+ if meta_path.exists():
+ data = json.loads(meta_path.read_text(), object_hook=_lossless_object_hook)
+ vector_ids = data.get("vector_ids", [])
+ metadata = data.get("metadata", {})
+ persisted_dimension = data.get("dimension")
+ persisted_index_type = data.get("index_type")
+ if persisted_dimension is not None:
+ dimension = int(persisted_dimension)
+ if persisted_index_type is not None:
+ index_type = persisted_index_type
+
+ # Check for vector count vs sidecar ID count mismatch
+ if len(vector_ids) != index.ntotal:
+ raise ProcessingError(
+ f"Sidecar metadata vector count ({len(vector_ids)}) does not match "
+ f"the binary FAISS index ntotal ({index.ntotal}). "
+ "This indicates data corruption or an incomplete save."
+ )
+ else:
+ warnings.warn(
+ "FAISS index loaded without a companion .meta.json file: "
+ "vector IDs and metadata could not be restored, so the index "
+ "will load without ID mappings.",
+ RuntimeWarning,
+ stacklevel=2,
+ )
+ vector_ids = []
+ metadata = {}
+
+ obj = cls(index, dimension, index_type)
+ obj.vector_ids = vector_ids
+ obj.metadata = metadata
+ return obj
class FAISSSearch:
@@ -184,11 +318,11 @@ class FAISSSearch:
if idx < len(self.index.vector_ids):
vector_id = self.index.vector_ids[idx]
dist_val = float(dist)
-
+
# Standardize score as similarity (0.0 to 1.0)
# while preserving original distance
similarity_score = 1.0 / (1.0 + max(0.0, dist_val))
-
+
results.append(
{
"id": vector_id,
@@ -481,6 +615,14 @@ class FAISSStore:
if not FAISS_AVAILABLE:
raise ProcessingError("FAISS not available")
+ path = Path(path)
+ if path.exists() and not _metadata_path(path).exists():
+ self.logger.warning(
+ f"Loaded FAISS index from {path} without a companion "
+ ".meta.json file: vector IDs and metadata could not be "
+ "restored, so the index will load without ID mappings."
+ )
+
self.index = FAISSIndex.load(path, self.dimension, index_type)
self.search_engine = FAISSSearch(self.index)
@@ -567,7 +709,7 @@ class FAISSStore:
if self.index is None or limit <= 0:
return []
- ids_page = self.index.vector_ids[offset:offset + limit]
+ ids_page = self.index.vector_ids[offset : offset + limit]
return [
{
"id": vector_id,
diff --git a/tests/vector_store/test_faiss_index.py b/tests/vector_store/test_faiss_index.py
index 4d0544b7..bf200d30 100644
--- a/tests/vector_store/test_faiss_index.py
+++ b/tests/vector_store/test_faiss_index.py
@@ -1,9 +1,130 @@
+import json
+import uuid
+from datetime import datetime, timezone
from unittest.mock import MagicMock
import numpy as np
import pytest
-from semantica.vector_store.faiss_store import FAISSIndex, FAISSStore
+from semantica.utils.exceptions import ProcessingError
+from semantica.vector_store.faiss_store import (
+ FAISSIndex,
+ FAISSStore,
+ _metadata_path,
+)
+
+
+def test_faiss_index_save_load_non_json_serializable_metadata(tmp_path):
+ """Save/load roundtrip works with non-JSON-serializable metadata types."""
+ faiss = pytest.importorskip("faiss")
+ vectors = np.array(
+ [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
+ dtype=np.float32,
+ )
+ ids = ["vec_a", "vec_b"]
+ now = datetime.now(timezone.utc)
+ uid = uuid.uuid4()
+ metadata = [
+ {
+ "timestamp": now,
+ "uuid": uid,
+ "numpy_int": np.int64(42),
+ "numpy_float": np.float64(3.14),
+ "a_set": {1, 2, 3},
+ },
+ {
+ "timestamp": now,
+ "uuid": uid,
+ "numpy_int": np.int64(99),
+ "numpy_float": np.float64(2.71),
+ "a_set": {4, 5, 6},
+ },
+ ]
+
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ index.add_vectors(vectors, ids=ids)
+ for vec_id, meta in zip(ids, metadata):
+ index.metadata[vec_id] = meta
+
+ index_path = tmp_path / "test_index.faiss"
+ index.save(index_path)
+ assert _metadata_path(index_path).exists()
+
+ loaded_index = FAISSIndex.load(index_path, dimension=3)
+
+ assert loaded_index.vector_ids == ids
+ assert loaded_index.dimension == 3
+ assert loaded_index.index_type == "flat"
+
+ for i, vec_id in enumerate(ids):
+ np.testing.assert_allclose(
+ loaded_index.get_vector(vec_id), vectors[i], atol=1e-6
+ )
+ loaded_meta = loaded_index.get_metadata(vec_id)
+ # Verify lossless restoration of all types
+ assert loaded_meta["timestamp"] == now
+ assert isinstance(loaded_meta["timestamp"], datetime)
+ assert loaded_meta["uuid"] == uid
+ assert isinstance(loaded_meta["uuid"], uuid.UUID)
+ assert loaded_meta["numpy_int"] == metadata[i]["numpy_int"]
+ assert isinstance(loaded_meta["numpy_int"], int)
+ assert loaded_meta["numpy_float"] == float(metadata[i]["numpy_float"])
+ assert isinstance(loaded_meta["numpy_float"], float)
+ assert loaded_meta["a_set"] == metadata[i]["a_set"]
+ assert isinstance(loaded_meta["a_set"], set)
+
+
+def test_faiss_index_save_load_bytes_roundtrip(tmp_path):
+ """Save/load roundtrip preserves bytes metadata via base64 encoding."""
+ faiss = pytest.importorskip("faiss")
+ vectors = np.array(
+ [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
+ dtype=np.float32,
+ )
+ ids = ["doc_1", "doc_2"]
+ metadata = [
+ {"blob": b"raw-embedding-hash"},
+ {"blob": b"\x00\x01\x02\xff"},
+ ]
+
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ index.add_vectors(vectors, ids=ids)
+ for vec_id, meta in zip(ids, metadata):
+ index.metadata[vec_id] = meta
+
+ index_path = tmp_path / "test_index.faiss"
+ index.save(index_path)
+
+ loaded = FAISSIndex.load(index_path, dimension=3)
+ assert loaded.metadata["doc_1"]["blob"] == b"raw-embedding-hash"
+ assert isinstance(loaded.metadata["doc_1"]["blob"], bytes)
+ assert loaded.metadata["doc_2"]["blob"] == b"\x00\x01\x02\xff"
+ assert isinstance(loaded.metadata["doc_2"]["blob"], bytes)
+
+
+def test_faiss_index_load_raises_on_vector_count_mismatch(tmp_path):
+ """Loading an index with mismatched vector_ids count vs index.ntotal raises ProcessingError."""
+ faiss = pytest.importorskip("faiss")
+ vectors = np.array(
+ [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]],
+ dtype=np.float32,
+ )
+ ids = ["vec_a", "vec_b", "vec_c"]
+
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ index.add_vectors(vectors, ids=ids)
+
+ index_path = tmp_path / "test_index.faiss"
+ index.save(index_path)
+
+ # Corrupt the metadata: remove one vector_id but keep the FAISS index intact
+ meta_path = _metadata_path(index_path)
+ data = json.loads(meta_path.read_text())
+ data["vector_ids"] = ["vec_a", "vec_b"] # Only 2 IDs, but index has 3 vectors
+ meta_path.write_text(json.dumps(data))
+
+ with pytest.raises(ProcessingError, match="Sidecar metadata vector count.*does not match"):
+ FAISSIndex.load(index_path, dimension=3)
def test_get_vector_reconstructs_from_flat_l2_index():
@@ -157,7 +278,9 @@ def test_scan_vectors_includes_vector_and_metadata():
assert len(page) == 1
assert page[0]["id"] == "a"
assert page[0]["metadata"] == {"tag": "only"}
- np.testing.assert_array_equal(page[0]["vector"], np.array([0.0, 0.0, 0.0], dtype=np.float32))
+ np.testing.assert_array_equal(
+ page[0]["vector"], np.array([0.0, 0.0, 0.0], dtype=np.float32)
+ )
def test_scan_vectors_no_index_returns_empty_list():
@@ -183,7 +306,9 @@ def test_add_vectors_retry_with_same_ids_does_not_duplicate():
store = FAISSStore(dimension=3)
store.index = FAISSIndex(backend_index, dimension=3)
- vectors = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=np.float32)
+ vectors = np.array(
+ [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=np.float32
+ )
ids = ["a", "b", "c", "d"]
store.add_vectors(vectors, ids=ids, metadata=[{"i": i} for i in range(4)])
@@ -200,10 +325,261 @@ def test_add_vectors_retry_with_partial_overlap_only_adds_new_ids():
store = FAISSStore(dimension=3)
store.index = FAISSIndex(backend_index, dimension=3)
- store.add_vectors(np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), ids=["a", "b"])
- store.add_vectors(np.array([[1, 2, 3], [7, 8, 9]], dtype=np.float32), ids=["a", "c"])
+ store.add_vectors(
+ np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32), ids=["a", "b"]
+ )
+ store.add_vectors(
+ np.array([[1, 2, 3], [7, 8, 9]], dtype=np.float32), ids=["a", "c"]
+ )
assert store.index.vector_ids == ["a", "b", "c"]
second_call_vectors = backend_index.add.call_args[0][0]
assert second_call_vectors.shape[0] == 1
- np.testing.assert_array_equal(second_call_vectors[0], np.array([7, 8, 9], dtype=np.float32))
+ np.testing.assert_array_equal(
+ second_call_vectors[0], np.array([7, 8, 9], dtype=np.float32)
+ )
+
+
+def test_faiss_index_save_load_roundtrip_with_metadata(tmp_path):
+ """vector_ids and metadata persist across a FAISSIndex save/load round-trip."""
+ faiss = pytest.importorskip("faiss")
+ vectors = np.array(
+ [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]],
+ dtype=np.float32,
+ )
+ ids = ["vec_a", "vec_b", "vec_c"]
+ metadata = [
+ {"tag": "alpha", "value": 1},
+ {"tag": "beta", "value": 2},
+ {"tag": "gamma", "value": 3},
+ ]
+
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ index.add_vectors(vectors, ids=ids)
+ for vec_id, meta in zip(ids, metadata):
+ index.metadata[vec_id] = meta
+
+ index_path = tmp_path / "test_index.faiss"
+ index.save(index_path)
+ assert _metadata_path(index_path).exists()
+
+ loaded_index = FAISSIndex.load(index_path, dimension=3)
+
+ assert loaded_index.vector_ids == ids
+ assert loaded_index.metadata == dict(zip(ids, metadata))
+ assert loaded_index.dimension == 3
+ assert loaded_index.index_type == "flat"
+
+ for i, vec_id in enumerate(ids):
+ np.testing.assert_allclose(
+ loaded_index.get_vector(vec_id), vectors[i], atol=1e-6
+ )
+ assert loaded_index.get_metadata(vec_id) == metadata[i]
+
+
+def test_faiss_index_load_writes_companion_json_file(tmp_path):
+ """save() writes a companion .meta.json file alongside the index."""
+ faiss = pytest.importorskip("faiss")
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ index.add_vectors(np.array([[1, 2, 3]], dtype=np.float32), ids=["x"])
+ index.metadata["x"] = {"source": "doc"}
+
+ index_path = tmp_path / "sub" / "dir" / "index.faiss"
+ index.save(index_path)
+
+ meta_path = _metadata_path(index_path)
+ assert meta_path.exists()
+ payload = json.loads(meta_path.read_text())
+ assert payload["vector_ids"] == ["x"]
+ assert payload["metadata"] == {"x": {"source": "doc"}}
+ assert payload["dimension"] == 3
+ assert payload["index_type"] == "flat"
+
+
+def test_faiss_store_save_load_roundtrip_with_metadata(tmp_path):
+ """FAISSStore save_index/load_index round-trip preserves IDs and metadata."""
+ _ = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vectors = np.array(
+ [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
+ dtype=np.float32,
+ )
+ ids = ["store_vec_1", "store_vec_2"]
+ metadata = [{"source": "doc1"}, {"source": "doc2"}]
+
+ store.add_vectors(vectors, ids=ids, metadata=metadata)
+
+ index_path = tmp_path / "store_index.faiss"
+ store.save_index(index_path)
+
+ new_store = FAISSStore(dimension=3)
+ new_store.load_index(index_path)
+
+ assert new_store.index.vector_ids == ids
+ assert new_store.index.metadata == dict(zip(ids, metadata))
+ assert new_store.count() == 2
+
+ for i, vec_id in enumerate(ids):
+ np.testing.assert_allclose(new_store.get_vector(vec_id), vectors[i], atol=1e-6)
+ assert new_store.get_metadata(vec_id) == metadata[i]
+
+ results = new_store.search_similar(vectors[0], k=2)
+ assert len(results) == 2
+ assert results[0]["id"] == ids[0]
+ assert results[0]["metadata"] == metadata[0]
+
+
+def test_roundtrip_load_respects_persisted_dimension_and_index_type(tmp_path):
+ """load() uses persisted dimension/index_type over caller-supplied values."""
+ faiss = pytest.importorskip("faiss")
+ vectors = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3, index_type="flat")
+ index.add_vectors(vectors, ids=["a", "b"])
+
+ index_path = tmp_path / "index.faiss"
+ index.save(index_path)
+
+ loaded_index = FAISSIndex.load(index_path, dimension=999, index_type="hnsw")
+
+ assert loaded_index.dimension == 3
+ assert loaded_index.index_type == "flat"
+ assert loaded_index.vector_ids == ["a", "b"]
+
+
+def test_roundtrip_filter_by_metadata_after_reload(tmp_path):
+ """filter_by_metadata works correctly on a reloaded store."""
+ _ = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vectors = np.array(
+ [
+ [0.1, 0.2, 0.3],
+ [0.4, 0.5, 0.6],
+ [0.7, 0.8, 0.9],
+ ],
+ dtype=np.float32,
+ )
+ ids = ["d1", "d2", "d3"]
+ metadata = [
+ {"source": "alpha", "tier": 1},
+ {"source": "beta", "tier": 2},
+ {"source": "alpha", "tier": 3},
+ ]
+ store.add_vectors(vectors, ids=ids, metadata=metadata)
+
+ index_path = tmp_path / "index.faiss"
+ store.save_index(index_path)
+
+ new_store = FAISSStore(dimension=3)
+ new_store.load_index(index_path)
+
+ alpha = new_store.filter_by_metadata({"source": "alpha"})
+ assert {r["id"] for r in alpha} == {"d1", "d3"}
+ for r in alpha:
+ assert r["metadata"]["source"] == "alpha"
+ np.testing.assert_allclose(r["vector"], store.get_vector(r["id"]), atol=1e-6)
+
+ tier = new_store.filter_by_metadata({"tier": {"min": 2}})
+ assert {r["id"] for r in tier} == {"d2", "d3"}
+
+ none_match = new_store.filter_by_metadata({"source": "gamma"})
+ assert none_match == []
+
+
+def test_roundtrip_scan_vectors_on_loaded_store(tmp_path):
+ """scan_vectors returns restored ids and metadata on a loaded store."""
+ _ = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vectors = np.array(
+ [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9]],
+ dtype=np.float32,
+ )
+ ids = ["a", "b", "c"]
+ metadata = [{"i": 0}, {"i": 1}, {"i": 2}]
+ store.add_vectors(vectors, ids=ids, metadata=metadata)
+
+ index_path = tmp_path / "index.faiss"
+ store.save_index(index_path)
+
+ new_store = FAISSStore(dimension=3)
+ new_store.load_index(index_path)
+
+ page = new_store.scan_vectors(offset=0, limit=10)
+ assert [p["id"] for p in page] == ids
+ for p, v, meta in zip(page, vectors, metadata):
+ np.testing.assert_allclose(p["vector"], v, atol=1e-6)
+ assert p["metadata"] == meta
+
+ assert [p["id"] for p in new_store.scan_vectors(offset=1, limit=2)] == ["b", "c"]
+
+
+def test_roundtrip_duplicate_check_on_loaded_store(tmp_path):
+ """Re-adding existing ids on a loaded store does not duplicate vectors."""
+ _ = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vectors = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32)
+ ids = ["a", "b"]
+ store.add_vectors(vectors, ids=ids, metadata=[{"i": 0}, {"i": 1}])
+
+ index_path = tmp_path / "index.faiss"
+ store.save_index(index_path)
+
+ new_store = FAISSStore(dimension=3)
+ new_store.load_index(index_path)
+ assert new_store.count() == 2
+
+ new_store.add_vectors(vectors, ids=ids, metadata=[{"i": 0}, {"i": 1}])
+
+ assert new_store.count() == 2
+ assert new_store.index.vector_ids == ids
+ assert new_store.index.metadata == dict(zip(ids, [{"i": 0}, {"i": 1}]))
+ assert new_store.index.index.ntotal == 2
+
+
+def test_faiss_store_save_load_scan_vectors_end_to_end(tmp_path):
+ """End-to-end: save/load a store, then scan_vectors returns original ids and metadata."""
+ _ = pytest.importorskip("faiss")
+ store = FAISSStore(dimension=3)
+ vectors = np.array(
+ [
+ [0.1, 0.2, 0.3],
+ [0.4, 0.5, 0.6],
+ [0.7, 0.8, 0.9],
+ ],
+ dtype=np.float32,
+ )
+ ids = ["doc_a", "doc_b", "doc_c"]
+ metadata = [
+ {"source": "alpha", "page": 1},
+ {"source": "beta", "page": 2},
+ {"source": "alpha", "page": 3},
+ ]
+ store.add_vectors(vectors, ids=ids, metadata=metadata)
+
+ index_path = tmp_path / "index.faiss"
+ store.save_index(index_path)
+
+ new_store = FAISSStore(dimension=3)
+ new_store.load_index(index_path)
+
+ page = new_store.scan_vectors(offset=0, limit=10)
+ assert [p["id"] for p in page] == ids
+ for p, v, meta in zip(page, vectors, metadata):
+ np.testing.assert_allclose(p["vector"], v, atol=1e-6)
+ assert p["metadata"] == meta
+
+
+def test_loading_index_without_meta_json_warns(tmp_path):
+ """Loading an index with no companion .meta.json emits an explicit warning."""
+ faiss = pytest.importorskip("faiss")
+ index = FAISSIndex(faiss.IndexFlatL2(3), dimension=3)
+ index.add_vectors(np.array([[1, 2, 3]], dtype=np.float32), ids=["x"])
+
+ index_path = tmp_path / "index.faiss"
+ index.save(index_path)
+ _metadata_path(index_path).unlink()
+
+ with pytest.warns(RuntimeWarning, match="without ID mappings"):
+ loaded = FAISSIndex.load(index_path, dimension=3)
+
+ assert loaded.vector_ids == []
+ assert loaded.metadata == {}