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.
This commit is contained in:
Yang Cen
2026-12-02 09:28:50 +00:00
committed by GitHub
parent 2e46464589
commit 50c66c66d5
10 changed files with 203 additions and 10 deletions
+1
View File
@@ -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: ...
+9 -2
View File
@@ -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,
*,
+17 -5
View File
@@ -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()
@@ -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(
+36
View File
@@ -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",
[
+83
View File
@@ -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]}))
+5 -1
View File
@@ -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,
})
}