perf(python): add native eager collection for to_arrow (#5127)

## Summary

`to_arrow()` currently collects results one Python future per batch:
both sync and async paths call `to_batches()`, which crosses the
Python/Rust bridge for every default 1024-row batch. Vector queries also
materialize the whole native stream even when no reranker is configured.

This adds a shared Rust eager collector. `execute_to_reader` collects
the batches in Rust, asks the core to skip the default 1024-row output
slicing, and exposes the result through the Arrow C Stream interface, so
Python builds the Table without a Python future per batch. Sync and
async `to_arrow`, including FTS, vector and hybrid eager paths, use it.
`AsyncVectorQuery.to_batches` no longer materializes results when there
is no reranker and now honors `max_batch_length`.

Schema, empty results, timeout, cancellation, and error behavior are
preserved. The existing fragment guard is enforced on the new fast path,
and namespace-pushdown routing keeps its existing Python/Rust split.

## Benchmark

Development-profile editable build, full scans on one revision, 1 warmup
+ 5 measured runs. Absolute values are not release-profile numbers;
compare before/after on the same build.

| Workload | Before | After |
|---|---|---|
| 5M rows x 3 columns, async | 3.054 s | 0.087 s (35.1x) |
| 5M rows x 3 columns, sync | 3.462 s | 0.090 s (38.3x) |
| 200k rows x 129 columns, async | 0.354 s | 0.082 s (4.3x) |
| 200k rows x 129 columns, sync | 0.387 s | 0.085 s (4.5x) |

The narrow scan returned 4,883 batches capped at 1,024 rows before and
611 batches up to 8,192 rows after.
This commit is contained in:
Xuanwo
2026-11-20 21:30:40 +08:00
committed by GitHub
parent dcded7fb70
commit 9799686986
9 changed files with 333 additions and 16 deletions
+43 -2
View File
@@ -2,15 +2,20 @@
// SPDX-FileCopyrightText: Copyright The LanceDB Authors
use std::sync::Arc;
use std::time::Duration;
use crate::error::PythonErrorExt;
use crate::runtime::future_into_py;
use arrow::{
datatypes::SchemaRef,
pyarrow::{IntoPyArrow, ToPyArrow},
record_batch::{RecordBatchIterator, RecordBatchReader as ArrowRecordBatchReader},
};
use futures::{TryStreamExt, stream::StreamExt};
use lancedb::{
arrow::SendableRecordBatchStream,
query::{ExecutableQuery, QueryExecutionOptions},
};
use futures::stream::StreamExt;
use lancedb::arrow::SendableRecordBatchStream;
use pyo3::{
Bound, Py, PyAny, PyRef, PyResult, Python, exceptions::PyStopAsyncIteration, pyclass, pymethods,
};
@@ -63,3 +68,39 @@ impl RecordBatchStream {
})
}
}
/// Execute `query` and collect every batch in Rust before returning to Python.
///
/// `to_arrow()` needs the complete table, so the default 1024-row output
/// slicing only adds work. Returning an Arrow C Stream reader also avoids a
/// Python future per batch while python materializes the table.
///
/// The stream is collected inside the returned future, so timeout and
/// cancellation keep the same observable behavior as reading the stream from
/// Python: errors surface from the awaited call and dropping the future drops
/// the underlying stream.
pub fn execute_to_reader<Q>(
py: Python<'_>,
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Bound<'_, PyAny>>
where
Q: ExecutableQuery + Send + 'static,
{
future_into_py(py, async move {
let mut options = QueryExecutionOptions::default();
// `None` means the caller wants one eager result, not the core's
// default batch size. An explicit value is still honored.
options.max_batch_length = max_batch_length.unwrap_or(0);
options.timeout = timeout;
let stream = query.execute_with_options(options).await.infer_error()?;
let schema = stream.schema();
let batches = stream.try_collect::<Vec<_>>().await.infer_error()?;
let reader: Box<dyn ArrowRecordBatchReader + Send> = Box::new(RecordBatchIterator::new(
batches.into_iter().map(Ok),
schema,
));
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
})
}