diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 819d7599..fbbc1353 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -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 diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index 73883914..1189c9db 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -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 { @@ -38,11 +38,11 @@ pub(crate) struct ExecutedAsyncStatement { struct ExecutedAsyncInner { exec: KExecutedAsyncStatement, - runtime: Arc, + runtime: Arc, } impl ExecutedAsyncStatement { - pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc) -> Self { + pub(crate) fn new(exec: KExecutedAsyncStatement, runtime: Arc) -> Self { let statement_id = exec.statement_id().to_owned(); Self { statement_id, @@ -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(|_| ()) } diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 4909cee0..adafe292 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -40,6 +40,7 @@ mod logging; mod metadata; mod params; mod result_stream; +mod runtime; mod session; mod statement; diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 8a96be6c..0271f276 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -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 @@ -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); + +impl log::Log for ExitGuard { + 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 @@ -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(_) => { @@ -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 diff --git a/pyo3/src/metadata.rs b/pyo3/src/metadata.rs index c6b69e40..8292453e 100644 --- a/pyo3/src/metadata.rs +++ b/pyo3/src/metadata.rs @@ -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. /// @@ -56,11 +56,11 @@ use tokio::runtime::Runtime; #[pyclass(name = "Metadata")] pub(crate) struct Metadata { inner: KMetadata, - runtime: Arc, + runtime: Arc, } impl Metadata { - pub(crate) fn new(inner: KMetadata, runtime: Arc) -> Self { + pub(crate) fn new(inner: KMetadata, runtime: Arc) -> Self { Self { inner, runtime } } } diff --git a/pyo3/src/result_stream.rs b/pyo3/src/result_stream.rs index a22e56b1..cd193bb9 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -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")] @@ -44,12 +44,12 @@ pub(crate) struct ResultStream { struct ResultStreamInner { stream: KResultStream, - runtime: Arc, + runtime: Arc, exhausted: bool, } impl ResultStream { - pub(crate) fn new(stream: KResultStream, runtime: Arc) -> Self { + pub(crate) fn new(stream: KResultStream, runtime: Arc) -> Self { let schema = stream.schema(); Self { schema, @@ -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); } } diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs new file mode 100644 index 00000000..a443b7c2 --- /dev/null +++ b/pyo3/src/runtime.rs @@ -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); + +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, 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(); + } + } +} + +#[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) { + 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(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" + ); + } +} diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 2b12dc9d..4cae6a2b 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -23,12 +23,13 @@ use crate::auth::{build_auth_config, OAuthParams}; use crate::executed_async::ExecutedAsyncStatement; use crate::metadata::Metadata; +use crate::runtime::KernelRuntime; use crate::statement::Statement; use databricks_sql_kernel::Session as KSession; use pyo3::prelude::*; use std::collections::HashMap; use std::sync::Arc; -use tokio::runtime::{Builder, Runtime}; +use tokio::runtime::Builder; /// Python-facing session handle. /// @@ -48,7 +49,7 @@ pub(crate) struct Session { pub(crate) struct SessionInner { pub(crate) session: KSession, - pub(crate) runtime: Arc, + pub(crate) runtime: Arc, } #[derive(Default)] @@ -586,7 +587,7 @@ impl Session { // One tokio runtime per session. Multi-thread so CloudFetch // chunk downloads can overlap with the main poll loop. Worker // count left to tokio's default (logical CPU count). - let runtime = Arc::new( + let runtime = Arc::new(KernelRuntime::new( Builder::new_multi_thread() .enable_all() .thread_name("dbx-sql-kernel") @@ -596,7 +597,7 @@ impl Session { "failed to build tokio runtime: {e}" )) })?, - ); + )); // `Session::open` is async and grabs the current tokio handle. // Drive it on the runtime; the macro detaches the GIL for the @@ -717,8 +718,9 @@ impl Session { target: crate::logging::PYO3_LOG_TARGET, "Session.close: closing kernel session (GIL released)" ); - run_kernel!(py, rt, session.close())?; - Ok(()) + let result = run_kernel!(py, rt, session.close()); + KernelRuntime::release(rt, py); + result } fn __repr__(&self) -> String { @@ -738,7 +740,7 @@ mod send_sync_tests { fn assert_send_sync() {} #[test] fn runtime_arc_is_send_sync() { - assert_send_sync::>(); + assert_send_sync::>(); assert_send_sync::(); } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 2b75eca6..7f2dc3e8 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -23,6 +23,7 @@ use crate::errors::to_py_err; use crate::executed_async::ExecutedAsyncStatement; use crate::fetch; use crate::params::parse_typed_value; +use crate::runtime::KernelRuntime; use arrow_pyarrow::ToPyArrow; use arrow_schema::Schema; use databricks_sql_kernel::{ @@ -32,7 +33,6 @@ use databricks_sql_kernel::{ use pyo3::prelude::*; use std::collections::HashMap; use std::sync::Arc; -use tokio::runtime::Runtime; /// Python-facing mutable statement. /// @@ -46,11 +46,11 @@ pub(crate) struct Statement { struct StatementInner { stmt: KStatement, - runtime: Arc, + runtime: Arc, } impl Statement { - pub(crate) fn new(stmt: KStatement, runtime: Arc) -> Self { + pub(crate) fn new(stmt: KStatement, runtime: Arc) -> Self { Self { inner: Some(StatementInner { stmt, runtime }), } @@ -270,8 +270,9 @@ impl Statement { // CancelStatement + CloseStatement against the tracked // executed handle), so we route it through the standard // py.detach + block_on path. - run_kernel!(py, runtime, stmt.close())?; - Ok(()) + let result = run_kernel!(py, runtime, stmt.close()); + KernelRuntime::release(runtime, py); + result } } @@ -296,12 +297,12 @@ pub(crate) struct ExecutedStatement { struct ExecutedInner { exec: KExecutedStatement, - runtime: Arc, + runtime: Arc, exhausted: bool, } impl ExecutedStatement { - fn new(exec: KExecutedStatement, runtime: Arc) -> Self { + fn new(exec: KExecutedStatement, runtime: Arc) -> Self { let statement_id = exec.statement_id().to_owned(); let schema = exec.schema(); let num_modified_rows = exec.num_modified_rows(); @@ -401,6 +402,7 @@ impl ExecutedStatement { // kernel's Drop impl runs fire-and-forget cleanup if close() // failed mid-flight. self.inner = None; + KernelRuntime::release(runtime, py); res.map(|_| ()) } @@ -427,7 +429,7 @@ impl ExecutedStatement { #[pyclass(name = "StatementCanceller")] pub(crate) struct StatementCanceller { inner: KStatementCanceller, - runtime: Arc, + runtime: Arc, } #[pymethods]