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
+39 -7
View File
@@ -7,6 +7,7 @@ use std::time::Duration;
use crate::expr::PyExpr;
use crate::runtime::future_into_py;
use crate::sync_stream::SyncRecordBatchStream;
use crate::util::parse_distance_type;
use crate::{arrow::RecordBatchStream, util::PyLanceDB};
use crate::{error::PythonErrorExt, index::class_name};
@@ -80,6 +81,20 @@ where
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
}
fn query_execution_options(
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> QueryExecutionOptions {
let mut options = QueryExecutionOptions::default();
if let Some(max_batch_length) = max_batch_length {
options.max_batch_length = max_batch_length;
}
if let Some(timeout) = timeout {
options.timeout = Some(timeout);
}
options
}
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
type Error = PyErr;
@@ -709,18 +724,35 @@ impl Query {
) -> PyResult<Bound<'_, PyAny>> {
let inner = self_.inner.clone();
future_into_py(self_.py(), async move {
let mut opts = QueryExecutionOptions::default();
if let Some(max_batch_length) = max_batch_length {
opts.max_batch_length = max_batch_length;
}
if let Some(timeout) = timeout {
opts.timeout = Some(timeout);
}
let opts = query_execution_options(max_batch_length, timeout);
let inner_stream = inner.execute_with_options(opts).await.infer_error()?;
Ok(RecordBatchStream::new(inner_stream))
})
}
/// Execute this local query and return a pull-driven synchronous iterator.
///
/// The query is started once. Each `__next__` fetches exactly one batch
/// from the caller's thread while the GIL is released. `None` keeps the
/// core's default 1024-row output cap, `0` lets the engine choose, and a
/// positive value caps each returned batch.
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_sync(
self_: PyRef<'_, Self>,
py: Python<'_>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<SyncRecordBatchStream> {
let inner = self_.inner.clone();
let opts = query_execution_options(max_batch_length, timeout);
let stream = py.detach(move || {
crate::runtime::block_on_interruptible(async move {
inner.execute_with_options(opts).await.infer_error()
})
})?;
Ok(SyncRecordBatchStream::new(stream))
}
/// Execute this query eagerly and return an Arrow C Stream reader.
///
/// The returned reader exposes batches already collected in Rust, so