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
+40 -13
View File
@@ -5,7 +5,7 @@ use std::sync::Arc;
use std::time::Duration;
use crate::error::PythonErrorExt;
use crate::runtime::future_into_py;
use crate::runtime::{block_on_interruptible, future_into_py};
use arrow::{
datatypes::SchemaRef,
pyarrow::{IntoPyArrow, ToPyArrow},
@@ -89,18 +89,45 @@ 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,
));
let reader = collect_to_reader(query, max_batch_length, timeout).await?;
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
})
}
/// Synchronous counterpart of [`execute_to_reader`].
///
/// The returned reader owns the collected batches; the caller converts it to
/// Python after reattaching to the interpreter. The wait releases the GIL and
/// keeps Python signal handlers on the calling thread.
pub fn execute_to_reader_sync<Q>(
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
where
Q: ExecutableQuery + Send + 'static,
{
block_on_interruptible(collect_to_reader(query, max_batch_length, timeout))
}
async fn collect_to_reader<Q>(
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Box<dyn ArrowRecordBatchReader + Send>>
where
Q: ExecutableQuery + Send + 'static,
{
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()?;
Ok(Box::new(RecordBatchIterator::new(
batches.into_iter().map(Ok),
schema,
)))
}
+50
View File
@@ -33,6 +33,7 @@ use lancedb::query::{HasQuery, QueryBase};
use lancedb::table::AnyQuery;
use pyo3::Bound;
use pyo3::IntoPyObject;
use pyo3::Py;
use pyo3::PyAny;
use pyo3::PyRef;
use pyo3::PyResult;
@@ -65,6 +66,20 @@ fn analyze_plan_options(distributed_metrics: Option<&str>) -> PyResult<QueryExec
Ok(options)
}
fn execute_to_reader_sync<Q>(
py: Python<'_>,
query: Q,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>>
where
Q: ExecutableQuery + Send + 'static,
{
let reader =
py.detach(move || crate::arrow::execute_to_reader_sync(query, max_batch_length, timeout))?;
Python::attach(|py| reader.into_pyarrow(py).map(|obj| obj.unbind()))
}
impl<'a, 'py> FromPyObject<'a, 'py> for PyLanceDB<FtsQuery> {
type Error = PyErr;
@@ -713,6 +728,15 @@ impl Query {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader_sync(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>> {
execute_to_reader_sync(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 {
@@ -966,6 +990,23 @@ impl FTSQuery {
)
}
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader_sync(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>> {
execute_to_reader_sync(
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
@@ -1219,6 +1260,15 @@ impl VectorQuery {
crate::arrow::execute_to_reader(self_.py(), self_.inner.clone(), max_batch_length, timeout)
}
#[pyo3(signature = (max_batch_length=None, timeout=None))]
pub fn execute_to_reader_sync(
self_: PyRef<'_, Self>,
max_batch_length: Option<u32>,
timeout: Option<Duration>,
) -> PyResult<Py<PyAny>> {
execute_to_reader_sync(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 {
+199 -1
View File
@@ -93,15 +93,19 @@
//! `Arc` clone from becoming the final owner that drops it.
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::{Duration, Instant};
use arc_swap::ArcSwapOption;
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject};
use futures::FutureExt;
use pyo3::{Bound, PyAny, PyResult, Python, conversion::IntoPyObject, exceptions::PyRuntimeError};
use pyo3_async_runtimes::{
TaskLocals,
err::RustPanic,
generic::{ContextExt, JoinError, Runtime},
};
use tokio::{runtime, task};
@@ -282,6 +286,111 @@ pub fn block_on<F: std::future::Future>(fut: F) -> F::Output {
get_runtime().block_on(fut)
}
/// How often an interruptible wait returns to the Python caller for signal checks.
const SIGNAL_CHECK_INTERVAL: Duration = Duration::from_millis(25);
/// Block on `fut` while keeping the Python caller responsive to signals.
///
/// The query task lives on the shared runtime and carries an [`OutstandingGuard`].
/// The caller waits on the result channel without holding the GIL and periodically
/// reacquires it to run CPython's signal handlers on the same thread. A signal
/// exception aborts the task and drops the result receiver.
///
/// A synchronous callback already running on a multi-threaded Tokio worker uses
/// [`tokio::task::block_in_place`] so the core can be handed off while the callback
/// waits. Current-thread runtimes and contexts that reject blocking are returned as
/// Python errors instead of falling back to the Python event loop.
pub fn block_on_interruptible<F, T>(fut: F) -> PyResult<T>
where
F: Future<Output = PyResult<T>> + Send + 'static,
T: Send + 'static,
{
block_on_interruptible_with(fut, || Python::attach(|py| py.check_signals()))
}
fn block_on_interruptible_with<F, T, C>(fut: F, check: C) -> PyResult<T>
where
F: Future<Output = PyResult<T>> + Send + 'static,
T: Send + 'static,
C: FnMut() -> PyResult<()>,
{
match runtime::Handle::try_current() {
Ok(handle) => match handle.runtime_flavor() {
runtime::RuntimeFlavor::MultiThread => {
let result = catch_unwind(AssertUnwindSafe(|| {
task::block_in_place(|| block_on_interruptible_inner(fut, check))
}));
match result {
Ok(result) => result,
Err(payload) => Err(PyRuntimeError::new_err(format!(
"synchronous query cannot block in this Tokio context: {}",
panic_message(payload.as_ref())
))),
}
}
_ => Err(PyRuntimeError::new_err(
"synchronous query execution cannot block on a current-thread Tokio runtime; use the async API",
)),
},
Err(_) => block_on_interruptible_inner(fut, check),
}
}
fn block_on_interruptible_inner<F, T, C>(fut: F, mut check: C) -> PyResult<T>
where
F: Future<Output = PyResult<T>> + Send + 'static,
T: Send + 'static,
C: FnMut() -> PyResult<()>,
{
let guard = OutstandingGuard::new();
let (tx, rx) = mpsc::sync_channel(1);
let task = async move {
let _guard = guard;
let result = AssertUnwindSafe(fut).catch_unwind().await;
// Dropping a completed result is enough when the caller has already
// returned on an interrupt; the task's guard is dropped with it.
let _ = tx.send(result);
};
let handle = get_runtime().spawn(task);
loop {
match rx.recv_timeout(SIGNAL_CHECK_INTERVAL) {
Ok(Ok(result)) => {
check()?;
return result;
}
Ok(Err(payload)) => {
check()?;
return Err(RustPanic::new_err(format!(
"rust future panicked: {}",
panic_message(payload.as_ref())
)));
}
Err(RecvTimeoutError::Timeout) => {
if let Err(error) = check() {
handle.abort();
return Err(error);
}
}
Err(RecvTimeoutError::Disconnected) => {
return Err(PyRuntimeError::new_err(
"query task stopped before producing a result",
));
}
}
}
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str {
if let Some(message) = payload.downcast_ref::<&str>() {
message
} else if let Some(message) = payload.downcast_ref::<String>() {
message.as_str()
} else {
"unknown error"
}
}
/// Run a detached task, including when the caller is already on a runtime worker.
/// Keep it visible to [`shutdown`] until it finishes.
pub fn spawn_background<F>(fut: F)
@@ -571,6 +680,95 @@ mod tests {
shutdown(Duration::from_secs(5));
}
#[test]
fn test_block_on_interruptible_aborts_and_drops_future() {
use std::sync::mpsc;
Python::initialize();
let _lock = lock_runtime_state_for_test();
let (started_tx, started_rx) = mpsc::channel();
let (dropped_tx, dropped_rx) = mpsc::channel();
struct DropNotify(Option<mpsc::Sender<()>>);
impl Drop for DropNotify {
fn drop(&mut self) {
if let Some(tx) = self.0.take() {
let _ = tx.send(());
}
}
}
let fut = async move {
started_tx.send(()).unwrap();
let _notify = DropNotify(Some(dropped_tx));
std::future::pending::<()>().await;
#[allow(unreachable_code)]
Ok::<(), pyo3::PyErr>(())
};
let result = block_on_interruptible_with(fut, || {
Err(pyo3::exceptions::PyRuntimeError::new_err("interrupted"))
});
assert!(result.is_err());
started_rx
.recv_timeout(Duration::from_secs(2))
.expect("query task never started");
dropped_rx
.recv_timeout(Duration::from_secs(2))
.expect("interrupted query future was not dropped");
shutdown(Duration::from_secs(5));
}
#[test]
fn test_block_on_interruptible_maps_panic() {
Python::initialize();
let result = block_on_interruptible(async {
panic!("boom");
#[allow(unreachable_code)]
Ok::<(), pyo3::PyErr>(())
});
assert!(
result
.expect_err("panic must become a Python exception")
.to_string()
.contains("rust future panicked: boom")
);
}
#[test]
fn test_block_on_interruptible_rejects_current_thread_runtime() {
Python::initialize();
let runtime = runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("current-thread runtime");
let error = runtime
.block_on(async { block_on_interruptible(async { Ok::<_, pyo3::PyErr>(1) }) })
.expect_err("current-thread runtime must be rejected");
assert!(error.to_string().contains("current-thread"));
}
#[cfg(target_os = "linux")]
#[test]
fn test_block_on_interruptible_from_single_worker_runtime() {
Python::initialize();
let _lock = lock_runtime_state_for_test();
let _worker_threads = TestWorkerThreads::new(1);
shutdown(Duration::from_secs(5));
let (done_tx, done_rx) = mpsc::channel();
drop(get_runtime().spawn(async move {
let result = block_on_interruptible(async { Ok::<_, pyo3::PyErr>(42) });
let _ = done_tx.send(result.map_err(|error| error.to_string()));
}));
let result = done_rx
.recv_timeout(Duration::from_secs(10))
.expect("single-worker runtime made no progress");
assert_eq!(result.expect("single-worker query failed"), 42);
shutdown(Duration::from_secs(5));
}
// Adapted from the concurrent reproducer that found the original bug:
// many threads hammering the runtime while shutdown races them, not
// just the sequential rebuild path above. Before every reader held its
+9 -1
View File
@@ -9,7 +9,7 @@ use std::{
},
};
use crate::runtime::{block_on, future_into_py, spawn_background};
use crate::runtime::{block_on, block_on_interruptible, future_into_py, spawn_background};
use crate::{
connection::Connection,
error::PythonErrorExt,
@@ -1619,6 +1619,14 @@ impl Table {
})
}
pub fn schema_sync(self_: PyRef<'_, Self>) -> PyResult<Py<PyAny>> {
let inner = self_.inner_ref()?.clone();
let schema = self_.py().detach(move || {
block_on_interruptible(async move { inner.schema().await.infer_error() })
})?;
Python::attach(|py| schema.to_pyarrow(py).map(|obj| obj.unbind()))
}
#[pyo3(signature = (data, mode, progress=None, write_parallelism=None, allow_external_blob_outside_bases=false, retries=None))]
pub fn add<'a>(
self_: PyRef<'a, Self>,