Skip to content

perf(python): drop log records below the Python loggers' level before pyo3_log - #469

Open
vuanhphung wants to merge 9 commits into
mainfrom
perf/rd-log-max-level
Open

vuanhphung wants to merge 9 commits into
mainfrom
perf/rd-log-max-level

Conversation

@vuanhphung

@vuanhphung vuanhphung commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

The Python log bridge set log::max_level to Trace. Every tracing event, and every span enter and exit (an instrumented future enters its span on each poll), from the kernel and its HTTP stack therefore built a log::Record. Each record went through pyo3_log's per-target lookup (splitting the target and hashing each segment) before being dropped at the Python logger's level, which is WARNING unless a customer changes it. Most of this runs on tokio threads; some runs on the Python thread with the GIL held. In a profile of a one-process client running SELECT 1 on 800 threads, stacks under pyo3_log were about 1.6% of all client CPU samples, with Logger::lookup the hottest leaf in the bridge.

log::max_level is now the most verbose level any Python logger accepts. It is read from the root logger, every existing logger (a logger created later inherits an existing ancestor's level), and logging.disable(). The log and tracing macros compare against it before building a record, so records nobody would see stop there. The level is recomputed at install, when a Session is created, and by reset_logging(). A Session skips the read when nothing changed. logging clears every logger's _cache on setLevel() and logging.disable(), so a probe logger whose cache is still filled, with the same number of loggers as the last read, means no level changed. With 2,045 loggers, Session() up to its auth check takes ~1.5 µs (0.7 µs before this change, 276 µs if it walked the loggers every time). When a level did change, pyo3_log's cache is cleared too. A logger cached at its old level used to keep dropping newly enabled records until reset_logging(); now, levels set before connecting always apply. A level raised while a session is open applies from the next Session or reset_logging() call. Concurrent reads are ordered by ticket, and nothing runs Python code under the install lock. If the loggers can't be read, the bridge falls back to Trace, the previous behaviour.

Tests. cargo fmt, cargo clippy --all-targets -- -D warnings and cargo test --lib pass in pyo3/. The Rust tests cover the level mapping and the ordering decisions. An embedded-interpreter test checks the level read and change detection: setLevel, logging.disable, new loggers, a setLoggerClass() class that sets its level, and dictConfig() disabling the probe. The new offline pyo3/tests/test_logging.py checks the gate through a private _log_max_level(): WARN by default, DEBUG once a Session sees a DEBUG logger. It also checks that a DEBUG level set after import reaches Python, and that a new Session picks up a level raised after the logger was cached; that last test fails against the released 1.4.0 wheel. The rest of the offline pyo3 suite passes. Against a live warehouse, the connector's kernel logging e2e tests pass (test_kernel_logs_reach_python_logging, test_kernel_log_level_is_respected, test_kernel_and_driver_logs_share_file), and the full test_kernel_backend.py gives the same result with and without this change.

Measurements. databricks-sql-connector, use_kernel=True, SELECT 1, one process. Both arms use the same open kernel and connector PRs (this kernel: #453 #455 #456 #457 #458 #459 #461 #467; connector: databricks/databricks-sql-python#1059 #1061 #1052 #1050 #1051 #1053), with and without this change. Client on 7-8 cores.

without with
one thread, local mock, process CPU per query (4 rounds) 183-185 µs 156-177 µs (median -5%)
mock (30 ms server time), 800 threads, CPU per query 0.346 / 0.350 / 0.351 ms 0.336 / 0.331 / 0.342 ms (-4%)
same, average QPS 11094 / 10981 / 10161 9731 / 11142 / 11278
mock, 1600 threads, CPU per query 0.386 / 0.391 / 0.391 ms 0.383 / 0.384 / 0.366 ms (-2%)
same, average QPS 10184 / 10219 / 9574 10392 / 10326 / 9874
live Real-Time X-Large warehouse, 800 threads, 60 s, CPU per query 0.443 / 0.438 ms 0.421 / 0.423 ms (-4%)
same, average QPS 7819 / 7603 7831 / 7793

At 800 threads the live client is round-trip-bound, so the saving shows as CPU, not QPS. GIL-held time per query is unchanged within sampling error; most of the saving is on tokio threads.

This pull request and its description were written by Isaac.

vuanhphung and others added 2 commits November 14, 2026 22:47
… 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 <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>
Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 3 Low

Looks good overall. The level computation is conservative (it falls back to Trace on failure, and logging.disable is respected), and the fingerprint-based cache reset fixes the stale-cache issue. Three low-severity items: a read-then-store race between concurrent refresh and reset calls, the cost of walking every logger on each connect, and a Python test that doesn't actually exercise the new max-level gate.

Comment thread pyo3/src/logging.rs Resolved
Comment thread pyo3/src/session.rs Resolved
Comment thread pyo3/tests/test_logging.py Resolved
…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 <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 2 Low · 1 Nit

The approach is sound and correct for typical configs: the max level is bounded conservatively from the root logger, every existing logger, and logging.disable, and it falls back to Trace if the loggers can't be read. I found three low-severity issues: the change-detection fast path silently stops working when dictConfig disables the probe logger, and the ticket/reset logic and the new max_level gate have no tests that could fail.

Other findings

  • ⚪ Nit — test_records_below_the_level_are_not_forwarded also passes without this PR. With max_level = Trace, pyo3_log still drops the DEBUG breadcrumb at the WARNING logger level, so the test never checks the new gate (that log::max_level was lowered). A regression that left max_level at Trace would bring back the CPU cost this PR removes, and no test would catch it. Consider exposing the current log::max_level() through a private test hook (e.g. _log_max_level()) and asserting it is WARN under the default config and DEBUG after setLevel(DEBUG) plus a Session construction.

Comment thread pyo3/src/logging.rs Resolved
Comment thread pyo3/src/logging.rs Resolved

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 2 Low

Looks good: the max-level gate and the probe-cache change detection are sound, and the ticket ordering in decide handles reads that are interrupted. Two low-severity notes: the probe misses level changes that don't clear Python's logger cache, and a unit test leaves global install state mutated.

Comment thread pyo3/src/logging.rs Resolved
Comment thread pyo3/src/logging.rs Resolved
…he 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 <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 1 Medium · 1 Low

The approach works and the code is careful, with one medium issue. Ticket ordering doesn't guarantee that a newer ticket saw a newer configuration, so a read that is later discarded can refill the fast-path probe and leave log::max_level stuck at a stale level until reset_logging() is called. I also noted a low-severity behaviour change for levels raised mid-session.

Comment thread pyo3/src/logging.rs Resolved
Comment thread pyo3/src/session.rs Resolved
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 <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 1 Low

Looks good, with one low-severity concern. The ticket/fingerprint ordering, the change-detection probe, the dictConfig handling and the fallback to Trace all look sound and are well tested. The one inconsistency is that some Python calls still run while the install lock is held.

Comment thread pyo3/src/logging.rs Resolved
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 <vu.phung@databricks.com>
Co-authored-by: Isaac <no-reply@databricks.com>

@oss-reviewer-bot oss-reviewer-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: 1 Nit

Looks good. The ticket/fingerprint ordering, the lock discipline around the GIL, and the fallback to Trace all look right, and the unit and offline Python tests cover the main paths. One low-severity note: the change detector relies on CPython's private Logger._cache, and when that attribute is missing it falls back to a full logger walk on every Session.

Other findings

  • ⚪ Nit — The change check depends on Logger._cache, which is a private CPython detail (added in 3.7, not guaranteed on other interpreters). If the attribute is missing, check() errors and levels_unchanged returns false. Nothing breaks, but every Session construction then does a full loggerDict walk with the GIL held, calling getEffectiveLevel() on each logger. Apps with many loggers would pay that on every connect, which cuts into the win this PR is after. You could note this fallback cost in the doc comment, or cache a 'probe unsupported' flag so the hasattr failure is only discovered once. Even then each Session still needs a cheaper signal (or skips refresh) for the per-connect cost to go away.

@vuanhphung

Copy link
Copy Markdown
Collaborator Author

On the round-8 nit (Logger._cache being private): the wheel is built abi3 for CPython (cp39-abi3), so it only loads into CPython 3.9+, where Logger._cache and its clearing in setLevel() / logging.disable() have existed since 3.7. The fallback to a full read is only a safety net and can't trigger on a supported interpreter, so I'm leaving it as is.

This branch was previously deployed

1 inactive deployment
azure-prod — fa5af84e Deployed Nov 15, 2026 by vuanhphung via followup #3172
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant