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
4 changes: 4 additions & 0 deletions pyo3/NEXT_CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ changes go in the root `NEXT_CHANGELOG.md`.

### Fixed

- Fixed an intermittent hang in `Session.close()` (or when Python frees a
handle) when a runtime worker was forwarding a log record to Python
`logging` at the moment the session's runtime shut down.

---
*Note: When making changes, please add your change under the appropriate
section with a brief description. At release time, move the entries here
Expand Down
7 changes: 4 additions & 3 deletions pyo3/src/executed_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@

use crate::errors::to_py_err;
use crate::result_stream::ResultStream;
use crate::runtime::KernelRuntime;
use databricks_sql_kernel::{
ExecutedAsyncStatement as KExecutedAsyncStatement, ExecutedStatementHandle, StatementStatus,
};
use pyo3::prelude::*;
use std::sync::Arc;
use tokio::runtime::Runtime;

#[pyclass(name = "ExecutedAsyncStatement")]
pub(crate) struct ExecutedAsyncStatement {
Expand All @@ -38,11 +38,11 @@ pub(crate) struct ExecutedAsyncStatement {

struct ExecutedAsyncInner {
exec: KExecutedAsyncStatement,
runtime: Arc<Runtime>,
runtime: Arc<KernelRuntime>,
}

impl ExecutedAsyncStatement {
pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc<Runtime>) -> Self {
pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc<KernelRuntime>) -> Self {
let statement_id = exec.statement_id().to_owned();
Self {
statement_id,
Expand Down Expand Up @@ -135,6 +135,7 @@ impl ExecutedAsyncStatement {
let runtime = inner.runtime.clone();
let res = run_kernel!(py, runtime, KExecutedAsyncStatement::close(&mut inner.exec));
self.inner = None;
KernelRuntime::release(runtime, py);
res.map(|_| ())
}

Expand Down
1 change: 1 addition & 0 deletions pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ mod logging;
mod metadata;
mod params;
mod result_stream;
mod runtime;
mod session;
mod statement;

Expand Down
86 changes: 79 additions & 7 deletions pyo3/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,19 @@
//! cache so the new level takes effect. The connector calls this after
//! it adjusts logging; most customers configure logging before
//! connecting and never need it.
//!
//! ## Interpreter exit
//!
//! Runtime workers can outlive their handle (`KernelRuntime`'s `Drop`
//! doesn't wait for them), and pyo3's finalization check is compiled out
//! under `abi3-py39`, so a worker forwarding a record while the
//! interpreter finalizes can abort the process. An `atexit` hook, which
//! runs before finalization starts, makes the bridge drop records from
//! then on.

use pyo3::prelude::*;
use pyo3_log::{Caching, Logger, ResetHandle};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock};

/// Logger target the kernel tags every event with. Maps to the Python
Expand Down Expand Up @@ -107,6 +117,39 @@ fn lock_state() -> std::sync::MutexGuard<'static, LogState> {
.unwrap_or_else(|poisoned| poisoned.into_inner())
}

/// Set by an `atexit` hook; see "Interpreter exit" above.
static INTERPRETER_EXITING: AtomicBool = AtomicBool::new(false);

#[pyfunction]
fn mark_interpreter_exiting() {
INTERPRETER_EXITING.store(true, Ordering::SeqCst);
}

fn register_exit_hook(py: Python<'_>) -> PyResult<()> {
let hook = wrap_pyfunction!(mark_interpreter_exiting, py)?;
py.import("atexit")?.call_method1("register", (hook,))?;
Ok(())
}

/// Forwards to `pyo3_log` until the interpreter starts exiting.
struct ExitGuard<L>(L);

impl<L: log::Log> log::Log for ExitGuard<L> {
fn enabled(&self, metadata: &log::Metadata<'_>) -> bool {
!INTERPRETER_EXITING.load(Ordering::SeqCst) && self.0.enabled(metadata)
}

fn log(&self, record: &log::Record<'_>) {
if !INTERPRETER_EXITING.load(Ordering::SeqCst) {
self.0.log(record);
}
}

fn flush(&self) {
self.0.flush();
}
}

/// Install the `tracing`/`log` -> Python `logging` bridge.
///
/// Idempotent: the first call installs `pyo3_log`; later calls are
Expand Down Expand Up @@ -161,14 +204,19 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool {
return false;
}
};
let handle = logger
let logger = logger
.filter(log::LevelFilter::Trace)
.filter_target(KERNEL_TARGET.to_owned(), log::LevelFilter::Trace)
.install();
.filter_target(KERNEL_TARGET.to_owned(), log::LevelFilter::Trace);

match handle {
Ok(h) => {
*state = LogState::Installed(h);
// What `Logger::install()` does, but behind `ExitGuard`. `Trace` is the
// highest filter set above.
let handle = logger.reset_handle();
match log::set_boxed_logger(Box::new(ExitGuard(logger))) {
Ok(()) => {
log::set_max_level(log::LevelFilter::Trace);
// Best effort: without the hook, records still flow until exit.
let _ = register_exit_hook(py);
*state = LogState::Installed(handle);
true
}
Err(_) => {
Expand All @@ -195,7 +243,31 @@ pub(crate) fn reset_logging() {

#[cfg(test)]
mod tests {
use super::KERNEL_TARGET;
use super::{mark_interpreter_exiting, ExitGuard, KERNEL_TARGET};
use log::Log;
use std::sync::atomic::{AtomicUsize, Ordering};

#[test]
fn exit_guard_drops_records_once_interpreter_exits() {
struct Count(AtomicUsize);
impl Log for Count {
fn enabled(&self, _: &log::Metadata<'_>) -> bool {
true
}
fn log(&self, _: &log::Record<'_>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
fn flush(&self) {}
}

let guard = ExitGuard(Count(AtomicUsize::new(0)));
let record = log::Record::builder().level(log::Level::Error).build();
guard.log(&record);
mark_interpreter_exiting();
guard.log(&record);
assert!(!guard.enabled(record.metadata()));
assert_eq!(guard.0 .0.load(Ordering::SeqCst), 1);
}

/// Layer 2 of the logger-name drift guard (see also the kernel's
/// `klog::tests::klog_emits_contract_target` and the Python
Expand Down
6 changes: 3 additions & 3 deletions pyo3/src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,11 @@
//! conversions stay explicit and grep-able.

use crate::result_stream::ResultStream;
use crate::runtime::KernelRuntime;
use databricks_sql_kernel::metadata_v0::exact_catalog_and_pattern;
use databricks_sql_kernel::{Identifier, LikePattern, Metadata as KMetadata};
use pyo3::prelude::*;
use std::sync::Arc;
use tokio::runtime::Runtime;

/// Python-facing metadata handle.
///
Expand All @@ -56,11 +56,11 @@ use tokio::runtime::Runtime;
#[pyclass(name = "Metadata")]
pub(crate) struct Metadata {
inner: KMetadata,
runtime: Arc<Runtime>,
runtime: Arc<KernelRuntime>,
}

impl Metadata {
pub(crate) fn new(inner: KMetadata, runtime: Arc<Runtime>) -> Self {
pub(crate) fn new(inner: KMetadata, runtime: Arc<KernelRuntime>) -> Self {
Self { inner, runtime }
}
}
Expand Down
9 changes: 5 additions & 4 deletions pyo3/src/result_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
//! the same code path through its `result_stream_mut()` borrow.

use crate::fetch;
use crate::runtime::KernelRuntime;
use arrow_pyarrow::ToPyArrow;
use arrow_schema::Schema;
use databricks_sql_kernel::ResultStream as KResultStream;
use pyo3::prelude::*;
use std::sync::Arc;
use tokio::runtime::Runtime;

/// Python-facing borrowed result stream.
#[pyclass(name = "ResultStream")]
Expand All @@ -44,12 +44,12 @@ pub(crate) struct ResultStream {

struct ResultStreamInner {
stream: KResultStream,
runtime: Arc<Runtime>,
runtime: Arc<KernelRuntime>,
exhausted: bool,
}

impl ResultStream {
pub(crate) fn new(stream: KResultStream, runtime: Arc<Runtime>) -> Self {
pub(crate) fn new(stream: KResultStream, runtime: Arc<KernelRuntime>) -> Self {
let schema = stream.schema();
Self {
schema,
Expand Down Expand Up @@ -98,13 +98,14 @@ impl ResultStream {

/// Release client-side resources. Idempotent. Subsequent calls
/// on this handle raise `KernelError`.
fn close(&mut self) {
fn close(&mut self, py: Python<'_>) {
if let Some(inner) = self.inner.take() {
// ResultStream::close() is sync (no server RPC) and
// consumes self; the kernel's Drop performs the same
// cleanup, but the explicit call is cheaper to reason
// about.
inner.stream.close();
KernelRuntime::release(inner.runtime, py);
}
}

Expand Down
142 changes: 142 additions & 0 deletions pyo3/src/runtime.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// 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.

//! `KernelRuntime` — the session-owned tokio runtime.

use pyo3::prelude::*;
use std::ops::Deref;
use std::sync::Arc;
use std::time::Duration;
use tokio::runtime::Runtime;

/// Upper bound on how long an explicit `close()` waits for the runtime to
/// stop. Shutdown also waits on blocking-pool work (e.g. the OAuth refresh
/// in `src/auth/oauth/token_store.rs`), so this caps `close()` latency.
const CLOSE_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(1);

/// Tokio runtime that never blocks on its workers while the GIL may be held.
///
/// A plain `Runtime` drop blocks until every worker exits, but a worker
/// forwarding a log record through `pyo3_log` waits for the GIL, so
/// dropping it with the GIL held deadlocks. Explicit `close()` calls go
/// through [`release`](Self::release), which waits with the GIL released.
/// `Drop` — reached when Python frees a handle — uses `shutdown_background`,
/// so workers may still run briefly after it returns.
///
/// Handle structs must declare their kernel object before this field:
/// fields drop in order, and kernel `Drop` impls queue cleanup on it.
pub(crate) struct KernelRuntime(Option<Runtime>);

impl KernelRuntime {
pub(crate) fn new(runtime: Runtime) -> Self {
Self(Some(runtime))
}

/// Release a handle at the end of an explicit `close()`. If it was the
/// last one, shut down and wait for the workers with the GIL released,
/// so none is still logging into Python after `close()` returns.
pub(crate) fn release(runtime: Arc<Self>, py: Python<'_>) {
if let Ok(mut runtime) = Arc::try_unwrap(runtime) {
if let Some(runtime) = runtime.0.take() {
py.detach(|| runtime.shutdown_timeout(CLOSE_SHUTDOWN_TIMEOUT));
}
}
}
}

impl Deref for KernelRuntime {
type Target = Runtime;

fn deref(&self) -> &Runtime {
self.0.as_ref().expect("runtime is only taken on shutdown")
}
}

impl Drop for KernelRuntime {
fn drop(&mut self) {
if let Some(runtime) = self.0.take() {
runtime.shutdown_background();
Comment thread
vuanhphung marked this conversation as resolved.
Resolved
}
}
}

#[cfg(test)]
mod tests {
use super::KernelRuntime;
use pyo3::prelude::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc};
use std::time::Duration;

/// One-worker runtime whose worker is mid-task and needs the GIL, which
/// the calling (attached) thread holds. Stands in for a worker
/// forwarding a record via pyo3_log. The flag is set once it got the GIL.
fn runtime_with_gil_blocked_worker() -> (KernelRuntime, Arc<AtomicBool>) {
let runtime = KernelRuntime::new(
tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.build()
.expect("build runtime"),
);
let finished = Arc::new(AtomicBool::new(false));
let flag = finished.clone();
let (started_tx, started_rx) = mpsc::channel();
runtime.spawn(async move {
started_tx.send(()).expect("signal started");
Python::attach(|_py| {});
flag.store(true, Ordering::SeqCst);
});
started_rx.recv().expect("worker started");
(runtime, finished)
}

/// Runs `f` on its own attached thread, so a regression fails the test
/// instead of hanging it.
fn run_attached<T: Send + 'static>(f: fn(Python<'_>) -> T, what: &str) -> T {
Python::initialize();
let (done_tx, done_rx) = mpsc::channel();
std::thread::spawn(move || {
let out = Python::attach(f);
done_tx.send(out).expect("signal done");
});
done_rx
.recv_timeout(Duration::from_secs(10))
.unwrap_or_else(|_| panic!("{what} deadlocked on a GIL-blocked worker"))
}

#[test]
fn drop_with_gil_held_does_not_wait_for_gil_blocked_worker() {
run_attached(
|_py| drop(runtime_with_gil_blocked_worker().0),
"dropping the runtime with the GIL held",
);
}

#[test]
fn release_waits_for_gil_blocked_worker_to_finish() {
let finished_at_return = run_attached(
|py| {
let (runtime, finished) = runtime_with_gil_blocked_worker();
KernelRuntime::release(Arc::new(runtime), py);
// Still attached: a worker that hasn't run yet can't now.
finished.load(Ordering::SeqCst)
},
"release()",
);
assert!(
finished_at_return,
"release() returned before the worker finished"
);
}
}
Loading
Loading