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(vector_store): sync qdrant iter_all() with #1316's stall-guard fix
KaifAhmad11ad17beaf66a
diff --git a/semantica/vector_store/qdrant_store.py b/semantica/vector_store/qdrant_store.pyindex 85ce7302..ac55f553 100644--- a/semantica/vector_store/qdrant_store.py+++ b/semantica/vector_store/qdrant_store.py@@ -590,33 +590,30 @@ class QdrantStore:with_payload=True,with_vectors=True,)- results = []- for rec in records:- results.append(- {- "id": str(rec.id),- "metadata": rec.payload or {},- "vector": np.array(rec.vector) if rec.vector is not None else None,- }- )- return results+ return [self._record_to_result(rec) for rec in records]except Exception as e:self.logger.warning(f"Failed to scroll Qdrant points by metadata filter: {e}")return []+ @staticmethod+ def _record_to_result(rec: Any) -> Dict[str, Any]:+ return {+ "id": str(rec.id),+ "metadata": rec.payload or {},+ "vector": np.array(rec.vector) if rec.vector is not None else None,+ }+def iter_all(self, batch_size: int = 500):"""- Iterate over every stored point using Qdrant's native scroll cursor.+ Iterate over every stored point using Qdrant's scroll cursor.- Qdrant paginates by point-ID cursor, not by row offset, so this is- exposed instead of scan_vectors(offset, limit). An integer passed to- scroll()'s offset is a point ID rather than a rank, so there is no way- to seek to "the Nth record" without walking from the start.- VectorStore.iter_vectors() prefers this method when it is present.+ Paginates by point-ID cursor rather than row offset, which is why this+ exists instead of scan_vectors(offset, limit). An integer offset is a+ point ID, not a rank.- Assumes a single unnamed vector per point, matching how insert_vectors()- writes them and how get_vector() reads them back. Collections configured- with named or multi-vectors are not handled here.+ Assumes a single unnamed vector per point, as insert_vectors() and+ get_vector() already do. Named and multi-vector collections are not+ handled.Args:batch_size: Points to request per scroll call@@ -625,11 +622,8 @@ class QdrantStore:Result dicts with 'id', 'metadata', and 'vector', in scroll orderRaises:- ProcessingError: If the collection or client is not initialized.- 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).+ ProcessingError: If the collection or client is not initialized, or+ if the cursor stops advancing before the scan completes."""if self.collection is None or self.client is None or not QDRANT_AVAILABLE:raise ProcessingError(@@ -637,6 +631,7 @@ class QdrantStore:)next_offset = None+ last_offset = object()while True:records, next_offset = self.client.scroll(collection_name=self.collection.collection_name,@@ -647,19 +642,25 @@ class QdrantStore:)for rec in records:- yield {- "id": str(rec.id),- "metadata": rec.payload or {},- "vector": np.array(rec.vector) if rec.vector is not None else None,- }-- # The final page can carry records while already reporting no next- # cursor, so those records are yielded above before stopping here.- # Calling scroll() again with offset=None would restart from the- # beginning rather than continue past the end.- if next_offset is None or not records:+ yield self._record_to_result(rec)++ # A final page can carry records alongside a null cursor, so they+ # are yielded above before stopping. Passing offset=None back to+ # scroll() would restart from the beginning, not continue.+ if next_offset is None:return+ # An empty page with a live cursor isn't necessarily truncation —+ # a batch window that lands entirely on deleted points comes back+ # this way too, and there's more to scan past it. Only treat it as+ # stuck if the cursor itself stops moving.+ if not records and next_offset == last_offset:+ raise ProcessingError(+ "Qdrant scroll cursor stopped advancing without reaching "+ "the end of the collection, so the scan cannot complete."+ )+ last_offset = next_offset+def delete_vectors(self, point_ids: List[Union[str, int]], **options) -> Dict[str, Any]:diff --git a/semantica/vector_store/vector_store.py b/semantica/vector_store/vector_store.pyindex cd703eda..e504a455 100644--- a/semantica/vector_store/vector_store.py+++ b/semantica/vector_store/vector_store.py@@ -867,12 +867,9 @@ class VectorStore:"""Iterate over every stored vector, one page at a time.- Backends whose native pagination is cursor based (Qdrant, Pinecone,- Milvus, Weaviate) cannot honestly implement the positional- scan_vectors(offset, limit) contract, so they expose iter_all()- instead and it is preferred here when present. Backends with real- positional access (inmemory, FAISS, SQLite-vec, PgVector) fall- through to the offset loop below.+ Cursor-based backends expose iter_all() because they cannot support a+ positional offset; it takes precedence when present. Everything else+ falls through to the scan_vectors() offset loop.Args:batch_size: Number of vectors to fetch per underlying calldiff --git a/tests/vector_store/test_qdrant_store.py b/tests/vector_store/test_qdrant_store.pyindex 89a9fee3..8958d8c1 100644--- a/tests/vector_store/test_qdrant_store.py+++ b/tests/vector_store/test_qdrant_store.py@@ -35,7 +35,7 @@ def _store_with_scroll(*pages):@patch("semantica.vector_store.qdrant_store.QDRANT_AVAILABLE", True)def test_iter_all_threads_cursor_across_pages():- """The next call must continue from the previous page's next_page_offset."""+ """The next call continues from the previous page's cursor."""store = _store_with_scroll(([_record(1), _record(2)], "cursor-1"),([_record(3)], None),@@ -53,11 +53,8 @@ def test_iter_all_threads_cursor_across_pages():@patch("semantica.vector_store.qdrant_store.QDRANT_AVAILABLE", True)def test_iter_all_yields_final_page_that_reports_no_next_cursor():- """Qdrant can return records and a null cursor on the same page.-- Those records must still be yielded. Treating a null cursor as "stop- before this page" would silently drop the tail of every scan.- """+ """Records and a null cursor can arrive together; those records must still+ be yielded or every scan loses its tail."""store = _store_with_scroll(([_record(1), _record(2)], None))result = list(store.iter_all(batch_size=10))@@ -97,21 +94,32 @@ def test_iter_all_empty_collection_yields_nothing():@patch("semantica.vector_store.qdrant_store.QDRANT_AVAILABLE", True)-def test_iter_all_stops_on_empty_page_even_with_a_cursor():- """Defensive: an empty page ends the scan rather than looping forever."""- store = _store_with_scroll(([], "cursor-that-never-clears"))+def test_iter_all_continues_past_empty_page_with_advancing_cursor():+ store = _store_with_scroll(+ ([], "cursor-1"),+ ([_record(1)], None),+ )- assert list(store.iter_all()) == []- assert store.client.scroll.call_count == 1+ result = list(store.iter_all())++ assert [item["id"] for item in result] == ["1"]+ assert store.client.scroll.call_count == 2@patch("semantica.vector_store.qdrant_store.QDRANT_AVAILABLE", True)-def test_iter_all_raises_when_collection_not_initialized():- """Must fail loudly, not yield nothing.+def test_iter_all_raises_when_cursor_stops_advancing():+ store = _store_with_scroll(+ ([], "stuck-cursor"),+ ([], "stuck-cursor"),+ )++ with pytest.raises(ProcessingError, match="stopped advancing"):+ list(store.iter_all())- An empty scan is indistinguishable from an empty source, which would let- `store migrate` report success having copied nothing (issue #1083).- """++@patch("semantica.vector_store.qdrant_store.QDRANT_AVAILABLE", True)+def test_iter_all_raises_when_collection_not_initialized():+ """Must fail loudly: an empty scan reads the same as an empty source."""store = QdrantStore()with pytest.raises(ProcessingError, match="Collection not initialized"):diff --git a/tests/vector_store/test_vector_manager_persistent.py b/tests/vector_store/test_vector_manager_persistent.pyindex f0586ad2..147fa669 100644--- a/tests/vector_store/test_vector_manager_persistent.py+++ b/tests/vector_store/test_vector_manager_persistent.py@@ -140,11 +140,7 @@ class _NonScanningBackendStore:class _IterAllBackendStore:- """Fake cursor-based backend store exposing iter_all() but not scan_vectors().-- Mirrors qdrant/pinecone/milvus/weaviate, which cannot honour a positional- offset and therefore expose native iteration instead.- """+ """Fake cursor-based store: iter_all() only, no usable scan_vectors()."""def __init__(self, items):self._items = items@@ -230,12 +226,7 @@ class VectorStoreScanVectorsTests(unittest.TestCase):# ---------------------------------------------------------------------------class VectorStoreIterAllDispatchTests(unittest.TestCase):- """iter_vectors() prefers a backend's native iter_all() when present.-- Cursor-based backends cannot implement scan_vectors(offset, limit)- honestly, so they expose iter_all() instead and iter_vectors() routes to- it rather than walking offsets.- """+ """iter_vectors() prefers a backend's native iter_all() when present."""def _persistent_store(self, backend_store, backend_name="qdrant"):store = VectorStore(backend="inmemory", dimension=2)@@ -268,9 +259,7 @@ class VectorStoreIterAllDispatchTests(unittest.TestCase):self.assertEqual(list(store.iter_vectors(batch_size=2)), items)def test_iter_vectors_falls_back_when_iter_all_not_callable(self):- # A mis-shaped adapter exposing a non-callable ``iter_all`` must not be- # invoked; the offset path still has to work. Mirrors the count()- # precedent in _MisShapedBackendStore.+ # Mirrors the count() precedent in _MisShapedBackendStore.items = [{"id": "a", "vector": None, "metadata": {}}]store = self._persistent_store(_MisShapedIterAllBackendStore(items))@@ -286,9 +275,7 @@ class VectorStoreIterAllDispatchTests(unittest.TestCase):self.assertEqual([item["metadata"] for item in collected], [{"type": "a"}])def test_iter_vectors_propagates_iter_all_errors(self):- # A scan that silently yields nothing is indistinguishable from an- # empty source, which would let `store migrate` report success having- # copied nothing (issue #1083).+ # Silently yielding nothing would read as an empty source (#1083).class _FailingIterAll:def iter_all(self, batch_size=500):raise ProcessingError("backend unreachable")