From 3f14592a92ca0ea0bf5bb31a9b3b763bf6544957 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 7 Oct 2026 16:00:44 +0000 Subject: [PATCH 1/3] fix(pyo3): don't wait for runtime workers when the last handle drops Dropping the session's tokio runtime blocks until every worker thread exits, and the last reference is usually released with the GIL held: at the end of Session.close(), or when Python frees a handle. A worker forwarding a log record through pyo3_log waits for that same GIL, so the two deadlock and the process hangs. pytest-timeout can't fire either, since its timer thread also needs the GIL. Wrap the runtime in KernelRuntime, whose Drop calls shutdown_background() so releasing the last handle never waits on the workers. Pending tasks are cancelled as before. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 4 ++ pyo3/src/executed_async.rs | 6 +-- pyo3/src/lib.rs | 1 + pyo3/src/metadata.rs | 6 +-- pyo3/src/result_stream.rs | 6 +-- pyo3/src/runtime.rs | 87 ++++++++++++++++++++++++++++++++++++++ pyo3/src/session.rs | 11 ++--- pyo3/src/statement.rs | 12 +++--- 8 files changed, 113 insertions(+), 20 deletions(-) create mode 100644 pyo3/src/runtime.rs 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..b366fb57 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, 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/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..3161094d 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, diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs new file mode 100644 index 00000000..2e6b4df0 --- /dev/null +++ b/pyo3/src/runtime.rs @@ -0,0 +1,87 @@ +// 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 std::ops::Deref; +use tokio::runtime::Runtime; + +/// Tokio runtime that shuts down without waiting for its worker threads. +/// +/// The last `Arc` is usually released with the GIL held — at the end of +/// `Session.close()`, or when Python frees a handle. A plain `Runtime` +/// drop blocks until every worker exits, but a worker forwarding a log +/// record through `pyo3_log` is waiting for that same GIL, so the two +/// deadlock. `shutdown_background` returns immediately instead. +pub(crate) struct KernelRuntime(Option); + +impl KernelRuntime { + pub(crate) fn new(runtime: Runtime) -> Self { + Self(Some(runtime)) + } +} + +impl Deref for KernelRuntime { + type Target = Runtime; + + fn deref(&self) -> &Runtime { + self.0.as_ref().expect("runtime is only taken in Drop") + } +} + +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::mpsc; + use std::time::Duration; + + #[test] + fn drop_with_gil_held_does_not_wait_for_gil_blocked_worker() { + Python::initialize(); + let (done_tx, done_rx) = mpsc::channel(); + // Own thread so a regression fails the test instead of hanging it. + std::thread::spawn(move || { + Python::attach(|_py| { + let runtime = KernelRuntime::new( + tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .build() + .expect("build runtime"), + ); + let (started_tx, started_rx) = mpsc::channel(); + // Stands in for a worker forwarding a record via pyo3_log. + runtime.spawn(async move { + started_tx.send(()).expect("signal started"); + Python::attach(|_py| {}); + }); + started_rx.recv().expect("worker started"); + drop(runtime); + }); + done_tx.send(()).expect("signal done"); + }); + assert!( + done_rx.recv_timeout(Duration::from_secs(10)).is_ok(), + "dropping the runtime with the GIL held deadlocked on its worker" + ); + } +} diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 2b12dc9d..29a300ef 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 @@ -738,7 +739,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..3e124a92 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 }), } @@ -296,12 +296,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(); @@ -427,7 +427,7 @@ impl ExecutedStatement { #[pyclass(name = "StatementCanceller")] pub(crate) struct StatementCanceller { inner: KStatementCanceller, - runtime: Arc, + runtime: Arc, } #[pymethods] From b7fca84f976d5ba16917d42de6d79101c7226d27 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Wed, 7 Oct 2026 23:05:53 +0000 Subject: [PATCH 2/3] fix(pyo3): wait for runtime workers in Session.close() With shutdown_background() alone, close() can return while a worker is still forwarding a log record into Python. pyo3's finalization check is compiled out for abi3-py39, so a worker that attaches while the interpreter exits can crash it. When close() holds the last runtime handle, shut the runtime down with the GIL released and wait up to 1s for the workers. Drop keeps shutdown_background() for handles Python frees without close(). Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/runtime.rs | 24 +++++++++++++++++------- pyo3/src/session.rs | 9 +++++++-- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/pyo3/src/runtime.rs b/pyo3/src/runtime.rs index 2e6b4df0..9735081e 100644 --- a/pyo3/src/runtime.rs +++ b/pyo3/src/runtime.rs @@ -15,28 +15,38 @@ //! `KernelRuntime` — the session-owned tokio runtime. use std::ops::Deref; +use std::time::Duration; use tokio::runtime::Runtime; -/// Tokio runtime that shuts down without waiting for its worker threads. +/// Tokio runtime that never blocks on its workers while the GIL may be held. /// -/// The last `Arc` is usually released with the GIL held — at the end of -/// `Session.close()`, or when Python frees a handle. A plain `Runtime` -/// drop blocks until every worker exits, but a worker forwarding a log -/// record through `pyo3_log` is waiting for that same GIL, so the two -/// deadlock. `shutdown_background` returns immediately instead. +/// 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. `Session.close()` instead calls +/// [`shutdown_timeout`](Self::shutdown_timeout) with the GIL released. +/// `Drop` — reached when Python frees a handle — uses `shutdown_background`, +/// so workers may still run briefly after it returns. pub(crate) struct KernelRuntime(Option); impl KernelRuntime { pub(crate) fn new(runtime: Runtime) -> Self { Self(Some(runtime)) } + + /// Shut down, waiting up to `timeout` for the workers to exit. Call + /// with the GIL released: workers may need it to finish. + pub(crate) fn shutdown_timeout(mut self, timeout: Duration) { + if let Some(runtime) = self.0.take() { + runtime.shutdown_timeout(timeout); + } + } } impl Deref for KernelRuntime { type Target = Runtime; fn deref(&self) -> &Runtime { - self.0.as_ref().expect("runtime is only taken in Drop") + self.0.as_ref().expect("runtime is only taken on shutdown") } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index 29a300ef..ac4bab36 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -718,8 +718,13 @@ 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()); + // Last handle: wait for the workers so none is still logging into + // Python after close() returns (e.g. while the interpreter exits). + if let Ok(rt) = Arc::try_unwrap(rt) { + py.detach(|| rt.shutdown_timeout(std::time::Duration::from_secs(1))); + } + result } fn __repr__(&self) -> String { From 42965f04997845c4bd426184f605f2eca303c13b Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Thu, 8 Oct 2026 07:03:29 +0000 Subject: [PATCH 3/3] fix(pyo3): address review on runtime shutdown Route every explicit close() through KernelRuntime::release(), so whichever handle drops the last runtime reference waits for the workers with the GIL released, including when close() fails. The wait is capped by a named CLOSE_SHUTDOWN_TIMEOUT, since shutdown also waits on blocking-pool work such as the OAuth refresh. For handles Python frees without close(), Drop still doesn't wait. An atexit hook now makes the log bridge drop records once the interpreter starts exiting, so a lingering worker can't attach to a finalizing interpreter (pyo3's guard for that is compiled out under abi3-py39). Also note that handle structs must declare the kernel object before the runtime, and add tests for release() and the exit guard. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/executed_async.rs | 1 + pyo3/src/logging.rs | 86 +++++++++++++++++++++++++++--- pyo3/src/result_stream.rs | 3 +- pyo3/src/runtime.rs | 105 ++++++++++++++++++++++++++----------- pyo3/src/session.rs | 6 +-- pyo3/src/statement.rs | 6 ++- 6 files changed, 162 insertions(+), 45 deletions(-) diff --git a/pyo3/src/executed_async.rs b/pyo3/src/executed_async.rs index b366fb57..1189c9db 100644 --- a/pyo3/src/executed_async.rs +++ b/pyo3/src/executed_async.rs @@ -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/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/result_stream.rs b/pyo3/src/result_stream.rs index 3161094d..cd193bb9 100644 --- a/pyo3/src/result_stream.rs +++ b/pyo3/src/result_stream.rs @@ -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 index 9735081e..a443b7c2 100644 --- a/pyo3/src/runtime.rs +++ b/pyo3/src/runtime.rs @@ -14,18 +14,28 @@ //! `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. `Session.close()` instead calls -/// [`shutdown_timeout`](Self::shutdown_timeout) with the GIL released. +/// 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 { @@ -33,11 +43,14 @@ impl KernelRuntime { Self(Some(runtime)) } - /// Shut down, waiting up to `timeout` for the workers to exit. Call - /// with the GIL released: workers may need it to finish. - pub(crate) fn shutdown_timeout(mut self, timeout: Duration) { - if let Some(runtime) = self.0.take() { - runtime.shutdown_timeout(timeout); + /// 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)); + } } } } @@ -62,36 +75,68 @@ impl Drop for KernelRuntime { mod tests { use super::KernelRuntime; use pyo3::prelude::*; - use std::sync::mpsc; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{mpsc, Arc}; use std::time::Duration; - #[test] - fn drop_with_gil_held_does_not_wait_for_gil_blocked_worker() { + /// 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(); - // Own thread so a regression fails the test instead of hanging it. std::thread::spawn(move || { - Python::attach(|_py| { - let runtime = KernelRuntime::new( - tokio::runtime::Builder::new_multi_thread() - .worker_threads(1) - .build() - .expect("build runtime"), - ); - let (started_tx, started_rx) = mpsc::channel(); - // Stands in for a worker forwarding a record via pyo3_log. - runtime.spawn(async move { - started_tx.send(()).expect("signal started"); - Python::attach(|_py| {}); - }); - started_rx.recv().expect("worker started"); - drop(runtime); - }); - done_tx.send(()).expect("signal done"); + 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!( - done_rx.recv_timeout(Duration::from_secs(10)).is_ok(), - "dropping the runtime with the GIL held deadlocked on its worker" + finished_at_return, + "release() returned before the worker finished" ); } } diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index ac4bab36..4cae6a2b 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -719,11 +719,7 @@ impl Session { "Session.close: closing kernel session (GIL released)" ); let result = run_kernel!(py, rt, session.close()); - // Last handle: wait for the workers so none is still logging into - // Python after close() returns (e.g. while the interpreter exits). - if let Ok(rt) = Arc::try_unwrap(rt) { - py.detach(|| rt.shutdown_timeout(std::time::Duration::from_secs(1))); - } + KernelRuntime::release(rt, py); result } diff --git a/pyo3/src/statement.rs b/pyo3/src/statement.rs index 3e124a92..7f2dc3e8 100644 --- a/pyo3/src/statement.rs +++ b/pyo3/src/statement.rs @@ -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 } } @@ -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(|_| ()) }