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
@@ -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,
)