perf(python): add direct sync query execution (#5141)

## Summary

Route ordinary local `table.search(...).to_arrow()` queries through
private synchronous schema and eager-collection bindings instead of the
Python background event loop. Plain scans, vector searches (including
default vector-column inference), and native FTS in lazy Blob mode now
complete with zero `LOOP.run` submissions.

The synchronous path reuses the existing query lowering, core query
execution, eager collector, Arrow ownership, projection validation,
fragments, row ids, Blob finalization, reranking, and snapshot handling.
It uses the generation-scoped Tokio runtime and `OutstandingGuard`,
releases the GIL while waiting, checks CPython signals on the caller
thread at a bounded interval, and aborts and drops collected state when
a handler raises. Multi-threaded Tokio callback re-entry uses
`block_in_place`; current-thread contexts return a Python error.
Namespace, RemoteTable, Enterprise, streaming, take, and non-lazy Blob
routing are unchanged. No public API is added.

## Benchmark

Workload: 200,000 rows, 64 dimensions, BTREE on `id`, IVF_PQ on
`vector`; 50 warmups + 500 calls, p50/p99 of three alternating runs.
Build: `release-with-debug`. Baseline Python package from `03fc5404` ran
against the same candidate extension as the candidate, so this isolates
the Python event-loop route; a separately built matching baseline
extension is a follow-up validation target. The host had competing Rust
builds, so these numbers are preliminary, not isolated release
throughput.

| Workload | LOOP/schema per call before -> after | p50 before -> after
| p99 before -> after |
|---|---|---|---|
| plain point lookup `to_arrow()` | 2 / 1 -> 0 / 1 | 2.32 / 3.26 / 2.64
ms -> 1.64 / 1.89 / 1.80 ms | 3.87 / 3.92 / 3.69 ms -> 2.42 / 2.63 /
2.62 ms |
| indexed vector `to_arrow()` | 3 / 2 -> 0 / 2 | 5.20 / 5.13 / 3.79 ms
-> 4.65 / 4.22 / 4.31 ms | 7.18 / 7.52 / 6.45 ms -> 6.29 / 6.01 / 6.43
ms |

`to_batches()` remains on the existing streaming path. OSS-2868
1/2/4/8/16-thread scaling and fully matched build artifacts remain
separate follow-up.

## Validation

- `test_sync_query_direct.py`: plain/vector/native FTS with `LOOP.run`
patched to fail, default vector inference, empty schema, timeout,
single-worker progress-callback re-entry, and SIGINT/runtime reuse.
- `test_query.py` with direct tests: 253 passed, 1 skipped.
- `test_blob.py`: 266 passed, 1 skipped.
- `test_fts.py` + `test_rerankers.py`: 163 passed, 13 skipped.
- `test_table.py` + `test_namespace.py` + `test_sync_api_parity.py`: 649
passed, 17 skipped.
- Remote query/blob/schema subset: 206 passed.
- Runtime unit tests: 12 passed; `cargo check`, `cargo clippy`, `cargo
fmt --check`, and Python ruff passed.

The SIGINT case is marked slow and was run in focused validation; it is
not part of the default suite. Refs OSS-2867 (non-closing).
This commit is contained in:
Xuanwo
2026-11-21 04:41:11 +08:00
committed by GitHub
parent a3b6fecfd6
commit 13fe33581e
9 changed files with 546 additions and 20 deletions
+10
View File
@@ -575,6 +575,7 @@ class Table:
def _is_native(self) -> bool: ...
def close(self) -> None: ...
async def schema(self) -> pa.Schema: ...
def schema_sync(self) -> pa.Schema: ...
async def add(
self,
data: pa.RecordBatchReader,
@@ -976,6 +977,9 @@ class Query:
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
def execute_to_reader_sync(
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
@@ -1021,6 +1025,9 @@ class FTSQuery:
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
def execute_to_reader_sync(
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
@@ -1033,6 +1040,9 @@ class VectorQuery:
async def execute_to_reader(
self, max_batch_length: Optional[int], timeout: Optional[timedelta]
) -> pa.RecordBatchReader: ...
def execute_to_reader_sync(
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]]): ...
+60
View File
@@ -4033,6 +4033,26 @@ class AsyncQueryBase(object):
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
self._inner.with_row_id()
def _maybe_add_blob_row_id_sync(self) -> None:
if self._table is None:
self._blob_auto_row_id = False
self._blob_paths = ()
return
req = self._inner.to_query_request()
schema = self._table._schema_sync()
projection = _query_request_projection(req)
self._blob_auto_row_id = blob_auto_row_id_for_scan(
schema,
projection,
with_row_id=self._with_row_id,
)
if not self._blob_auto_row_id:
self._blob_paths = ()
return
self._blob_paths = tuple(blob_v2_projection_sources(schema, projection).keys())
self._inner.with_row_id()
async def _can_fetch_plain_legacy_blobs(self, blob_mode: BlobMode) -> bool:
if blob_mode != "bytes" or self._table is None:
return False
@@ -4220,6 +4240,18 @@ class AsyncQueryBase(object):
reader = await self._inner.execute_to_reader(None, timeout)
return pa.Table.from_batches(reader, schema=reader.schema)
def _execute_eager_sync(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
"""Execute with the synchronous native eager collector."""
self._ensure_fragment_constraints_supported("to_arrow()")
if not self._blob_row_id_prepared:
self._maybe_add_blob_row_id_sync()
reader = self._inner.execute_to_reader_sync(None, timeout)
return pa.Table.from_batches(reader, schema=reader.schema)
async def _execute_batches(
self,
*,
@@ -5118,6 +5150,22 @@ class AsyncFTSQuery(AsyncStandardQuery):
results = _merge_query_snapshot(results, source)
return results
def _execute_eager_sync(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
try:
results = super()._execute_eager_sync(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,
*,
@@ -5480,6 +5528,18 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
results = _merge_query_snapshot(results, source)
return results
def _execute_eager_sync(
self,
*,
timeout: Optional[timedelta] = None,
) -> pa.Table:
results = super()._execute_eager_sync(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,
*,
+14 -1
View File
@@ -4533,7 +4533,10 @@ class LanceTable(Table):
-------
pa.Schema
A PyArrow schema object."""
return LOOP.run(self._table.schema())
schema_sync = getattr(self._table, "_schema_sync", None)
if schema_sync is None:
return LOOP.run(self._table.schema())
return schema_sync()
def list_versions(self) -> List[Dict[str, Any]]:
"""List all versions of the table"""
@@ -6060,6 +6063,13 @@ class LanceTable(Table):
async_query = self._table._sync_query_to_async(query)
async_query._blob_row_id_prepared = query._blob_row_id_prepared
if (
self._table._inner._is_native()
and self._namespace_client is None
and not self._route_pushdown_to_rust
and isinstance(async_query, (AsyncQuery, AsyncVectorQuery, AsyncFTSQuery))
):
return async_query._execute_eager_sync(timeout=timeout)
return LOOP.run(async_query._execute_eager(timeout=timeout))
def _explain_plan(self, query: Query, verbose: Optional[bool] = False) -> str:
@@ -7430,6 +7440,9 @@ class AsyncTable:
"""
return _restore_blob_extensions(await self._inner.schema())
def _schema_sync(self) -> pa.Schema:
return _restore_blob_extensions(self._inner.schema_sync())
async def embedding_functions(self) -> Dict[str, EmbeddingFunctionConfig]:
"""
Get the embedding functions for the table
+4 -4
View File
@@ -2676,14 +2676,14 @@ def test_sync_query_prepares_schema_once_per_execution(tmp_path, monkeypatch):
)
calls = 0
original = AsyncTable.schema
original = AsyncTable._schema_sync
async def counted(self):
def counted(self):
nonlocal calls
calls += 1
return await original(self)
return original(self)
monkeypatch.setattr(AsyncTable, "schema", counted)
monkeypatch.setattr(AsyncTable, "_schema_sync", counted)
table.search().where("id = 1").select(["id"]).to_arrow()
assert calls <= 1
@@ -0,0 +1,160 @@
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright The LanceDB Authors
import signal
import os
import subprocess
import sys
import threading
from datetime import timedelta
import pyarrow as pa
import pytest
import lancedb
from lancedb import background_loop
from lancedb.index import BTree, FTS, IvfFlat
def _direct_query_table(tmp_path):
table = lancedb.connect(tmp_path).create_table(
"direct",
pa.table(
{
"id": pa.array([1, 2, 3, 4], pa.int64()),
"text": ["alpha beta", "alpha gamma", "beta gamma", "delta epsilon"],
"vector": pa.array(
[
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
],
pa.list_(pa.float32(), 4),
),
}
),
)
table.create_index("id", config=BTree())
table.create_index("vector", config=IvfFlat(distance_type="l2", num_partitions=1))
table.create_index("text", config=FTS(with_position=True))
return table
def test_direct_sync_queries_do_not_use_background_loop(tmp_path, monkeypatch):
table = _direct_query_table(tmp_path)
expected_empty_schema = table.search().where("id < 0").output_schema()
def fail(*_args, **_kwargs):
raise AssertionError("LOOP.run must not be used by direct sync queries")
monkeypatch.setattr(background_loop.LOOP, "run", fail)
point = table.search().where("id = 1").select(["id", "text"]).to_arrow()
assert point.to_pylist() == [{"id": 1, "text": "alpha beta"}]
with_row_id = (
table.search().where("id = 1").select(["id"]).with_row_id(True).to_arrow()
)
assert with_row_id["_rowid"].to_pylist() == [0]
# The vector column is inferred from the sync schema binding.
vector = table.search([0.9, 0.1, 0.0, 0.0]).limit(2).to_arrow()
assert vector["id"].to_pylist() == [1, 2]
assert "_distance" in vector.column_names
fts = table.search("alpha", query_type="fts").select(["id"]).to_arrow()
assert sorted(fts["id"].to_pylist()) == [1, 2]
assert "_score" in fts.column_names
phrase = table.search('"alpha beta"', query_type="fts").select(["id"]).to_arrow()
assert phrase["id"].to_pylist() == [1]
empty = table.search().where("id < 0").to_arrow()
assert empty.num_rows == 0
assert empty.schema == expected_empty_schema
with pytest.raises(Exception, match="Query timeout"):
table.search([1.0, 0.0, 0.0, 0.0]).to_arrow(timeout=timedelta(0))
@pytest.mark.skipif(sys.platform != "linux", reason="needs sched_setaffinity")
def test_direct_sync_query_from_single_worker_progress_callback(tmp_path):
script = r"""
import os
import sys
try:
cpus = sorted(os.sched_getaffinity(0))
if not cpus:
print("SKIP")
sys.exit(0)
os.sched_setaffinity(0, {cpus[0]})
except OSError:
print("SKIP")
sys.exit(0)
import lancedb
db = lancedb.connect("memory:///")
target = db.create_table(
"target",
[{"id": 1, "value": "one"}, {"id": 2, "value": "two"}],
)
source = db.create_table("source", [{"id": 1}])
seen = []
def progress(_update):
if not seen:
seen.append(
target.search()
.where("id = 1")
.select(["value"])
.to_arrow()
.to_pylist()
)
source.add([{"id": 2}], progress=progress)
assert seen == [[{"value": "one"}]], seen
print("OK")
"""
result = subprocess.run(
[sys.executable, "-c", script],
cwd=tmp_path,
capture_output=True,
text=True,
timeout=30,
)
if "SKIP" in result.stdout:
pytest.skip("sched_setaffinity did not leave a usable CPU")
assert result.returncode == 0, result.stdout + result.stderr
assert "OK" in result.stdout
@pytest.mark.slow
def test_direct_sync_query_sigint_aborts_and_reuses_runtime(tmp_path):
rows = 500_000
table = lancedb.connect(tmp_path).create_table(
"sigint",
pa.table(
{
"id": pa.array(range(rows), pa.int64()),
"text": pa.array([f"row-{row}" for row in range(rows)]),
}
),
)
# Warm the runtime and page cache so the timed call is long enough to observe.
table.search().select(["id"]).to_arrow()
timer = threading.Timer(0.001, os.kill, args=(os.getpid(), signal.SIGINT))
timer.start()
try:
with pytest.raises(KeyboardInterrupt):
table.search().select(["id", "text"]).to_arrow()
finally:
timer.cancel()
timer.join()
# The shared runtime and its generation counter remain usable.
after = table.search().where("id = 1").select(["id", "text"]).to_arrow()
assert after.to_pylist() == [{"id": 1, "text": "row-1"}]