Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

Fix candidate-embeddings loop dropping matches when pool exhausted

KaifAhmad1721a2f0e9cfb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 540d5240..244b45fc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -69,6 +69,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **`DecisionEmbeddingPipeline.find_similar_decisions()` crashed with `AttributeError` for any `VectorStore` backend other than `inmemory`** (#842, closes #839) by @Sameer6305
+ - `_get_candidate_embeddings()` iterated `VectorStore.vectors`/`VectorStore.metadata` directly, internal dicts only populated for `backend="inmemory"`; every persistent backend (FAISS, Pinecone, Qdrant, Milvus, ...) raised `AttributeError`. It now fetches candidates via the backend-agnostic `VectorStore.search_vectors()`, reading metadata via a `res.get("metadata") or res.get("payload")` fallback for backends that key it differently
+ - Backends such as FAISS don't return the raw vector for each hit; `find_similar_decisions()` and `_find_semantic_similar()` now fall back to the search-provided score (normalized from `distance` when present) as the semantic similarity for those candidates instead of computing cosine similarity against a zero placeholder vector
+ - `get_decision_statistics()` had the identical bug iterating `store.metadata.values()`; it now returns a limited stats payload with an explanatory `warning` field for backends that don't expose a full in-memory metadata dict, instead of crashing
+ - **Fixed along the way**: `_get_candidate_embeddings()`'s expand-and-retry loop (which widens the search pool when post-filtering leaves too few matches) discarded every candidate it had found once the pool hit its cap (`limit * 10`) without ever collecting `limit` matches or getting a short page back from the backend — the loop fell through without executing the branch that assigns results, silently returning `[]` even when matching candidates existed. It now falls back to the last batch collected instead of dropping it
+ - Added end-to-end regression tests against real `inmemory` and `faiss` backends (no mocks) plus a targeted unit test for the expand-and-retry loop's fallback behavior
+
- **`QdrantStore.search_vectors()` returned results keyed by `"payload"` instead of `"metadata"`** (#841, closes #840) by @divyankshah
- `QdrantCollection.search_points()` built its result dicts as `{"id", "score", "payload"}`, while `PineconeStore.search_vectors()` and every other backend consumed by `HybridSearch` use `"metadata"`. This silently dropped Qdrant metadata from results and made `HybridSearch.filter_by_metadata()` reject every candidate whenever a filter was applied, since it looks up `result["metadata"]` and got nothing back
- Normalized `search_points()` to return `"metadata"` instead of `"payload"`, matching the existing convention; no other module reads the old key, so the rename is a straight fix rather than a partial one
diff --git a/semantica/vector_store/decision_embedding_pipeline.py b/semantica/vector_store/decision_embedding_pipeline.py
index 46f61ac7..882f7b40 100644
--- a/semantica/vector_store/decision_embedding_pipeline.py
+++ b/semantica/vector_store/decision_embedding_pipeline.py
@@ -790,15 +790,16 @@ class DecisionEmbeddingPipeline:
if query_vector is None:
query_vector = np.zeros(self.embedding_dimension)
- embeddings = []
- metadata = []
- scores = []
-
+ embeddings = None
+ metadata = None
+ scores = None
+ collected_embeddings, collected_metadata, collected_scores = [], [], []
+
# If we have filters, we might need to fetch more candidates iteratively
# if the backend doesn't support native filtering and we rely on post-filtering.
current_k = limit
max_k = limit * 10 if limit else 100000
-
+
while current_k <= max_k:
results = self.vector_store.search_vectors(query_vector, k=current_k, filter=filters)
@@ -853,7 +854,16 @@ class DecisionEmbeddingPipeline:
# Otherwise, double the search pool and try again
current_k *= 2
-
+
+ if embeddings is None:
+ # max_k was exhausted without either stop condition firing (e.g. the
+ # backend always returns a full page and filtered matches never reach
+ # `limit`). Fall back to whatever the final, largest iteration found
+ # rather than discarding it and returning nothing.
+ embeddings = collected_embeddings[:limit]
+ metadata = collected_metadata[:limit]
+ scores = collected_scores[:limit]
+
return {"embeddings": embeddings, "metadata": metadata, "scores": scores}
def _find_semantic_similar(
diff --git a/tests/vector_store/test_decision_embedding_pipeline.py b/tests/vector_store/test_decision_embedding_pipeline.py
index 15e5f444..4fb69280 100644
--- a/tests/vector_store/test_decision_embedding_pipeline.py
+++ b/tests/vector_store/test_decision_embedding_pipeline.py
@@ -448,5 +448,40 @@ class TestDecisionEmbeddingPipelineEdgeCases:
assert "semantic_similarity" in results[0]
assert "structural_similarity" in results[0]
+ def test_get_candidate_embeddings_returns_partial_matches_when_pool_exhausted(self):
+ """Regression test: _get_candidate_embeddings must not discard matches found
+ in its final retry iteration when the expand-and-retry loop exhausts max_k
+ without ever crossing `limit` matches or getting a short page back."""
+ pipeline = DecisionEmbeddingPipeline.__new__(DecisionEmbeddingPipeline)
+ pipeline.vector_store = Mock()
+ pipeline.embedding_dimension = 384
+ pipeline.node_embedding_dimension = 128
+
+ rare_indices = {10, 30, 50, 70}
+
+ def fake_search_vectors(query_vector, k=10, filter=None):
+ # Always returns a full page, so the backend never hits the
+ # "len(results) < current_k" stop condition.
+ return [
+ {
+ "id": f"v{i}",
+ "vector": np.random.rand(384),
+ "metadata": {"category": "rare" if i in rare_indices else "common"},
+ "score": 1.0 - i / 1000.0,
+ }
+ for i in range(k)
+ ]
+
+ pipeline.vector_store.search_vectors.side_effect = fake_search_vectors
+
+ result = pipeline._get_candidate_embeddings(
+ np.random.rand(384), limit=10, filters={"category": "rare"}
+ )
+
+ assert len(result["embeddings"]) == len(rare_indices)
+ assert len(result["metadata"]) == len(rare_indices)
+ assert len(result["scores"]) == len(rare_indices)
+
+
if __name__ == "__main__":
pytest.main([__file__])