From ea4f1a38cf720ba7dd9d7c7d1350f8dfca99d293 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 20:45:03 +0800 Subject: [PATCH] fix: keep nonempty order_by out of namespace query pushdown (#5122) ## Problem With namespace `QueryTable` pushdown enabled, a query with a nonempty `order_by` was sent to the namespace server even though the request schema has no `order_by` field. With `limit(1)` this returned the wrong top row instead of the requested ordering. ## Fix Treat a nonempty `order_by` as requiring local execution in both the Python and Rust namespace pushdown gates. `None` or an empty ordering still uses pushdown. Local execution preserves branch, version and RTE semantics; if local storage cannot be read, the query fails explicitly rather than silently dropping the ordering. ## Validation - Public Python sync `search().order_by(...).limit(1).to_arrow()` and async `query().order_by(...).limit(1).to_arrow()` against a namespace mock: returned id 1 with zero pushdown calls. - `python/tests/test_namespace.py`: 83 passed. - Rust namespace pushdown tests: 5 passed; `table::query::tests`: 21 passed. - `cargo fmt`, `cargo clippy`, and Ruff clean. Fixes [OSS-3126](https://linear.app/lancedb/issue/OSS-3126/bug-namespace-querytable-pushdown-silently-drops-order-by). --- python/python/lancedb/namespace.py | 16 ++++-- python/python/lancedb/table.py | 3 ++ python/python/tests/test_namespace.py | 37 +++++++++++++- rust/lancedb/src/connection.rs | 7 +++ rust/lancedb/src/table/query.rs | 70 +++++++++++++++++++++++++-- 5 files changed, 124 insertions(+), 9 deletions(-) diff --git a/python/python/lancedb/namespace.py b/python/python/lancedb/namespace.py index 1de49d935..735eab51e 100644 --- a/python/python/lancedb/namespace.py +++ b/python/python/lancedb/namespace.py @@ -509,7 +509,9 @@ class LanceNamespaceDBConnection(DBConnection): Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1208,7 +1210,9 @@ class AsyncLanceNamespaceDBConnection: Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a + nonempty ``order_by`` execute locally and require the client to + access the table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1811,7 +1815,9 @@ def connect_namespace( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access the + table storage. - "CreateTable": Execute table creation on the namespace server via namespace.create_table() instead of using declare_table + local write. @@ -1902,7 +1908,9 @@ def connect_namespace_async( Supported values: - "QueryTable": Execute queries on the namespace server via - namespace.query_table() instead of locally. + namespace.query_table() instead of locally. Queries with a nonempty + ``order_by`` execute locally and require the client to access 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/table.py b/python/python/lancedb/table.py index ea9dee024..492526344 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -146,6 +146,9 @@ def _requires_local_namespace_execution(query: Query) -> bool: or query.take_row_ids is not None or query.search_effort is not None or query.approx_mode is not None + # 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) or ( query.full_text_query is not None and query.fast_search is True diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index c965618cd..937572cc0 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -29,7 +29,7 @@ from lancedb.namespace import ( LanceNamespaceDBConnection, _query_to_namespace_request, ) -from lancedb.query import FullTextSearchQuery, Query +from lancedb.query import ColumnOrdering, FullTextSearchQuery, Query from lancedb.table import AsyncTable, LanceTable @@ -1772,6 +1772,23 @@ class TestPushdownOperations: assert request.maximum_nprobes == 0 assert request.to_dict()["maximum_nprobes"] == 0 + def test_lance_table_order_by_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}, {"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=1, order_by=[ColumnOrdering(column_name="id")]) + ).read_all() + + # Pushing this query down would drop order_by and return id 3. + assert result.column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1834,6 +1851,24 @@ class TestAsyncPushdownOperations: assert [request.k for request in namespace_client.requests] == [_MAX_QUERY_K] assert all(r.k <= 2**31 - 1 for r in namespace_client.requests) + async def test_async_table_order_by_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}, {"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=1, order_by=[ColumnOrdering(column_name="id")]) + ) + + # Pushing this query down would drop order_by and return id 3. + batches = await result.read_all() + assert pa.Table.from_batches(batches).column("id").to_pylist() == [1] + assert namespace_client.requests == [] + @pytest.mark.parametrize( "query_kwargs", [ diff --git a/rust/lancedb/src/connection.rs b/rust/lancedb/src/connection.rs index db6aa2ba8..d413b2b78 100644 --- a/rust/lancedb/src/connection.rs +++ b/rust/lancedb/src/connection.rs @@ -2138,6 +2138,9 @@ use std::collections::HashSet; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum NamespaceClientPushdownOperation { /// Execute queries on the namespace server via `query_table()` instead of locally. + /// + /// Queries with a nonempty `order_by` execute locally and require client access + /// to the table storage. QueryTable, /// Execute table creation on the namespace server via `create_table()` /// instead of using `declare_table` + local write. @@ -2253,6 +2256,10 @@ impl ConnectNamespaceBuilder { /// - [`NamespaceClientPushdownOperation::QueryTable`]: Execute queries via `namespace.query_table()` /// - [`NamespaceClientPushdownOperation::CreateTable`]: Execute table creation via `namespace.create_table()` /// + /// Some query options cannot be represented in the namespace request. A query + /// with a nonempty `order_by` executes locally and requires client access to + /// the table storage. + /// /// By default, no operations are pushed down (all executed locally). pub fn pushdown_operation(mut self, operation: NamespaceClientPushdownOperation) -> Self { self.pushdown_operations.insert(operation); diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index 7d98dc001..6789714e1 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -120,10 +120,18 @@ 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 or use_rte. - // 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. - if query.base().use_rte.is_some() || query.base().has_take() { + // 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. + if query.base().use_rte.is_some() + || query.base().has_take() + || query + .base() + .order_by + .as_ref() + .is_some_and(|order_by| !order_by.is_empty()) + { return true; } if matches!(query, AnyQuery::Query(query) if query.fast_search && query.full_text_search.is_some()) @@ -1858,6 +1866,60 @@ mod tests { assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); } + #[tokio::test] + async fn test_execute_query_order_by_with_namespace_pushdown_runs_locally() { + use crate::connect; + use crate::query::ColumnOrdering; + use crate::table::query::execute_query; + use arrow_array::{Int32Array, RecordBatch}; + 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)])); + // Insertion order differs from ascending id, so a pushed-down query that + // drops order_by would return 3 instead of the correct top-1 row 1. + let batch = + RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![3, 1, 2]))]).unwrap(); + + let table = conn + .create_table("test_order_by_namespace_fallback", vec![batch]) + .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 { + limit: Some(1), + order_by: Some(vec![ColumnOrdering::asc_nulls_first("id".to_string())]), + ..Default::default() + }); + + let stream = execute_query(&native_table, &query, QueryExecutionOptions::default()) + .await + .unwrap(); + let batches = stream.try_collect::>().await.unwrap(); + let ids: Vec = batches + .iter() + .flat_map(|batch| { + batch + .column(0) + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec() + }) + .collect(); + + assert_eq!(ids, vec![1]); + assert_eq!(namespace_client.query_table_calls.load(Ordering::SeqCst), 0); + } + #[tokio::test] async fn test_query_snapshot_disables_namespace_pushdown() { use crate::connect;