Repository navigation
fix(pyo3): don't wait for runtime workers when the last handle drops #388
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -40,6 +40,7 @@ mod logging; | |
| mod metadata; | ||
| mod params; | ||
| mod result_stream; | ||
| mod runtime; | ||
| mod session; | ||
| mod statement; | ||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[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" | ||
| ); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.