Skip to content

Commit 8877579

Browse files
perf(pyo3): avoid runtime entry for buffered fetch and drained close (#477)
Python result fetching enters Tokio and releases/reacquires the GIL even when a batch is already buffered. **Before:** Every `fetch_next_batch()` call enters the runtime, including buffered data and EOF. Closing a drained executed handle enters it again after exhaustion has already finalized telemetry and scheduled cleanup. **After:** Both Python result handles probe for an available batch first. Buffered data and EOF return directly. Pending reads retain the wait with the GIL released; drained close retains runtime release and skips the completed kernel close operation. CloudFetch uses nonblocking buffer, shard and error-lock attempts, returning `Pending` on contention. The waiting path skips empty chunks, and both paths deliver earlier chunks before a later link-fetch error. Shared guards are released before logging, including for uncached loggers that can acquire the GIL before filtering. Batch order, accounting, terminal errors and statement DELETE cleanup are preserved. Unsupported formats retain `InvalidArgument` across Python fetch/drain paths, matching Node. One buffered batch, EOF and drained close avoid three runtime entries and GIL release/reacquire pairs while the session remains open and provider locks are available. Isolated end-to-end throughput gain is unmeasured. Buffered batches requiring column rewrites perform that synchronous work with the GIL held. **Validation** - Kernel: 1,323 Rust tests passed; 64 live/optional cases ignored. PyO3: 31 Rust tests passed. Formatting and clippy pass with warnings denied. - Rebuilt CPython 3.12 extension: 21 offline Python tests passed; 37 live cases skipped. Coverage includes both result handles, delayed inline/CloudFetch continuation, empty chunks, errors, EOF cleanup before handle closure, partial cleanup and final runtime release. - Bounded lock-contention tests verify `Pending`, ordered recovery and accounting. Binding tests verify runtime bypass and that waiting releases the GIL; restoring unconditional runtime entry in either real handle fails its guard. - Fourteen local connector/logging checks passed, including mixed row/Arrow reads, sync/async execution, standard/realtime routes and cold DEBUG logging. No new warehouse workload was run. The native binding and Python tests share one local HTTP fixture. --------- Signed-off-by: Aakash Saravanan <aakash.saravanan@databricks.com>
1 parent 223ef56 commit 8877579

8 files changed

Lines changed: 694 additions & 181 deletions

File tree

‎pyo3/src/fetch.rs‎

Lines changed: 147 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,58 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
//! Internal helpers for pulling batches out of a `ResultStream`.
15+
//! Shared batch ownership and GIL handoff for both Python result handles.
1616
//!
17-
//! Shared by `ExecutedStatement` (drives the kernel `ExecutedStatement`'s
18-
//! borrowed result stream) and `ResultStream` (owns its kernel
19-
//! `ResultStream` directly). Both call `next_batch` on the kernel
20-
//! stream and clone the Arrow `RecordBatch` out from under the
21-
//! borrow so the result can cross the GIL boundary as an owned value.
17+
//! A nonblocking probe holds the GIL through kernel post-processing, so large
18+
//! batches requiring column rewrites can delay other Python threads.
19+
//!
20+
//! Contended CloudFetch provider-state locks yield `Pending`, allowing the
21+
//! fallback to wait with the GIL released.
2222
2323
use arrow_array::RecordBatch;
2424
use arrow_pyarrow::ToPyArrow;
2525
use arrow_schema::Schema;
26-
use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream};
26+
use databricks_sql_kernel::reader::TryNextBatch as BatchRead;
27+
use databricks_sql_kernel::{
28+
Error, ExecutedStatement, Result, ResultBatch, ResultStream, TryNextBatch,
29+
};
2730
use pyo3::prelude::*;
2831
use std::sync::Arc;
2932
use tokio::runtime::Runtime;
3033

34+
fn own_arrow_batch(batch: &ResultBatch) -> Result<RecordBatch> {
35+
match batch {
36+
ResultBatch::Arrow(batch) => Ok(batch.clone()),
37+
_ => {
38+
Err(Error::invalid_argument()
39+
.message("kernel returned a non-Arrow ResultBatch variant"))
40+
}
41+
}
42+
}
43+
44+
pub(crate) fn own_batch(read: Result<TryNextBatch<'_>>) -> Result<BatchRead> {
45+
match read? {
46+
TryNextBatch::Ready(batch) => own_arrow_batch(batch).map(BatchRead::Ready),
47+
TryNextBatch::Pending => Ok(BatchRead::Pending),
48+
TryNextBatch::End => Ok(BatchRead::End),
49+
_ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")),
50+
}
51+
}
52+
53+
pub(crate) fn read_batch(
54+
py: Python<'_>,
55+
read: Result<BatchRead>,
56+
pending: impl FnOnce() -> Result<Option<RecordBatch>> + pyo3::marker::Ungil,
57+
) -> PyResult<Option<RecordBatch>> {
58+
let result = match read.map_err(|error| crate::errors::to_py_err(py, error))? {
59+
BatchRead::Ready(batch) => Ok(Some(batch)),
60+
BatchRead::End => Ok(None),
61+
BatchRead::Pending => py.detach(pending),
62+
_ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")),
63+
};
64+
result.map_err(|error| crate::errors::to_py_err(py, error))
65+
}
66+
3167
/// Pull the next batch from the kernel stream and return it as an
3268
/// owned `RecordBatch`, or `None` if the stream is exhausted.
3369
///
@@ -37,29 +73,15 @@ pub(crate) fn next_batch(
3773
runtime: &Runtime,
3874
stream: &mut ResultStream,
3975
) -> Result<Option<RecordBatch>> {
40-
runtime.block_on(async {
41-
match stream.next_batch().await? {
42-
Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())),
43-
Some(_) => Err(Error::invalid_argument()
44-
.message("kernel returned a non-Arrow ResultBatch variant")),
45-
None => Ok(None),
46-
}
47-
})
76+
runtime.block_on(async { stream.next_batch().await?.map(own_arrow_batch).transpose() })
4877
}
4978

5079
/// Drain the kernel stream and collect every remaining batch.
5180
pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result<Vec<RecordBatch>> {
5281
runtime.block_on(async {
5382
let mut out = Vec::new();
54-
loop {
55-
match stream.next_batch().await? {
56-
Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()),
57-
Some(_) => {
58-
return Err(Error::invalid_argument()
59-
.message("kernel returned a non-Arrow ResultBatch variant"));
60-
}
61-
None => break,
62-
}
83+
while let Some(batch) = stream.next_batch().await? {
84+
out.push(own_arrow_batch(batch)?);
6385
}
6486
Ok(out)
6587
})
@@ -72,14 +94,7 @@ pub(crate) fn next_batch_exec(
7294
runtime: &Runtime,
7395
exec: &mut ExecutedStatement,
7496
) -> Result<Option<RecordBatch>> {
75-
runtime.block_on(async {
76-
match exec.next_batch().await? {
77-
Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())),
78-
Some(_) => Err(Error::invalid_argument()
79-
.message("kernel returned a non-Arrow ResultBatch variant")),
80-
None => Ok(None),
81-
}
82-
})
97+
runtime.block_on(async { exec.next_batch().await?.map(own_arrow_batch).transpose() })
8398
}
8499

85100
/// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on-
@@ -91,15 +106,8 @@ pub(crate) fn drain_exec(
91106
) -> Result<Vec<RecordBatch>> {
92107
runtime.block_on(async {
93108
let mut out = Vec::new();
94-
loop {
95-
match exec.next_batch().await? {
96-
Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()),
97-
Some(_) => {
98-
return Err(Error::invalid_argument()
99-
.message("kernel returned a non-Arrow ResultBatch variant"));
100-
}
101-
None => break,
102-
}
109+
while let Some(batch) = exec.next_batch().await? {
110+
out.push(own_arrow_batch(batch)?);
103111
}
104112
Ok(out)
105113
})
@@ -122,3 +130,101 @@ pub(crate) fn batches_to_pyarrow_table<'py>(
122130
pa.getattr("Table")?
123131
.call_method1("from_batches", (py_batches, py_schema))
124132
}
133+
134+
#[cfg(test)]
135+
mod tests {
136+
use super::*;
137+
use std::sync::atomic::{AtomicUsize, Ordering};
138+
139+
#[test]
140+
fn only_pending_reads_enter_the_runtime() {
141+
let runtime = tokio::runtime::Builder::new_current_thread()
142+
.build()
143+
.unwrap();
144+
let entries = AtomicUsize::new(0);
145+
let pending = || {
146+
entries.fetch_add(1, Ordering::Relaxed);
147+
let (sender, receiver) = std::sync::mpsc::channel();
148+
let worker = std::thread::spawn(move || {
149+
Python::attach(|_| {
150+
let _ = sender.send(());
151+
});
152+
});
153+
receiver
154+
.recv_timeout(std::time::Duration::from_secs(5))
155+
.expect("pending fallback held the GIL");
156+
worker.join().unwrap();
157+
runtime.block_on(async { Ok(None) })
158+
};
159+
Python::initialize();
160+
Python::attach(|py| {
161+
let batch = RecordBatch::new_empty(Arc::new(Schema::empty()));
162+
let ready = read_batch(py, Ok(BatchRead::Ready(batch.clone())), pending).unwrap();
163+
assert_eq!(ready, Some(batch));
164+
assert!(read_batch(py, Ok(BatchRead::End), pending)
165+
.unwrap()
166+
.is_none());
167+
assert_eq!(entries.load(Ordering::Relaxed), 0);
168+
169+
assert!(read_batch(py, Ok(BatchRead::Pending), pending)
170+
.unwrap()
171+
.is_none());
172+
assert_eq!(entries.load(Ordering::Relaxed), 1);
173+
});
174+
}
175+
176+
#[test]
177+
fn real_result_handles_return_eof_without_runtime_entry() {
178+
use pyo3::types::PyDict;
179+
180+
Python::initialize();
181+
Python::attach(|py| {
182+
let globals = PyDict::new(py);
183+
globals
184+
.set_item("Session", py.get_type::<crate::session::Session>())
185+
.unwrap();
186+
let fixture = std::ffi::CString::new(include_str!("../tests/sql_api.py")).unwrap();
187+
py.run(&fixture, Some(&globals), None).unwrap();
188+
py.run(
189+
c"from contextlib import ExitStack\nresources = ExitStack()",
190+
Some(&globals),
191+
None,
192+
)
193+
.unwrap();
194+
let checked =
195+
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> PyResult<()> {
196+
py.run(
197+
c"
198+
state = resources.enter_context(sql_api(Session))
199+
results = []
200+
for asynchronous in (False, True):
201+
statement = state.session.statement()
202+
resources.callback(statement.close)
203+
statement.set_sql(\"SELECT 1\")
204+
owner = statement.submit() if asynchronous else statement.execute()
205+
resources.callback(owner.close)
206+
result = owner.await_result() if asynchronous else owner
207+
resources.callback(result.close)
208+
results.append(result)
209+
",
210+
Some(&globals),
211+
None,
212+
)?;
213+
let runtime = tokio::runtime::Builder::new_current_thread()
214+
.build()
215+
.unwrap();
216+
// Tokio rejects nested block_on calls through either real handle.
217+
runtime.block_on(async {
218+
py.run(
219+
c"for result in results:\n assert result.fetch_next_batch() is None",
220+
Some(&globals),
221+
None,
222+
)
223+
})
224+
}));
225+
let cleanup = py.run(c"resources.close()", Some(&globals), None);
226+
checked.unwrap().unwrap();
227+
cleanup.unwrap();
228+
});
229+
}
230+
}

‎pyo3/src/lib.rs‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,6 @@
2222
//! Both synchronous `execute()` and async `submit()` paths supported.
2323
//! Built as the `databricks_sql_kernel` extension module via
2424
//! `maturin develop` / `maturin build`.
25-
//!
26-
//! The kernel's API is async — every method call from Python detaches
27-
//! the GIL and `block_on`s on the session-owned tokio runtime.
2825
2926
// `macros` is `#[macro_use]` so the `run_kernel!` / `alive!` /
3027
// `alive_mut!` macros are visible across the rest of the crate

‎pyo3/src/logging.rs‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,20 @@
3737
//! logging.getLogger("databricks.sql.kernel").setLevel(logging.DEBUG) # kernel only
3838
//! ```
3939
//!
40-
//! ## Filtering happens before the GIL
40+
//! ## GIL and filtering
4141
//!
42-
//! Kernel events fire on tokio worker threads with the GIL released
43-
//! (see `run_kernel!`). `pyo3_log` re-acquires the GIL per surviving
44-
//! record, so we must drop below-threshold events *before* that
45-
//! boundary. Two cheap gates do this: the global `log::max_level`
46-
//! (set by `pyo3_log` from the Python loggers' effective levels) and
47-
//! `pyo3_log`'s per-logger level cache. The customer's single knob
48-
//! (`setLevel`) drives both — there is no separate Rust-side level
49-
//! argument.
42+
//! This bridge sets `log::max_level` to `Trace`; Python logger levels
43+
//! control filtering through `pyo3_log`'s per-logger cache. Cached
44+
//! below-threshold records can be rejected without acquiring the GIL.
45+
//! A cache miss can acquire the GIL to resolve the logger and its level,
46+
//! even if a Python logger set to WARNING discards the record.
47+
//! Forwarding an enabled record also acquires the GIL.
48+
//!
49+
//! Events can originate on runtime workers or a Python caller holding
50+
//! the GIL during a buffered fetch. Callers holding the GIL must avoid
51+
//! waiting for locks held by a logging worker, regardless of Python log
52+
//! levels. CloudFetch probes yield on contended provider-state locks
53+
//! so the fallback can wait with the GIL released.
5054
//!
5155
//! ## Reconfiguration
5256
//!
@@ -166,9 +170,8 @@ impl<L: log::Log> log::Log for ExitGuard<L> {
166170
/// stays quiet, while a customer who turns on DEBUG to diagnose a
167171
/// connectivity / TLS issue gets the full wire-level picture in one
168172
/// shot, with no flag to flip and no support round-trip to ask for it.
169-
/// The per-record GIL re-acquire cost of forwarding deps only
170-
/// materializes when DEBUG is actually enabled on those loggers; a
171-
/// customer can silence them with the standard
173+
/// Uncached targets can acquire the GIL even if Python filters out
174+
/// their records. A customer can silence dependency output with
172175
/// `logging.getLogger("hyper_util").setLevel(WARNING)`.
173176
///
174177
/// Returns `true` if this call performed the install, `false` otherwise

‎pyo3/src/result_stream.rs‎

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,8 @@
1414

1515
//! `ResultStream` — Python class wrapping a kernel `ResultStream`.
1616
//!
17-
//! Returned by `Session.metadata().list_*` calls and (in future)
18-
//! anywhere the kernel hands back a bare `ResultStream` without an
19-
//! enclosing `ExecutedStatement`. Identical fetch surface to
20-
//! `ExecutedStatement` (Arrow batches, drain-to-Table), minus the
21-
//! statement_id / cancel hooks that only make sense for an executed
22-
//! statement.
23-
//!
24-
//! The actual batch-pulling logic lives in `fetch::*` helpers so
25-
//! `ExecutedStatement::fetch_next_batch` / `fetch_all_arrow` can call
26-
//! the same code path through its `result_stream_mut()` borrow.
17+
//! Returned by metadata calls and asynchronous statement reads. Server cleanup
18+
//! belongs to the metadata close guard or the asynchronous statement owner.
2719
2820
use crate::fetch;
2921
use crate::runtime::KernelRuntime;
@@ -76,8 +68,9 @@ impl ResultStream {
7668
if inner.exhausted {
7769
return Ok(None);
7870
}
79-
let runtime = inner.runtime.clone();
80-
let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))?;
71+
let batch = fetch::read_batch(py, fetch::own_batch(inner.stream.try_next_batch()), || {
72+
fetch::next_batch(&inner.runtime, &mut inner.stream)
73+
})?;
8174
match batch {
8275
Some(b) => Ok(Some(b.to_pyarrow(py)?)),
8376
None => {

‎pyo3/src/statement.rs‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -348,11 +348,9 @@ impl ExecutedStatement {
348348
if inner.exhausted {
349349
return Ok(None);
350350
}
351-
let runtime = inner.runtime.clone();
352-
// `next_batch_exec` drives the ExecutedStatement so the kernel's
353-
// auto-close-on-drain fires the server CloseStatement once the
354-
// stream is exhausted (after all lazy CloudFetch link fetches).
355-
let batch = run_sync_kernel!(py, fetch::next_batch_exec(&runtime, &mut inner.exec))?;
351+
let batch = fetch::read_batch(py, fetch::own_batch(inner.exec.try_next_batch()), || {
352+
fetch::next_batch_exec(&inner.runtime, &mut inner.exec)
353+
})?;
356354
match batch {
357355
Some(b) => Ok(Some(b.to_pyarrow(py)?)),
358356
None => {
@@ -397,7 +395,12 @@ impl ExecutedStatement {
397395
return Ok(());
398396
};
399397
let runtime = inner.runtime.clone();
400-
let res = run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec));
398+
// Exhaustion finalizes telemetry and schedules server cleanup.
399+
let res = if inner.exhausted {
400+
Ok(())
401+
} else {
402+
run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec))
403+
};
401404
// Drop the kernel handle regardless of close() outcome — the
402405
// kernel's Drop impl runs fire-and-forget cleanup if close()
403406
// failed mid-flight.

0 commit comments

Comments
 (0)