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
+12
View File
@@ -962,6 +962,9 @@ class Query:
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -974,6 +977,9 @@ class TakeQuery:
def use_rte(self, enable: bool): ...
async def output_schema(self) -> pa.Schema: ...
async def execute(self) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -1000,6 +1006,9 @@ class FTSQuery:
async def execute(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
async def explain_plan(self, verbose: Optional[bool]) -> str: ...
async def analyze_plan(
self, distributed_metrics: Optional[AnalyzePlanDistributedMetrics] = None
@@ -1009,6 +1018,9 @@ class FTSQuery:
class VectorQuery:
async def output_schema(self) -> pa.Schema: ...
async def execute(self) -> RecordBatchStream: ...
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
def where(self, filter: str): ...
def where_expr(self, expr: PyExpr): ...
def select(self, columns: List[Tuple[str, str]]): ...
+97 -10
View File
@@ -2567,10 +2567,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
columns and raises for blobs inside lists.
"""
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode != "lazy":
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
)
self._ensure_fragment_constraints_supported("to_arrow()")
results = self._table._execute_arrow(
self._query_for_scan(blob_sources), timeout=timeout
)
if self._reranker is not None:
source = results
results = self._reranker.rerank_vector(self._str_query, results)
check_reranker_result(results)
results = _merge_query_snapshot(results, source)
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
results, blob_mode=blob_mode, blob_sources=blob_sources
)
def to_query_object(self) -> Query:
@@ -2895,8 +2909,12 @@ class LanceFtsQueryBuilder(LanceQueryBuilder):
blob_sources = self._validated_blob_sources(blob_mode)
self._table._ensure_no_legacy_fts_index()
self._ensure_fragment_constraints_supported("to_arrow()")
query = self._query_for_scan(blob_sources)
results = self._table._execute_query(query, timeout=timeout).read_all()
if blob_mode == "lazy":
results = self._table._execute_arrow(query, timeout=timeout)
else:
results = self._table._execute_query(query, timeout=timeout).read_all()
if self._reranker is not None:
source = results
results = self._reranker.rerank_fts(self._query, results)
@@ -2945,8 +2963,18 @@ class LanceEmptyQueryBuilder(LanceQueryBuilder):
blob_sources = self._validated_blob_sources(blob_mode)
if blob_mode == "bytes" and blob_sources:
return self.to_batches(timeout=timeout, blob_mode=blob_mode).read_all()
if blob_mode != "lazy":
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
blob_mode=blob_mode,
blob_sources=blob_sources,
)
self._ensure_fragment_constraints_supported("to_arrow()")
return self._finalize_blob_query_table(
self.to_batches(timeout=timeout).read_all(),
self._table._execute_arrow(
self._query_for_scan(blob_sources), timeout=timeout
),
blob_mode=blob_mode,
blob_sources=blob_sources,
)
@@ -4062,6 +4090,17 @@ class AsyncQueryBase(object):
return AsyncRecordBatchReader._from_batches(schema, batches())
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
"""Execute with the native eager collector used by ``to_arrow``."""
self._ensure_fragment_constraints_supported("to_arrow()")
await self._maybe_add_blob_row_id()
reader = await self._inner.execute_to_reader(None, timeout)
return pa.Table.from_batches(reader, schema=reader.schema)
async def _execute_batches(
self,
*,
@@ -4187,10 +4226,17 @@ class AsyncQueryBase(object):
if blob_mode == "bytes" and blob_sources:
reader = await self.to_batches(timeout=timeout, blob_mode=blob_mode)
return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
batch_iter = await self.to_batches(timeout=timeout)
tbl = self._finalize_blob_query_table(
pa.Table.from_batches(await batch_iter.read_all(), schema=batch_iter.schema)
)
if blob_mode != "lazy":
batch_iter = await self.to_batches(timeout=timeout)
tbl = self._finalize_blob_query_table(
pa.Table.from_batches(
await batch_iter.read_all(), schema=batch_iter.schema
)
)
else:
tbl = self._finalize_blob_query_table(
await self._execute_eager(timeout=timeout)
)
return await self._apply_arrow_blob_mode(tbl, blob_mode, blob_sources)
async def to_list(
@@ -4936,6 +4982,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
)
)
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
try:
results = await super()._execute_eager(timeout=timeout)
except Exception as error:
_add_fts_position_error_note(error)
raise
if self._reranker:
source = results
results = self._reranker.rerank_fts(self.get_query(), results)
results = _merge_query_snapshot(results, source)
return results
async def _execute_batches(
self,
*,
@@ -5286,6 +5348,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table)
)
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
results = await super()._execute_eager(timeout=timeout)
if self._reranker:
source = results
results = self._reranker.rerank_vector(self._query_string, results)
results = _merge_query_snapshot(results, source)
return results
async def _execute_batches(
self,
*,
@@ -5294,8 +5368,12 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
blob_sources: Optional[dict[str, str]] = None,
) -> AsyncRecordBatchReader:
reader = await super()._execute_batches(
timeout=timeout, blob_sources=blob_sources
max_batch_length=max_batch_length,
timeout=timeout,
blob_sources=blob_sources,
)
if self._reranker is None:
return reader
results = pa.Table.from_batches(await reader.read_all(), reader.schema)
if self._reranker:
source = results
@@ -5421,6 +5499,15 @@ class AsyncHybridQuery(AsyncStandardQuery, AsyncVectorQueryBase):
return fts_query, vec_query, limit, offset
async def _execute_eager(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
self._ensure_fragment_constraints_supported("to_arrow()")
reader = await self._execute_batches(timeout=timeout)
return pa.Table.from_batches(await reader.read_all(), schema=reader.schema)
async def _execute_batches(
self,
*,
+8
View File
@@ -927,6 +927,14 @@ class RemoteTable(Table):
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
return LOOP.run(self._table._execute_arrow(query, timeout=timeout))
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
return LOOP.run(self._table._explain_plan(query, verbose))
+47
View File
@@ -2926,6 +2926,15 @@ class Table(ABC):
timeout: Optional[timedelta] = None,
) -> pa.RecordBatchReader: ...
def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
"""Execute a query and collect the whole result eagerly."""
return self._execute_query(query, timeout=timeout).read_all()
@abstractmethod
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str: ...
@@ -5968,6 +5977,26 @@ class LanceTable(Table):
return pa.RecordBatchReader.from_batches(async_iter.schema, iter_sync())
def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
# Keep the Python namespace pushdown path, including its branch rule.
if (
_should_push_down_query_table(
self._namespace_client, self._pushdown_operations
)
and not self._route_pushdown_to_rust
and self.current_branch() is None
and not _requires_local_namespace_execution(query)
):
return self._execute_query(query, timeout=timeout).read_all()
async_query = self._table._sync_query_to_async(query)
return LOOP.run(async_query._execute_eager(timeout=timeout))
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
return LOOP.run(self._table._explain_plan(query, verbose))
@@ -8485,6 +8514,24 @@ class AsyncTable:
max_batch_length=batch_size, timeout=timeout
)
async def _execute_arrow(
self,
query: Query,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
if (
_should_push_down_query_table(
self._namespace_client, self._pushdown_operations
)
and not self._route_pushdown_to_rust
and not _requires_local_namespace_execution(query)
):
return (await self._execute_query(query, timeout=timeout)).read_all()
async_query = self._sync_query_to_async(query)
return await async_query._execute_eager(timeout=timeout)
async def _explain_plan(self, query: Query, verbose: Optional[bool]) -> str:
# This method is used by the sync table
async_query = self._sync_query_to_async(query)
@@ -0,0 +1,57 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
from datetime import timedelta
import pyarrow as pa
import pytest
import lancedb
@pytest.mark.asyncio
async def test_execute_to_reader_collects_without_default_slicing(tmp_path):
db = await lancedb.connect_async(tmp_path)
rows = 5000
data = pa.table(
{
"id": pa.array(range(rows), type=pa.int64()),
"text": pa.array([f"row-{i}" for i in range(rows)]),
}
)
table = await db.create_table("test", data)
reader = await table._inner.query().execute_to_reader(None, None)
batches = list(reader)
assert sum(batch.num_rows for batch in batches) == rows
assert max(batch.num_rows for batch in batches) > 1024
@pytest.mark.asyncio
async def test_execute_to_reader_preserves_empty_schema(tmp_path):
db = await lancedb.connect_async(tmp_path)
data = pa.table(
{
"id": pa.array([1, 2], type=pa.int64()),
"text": pa.array(["a", "b"]),
}
)
table = await db.create_table("test", data)
query = table._inner.query()
query.where("id < 0")
reader = await query.execute_to_reader(None, None)
result = pa.Table.from_batches(reader, schema=reader.schema)
assert result.num_rows == 0
assert result.schema == await table.query().where("id < 0").output_schema()
@pytest.mark.asyncio
async def test_execute_to_reader_propagates_timeout(tmp_path):
db = await lancedb.connect_async(tmp_path)
table = await db.create_table("test", data=[{"id": 1}, {"id": 2}])
with pytest.raises(Exception, match="Query timeout"):
await table._inner.query().execute_to_reader(None, timedelta(0))
+4 -2
View File
@@ -1655,7 +1655,9 @@ def test_fts_phrase_query_is_preserved_in_query_object():
def test_fts_phrase_query_execution_preserves_user_text():
table = mock.Mock()
table.schema = pa.schema([])
table._execute_query.return_value = pa.table({"text": ["result"]}).to_reader()
# to_arrow() collects through the eager path; keep a real Table so the
# reranker still receives and returns the real result contract.
table._execute_arrow.return_value = pa.table({"text": ["result"]})
class CapturingReranker:
score = "relevance"
@@ -1677,7 +1679,7 @@ def test_fts_phrase_query_execution_preserves_user_text():
query.to_arrow()
backend_query = table._execute_query.call_args.args[0]
backend_query = table._execute_arrow.call_args.args[0]
assert (
backend_query.full_text_query.query,
reranker.queries,
+1 -2
View File
@@ -1739,7 +1739,7 @@ def test_query_builder_with_different_vector_column():
ds = mock.Mock()
table.to_lance.return_value = ds
builder.to_arrow()
table._execute_query.assert_called_once_with(
table._execute_arrow.assert_called_once_with(
Query(
vector=query,
filter="b < 10",
@@ -1748,7 +1748,6 @@ def test_query_builder_with_different_vector_column():
columns=["b"],
vector_column="foo_vector",
),
batch_size=None,
timeout=None,
)
+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()))
})
}
+64
View File
@@ -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 {