From c1aefaff88ab3b30381d85d239620fbb311e7d1d Mon Sep 17 00:00:00 2001 From: keicodex Date: Sat, 5 Dec 2026 15:55:20 +0700 Subject: [PATCH] Fix shared sync HTTP/2 client corrupting connection state across threads A synchronous Client with http2=True shared between threads could fail with RuntimeError: deque mutated during iteration from the HPACK encoder, or companion errors such as KeyError and LocalProtocolError from the h2 state machine. httpcore multiplexes concurrent requests onto a single HTTP/2 connection, but that connection's state is not thread-safe, and unlike HTTP/1.1 connections it never refuses a concurrent request. The sync transport now wraps pooled connections so each serves one request at a time, from handle_request until the response stream closes, signalling httpcore.ConnectionNotAvailable while busy - the same contract HTTP/1.1 connections already use - so the pool assigns concurrent requests to separate connections, bounded by the configured limits. The async transport is unchanged. Fixes #3633. --- httpx/_transports/default.py | 151 +++++++++++++++++++- tests/client/test_thread_safety.py | 216 +++++++++++++++++++++++++++++ 2 files changed, 364 insertions(+), 3 deletions(-) create mode 100644 tests/client/test_thread_safety.py diff --git a/httpx/_transports/default.py b/httpx/_transports/default.py index fc8c70970a..04aa4c71ea 100644 --- a/httpx/_transports/default.py +++ b/httpx/_transports/default.py @@ -27,6 +27,7 @@ from __future__ import annotations import contextlib +import threading import typing from types import TracebackType @@ -132,6 +133,139 @@ def close(self) -> None: self._httpcore_stream.close() +class _SingleRequestStream(typing.Iterable[bytes]): + """ + Wrap a pooled connection's response stream, invoking `on_release` + exactly once when the stream is exhausted or closed. + """ + + def __init__( + self, + stream: typing.Iterable[bytes], + on_release: typing.Callable[[], None], + ) -> None: + self._stream = stream + self._on_release = on_release + self._released = False + + def __iter__(self) -> typing.Iterator[bytes]: + try: + yield from self._stream + finally: + self._release() + + def close(self) -> None: + try: + if hasattr(self._stream, "close"): + self._stream.close() + finally: + self._release() + + def _release(self) -> None: + if not self._released: + self._released = True + self._on_release() + + +class _SingleRequestConnection: + """ + Wrap an httpcore connection so that it serves at most one request + at a time, from `handle_request` until the response stream closes. + + The HTTP/2 implementation in httpcore multiplexes concurrent requests + onto a single connection, but its connection state is not thread-safe: + when a synchronous client is shared between threads, two threads can + encode headers concurrently and corrupt the shared HPACK state, + raising errors such as `RuntimeError: deque mutated during iteration` + (see #3633). HTTP/1.1 connections already refuse concurrent requests + with `ConnectionNotAvailable`, which makes the pool assign the request + to another connection. This wrapper restores the same guarantee for + every connection created by a synchronous HTTP/2 transport, at the + cost of using separate connections for concurrent requests, bounded + by the configured connection limits. + """ + + def __init__(self, connection: typing.Any) -> None: + self._connection = connection + self._in_flight = threading.Lock() + + def handle_request(self, request: typing.Any) -> typing.Any: + import httpcore + + if not self._in_flight.acquire(blocking=False): + raise httpcore.ConnectionNotAvailable() + try: + response = self._connection.handle_request(request) + except BaseException: + self._in_flight.release() + raise + return httpcore.Response( + status=response.status, + headers=response.headers, + content=_SingleRequestStream(response.stream, self._release), + extensions=response.extensions, + ) + + def _release(self) -> None: + if self._in_flight.locked(): + self._in_flight.release() + + def can_handle_request(self, origin: typing.Any) -> bool: + return bool(self._connection.can_handle_request(origin)) + + def is_available(self) -> bool: + if self._in_flight.locked(): + return False + return bool(self._connection.is_available()) + + def is_idle(self) -> bool: + return bool(self._connection.is_idle()) + + def is_closed(self) -> bool: + return bool(self._connection.is_closed()) + + def has_expired(self) -> bool: + return bool(self._connection.has_expired()) + + def close(self) -> None: + self._connection.close() + + def info(self) -> str: + return str(self._connection.info()) + + def __repr__(self) -> str: + return repr(self._connection) + + +class _SingleRequestPoolMixin: + """ + Pool behaviour override: wrap every connection the pool creates in + `_SingleRequestConnection`. Used with each of the synchronous httpcore + pool classes when HTTP/2 is enabled. + """ + + def create_connection(self, origin: typing.Any) -> typing.Any: + return _SingleRequestConnection(super().create_connection(origin)) # type: ignore[misc] + + +_single_request_pool_classes: dict[type, type] = {} + + +def _single_request_pool_class(pool_cls: type) -> type: + """ + Return a subclass of an httpcore sync pool class that creates + `_SingleRequestConnection` instances, building it on first use so + that httpcore is only imported once a transport is instantiated. + """ + if pool_cls not in _single_request_pool_classes: + _single_request_pool_classes[pool_cls] = type( + f"SingleRequest{pool_cls.__name__}", + (_SingleRequestPoolMixin, pool_cls), + {}, + ) + return _single_request_pool_classes[pool_cls] + + class HTTPTransport(BaseTransport): def __init__( self, @@ -152,8 +286,19 @@ def __init__( proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) + # With HTTP/2 enabled, guard pooled connections so that a single + # connection is only ever used by one thread at a time. See + # `_SingleRequestConnection` and #3633. + pool_cls: type = httpcore.ConnectionPool + proxy_pool_cls: type = httpcore.HTTPProxy + socks_pool_cls: type = httpcore.SOCKSProxy + if http2: + pool_cls = _single_request_pool_class(pool_cls) + proxy_pool_cls = _single_request_pool_class(proxy_pool_cls) + socks_pool_cls = _single_request_pool_class(socks_pool_cls) + if proxy is None: - self._pool = httpcore.ConnectionPool( + self._pool = pool_cls( ssl_context=ssl_context, max_connections=limits.max_connections, max_keepalive_connections=limits.max_keepalive_connections, @@ -166,7 +311,7 @@ def __init__( socket_options=socket_options, ) elif proxy.url.scheme in ("http", "https"): - self._pool = httpcore.HTTPProxy( + self._pool = proxy_pool_cls( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, @@ -193,7 +338,7 @@ def __init__( "Make sure to install httpx using `pip install httpx[socks]`." ) from None - self._pool = httpcore.SOCKSProxy( + self._pool = socks_pool_cls( proxy_url=httpcore.URL( scheme=proxy.url.raw_scheme, host=proxy.url.raw_host, diff --git a/tests/client/test_thread_safety.py b/tests/client/test_thread_safety.py new file mode 100644 index 0000000000..7be64e40ea --- /dev/null +++ b/tests/client/test_thread_safety.py @@ -0,0 +1,216 @@ +""" +Thread-safety regression tests for a synchronous `Client` shared +between threads, as reported in #3633. + +With HTTP/2 enabled, httpcore multiplexes concurrent requests onto a +single connection, but the connection state is not thread-safe. Two +threads encoding headers at the same time could corrupt the shared +HPACK dynamic table, raising `RuntimeError: deque mutated during +iteration`, alongside companion failures such as `KeyError` and +`LocalProtocolError` from the h2 state machine. + +These tests use a minimal prior-knowledge HTTP/2 server, implemented +with the `h2` package, so that requests really are served over HTTP/2. +""" + +import socket +import sys +import threading +import time +import typing + +import h2.config +import h2.connection +import h2.events +import pytest + +import httpx + + +class HTTP2TestServer: + """ + A threaded TCP server speaking prior-knowledge HTTP/2. + + Every request is answered with a `200` response and the body `b"ok"`. + A small optional delay before responding makes concurrent requests + overlap in flight. + """ + + def __init__(self, response_delay: float = 0.0) -> None: + self._response_delay = response_delay + self._listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self._listener.bind(("127.0.0.1", 0)) + self._listener.listen(50) + self.port = self._listener.getsockname()[1] + self.connections = 0 + self._lock = threading.Lock() + self._stopped = False + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.port}/" + + def start(self) -> None: + threading.Thread(target=self._accept_loop, daemon=True).start() + + def stop(self) -> None: + self._stopped = True + try: + self._listener.close() + except OSError: # pragma: no cover + pass + + def _accept_loop(self) -> None: + while not self._stopped: + try: + sock, _ = self._listener.accept() + except OSError: + return + with self._lock: + self.connections += 1 + threading.Thread( + target=self._serve_connection, args=(sock,), daemon=True + ).start() + + def _serve_connection(self, sock: socket.socket) -> None: + config = h2.config.H2Configuration(client_side=False) + connection = h2.connection.H2Connection(config=config) + connection.initiate_connection() + try: + sock.sendall(connection.data_to_send()) + while True: + data = sock.recv(65535) + if not data: + return + for event in connection.receive_data(data): + if isinstance(event, h2.events.RequestReceived): + if self._response_delay: + time.sleep(self._response_delay) + connection.send_headers( + event.stream_id, + [(":status", "200"), ("content-type", "text/plain")], + ) + connection.send_data(event.stream_id, b"ok", end_stream=True) + outgoing = connection.data_to_send() + if outgoing: + sock.sendall(outgoing) + except Exception: # noqa: BLE001 - a broken connection ends its thread + return + finally: + try: + sock.close() + except OSError: # pragma: no cover + pass + + +@pytest.fixture() +def h2_server() -> typing.Iterator[HTTP2TestServer]: + server = HTTP2TestServer(response_delay=0.01) + server.start() + yield server + server.stop() + + +def test_shared_sync_client_with_http2_used_from_many_threads( + h2_server: HTTP2TestServer, +) -> None: + """ + Many threads sharing one synchronous HTTP/2 client must all complete + successfully. Before the fix this reliably raised errors from the + shared connection state within the first few concurrent requests. + """ + thread_count = 12 + requests_per_thread = 50 + barrier = threading.Barrier(thread_count) + failures: list[str] = [] + failures_lock = threading.Lock() + + def worker(index: int) -> None: + barrier.wait(timeout=30) + for count in range(requests_per_thread): + try: + # Distinct header values on every request churn the + # HPACK dynamic table of the shared connection. + response = client.get( + h2_server.url, + headers={"x-seq": f"t{index}-r{count}-" + "v" * (count % 37)}, + ) + assert response.status_code == 200 + assert response.content == b"ok" + except Exception as exc: # noqa: BLE001 - collected and asserted below + with failures_lock: + failures.append( + f"thread {index} request {count}: {type(exc).__name__}: {exc}" + ) + return + + # Tighten the GIL switch interval while the test runs, to maximise + # interleaving between the worker threads. + previous_interval = sys.getswitchinterval() + sys.setswitchinterval(1e-6) + try: + with httpx.Client( + http1=False, http2=True, trust_env=False, timeout=30.0 + ) as client: + threads = [ + threading.Thread(target=worker, args=(index,)) + for index in range(thread_count) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=60) + finally: + sys.setswitchinterval(previous_interval) + + assert not any(thread.is_alive() for thread in threads) + assert failures == [] + + +def test_concurrent_requests_are_not_multiplexed_onto_one_connection( + h2_server: HTTP2TestServer, +) -> None: + """ + While one request is in flight, a concurrent request on a shared + synchronous HTTP/2 client must be served by a separate connection, + rather than sharing connection state with the first. + """ + started = threading.Event() + release = threading.Event() + responses: dict[str, int] = {} + + def first_request() -> None: + with client.stream("GET", h2_server.url) as response: + started.set() + release.wait(timeout=30) + responses["first"] = response.status_code + + with httpx.Client(http1=False, http2=True, trust_env=False, timeout=30.0) as client: + thread = threading.Thread(target=first_request) + thread.start() + try: + assert started.wait(timeout=30) + response = client.get(h2_server.url) + responses["second"] = response.status_code + finally: + release.set() + thread.join(timeout=30) + + assert responses == {"first": 200, "second": 200} + assert h2_server.connections >= 2 + + +def test_sequential_requests_reuse_a_single_connection( + h2_server: HTTP2TestServer, +) -> None: + """ + The single-request guard must not disable connection reuse: + sequential requests on a shared client still use one connection. + """ + with httpx.Client(http1=False, http2=True, trust_env=False, timeout=30.0) as client: + for count in range(20): + response = client.get(h2_server.url, headers={"x-seq": f"seq-{count}"}) + assert response.status_code == 200 + + assert h2_server.connections == 1