From dc4759b6c3e1e9122d03e8a1c725bbb60f5c006f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 18:50:26 +0000 Subject: [PATCH 1/5] perf(python): skip GIL hand-offs that wait for nothing With many Python threads, every py.detach costs a GIL release and a contended re-acquire. fetch_next_batch now takes batches that are already in memory through try_next_batch with the GIL held, close() of a drained statement completes without detaching, and execute() on a non-main thread runs in one GIL-released slice instead of waking every 100 ms for signal checks only the main thread can act on. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 6 ++ pyo3/src/gil.rs | 102 +++++++++++++++++++++ pyo3/src/lib.rs | 1 + pyo3/src/macros.rs | 10 +++ pyo3/src/statement.rs | 40 +++++++-- pyo3/tests/test_sync_fetch.py | 161 ++++++++++++++++++++++++++++++++++ 6 files changed, 313 insertions(+), 7 deletions(-) create mode 100644 pyo3/src/gil.rs create mode 100644 pyo3/tests/test_sync_fetch.py diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..713efb4c 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -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 diff --git a/pyo3/src/gil.rs b/pyo3/src/gil.rs new file mode 100644 index 00000000..ea695642 --- /dev/null +++ b/pyo3/src/gil.rs @@ -0,0 +1,102 @@ +// 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> = PyOnceLock::new(); + +/// Whether the calling thread is Python's main thread, the only one that +/// runs signal handlers. Errs towards `true` so a lookup failure keeps +/// signal checks on. +pub(crate) fn on_main_thread(py: Python<'_>) -> bool { + let check = || -> PyResult { + let threading = THREADING + .get_or_try_init(py, || py.import("threading").map(Bound::unbind))? + .bind(py); + let current = threading.call_method0("get_ident")?; + let main = threading.call_method0("main_thread")?.getattr("ident")?; + current.eq(main) + }; + 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(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)); + } +} diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index f42ffa85..0debe4fa 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -36,6 +36,7 @@ mod auth; mod errors; mod executed_async; mod fetch; +mod gil; mod logging; mod metadata; mod params; diff --git a/pyo3/src/macros.rs b/pyo3/src/macros.rs index 9eb9b740..9dae2075 100644 --- a/pyo3/src/macros.rs +++ b/pyo3/src/macros.rs @@ -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` (the future's /// `Ok` value), mapping kernel `Error`s via `to_py_err` and surfacing @@ -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 { diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 7f2dc3e8..a0df756a 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -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; @@ -349,10 +349,30 @@ 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. Both paths drive the + // ExecutedStatement, so auto-close-on-drain still fires the server + // CloseStatement once the stream is exhausted. + let ready = { + let _context = runtime.enter(); + match inner.exec.try_next_batch().map_err(|e| to_py_err(py, e))? { + 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 => { @@ -397,7 +417,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. diff --git a/pyo3/tests/test_sync_fetch.py b/pyo3/tests/test_sync_fetch.py new file mode 100644 index 00000000..859fe040 --- /dev/null +++ b/pyo3/tests/test_sync_fetch.py @@ -0,0 +1,161 @@ +# 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. + +"""Sync execute / fetch / close against a local SEA stand-in (no network).""" + +from __future__ import annotations + +import base64 +import contextlib +import json +import os +import signal +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import databricks_sql_kernel as k +import pyarrow as pa +import pytest + +SESSIONS = "/api/2.0/sql/warehouses/test-wh/sessions" + + +def _attachment(): + batch = pa.record_batch([pa.array([1, 2], type=pa.int64())], names=["n"]) + buffer = pa.BufferOutputStream() + with pa.ipc.new_stream(buffer, batch.schema) as writer: + writer.write_batch(batch) + return base64.b64encode(buffer.getvalue()).decode() + + +@contextlib.contextmanager +def _server(execute_delay_s=0.0): + """Yields ``(port, requests)``; ``requests`` collects ``(method, path)``.""" + requests = [] + attachment = _attachment() + + class Handler(BaseHTTPRequestHandler): + def respond(self, body, headers=()): + requests.append((self.command, self.path)) + self.rfile.read(int(self.headers.get("Content-Length", 0))) + payload = json.dumps(body).encode() + self.send_response(200) + self.send_header("Content-Length", str(len(payload))) + for name, value in headers: + self.send_header(name, value) + self.end_headers() + self.wfile.write(payload) + + def do_POST(self): + if self.path == SESSIONS: + self.respond({"session_id": "test-session"}, [("x-databricks-rt-session", "true")]) + return + if self.path.endswith("/statements"): + time.sleep(execute_delay_s) + self.respond( + { + "statement_id": "test-statement", + "status": {"state": "SUCCEEDED"}, + "manifest": { + "format": "ARROW_STREAM", + "schema": { + "column_count": 1, + "columns": [ + {"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0} + ], + }, + "total_chunk_count": 1, + "total_row_count": 2, + }, + "result": {"chunk_index": 0, "row_offset": 0, "row_count": 2, "attachment": attachment}, + } + ) + + def do_DELETE(self): + self.respond({}) + + def log_message(self, *_args): + pass + + with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: + server.daemon_threads = True + threading.Thread(target=server.serve_forever, daemon=True).start() + try: + yield server.server_port, requests + finally: + server.shutdown() + + +def _session(port): + return k.Session( + host=f"http://127.0.0.1:{port}", + http_path="/sql/1.0/warehouses/test-wh", + access_token="test-token", + telemetry_enabled=False, + ) + + +def _statement_deletes(requests): + return [p for m, p in requests if m == "DELETE" and "/statements/" in p] + + +def test_worker_thread_fetch_closes_statement_once(): + with _server() as (port, requests): + session = _session(port) + result = {} + + def run(): + stmt = session.statement() + stmt.set_sql("SELECT 1") + executed = stmt.execute() + first = executed.fetch_next_batch() + result["rows"] = first.column(0).to_pylist() + result["end"] = executed.fetch_next_batch() + result["again"] = executed.fetch_next_batch() + executed.close() + stmt.close() + + worker = threading.Thread(target=run) + worker.start() + worker.join(10) + assert not worker.is_alive() + assert result == {"rows": [1, 2], "end": None, "again": None} + # Draining fires CloseStatement; the explicit close sends no second one. + deadline = time.monotonic() + 5 + while not _statement_deletes(requests) and time.monotonic() < deadline: + time.sleep(0.02) + time.sleep(0.1) + assert len(_statement_deletes(requests)) == 1 + session.close() + + +@pytest.mark.skipif(not hasattr(signal, "SIGINT") or os.name == "nt", reason="POSIX signals") +def test_main_thread_execute_stays_interruptible(): + assert threading.current_thread() is threading.main_thread() + with _server(execute_delay_s=5.0) as (port, _): + session = _session(port) + stmt = session.statement() + stmt.set_sql("SELECT 1") + timer = threading.Timer(0.3, os.kill, (os.getpid(), signal.SIGINT)) + started = time.monotonic() + timer.start() + try: + with pytest.raises(KeyboardInterrupt): + stmt.execute() + finally: + timer.cancel() + assert time.monotonic() - started < 2.0 + stmt.close() + session.close() From f53c150b1980af295ce8977ab3e7649f57845791 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:07:11 +0000 Subject: [PATCH 2/5] perf(python): release the GIL for batches that need column rewrites try_next_batch runs the post-processor's per-batch column rewrites (geospatial, interval, JSON, untyped NULL) on the calling thread, so fetch_next_batch now takes its GIL-held fast path only when the stream has no rewrites. Adds rewrites_batches() on ExecutedStatement and ResultStream, and tests for the CloudFetch Pending fallback and the rewritten-column path. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 3 ++ pyo3/src/statement.rs | 10 +++--- pyo3/tests/test_sync_fetch.py | 56 ++++++++++++++++++++++---------- src/reader/mod.rs | 6 ++++ src/reader/post_processor/mod.rs | 11 +++++++ src/result_stream.rs | 9 +++++ src/statement/executed.rs | 5 +++ 7 files changed, 79 insertions(+), 21 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 6aa75289..2317a699 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,6 +13,9 @@ 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::rewrites_batches()` and `ResultStream::rewrites_batches()` + report whether reading a ready batch still rewrites column values on the + calling thread, so bindings can tell when `try_next_batch` is not cheap. ### Changed diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index a0df756a..1c2d97ec 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -350,10 +350,12 @@ impl ExecutedStatement { } let runtime = inner.runtime.clone(); // Inline results and already-downloaded CloudFetch chunks are in - // memory: take them without a GIL hand-off. Both paths drive the - // ExecutedStatement, so auto-close-on-drain still fires the server - // CloseStatement once the stream is exhausted. - let ready = { + // memory: take them without a GIL hand-off, unless reading one still + // rewrites column values. Both paths drive the ExecutedStatement, so + // auto-close-on-drain still fires CloseStatement once exhausted. + let ready = if inner.exec.rewrites_batches() { + None + } else { let _context = runtime.enter(); match inner.exec.try_next_batch().map_err(|e| to_py_err(py, e))? { TryNextBatch::Ready(ResultBatch::Arrow(rb)) => Some(Some(rb.clone())), diff --git a/pyo3/tests/test_sync_fetch.py b/pyo3/tests/test_sync_fetch.py index 859fe040..6617406a 100644 --- a/pyo3/tests/test_sync_fetch.py +++ b/pyo3/tests/test_sync_fetch.py @@ -32,25 +32,27 @@ SESSIONS = "/api/2.0/sql/warehouses/test-wh/sessions" -def _attachment(): - batch = pa.record_batch([pa.array([1, 2], type=pa.int64())], names=["n"]) +def _ipc(column): + batch = pa.record_batch([column], names=["n"]) buffer = pa.BufferOutputStream() with pa.ipc.new_stream(buffer, batch.schema) as writer: writer.write_batch(batch) - return base64.b64encode(buffer.getvalue()).decode() + return buffer.getvalue().to_pybytes() @contextlib.contextmanager -def _server(execute_delay_s=0.0): - """Yields ``(port, requests)``; ``requests`` collects ``(method, path)``.""" +def _server(execute_delay_s=0.0, column=None, type_name="BIGINT", chunk_delay_s=None): + """Yields ``(port, requests)``; ``requests`` collects ``(method, path)``. + With ``chunk_delay_s`` the result is an external link served after that delay.""" requests = [] - attachment = _attachment() + ipc = _ipc(column if column is not None else pa.array([1, 2], type=pa.int64())) + ports = [] class Handler(BaseHTTPRequestHandler): def respond(self, body, headers=()): requests.append((self.command, self.path)) self.rfile.read(int(self.headers.get("Content-Length", 0))) - payload = json.dumps(body).encode() + payload = body if isinstance(body, bytes) else json.dumps(body).encode() self.send_response(200) self.send_header("Content-Length", str(len(payload))) for name, value in headers: @@ -64,25 +66,31 @@ def do_POST(self): return if self.path.endswith("/statements"): time.sleep(execute_delay_s) + chunk = {"chunk_index": 0, "row_offset": 0, "row_count": 2, "byte_count": len(ipc)} + if chunk_delay_s is None: + result = dict(chunk, attachment=base64.b64encode(ipc).decode()) + else: + link = f"http://127.0.0.1:{ports[0]}/chunk0" + result = {"external_links": [dict(chunk, external_link=link, expiration="2099-01-01T00:00:00.000Z")]} + column_info = {"name": "n", "type_name": type_name, "type_text": type_name, "position": 0} self.respond( { "statement_id": "test-statement", "status": {"state": "SUCCEEDED"}, "manifest": { "format": "ARROW_STREAM", - "schema": { - "column_count": 1, - "columns": [ - {"name": "n", "type_name": "BIGINT", "type_text": "BIGINT", "position": 0} - ], - }, + "schema": {"column_count": 1, "columns": [column_info]}, "total_chunk_count": 1, "total_row_count": 2, }, - "result": {"chunk_index": 0, "row_offset": 0, "row_count": 2, "attachment": attachment}, + "result": result, } ) + def do_GET(self): + time.sleep(chunk_delay_s or 0) + self.respond(ipc) + def do_DELETE(self): self.respond({}) @@ -91,6 +99,7 @@ def log_message(self, *_args): with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server: server.daemon_threads = True + ports.append(server.server_port) threading.Thread(target=server.serve_forever, daemon=True).start() try: yield server.server_port, requests @@ -111,8 +120,19 @@ def _statement_deletes(requests): return [p for m, p in requests if m == "DELETE" and "/statements/" in p] -def test_worker_thread_fetch_closes_statement_once(): - with _server() as (port, requests): +@pytest.mark.parametrize( + "server_kwargs,rows", + [ + # Inline batch already in memory: read without releasing the GIL. + pytest.param({}, [1, 2], id="inline"), + # Chunk still downloading on the first read: falls back to the blocking path. + pytest.param({"chunk_delay_s": 0.3}, [1, 2], id="cloudfetch-pending"), + # Untyped NULL is rewritten to Utf8 per batch: read on the blocking path. + pytest.param({"column": pa.nulls(2), "type_name": "STRING"}, [None, None], id="rewritten"), + ], +) +def test_worker_thread_fetch_closes_statement_once(server_kwargs, rows): + with _server(**server_kwargs) as (port, requests): session = _session(port) result = {} @@ -131,7 +151,9 @@ def run(): worker.start() worker.join(10) assert not worker.is_alive() - assert result == {"rows": [1, 2], "end": None, "again": None} + assert result == {"rows": rows, "end": None, "again": None} + if "chunk_delay_s" in server_kwargs: + assert ("GET", "/chunk0") in requests # Draining fires CloseStatement; the explicit close sends no second one. deadline = time.monotonic() + 5 while not _statement_deletes(requests) and time.monotonic() < deadline: diff --git a/src/reader/mod.rs b/src/reader/mod.rs index dd8023c3..a0eb7fd2 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -716,6 +716,12 @@ pub trait ResultReader: Send + Sync { Err(Error::invalid_state().message("reader does not support non-blocking batch reads")) } + /// Whether producing a batch rewrites column values on the reading + /// thread (per-row work), so a ready `try_next_batch` is not cheap. + fn rewrites_batches(&self) -> bool { + false + } + /// Optional reader-level metrics accumulated below `ResultStream`. /// /// CloudFetch overrides this to surface chunk download metrics into diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index a57b5d5d..4130f9c7 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -92,6 +92,8 @@ pub(crate) struct ResultPostProcessor { inner: Box, schema: SchemaRef, transform: Option, + /// `transform` rewrites column values (per-row work), not just the schema. + rewrites: bool, } type BatchTransform = Box Result + Send + Sync>; @@ -278,6 +280,7 @@ impl ResultPostProcessor { inner, schema: output_schema, transform, + rewrites: has_rewrites, }) } } @@ -300,6 +303,10 @@ impl ResultReader for ResultPostProcessor { next.map_ready(|batch| self.process_batch(batch)) } + fn rewrites_batches(&self) -> bool { + self.rewrites + } + fn metrics(&self) -> Option { self.inner.metrics() } @@ -547,6 +554,7 @@ mod tests { .unwrap(); // No transform should have been installed. assert!(pp.transform.is_none()); + assert!(!pp.rewrites_batches()); let out = pp.next_batch().await.unwrap().unwrap(); assert_eq!(out.num_rows(), 1); assert_eq!(out.schema().field(0).metadata().len(), 0); @@ -568,6 +576,8 @@ mod tests { .await .unwrap(); assert!(pp.transform.is_some()); + // Re-projecting onto the augmented schema reuses the arrays. + assert!(!pp.rewrites_batches()); let out = pp.next_batch().await.unwrap().unwrap(); assert_eq!( @@ -667,6 +677,7 @@ mod tests { let mut pp = ResultPostProcessor::new(inner, None, PostProcessOptions::default()) .await .unwrap(); + assert!(pp.rewrites_batches()); // Both the advertised schema and the yielded batch report Utf8 for // the untyped-NULL column, identical to the CAST(NULL AS STRING) diff --git a/src/result_stream.rs b/src/result_stream.rs index 7a2a8495..f09240e2 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -748,6 +748,15 @@ impl ResultStream { } } + /// Whether a ready [`try_next_batch`](Self::try_next_batch) still rewrites + /// column values on the calling thread (e.g. geospatial, interval or JSON + /// stringification), so it costs per-row CPU rather than a buffer hand-off. + pub fn rewrites_batches(&self) -> bool { + self.reader + .as_ref() + .is_some_and(|reader| reader.rewrites_batches()) + } + /// Return the next batch if it is already available without waiting for /// network or background-prefetch progress. pub fn try_next_batch(&mut self) -> Result> { diff --git a/src/statement/executed.rs b/src/statement/executed.rs index 025db78e..a5b180dd 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -151,6 +151,11 @@ impl ExecutedStatement { Ok(None) } + /// See [`ResultStream::rewrites_batches`]. + pub fn rewrites_batches(&self) -> bool { + self.result_stream.rewrites_batches() + } + /// Non-blocking counterpart to [`Self::next_batch`]. It preserves the same /// drain-driven auto-close behavior when end-of-stream is observed. pub fn try_next_batch(&mut self) -> Result> { From a0e8ca9abf072c3043673df856ae5e5bb57973f6 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 20:44:42 +0000 Subject: [PATCH 3/5] perf(python): take the GIL-held fast path only for readers that opt in Replace rewrites_batches() with try_next_batch_is_cheap(), a capability that defaults to false. The inline, CloudFetch, inline-streaming, in-memory and empty readers opt in, and the post-processor reports it only when it has no column rewrites. A reader that keeps the trait's default try_next_batch therefore stays on the blocking next_batch path instead of surfacing "reader does not support non-blocking batch reads" from fetch_next_batch. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- NEXT_CHANGELOG.md | 8 +++++--- pyo3/src/statement.rs | 6 +++--- src/reader/mod.rs | 31 ++++++++++++++++++++++++++++--- src/reader/post_processor/mod.rs | 23 ++++++++++++++++++----- src/reader/test_utils.rs | 4 ++++ src/result_stream.rs | 11 ++++++----- src/statement/executed.rs | 6 +++--- 7 files changed, 67 insertions(+), 22 deletions(-) diff --git a/NEXT_CHANGELOG.md b/NEXT_CHANGELOG.md index 2317a699..017e11a8 100644 --- a/NEXT_CHANGELOG.md +++ b/NEXT_CHANGELOG.md @@ -13,9 +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::rewrites_batches()` and `ResultStream::rewrites_batches()` - report whether reading a ready batch still rewrites column values on the - calling thread, so bindings can tell when `try_next_batch` is not cheap. +- `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 diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 1c2d97ec..52748f2c 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -350,10 +350,10 @@ impl ExecutedStatement { } let runtime = inner.runtime.clone(); // Inline results and already-downloaded CloudFetch chunks are in - // memory: take them without a GIL hand-off, unless reading one still - // rewrites column values. Both paths drive the ExecutedStatement, so + // 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.rewrites_batches() { + let ready = if !inner.exec.try_next_batch_is_cheap() { None } else { let _context = runtime.enter(); diff --git a/src/reader/mod.rs b/src/reader/mod.rs index a0eb7fd2..aa047db7 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -716,9 +716,11 @@ pub trait ResultReader: Send + Sync { Err(Error::invalid_state().message("reader does not support non-blocking batch reads")) } - /// Whether producing a batch rewrites column values on the reading - /// thread (per-row work), so a ready `try_next_batch` is not cheap. - fn rewrites_batches(&self) -> bool { + /// Whether `try_next_batch` is supported and a ready batch is a buffer + /// hand-off, with no per-row work on the calling thread. Defaults to + /// `false`, so callers keep using `next_batch` for readers that don't + /// opt in. + fn try_next_batch_is_cheap(&self) -> bool { false } @@ -797,6 +799,11 @@ impl ResultReader for CloudFetchResultReader { self.provider.try_next_batch() } + // Download tasks decode chunks; a ready read only takes a buffered batch. + fn try_next_batch_is_cheap(&self) -> bool { + true + } + fn metrics(&self) -> Option { self.provider.metrics() } @@ -833,6 +840,11 @@ impl ResultReader for InlineArrowReader { fn try_next_batch(&mut self) -> Result { Ok(TryNextBatch::from_option(self.provider.next_batch()?)) } + + // The attachment is decoded when the provider is built. + fn try_next_batch_is_cheap(&self) -> bool { + true + } } /// Reader for multi-chunk inline-Arrow streaming. @@ -869,6 +881,11 @@ impl ResultReader for InlineStreamingReader { fn try_next_batch(&mut self) -> Result { self.provider.try_next_batch() } + + // The prefetch task decodes chunks; a ready read only takes one. + fn try_next_batch_is_cheap(&self) -> bool { + true + } } /// In-memory result reader. @@ -908,6 +925,10 @@ impl ResultReader for InMemoryReader { fn try_next_batch(&mut self) -> Result { Ok(TryNextBatch::from_option(self.batches.next())) } + + fn try_next_batch_is_cheap(&self) -> bool { + true + } } /// Empty reader for queries with no results. @@ -938,6 +959,10 @@ impl ResultReader for EmptyReader { fn try_next_batch(&mut self) -> Result { Ok(TryNextBatch::End) } + + fn try_next_batch_is_cheap(&self) -> bool { + true + } } /// Arrow field metadata keys for Databricks column information. diff --git a/src/reader/post_processor/mod.rs b/src/reader/post_processor/mod.rs index 4130f9c7..bc0aed7d 100644 --- a/src/reader/post_processor/mod.rs +++ b/src/reader/post_processor/mod.rs @@ -303,8 +303,8 @@ impl ResultReader for ResultPostProcessor { next.map_ready(|batch| self.process_batch(batch)) } - fn rewrites_batches(&self) -> bool { - self.rewrites + fn try_next_batch_is_cheap(&self) -> bool { + !self.rewrites && self.inner.try_next_batch_is_cheap() } fn metrics(&self) -> Option { @@ -554,12 +554,24 @@ mod tests { .unwrap(); // No transform should have been installed. assert!(pp.transform.is_none()); - assert!(!pp.rewrites_batches()); + assert!(pp.try_next_batch_is_cheap()); let out = pp.next_batch().await.unwrap().unwrap(); assert_eq!(out.num_rows(), 1); assert_eq!(out.schema().field(0).metadata().len(), 0); } + #[tokio::test] + async fn cheap_try_next_batch_requires_the_inner_reader_to_opt_in() { + let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)])); + let inner: Box = + Box::new(crate::reader::test_utils::ErrorReader { schema }); + let pp = ResultPostProcessor::new(inner, None, PostProcessOptions::default()) + .await + .unwrap(); + assert!(pp.transform.is_none()); + assert!(!pp.try_next_batch_is_cheap()); + } + #[tokio::test] async fn manifest_only_attaches_metadata_to_batches() { let schema = Arc::new(Schema::new(vec![Field::new("name", DataType::Utf8, true)])); @@ -577,7 +589,7 @@ mod tests { .unwrap(); assert!(pp.transform.is_some()); // Re-projecting onto the augmented schema reuses the arrays. - assert!(!pp.rewrites_batches()); + assert!(pp.try_next_batch_is_cheap()); let out = pp.next_batch().await.unwrap().unwrap(); assert_eq!( @@ -677,7 +689,8 @@ mod tests { let mut pp = ResultPostProcessor::new(inner, None, PostProcessOptions::default()) .await .unwrap(); - assert!(pp.rewrites_batches()); + // Rewriting the column is per-row work on the reading thread. + assert!(!pp.try_next_batch_is_cheap()); // Both the advertised schema and the yielded batch report Utf8 for // the untyped-NULL column, identical to the CAST(NULL AS STRING) diff --git a/src/reader/test_utils.rs b/src/reader/test_utils.rs index 2b3dbb94..8454a1d9 100644 --- a/src/reader/test_utils.rs +++ b/src/reader/test_utils.rs @@ -69,6 +69,10 @@ impl ResultReader for MockReader { crate::reader::TryNextBatch::Ready(batch) }) } + + fn try_next_batch_is_cheap(&self) -> bool { + true + } } /// A reader that returns an error on `next_batch()`. diff --git a/src/result_stream.rs b/src/result_stream.rs index f09240e2..1addadf0 100644 --- a/src/result_stream.rs +++ b/src/result_stream.rs @@ -748,13 +748,14 @@ impl ResultStream { } } - /// Whether a ready [`try_next_batch`](Self::try_next_batch) still rewrites - /// column values on the calling thread (e.g. geospatial, interval or JSON - /// stringification), so it costs per-row CPU rather than a buffer hand-off. - pub fn rewrites_batches(&self) -> bool { + /// Whether [`try_next_batch`](Self::try_next_batch) is supported and a + /// ready batch is a buffer hand-off: no per-row work (geospatial, + /// interval or JSON stringification) on the calling thread. When `false`, + /// use [`next_batch`](Self::next_batch). + pub fn try_next_batch_is_cheap(&self) -> bool { self.reader .as_ref() - .is_some_and(|reader| reader.rewrites_batches()) + .is_some_and(|reader| reader.try_next_batch_is_cheap()) } /// Return the next batch if it is already available without waiting for diff --git a/src/statement/executed.rs b/src/statement/executed.rs index a5b180dd..c2051aa1 100644 --- a/src/statement/executed.rs +++ b/src/statement/executed.rs @@ -151,9 +151,9 @@ impl ExecutedStatement { Ok(None) } - /// See [`ResultStream::rewrites_batches`]. - pub fn rewrites_batches(&self) -> bool { - self.result_stream.rewrites_batches() + /// See [`ResultStream::try_next_batch_is_cheap`]. + pub fn try_next_batch_is_cheap(&self) -> bool { + self.result_stream.try_next_batch_is_cheap() } /// Non-blocking counterpart to [`Self::next_batch`]. It preserves the same From 07db0b1081784f3181fba643ead7315056ea7313 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 21:04:27 +0000 Subject: [PATCH 4/5] test(reader): pin which readers report a cheap try_next_batch Assert try_next_batch_is_cheap() for the readers the factory builds (inline, also through ResultStream, and opting out for a rewritten column) and for the CloudFetch and inline-streaming readers, so the GIL-held fetch path can't silently stop being taken. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- src/reader/cloudfetch/streaming_provider.rs | 16 ++++++ src/reader/inline/streaming.rs | 24 ++++++++ src/reader/mod.rs | 64 +++++++++++++++++++++ 3 files changed, 104 insertions(+) diff --git a/src/reader/cloudfetch/streaming_provider.rs b/src/reader/cloudfetch/streaming_provider.rs index 5fbab8d7..9a5da1c6 100644 --- a/src/reader/cloudfetch/streaming_provider.rs +++ b/src/reader/cloudfetch/streaming_provider.rs @@ -2508,6 +2508,22 @@ mod tests { )) } + /// Download tasks decode chunks, so the reader over this provider reports + /// a ready `try_next_batch` as a cheap buffer hand-off. + #[tokio::test] + async fn cloudfetch_reader_try_next_batch_is_cheap() { + use crate::reader::ResultReader; + + let fetcher: Arc = Arc::new(MockLinkFetcher::new(1)); + let provider = StreamingCloudFetchProvider::for_test_with_chunks( + fetcher, + unused_downloader(), + Arc::new(DashMap::new()), + true, + ); + assert!(crate::reader::CloudFetchResultReader::new(provider).try_next_batch_is_cheap()); + } + /// `try_next_batch` must return `Pending` (without blocking) while the /// head chunk is not yet `Downloaded`, then `Ready` once it flips, and /// finally `End` after the last chunk is consumed. This exercises the diff --git a/src/reader/inline/streaming.rs b/src/reader/inline/streaming.rs index 2f89fb1a..e4ae7e6f 100644 --- a/src/reader/inline/streaming.rs +++ b/src/reader/inline/streaming.rs @@ -916,6 +916,30 @@ mod tests { assert_eq!(schema.field(1).name(), "colB"); } + #[tokio::test] + async fn streaming_reader_try_next_batch_is_cheap() { + use crate::reader::ResultReader; + + let (initial_bytes, c0, c1, c2) = three_chunk_fixture(); + let source: Arc = MockSource::new(vec![c1, c2]); + let provider = InlineStreamingProvider::new( + source, + "stmt-1", + &initial_bytes, + c0.chunk_index, + c0.row_offset, + c0.row_count, + c0.next_chunk_index, + CompressionCodec::None, + 1, + None, + tokio::runtime::Handle::current(), + ) + .unwrap(); + // The prefetch task decodes chunks, so a ready read only takes one. + assert!(crate::reader::InlineStreamingReader::new(provider).try_next_batch_is_cheap()); + } + #[tokio::test] async fn prefetch_task_exits_when_consumer_drops() { // P0 #2 regression guard. The prefetch task must not keep diff --git a/src/reader/mod.rs b/src/reader/mod.rs index aa047db7..d1a68a60 100644 --- a/src/reader/mod.rs +++ b/src/reader/mod.rs @@ -2260,6 +2260,70 @@ mod tests { } } + fn inline_response(batch: &RecordBatch) -> ExecuteResponse { + let mut bytes = Vec::new(); + let mut writer = StreamWriter::try_new(&mut bytes, &batch.schema()).unwrap(); + writer.write(batch).unwrap(); + writer.finish().unwrap(); + drop(writer); + ExecuteResponse { + statement_id: "stmt-1".to_string(), + status: ok_status(), + manifest: Some(minimal_manifest(Some(1))), + result: Some(ExecuteResultData { + next_chunk_internal_link: None, + external_links: None, + inline_arrow_data: Some(bytes), + inline_chunk_index: Some(0), + inline_row_offset: Some(0), + inline_row_count: Some(batch.num_rows() as i64), + inline_next_chunk_index: None, + }), + } + } + + /// Bindings read ready batches without giving up a host lock only when + /// this holds, so pin it for the readers the factory builds, including + /// through `ResultStream`. + #[tokio::test] + async fn factory_readers_report_cheap_try_next_batch() { + let factory = factory_for_control_flow_test(); + let ints = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("n", DataType::Int64, false)])), + vec![Arc::new(arrow_array::Int64Array::from(vec![1, 2]))], + ) + .unwrap(); + let reader = factory + .create_reader( + "stmt-1", + &inline_response(&ints), + SessionAttribution::Current, + ) + .await + .unwrap(); + assert!(reader.try_next_batch_is_cheap()); + let stream = crate::result_stream::ResultStream::from_reader(reader) + .await + .unwrap(); + assert!(stream.try_next_batch_is_cheap()); + + // An untyped NULL column is rewritten per batch on the reading thread. + let nulls = RecordBatch::try_new( + Arc::new(Schema::new(vec![Field::new("n", DataType::Null, true)])), + vec![Arc::new(arrow_array::NullArray::new(2))], + ) + .unwrap(); + let reader = factory + .create_reader( + "stmt-1", + &inline_response(&nulls), + SessionAttribution::Current, + ) + .await + .unwrap(); + assert!(!reader.try_next_batch_is_cheap()); + } + /// B-3: initial execute response must be strict about /// `row_count` when `next_chunk_index.is_some()`. Defaulting /// to 0 would silently corrupt the next-fetch row_offset. From a9d5ab99dbd01fc2a20350e4f94760a53682bd68 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 13 Nov 2026 21:53:07 +0000 Subject: [PATCH 5/5] fix(python): recognise the main thread by either thread id Greenlet libraries (gevent, eventlet) patch threading.get_ident, so a greenlet on the main OS thread looked like a worker and execute() lost its Ctrl-C checks. Also accept a native_id match; ident alone stays the check after fork, which threading refreshes for ident but not for native_id. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/gil.rs | 21 ++++++++++++++++----- pyo3/tests/test_sync_fetch.py | 10 +++++++++- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/pyo3/src/gil.rs b/pyo3/src/gil.rs index ea695642..27ca9daa 100644 --- a/pyo3/src/gil.rs +++ b/pyo3/src/gil.rs @@ -29,16 +29,27 @@ use tokio::runtime::Runtime; static THREADING: PyOnceLock> = PyOnceLock::new(); /// Whether the calling thread is Python's main thread, the only one that -/// runs signal handlers. Errs towards `true` so a lookup failure keeps -/// signal checks on. +/// 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 { let threading = THREADING .get_or_try_init(py, || py.import("threading").map(Bound::unbind))? .bind(py); - let current = threading.call_method0("get_ident")?; - let main = threading.call_method0("main_thread")?.getattr("ident")?; - current.eq(main) + 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) } diff --git a/pyo3/tests/test_sync_fetch.py b/pyo3/tests/test_sync_fetch.py index 6617406a..8db7914f 100644 --- a/pyo3/tests/test_sync_fetch.py +++ b/pyo3/tests/test_sync_fetch.py @@ -23,6 +23,7 @@ import signal import threading import time +import types from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import databricks_sql_kernel as k @@ -164,8 +165,15 @@ def run(): @pytest.mark.skipif(not hasattr(signal, "SIGINT") or os.name == "nt", reason="POSIX signals") -def test_main_thread_execute_stays_interruptible(): +@pytest.mark.parametrize("greenlet_ident", [False, True], ids=["plain", "greenlet-ident"]) +def test_main_thread_execute_stays_interruptible(monkeypatch, greenlet_ident): assert threading.current_thread() is threading.main_thread() + if greenlet_ident: + # Under gevent/eventlet, get_ident() is a greenlet id that matches no + # thread's ident; only the OS-level native id still identifies main. + main = threading.main_thread() + fake = types.SimpleNamespace(ident=object(), native_id=main.native_id) + monkeypatch.setattr(threading, "main_thread", lambda: fake) with _server(execute_delay_s=5.0) as (port, _): session = _session(port) stmt = session.statement()