Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ changes go in their respective binding's NEXT_CHANGELOG.

- A native Rust ADBC 1.1 driver in `adbc/`, with an optional standard ADBC C
ABI for driver-manager loading from other languages.
- `ExecutedStatement::try_next_batch_is_cheap()` and
`ResultStream::try_next_batch_is_cheap()` report whether `try_next_batch` is
supported and a ready batch needs no per-row work on the calling thread, so
bindings can take it without giving up a host lock. Readers opt in with
`ResultReader::try_next_batch_is_cheap` (default `false`).

### Changed

Expand Down
6 changes: 6 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ changes go in the root `NEXT_CHANGELOG.md`.
### Added

### Changed
- `ExecutedStatement.fetch_next_batch()` returns batches that are already
in memory without releasing the GIL, `close()` after the stream is
drained no longer releases it either, and `Statement.execute()` on a
thread other than the main thread no longer re-acquires it every
100 ms to check for signals that only the main thread can receive.
This cuts GIL hand-offs per query when many threads share the GIL.

### Updated

Expand Down
113 changes: 113 additions & 0 deletions pyo3/src/gil.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright (c) 2026 Databricks, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Helpers that avoid needless GIL hand-offs.
//!
//! Each `py.detach` releases the GIL and re-acquires it on return. With
//! hundreds of Python threads sharing one connection pool, every
//! re-acquire waits behind the other threads, so a call that needs no
//! I/O is cheaper done with the GIL held.

use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::types::PyModule;
use std::future::Future;
use std::task::{Context, Poll, Waker};
use tokio::runtime::Runtime;

static THREADING: PyOnceLock<Py<PyModule>> = PyOnceLock::new();

/// Whether the calling thread is Python's main thread, the only one that
/// runs signal handlers. Errs towards `true` (a wrong `true` only keeps
/// signal checks on).
///
/// Either id may match: `threading` refreshes the main thread's `ident`
/// after `fork()` but not its `native_id`, while greenlet libraries
/// (gevent, eventlet) patch `get_ident` but not the OS-level `native_id`.
pub(crate) fn on_main_thread(py: Python<'_>) -> bool {
let check = || -> PyResult<bool> {
let threading = THREADING
.get_or_try_init(py, || py.import("threading").map(Bound::unbind))?
.bind(py);
let main = threading.call_method0("main_thread")?;
if threading
.call_method0("get_ident")?
.eq(main.getattr("ident")?)?
{
return Ok(true);
}
threading
.call_method0("get_native_id")?
.eq(main.getattr("native_id")?)
};
check().unwrap_or(true)
}

/// Drive `fut` to completion, polling it once with the GIL held first and
/// releasing the GIL only if it isn't ready.
///
/// Only for futures whose first poll never blocks the thread: no network
/// I/O and no token refresh before the first `.await` that can pend.
pub(crate) fn run_ready_first<F>(py: Python<'_>, runtime: &Runtime, fut: F) -> F::Output
where
F: Future + Send,
F::Output: Send,
{
let mut fut = std::pin::pin!(fut);
let first = {
let _context = runtime.enter();
fut.as_mut().poll(&mut Context::from_waker(Waker::noop()))
};
match first {
Poll::Ready(output) => output,
Poll::Pending => py.detach(|| runtime.block_on(fut)),
}
}

#[cfg(test)]
mod tests {
use super::run_ready_first;
use pyo3::prelude::*;
use std::time::Duration;

fn runtime() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_all()
.build()
.expect("build runtime")
}

#[test]
fn ready_future_completes_on_first_poll() {
Python::initialize();
let runtime = runtime();
let out = Python::attach(|py| run_ready_first(py, &runtime, async { 7 }));
assert_eq!(out, 7);
}

#[test]
fn pending_future_finishes_on_the_runtime() {
Python::initialize();
let runtime = runtime();
let (tx, rx) = tokio::sync::oneshot::channel();
runtime.spawn(async move {
tokio::time::sleep(Duration::from_millis(20)).await;
let _ = tx.send(7);
});
// The first poll registers a no-op waker; block_on must re-poll.
let out = Python::attach(|py| run_ready_first(py, &runtime, async { rx.await.ok() }));
assert_eq!(out, Some(7));
}
}
1 change: 1 addition & 0 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ mod auth;
mod errors;
mod executed_async;
mod fetch;
mod gil;
mod logging;
mod metadata;
mod params;
Expand Down
10 changes: 10 additions & 0 deletions pyo3/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ macro_rules! run_kernel {
/// mid-execute cancel guard, so the server-side statement is cancelled
/// too, not just abandoned.
///
/// Only Python's main thread runs signal handlers, so on any other thread
/// the future runs in one GIL-released slice: re-acquiring the GIL every
/// tick there costs a GIL hand-off and checks nothing.
///
/// `$runtime` must be a `&tokio::runtime::Runtime` (so the future can
/// be driven across slices). Expands to a `PyResult<T>` (the future's
/// `Ok` value), mapping kernel `Error`s via `to_py_err` and surfacing
Expand All @@ -73,7 +77,13 @@ macro_rules! run_kernel_interruptible {
// 100ms balances interrupt latency against per-tick overhead.
const TICK: ::std::time::Duration = ::std::time::Duration::from_millis(100);
let mut fut = ::std::boxed::Box::pin($future);
let interruptible = $crate::gil::on_main_thread(py);
loop {
if !interruptible {
break py
.detach(|| runtime.block_on(&mut fut))
.map_err(|e| $crate::errors::to_py_err(py, e));
}
let step = py.detach(|| {
runtime.block_on(async {
match ::tokio::time::timeout(TICK, &mut fut).await {
Expand Down
42 changes: 35 additions & 7 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ use crate::runtime::KernelRuntime;
use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::{
Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle,
Statement as KStatement, StatementCanceller as KStatementCanceller,
Error as KError, ExecutedStatement as KExecutedStatement, ExecutedStatementHandle, ResultBatch,
Statement as KStatement, StatementCanceller as KStatementCanceller, TryNextBatch,
};
use pyo3::prelude::*;
use std::collections::HashMap;
Expand Down Expand Up @@ -349,10 +349,32 @@ impl ExecutedStatement {
return Ok(None);
}
let runtime = inner.runtime.clone();
// `next_batch_exec` drives the ExecutedStatement so the kernel's
// auto-close-on-drain fires the server CloseStatement once the
// stream is exhausted (after all lazy CloudFetch link fetches).
let batch = run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))?;
// Inline results and already-downloaded CloudFetch chunks are in
// memory: take them without a GIL hand-off when reading one is only a
// buffer hand-off. Both paths drive the ExecutedStatement, so
// auto-close-on-drain still fires CloseStatement once exhausted.
let ready = if !inner.exec.try_next_batch_is_cheap() {
None
} else {
let _context = runtime.enter();
match inner.exec.try_next_batch().map_err(|e| to_py_err(py, e))? {
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
TryNextBatch::Ready(ResultBatch::Arrow(rb)) => Some(Some(rb.clone())),
// Same error as the blocking path; falling back would skip it.
TryNextBatch::Ready(_) => {
return Err(to_py_err(
py,
KError::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"),
))
}
TryNextBatch::End => Some(None),
_ => None,
}
};
let batch = match ready {
Some(batch) => batch,
None => run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))?,
};
match batch {
Some(b) => Ok(Some(b.to_pyarrow(py)?)),
None => {
Expand Down Expand Up @@ -397,7 +419,13 @@ impl ExecutedStatement {
return Ok(());
};
let runtime = inner.runtime.clone();
let res = run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec));
let res = if inner.exhausted {
// Drain already fired CloseStatement, so this does no I/O.
crate::gil::run_ready_first(py, &runtime, KExecutedStatement::close(&mut inner.exec))
.map_err(|e| to_py_err(py, e))
} else {
run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec))
};
// Drop the kernel handle regardless of close() outcome — the
// kernel's Drop impl runs fire-and-forget cleanup if close()
// failed mid-flight.
Expand Down
Loading
Loading