From 50c66c66d5e00ba903d76a388c94d7edfd424f4f Mon Sep 17 00:00:00 2001 From: Yang Cen Date: Wed, 2 Dec 2026 17:28:50 +0800 Subject: [PATCH] fix(python): return row addresses from embedded scans (#5344) ## Problem Embedded Python queries accept `with_row_address()`, but ordinary sync and async scans omit `_rowaddr`. ## Fix Pass the existing option to the Lance scanner for Embedded base-table scans. Embedded namespace queries that request addresses use the Embedded scanner. An RTE scan reports that addresses require `use_rte(False)` to read the base table. ## Validation The two-fragment tests verify sync batches and async Arrow results, `uint64` physical addresses, projection, and default and explicit disabling. Stable row IDs confirm that `_rowaddr` is distinct from `_rowid`. Additional tests cover namespace routing, RTE and vector/FTS builder conversion. All applicable checks passed for `64dd3c0e`. The baseline test run stopped at the `stats()` fixture and did not reach the query assertions. Tracks OSS-2972. --- docs/web/curation/selective-sampling.mdx | 6 ++ python/python/lancedb/_lancedb.pyi | 1 + python/python/lancedb/query.py | 11 ++- python/python/lancedb/table.py | 22 ++++-- python/python/tests/test_merge_insert_lsm.py | 18 +++++ python/python/tests/test_namespace.py | 36 +++++++++ python/python/tests/test_query.py | 83 ++++++++++++++++++++ python/src/query.rs | 6 +- rust/lancedb/src/query.rs | 10 +++ rust/lancedb/src/table/query.rs | 20 ++++- 10 files changed, 203 insertions(+), 10 deletions(-) diff --git a/docs/web/curation/selective-sampling.mdx b/docs/web/curation/selective-sampling.mdx index 6505bddf4..162196bb3 100644 --- a/docs/web/curation/selective-sampling.mdx +++ b/docs/web/curation/selective-sampling.mdx @@ -71,6 +71,12 @@ let rows_by_offset_in_order = tbl Both methods return a query builder; call `.to_arrow()`, `.to_list()` or similar to execute it. +To include physical row addresses in a LanceDB Embedded Python scan, call +`tbl.search().with_row_address().to_arrow()`. The async builder supports the +same option with `await tbl.query().with_row_address().to_arrow()`. The +`_rowaddr` column is omitted by default. On RTE tables, add `.use_rte(False)` +to read only the base table and return its physical row addresses. + The guarantees for row IDs below apply to SDK releases containing [the ordering fix in #4826](https://github.com/lancedb/lancedb/pull/4826). diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 578ac81c6..61d77e668 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -1090,6 +1090,7 @@ class Query: def offset(self, offset: int): ... def fast_search(self): ... def with_row_id(self): ... + def _with_row_address(self, enabled: bool) -> None: ... def postfilter(self): ... def use_rte(self, enable: bool): ... def nearest_to(self, query_vec: pa.Array) -> VectorQuery: ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index e6cd3c624..752736733 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -2131,12 +2131,12 @@ class LanceQueryBuilder(ABC): return pa.RecordBatchReader.from_batches(result_schema, batches()) def with_row_address(self, with_row_address: bool = True) -> Self: - """Set whether to return row addresses. + """Set whether to return physical row addresses in Embedded base-table scans. Parameters ---------- with_row_address: bool, default True - If True, return the _rowaddr column in the results. + If True, include the ``_rowaddr`` column in the results. Returns ------- @@ -5203,6 +5203,13 @@ class AsyncQuery(AsyncStandardQuery): super().__init__(inner, table) self._inner = inner + def with_row_address(self, with_row_address: bool = True) -> Self: + """Include the ``_rowaddr`` column in Embedded base-table scans.""" + super().with_row_address(with_row_address) + if self._table is not None and self._table._inner._is_native(): + self._inner._with_row_address(with_row_address) + return self + def _execute_batches_sync( self, *, diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 9b3cabbf6..14aa3f30b 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -143,7 +143,9 @@ def _should_push_down_query_table( return namespace_client is not None and "QueryTable" in pushdown_operations -def _requires_local_namespace_execution(query: Query) -> bool: +def _requires_local_namespace_execution( + query: Query, table: Optional[AsyncTable] = None +) -> bool: # The namespace QueryTable request does not support these query options. _fts_wand = ( query.full_text_query.wand_factor if query.full_text_query is not None else None @@ -153,6 +155,13 @@ def _requires_local_namespace_execution(query: Query) -> bool: (isinstance(query.filter, str) and _uses_sql_subquery_filter(query.filter)) or query.take_offsets is not None or query.take_row_ids is not None + or ( + query.with_row_address + and query.vector is None + and query.full_text_query is None + and table is not None + and table._inner._is_native() + ) 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 @@ -6432,7 +6441,7 @@ class LanceTable(Table): ) and not self._route_pushdown_to_rust and self.current_branch() is None - and not _requires_local_namespace_execution(query) + and not _requires_local_namespace_execution(query, self._table) ): from lancedb.namespace import _execute_server_side_query @@ -6486,7 +6495,7 @@ class LanceTable(Table): ) and not self._route_pushdown_to_rust and self.current_branch() is None - and not _requires_local_namespace_execution(query) + and not _requires_local_namespace_execution(query, self._table) ): return self._execute_query(query, timeout=timeout).read_all() @@ -9101,6 +9110,9 @@ class AsyncTable: if getattr(query, "_force_local_namespace", False): async_query._force_local_namespace = True + if query.with_row_address and isinstance(async_query, AsyncQuery): + async_query = async_query.with_row_address() + if query.ordered is False and isinstance( async_query, (AsyncFTSQuery, AsyncVectorQuery) ): @@ -9119,7 +9131,7 @@ class AsyncTable: self._namespace_client, self._pushdown_operations ) and not self._route_pushdown_to_rust - and not _requires_local_namespace_execution(query) + and not _requires_local_namespace_execution(query, self) ): from lancedb.namespace import _execute_server_side_query @@ -9148,7 +9160,7 @@ class AsyncTable: self._namespace_client, self._pushdown_operations ) and not self._route_pushdown_to_rust - and not _requires_local_namespace_execution(query) + and not _requires_local_namespace_execution(query, self) ): return (await self._execute_query(query, timeout=timeout)).read_all() diff --git a/python/python/tests/test_merge_insert_lsm.py b/python/python/tests/test_merge_insert_lsm.py index 5b4114112..7523cf034 100644 --- a/python/python/tests/test_merge_insert_lsm.py +++ b/python/python/tests/test_merge_insert_lsm.py @@ -305,6 +305,24 @@ def test_lsm_read_unsupported_shape_errors_without_use_rte_false(tmp_path): assert sorted(base["id"].to_pylist()) == [1, 2, 3] +def test_lsm_row_address_requires_base_scan(tmp_path): + db = lancedb.connect(tmp_path) + table = db.create_table("t", _reader([1, 2, 3])) + table.set_unenforced_primary_key("id") + table.enable_rte(RTEWriteSpec.unsharded()) + _lsm_upsert(table, [4]) + + query = table.search().with_row_address() + with pytest.raises( + NotImplementedError, match=r"with_row_address.*use_rte\(false\)" + ): + query.to_arrow() + + base = query.use_rte(False).select(["id"]).to_arrow().sort_by("id") + assert base["id"].to_pylist() == [1, 2, 3] + assert base["_rowaddr"].to_pylist() == [0, 1, 2] + + @pytest.mark.asyncio async def test_async_lsm_read(tmp_path): db = await lancedb.connect_async( diff --git a/python/python/tests/test_namespace.py b/python/python/tests/test_namespace.py index d04da4568..8329a71d6 100644 --- a/python/python/tests/test_namespace.py +++ b/python/python/tests/test_namespace.py @@ -1814,6 +1814,30 @@ class TestPushdownOperations: assert result.column("id").to_pylist() == [3, 1] assert namespace_client.requests == [] + def test_lance_table_row_addresses_use_embedded_scan(self, tmp_path): + namespace_client = _NamespaceClient() + db = lancedb.connect(tmp_path) + table = db.create_table("hist", data=[{"id": 1}]) + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = table.search().with_row_address().to_arrow() + assert result.to_pylist() == [{"id": 1, "_rowaddr": 0}] + assert namespace_client.requests == [] + + def test_native_namespace_row_addresses_use_embedded_scan(self, tmp_path): + db = lancedb.connect_namespace( + "dir", + {"root": str(tmp_path)}, + namespace_client_pushdown_operations=["QueryTable"], + ) + table = db.create_table("hist", data=[{"id": 1}]) + + assert table._route_pushdown_to_rust + result = table.search().with_row_address().to_arrow() + assert result.to_pylist() == [{"id": 1, "_rowaddr": 0}] + @pytest.mark.asyncio class TestAsyncPushdownOperations: @@ -1917,6 +1941,18 @@ class TestAsyncPushdownOperations: assert pa.Table.from_batches(batches).column("id").to_pylist() == [3, 1] assert namespace_client.requests == [] + async def test_async_table_row_addresses_use_embedded_scan(self, tmp_path): + namespace_client = _NamespaceClient() + db = await lancedb.connect_async(tmp_path) + table = await db.create_table("hist", data=[{"id": 1}]) + table._namespace_client = namespace_client + table._pushdown_operations = {"QueryTable"} + table._route_pushdown_to_rust = False + + result = await table._execute_arrow(Query(with_row_address=True)) + assert result.to_pylist() == [{"id": 1, "_rowaddr": 0}] + 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 e81d1f355..d2e560c21 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -1103,6 +1103,89 @@ 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_plain_scan_with_row_address_sync(tmp_db): + table = tmp_db.create_table( + "row_addresses", + pa.table({"id": [1, 2, 3], "value": ["a", "b", "c"]}), + storage_options={"new_table_enable_stable_row_ids": "true"}, + ) + table.add(pa.table({"id": [4], "value": ["d"]})) + assert table.stats()["fragment_stats"]["num_fragments"] == 2 + + query = table.search() + assert query.to_arrow().column_names == ["id", "value"] + reader = query.with_row_address().to_batches() + assert "_rowaddr" in reader.schema.names + rows = reader.read_all().sort_by("id") + assert rows["_rowaddr"].type == pa.uint64() + assert rows["_rowaddr"].to_pylist() == [0, 1, 2, 1 << 32] + assert "_rowid" not in rows.column_names + + projected = ( + query.where("id >= 3").select(["id"]).with_row_id(True).to_arrow() + ).sort_by("id") + assert set(projected.column_names) == {"id", "_rowid", "_rowaddr"} + assert projected["_rowaddr"].to_pylist() == [2, 1 << 32] + assert projected["_rowid"][1].as_py() != projected["_rowaddr"][1].as_py() + assert query.with_row_address(False).to_arrow().column_names == ["id", "_rowid"] + + +@pytest.mark.asyncio +async def test_plain_scan_with_row_address_async(tmp_db_async): + table = await tmp_db_async.create_table( + "row_addresses", + pa.table({"id": [1, 2, 3], "value": ["a", "b", "c"]}), + storage_options={"new_table_enable_stable_row_ids": "true"}, + ) + await table.add(pa.table({"id": [4], "value": ["d"]})) + assert (await table.stats())["fragment_stats"]["num_fragments"] == 2 + + query = table.query() + assert (await query.to_arrow()).column_names == ["id", "value"] + rows = (await query.with_row_address().to_arrow()).sort_by("id") + assert "_rowaddr" in rows.column_names + assert rows["_rowaddr"].type == pa.uint64() + assert rows["_rowaddr"].to_pylist() == [0, 1, 2, 1 << 32] + assert "_rowid" not in rows.column_names + + query = query.where("id >= 3").select({"key": "id"}).with_row_id() + projected = (await query.to_arrow()).sort_by("key") + assert set(projected.column_names) == {"key", "_rowid", "_rowaddr"} + assert projected["_rowaddr"].to_pylist() == [2, 1 << 32] + assert projected["_rowid"][1].as_py() != projected["_rowaddr"][1].as_py() + assert (await query.with_row_address(False).to_arrow()).column_names == [ + "key", + "_rowid", + ] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("fts", [False, True], ids=["vector", "fts"]) +async def test_async_search_conversion_does_not_add_row_address(tmp_db_async, fts): + table = await tmp_db_async.create_table( + "row_address_search", _fragment_query_data() + ) + if fts: + await table.create_index("text", config=FTS()) + + def as_search(query): + if fts: + return query.nearest_to_text("one") + return query.nearest_to([1.0, 0.0]) + + scan = table.query().with_row_address() + before = as_search(scan) + after = as_search(table.query()).with_row_address() + + for query in (before, after): + assert "_rowaddr" not in (await query.output_schema()).names + result = await query.to_arrow() + assert result.num_rows > 0 + assert "_rowaddr" not in result.column_names + + assert "_rowaddr" in (await scan.to_arrow()).column_names + + 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]})) diff --git a/python/src/query.rs b/python/src/query.rs index 7bf2faf41..a755b38fe 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -654,6 +654,10 @@ impl Query { self.inner = self.inner.clone().with_row_id(); } + pub fn _with_row_address(&mut self, enabled: bool) { + self.inner = self.inner.clone().with_row_address(enabled); + } + pub fn postfilter(&mut self) { self.inner = self.inner.clone().postfilter(); } @@ -735,7 +739,7 @@ impl Query { } Ok(FTSQuery { - inner: self.inner.clone(), + inner: self.inner.clone().with_row_address(false), fts_query: query, }) } diff --git a/rust/lancedb/src/query.rs b/rust/lancedb/src/query.rs index 3db4866c2..c761f75a9 100644 --- a/rust/lancedb/src/query.rs +++ b/rust/lancedb/src/query.rs @@ -959,6 +959,8 @@ pub struct QueryRequest { /// By default, this is false. pub with_row_id: bool, + pub(crate) with_row_address: bool, + /// If set to false, the filter will be applied after the vector search. pub prefilter: bool, @@ -1029,6 +1031,7 @@ impl Default for QueryRequest { select: Select::All, fast_search: false, with_row_id: false, + with_row_address: false, prefilter: true, reranker: None, norm: None, @@ -1188,6 +1191,13 @@ impl Query { self } + /// Include the physical row address in Embedded base-table scans. + #[doc(hidden)] + pub fn with_row_address(mut self, enabled: bool) -> Self { + self.request.with_row_address = enabled; + self + } + /// Find the nearest vectors to the given query vector. /// /// This converts the query from a plain query to a vector query. diff --git a/rust/lancedb/src/table/query.rs b/rust/lancedb/src/table/query.rs index a9ea4b035..8e6c9a926 100644 --- a/rust/lancedb/src/table/query.rs +++ b/rust/lancedb/src/table/query.rs @@ -69,6 +69,11 @@ impl AnyQuery { } } + fn requests_row_address(&self) -> bool { + matches!(self, Self::Query(request) + if request.with_row_address && request.full_text_search.is_none() && !request.has_take()) + } + /// Canonicalize the query immediately before backend dispatch. pub(crate) fn canonicalized(&self) -> Result { let mut query = self.clone(); @@ -136,11 +141,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, - // query_parallelism, use_rte, order_by or scan_in_order. RTE read routing lives - // only in `create_plan`, so a pushed-down query would return stale base-only data. + // query_parallelism, use_rte, order_by, scan_in_order or row addresses. + // RTE read routing lives only in `create_plan`, so a pushed-down query would + // return stale base-only data. // Dropping order_by changes the top-K rows, and dropping scan_in_order loses // the guarantee of manifest order. if subquery_filter::predicate(query.base().filter.as_ref()).is_some() + || query.requests_row_address() || query.base().use_rte.is_some() || query.base().has_take() || query.base().scan_in_order == Some(true) @@ -287,6 +294,7 @@ pub async fn create_plan( .await; } + let with_row_address = query.requests_row_address(); let query = match query { AnyQuery::VectorQuery(query) => query, AnyQuery::Query(query) => VectorQueryRequest::from_plain_query(query), @@ -319,6 +327,11 @@ pub async fn create_plan( None => has_spec, }; if use_rte { + if with_row_address { + return Err(Error::NotSupported { + message: "with_row_address() requires a base-table scan. Use use_rte(false) to read only the base table.".into(), + }); + } if subquery_filter::predicate(query.base.filter.as_ref()).is_some() { return Err(Error::NotSupported { message: "SQL subquery filters require a base table scan. Use use_rte(false) to search the base table.".into(), @@ -495,6 +508,9 @@ pub async fn create_plan( if query.base.with_row_id { scanner.with_row_id(); } + if with_row_address { + scanner.with_row_address(); + } if options.max_batch_length > 0 { scanner.batch_size(options.max_batch_length as usize);