Skip to content

fix(client): release GIL during builder + cache pyo3-log lookups - #141

Closed
PhilflowIO wants to merge 1 commit into
deedy5:mainfrom
PhilflowIO:fix/lazy-init-deadlock
Closed

PhilflowIO wants to merge 1 commit into
deedy5:mainfrom
PhilflowIO:fix/lazy-init-deadlock

Conversation

@PhilflowIO

Copy link
Copy Markdown

Summary

Fixes a first-call deadlock that occurs when multiple threads construct primp.Client(impersonate="random", …) concurrently — the typical pattern for asyncio.gather(asyncio.to_thread(primp.Client, …)) in FastAPI / agent / scraping workloads.

Reproduction

import threading, primp
barrier = threading.Barrier(8)

def worker():
    barrier.wait()
    primp.Client(impersonate="random", impersonate_os="random", timeout=5)

threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads: t.start()
for t in threads: t.join(timeout=20)  # never returns on primp 1.2.2

Before this change: hangs for the full 20 s (and indefinitely in real workloads).
After: completes in ~10 ms on my machine.

faulthandler fingerprint

Thread W*:
  File ".../primp_repro.py" in worker
  -> primp.Client(impersonate="random", ...)
     -> logging/__init__.py:2130 in getLogger   ← stuck

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 fires log::warn! / tracing::*! call-sites inside primp-reqwest, hyper, rustls — notably log::warn!("failed to load native root certificate: …") in primp-reqwest/src/tls.rs:633. Every log call forwards through pyo3-log back into Python's logging.getLogger(target).isEnabledFor(level).

With several threads all trying to do this under the GIL, they race on Python's logging._lock inside Manager.getLogger in a way that does not recover. requests/primp inter-byte timeout semantics cannot break it, and asyncio.to_thread / run_in_executor cannot 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 — no ddgs involved.

Client::request() already does the right thing with py.detach(|| RUNTIME.block_on(future)) at lib.rs:491. Client::new() and AsyncClient::new() were missing the corresponding release.

Fix

Two parts, both in crates/primp-python/:

  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 and enforced at compile time (the closure is Send). pyo3-log 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 in 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 .pyi stub stays identical, and the module-level convenience functions (get / head / post / …) forward py to Client::new so they automatically benefit from the fix.

Verification

  • New regression test crates/primp-python/tests/test_parallel_client.py: 8 threads constructing Client(impersonate="random") concurrently. Before: hangs for 20 s timeout. After: passes in 0.03 s.
  • Existing pytest suite: 354/354 pass (pytest tests/).
  • End-to-end downstream: running ddgs 9.13.0 against this patched primp with the 4-way concurrent asyncio.gather search 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

Happy to iterate on naming, comment style, or split the two hunks into separate commits if preferred.

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
@deedy5

deedy5 commented Apr 20, 2026

Copy link
Copy Markdown
Owner

Thank you for this PR. You correctly identified and fixed this deadlock, the core py.detach() fix is perfect.

There is just one small issue: the changes apparently doesn't seem to be human-reviewed, because Caching::LoggersAndLevels has actually been the default behaviour in pyo3-log since version 0.8.0 released in 2023, so this part of the change doesn't actually do anything.

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.

@deedy5 deedy5 closed this Apr 20, 2026
@PhilflowIO

Copy link
Copy Markdown
Author

Superb thank you

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.

2 participants