Repository navigation
fix(client): release GIL during builder + cache pyo3-log lookups - #141
Closed
PhilflowIO wants to merge 1 commit into
Closed
PhilflowIO wants to merge 1 commit into
PhilflowIO wants to merge 1 commit into
Conversation
When Client.new() / AsyncClient.new() ran the reqwest builder under the
GIL, log/tracing callsites deep in primp-reqwest, hyper, and rustls
(e.g. "failed to load native root certificate" in primp-reqwest/tls.rs)
forwarded through pyo3-log back into Python's logging.getLogger.
Several threads constructing a client concurrently — the typical pattern
for asyncio.gather(asyncio.to_thread(primp.Client, ...)) — deadlocked
against Python's logging._lock / GIL ordering while each build ran.
faulthandler fingerprint from a minimal reproducer:
Thread W*: worker -> primp.Client(...)
-> logging/__init__.py:getLogger ← stuck
This is the deadlock pattern documented by the pyo3-log maintainer in
vorner/pyo3-log#65: a PyO3 method must release the GIL around blocking
Rust work that may log, otherwise concurrent callers cannot serialize
through pyo3-log's Python callback.
Fix, in two parts:
1. Wrap the reqwest build path in `py.detach(|| ...)` for both
Client::new and AsyncClient::new. Everything inside the closure is
pure Rust (no PyObject is touched), so releasing the GIL is safe;
pyo3-log's callbacks from reqwest/hyper/rustls now acquire the GIL
cleanly when they fire. This is the root-cause fix.
2. Install pyo3-log with `Caching::LoggersAndLevels`. After the first
emission per target, subsequent emissions hit a Rust-side cache and
never cross the GIL. Documented pyo3-log best-practice; complements
(1) by keeping steady-state hot paths GIL-free for logging.
The Python-level API is unchanged. `py: Python<'_>` on the constructors
is PyO3-internal — the .pyi stub and user-visible signatures stay
identical. Module-level convenience functions (get/head/post/...)
forward `py` to Client::new.
Verification:
- New test `tests/test_parallel_client.py`: 8 threads constructing
Client(impersonate="random") concurrently. Before this change: hangs
for the full 20 s timeout. After: completes in ~10 ms.
- Existing pytest suite: 354/354 pass.
- End-to-end: running ddgs 9.13.0 against this patched primp with the
4-way concurrent `asyncio.gather` search pattern from downstream
reports completes in ~2.8 s instead of hanging; the asyncio loop
probe stays responsive throughout.
Downstream reports that this unblocks:
- deedy5/ddgs#452 (consumer-side threading.Lock workaround)
- HKUDS/nanobot#2804 / #2805 (consumer-side asyncio.wait_for wrap)
- microsoft/amplifier#219
This was referenced Apr 18, 2026
Closed
Owner
|
Thank you for this PR. You correctly identified and fixed this deadlock, the core There is just one small issue: the changes apparently doesn't seem to be human-reviewed, because Rather than merge this PR and then immediately revert the redundant part, I am going to implement just the actual correct fix directly. Thanks again. |
Author
|
Superb thank you |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes a first-call deadlock that occurs when multiple threads construct
primp.Client(impersonate="random", …)concurrently — the typical pattern forasyncio.gather(asyncio.to_thread(primp.Client, …))in FastAPI / agent / scraping workloads.Reproduction
Before this change: hangs for the full 20 s (and indefinitely in real workloads).
After: completes in ~10 ms on my machine.
faulthandler fingerprint
Root cause
Walking back from the stuck stack:
Client::new()runs the reqwest builder (TLS / root-CA / impersonation setup) while holding the GIL. That builder path fireslog::warn!/tracing::*!call-sites insideprimp-reqwest,hyper,rustls— notablylog::warn!("failed to load native root certificate: …")inprimp-reqwest/src/tls.rs:633. Every log call forwards throughpyo3-logback into Python'slogging.getLogger(target).isEnabledFor(level).With several threads all trying to do this under the GIL, they race on Python's
logging._lockinsideManager.getLoggerin a way that does not recover.requests/primp inter-bytetimeoutsemantics cannot break it, andasyncio.to_thread/run_in_executorcannot cancel OS threads — so from the outside, the process looks permanently stalled.This matches the pattern documented by the pyo3-log maintainer in vorner/pyo3-log#65 ("PyO3 method holding the GIL while something else tries to log from Rust → deadlock"), and reproduces identically with just
primp— noddgsinvolved.Client::request()already does the right thing withpy.detach(|| RUNTIME.block_on(future))at lib.rs:491.Client::new()andAsyncClient::new()were missing the corresponding release.Fix
Two parts, both in
crates/primp-python/:Wrap the reqwest build path in
py.detach(|| …)for bothClient::newandAsyncClient::new. Everything inside the closure is pure Rust (noPyObjectis touched), so releasing the GIL is safe and enforced at compile time (the closure isSend).pyo3-logcallbacks from reqwest / hyper / rustls now acquire the GIL cleanly when they fire. This is the root-cause fix.Install
pyo3-logwithCaching::LoggersAndLevelsin the#[pymodule]init. After the first emission per target, subsequent emissions hit a Rust-side cache and never cross the GIL. Documented pyo3-log best-practice; complements (1) by keeping steady-state hot paths GIL-free for logging.The Python-level API is unchanged:
py: Python<'_>on the constructors is PyO3-internal, the.pyistub stays identical, and the module-level convenience functions (get/head/post/ …) forwardpytoClient::newso they automatically benefit from the fix.Verification
crates/primp-python/tests/test_parallel_client.py: 8 threads constructingClient(impersonate="random")concurrently. Before: hangs for 20 s timeout. After: passes in 0.03 s.pytest tests/).ddgs 9.13.0against this patchedprimpwith the 4-way concurrentasyncio.gathersearch pattern from the linked consumer reports completes in ~2.8 s instead of hanging, and the asyncio event loop stays responsive throughout.Downstream reports this unblocks
threading.Lockaroundprimp.Client(...)construction. Becomes obsolete once this lands.asyncio.wait_forwrap. Still useful as defense-in-depth, but the underlying hang disappears.Happy to iterate on naming, comment style, or split the two hunks into separate commits if preferred.