diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index a3a9610c9..f40fbc30c 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -972,6 +972,7 @@ class Query: def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ... def nearest_to_text(self, query: dict) -> FTSQuery: ... def order_by(self, ordering: Optional[List[ColumnOrdering]]): ... + def scan_in_order(self, ordered: bool): ... async def output_schema(self) -> pa.Schema: ... async def execute( self, max_batch_length: Optional[int], timeout: Optional[timedelta] @@ -1129,6 +1130,7 @@ class PyQueryRequest: postfilter: Optional[bool] norm: Optional[str] order_by: Optional[List[ColumnOrdering]] + scan_in_order: Optional[bool] class CompactionStats: fragments_removed: int diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 3940e7b7e..4c8ec1a62 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -510,8 +510,8 @@ class LanceNamespaceDBConnection(DBConnection): - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a - nonempty ``order_by`` execute locally and require the client to - access the table storage. + nonempty ``order_by`` or an explicit ``scan_in_order(True)`` + execute on the client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1215,8 +1215,8 @@ class AsyncLanceNamespaceDBConnection: - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a - nonempty ``order_by`` execute locally and require the client to - access the table storage. + nonempty ``order_by`` or an explicit ``scan_in_order(True)`` + execute on the client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1824,8 +1824,8 @@ def connect_namespace( - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a nonempty - ``order_by`` execute locally and require the client to access the - table storage. + ``order_by`` or an explicit ``scan_in_order(True)`` execute on the + client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1917,8 +1917,8 @@ def connect_namespace_async( - "QueryTable": Execute queries on the namespace server via namespace.query_table() instead of locally. Queries with a nonempty - ``order_by`` execute locally and require the client to access the - table storage. + ``order_by`` or an explicit ``scan_in_order(True)`` execute on the + client and require access to the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 19e9051f7..68598dd68 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -371,6 +371,10 @@ def _scanner_kwargs_for_query( "with_row_id": with_row_id if with_row_id is not None else query.with_row_id, "with_row_address": query.with_row_address, "fast_search": query.fast_search, + "scan_in_order": query.scan_in_order, + # Legacy scalar-index plans can reorder rows. Explicit storage order + # evaluates filters over the manifest-ordered scan instead. + "use_scalar_index": False if query.scan_in_order is True else None, "blob_handling": BLOB_MODE_TO_HANDLING[blob_mode], "fragments": fragments, } @@ -381,6 +385,12 @@ def _scanner_fragments_for_query(query: Query, dataset: Optional[Any]) -> Option if query.fragments is not None and query.fragment_ids is not None: raise ValueError("fragments and fragment_ids cannot both be set") if query.fragments is not None: + if query.scan_in_order is True: + raise ValueError( + "scan_in_order(True) cannot validate with_fragments() against " + "the scanned dataset version; use fragment_ids() to select " + "fragments by manifest id" + ) return query.fragments if query.fragment_ids is None: return None @@ -1208,6 +1218,10 @@ class Query(pydantic.BaseModel): order_by: Optional[List[ColumnOrdering]] = None + # Tri-state storage-order requirement: None preserves the backend default, + # True requires manifest order, False allows an unordered scan. + scan_in_order: Optional[bool] = None + @classmethod def from_inner(cls, req: PyQueryRequest) -> Self: query = cls() @@ -1241,6 +1255,7 @@ class Query(pydantic.BaseModel): query.postfilter = req.postfilter if req.order_by is not None: query.order_by = [ColumnOrdering(**o) for o in req.order_by] + query.scan_in_order = req.scan_in_order if req.full_text_search is not None: query.full_text_query = FullTextSearchQuery( columns=None, @@ -1415,6 +1430,7 @@ class LanceQueryBuilder(ABC): self._approx_mode = None self._bypass_vector_index = None self._order_by = None + self._scan_in_order = None @deprecation.deprecated( deprecated_in="0.3.1", @@ -2023,7 +2039,9 @@ class LanceQueryBuilder(ABC): ---------- fragments : list[lance.Fragment] Fragments from ``table.to_lance().get_fragments()``. Pass fragments - from the same dataset snapshot. + from the same dataset snapshot. Use ``fragment_ids()`` instead when + ``scan_in_order(True)`` is set; fragment objects cannot be validated + against the pinned dataset version. Returns ------- @@ -3082,6 +3100,52 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): schema=schema, ) + def scan_in_order(self, ordered: bool = True) -> Self: + """Control whether an ordinary scan must preserve storage order. + + Parameters + ---------- + ordered: bool, default True + ``True`` requires manifest order: fragments in manifest order, then + rows in fragment order. ``False`` allows the backend to scan + unordered. Leave the method uncalled to preserve the backend + default. + + An unfiltered plain base-only scan of an Embedded table, pinned to one + dataset version, returns manifest order by default. RTE tables scan the + LSM by default and do not provide this guarantee unless + ``use_rte(False)`` selects the base table. Explicit ``True`` also + disables scalar-index filter planning, because legacy scalar-index plans + can return a different sequence; default filtered scans can still use + those plans and may not preserve manifest order. Filters still apply, + but the scan can read more data. ``with_fragments()`` is not supported + with ``True`` because fragment objects cannot be validated against the + pinned dataset version; use ``fragment_ids()`` instead, which resolves + ids from the manifest and remains ordered. Compaction, updates, or + opening a newer version can change that order, so pin the table version + when positions must remain stable across executions. An explicit + ``order_by()`` replaces manifest order with a global sort, and vector, + full-text, hybrid, or reranked queries return ranked results; combining + those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise + tables and RTE/LSM reads raise ``NotImplementedError`` because they + cannot uphold the order; set ``use_rte(False)`` to read the RTE base + table in storage order. When ``QueryTable`` pushdown is enabled, the + backend default may not preserve order; requesting ``True`` executes + against Embedded storage instead, because the namespace request has no + order field. + + Examples + -------- + >>> import lancedb + >>> db = lancedb.connect("memory://") + >>> table = db.create_table("scan_in_order", [{"id": 1}]) + >>> query = table.search().scan_in_order(True).select(["id"]) + >>> query.to_arrow()["id"].to_pylist() + [1] + """ + self._scan_in_order = ordered + return self + def to_query_object(self) -> Query: return Query( columns=self._columns, @@ -3094,6 +3158,7 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder): use_rte=self._use_rte, offset=self._offset, order_by=self._order_by, + scan_in_order=self._scan_in_order, ) def output_schema(self) -> pa.Schema: @@ -4142,7 +4207,9 @@ class AsyncQueryBase(object): query types. Other terminals and remote tables raise ``NotImplementedError`` before scanning instead of silently scanning the full table. Blob-specific ``to_pandas()`` fallbacks keep their - existing validation errors. + existing validation errors. Use ``fragment_ids()`` instead when + ``scan_in_order(True)`` is set; fragment objects cannot be validated + against the pinned dataset version. """ self._fragments = fragments return self @@ -4866,6 +4933,55 @@ class AsyncQuery(AsyncStandardQuery): super().__init__(inner, table) self._inner = inner + def scan_in_order(self, ordered: bool = True) -> Self: + """Control whether an ordinary scan must preserve storage order. + + Parameters + ---------- + ordered: bool, default True + ``True`` requires manifest order: fragments in manifest order, then + rows in fragment order. ``False`` allows the backend to scan + unordered. Leave the method uncalled to preserve the backend + default. + + An unfiltered plain base-only scan of an Embedded table, pinned to one + dataset version, returns manifest order by default. RTE tables scan the + LSM by default and do not provide this guarantee unless + ``use_rte(False)`` selects the base table. Explicit ``True`` also + disables scalar-index filter planning, because legacy scalar-index plans + can return a different sequence; default filtered scans can still use + those plans and may not preserve manifest order. Filters still apply, + but the scan can read more data. ``with_fragments()`` is not supported + with ``True`` because fragment objects cannot be validated against the + pinned dataset version; use ``fragment_ids()`` instead, which resolves + ids from the manifest and remains ordered. Compaction, updates, or + opening a newer version can change that order, so pin the table version + when positions must remain stable across executions. An explicit + ``order_by()`` replaces manifest order with a global sort, and vector, + full-text, hybrid, or reranked queries return ranked results; combining + those with ``scan_in_order(True)`` raises ``ValueError``. Enterprise + tables and RTE/LSM reads raise ``NotImplementedError`` because they + cannot uphold the order; set ``use_rte(False)`` to read the RTE base + table in storage order. When ``QueryTable`` pushdown is enabled, the + backend default may not preserve order; requesting ``True`` executes + against Embedded storage instead, because the namespace request has no + order field. + + Examples + -------- + >>> import asyncio + >>> import lancedb + >>> async def example(): + ... db = await lancedb.connect_async("memory://") + ... table = await db.create_table("scan_in_order_async", [{"id": 1}]) + ... query = table.query().scan_in_order(True).select(["id"]) + ... return (await query.to_arrow())["id"].to_pylist() + >>> asyncio.run(example()) + [1] + """ + self._inner.scan_in_order(ordered) + return self + @classmethod def _query_vec_to_array(self, vec: Union[VEC, Tuple]): if isinstance(vec, list): diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index a6ba1692e..529375f6e 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -149,6 +149,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: # The namespace QueryTable request has no order_by field. Pushing a # nonempty ordering down would drop it and return the wrong top-K rows. or bool(query.order_by) + # An ordered scan is a local manifest-order guarantee. The request has + # no scan-order field, so run it locally where storage is available. + or query.scan_in_order is True or ( query.full_text_query is not None and query.fast_search is True @@ -8529,6 +8532,8 @@ class AsyncTable: async_query = async_query.with_row_id() if query.order_by: async_query = async_query.order_by(query.order_by) + if query.scan_in_order is not None: + async_query = async_query.scan_in_order(query.scan_in_order) if query.vector: async_query = async_query.nearest_to(query.vector).distance_range( diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index 937572cc0..2c999d1b0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -1789,6 +1789,31 @@ class TestPushdownOperations: assert result.column("id").to_pylist() == [1] assert namespace_client.requests == [] + def test_lance_table_scan_in_order_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(str(tmp_path / "db")) + table = db.create_table("hist", data=[{"id": 3}, {"id": 1}]) + table.add([{"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table._execute_query( + Query( + limit=2, + filter="id >= 1", + columns=["id"], + scan_in_order=True, + ) + ).read_all() + + # The namespace request has no scan-order field. Local execution keeps + # membership order, projection and limit; a dropped order or a sort + # would return [1, 3] or [1, 2]. + assert result.column("id").to_pylist() == [3, 1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1869,6 +1894,29 @@ class TestAsyncPushdownOperations: assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] assert namespace_client.requests == [] + async def test_async_table_scan_in_order_is_not_pushed_down(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(str(tmp_path / "db")) + table = await db.create_table("hist", data=[{"id": 3}, {"id": 1}]) + await table.add([{"id": 2}]) + table._namespace_path = ["geneva"] + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_query( + Query( + limit=2, + filter="id >= 1", + columns=["id"], + scan_in_order=True, + ) + ) + + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index c01b3f9dc..ed8e0d24f 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1102,6 +1102,201 @@ def test_order_by_clears_with_none_and_empty_list(mem_db): assert query.order_by([]).to_query_object().order_by is None +def test_scan_in_order_plain_query(tmp_db): + table = tmp_db.create_table("scan_in_order", pa.table({"id": [0, 1]})) + table.add(pa.table({"id": [2, 3]})) + table.add(pa.table({"id": [4, 5]})) + + fragments = table.to_lance().get_fragments() + assert len(fragments) == 3, "the test needs real multi-fragment data" + + version = table.version + table.checkout(version) + + default = table.search().select(["id"]).to_arrow()["id"].to_pylist() + assert default == [0, 1, 2, 3, 4, 5] + assert table.search().to_query_object().scan_in_order is None + + ordered = table.search().scan_in_order().select(["id"]).to_arrow() + assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5] + repeated = table.search().scan_in_order(True).select(["id"]).to_arrow() + assert repeated.equals(ordered) + + unordered = ( + table.search().scan_in_order(False).select(["id"]).to_arrow()["id"].to_pylist() + ) + assert sorted(unordered) == [0, 1, 2, 3, 4, 5] + + sorted_desc = ( + table.search() + .scan_in_order(False) + .order_by(("id", "desc")) + .select(["id"]) + .to_arrow()["id"] + .to_pylist() + ) + assert sorted_desc == [5, 4, 3, 2, 1, 0] + + with pytest.raises(ValueError, match="nonempty order_by"): + table.search().scan_in_order().order_by("id").to_arrow() + + +@pytest.mark.asyncio +async def test_scan_in_order_async_query(tmp_db_async: AsyncConnection): + table = await tmp_db_async.create_table( + "scan_in_order_async", pa.table({"id": [0, 1]}) + ) + await table.add(pa.table({"id": [2, 3]})) + await table.add(pa.table({"id": [4, 5]})) + + assert len((await table.to_lance()).get_fragments()) == 3 + version = await table.version() + await table.checkout(version) + + ordered = await table.query().scan_in_order().select(["id"]).to_arrow() + assert ordered["id"].to_pylist() == [0, 1, 2, 3, 4, 5] + assert table.query().to_query_object().scan_in_order is None + + unordered = (await table.query().scan_in_order(False).select(["id"]).to_arrow())[ + "id" + ].to_pylist() + assert sorted(unordered) == [0, 1, 2, 3, 4, 5] + + with pytest.raises(ValueError, match="nonempty order_by"): + await table.query().scan_in_order().order_by("id").to_arrow() + with pytest.raises(ValueError, match="ranked results"): + await table.query().scan_in_order().nearest_to([0.0, 0.0]).to_arrow() + + +@pytest.mark.parametrize("ordered", [False, True]) +def test_scan_in_order_pandas_scanner_path(tmp_db, monkeypatch, ordered): + pytest.importorskip("lance") + data = _blob_query_data() + table = tmp_db.create_table( + f"scan_in_order_scanner_{ordered}", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + table.add(data.slice(2, 2)) + + query = table.search().select(["id", "blob"]).scan_in_order(ordered) + + def fail_to_arrow(*args, **kwargs): + raise AssertionError("scanner-backed pandas must not collect through to_arrow") + + monkeypatch.setattr(query, "to_arrow", fail_to_arrow) + + dataset = table.to_lance() + dataset_cls = type(dataset) + real_scanner = dataset_cls.scanner + captured = {} + + def capture_scanner(self, **kwargs): + captured.update(kwargs) + return real_scanner(self, **kwargs) + + monkeypatch.setattr(dataset_cls, "scanner", capture_scanner) + + df = query.to_pandas(blob_mode="descriptions", flatten=True) + + assert captured["scan_in_order"] is ordered + assert captured.get("use_scalar_index") is (False if ordered else None) + assert sorted(df["id"].tolist()) == [1, 2, 3, 4] + + +@pytest.mark.parametrize("storage_version", ["legacy", "stable"]) +def test_scan_in_order_indexed_filter_preserves_manifest_order( + tmp_path, storage_version +): + lance = pytest.importorskip("lance") + data = pa.table({"id": list(range(20)), "value": list(range(20))}) + dataset = lance.write_dataset( + data, + tmp_path / "t.lance", + data_storage_version=storage_version, + max_rows_per_file=10, + ) + dataset.create_scalar_index("value", "BTREE") + version_before_update = dataset.version + dataset.update({"value": "100"}, where="id = 0") + + table = lancedb.connect(str(tmp_path)).open_table("t") + for version in (version_before_update, dataset.version): + table.checkout(version) + base = table.search().scan_in_order(True).select(["id"]).limit(100) + expected = base.to_arrow()["id"].to_pylist() + actual = base.where("value < 1000").to_arrow()["id"].to_pylist() + assert actual == expected + + +def test_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids(tmp_db): + pytest.importorskip("lance") + data = _blob_query_data() + table = tmp_db.create_table( + "scan_in_order_fragments", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + table.add(data.slice(2, 2)) + table.checkout(table.version) + + fragments = table.to_lance().get_fragments() + reversed_fragments = fragments[::-1] + with pytest.raises(ValueError, match="use fragment_ids"): + ( + table.search() + .scan_in_order() + .select(["id", "blob"]) + .with_fragments(reversed_fragments) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + + # fragment_ids is already resolved from the manifest and stays ordered. + df_by_id = ( + table.search() + .scan_in_order() + .select(["id", "blob"]) + .fragment_ids([fragment.fragment_id for fragment in reversed_fragments]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + assert df_by_id["id"].tolist() == [1, 2, 3, 4] + + +@pytest.mark.asyncio +async def test_async_scan_in_order_rejects_with_fragments_and_keeps_fragment_ids( + tmp_db_async, +): + pytest.importorskip("lance") + data = _blob_query_data() + table = await tmp_db_async.create_table( + "scan_in_order_fragments_async", + data.slice(0, 2), + storage_options=LEGACY_BLOB_STORAGE_OPTIONS, + ) + await table.add(data.slice(2, 2)) + await table.checkout(await table.version()) + + fragments = (await table.to_lance()).get_fragments() + reversed_fragments = fragments[::-1] + with pytest.raises(ValueError, match="use fragment_ids"): + await ( + table.query() + .scan_in_order() + .with_fragments(fragments[::-1]) + .select(["id", "blob"]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + + df_by_id = await ( + table.query() + .scan_in_order() + .fragment_ids([fragment.fragment_id for fragment in reversed_fragments]) + .select(["id", "blob"]) + .to_pandas(blob_mode="descriptions", flatten=True) + ) + assert df_by_id["id"].tolist() == [1, 2, 3, 4] + + def test_order_by_rejects_invalid_input_early(mem_db): table = mem_db.create_table("test_order_by_invalid", [{"name": "a"}]) diff --git a/python/src/query.rs b/python/src/query.rs index 7a7e34416..d8cfedfdb 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -396,6 +396,7 @@ pub struct PyQueryRequest { pub postfilter: Option, pub norm: Option, pub order_by: Option>, + pub scan_in_order: Option, } impl From for PyQueryRequest { @@ -434,6 +435,7 @@ impl From for PyQueryRequest { order_by: query_request .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: query_request.scan_in_order, }, AnyQuery::VectorQuery(vector_query) => Self { limit: vector_query.base.limit, @@ -467,6 +469,7 @@ impl From for PyQueryRequest { .base .order_by .map(|order_by| order_by.into_iter().map(PyColumnOrdering::from).collect()), + scan_in_order: vector_query.base.scan_in_order, }, } } @@ -685,6 +688,10 @@ impl Query { Ok(()) } + pub fn scan_in_order(&mut self, ordered: bool) { + self.inner = self.inner.clone().scan_in_order(ordered); + } + #[pyo3(signature = ())] pub fn output_schema(self_: PyRef<'_, Self>) -> PyResult> { let inner = self_.inner.clone(); diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 57af7f28d..bc460dc35 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -742,8 +742,14 @@ pub trait ExecutableQuery { /// an Stream of Arrow [`arrow_array::RecordBatch`] (and you can also independently /// access the [`arrow_schema::Schema`] without polling the stream). /// - /// Note: The size of the returned batches and the order of individual rows is - /// not deterministic. + /// Note: The size of the returned batches is not deterministic. Row order + /// depends on the query shape: an ordinary unfiltered base-only scan of a + /// fixed table version in Embedded returns manifest order unless + /// [`Query::scan_in_order`] is set to `false` or a nonempty + /// [`QueryBase::order_by`] adds a sort. RTE + /// tables scan the LSM by default; use `use_rte(false)` for the base-only + /// guarantee. Ranked searches return rank order, while Enterprise and + /// namespace-pushed scans have no order guarantee. /// /// LanceDb will use many threads to calculate results and, when /// the result set is large, multiple batches will be processed at one time. @@ -922,6 +928,11 @@ pub struct QueryRequest { /// This allows ordering query results by one or more columns in either ascending or descending order. pub order_by: Option>, + /// Require (`Some(true)`), allow (`Some(false)`), or leave unchanged (`None`) + /// the scan order. See [`Query::scan_in_order`] for the contract and its + /// boundaries. + pub scan_in_order: Option, + /// Controls RTE read routing. When unset (the default), a query against a /// table that carries an RTE write spec (see /// [`crate::Table::enable_rte`]) is routed through the LSM scanner so @@ -956,6 +967,7 @@ impl Default for QueryRequest { norm: None, disable_scoring_autoprojection: false, order_by: None, + scan_in_order: None, use_rte: None, } } @@ -1044,6 +1056,64 @@ impl Query { VectorQuery::new(self) } + /// Require the results to follow storage order instead of allowing an + /// unordered scan. + /// + /// An unfiltered plain base-only scan of an Embedded table, pinned to one + /// dataset version, returns rows in that version's manifest order: + /// fragments in manifest order, then rows in fragment order. Ordinary + /// unfiltered base-only scans already use Lance's ordered scan by default, + /// so leaving this unset preserves that behavior. RTE tables scan the LSM + /// by default and do not provide this guarantee unless `use_rte(false)` + /// selects the base table. Use `true` when a caller assigns meaning to row + /// positions and must fail instead of silently receiving a different order. + /// + /// Explicit `true` also disables scalar-index filter planning. Legacy + /// scalar-index plans can materialize index rows in a different sequence, + /// so filters are evaluated over the manifest-ordered scan instead. Default + /// filtered scans can still use those plans and may not preserve manifest + /// order. The filter result is unchanged, but the scan can read more data. + /// + /// Leaving this unset preserves the backend default. In particular, a + /// namespace-backed native table configured for `QueryTable` pushdown may + /// not preserve order because the request has no order field; request + /// `true` to execute against Embedded storage. + /// + /// The order is fixed only for the dataset version being scanned. + /// Compaction, updates, or opening a newer version can change it, so pin a + /// version when positions must remain stable across executions. A latest + /// handle can also observe a different version between two executions. + /// + /// - `true` requires manifest order without adding a sort. A nonempty + /// [`QueryBase::order_by`], take query, vector, full-text, hybrid, or + /// reranked query conflicts with storage order and fails with + /// [`Error::InvalidInput`]. + /// Enterprise tables and RTE/LSM reads fail with [`Error::NotSupported`] + /// because they cannot uphold the requirement; set `use_rte(false)` to + /// read the RTE base table in storage order. Namespace-backed native + /// tables execute against Embedded storage instead of using `QueryTable` + /// pushdown, which has no order field, and fail if that storage cannot be + /// read. + /// + /// # Examples + /// + /// ```no_run + /// # use lancedb::query::ExecutableQuery; + /// # async fn example(table: &lancedb::Table) -> lancedb::Result<()> { + /// let rows = table.query().scan_in_order(true).execute().await?; + /// # Ok(()) + /// # } + /// ``` + /// - `false` allows the backend to scan without preserving order. An + /// explicit nonempty `order_by` still applies its sort. + /// + /// A nonempty `order_by` replaces manifest order with a global sort. Vector + /// and full-text searches return ranked results regardless of this option. + pub fn scan_in_order(mut self, ordered: bool) -> Self { + self.request.scan_in_order = Some(ordered); + self + } + /// Find the nearest vectors to the given query vector. /// /// This converts the query from a plain query to a vector query. @@ -2086,6 +2156,20 @@ struct TakeLookup { output_projection: Option>, } +/// Take queries restore rows in the requested offset or row-id order, so an +/// explicit storage-order requirement cannot be honored. Check this before the +/// lookup strips the take selectors and hands the inner request to a scan. +pub(crate) fn validate_take_scan_in_order(request: &QueryRequest) -> Result<()> { + if request.scan_in_order == Some(true) { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with take by row id or offset, which \ + defines its own result order" + .to_string(), + }); + } + Ok(()) +} + impl TakeQuery { /// Create a new `TakeQuery` that will return rows at the given offsets. /// @@ -2200,6 +2284,7 @@ impl TakeQuery { request: &QueryRequest, preserve_order: bool, ) -> Result { + validate_take_scan_in_order(request)?; let (indices, by_row_id) = match (&request.take_offsets, &request.take_row_ids) { (Some(indices), None) => (indices.clone(), false), (None, Some(indices)) => (indices.clone(), true), @@ -4564,6 +4649,78 @@ mod tests { assert!(!analyzed.contains("CoalescePartitionsExec")); } + #[tokio::test] + async fn test_take_scan_in_order_is_rejected_before_lookup() { + let tmp_dir = tempdir().unwrap(); + let table = make_test_table(&tmp_dir).await; + + let mut offsets = table + .take_offsets(vec![5, 1, 17]) + .select(Select::Columns(vec!["id".to_string()])) + .limit(2) + .offset(1); + offsets.mut_query().scan_in_order = Some(true); + + let plan_err = offsets + .create_plan(QueryExecutionOptions::default()) + .await + .expect_err("take planning must reject scan_in_order(true)"); + assert!( + matches!(&plan_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {plan_err}" + ); + + let execution_err = offsets + .execute() + .await + .err() + .expect("take execution must reject scan_in_order(true)"); + assert!( + matches!(&execution_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {execution_err}" + ); + + let explain_err = offsets + .explain_plan(false) + .await + .expect_err("take explain must reject scan_in_order(true)"); + assert!( + matches!(&explain_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {explain_err}" + ); + + let mut row_ids = table.take_row_ids(vec![5, 1]); + row_ids.mut_query().scan_in_order = Some(true); + let row_id_err = row_ids + .execute() + .await + .err() + .expect("take by row id must reject scan_in_order(true)"); + assert!( + matches!(&row_id_err, Error::InvalidInput { message } + if message.contains("take by row id or offset")), + "unexpected error: {row_id_err}" + ); + + // Allowing unordered scans leaves an ordinary take unchanged. + let mut allowed = table.take_offsets(vec![5, 1]); + allowed.mut_query().scan_in_order = Some(false); + let batches = allowed + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!( + batches.iter().map(|batch| batch.num_rows()).sum::(), + 2 + ); + } + #[rstest::rstest] #[case::unsorted(vec![5, 1, 17], vec![5, 1, 17])] #[case::duplicate_and_missing(vec![17, 5, 17, u64::MAX, 1], vec![17, 5, 17, 1])] diff --git a/rust/lancedb/src/remote/table.rs b/rust/lancedb/src/remote/table.rs index 760ab83fe..fc888e32b 100644 --- a/rust/lancedb/src/remote/table.rs +++ b/rust/lancedb/src/remote/table.rs @@ -1326,6 +1326,13 @@ impl RemoteTable { params: &QueryRequest, ) -> Result<()> { params.check_filter()?; + if params.scan_in_order == Some(true) { + return Err(Error::NotSupported { + message: "scan_in_order(true) requires an ordered scan of Embedded storage; \ + LanceDB Enterprise tables do not support storage-order scans yet" + .to_string(), + }); + } body["prefilter"] = params.prefilter.into(); // Only forward use_rte when explicitly set; a server that predates it // ignores the field and routes as it would by default. @@ -6718,6 +6725,27 @@ mod tests { assert_eq!(result.version, if old_server { 0 } else { 43 }); } + #[tokio::test] + async fn test_query_scan_in_order_true_is_not_supported() { + let table = Table::new_with_handler::<&str>("my_table", |_| { + panic!("scan_in_order(true) must fail before sending a request") + }); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("remote scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") + && message.contains("Enterprise tables")), + "unexpected error: {err}" + ); + } + #[tokio::test] async fn test_query_plain() { let expected_data = RecordBatch::try_new( diff --git a/rust/lancedb/src/table.rs b/rust/lancedb/src/table.rs index b168ff6ff..b79beca55 100644 --- a/rust/lancedb/src/table.rs +++ b/rust/lancedb/src/table.rs @@ -1897,10 +1897,17 @@ impl Table { /// Create a [`Query`] Builder. /// /// Queries allow you to search your existing data. By default the query will - /// return all the data in the table in no particular order. The builder + /// return all the data in the table. The builder /// returned by this method can be used to control the query using filtering, /// vector similarity, sorting, and more. /// + /// An ordinary unfiltered base-only scan of a fixed table version in + /// Embedded returns manifest order: fragments in manifest order, then rows + /// in fragment order. RTE tables scan the LSM by default; use + /// `use_rte(false)` for the base table guarantee. Compaction, updates, and + /// newer versions can change that order. Use [`Query::scan_in_order`] to + /// require it explicitly and fail on paths that cannot uphold it. + /// /// Note: By default, all columns are returned. For best performance, you should /// only fetch the columns you need. See [`Query::select_with_projection`] for /// more details. @@ -1967,8 +1974,10 @@ impl Table { /// /// ## Full scan /// - /// This query will return everything in the table in no particular - /// order. + /// This query returns everything in the table. On an Embedded table, an + /// ordinary unfiltered base-only scan of a fixed version returns manifest + /// order. RTE tables scan the LSM by default and need `use_rte(false)` for + /// base manifest order. /// /// ```no_run /// # use arrow_array::RecordBatch; diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index b69b85cb3..4dd8df294 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -121,11 +121,13 @@ async fn can_execute_namespace_query(table: &NativeTable, query: &AnyQuery) -> R fn requires_local_namespace_execution(query: &AnyQuery) -> bool { // The namespace QueryTable request cannot represent approx_mode, search_effort, - // use_rte or order_by. For use_rte that is worse than a tuning miss: RTE read - // routing lives only in `create_plan`, so a pushed-down query would return - // stale base-only data. A dropped order_by would return the wrong top-K rows. + // use_rte, order_by or scan_in_order. For use_rte that is worse than a tuning miss: + // RTE read routing lives only in `create_plan`, so a pushed-down query would return + // stale base-only data. A dropped order_by would return the wrong top-K rows, and a + // dropped ordered scan would silently stop guaranteeing manifest order. if query.base().use_rte.is_some() || query.base().has_take() + || query.base().scan_in_order == Some(true) || query .base() .order_by @@ -154,6 +156,47 @@ pub async fn analyze_query_plan( Ok(lance_analyze_plan(plan, Default::default()).await?) } +/// Reject requests that ask for storage order in a query shape that cannot +/// preserve it, or that also define a different result order. +fn validate_scan_in_order(query: &AnyQuery) -> Result<()> { + if query.base().scan_in_order != Some(true) { + return Ok(()); + } + + let ranked = match query { + AnyQuery::VectorQuery(_) => true, + AnyQuery::Query(query) => { + query.full_text_search.is_some() || query.reranker.is_some() || query.norm.is_some() + } + }; + if ranked { + return Err(Error::InvalidInput { + message: "scan_in_order(true) is only supported for ordinary scans; vector, \ + full-text, hybrid, and reranked queries return ranked results" + .to_string(), + }); + } + + if query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { + return Err(Error::InvalidInput { + message: "scan_in_order(true) conflicts with a nonempty order_by; remove the \ + ordering to keep manifest order, or remove scan_in_order(true) to sort" + .to_string(), + }); + } + + if query.base().has_take() { + return crate::query::validate_take_scan_in_order(query.base()); + } + + Ok(()) +} + /// Local Execution Path (DataFusion) async fn execute_generic_query( table: &NativeTable, @@ -177,6 +220,7 @@ pub async fn create_plan( options: QueryExecutionOptions, ) -> Result> { let query = query.canonicalized()?; + validate_scan_in_order(&query)?; if let AnyQuery::Query(request) = &query && request.has_take() { @@ -435,6 +479,17 @@ pub async fn create_plan( scanner.order_by(Some(order_by.clone()))?; } + if let Some(scan_in_order) = query.base.scan_in_order { + scanner.scan_in_order(scan_in_order); + if scan_in_order { + // Legacy scalar-index plans can union materialized index rows with + // unindexed fragments and emit a different sequence. Explicit + // storage order must come from the manifest scan, so filters fall + // back to evaluating over the ordered fragments. + scanner.use_scalar_index(false); + } + } + let mut plan = scanner .create_plan() .await @@ -1191,6 +1246,21 @@ mod tests { FixedSizeListArray::try_new_from_values(Float32Array::from(values), dimension).unwrap() } + fn collect_i32(batches: &[RecordBatch]) -> Vec { + batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect() + } + #[tokio::test] async fn test_parse_arrow_ipc_response_handles_file_and_stream() { use arrow_array::{Int32Array, RecordBatch}; @@ -2462,4 +2532,300 @@ mod tests { Some(ApproxMode::Accurate) ); } + + #[tokio::test] + async fn test_scan_in_order_local_multi_fragment_contract() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + + let table = conn + .create_table("scan_in_order_contract", batch(vec![0, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2, 3])).execute().await.unwrap(); + table.add(batch(vec![4, 5])).execute().await.unwrap(); + + let fragments = table + .as_native() + .unwrap() + .dataset + .get() + .await + .unwrap() + .get_fragments() + .len(); + assert_eq!(fragments, 3, "the test needs real multi-fragment data"); + + // An ordered scan must not introduce a global sort. + let plan = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .explain_plan(false) + .await + .unwrap(); + assert!( + !plan.contains("SortExec"), + "scan_in_order(true) must not add a sort, got:\n{plan}" + ); + + // Pin one version so repeated executions describe the same manifest. + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + for _ in 0..2 { + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + } + + // The default keeps the ordered local behavior. + let batches = table + .query() + .select(Select::columns(&["id"])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1, 2, 3, 4, 5]); + + // Allowing unordered scans changes no membership. + let mut unordered = collect_i32( + &table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(), + ); + unordered.sort(); + assert_eq!(unordered, vec![0, 1, 2, 3, 4, 5]); + + // An explicit sort still wins when storage order is not required. + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(false) + .order_by(Some(vec![ColumnOrdering::desc_nulls_last( + "id".to_string(), + )])) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![5, 4, 3, 2, 1, 0]); + + // Deletions keep manifest order, and small output batches plus + // limit/offset must not disturb it. + table.checkout_latest().await.unwrap(); + table.delete("id = 3").await.unwrap(); + let version = table.version().await.unwrap(); + table.checkout(version).await.unwrap(); + let batches = table + .query() + .select(Select::columns(&["id"])) + .scan_in_order(true) + .offset(1) + .limit(2) + .execute_with_options(QueryExecutionOptions { + max_batch_length: 1, + ..Default::default() + }) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert!( + batches.iter().all(|batch| batch.num_rows() <= 1), + "max_batch_length must stay bounded" + ); + assert_eq!(collect_i32(&batches), vec![1, 2]); + } + + #[tokio::test] + async fn test_scan_in_order_rejects_ranked_and_sorted_queries() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let vector = fixed_size_list_array(vec![0.0, 0.0, 1.0, 0.0, 2.0, 0.0], 2); + let schema = Arc::new(Schema::new(vec![ + Field::new("id", DataType::Int32, false), + Field::new("vector", vector.data_type().clone(), false), + ])); + let batch = RecordBatch::try_new( + schema, + vec![Arc::new(Int32Array::from(vec![0, 1, 2])), Arc::new(vector)], + ) + .unwrap(); + let table = conn + .create_table("scan_in_order_conflicts", batch) + .execute() + .await + .unwrap(); + + let err = table + .query() + .scan_in_order(true) + .order_by(Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())])) + .execute() + .await + .err() + .expect("ranked and sorted scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("nonempty order_by")), + "unexpected error: {err}" + ); + + let err = table + .query() + .scan_in_order(true) + .nearest_to(vec![0.0f32, 0.0]) + .unwrap() + .execute() + .await + .err() + .expect("ranked scans must be rejected"); + assert!( + matches!(&err, Error::InvalidInput { message } + if message.contains("ranked results")), + "unexpected error: {err}" + ); + } + + #[tokio::test] + async fn test_scan_in_order_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use arrow_schema::{DataType, Field, Schema}; + + let conn = connect("memory://").execute().await.unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = |ids: Vec| { + RecordBatch::try_new(schema.clone(), vec![Arc::new(Int32Array::from(ids))]).unwrap() + }; + // Insertion order differs from sorted order so a dropped scan order or + // an accidental sort changes the result. + let table = conn + .create_table("scan_in_order_namespace", batch(vec![3, 1])) + .execute() + .await + .unwrap(); + table.add(batch(vec![2])).execute().await.unwrap(); + + let namespace_client = Arc::new(CountingNamespaceClient::default()); + let mut native_table = table.as_native().unwrap().clone(); + native_table.namespace_client = Some(namespace_client.clone()); + native_table + .pushdown_operations + .insert(NamespaceClientPushdownOperation::QueryTable); + + let query = AnyQuery::Query(QueryRequest { + filter: Some(QueryFilter::Sql("id >= 1".to_string())), + select: Select::columns(&["id"]), + limit: Some(2), + scan_in_order: Some(true), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&query)); + + let batches = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![3, 1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + + // Allowing unordered scans does not require local execution. + let allow_unordered = AnyQuery::Query(QueryRequest { + scan_in_order: Some(false), + ..Default::default() + }); + assert!(!requires_local_namespace_execution(&allow_unordered)); + + // An explicit sort is already local because the namespace request has + // no order_by field. + let sorted = AnyQuery::Query(QueryRequest { + order_by: Some(vec![ColumnOrdering::asc_nulls_last("id".to_string())]), + ..Default::default() + }); + assert!(requires_local_namespace_execution(&sorted)); + } + + #[tokio::test] + async fn test_scan_in_order_true_rejected_on_rte() { + use crate::connect; + use crate::table::RTEWriteSpec; + use arrow_schema::{DataType, Field, Schema}; + + let dir = tempfile::tempdir().unwrap(); + let conn = connect(dir.path().to_str().unwrap()) + .execute() + .await + .unwrap(); + let schema = Arc::new(Schema::new(vec![Field::new("id", DataType::Int32, false)])); + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![0, 1]))]).unwrap(); + let table = conn + .create_table("scan_in_order_rte", batch) + .execute() + .await + .unwrap(); + table.set_unenforced_primary_key(["id"]).await.unwrap(); + table.enable_rte(RTEWriteSpec::unsharded()).await.unwrap(); + + let err = table + .query() + .scan_in_order(true) + .execute() + .await + .err() + .expect("RTE scans cannot guarantee manifest order"); + assert!( + matches!(&err, Error::NotSupported { message } + if message.contains("scan_in_order(true)") && message.contains("use_rte(false)")), + "unexpected error: {err}" + ); + + // The base table can still be read in storage order explicitly. + let batches = table + .query() + .scan_in_order(true) + .use_rte(false) + .execute() + .await + .unwrap() + .try_collect::>() + .await + .unwrap(); + assert_eq!(collect_i32(&batches), vec![0, 1]); + } } diff --git a/rust/lancedb/src/table/query/lsm.rs b/rust/lancedb/src/table/query/lsm.rs index 400df6c82..eddb4d0c0 100644 --- a/rust/lancedb/src/table/query/lsm.rs +++ b/rust/lancedb/src/table/query/lsm.rs @@ -183,6 +183,11 @@ fn reject_unsupported(query: &VectorQueryRequest) -> Result<()> { if query.base.order_by.is_some() { return unsupported("order_by"); } + if query.base.scan_in_order == Some(true) { + return unsupported( + "scan_in_order(true) (the LSM scanner does not preserve base manifest order)", + ); + } // Vector-only knobs the LSM scanner cannot honor. Both change results rather // than just recall, so error instead of silently ignoring them: distance_range // would return rows outside the bound, and use_index(false) asks for a