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
feat(vector_store): add milvus iter_all
Zohaib Hassnaine335971dcd96
diff --git a/semantica/vector_store/milvus_store.py b/semantica/vector_store/milvus_store.pyindex f467eeb4..018484f0 100644--- a/semantica/vector_store/milvus_store.py+++ b/semantica/vector_store/milvus_store.py@@ -680,6 +680,76 @@ class MilvusStore:self.logger.warning(f"Failed to query Milvus vectors by metadata expression: {e}")return []+ def iter_all(self, batch_size: int = 500):+ """+ Iterate over every stored entity using Milvus's query iterator.++ Milvus paginates large result sets with a primary-key cursor rather+ than a row offset, so this is exposed instead of+ scan_vectors(offset, limit). Plain query(offset=...) is bounded by the+ 16384 result window, which would silently truncate any collection+ larger than that. VectorStore.iter_vectors() prefers this method when+ it is present.++ Args:+ batch_size: Entities to request per iterator batch++ Yields:+ Result dicts with 'id', 'metadata', and 'vector', in cursor order++ Raises:+ ProcessingError: If the collection is not initialized, or the+ installed pymilvus does not expose query_iterator(). Errors are+ raised rather than swallowed because a scan that silently+ yields nothing is indistinguishable from an empty source,+ which would let a caller such as `store migrate` report+ success having copied nothing (issue #1083).+ """+ if self.collection is None or not MILVUS_AVAILABLE:+ raise ProcessingError(+ "Collection not initialized. Call create_collection() or get_collection() first."+ )++ query_iterator = getattr(self.collection.collection, "query_iterator", None)+ if not callable(query_iterator):+ raise ProcessingError(+ "This pymilvus version does not expose Collection.query_iterator(), "+ "which full enumeration requires. Falling back to query(offset=...) "+ "is not safe here: it is capped by the 16384 result window and would "+ "silently truncate a larger collection."+ )++ # Query operations require the collection to be loaded. load() is+ # idempotent, and this runs once per scan rather than per batch.+ self.collection.load()++ # Milvus rejects an empty expression, so this is the match-everything+ # form already used by filter_by_metadata().+ iterator = query_iterator(+ batch_size=batch_size,+ expr="id != ''",+ output_fields=["id", "vector", "metadata"],+ )++ try:+ while True:+ batch = iterator.next()+ if not batch:+ return+ for item in batch:+ vec = item.get("vector")+ yield {+ "id": str(item.get("id")),+ "metadata": item.get("metadata") or {},+ "vector": np.array(vec) if vec is not None else None,+ }+ finally:+ # The iterator holds server-side state; release it even if the+ # consumer abandons iteration part way through.+ close = getattr(iterator, "close", None)+ if callable(close):+ close()+def get_stats(self, collection_name: Optional[str] = None) -> Dict[str, Any]:"""Get collection statistics."""if self.collection is None and collection_name:diff --git a/tests/vector_store/test_milvus_store.py b/tests/vector_store/test_milvus_store.pynew file mode 100644index 00000000..780424bc--- /dev/null+++ b/tests/vector_store/test_milvus_store.py@@ -0,0 +1,183 @@+"""Tests for MilvusStore.iter_all() query-iterator enumeration.++pymilvus is not installed in this environment, so these drive the real+MilvusStore against MagicMocks, following the pattern already used for milvus+in test_backend_metadata_filtering.py.+"""++from unittest.mock import MagicMock, patch++import numpy as np+import pytest++from semantica.utils.exceptions import ProcessingError+from semantica.vector_store.milvus_store import MilvusStore+++def _store_with_batches(*batches):+ """MilvusStore whose query_iterator yields the given batches then stops.++ Mirrors the real attribute path, which is doubled: the store holds a+ MilvusCollection wrapper, and the pymilvus Collection sits at+ wrapper.collection.+ """+ store = MilvusStore()+ wrapper = MagicMock()+ inner = MagicMock()+ iterator = MagicMock()+ iterator.next.side_effect = list(batches)+ inner.query_iterator.return_value = iterator+ wrapper.collection = inner+ store.collection = wrapper+ return store, wrapper, inner, iterator+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_yields_batches_until_exhausted():+ """The iterator signals exhaustion with an empty list, not StopIteration."""+ store, _, _, iterator = _store_with_batches(+ [{"id": 1, "vector": [0.1], "metadata": {}}],+ [{"id": 2, "vector": [0.2], "metadata": {}}],+ [],+ )++ result = list(store.iter_all(batch_size=1))++ assert [item["id"] for item in result] == ["1", "2"]+ assert iterator.next.call_count == 3+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_requests_the_fields_needed_for_the_result_shape():+ store, _, inner, _ = _store_with_batches([])++ list(store.iter_all(batch_size=64))++ kwargs = inner.query_iterator.call_args[1]+ assert kwargs["batch_size"] == 64+ assert kwargs["output_fields"] == ["id", "vector", "metadata"]+ # Milvus rejects an empty expression, so a match-all form is required.+ assert kwargs["expr"] == "id != ''"+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_loads_the_collection_before_querying():+ """Milvus requires a loaded collection for query operations."""+ store, wrapper, _, _ = _store_with_batches([])++ list(store.iter_all())++ assert wrapper.load.called+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_closes_the_iterator_on_exhaustion():+ store, _, _, iterator = _store_with_batches([])++ list(store.iter_all())++ assert iterator.close.called+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_closes_the_iterator_when_consumer_stops_early():+ """The iterator holds server-side state, so abandoning the generator part+ way through must still release it."""+ store, _, _, iterator = _store_with_batches(+ [{"id": 1, "vector": [0.1], "metadata": {}}],+ [{"id": 2, "vector": [0.2], "metadata": {}}],+ [],+ )++ generator = store.iter_all(batch_size=1)+ next(generator)+ assert not iterator.close.called+ generator.close()++ assert iterator.close.called+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_converts_entities_to_the_shared_result_shape():+ store, _, _, _ = _store_with_batches(+ [{"id": 7, "vector": [0.1, 0.2, 0.3], "metadata": {"tag": "x"}}], []+ )++ item = list(store.iter_all())[0]++ assert item["id"] == "7"+ assert item["metadata"] == {"tag": "x"}+ np.testing.assert_allclose(item["vector"], np.array([0.1, 0.2, 0.3]))+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_handles_missing_vector_and_metadata():+ store, _, _, _ = _store_with_batches([{"id": 1, "vector": None, "metadata": None}], [])++ item = list(store.iter_all())[0]++ assert item["metadata"] == {}+ assert item["vector"] is None+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_empty_collection_yields_nothing():+ store, _, _, _ = _store_with_batches([])++ assert list(store.iter_all()) == []+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_raises_when_query_iterator_is_unavailable():+ """Older pymilvus lacks query_iterator. Falling back to query(offset=...)+ would silently truncate at the 16384 result window, so this fails loudly+ instead."""+ store = MilvusStore()+ wrapper = MagicMock()+ wrapper.collection = MagicMock(spec=["query"])+ store.collection = wrapper++ with pytest.raises(ProcessingError, match="query_iterator"):+ list(store.iter_all())+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_raises_when_collection_not_initialized():+ """Must fail loudly, not yield nothing.++ An empty scan is indistinguishable from an empty source, which would let+ `store migrate` report success having copied nothing (issue #1083).+ """+ store = MilvusStore()++ with pytest.raises(ProcessingError, match="Collection not initialized"):+ list(store.iter_all())+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", False)+def test_iter_all_raises_when_milvus_unavailable():+ store = MilvusStore()+ store.collection = MagicMock()++ with pytest.raises(ProcessingError):+ list(store.iter_all())+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_propagates_iterator_errors():+ store, _, _, iterator = _store_with_batches()+ iterator.next.side_effect = RuntimeError("connection reset")++ with pytest.raises(RuntimeError, match="connection reset"):+ list(store.iter_all())+++@patch("semantica.vector_store.milvus_store.MILVUS_AVAILABLE", True)+def test_iter_all_closes_the_iterator_when_a_batch_fails():+ store, _, _, iterator = _store_with_batches()+ iterator.next.side_effect = RuntimeError("connection reset")++ with pytest.raises(RuntimeError):+ list(store.iter_all())++ assert iterator.close.called