From 97996869864ff3c9b59a87532881f498a31f329b Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Fri, 20 Nov 2026 21:30:40 +0800 Subject: [PATCH] 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. --- python/python/lancedb/_lancedb.pyi | 12 +++ python/python/lancedb/query.py | 107 ++++++++++++++++++-- python/python/lancedb/remote/table.py | 8 ++ python/python/lancedb/table.py | 47 +++++++++ python/python/tests/test_eager_collector.py | 57 +++++++++++ python/python/tests/test_fts.py | 6 +- python/python/tests/test_query.py | 3 +- python/src/arrow.rs | 45 +++++++- python/src/query.rs | 64 ++++++++++++ 9 files changed, 333 insertions(+), 16 deletions(-) create mode 100644 python/python/tests/test_eager_collector.py diff --git a/python/python/lancedb/_lancedb.pyi b/python/python/lancedb/_lancedb.pyi index 5a89f100b..962000c99 100644 --- a/python/python/lancedb/_lancedb.pyi +++ b/python/python/lancedb/_lancedb.pyi @@ -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]]): ... diff --git a/python/python/lancedb/query.py b/python/python/lancedb/query.py index 76d98e4f6..ce75dd68c 100644 --- a/python/python/lancedb/query.py +++ b/python/python/lancedb/query.py @@ -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, *, diff --git a/python/python/lancedb/remote/table.py b/python/python/lancedb/remote/table.py index 51a656a52..47d0d048f 100644 --- a/python/python/lancedb/remote/table.py +++ b/python/python/lancedb/remote/table.py @@ -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)) diff --git a/python/python/lancedb/table.py b/python/python/lancedb/table.py index 492526344..863671bd5 100644 --- a/python/python/lancedb/table.py +++ b/python/python/lancedb/table.py @@ -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) diff --git a/python/python/tests/test_eager_collector.py b/python/python/tests/test_eager_collector.py new file mode 100644 index 000000000..1eaed9678 --- /dev/null +++ b/python/python/tests/test_eager_collector.py @@ -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)) diff --git a/python/python/tests/test_fts.py b/python/python/tests/test_fts.py index 26ce5e528..1bf019fc2 100644 --- a/python/python/tests/test_fts.py +++ b/python/python/tests/test_fts.py @@ -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, diff --git a/python/python/tests/test_query.py b/python/python/tests/test_query.py index 82b40f9c6..3b0f3d5a2 100644 --- a/python/python/tests/test_query.py +++ b/python/python/tests/test_query.py @@ -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, ) diff --git a/python/src/arrow.rs b/python/src/arrow.rs index f0b4bceed..0384f2b2a 100644 --- a/python/src/arrow.rs +++ b/python/src/arrow.rs @@ -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( + py: Python<'_>, + query: Q, + max_batch_length: Option, + timeout: Option, +) -> PyResult> +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::>().await.infer_error()?; + let reader: Box = Box::new(RecordBatchIterator::new( + batches.into_iter().map(Ok), + schema, + )); + Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind())) + }) +} diff --git a/python/src/query.rs b/python/src/query.rs index 9864d7d74..3c6d9d662 100644 --- a/python/src/query.rs +++ b/python/src/query.rs @@ -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, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { 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, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { 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, + timeout: Option, + ) -> PyResult> { + 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> { 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, + timeout: Option, + ) -> PyResult> { + crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout) + } + pub fn explain_plan(self_: PyRef<'_, Self>, verbose: bool) -> PyResult> { let inner = self_.inner.clone(); future_into_py(self_.py(), async move {