Skip to content
Merged
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
188 changes: 147 additions & 41 deletions pyo3/src/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,58 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! Internal helpers for pulling batches out of a `ResultStream`.
//! Shared batch ownership and GIL handoff for both Python result handles.
//!
//! Shared by `ExecutedStatement` (drives the kernel `ExecutedStatement`'s
//! borrowed result stream) and `ResultStream` (owns its kernel
//! `ResultStream` directly). Both call `next_batch` on the kernel
//! stream and clone the Arrow `RecordBatch` out from under the
//! borrow so the result can cross the GIL boundary as an owned value.
//! A nonblocking probe holds the GIL through kernel post-processing, so large
//! batches requiring column rewrites can delay other Python threads.
//!
//! Contended CloudFetch provider-state locks yield `Pending`, allowing the
//! fallback to wait with the GIL released.

use arrow_array::RecordBatch;
use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::{Error, ExecutedStatement, Result, ResultBatch, ResultStream};
use databricks_sql_kernel::reader::TryNextBatch as BatchRead;
use databricks_sql_kernel::{
Error, ExecutedStatement, Result, ResultBatch, ResultStream, TryNextBatch,
};
use pyo3::prelude::*;
use std::sync::Arc;
use tokio::runtime::Runtime;

fn own_arrow_batch(batch: &ResultBatch) -> Result<RecordBatch> {
match batch {
ResultBatch::Arrow(batch) => Ok(batch.clone()),
_ => {
Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"))
}
}
}

pub(crate) fn own_batch(read: Result<TryNextBatch<'_>>) -> Result<BatchRead> {
match read? {
TryNextBatch::Ready(batch) => own_arrow_batch(batch).map(BatchRead::Ready),
TryNextBatch::Pending => Ok(BatchRead::Pending),
TryNextBatch::End => Ok(BatchRead::End),
_ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")),
}
}

pub(crate) fn read_batch(
py: Python<'_>,
read: Result<BatchRead>,
pending: impl FnOnce() -> Result<Option<RecordBatch>> + pyo3::marker::Ungil,
) -> PyResult<Option<RecordBatch>> {
let result = match read.map_err(|error| crate::errors::to_py_err(py, error))? {
BatchRead::Ready(batch) => Ok(Some(batch)),
BatchRead::End => Ok(None),
BatchRead::Pending => py.detach(pending),
_ => Err(Error::invalid_state().message("kernel returned an unknown batch-read state")),
};
result.map_err(|error| crate::errors::to_py_err(py, error))
}

/// Pull the next batch from the kernel stream and return it as an
/// owned `RecordBatch`, or `None` if the stream is exhausted.
///
Expand All @@ -37,29 +73,15 @@ pub(crate) fn next_batch(
runtime: &Runtime,
stream: &mut ResultStream,
) -> Result<Option<RecordBatch>> {
runtime.block_on(async {
match stream.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())),
Some(_) => Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant")),
None => Ok(None),
}
})
runtime.block_on(async { stream.next_batch().await?.map(own_arrow_batch).transpose() })
}

/// Drain the kernel stream and collect every remaining batch.
pub(crate) fn drain(runtime: &Runtime, stream: &mut ResultStream) -> Result<Vec<RecordBatch>> {
runtime.block_on(async {
let mut out = Vec::new();
loop {
match stream.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()),
Some(_) => {
return Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"));
}
None => break,
}
while let Some(batch) = stream.next_batch().await? {
out.push(own_arrow_batch(batch)?);
}
Ok(out)
})
Expand All @@ -72,14 +94,7 @@ pub(crate) fn next_batch_exec(
runtime: &Runtime,
exec: &mut ExecutedStatement,
) -> Result<Option<RecordBatch>> {
runtime.block_on(async {
match exec.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => Ok(Some(rb.clone())),
Some(_) => Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant")),
None => Ok(None),
}
})
runtime.block_on(async { exec.next_batch().await?.map(own_arrow_batch).transpose() })
}

/// Like [`drain`], but drives the `ExecutedStatement` so auto-close-on-
Expand All @@ -91,15 +106,8 @@ pub(crate) fn drain_exec(
) -> Result<Vec<RecordBatch>> {
runtime.block_on(async {
let mut out = Vec::new();
loop {
match exec.next_batch().await? {
Some(ResultBatch::Arrow(rb)) => out.push(rb.clone()),
Some(_) => {
return Err(Error::invalid_argument()
.message("kernel returned a non-Arrow ResultBatch variant"));
}
None => break,
}
while let Some(batch) = exec.next_batch().await? {
out.push(own_arrow_batch(batch)?);
}
Ok(out)
})
Expand All @@ -122,3 +130,101 @@ pub(crate) fn batches_to_pyarrow_table<'py>(
pa.getattr("Table")?
.call_method1("from_batches", (py_batches, py_schema))
}

#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};

#[test]
fn only_pending_reads_enter_the_runtime() {
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let entries = AtomicUsize::new(0);
let pending = || {
entries.fetch_add(1, Ordering::Relaxed);
let (sender, receiver) = std::sync::mpsc::channel();
let worker = std::thread::spawn(move || {
Python::attach(|_| {
let _ = sender.send(());
});
});
receiver
.recv_timeout(std::time::Duration::from_secs(5))
.expect("pending fallback held the GIL");
worker.join().unwrap();
runtime.block_on(async { Ok(None) })
};
Python::initialize();
Python::attach(|py| {
let batch = RecordBatch::new_empty(Arc::new(Schema::empty()));
let ready = read_batch(py, Ok(BatchRead::Ready(batch.clone())), pending).unwrap();
assert_eq!(ready, Some(batch));
assert!(read_batch(py, Ok(BatchRead::End), pending)
.unwrap()
.is_none());
assert_eq!(entries.load(Ordering::Relaxed), 0);

assert!(read_batch(py, Ok(BatchRead::Pending), pending)
.unwrap()
.is_none());
assert_eq!(entries.load(Ordering::Relaxed), 1);
});
}

#[test]
fn real_result_handles_return_eof_without_runtime_entry() {
use pyo3::types::PyDict;

Python::initialize();
Python::attach(|py| {
let globals = PyDict::new(py);
globals
.set_item("Session", py.get_type::<crate::session::Session>())
.unwrap();
let fixture = std::ffi::CString::new(include_str!("../tests/sql_api.py")).unwrap();
py.run(&fixture, Some(&globals), None).unwrap();
py.run(
c"from contextlib import ExitStack\nresources = ExitStack()",
Some(&globals),
None,
)
.unwrap();
let checked =
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> PyResult<()> {
py.run(
c"
state = resources.enter_context(sql_api(Session))
results = []
for asynchronous in (False, True):
statement = state.session.statement()
resources.callback(statement.close)
statement.set_sql(\"SELECT 1\")
owner = statement.submit() if asynchronous else statement.execute()
resources.callback(owner.close)
result = owner.await_result() if asynchronous else owner
resources.callback(result.close)
results.append(result)
",
Some(&globals),
None,
)?;
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
// Tokio rejects nested block_on calls through either real handle.
runtime.block_on(async {
py.run(
c"for result in results:\n assert result.fetch_next_batch() is None",
Some(&globals),
None,
)
})
}));
let cleanup = py.run(c"resources.close()", Some(&globals), None);
checked.unwrap().unwrap();
cleanup.unwrap();
});
}
}
3 changes: 0 additions & 3 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,6 @@
//! Both synchronous `execute()` and async `submit()` paths supported.
//! Built as the `databricks_sql_kernel` extension module via
//! `maturin develop` / `maturin build`.
//!
//! The kernel's API is async — every method call from Python detaches
//! the GIL and `block_on`s on the session-owned tokio runtime.

// `macros` is `#[macro_use]` so the `run_kernel!` / `alive!` /
// `alive_mut!` macros are visible across the rest of the crate
Expand Down
27 changes: 15 additions & 12 deletions pyo3/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,20 @@
//! logging.getLogger("databricks.sql.kernel").setLevel(logging.DEBUG) # kernel only
//! ```
//!
//! ## Filtering happens before the GIL
//! ## GIL and filtering
//!
//! Kernel events fire on tokio worker threads with the GIL released
//! (see `run_kernel!`). `pyo3_log` re-acquires the GIL per surviving
//! record, so we must drop below-threshold events *before* that
//! boundary. Two cheap gates do this: the global `log::max_level`
//! (set by `pyo3_log` from the Python loggers' effective levels) and
//! `pyo3_log`'s per-logger level cache. The customer's single knob
//! (`setLevel`) drives both — there is no separate Rust-side level
//! argument.
//! This bridge sets `log::max_level` to `Trace`; Python logger levels
//! control filtering through `pyo3_log`'s per-logger cache. Cached
//! below-threshold records can be rejected without acquiring the GIL.
//! A cache miss can acquire the GIL to resolve the logger and its level,
//! even if a Python logger set to WARNING discards the record.
//! Forwarding an enabled record also acquires the GIL.
//!
//! Events can originate on runtime workers or a Python caller holding
//! the GIL during a buffered fetch. Callers holding the GIL must avoid
//! waiting for locks held by a logging worker, regardless of Python log
//! levels. CloudFetch probes yield on contended provider-state locks
//! so the fallback can wait with the GIL released.
//!
//! ## Reconfiguration
//!
Expand Down Expand Up @@ -166,9 +170,8 @@ impl<L: log::Log> log::Log for ExitGuard<L> {
/// stays quiet, while a customer who turns on DEBUG to diagnose a
/// connectivity / TLS issue gets the full wire-level picture in one
/// shot, with no flag to flip and no support round-trip to ask for it.
/// The per-record GIL re-acquire cost of forwarding deps only
/// materializes when DEBUG is actually enabled on those loggers; a
/// customer can silence them with the standard
/// Uncached targets can acquire the GIL even if Python filters out
/// their records. A customer can silence dependency output with
/// `logging.getLogger("hyper_util").setLevel(WARNING)`.
///
/// Returns `true` if this call performed the install, `false` otherwise
Expand Down
17 changes: 5 additions & 12 deletions pyo3/src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,8 @@

//! `ResultStream` — Python class wrapping a kernel `ResultStream`.
//!
//! Returned by `Session.metadata().list_*` calls and (in future)
//! anywhere the kernel hands back a bare `ResultStream` without an
//! enclosing `ExecutedStatement`. Identical fetch surface to
//! `ExecutedStatement` (Arrow batches, drain-to-Table), minus the
//! statement_id / cancel hooks that only make sense for an executed
//! statement.
//!
//! The actual batch-pulling logic lives in `fetch::*` helpers so
//! `ExecutedStatement::fetch_next_batch` / `fetch_all_arrow` can call
//! the same code path through its `result_stream_mut()` borrow.
//! Returned by metadata calls and asynchronous statement reads. Server cleanup
//! belongs to the metadata close guard or the asynchronous statement owner.

use crate::fetch;
use crate::runtime::KernelRuntime;
Expand Down Expand Up @@ -76,8 +68,9 @@ impl ResultStream {
if inner.exhausted {
return Ok(None);
}
let runtime = inner.runtime.clone();
let batch = run_sync_kernel!(py, fetch::next_batch(&runtime, &mut inner.stream))?;
let batch = fetch::read_batch(py, fetch::own_batch(inner.stream.try_next_batch()), || {
fetch::next_batch(&inner.runtime, &mut inner.stream)
})?;
match batch {
Some(b) => Ok(Some(b.to_pyarrow(py)?)),
None => {
Expand Down
15 changes: 9 additions & 6 deletions pyo3/src/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -348,11 +348,9 @@ impl ExecutedStatement {
if inner.exhausted {
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))?;
let batch = fetch::read_batch(py, fetch::own_batch(inner.exec.try_next_batch()), || {
fetch::next_batch_exec(&inner.runtime, &mut inner.exec)
})?;
match batch {
Some(b) => Ok(Some(b.to_pyarrow(py)?)),
None => {
Expand Down Expand Up @@ -397,7 +395,12 @@ impl ExecutedStatement {
return Ok(());
};
let runtime = inner.runtime.clone();
let res = run_kernel!(py, runtime, KExecutedStatement::close(&mut inner.exec));
// Exhaustion finalizes telemetry and schedules server cleanup.
let res = if inner.exhausted {
Ok(())
} 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