mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
@@ -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
|
||||
Reference in New Issue
Block a user