perf(python): stream plain sync batches on demand (#5143)

## Problem

Synchronous local `table.search().to_batches()` creates one Python
future per batch through the background event loop. At the default
1024-row cap, a large scan pays that Python round trip thousands of
times even though the Rust stream can produce the next batch
immediately.

## Change

Use a pull-driven synchronous reader for native, non-namespace, ordinary
lazy plain scans. The query is executed once with the same
`QueryExecutionOptions` as the async path: `None` keeps the 1024-row
cap, `0` leaves sizing to the engine, and a positive value caps each
returned batch. Each `__next__` releases the GIL, waits for exactly one
batch from the same Rust stream through the reviewed
`block_on_interruptible`, and stores the stream back on success.

- No background producer and no Python `LOOP.run` per batch.
- A read error, interrupt, EOF, or the last owner drops the stream. A
normal early `break` can resume the same reader.
- The public `pa.RecordBatchReader` still comes from `from_batches`, so
the schema, Arrow capsule, and exception types stay unchanged. Existing
PyArrow `close()` behavior is unchanged; the known PyArrow close issue
is separately scoped.
- Routing is limited to native, non-namespace, lazy plain scans. Vector,
take, FTS/hybrid, remote, namespace, `to_arrow` direct eager routes, and
Blob `bytes`/`descriptions` keep their existing paths. Take ordering
from #5140 remains on the take path.
- Forward explicit `scan_in_order` through the pull launch; base-only
ordered `to_batches` results and the incompatible `order_by`/fragment
behavior are included in the scan-order suite.
- Adds a public RTE `to_batches` regression: the default LSM route sees
pending memtable writes, while `use_rte(False)` remains base-only.

## Validation

- `test_sync_pull_reader.py`, `test_merge_insert_lsm.py`, and
`test_sync_query_direct.py`: 53 passed.
- `test_query.py`, `test_blob.py`, and
`test_blob_query_without_pylance.py`: 539 passed, 1 skipped.
- `test_table.py`: 552 passed, 17 skipped.
- `test_remote_db.py -k "to_batches or take"`: 16 passed.
- `test_background_loop.py`: 4 passed.
- Rust `cargo test --manifest-path python/Cargo.toml --lib sync_stream`:
5 passed.
- `cargo check -j 1 --manifest-path python/Cargo.toml --lib --tests`
passed; no full Rust doctests were run.

A matched same-base release-with-debug streaming comparison is a
follow-up and is not claimed here.

Tracking: [OSS-2865](https://linear.app/lancedb/issue/OSS-2865)
This commit is contained in:
Xuanwo
2026-11-21 06:25:05 +08:00
committed by GitHub
parent 87262842e0
commit 8b8778938f
8 changed files with 628 additions and 8 deletions
+9
View File
@@ -952,6 +952,12 @@ class RecordBatchStream:
def __aiter__(self) -> "RecordBatchStream": ...
async def __anext__(self) -> pa.RecordBatch: ...
class SyncRecordBatchStream:
@property
def schema(self) -> pa.Schema: ...
def __iter__(self) -> "SyncRecordBatchStream": ...
def __next__(self) -> pa.RecordBatch: ...
class ColumnOrdering(TypedDict):
column_name: str
ascending: bool
@@ -977,6 +983,9 @@ class Query:
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> RecordBatchStream: ...
def execute_sync(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> SyncRecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
+35 -1
View File
@@ -1850,7 +1850,14 @@ class LanceQueryBuilder(ABC):
) -> pa.RecordBatchReader:
query = self._query_for_scan(blob_sources, schema)
reader = self._execute_query_prepared(
query, batch_size=batch_size, timeout=timeout
query,
batch_size=batch_size,
timeout=timeout,
pull_reader=(
blob_mode == "lazy"
and _query_is_plain_scan(query)
and not _query_needs_lance_scanner(self)
),
)
return self._batches_in_mode(reader, blob_mode, blob_sources, schema)
@@ -1860,9 +1867,19 @@ class LanceQueryBuilder(ABC):
*,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
pull_reader: bool = False,
) -> pa.RecordBatchReader:
if not _is_remote_query_table(self._table):
query._blob_row_id_prepared = True
if (
pull_reader
and not _is_remote_query_table(self._table)
and not self._table.namespace
and getattr(self._table, "_namespace_client", None) is None
):
return self._table._execute_pull_query(
query, batch_size=batch_size, timeout=timeout
)
return self._table._execute_query(query, batch_size=batch_size, timeout=timeout)
def _execute_arrow_prepared(
@@ -4933,6 +4950,23 @@ class AsyncQuery(AsyncStandardQuery):
super().__init__(inner, table)
self._inner = inner
def _execute_batches_sync(
self,
*,
max_batch_length: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader:
"""Execute a plain local scan with one Rust fetch per batch.
The query starts once; each iteration asks the same Rust stream for a
single batch instead of submitting one Python future per batch to the
background event loop. The public reader type and schema come from the
same stream, so Arrow export and exception behavior stay unchanged.
"""
self._ensure_fragment_constraints_supported("to_batches()")
stream = self._inner.execute_sync(max_batch_length, timeout)
return pa.RecordBatchReader.from_batches(stream.schema, stream)
def scan_in_order(self, ordered: bool = True) -> Self:
"""Control whether an ordinary scan must preserve storage order.
+31
View File
@@ -2961,6 +2961,16 @@ class Table(ABC):
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader: ...
def _execute_pull_query(
self,
query: Query,
*,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader:
"""Execute a pull-driven batch query, falling back to the normal path."""
return self._execute_query(query, batch_size=batch_size, timeout=timeout)
def _execute_arrow(
self,
query: Query,
@@ -6047,6 +6057,27 @@ class LanceTable(Table):
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
def _execute_pull_query(
self,
query: Query,
*,
batch_size: Optional[int] = None,
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader:
"""Execute a plain local scan with one Rust fetch per batch.
The caller has already checked that this is an embedded, non-namespace
plain lazy scan. A query shape that does not map to ``AsyncQuery``
keeps the existing reader path instead of guessing at its semantics.
"""
async_query = self._table._sync_query_to_async(query)
async_query._blob_row_id_prepared = query._blob_row_id_prepared
if isinstance(async_query, AsyncQuery):
return async_query._execute_batches_sync(
max_batch_length=batch_size, timeout=timeout
)
return self._execute_query(query, batch_size=batch_size, timeout=timeout)
def _execute_arrow(
self,
query: Query,
@@ -241,6 +241,25 @@ def test_lsm_read_sees_active_memtable(tmp_path):
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
def test_lsm_read_to_batches_sees_active_memtable(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
table = db.create_table("t", _reader([1, 2, 3])) # base ids 1,2,3
table.set_unenforced_primary_key("id")
table.enable_rte(RTEWriteSpec.unsharded())
_lsm_upsert(table, [4, 5]) # active memtable only, not committed to base
# The sync batch reader keeps the default LSM route and its pending writes.
lsm = pa.Table.from_batches(list(table.search().to_batches(batch_size=2)))
assert sorted(lsm["id"].to_pylist()) == [1, 2, 3, 4, 5]
# use_rte(False) still takes the base-only escape hatch through to_batches.
base_only = pa.Table.from_batches(
list(table.search().use_rte(False).to_batches(batch_size=2))
)
assert sorted(base_only["id"].to_pylist()) == [1, 2, 3]
def test_lsm_read_dedup_newest_wins(tmp_path):
db = lancedb.connect(tmp_path, read_consistency_interval=timedelta(seconds=0))
table = db.create_table("t", _reader([1, 2, 3])) # id 2 -> value 1
@@ -0,0 +1,195 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import gc
import time
from datetime import timedelta
import pyarrow as pa
import pytest
import lancedb
import lancedb.table as table_module
from lancedb.query import AsyncQuery
def _table(db, name="sync_pull_reader"):
return db.create_table(
name,
data=[{"id": i, "vector": [float(i), float(i)]} for i in range(10)],
)
def _spy_on_pull_reader(monkeypatch):
calls = []
real = AsyncQuery._execute_batches_sync
def spy(self, *, max_batch_length=None, timeout=None):
calls.append((max_batch_length, timeout))
return real(self, max_batch_length=max_batch_length, timeout=timeout)
monkeypatch.setattr(AsyncQuery, "_execute_batches_sync", spy)
return calls
@pytest.mark.parametrize(
"batch_size,row_limit",
[
(None, 1024),
(0, None),
(4, 4),
],
)
def test_plain_sync_batches_use_pull_reader(mem_db, monkeypatch, batch_size, row_limit):
table = _table(mem_db)
calls = _spy_on_pull_reader(monkeypatch)
reader = table.search().select(["id"]).to_batches(batch_size=batch_size)
assert isinstance(reader, pa.RecordBatchReader)
assert calls == [(batch_size, None)]
batches = list(reader)
assert sum(batch.num_rows for batch in batches) == 10
assert pa.Table.from_batches(batches).column("id").to_pylist() == list(range(10))
if row_limit is not None:
assert all(batch.num_rows <= row_limit for batch in batches)
def test_scan_in_order_routes_through_pull_reader(tmp_db, monkeypatch):
table = tmp_db.create_table("ordered_pull_reader", pa.table({"id": [0, 1]}))
table.add(pa.table({"id": [2, 3]}))
table.add(pa.table({"id": [4, 5]}))
table.checkout(table.version)
calls = _spy_on_pull_reader(monkeypatch)
reader = table.search().scan_in_order(True).select(["id"]).to_batches(batch_size=2)
assert calls == [(2, None)]
assert [value for batch in reader for value in batch["id"].to_pylist()] == [
0,
1,
2,
3,
4,
5,
]
with pytest.raises(ValueError, match="nonempty order_by"):
table.search().scan_in_order(True).order_by("id").to_batches()
def test_plain_sync_batches_do_not_enter_background_loop(mem_db, monkeypatch):
table = _table(mem_db)
def fail(*args, **kwargs):
raise AssertionError("plain sync batches entered the background event loop")
monkeypatch.setattr(table_module.LOOP, "run", fail)
reader = table.search().select(["id"]).to_batches(batch_size=4)
assert sum(batch.num_rows for batch in reader) == 10
@pytest.mark.parametrize(
"execute",
[
lambda table: table.search().select(["id"]).to_arrow(),
lambda table: table.search([0.0, 0.0]).to_batches(),
lambda table: table.take_offsets([0]).to_batches(),
lambda table: table.search().select(["id"]).order_by(["id"]).to_batches(),
lambda table: (
table.search().select(["id"]).to_batches(blob_mode="descriptions")
),
],
)
def test_other_sync_routes_keep_the_existing_reader(mem_db, monkeypatch, execute):
table = _table(mem_db)
calls = _spy_on_pull_reader(monkeypatch)
execute(table)
assert calls == []
@pytest.mark.asyncio
async def test_async_batches_keep_the_existing_reader(monkeypatch):
db = await lancedb.connect_async("memory://")
table = await db.create_table(
"async_sync_pull_reader", data=[{"id": i} for i in range(4)]
)
calls = _spy_on_pull_reader(monkeypatch)
reader = await table.query().to_batches()
total_rows = 0
async for batch in reader:
total_rows += batch.num_rows
assert total_rows == 4
assert calls == []
def test_timeout_starts_on_first_read_and_spans_reads(tmp_path):
table = lancedb.connect(tmp_path).create_table(
"timeout_pull_reader", data=[{"id": i} for i in range(8)]
)
reader = (
table.search()
.select(["id"])
.to_batches(batch_size=2, timeout=timedelta(milliseconds=200))
)
# A slow consumer before the first poll must not count against the query:
# the timeout starts when the first batch is requested.
time.sleep(0.25)
first = reader.read_next_batch()
assert first.num_rows == 2
# The deadline spans reads, so a pause between batches expires it.
time.sleep(0.25)
with pytest.raises(RuntimeError, match="Query timeout"):
reader.read_next_batch()
def test_early_break_can_resume_the_same_reader(mem_db):
table = _table(mem_db)
reader = table.search().select(["id"]).to_batches(batch_size=2)
first = next(iter(reader))
rest = list(reader)
assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
range(10)
)
reader = table.search().select(["id"]).to_batches(batch_size=2)
for first in reader:
break
rest = list(reader)
assert pa.Table.from_batches([first, *rest]).column("id").to_pylist() == list(
range(10)
)
def test_arrow_export_shares_cursor_with_the_last_owner(mem_db):
table = _table(mem_db)
reader = table.search().select(["id"]).to_batches(batch_size=2)
first = reader.read_next_batch()
capsule = reader.__arrow_c_stream__()
del reader
gc.collect()
imported = pa.RecordBatchReader._import_from_c_capsule(capsule)
rest = imported.read_all()
combined = pa.concat_tables([pa.Table.from_batches([first]), rest])
assert combined.column("id").to_pylist() == list(range(10))
def test_empty_result_preserves_the_query_schema(mem_db):
table = _table(mem_db)
query = table.search().select(["id"]).where("id < 0")
reader = query.to_batches(batch_size=4)
assert reader.schema == query.output_schema()
assert reader.read_all().num_rows == 0