From cf2ba0d4706ad11e77fb716ce8a1563bed4b6b20 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 22:47:27 +0000 Subject: [PATCH 1/9] perf(python): drop log records below the Python loggers' level before pyo3_log The log bridge set log::max_level to Trace, so every tracing event and span enter/exit from the kernel and its HTTP stack built a log::Record and went through pyo3_log's per-target lookup (string split and hashing) before being dropped. Some of these run on the Python thread with the GIL held. The max level is now the most verbose level any Python logger accepts, read from the root logger and every existing logger (and logging.disable()). It is recomputed at install, on Session construction and by reset_logging(), so levels set before connecting apply without reset_logging(). Session construction also clears pyo3_log's cache when any level changed, so a logger cached at its old level no longer drops newly enabled records. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/lib.rs | 11 +-- pyo3/src/logging.rs | 170 ++++++++++++++++++++++++++++++++----- pyo3/src/session.rs | 2 + pyo3/tests/test_logging.py | 90 ++++++++++++++++++++ 4 files changed, 249 insertions(+), 24 deletions(-) create mode 100644 pyo3/tests/test_logging.py diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index f42ffa85..a2601820 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -67,12 +67,13 @@ fn init_logging(py: Python<'_>) -> bool { logging::init_logging(py) } -/// Clear cached logger levels so a Python-side logging reconfiguration -/// applied *after* the first kernel log (e.g. raising -/// `databricks.sql.kernel` to DEBUG mid-session) takes effect. +/// Re-read the Python logger levels and clear cached ones so a Python-side +/// logging reconfiguration applied *after* the first kernel log (e.g. +/// raising `databricks.sql.kernel` to DEBUG mid-session) takes effect. +/// Levels set before a `Session` is created apply without this call. #[pyfunction] -fn reset_logging() { - logging::reset_logging(); +fn reset_logging(py: Python<'_>) { + logging::reset_logging(py); } #[pymodule] diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 0271f276..cc917a5a 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -42,20 +42,25 @@ //! Kernel events fire on tokio worker threads with the GIL released //! (see `run_kernel!`). `pyo3_log` re-acquires the GIL per surviving //! record, so we must drop below-threshold events *before* that -//! boundary. Two cheap gates do this: the global `log::max_level` -//! (set by `pyo3_log` from the Python loggers' effective levels) and -//! `pyo3_log`'s per-logger level cache. The customer's single knob +//! boundary. Two cheap gates do this: the global `log::max_level`, set +//! here to the most verbose level any Python logger accepts (see +//! `PythonLevels`), and `pyo3_log`'s per-logger level cache. The +//! first gate is an atomic compare inside the `log` and `tracing` macros, +//! so a record (or span enter/exit) below every logger's level is dropped +//! before it is built or reaches `pyo3_log`. The customer's single knob //! (`setLevel`) drives both — there is no separate Rust-side level //! argument. //! //! ## Reconfiguration //! -//! `pyo3_log` caches logger objects and their levels on first use. If a -//! customer changes levels *after* the first kernel log (e.g. raises a -//! logger to DEBUG mid-session), call [`reset_logging`] to clear the -//! 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. +//! The max level is recomputed at install, on every `Session` +//! construction ([`refresh_max_level`], which also clears `pyo3_log`'s +//! cache when a level changed) and by [`reset_logging`], so levels set +//! before connecting take effect on their own. `pyo3_log` caches logger +//! objects and their levels on first use. If a customer changes levels on +//! an open session (e.g. raises a logger to DEBUG mid-session), call +//! [`reset_logging`] to recompute the max level and clear the cache so +//! the new level takes effect. //! //! ## Interpreter exit //! @@ -68,7 +73,9 @@ use pyo3::prelude::*; use pyo3_log::{Caching, Logger, ResetHandle}; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Mutex, OnceLock}; /// Logger target the kernel tags every event with. Maps to the Python @@ -208,12 +215,14 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { .filter(log::LevelFilter::Trace) .filter_target(KERNEL_TARGET.to_owned(), log::LevelFilter::Trace); - // What `Logger::install()` does, but behind `ExitGuard`. `Trace` is the - // highest filter set above. + // What `Logger::install()` does, but behind `ExitGuard`, and with the max + // level taken from the Python loggers instead of the `Trace` filter above. let handle = logger.reset_handle(); match log::set_boxed_logger(Box::new(ExitGuard(logger))) { Ok(()) => { - log::set_max_level(log::LevelFilter::Trace); + let levels = PythonLevels::read(py); + log::set_max_level(levels.max_level); + LEVELS_FINGERPRINT.store(levels.fingerprint, Ordering::Relaxed); // Best effort: without the hook, records still flow until exit. let _ = register_exit_hook(py); *state = LogState::Installed(handle); @@ -232,21 +241,144 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { } } -/// Clear `pyo3_log`'s logger/level caches so a Python-side logging -/// reconfiguration (e.g. a `setLevel` call after the first kernel log) -/// takes effect. No-op if logging was never installed. Never panics. -pub(crate) fn reset_logging() { +/// Recompute the max level and clear `pyo3_log`'s logger/level caches so a +/// Python-side logging reconfiguration (e.g. a `setLevel` call after the +/// first kernel log) takes effect. No-op if logging was never installed. +/// Never panics. +pub(crate) fn reset_logging(py: Python<'_>) { + if !is_installed() { + return; + } + let levels = PythonLevels::read(py); + log::set_max_level(levels.max_level); + LEVELS_FINGERPRINT.store(levels.fingerprint, Ordering::Relaxed); if let LogState::Installed(handle) = &*lock_state() { handle.reset(); } } +/// Recompute the max level from the Python loggers. Called when a `Session` +/// is created, so levels a customer sets before connecting apply without +/// [`reset_logging`]. If any logger's level changed since the last read, +/// `pyo3_log`'s cache is cleared too: a logger it cached at the old level +/// would otherwise keep dropping newly enabled records. No-op if logging +/// was never installed. +pub(crate) fn refresh_max_level(py: Python<'_>) { + if !is_installed() { + return; + } + let levels = PythonLevels::read(py); + if LEVELS_FINGERPRINT.swap(levels.fingerprint, Ordering::Relaxed) != levels.fingerprint { + if let LogState::Installed(handle) = &*lock_state() { + handle.reset(); + } + } + log::set_max_level(levels.max_level); +} + +fn is_installed() -> bool { + matches!(*lock_state(), LogState::Installed(_)) +} + +/// Fingerprint of the Python logger levels last applied to `log::max_level`. +static LEVELS_FINGERPRINT: AtomicU64 = AtomicU64::new(0); + +struct PythonLevels { + /// The most verbose `log` level any Python logger currently accepts. + max_level: log::LevelFilter, + /// Changes whenever a logger is added or its effective level changes. + fingerprint: u64, +} + +impl PythonLevels { + /// Read the levels of the root logger and every existing logger. A + /// logger nobody has created yet inherits its nearest existing + /// ancestor's level, so these bound what `pyo3_log` could forward; + /// Python's `logging.disable()` raises the bound further. If the + /// loggers can't be read, falls back to `Trace` (forward everything to + /// `pyo3_log`, the previous behaviour). + fn read(py: Python<'_>) -> Self { + let read = || -> PyResult { + let logging = py.import("logging")?; + let root = logging.getattr("root")?; + let manager = root.getattr("manager")?; + let logger_type = logging.getattr("Logger")?; + let mut hasher = DefaultHasher::new(); + let mut lowest: i64 = root.call_method0("getEffectiveLevel")?.extract()?; + lowest.hash(&mut hasher); + // Snapshot the values: another thread may create a logger meanwhile. + let loggers = py + .import("builtins")? + .getattr("list")? + .call1((manager.getattr("loggerDict")?.call_method0("values")?,))?; + for logger in loggers.try_iter()? { + let logger = logger?; + // `loggerDict` also holds `PlaceHolder`s for unnamed parents. + if logger.is_instance(&logger_type)? { + let level: i64 = logger.call_method0("getEffectiveLevel")?.extract()?; + (logger.as_ptr() as usize, level).hash(&mut hasher); + lowest = lowest.min(level); + } + } + let disabled_up_to: i64 = manager.getattr("disable")?.extract()?; + disabled_up_to.hash(&mut hasher); + Ok(Self { + max_level: level_filter_for_python_threshold(lowest.max(disabled_up_to + 1)), + fingerprint: hasher.finish(), + }) + }; + read().unwrap_or(Self { + max_level: log::LevelFilter::Trace, + fingerprint: 0, + }) + } +} + +/// The most verbose `log` level whose Python level (as `pyo3_log` maps +/// them: Trace 5, Debug 10, Info 20, Warn 30, Error 40) is at or above a +/// Python logger threshold. +fn level_filter_for_python_threshold(threshold: i64) -> log::LevelFilter { + match threshold { + t if t <= 5 => log::LevelFilter::Trace, + t if t <= 10 => log::LevelFilter::Debug, + t if t <= 20 => log::LevelFilter::Info, + t if t <= 30 => log::LevelFilter::Warn, + t if t <= 40 => log::LevelFilter::Error, + _ => log::LevelFilter::Off, + } +} + #[cfg(test)] mod tests { - use super::{mark_interpreter_exiting, ExitGuard, KERNEL_TARGET}; - use log::Log; + use super::{ + level_filter_for_python_threshold, mark_interpreter_exiting, ExitGuard, KERNEL_TARGET, + }; + use log::{LevelFilter, Log}; use std::sync::atomic::{AtomicUsize, Ordering}; + #[test] + fn python_thresholds_map_to_the_levels_pyo3_log_forwards() { + // pyo3_log maps Trace/Debug/Info/Warn/Error to Python 5/10/20/30/40. + for (threshold, expected) in [ + (0, LevelFilter::Trace), // NOTSET on the root: everything + (5, LevelFilter::Trace), + (6, LevelFilter::Debug), + (10, LevelFilter::Debug), // DEBUG + (15, LevelFilter::Info), + (20, LevelFilter::Info), // INFO + (30, LevelFilter::Warn), // WARNING, the default + (40, LevelFilter::Error), + (41, LevelFilter::Off), + (51, LevelFilter::Off), // logging.disable(CRITICAL) + ] { + assert_eq!( + level_filter_for_python_threshold(threshold), + expected, + "threshold {threshold}" + ); + } + } + #[test] fn exit_guard_drops_records_once_interpreter_exits() { struct Count(AtomicUsize); diff --git a/pyo3/src/session.rs b/pyo3/src/session.rs index c626ee89..41d0252b 100644 --- a/pyo3/src/session.rs +++ b/pyo3/src/session.rs @@ -478,6 +478,8 @@ impl Session { telemetry_circuit_breaker_threshold: Option, telemetry_circuit_breaker_timeout_ms: Option, ) -> PyResult { + // Pick up logger levels set since the bridge was installed. + crate::logging::refresh_max_level(py); // Resolve auth_type. Explicit `auth_type` always wins. When // omitted, default to "pat" if `access_token` was passed // (back-compat for existing PAT callers). A bare diff --git a/pyo3/tests/test_logging.py b/pyo3/tests/test_logging.py new file mode 100644 index 00000000..60105ddc --- /dev/null +++ b/pyo3/tests/test_logging.py @@ -0,0 +1,90 @@ +# 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. + +"""Kernel records reach Python ``logging`` at the levels set there. + +No network: ``Session`` without credentials raises before any I/O, after a +DEBUG breadcrumb on ``databricks.sql.kernel.pyo3``. +""" + +from __future__ import annotations + +import logging + +import pytest + +import databricks_sql_kernel as k + +KERNEL_LOGGER = "databricks.sql.kernel" +REJECTED = "Session.__new__ rejected" + + +def _reject_session() -> None: + with pytest.raises(ValueError): + k.Session(host="example.invalid", http_path="/sql/1.0/warehouses/x") + + +def _breadcrumbs(caplog) -> list: + return [ + r + for r in caplog.records + if r.name.startswith(KERNEL_LOGGER) and REJECTED in r.getMessage() + ] + + +@pytest.fixture(autouse=True) +def _restore_levels(): + yield + k.reset_logging() + + +def test_debug_set_after_import_reaches_python(caplog): + # The bridge was installed at import, before this level was set. + with caplog.at_level(logging.DEBUG, logger=KERNEL_LOGGER): + _reject_session() + (record,) = _breadcrumbs(caplog) + assert record.name == "databricks.sql.kernel.pyo3" + assert record.levelno == logging.DEBUG + + +def test_records_below_the_level_are_not_forwarded(caplog): + with caplog.at_level(logging.WARNING, logger=KERNEL_LOGGER): + k.reset_logging() + _reject_session() + assert not _breadcrumbs(caplog) + + +def test_new_session_picks_up_a_level_changed_after_caching(caplog): + # Another logger at DEBUG keeps the max level at Debug, so the + # breadcrumb reaches pyo3_log and is cached at the kernel logger's + # WARNING level without being forwarded. + other = logging.getLogger("test_logging.unrelated") + other.setLevel(logging.DEBUG) + try: + with caplog.at_level(logging.WARNING, logger=KERNEL_LOGGER): + k.reset_logging() + _reject_session() + assert not _breadcrumbs(caplog) + # Raising the kernel logger leaves the max level unchanged; the new + # Session still has to drop the stale cache entry. + with caplog.at_level(logging.DEBUG, logger=KERNEL_LOGGER): + _reject_session() + assert len(_breadcrumbs(caplog)) == 1 + finally: + other.setLevel(logging.NOTSET) + + +def test_reset_logging_is_safe_to_call_repeatedly(): + k.reset_logging() + k.reset_logging() From e02bf496d292c23c141d4bf5364626545ea7b276 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:04:42 +0000 Subject: [PATCH 2/9] docs(python): note the log-level change in NEXT_CHANGELOG Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index e0881e54..7046143a 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,6 +14,7 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added ### Changed +- Log records below every Python logger's level are now dropped before they reach the Python logging bridge, which cuts client CPU per query. Levels set before a `Session` is created take effect without `reset_logging()`. ### Updated From a5c47dab15ed89a61b183df6cdb4265ca6b5671a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:29:31 +0000 Subject: [PATCH 3/9] fix(python): order concurrent level reads; skip the logger walk when nothing changed Review follow-ups for the log-level change: - Reads run Python code, so a Session() read could be overtaken by a setLevel() + reset_logging() on another thread and then overwrite the newer level. Each read now takes a ticket, and a read older than the last applied one isn't applied; the store happens under a small mutex that never calls Python. init_logging reads before taking its install lock, and refresh/reset use the reset handle without that lock. - Session construction walked every logger. logging clears each logger's _cache on setLevel() and logging.disable(), so the read now fills a probe logger's cache first, and Session construction skips the walk while that cache is still filled: 1.3 us per Session() with 2,045 loggers, against 276 us for the walk (0.7 us before this change). - A Rust test runs PythonLevels::read and the change detection against an embedded interpreter: Warn by default, Debug after setLevel(DEBUG), Off under logging.disable(CRITICAL), Trace with the root at NOTSET. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/logging.rs | 167 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 130 insertions(+), 37 deletions(-) diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index cc917a5a..36aecc5b 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -94,24 +94,23 @@ use databricks_sql_kernel::KERNEL_LOG_TARGET as KERNEL_TARGET; /// customer can isolate boundary logs from core kernel logs by name. pub(crate) const PYO3_LOG_TARGET: &str = "databricks::sql::kernel::pyo3"; -/// One-time install state. Tristate (rather than `Option`) -/// so a *failed* install is sticky: we don't retry `Logger::install()` -/// — which re-walks construction + the global-logger set — on every -/// subsequent `init_logging` call. +/// One-time install state. Tristate so a *failed* install is sticky: we +/// don't retry `Logger::install()` — which re-walks construction + the +/// global-logger set — on every subsequent `init_logging` call. The +/// installed bridge's reset handle is kept in [`RESET_HANDLE`]. enum LogState { /// No install attempted yet. NotInstalled, - /// Installed; handle retained for [`reset_logging`]. - Installed(ResetHandle), + /// Installed. + Installed, /// Install was attempted and failed (or `Logger` construction /// failed). Sticky — we won't try again this process. Failed, } -/// Holds the install state so [`reset_logging`] can reach the -/// `ResetHandle` and repeated `init_logging` calls stay cheap. `Mutex` -/// poisoning is handled (`into_inner`) rather than `unwrap`-panicked — -/// a logging helper must never take down the process. +/// Holds the install state so repeated `init_logging` calls stay cheap. +/// `Mutex` poisoning is handled (`into_inner`) rather than +/// `unwrap`-panicked — a logging helper must never take down the process. static LOG_STATE: OnceLock> = OnceLock::new(); /// Lock the state, recovering the guard if a previous holder panicked @@ -183,6 +182,13 @@ impl log::Log for ExitGuard { /// failed, or another global `log` logger is already set). Never panics: /// a logging helper must not be able to tear down the host process. pub(crate) fn init_logging(py: Python<'_>) -> bool { + if RESET_HANDLE.get().is_some() { + return false; + } + // Read the levels before taking the install lock: the read runs Python + // code, during which another thread may take the GIL and then block on + // that lock. + let levels = PythonLevels::read(py); let mut state = lock_state(); // Already installed, or a prior attempt failed — don't retry. Retry // would re-run `Logger::install()`'s global-logger set, which is not @@ -220,12 +226,11 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { let handle = logger.reset_handle(); match log::set_boxed_logger(Box::new(ExitGuard(logger))) { Ok(()) => { - let levels = PythonLevels::read(py); - log::set_max_level(levels.max_level); - LEVELS_FINGERPRINT.store(levels.fingerprint, Ordering::Relaxed); + let _ = RESET_HANDLE.set(handle); + apply(levels, false); // Best effort: without the hook, records still flow until exit. let _ = register_exit_hook(py); - *state = LogState::Installed(handle); + *state = LogState::Installed; true } Err(_) => { @@ -246,14 +251,8 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { /// first kernel log) takes effect. No-op if logging was never installed. /// Never panics. pub(crate) fn reset_logging(py: Python<'_>) { - if !is_installed() { - return; - } - let levels = PythonLevels::read(py); - log::set_max_level(levels.max_level); - LEVELS_FINGERPRINT.store(levels.fingerprint, Ordering::Relaxed); - if let LogState::Installed(handle) = &*lock_state() { - handle.reset(); + if RESET_HANDLE.get().is_some() { + apply(PythonLevels::read(py), true); } } @@ -261,29 +260,71 @@ pub(crate) fn reset_logging(py: Python<'_>) { /// is created, so levels a customer sets before connecting apply without /// [`reset_logging`]. If any logger's level changed since the last read, /// `pyo3_log`'s cache is cleared too: a logger it cached at the old level -/// would otherwise keep dropping newly enabled records. No-op if logging -/// was never installed. +/// would otherwise keep dropping newly enabled records. When no level +/// changed, this costs one attribute read. No-op if logging was never +/// installed. pub(crate) fn refresh_max_level(py: Python<'_>) { - if !is_installed() { + if RESET_HANDLE.get().is_some() && !levels_unchanged(py) { + apply(PythonLevels::read(py), false); + } +} + +/// `pyo3_log`'s reset handle, set once the bridge is installed. +static RESET_HANDLE: OnceLock = OnceLock::new(); + +/// Orders level reads: each takes a ticket before it reads. +static NEXT_READ: AtomicU64 = AtomicU64::new(0); + +/// The ticket and fingerprint of the last applied read. +static APPLIED: Mutex<(u64, u64)> = Mutex::new((0, 0)); + +/// Set `log::max_level` from `levels`, and clear `pyo3_log`'s cache if the +/// levels changed or `reset` is set. +/// +/// Reads run Python code, so a read can be interrupted by a thread that +/// changes a level and applies its own read. A read that started earlier +/// than the last applied one is therefore not applied: the later read saw +/// at least as recent a configuration. Nothing in here calls Python, so +/// holding `APPLIED` can't deadlock with the GIL. +fn apply(levels: PythonLevels, reset: bool) { + let Some(handle) = RESET_HANDLE.get() else { return; + }; + let mut applied = APPLIED.lock().unwrap_or_else(|p| p.into_inner()); + let (applied_ticket, applied_fingerprint) = *applied; + let mut changed = false; + if levels.ticket > applied_ticket { + changed = levels.fingerprint != applied_fingerprint; + *applied = (levels.ticket, levels.fingerprint); + log::set_max_level(levels.max_level); } - let levels = PythonLevels::read(py); - if LEVELS_FINGERPRINT.swap(levels.fingerprint, Ordering::Relaxed) != levels.fingerprint { - if let LogState::Installed(handle) = &*lock_state() { - handle.reset(); - } + if reset || changed { + handle.reset(); } - log::set_max_level(levels.max_level); } -fn is_installed() -> bool { - matches!(*lock_state(), LogState::Installed(_)) -} +/// Name of a logger used only to detect level changes; see +/// [`levels_unchanged`]. +const LEVELS_PROBE: &str = "databricks.sql.kernel._levels_probe"; -/// Fingerprint of the Python logger levels last applied to `log::max_level`. -static LEVELS_FINGERPRINT: AtomicU64 = AtomicU64::new(0); +/// Whether no Python logger level changed since the last read. +/// +/// `logging` clears every logger's `_cache` on `setLevel()` and +/// `logging.disable()`. [`PythonLevels::read`] fills the probe logger's +/// cache before it reads, so a still-filled cache means nothing changed. +/// Errs towards `false` (do the full read). +fn levels_unchanged(py: Python<'_>) -> bool { + let check = || -> PyResult { + let probe = py + .import("logging")? + .call_method1("getLogger", (LEVELS_PROBE,))?; + Ok(probe.getattr("_cache")?.len()? > 0) + }; + check().unwrap_or(false) +} struct PythonLevels { + ticket: u64, /// The most verbose `log` level any Python logger currently accepts. max_level: log::LevelFilter, /// Changes whenever a logger is added or its effective level changes. @@ -298,8 +339,14 @@ impl PythonLevels { /// loggers can't be read, falls back to `Trace` (forward everything to /// `pyo3_log`, the previous behaviour). fn read(py: Python<'_>) -> Self { + let ticket = NEXT_READ.fetch_add(1, Ordering::Relaxed) + 1; let read = || -> PyResult { let logging = py.import("logging")?; + // Fill the probe's cache first, so a level changed during the read + // empties it again and the next refresh reads anew. + logging + .call_method1("getLogger", (LEVELS_PROBE,))? + .call_method1("isEnabledFor", (50,))?; let root = logging.getattr("root")?; let manager = root.getattr("manager")?; let logger_type = logging.getattr("Logger")?; @@ -323,11 +370,13 @@ impl PythonLevels { let disabled_up_to: i64 = manager.getattr("disable")?.extract()?; disabled_up_to.hash(&mut hasher); Ok(Self { + ticket, max_level: level_filter_for_python_threshold(lowest.max(disabled_up_to + 1)), fingerprint: hasher.finish(), }) }; read().unwrap_or(Self { + ticket, max_level: log::LevelFilter::Trace, fingerprint: 0, }) @@ -351,11 +400,55 @@ fn level_filter_for_python_threshold(threshold: i64) -> log::LevelFilter { #[cfg(test)] mod tests { use super::{ - level_filter_for_python_threshold, mark_interpreter_exiting, ExitGuard, KERNEL_TARGET, + level_filter_for_python_threshold, levels_unchanged, mark_interpreter_exiting, ExitGuard, + PythonLevels, KERNEL_TARGET, }; use log::{LevelFilter, Log}; + use pyo3::prelude::*; + use pyo3::types::PyDict; + use std::ffi::CString; use std::sync::atomic::{AtomicUsize, Ordering}; + // One test, since Python's logging configuration is process-wide. + #[test] + fn reads_python_levels_and_detects_changes() { + Python::initialize(); + Python::attach(|py| { + let globals = PyDict::new(py); + let run = |code: &str| { + py.run(&CString::new(code).unwrap(), Some(&globals), None) + .unwrap() + }; + run("import logging\nlogging.root.setLevel(logging.WARNING)\nchild = logging.getLogger('kernel_logging_test.child')"); + + let levels = PythonLevels::read(py); + assert_eq!(levels.max_level, LevelFilter::Warn); + assert!(levels_unchanged(py), "nothing changed since the read"); + let tickets = levels.ticket; + + run("child.setLevel(logging.DEBUG)"); + assert!(!levels_unchanged(py), "setLevel must be detected"); + let levels = PythonLevels::read(py); + assert_eq!(levels.max_level, LevelFilter::Debug); + assert!(levels.ticket > tickets, "each read takes a later ticket"); + assert!(levels_unchanged(py)); + + run("logging.disable(logging.CRITICAL)"); + assert!(!levels_unchanged(py), "logging.disable must be detected"); + assert_eq!(PythonLevels::read(py).max_level, LevelFilter::Off); + + run("logging.disable(logging.NOTSET)\nchild.setLevel(logging.NOTSET)\nlogging.root.setLevel(logging.NOTSET)"); + assert_eq!(PythonLevels::read(py).max_level, LevelFilter::Trace); + + // A new logger with no level of its own changes nothing. + run("logging.root.setLevel(logging.WARNING)"); + let before = PythonLevels::read(py).max_level; + run("logging.getLogger('kernel_logging_test.other')"); + assert!(levels_unchanged(py)); + assert_eq!(PythonLevels::read(py).max_level, before); + }); + } + #[test] fn python_thresholds_map_to_the_levels_pyo3_log_forwards() { // pyo3_log maps Trace/Debug/Info/Warn/Error to Python 5/10/20/30/40. From 3e61c7817edf7d4629716fc50fef8a09741ef359 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:37:27 +0000 Subject: [PATCH 4/9] fix(python): keep the level probe enabled; test apply's ordering and the gate - dictConfig() and fileConfig() disable existing loggers by default, and a disabled logger never refills its level cache, so change detection would stop working and every Session() would walk all loggers. The read now re-enables the probe (it emits nothing) before filling it. - The ordering and reset decisions in apply() are a pure helper, decide(), with a unit test: stale tickets dropped, the cache cleared only on a fingerprint change or reset_logging(), an overtaken reset_logging() still clearing it. - A private _log_max_level() lets the Python tests assert the gate itself: WARN at the default levels, DEBUG once a Session() sees a DEBUG logger. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/lib.rs | 8 +++ pyo3/src/logging.rs | 102 ++++++++++++++++++++++++++++++++----- pyo3/tests/test_logging.py | 7 ++- 3 files changed, 103 insertions(+), 14 deletions(-) diff --git a/pyo3/src/lib.rs b/pyo3/src/lib.rs index a2601820..4258e337 100644 --- a/pyo3/src/lib.rs +++ b/pyo3/src/lib.rs @@ -76,6 +76,13 @@ fn reset_logging(py: Python<'_>) { logging::reset_logging(py); } +/// The level below which kernel log records are dropped before reaching +/// Python (`"WARN"`, `"DEBUG"`, ...). Private; for tests. +#[pyfunction] +fn _log_max_level() -> &'static str { + logging::max_level_name() +} + #[pymodule] fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add("__version__", env!("CARGO_PKG_VERSION"))?; @@ -90,6 +97,7 @@ fn databricks_sql_kernel(m: &Bound<'_, PyModule>) -> PyResult<()> { m.add_class::()?; m.add_function(wrap_pyfunction!(init_logging, m)?)?; m.add_function(wrap_pyfunction!(reset_logging, m)?)?; + m.add_function(wrap_pyfunction!(_log_max_level, m)?)?; // Install the log bridge at module import so *any* consumer of the // bare wheel (the connector, integration tests, custom embedders) diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 36aecc5b..7a845f4f 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -291,18 +291,46 @@ fn apply(levels: PythonLevels, reset: bool) { return; }; let mut applied = APPLIED.lock().unwrap_or_else(|p| p.into_inner()); - let (applied_ticket, applied_fingerprint) = *applied; - let mut changed = false; - if levels.ticket > applied_ticket { - changed = levels.fingerprint != applied_fingerprint; - *applied = (levels.ticket, levels.fingerprint); - log::set_max_level(levels.max_level); + let (set_level, clear_cache) = decide(&mut applied, &levels, reset); + if let Some(level) = set_level { + log::set_max_level(level); } - if reset || changed { + if clear_cache { handle.reset(); } } +/// What [`apply`] does for `levels`, given the `(ticket, fingerprint)` of +/// the last applied read (updated in place): the max level to set, if +/// any, and whether to clear `pyo3_log`'s cache. +fn decide( + applied: &mut (u64, u64), + levels: &PythonLevels, + reset: bool, +) -> (Option, bool) { + let (applied_ticket, applied_fingerprint) = *applied; + if levels.ticket <= applied_ticket { + return (None, reset); + } + *applied = (levels.ticket, levels.fingerprint); + ( + Some(levels.max_level), + reset || levels.fingerprint != applied_fingerprint, + ) +} + +/// The current `log::max_level`, for tests. +pub(crate) fn max_level_name() -> &'static str { + match log::max_level() { + log::LevelFilter::Off => "OFF", + log::LevelFilter::Error => "ERROR", + log::LevelFilter::Warn => "WARN", + log::LevelFilter::Info => "INFO", + log::LevelFilter::Debug => "DEBUG", + log::LevelFilter::Trace => "TRACE", + } +} + /// Name of a logger used only to detect level changes; see /// [`levels_unchanged`]. const LEVELS_PROBE: &str = "databricks.sql.kernel._levels_probe"; @@ -343,10 +371,13 @@ impl PythonLevels { let read = || -> PyResult { let logging = py.import("logging")?; // Fill the probe's cache first, so a level changed during the read - // empties it again and the next refresh reads anew. - logging - .call_method1("getLogger", (LEVELS_PROBE,))? - .call_method1("isEnabledFor", (50,))?; + // empties it again and the next refresh reads anew. A disabled + // logger never fills its cache, and `dictConfig()` / `fileConfig()` + // disable existing loggers by default; the probe emits nothing, so + // re-enable it. + let probe = logging.call_method1("getLogger", (LEVELS_PROBE,))?; + probe.setattr("disabled", false)?; + probe.call_method1("isEnabledFor", (50,))?; let root = logging.getattr("root")?; let manager = root.getattr("manager")?; let logger_type = logging.getattr("Logger")?; @@ -400,8 +431,8 @@ fn level_filter_for_python_threshold(threshold: i64) -> log::LevelFilter { #[cfg(test)] mod tests { use super::{ - level_filter_for_python_threshold, levels_unchanged, mark_interpreter_exiting, ExitGuard, - PythonLevels, KERNEL_TARGET, + decide, level_filter_for_python_threshold, levels_unchanged, mark_interpreter_exiting, + ExitGuard, PythonLevels, KERNEL_TARGET, }; use log::{LevelFilter, Log}; use pyo3::prelude::*; @@ -446,9 +477,54 @@ mod tests { run("logging.getLogger('kernel_logging_test.other')"); assert!(levels_unchanged(py)); assert_eq!(PythonLevels::read(py).max_level, before); + + // dictConfig() disables existing loggers, the probe included. A + // disabled logger never refills its cache, so without re-enabling + // the probe every later read would look like a change. + run("import logging.config\nlogging.config.dictConfig({'version': 1})\nchild.setLevel(logging.INFO)"); + assert!(!levels_unchanged(py), "setLevel after dictConfig"); + assert_eq!(PythonLevels::read(py).max_level, LevelFilter::Info); + assert!(levels_unchanged(py), "the probe works after dictConfig"); + run("child.disabled = False\nchild.setLevel(logging.NOTSET)"); }); } + fn levels(ticket: u64, fingerprint: u64) -> PythonLevels { + PythonLevels { + ticket, + max_level: LevelFilter::Debug, + fingerprint, + } + } + + #[test] + fn apply_sets_newer_reads_and_resets_on_change() { + let mut applied = (0, 0); + // First read: set the level; the fingerprint differs from the + // initial state, so the cache is cleared too. + assert_eq!( + decide(&mut applied, &levels(1, 7), false), + (Some(LevelFilter::Debug), true) + ); + assert_eq!(applied, (1, 7)); + // Same levels: set again, keep the cache. + assert_eq!( + decide(&mut applied, &levels(2, 7), false), + (Some(LevelFilter::Debug), false) + ); + // reset_logging() always clears the cache. + assert_eq!( + decide(&mut applied, &levels(3, 7), true), + (Some(LevelFilter::Debug), true) + ); + // A read that started before the applied one is dropped... + decide(&mut applied, &levels(5, 9), false); + assert_eq!(decide(&mut applied, &levels(4, 8), false), (None, false)); + assert_eq!(applied, (5, 9)); + // ...but an overtaken reset_logging() still clears the cache. + assert_eq!(decide(&mut applied, &levels(4, 8), true), (None, true)); + } + #[test] fn python_thresholds_map_to_the_levels_pyo3_log_forwards() { // pyo3_log maps Trace/Debug/Info/Warn/Error to Python 5/10/20/30/40. diff --git a/pyo3/tests/test_logging.py b/pyo3/tests/test_logging.py index 60105ddc..866c596f 100644 --- a/pyo3/tests/test_logging.py +++ b/pyo3/tests/test_logging.py @@ -53,15 +53,20 @@ def test_debug_set_after_import_reaches_python(caplog): # The bridge was installed at import, before this level was set. with caplog.at_level(logging.DEBUG, logger=KERNEL_LOGGER): _reject_session() + assert k._log_max_level() == "DEBUG" (record,) = _breadcrumbs(caplog) assert record.name == "databricks.sql.kernel.pyo3" assert record.levelno == logging.DEBUG -def test_records_below_the_level_are_not_forwarded(caplog): +def test_records_below_the_level_are_dropped_before_python(caplog): with caplog.at_level(logging.WARNING, logger=KERNEL_LOGGER): k.reset_logging() + # Below WARNING nothing is forwarded, so DEBUG records are dropped + # by `log`'s own level check instead of reaching pyo3_log. + assert k._log_max_level() == "WARN" _reject_session() + assert k._log_max_level() == "WARN" assert not _breadcrumbs(caplog) From 9d3a79d3ac440f370cbbaed800338e67c540bbb7 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:43:47 +0000 Subject: [PATCH 5/9] fix(python): skip the level read in init_logging once install has failed After a failed install (another global log logger is set), each later init_logging() call still read every Python logger before finding the Failed state. It now checks the state under a short lock first, reads, and checks again under the install lock. The Rust test asserts that init_logging() takes no read ticket in the Failed state. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/logging.rs | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 7a845f4f..212856e5 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -182,17 +182,17 @@ impl log::Log for ExitGuard { /// failed, or another global `log` logger is already set). Never panics: /// a logging helper must not be able to tear down the host process. pub(crate) fn init_logging(py: Python<'_>) -> bool { - if RESET_HANDLE.get().is_some() { + // Already installed, or a prior attempt failed — don't retry. Retry + // would re-run `Logger::install()`'s global-logger set, which is not + // free, on every Session construction. + if !matches!(*lock_state(), LogState::NotInstalled) { return false; } - // Read the levels before taking the install lock: the read runs Python + // Read the levels without holding the install lock: the read runs Python // code, during which another thread may take the GIL and then block on // that lock. let levels = PythonLevels::read(py); let mut state = lock_state(); - // Already installed, or a prior attempt failed — don't retry. Retry - // would re-run `Logger::install()`'s global-logger set, which is not - // free, on every Session construction. if !matches!(*state, LogState::NotInstalled) { return false; } @@ -431,8 +431,8 @@ fn level_filter_for_python_threshold(threshold: i64) -> log::LevelFilter { #[cfg(test)] mod tests { use super::{ - decide, level_filter_for_python_threshold, levels_unchanged, mark_interpreter_exiting, - ExitGuard, PythonLevels, KERNEL_TARGET, + decide, init_logging, level_filter_for_python_threshold, levels_unchanged, lock_state, + mark_interpreter_exiting, ExitGuard, LogState, PythonLevels, KERNEL_TARGET, NEXT_READ, }; use log::{LevelFilter, Log}; use pyo3::prelude::*; @@ -486,6 +486,12 @@ mod tests { assert_eq!(PythonLevels::read(py).max_level, LevelFilter::Info); assert!(levels_unchanged(py), "the probe works after dictConfig"); run("child.disabled = False\nchild.setLevel(logging.NOTSET)"); + + // After a failed install, init_logging() returns without reading. + *lock_state() = LogState::Failed; + let reads = NEXT_READ.load(Ordering::Relaxed); + assert!(!init_logging(py)); + assert_eq!(NEXT_READ.load(Ordering::Relaxed), reads); }); } From 1b8f992ae58f96ba41d60fb45bc18d8f57d5094f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:47:11 +0000 Subject: [PATCH 6/9] docs(python): note when a mid-session level change applies; harden level asserts The changelog now says that a level raised while a session is open applies from the next Session or reset_logging() call, for every logger. The Python tests derive the expected max level from the process's loggers, and skip the exact WARN check when another logger is already below WARNING (e.g. pytest's log_level). Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 2 +- pyo3/tests/test_logging.py | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 7046143a..894596ba 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,7 +14,7 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added ### Changed -- Log records below every Python logger's level are now dropped before they reach the Python logging bridge, which cuts client CPU per query. Levels set before a `Session` is created take effect without `reset_logging()`. +- Log records below every Python logger's level are now dropped before they reach the Python logging bridge, which cuts client CPU per query. Levels set before a `Session` is created take effect without `reset_logging()`. A level raised while a session is open applies from the next `Session` or `reset_logging()` call, for every logger (before, loggers that had not logged yet picked it up on their own). ### Updated diff --git a/pyo3/tests/test_logging.py b/pyo3/tests/test_logging.py index 866c596f..cbbda938 100644 --- a/pyo3/tests/test_logging.py +++ b/pyo3/tests/test_logging.py @@ -49,11 +49,21 @@ def _restore_levels(): k.reset_logging() +def _lowest_level() -> int: + """The most verbose effective level of any logger in this process.""" + loggers = [logging.root] + [ + lg + for lg in logging.root.manager.loggerDict.values() + if isinstance(lg, logging.Logger) + ] + return min(lg.getEffectiveLevel() for lg in loggers) + + def test_debug_set_after_import_reaches_python(caplog): # The bridge was installed at import, before this level was set. with caplog.at_level(logging.DEBUG, logger=KERNEL_LOGGER): _reject_session() - assert k._log_max_level() == "DEBUG" + assert k._log_max_level() == ("TRACE" if _lowest_level() <= 5 else "DEBUG") (record,) = _breadcrumbs(caplog) assert record.name == "databricks.sql.kernel.pyo3" assert record.levelno == logging.DEBUG @@ -62,6 +72,8 @@ def test_debug_set_after_import_reaches_python(caplog): def test_records_below_the_level_are_dropped_before_python(caplog): with caplog.at_level(logging.WARNING, logger=KERNEL_LOGGER): k.reset_logging() + if _lowest_level() < logging.WARNING: + pytest.skip("another logger in this process is below WARNING") # Below WARNING nothing is forwarded, so DEBUG records are dropped # by `log`'s own level check instead of reaching pyo3_log. assert k._log_max_level() == "WARN" From 6ce2b140f2f7e9e84304e16ce170141cecb6bad0 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:52:01 +0000 Subject: [PATCH 7/9] fix(python): treat a new logger as a level change; restore state in the test A logger created with a level of its own (e.g. from a setLoggerClass() class) clears no logging cache, so Session() kept the old max level. Change detection now also compares the number of loggerDict entries with the last read. A level assigned directly (logger.level = ...) still needs reset_logging(); the doc comment and changelog say so. The Rust test now restores the global install state it sets to Failed. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/NEXT_CHANGELOG.md | 2 +- pyo3/src/logging.rs | 47 +++++++++++++++++++++++++++++++++--------- 2 files changed, 38 insertions(+), 11 deletions(-) diff --git a/pyo3/NEXT_CHANGELOG.md b/pyo3/NEXT_CHANGELOG.md index 894596ba..311b7013 100644 --- a/pyo3/NEXT_CHANGELOG.md +++ b/pyo3/NEXT_CHANGELOG.md @@ -14,7 +14,7 @@ changes go in the root `NEXT_CHANGELOG.md`. ### Added ### Changed -- Log records below every Python logger's level are now dropped before they reach the Python logging bridge, which cuts client CPU per query. Levels set before a `Session` is created take effect without `reset_logging()`. A level raised while a session is open applies from the next `Session` or `reset_logging()` call, for every logger (before, loggers that had not logged yet picked it up on their own). +- Log records below every Python logger's level are now dropped before they reach the Python logging bridge, which cuts client CPU per query. Levels set before a `Session` is created take effect without `reset_logging()`. A level raised while a session is open applies from the next `Session` or `reset_logging()` call, for every logger (before, loggers that had not logged yet picked it up on their own). A level assigned directly (`logger.level = ...`) instead of with `setLevel()` needs `reset_logging()`. ### Updated diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 212856e5..1ed3ebcb 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -75,7 +75,7 @@ use pyo3::prelude::*; use pyo3_log::{Caching, Logger, ResetHandle}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, OnceLock}; /// Logger target the kernel tags every event with. Maps to the Python @@ -339,18 +339,29 @@ const LEVELS_PROBE: &str = "databricks.sql.kernel._levels_probe"; /// /// `logging` clears every logger's `_cache` on `setLevel()` and /// `logging.disable()`. [`PythonLevels::read`] fills the probe logger's -/// cache before it reads, so a still-filled cache means nothing changed. -/// Errs towards `false` (do the full read). +/// cache before it reads, so a still-filled cache, with as many loggers as +/// that read saw, means nothing changed. Counting the loggers catches a new +/// logger that comes with a level (e.g. from a `setLoggerClass()` class). A +/// level assigned directly (`logger.level = ...`) clears no cache and is +/// only picked up by [`reset_logging`]. Errs towards `false` (do the full +/// read). fn levels_unchanged(py: Python<'_>) -> bool { let check = || -> PyResult { - let probe = py - .import("logging")? - .call_method1("getLogger", (LEVELS_PROBE,))?; - Ok(probe.getattr("_cache")?.len()? > 0) + let logging = py.import("logging")?; + let probe = logging.call_method1("getLogger", (LEVELS_PROBE,))?; + let loggers = logging + .getattr("root")? + .getattr("manager")? + .getattr("loggerDict")? + .len()?; + Ok(probe.getattr("_cache")?.len()? > 0 && loggers == LOGGERS_SEEN.load(Ordering::Relaxed)) }; check().unwrap_or(false) } +/// Number of `loggerDict` entries the last [`PythonLevels::read`] saw. +static LOGGERS_SEEN: AtomicUsize = AtomicUsize::new(0); + struct PythonLevels { ticket: u64, /// The most verbose `log` level any Python logger currently accepts. @@ -389,6 +400,7 @@ impl PythonLevels { .import("builtins")? .getattr("list")? .call1((manager.getattr("loggerDict")?.call_method0("values")?,))?; + LOGGERS_SEEN.store(loggers.len()?, Ordering::Relaxed); for logger in loggers.try_iter()? { let logger = logger?; // `loggerDict` also holds `PlaceHolder`s for unnamed parents. @@ -471,11 +483,24 @@ mod tests { run("logging.disable(logging.NOTSET)\nchild.setLevel(logging.NOTSET)\nlogging.root.setLevel(logging.NOTSET)"); assert_eq!(PythonLevels::read(py).max_level, LevelFilter::Trace); - // A new logger with no level of its own changes nothing. + // A new logger triggers a read; with no level of its own it changes + // nothing. run("logging.root.setLevel(logging.WARNING)"); let before = PythonLevels::read(py).max_level; run("logging.getLogger('kernel_logging_test.other')"); + assert!(!levels_unchanged(py), "a new logger is detected"); + assert_eq!(PythonLevels::read(py).max_level, before); assert!(levels_unchanged(py)); + + // A logger class that sets its level in __init__ clears no cache; + // the new logger is still detected. + run("class Verbose(logging.Logger):\n def __init__(self, name):\n super().__init__(name)\n self.level = logging.DEBUG\nlogging.setLoggerClass(Verbose)\nlogging.getLogger('kernel_logging_test.verbose')\nlogging.setLoggerClass(logging.Logger)"); + assert!( + !levels_unchanged(py), + "a new logger with a level is detected" + ); + assert_eq!(PythonLevels::read(py).max_level, LevelFilter::Debug); + run("logging.getLogger('kernel_logging_test.verbose').setLevel(logging.NOTSET)"); assert_eq!(PythonLevels::read(py).max_level, before); // dictConfig() disables existing loggers, the probe included. A @@ -488,9 +513,11 @@ mod tests { run("child.disabled = False\nchild.setLevel(logging.NOTSET)"); // After a failed install, init_logging() returns without reading. - *lock_state() = LogState::Failed; + let previous = std::mem::replace(&mut *lock_state(), LogState::Failed); let reads = NEXT_READ.load(Ordering::Relaxed); - assert!(!init_logging(py)); + let installed = init_logging(py); + *lock_state() = previous; + assert!(!installed); assert_eq!(NEXT_READ.load(Ordering::Relaxed), reads); }); } From 8634ec0ce7e4c596e06cf554969f60f9218ef10a Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sat, 14 Nov 2026 23:57:25 +0000 Subject: [PATCH 8/9] fix(python): make the next Session re-read levels when a read is dropped A read takes its ticket before it runs Python code, so a read dropped as older than the applied one may have seen a newer configuration, and it had already refilled the change probe. The next Session then skipped the walk and the level stayed stale until reset_logging(). A dropped read now resets the recorded logger count to a sentinel, so the next Session reads again. decide() returns this as read_again, covered by its unit test. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/logging.rs | 97 +++++++++++++++++++++++++++++++-------------- 1 file changed, 68 insertions(+), 29 deletions(-) diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 1ed3ebcb..5bbb078f 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -281,42 +281,57 @@ static APPLIED: Mutex<(u64, u64)> = Mutex::new((0, 0)); /// Set `log::max_level` from `levels`, and clear `pyo3_log`'s cache if the /// levels changed or `reset` is set. /// -/// Reads run Python code, so a read can be interrupted by a thread that -/// changes a level and applies its own read. A read that started earlier -/// than the last applied one is therefore not applied: the later read saw -/// at least as recent a configuration. Nothing in here calls Python, so -/// holding `APPLIED` can't deadlock with the GIL. +/// Reads run Python code, so threads can interleave them with level +/// changes. Applies are ordered by ticket: a read that started before the +/// last applied one is not applied. It may still have seen a newer +/// configuration than that one, and it already refilled the change probe, +/// so the next `Session` is made to read again. Nothing in here calls +/// Python, so holding `APPLIED` can't deadlock with the GIL. fn apply(levels: PythonLevels, reset: bool) { let Some(handle) = RESET_HANDLE.get() else { return; }; let mut applied = APPLIED.lock().unwrap_or_else(|p| p.into_inner()); - let (set_level, clear_cache) = decide(&mut applied, &levels, reset); - if let Some(level) = set_level { + let decision = decide(&mut applied, &levels, reset); + if let Some(level) = decision.set_level { log::set_max_level(level); } - if clear_cache { + if decision.clear_cache { handle.reset(); } + if decision.read_again { + LOGGERS_SEEN.store(usize::MAX, Ordering::Relaxed); + } +} + +/// What [`apply`] does with one read. +#[derive(Debug, PartialEq)] +struct Decision { + /// The max level to set, if any. + set_level: Option, + /// Whether to clear `pyo3_log`'s cache. + clear_cache: bool, + /// Whether the next `Session` must read the levels again. + read_again: bool, } -/// What [`apply`] does for `levels`, given the `(ticket, fingerprint)` of -/// the last applied read (updated in place): the max level to set, if -/// any, and whether to clear `pyo3_log`'s cache. -fn decide( - applied: &mut (u64, u64), - levels: &PythonLevels, - reset: bool, -) -> (Option, bool) { +/// [`apply`]'s decision for `levels`, given the `(ticket, fingerprint)` of +/// the last applied read (updated in place). +fn decide(applied: &mut (u64, u64), levels: &PythonLevels, reset: bool) -> Decision { let (applied_ticket, applied_fingerprint) = *applied; if levels.ticket <= applied_ticket { - return (None, reset); + return Decision { + set_level: None, + clear_cache: reset, + read_again: true, + }; } *applied = (levels.ticket, levels.fingerprint); - ( - Some(levels.max_level), - reset || levels.fingerprint != applied_fingerprint, - ) + Decision { + set_level: Some(levels.max_level), + clear_cache: reset || levels.fingerprint != applied_fingerprint, + read_again: false, + } } /// The current `log::max_level`, for tests. @@ -444,7 +459,8 @@ fn level_filter_for_python_threshold(threshold: i64) -> log::LevelFilter { mod tests { use super::{ decide, init_logging, level_filter_for_python_threshold, levels_unchanged, lock_state, - mark_interpreter_exiting, ExitGuard, LogState, PythonLevels, KERNEL_TARGET, NEXT_READ, + mark_interpreter_exiting, Decision, ExitGuard, LogState, PythonLevels, KERNEL_TARGET, + LOGGERS_SEEN, NEXT_READ, }; use log::{LevelFilter, Log}; use pyo3::prelude::*; @@ -512,6 +528,17 @@ mod tests { assert!(levels_unchanged(py), "the probe works after dictConfig"); run("child.disabled = False\nchild.setLevel(logging.NOTSET)"); + // A dropped read makes the next Session read again. + PythonLevels::read(py); + assert!(levels_unchanged(py)); + LOGGERS_SEEN.store(usize::MAX, Ordering::Relaxed); + assert!( + !levels_unchanged(py), + "the read-again sentinel forces a read" + ); + PythonLevels::read(py); + assert!(levels_unchanged(py)); + // After a failed install, init_logging() returns without reading. let previous = std::mem::replace(&mut *lock_state(), LogState::Failed); let reads = NEXT_READ.load(Ordering::Relaxed); @@ -532,30 +559,42 @@ mod tests { #[test] fn apply_sets_newer_reads_and_resets_on_change() { + let applied_read = |clear_cache| Decision { + set_level: Some(LevelFilter::Debug), + clear_cache, + read_again: false, + }; let mut applied = (0, 0); // First read: set the level; the fingerprint differs from the // initial state, so the cache is cleared too. assert_eq!( decide(&mut applied, &levels(1, 7), false), - (Some(LevelFilter::Debug), true) + applied_read(true) ); assert_eq!(applied, (1, 7)); // Same levels: set again, keep the cache. assert_eq!( decide(&mut applied, &levels(2, 7), false), - (Some(LevelFilter::Debug), false) + applied_read(false) ); // reset_logging() always clears the cache. assert_eq!( decide(&mut applied, &levels(3, 7), true), - (Some(LevelFilter::Debug), true) + applied_read(true) ); - // A read that started before the applied one is dropped... + // A read that started before the applied one is dropped, and since + // it may have seen a newer configuration, the next Session reads + // again... decide(&mut applied, &levels(5, 9), false); - assert_eq!(decide(&mut applied, &levels(4, 8), false), (None, false)); + let dropped = |clear_cache| Decision { + set_level: None, + clear_cache, + read_again: true, + }; + assert_eq!(decide(&mut applied, &levels(4, 8), false), dropped(false)); assert_eq!(applied, (5, 9)); - // ...but an overtaken reset_logging() still clears the cache. - assert_eq!(decide(&mut applied, &levels(4, 8), true), (None, true)); + // ...and an overtaken reset_logging() still clears the cache. + assert_eq!(decide(&mut applied, &levels(4, 8), true), dropped(true)); } #[test] From fa5af84e8fb17b1f1687f25ccddd54a45c8ec26f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Sun, 15 Nov 2026 00:02:36 +0000 Subject: [PATCH 9/9] refactor(python): run no Python code under the log install lock init_logging built the pyo3_log Logger and registered the atexit hook while holding the install lock, so a thread switch during either call could let another thread block on the lock while holding the GIL. The Logger is now built and the levels read before the lock is taken, the install itself (install()) runs no Python code, and the hook is registered after the lock is released. Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- pyo3/src/logging.rs | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/pyo3/src/logging.rs b/pyo3/src/logging.rs index 5bbb078f..722a835a 100644 --- a/pyo3/src/logging.rs +++ b/pyo3/src/logging.rs @@ -188,15 +188,10 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { if !matches!(*lock_state(), LogState::NotInstalled) { return false; } - // Read the levels without holding the install lock: the read runs Python - // code, during which another thread may take the GIL and then block on - // that lock. - let levels = PythonLevels::read(py); - let mut state = lock_state(); - if !matches!(*state, LogState::NotInstalled) { - return false; - } - + // Everything that runs Python code happens without holding the install + // lock: Python code can let another thread take the GIL, and that thread + // could then block on the lock while holding the GIL. + // // `LoggersAndLevels` caching: resolve each Python logger object and // its effective level once, then gate subsequent records cheaply // without re-entering Python. The default filter forwards every @@ -210,12 +205,26 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { // shutdown. We must NOT `expect()` it: an unwinding panic across the // pyo3/FFI boundary is undefined behavior and would tear down the // process over a non-essential feature. Treat it as a sticky failure. - let logger = match Logger::new(py, Caching::LoggersAndLevels) { - Ok(l) => l, - Err(_) => { - *state = LogState::Failed; - return false; - } + let logger = Logger::new(py, Caching::LoggersAndLevels); + let levels = PythonLevels::read(py); + if !install(logger, levels) { + return false; + } + // Best effort: without the hook, records still flow until exit. + let _ = register_exit_hook(py); + true +} + +/// Install `logger` as the global `log` logger, under the install lock. +/// Runs no Python code. Returns whether this call installed it. +fn install(logger: PyResult, levels: PythonLevels) -> bool { + let mut state = lock_state(); + if !matches!(*state, LogState::NotInstalled) { + return false; + } + let Ok(logger) = logger else { + *state = LogState::Failed; + return false; }; let logger = logger .filter(log::LevelFilter::Trace) @@ -228,8 +237,6 @@ pub(crate) fn init_logging(py: Python<'_>) -> bool { Ok(()) => { let _ = RESET_HANDLE.set(handle); apply(levels, false); - // Best effort: without the hook, records still flow until exit. - let _ = register_exit_hook(py); *state = LogState::Installed; true }