From 0c2c0355c11da0b095689d9b5adf64aaa5dc5f02 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 21:28:11 +0000 Subject: [PATCH 1/3] perf(python): cache the main-thread check per thread Statement.execute() asked Python's threading module whether it runs on the main thread on every call: four Python calls plus a gettid() with the GIL held (about 1-1.5 us per call, and 2% of the GIL-held samples in a live profile of 200 threads running SELECT 1). The answer only changes for a thread at fork(), so it is now cached per thread and recomputed after a fork, which a pthread_atfork child handler records. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/Cargo.lock | 1 + pyo3/Cargo.toml | 5 +++ pyo3/NEXT_CHANGELOG.md | 3 ++ pyo3/src/gil.rs | 91 +++++++++++++++++++++++++++++++++++++++++- pyo3/src/lib.rs | 1 + 5 files changed, 99 insertions(+), 2 deletions(-) diff --git a/pyo3/Cargo.lock b/pyo3/Cargo.lock index 30946d3c..3a38bb6b 100644 --- a/pyo3/Cargo.lock +++ b/pyo3/Cargo.lock @@ -654,6 +654,7 @@ dependencies = [ "arrow-schema", "chrono", "databricks-sql-kernel", + "libc", "log", "pyo3", "pyo3-log", diff --git a/pyo3/Cargo.toml b/pyo3/Cargo.toml index f8ee20dd..48feab00 100644 --- a/pyo3/Cargo.toml +++ b/pyo3/Cargo.toml @@ -97,3 +97,8 @@ chrono = "0.4" pyo3-log = "0.13" log = "0.4" tracing = "0.1" + +# `pthread_atfork`, to recompute the cached main-thread check in forked +# children (`gil::install_fork_handler`). +[target.'cfg(unix)'.dependencies] +libc = "0.2" diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 713efb4c..3a5b8805 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -20,6 +20,9 @@ changes go in the root `NEXT_CHANGELOG.md`. thread other than the main thread no longer re-acquires it every 100 ms to check for signals that only the main thread can receive. This cuts GIL hand-offs per query when many threads share the GIL. +- `Statement.execute()` remembers per thread whether it runs on the main + thread (recomputed after `fork()`) instead of asking `threading` on every + call. ### Updated diff --git a/pyo3/src/gil.rs b/pyo3/src/gil.rs index 27ca9daa..51788b36 100644 --- a/pyo3/src/gil.rs +++ b/pyo3/src/gil.rs @@ -22,12 +22,41 @@ use pyo3::prelude::*; use pyo3::sync::PyOnceLock; use pyo3::types::PyModule; +use std::cell::Cell; use std::future::Future; +use std::sync::atomic::{AtomicU64, Ordering}; use std::task::{Context, Poll, Waker}; use tokio::runtime::Runtime; static THREADING: PyOnceLock> = PyOnceLock::new(); +/// Incremented in the child after each `fork()`, where the forking thread +/// becomes the main thread, so answers cached before it are recomputed. +static FORK_GENERATION: AtomicU64 = AtomicU64::new(0); + +thread_local! { + /// This thread's `on_main_thread` answer and the fork generation it was + /// computed in. + static MAIN_THREAD: Cell> = const { Cell::new(None) }; +} + +/// Recompute cached `on_main_thread` answers in forked children. Called +/// once, at module import. +pub(crate) fn install_fork_handler() { + #[cfg(unix)] + { + extern "C" fn after_fork_in_child() { + FORK_GENERATION.fetch_add(1, Ordering::Relaxed); + } + static INSTALL: std::sync::Once = std::sync::Once::new(); + // SAFETY: registers a handler that only bumps an atomic, which is + // async-signal-safe as `fork()` requires of child handlers. + INSTALL.call_once(|| unsafe { + libc::pthread_atfork(None, None, Some(after_fork_in_child)); + }); + } +} + /// Whether the calling thread is Python's main thread, the only one that /// runs signal handlers. Errs towards `true` (a wrong `true` only keeps /// signal checks on). @@ -35,7 +64,16 @@ static THREADING: PyOnceLock> = PyOnceLock::new(); /// Either id may match: `threading` refreshes the main thread's `ident` /// after `fork()` but not its `native_id`, while greenlet libraries /// (gevent, eventlet) patch `get_ident` but not the OS-level `native_id`. +/// The answer only changes for a thread at `fork()`, so it is cached per +/// thread until the next one; asking `threading` costs a few Python calls +/// under the GIL on every `execute()`. pub(crate) fn on_main_thread(py: Python<'_>) -> bool { + let generation = FORK_GENERATION.load(Ordering::Relaxed); + if let Some((cached_generation, main)) = MAIN_THREAD.get() { + if cached_generation == generation { + return main; + } + } let check = || -> PyResult { let threading = THREADING .get_or_try_init(py, || py.import("threading").map(Bound::unbind))? @@ -51,7 +89,13 @@ pub(crate) fn on_main_thread(py: Python<'_>) -> bool { .call_method0("get_native_id")? .eq(main.getattr("native_id")?) }; - check().unwrap_or(true) + match check() { + Ok(main) => { + MAIN_THREAD.set(Some((generation, main))); + main + } + Err(_) => true, + } } /// Drive `fut` to completion, polling it once with the GIL held first and @@ -77,10 +121,53 @@ where #[cfg(test)] mod tests { - use super::run_ready_first; + use super::{on_main_thread, run_ready_first, FORK_GENERATION, MAIN_THREAD}; use pyo3::prelude::*; + use std::sync::atomic::Ordering; use std::time::Duration; + #[test] + fn main_thread_answer_is_cached_until_a_fork() { + Python::initialize(); + // `threading` takes the thread that imports it first as the main + // thread; the thread spawned below is never that one. + Python::attach(|py| py.import("threading").map(drop)).unwrap(); + std::thread::spawn(|| { + Python::attach(|py| { + assert!(!on_main_thread(py)); + let (generation, main) = MAIN_THREAD.get().expect("cached"); + assert!(!main); + // A stale answer from before a fork is recomputed. + MAIN_THREAD.set(Some((generation, true))); + assert!(on_main_thread(py)); + FORK_GENERATION.fetch_add(1, Ordering::Relaxed); + assert!(!on_main_thread(py)); + }) + }) + .join() + .unwrap(); + } + + #[cfg(unix)] + #[test] + fn forked_children_see_a_new_generation() { + super::install_fork_handler(); + let before = FORK_GENERATION.load(Ordering::Relaxed); + // SAFETY: the child only reads an atomic and exits. + match unsafe { libc::fork() } { + 0 => unsafe { + let bumped = FORK_GENERATION.load(Ordering::Relaxed) == before + 1; + libc::_exit(if bumped { 0 } else { 1 }) + }, + pid => { + let mut status = 0; + assert_eq!(unsafe { libc::waitpid(pid, &mut status, 0) }, pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); + assert!(FORK_GENERATION.load(Ordering::Relaxed) >= before); + } + } + } + fn runtime() -> tokio::runtime::Runtime { tokio::runtime::Builder::new_multi_thread() .worker_threads(1) diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index 0debe4fa..8a3f9cc3 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -99,5 +99,6 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { // Records still only surface once a customer raises the relevant // logger's level, so this default-on install is silent until asked. logging::init_logging(m.py()); + gil::install_fork_handler(); Ok(()) } From 6809ff12512e411a3dd095e322ade85a067a01b4 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:18:43 +0000 Subject: [PATCH 2/3] test(python): don't race the fork-generation test against the cache test Review feedback: both tests bump the shared counter, so the forked child now checks that it increased rather than that it rose by exactly one; the parent's assertion that could never fail is dropped. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/gil.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyo3/src/gil.rs b/pyo3/src/gil.rs index 51788b36..549057c9 100644 --- a/pyo3/src/gil.rs +++ b/pyo3/src/gil.rs @@ -156,14 +156,14 @@ mod tests { // SAFETY: the child only reads an atomic and exits. match unsafe { libc::fork() } { 0 => unsafe { - let bumped = FORK_GENERATION.load(Ordering::Relaxed) == before + 1; + // `>`: another test may bump the counter in parallel. + let bumped = FORK_GENERATION.load(Ordering::Relaxed) > before; libc::_exit(if bumped { 0 } else { 1 }) }, pid => { let mut status = 0; assert_eq!(unsafe { libc::waitpid(pid, &mut status, 0) }, pid); assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0); - assert!(FORK_GENERATION.load(Ordering::Relaxed) >= before); } } } From f9a3914b4a92551e5b2a40c972fc1f7a476527ff Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:22:33 +0000 Subject: [PATCH 3/3] fix(python): cache the main-thread check only when forks are tracked Review feedback: if pthread_atfork failed to register, a cached answer would outlive a fork, so a thread that became the child's main thread could skip signal checks. The cache is now used only after the handler registered (always on non-Unix platforms); otherwise every call asks threading, as before. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/gil.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/pyo3/src/gil.rs b/pyo3/src/gil.rs index 549057c9..fab06671 100644 --- a/pyo3/src/gil.rs +++ b/pyo3/src/gil.rs @@ -24,7 +24,7 @@ use pyo3::sync::PyOnceLock; use pyo3::types::PyModule; use std::cell::Cell; use std::future::Future; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::task::{Context, Poll, Waker}; use tokio::runtime::Runtime; @@ -40,8 +40,12 @@ thread_local! { static MAIN_THREAD: Cell> = const { Cell::new(None) }; } +/// Whether `on_main_thread` may cache: only once forks are tracked. +static CACHE_ENABLED: AtomicBool = AtomicBool::new(false); + /// Recompute cached `on_main_thread` answers in forked children. Called -/// once, at module import. +/// once, at module import. Without it (registration failed), every call +/// asks `threading`, as before caching. pub(crate) fn install_fork_handler() { #[cfg(unix)] { @@ -51,10 +55,14 @@ pub(crate) fn install_fork_handler() { static INSTALL: std::sync::Once = std::sync::Once::new(); // SAFETY: registers a handler that only bumps an atomic, which is // async-signal-safe as `fork()` requires of child handlers. - INSTALL.call_once(|| unsafe { - libc::pthread_atfork(None, None, Some(after_fork_in_child)); + INSTALL.call_once(|| { + if unsafe { libc::pthread_atfork(None, None, Some(after_fork_in_child)) } == 0 { + CACHE_ENABLED.store(true, Ordering::Relaxed); + } }); } + #[cfg(not(unix))] + CACHE_ENABLED.store(true, Ordering::Relaxed); } /// Whether the calling thread is Python's main thread, the only one that @@ -68,8 +76,9 @@ pub(crate) fn install_fork_handler() { /// thread until the next one; asking `threading` costs a few Python calls /// under the GIL on every `execute()`. pub(crate) fn on_main_thread(py: Python<'_>) -> bool { + let cache = CACHE_ENABLED.load(Ordering::Relaxed); let generation = FORK_GENERATION.load(Ordering::Relaxed); - if let Some((cached_generation, main)) = MAIN_THREAD.get() { + if let (true, Some((cached_generation, main))) = (cache, MAIN_THREAD.get()) { if cached_generation == generation { return main; } @@ -128,6 +137,8 @@ mod tests { #[test] fn main_thread_answer_is_cached_until_a_fork() { + super::install_fork_handler(); + assert!(super::CACHE_ENABLED.load(Ordering::Relaxed)); Python::initialize(); // `threading` takes the thread that imports it first as the main // thread; the thread spawned below is never that one.