Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
Fix VectorStore.save() empty state when added via document path (#1698)
Mayuri6aa63775c556
diff --git a/semantica/vector_store/decision_vector_methods.py b/semantica/vector_store/decision_vector_methods.pyindex b38a0298..3658c865 100644--- a/semantica/vector_store/decision_vector_methods.py+++ b/semantica/vector_store/decision_vector_methods.py@@ -365,8 +365,13 @@ def get_decision_statistics(outcome_counts = {}confidence_values = []- # Not all backends expose internal metadata dictionaries (e.g. FAISS).- if not hasattr(store, "metadata"):+ # For persistent backends (faiss, qdrant, etc.) the facade now maintains a+ # mirror in store.metadata, but that mirror only reflects vectors written+ # through the facade in the current session. Iterating it would silently+ # miss data stored externally or in a previous session. Return zeroed stats+ # with an explicit warning instead, as this function did before the mirror+ # was introduced.+ if getattr(store, "backend", "inmemory") != "inmemory":return {"total_decisions": 0,"categories": {},diff --git a/semantica/vector_store/hybrid_search.py b/semantica/vector_store/hybrid_search.pyindex 1f6d2a84..80415668 100644--- a/semantica/vector_store/hybrid_search.py+++ b/semantica/vector_store/hybrid_search.py@@ -347,16 +347,21 @@ class HybridSearch:# Resolve vector store data if not providedif vectors is None and self.vector_store:- if hasattr(self.vector_store, "vectors"):- # In-memory backend exposes its corpus directly+ if getattr(self.vector_store, "backend", None) == "inmemory":+ # In-memory backend: read corpus directly from the local dicts.+ # We must NOT use this path for persistent backends (faiss,+ # weaviate, qdrant, milvus, pgvector, sqlite) even though+ # self.vector_store.vectors now exists as a mirror — the mirror+ # only reflects writes made through the facade in the current+ # session and would miss pre-existing backend data entirely.vector_ids = list(self.vector_store.vectors.keys())vectors = [self.vector_store.vectors[vid] for vid in vector_ids]metadata = [self.vector_store.metadata.get(vid, {}) for vid in vector_ids]else:- # Backend-agnostic path: other backends (faiss, weaviate,- # qdrant, milvus, pinecone, pgvector, sqlite) don't expose- # a raw `.vectors` dict, so delegate similarity search to- # the store's public API instead.+ # Backend-agnostic path: all persistent backends (faiss, weaviate,+ # qdrant, milvus, pinecone, pgvector, sqlite) must go through the+ # store's public search API to cover the full index, including+ # data that predates the current session or was written externally.self.progress_tracker.update_tracking(tracking_id, message="Performing vector similarity search...")diff --git a/semantica/vector_store/vector_store.py b/semantica/vector_store/vector_store.pyindex d611e368..f4246838 100644--- a/semantica/vector_store/vector_store.py+++ b/semantica/vector_store/vector_store.py@@ -140,18 +140,13 @@ class VectorStore:self._init_backend_store()# For in-memory backend, initialize local storage- if self.backend == "inmemory":- self.vectors: Dict[str, np.ndarray] = {}- self.metadata: Dict[str, Dict[str, Any]] = {}- # Monotonic counter for default ID generation. Never decremented- # on deletion, so IDs generated by consecutive store_vectors calls- # can never collide with surviving IDs (fixes #1029).- self._next_id: int = 0- # Reentrant lock protecting all in-memory state mutations:- # _next_id, vectors, metadata, and index rebuilds. Matches the- # threading model used by SQLiteVecStore and AgentMemory.- self._inmemory_lock = threading.RLock()+ self.vectors: Dict[str, np.ndarray] = {}+ self.metadata: Dict[str, Dict[str, Any]] = {}+ self._next_id: int = 0+ self._inmemory_lock = threading.RLock()+ if self.backend == "inmemory":+ # self.vectors is now initialized universally# Initialize backend-specific indexer# Avoid duplicate dimension argumentindexer_config = self.config.copy()@@ -521,13 +516,14 @@ class VectorStore:# Delegate to backend store if availableif self._backend_store:# Handle different method names across backend stores+ ids = Noneif hasattr(self._backend_store, 'add'):- return self._backend_store.add(vectors, metadata, **options)+ ids = self._backend_store.add(vectors, metadata, **options)elif hasattr(self._backend_store, 'add_vectors'):# FAISSStore and others use add_vectors with different signatureif hasattr(self._backend_store, 'store_vectors'):# Some stores have store_vectors method- return self._backend_store.store_vectors(vectors, metadata=metadata, **options)+ ids = self._backend_store.store_vectors(vectors, metadata=metadata, **options)else:try:add_vectors_params = inspect.signature(self._backend_store.add_vectors).parameters@@ -537,20 +533,27 @@ class VectorStore:except (ValueError, TypeError):supports_metadata = Trueif supports_metadata:- return self._backend_store.add_vectors(vectors, metadata=metadata, **options)- return self._backend_store.add_vectors(vectors, **options)+ ids = self._backend_store.add_vectors(vectors, metadata=metadata, **options)+ else:+ ids = self._backend_store.add_vectors(vectors, **options)elif hasattr(self._backend_store, 'insert_vectors'):# QdrantStore: insert_vectors(vectors, ids, payloads=None)- # upserts the points but returns the client's status dict,- # while this facade promises callers the stored vector IDs- # (decision storage indexes the result at position 0).- # metadata entries already carry the source document (folded- # in by store()), so they map directly to Qdrant payloads.ids = options.pop('ids', None) or [str(uuid.uuid4()) for _ in range(len(vectors))]self._backend_store.insert_vectors(vectors, ids, payloads=metadata, **options)- return idselse:raise NotImplementedError(f"Backend store {type(self._backend_store).__name__} does not have add or add_vectors method")++ if ids is None:+ ids = [str(uuid.uuid4()) for _ in range(len(vectors))]+ elif len(ids) != len(vectors):+ raise ProcessingError(f"Backend store returned {len(ids)} IDs for {len(vectors)} vectors")++ metadata = metadata or [{}] * len(vectors)+ with self._inmemory_lock:+ for i, vid in enumerate(ids):+ self.vectors[vid] = vectors[i]+ self.metadata[vid] = metadata[i]+ return ids# Use in-memory implementationtracking_id = self.progress_tracker.start_tracking(@@ -694,30 +697,33 @@ class VectorStore:with open(data_path, "r", encoding="utf-8") as f:data = json.load(f)- self.vectors = data.get("vectors", {})+ vectors_raw = data.get("vectors", {})+ self.vectors = {k: np.array(v, dtype=np.float32) for k, v in vectors_raw.items()}self.metadata = data.get("metadata", {})self.config = data.get("config", {})self.backend = data.get("backend", "faiss")self.dimension = data.get("dimension", 768)++ if not hasattr(self, "_inmemory_lock"):+ self._inmemory_lock = threading.RLock()# Restore the monotonic ID counter. Always clamp to at least# max(vec_N suffix)+1 so a stale or missing persisted value (e.g.# written before this field was added, or written before a deletion# that lowered the count) cannot produce IDs that collide with# existing vectors (issue #1029).- if self.backend == "inmemory":- _vec_nums = [- int(v[4:]) + 1- for v in self.vectors- if v.startswith("vec_") and v[4:].isdigit()- ]- _inferred = max(_vec_nums) if _vec_nums else 0- persisted_next_id = data.get("next_id")- if persisted_next_id is not None:- self._next_id = max(int(persisted_next_id), _inferred)- else:- # Older store files lack this field; use the safe inferred value.- self._next_id = _inferred+ _vec_nums = [+ int(v[4:]) + 1+ for v in self.vectors+ if v.startswith("vec_") and v[4:].isdigit()+ ]+ _inferred = max(_vec_nums) if _vec_nums else 0+ persisted_next_id = data.get("next_id")+ if persisted_next_id is not None:+ self._next_id = max(int(persisted_next_id), _inferred)+ else:+ # Older store files lack this field; use the safe inferred value.+ self._next_id = _inferred# Restore backend-specific indexindexer = getattr(self, "indexer", None)@@ -876,12 +882,19 @@ class VectorStore:"""Delete vectors from store."""# Delegate to backend store if availableif self._backend_store:+ success = Falseif hasattr(self._backend_store, 'delete'):- return self._backend_store.delete(ids=vector_ids, **options)+ success = self._backend_store.delete(ids=vector_ids, **options)elif hasattr(self._backend_store, 'delete_vectors'):- return self._backend_store.delete_vectors(vector_ids, **options)+ success = self._backend_store.delete_vectors(vector_ids, **options)else:raise NotImplementedError(f"Backend store {type(self._backend_store).__name__} does not have delete or delete_vectors method")++ with self._inmemory_lock:+ for vec_id in vector_ids:+ self.vectors.pop(vec_id, None)+ self.metadata.pop(vec_id, None)+ return successwith self._inmemory_lock:for vec_id in vector_ids:diff --git a/tests/vector_store/test_vector_store.py b/tests/vector_store/test_vector_store.pyindex 80ff3e59..f7a8b99d 100644--- a/tests/vector_store/test_vector_store.py+++ b/tests/vector_store/test_vector_store.py@@ -4,6 +4,7 @@ import tempfileimport unittestfrom unittest.mock import MagicMock, patchimport numpy as np+import pytestfrom semantica.vector_store.vector_store import VectorStoreclass TestVectorStore(unittest.TestCase):@@ -259,3 +260,43 @@ class TestCreateIndexFunction(unittest.TestCase):if __name__ == '__main__':unittest.main()++def test_backend_mirroring_and_save(tmp_path):+ """+ Test that backend-backed vector stores maintain a synchronized in-memory mirror+ for serialization by save(). This covers #1698 regression.+ """+ pytest.importorskip("sqlite_vec")++ import numpy as np+ from semantica.vector_store import VectorStore+ import os++ # We use sqlite since it doesn't require an external service+ vs = VectorStore(backend="sqlite", config={"db_path": str(tmp_path / "test1.db")})++ vecs = [np.array([0.1, 0.2], dtype=np.float32)]+ meta = [{"test": "true"}]++ # store_vectors should populate mirror+ ids = vs.store_vectors(vecs, metadata=meta)+ assert len(ids) == 1+ assert ids[0] in vs.vectors+ assert ids[0] in vs.metadata++ # save() should persist mirror+ save_dir = str(tmp_path / "vs_save")+ vs.save(save_dir)+ assert os.path.exists(os.path.join(save_dir, "store_data.json"))++ # load() should restore mirror+ vs2 = VectorStore(backend="sqlite", config={"db_path": str(tmp_path / "test2.db")})+ vs2.load(save_dir)+ assert ids[0] in vs2.vectors+ assert ids[0] in vs2.metadata+ assert np.array_equal(vs2.vectors[ids[0]], vecs[0])++ # delete_vectors should update mirror+ vs.delete_vectors(ids)+ assert ids[0] not in vs.vectors+ assert ids[0] not in vs.metadata