Repository navigation
perf(python): drop log records below the Python loggers' level before pyo3_log - #469
vuanhphung wants to merge 9 commits into
Conversation
… 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>
There was a problem hiding this comment.
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.
…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>
There was a problem hiding this comment.
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_forwardedalso passes without this PR. Withmax_level = Trace,pyo3_logstill drops the DEBUG breadcrumb at the WARNING logger level, so the test never checks the new gate (thatlog::max_levelwas lowered). A regression that leftmax_levelatTracewould bring back the CPU cost this PR removes, and no test would catch it. Consider exposing the currentlog::max_level()through a private test hook (e.g._log_max_level()) and asserting it isWARNunder the default config andDEBUGaftersetLevel(DEBUG)plus aSessionconstruction.
There was a problem hiding this comment.
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.
…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>
There was a problem hiding this comment.
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.
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>
There was a problem hiding this comment.
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.
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>
There was a problem hiding this comment.
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 andlevels_unchangedreturnsfalse. Nothing breaks, but everySessionconstruction then does a fullloggerDictwalk with the GIL held, callinggetEffectiveLevel()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.
|
On the round-8 nit ( |
The Python log bridge set
log::max_leveltoTrace. Everytracingevent, and every span enter and exit (an instrumented future enters its span on each poll), from the kernel and its HTTP stack therefore built alog::Record. Each record went throughpyo3_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 runningSELECT 1on 800 threads, stacks underpyo3_logwere about 1.6% of all client CPU samples, withLogger::lookupthe hottest leaf in the bridge.log::max_levelis 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), andlogging.disable(). Thelogandtracingmacros compare against it before building a record, so records nobody would see stop there. The level is recomputed at install, when aSessionis created, and byreset_logging(). ASessionskips the read when nothing changed.loggingclears every logger's_cacheonsetLevel()andlogging.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 untilreset_logging(); now, levels set before connecting always apply. A level raised while a session is open applies from the nextSessionorreset_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 toTrace, the previous behaviour.Tests.
cargo fmt,cargo clippy --all-targets -- -D warningsandcargo test --libpass inpyo3/. 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, asetLoggerClass()class that sets its level, anddictConfig()disabling the probe. The new offlinepyo3/tests/test_logging.pychecks the gate through a private_log_max_level(): WARN by default, DEBUG once aSessionsees a DEBUG logger. It also checks that a DEBUG level set after import reaches Python, and that a newSessionpicks 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 fulltest_kernel_backend.pygives 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.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.