diff --git a/mempalace/backends/qdrant.py b/mempalace/backends/qdrant.py index 9ba5ab6..1e5b2b4 100644 --- a/mempalace/backends/qdrant.py +++ b/mempalace/backends/qdrant.py @@ -55,9 +55,17 @@ _POINT_NAMESPACE = uuid.UUID("c06c3fc7-5c14-4dc4-84c2-24a5f72d8dc1") _TOKEN_RE = re.compile(r"\w{2,}", re.UNICODE) # Page size for Qdrant's /points/scroll cursor. 4096 (up from the original # 256) cuts REST round-trips ~16x for any full-collection walk (#1796). -# Qdrant's own docs suggest larger scroll batches are safe; this is still far +# Qdrant's own docs suggest larger scroll batches are safe, and this is well # below typical REST payload-size limits for metadata-only (with_vector=False) -# scrolls. +# scrolls such as get_all_metadata(). +# +# This constant also governs vector-bearing scrolls (with_vector=True), used +# by _rows()/get() when embeddings are requested and by _query_local_exact() +# for the $or/$contains local-filter query fallback. At 4096 rows per page, +# high-dimensional embeddings make those particular responses tens of MB -- +# Qdrant handles it and round-trips still drop overall, but this is a real +# trade-off, not a metadata-only optimization. (Noted in maintainer review +# on #1832.) _SCROLL_PAGE_SIZE = 4096 _SUPPORTED_OPERATORS = frozenset( {"$eq", "$ne", "$in", "$nin", "$and", "$or", "$contains", "$gt", "$gte", "$lt", "$lte"} @@ -486,7 +494,7 @@ class _QdrantRESTClient: collection: str, *, qdrant_filter: Optional[dict] = None, - limit: int = 4096, + limit: int = _SCROLL_PAGE_SIZE, offset: Any = None, with_vector: bool = False, ) -> tuple[list[dict], Any]: @@ -1015,16 +1023,16 @@ class QdrantCollection(BaseCollection): loop would re-walk the entire collection from the start just to discard everything outside its slice (O(n^2) over collection size). - This walks _scroll_all() exactly once and returns every matching - metadata dict directly -- the single-cursor-scroll fix requested in - issue #1796. + Delegates to self._rows(), the same single-scroll-plus-local-filter + helper that backs get()/delete(). With ids=None and + where_document=None, _rows() reduces to exactly one _scroll_all() + pass followed by an unconditional _matches_where() re-check on every + row -- the same filter logic get(), delete(), and lexical_search() + already use, so this can't independently drift from those call + sites. (Maintainer review on #1832: avoid duplicating the filter + dance inline.) """ - _validate_where(where) - local_filter = _requires_local_filter(where) - q_filter = None if local_filter else _qdrant_filter(where) - rows = self._scroll_all(qdrant_filter=q_filter, with_vector=False) - if where and local_filter: - rows = [row for row in rows if _matches_where(row["metadata"], where)] + rows = self._rows(where=where) return [row["metadata"] for row in rows] def delete(self, *, ids=None, where=None): diff --git a/tests/test_qdrant_bulk_metadata_scroll.py b/tests/test_qdrant_bulk_metadata_scroll.py index b48f546..08ad46e 100644 --- a/tests/test_qdrant_bulk_metadata_scroll.py +++ b/tests/test_qdrant_bulk_metadata_scroll.py @@ -17,33 +17,59 @@ import types import sys from unittest import mock +import pytest + # ── Stub heavy deps so we can import mempalace modules in isolation ───────── -def _install_stubs(): - stub_np = sys.modules.get("numpy") - if stub_np is None: - import numpy # noqa: F401 -- numpy is a real, light dependency here +# +# These names are only stubbed for the DURATION OF THIS MODULE's collection + +# test run, via the autouse fixture below. Mutating sys.modules at import +# time with no teardown (the previous approach) risked an order-dependent +# flake: if pytest collected this file before something else that needed the +# REAL mempalace.config / mempalace.searcher / etc., that other test would +# silently get our fake module instead, with no error and no obvious cause. +# (Maintainer review on #1832.) +_STUB_MODULE_NAMES = [ + "mempalace.knowledge_graph", + "mempalace.searcher", + "mempalace.palace_graph", + "mempalace.config", +] - for name in [ - "mempalace.knowledge_graph", - "mempalace.searcher", - "mempalace.palace_graph", - "mempalace.config", - ]: + +def _build_stub(name: str) -> types.ModuleType: + m = types.ModuleType(name) + m.KnowledgeGraph = lambda: types.SimpleNamespace() + m.search_memories = lambda *a, **kw: [] + m.traverse = lambda *a, **kw: {} + m.find_tunnels = lambda *a, **kw: {} + m.graph_stats = lambda *a, **kw: {} + m.MempalaceConfig = lambda: types.SimpleNamespace( + palace_path="~/.mempalace/palace", collection_name="mempalace" + ) + return m + + +@pytest.fixture(autouse=True) +def _stub_heavy_deps(monkeypatch): + """Install fake modules for the stub names, restored automatically on teardown. + + monkeypatch.setitem(sys.modules, ...) records the original value (or + "absent") for each key and restores it when the test ends -- unlike the + previous bare module-level `if name not in sys.modules: sys.modules[name] + = stub` pattern, which left the stub installed permanently for the rest + of the test session once set. + """ + for name in _STUB_MODULE_NAMES: if name not in sys.modules: - m = types.ModuleType(name) - m.KnowledgeGraph = lambda: types.SimpleNamespace() - m.search_memories = lambda *a, **kw: [] - m.traverse = lambda *a, **kw: {} - m.find_tunnels = lambda *a, **kw: {} - m.graph_stats = lambda *a, **kw: {} - m.MempalaceConfig = lambda: types.SimpleNamespace( - palace_path="~/.mempalace/palace", collection_name="mempalace" - ) - sys.modules[name] = m + monkeypatch.setitem(sys.modules, name, _build_stub(name)) + yield -_install_stubs() +# numpy is a real, light dependency -- imported eagerly here (not stubbed) +# so qdrant.py's own `import numpy as np` resolves to the real module both +# during this file's first import below and during every test. +import numpy # noqa: E402,F401 from mempalace.backends.base import ( # noqa: E402 BaseCollection,