mirror of
https://github.com/lancedb/lancedb.git
synced 2026-11-26 12:33:59 +00:00
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:
+43
-2
@@ -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()))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -696,6 +696,20 @@ impl Query {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -784,6 +798,20 @@ impl TakeQuery {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
@@ -909,6 +937,28 @@ impl FTSQuery {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(
|
||||
self_.py(),
|
||||
self_
|
||||
.inner
|
||||
.clone()
|
||||
.full_text_search(self_.fts_query.clone()),
|
||||
max_batch_length,
|
||||
timeout,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn count_rows(self_: PyRef<'_, Self>) -> PyResult<Bound<'_, PyAny>> {
|
||||
let mut inner = self_
|
||||
.inner
|
||||
@@ -1148,6 +1198,20 @@ impl VectorQuery {
|
||||
})
|
||||
}
|
||||
|
||||
/// Execute this query eagerly and return an Arrow C Stream reader.
|
||||
///
|
||||
/// The returned reader exposes batches already collected in Rust, so
|
||||
/// `pyarrow` can build a table without a Python future per batch. `None`
|
||||
/// leaves out the core's default 1024-row output slicing.
|
||||
#[pyo3(signature = (max_batch_length=None, timeout=None))]
|
||||
pub fn execute_to_reader(
|
||||
self_: PyRef<'_, Self>,
|
||||
max_batch_length: Option<u32>,
|
||||
timeout: Option<Duration>,
|
||||
) -> PyResult<Bound<'_, PyAny>> {
|
||||
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
|
||||
}
|
||||
|
||||
pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult<Bound<'_, PyAny>> {
|
||||
let inner = self_.inner.clone();
|
||||
future_into_py(self_.py(), async move {
|
||||
|
||||
Reference in New Issue
Block a user