Created
June 13, 2026 06:38
-
-
Save sarmientoF/32bc18a587d96590cece3ecf9f4719dd to your computer and use it in GitHub Desktop.
httpcore HTTP/2 stream-cap E2E repro and benchmark harness
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
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import json | |
| import socket | |
| import statistics | |
| import threading | |
| import time | |
| import typing | |
| import h2.config | |
| import h2.connection | |
| import h2.events | |
| import h2.settings | |
| import httpcore | |
| class H2PriorKnowledgeServer: | |
| def __init__( | |
| self, max_concurrent_streams: int = 2, end_stream: bool = False | |
| ) -> None: | |
| self.max_concurrent_streams = max_concurrent_streams | |
| self.end_stream = end_stream | |
| self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
| self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
| self._sock.bind(("127.0.0.1", 0)) | |
| self._sock.listen() | |
| self._sock.settimeout(0.1) | |
| self.host, self.port = self._sock.getsockname() | |
| self.url = f"http://{self.host}:{self.port}/" | |
| self._stop_event = threading.Event() | |
| self._accept_thread = threading.Thread(target=self._accept, daemon=True) | |
| self._lock = threading.Lock() | |
| self.connection_count = 0 | |
| self.request_count = 0 | |
| self._connections: list[socket.socket] = [] | |
| def __enter__(self) -> H2PriorKnowledgeServer: | |
| self._accept_thread.start() | |
| return self | |
| def __exit__( | |
| self, | |
| exc_type: type[BaseException] | None, | |
| exc_value: BaseException | None, | |
| traceback: typing.Any, | |
| ) -> None: | |
| self.close() | |
| def close(self) -> None: | |
| self._stop_event.set() | |
| try: | |
| self._sock.close() | |
| except OSError: | |
| pass | |
| with self._lock: | |
| connections = list(self._connections) | |
| for conn in connections: | |
| try: | |
| conn.close() | |
| except OSError: | |
| pass | |
| self._accept_thread.join(timeout=1.0) | |
| def _accept(self) -> None: | |
| while not self._stop_event.is_set(): | |
| try: | |
| conn, _ = self._sock.accept() | |
| except TimeoutError: | |
| continue | |
| except OSError: | |
| break | |
| conn.settimeout(0.1) | |
| with self._lock: | |
| self.connection_count += 1 | |
| self._connections.append(conn) | |
| connection_id = self.connection_count | |
| thread = threading.Thread( | |
| target=self._handle_connection, | |
| args=(conn, connection_id), | |
| daemon=True, | |
| ) | |
| thread.start() | |
| def _handle_connection(self, conn: socket.socket, connection_id: int) -> None: | |
| config = h2.config.H2Configuration(client_side=False, header_encoding=None) | |
| state = h2.connection.H2Connection(config=config) | |
| state.local_settings = h2.settings.Settings( | |
| client=False, | |
| initial_values={ | |
| h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: ( | |
| self.max_concurrent_streams | |
| ) | |
| }, | |
| ) | |
| state.initiate_connection() | |
| self._send(conn, state.data_to_send()) | |
| while not self._stop_event.is_set(): | |
| try: | |
| data = conn.recv(65536) | |
| except TimeoutError: | |
| continue | |
| except OSError: | |
| break | |
| if not data: | |
| break | |
| try: | |
| events = state.receive_data(data) | |
| except Exception: | |
| break | |
| for event in events: | |
| if isinstance(event, h2.events.RequestReceived): | |
| with self._lock: | |
| self.request_count += 1 | |
| state.send_headers( | |
| event.stream_id, | |
| [ | |
| (b":status", b"200"), | |
| (b"server", b"httpcore-e2e"), | |
| (b"x-connection-id", str(connection_id).encode()), | |
| ], | |
| end_stream=self.end_stream, | |
| ) | |
| elif isinstance(event, h2.events.StreamReset): | |
| continue | |
| elif isinstance(event, h2.events.ConnectionTerminated): | |
| break | |
| self._send(conn, state.data_to_send()) | |
| def _send(self, conn: socket.socket, data: bytes) -> None: | |
| if not data: | |
| return | |
| try: | |
| conn.sendall(data) | |
| except OSError: | |
| pass | |
| def run_with_timeout( | |
| func: typing.Callable[[], typing.Any], | |
| timeout: float, | |
| ) -> tuple[bool, typing.Any]: | |
| result: dict[str, typing.Any] = {} | |
| def target() -> None: | |
| try: | |
| result["value"] = func() | |
| except BaseException as exc: | |
| result["error"] = exc | |
| thread = threading.Thread(target=target, daemon=True) | |
| thread.start() | |
| thread.join(timeout=timeout) | |
| if thread.is_alive(): | |
| return False, "timeout" | |
| if "error" in result: | |
| return True, result["error"] | |
| return True, result.get("value") | |
| def sync_open_extra_connection(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| with httpcore.ConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=3, | |
| ) as pool: | |
| with pool.stream("GET", server.url) as response_1: | |
| with pool.stream("GET", server.url) as response_2: | |
| start = time.perf_counter() | |
| def open_third() -> int: | |
| with pool.stream("GET", server.url) as response_3: | |
| return response_3.status | |
| completed, value = run_with_timeout(open_third, timeout) | |
| elapsed = time.perf_counter() - start | |
| return { | |
| "completed": completed, | |
| "value": repr(value) | |
| if isinstance(value, BaseException) | |
| else value, | |
| "elapsed": elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| def sync_queue_timeout(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| with httpcore.ConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=1, | |
| ) as pool: | |
| with pool.stream("GET", server.url) as response_1: | |
| with pool.stream("GET", server.url) as response_2: | |
| start = time.perf_counter() | |
| def third_request() -> str: | |
| try: | |
| pool.request( | |
| "GET", | |
| server.url, | |
| extensions={"timeout": {"pool": timeout / 2}}, | |
| ) | |
| except httpcore.PoolTimeout: | |
| return "PoolTimeout" | |
| return "completed" | |
| completed, value = run_with_timeout(third_request, timeout) | |
| elapsed = time.perf_counter() - start | |
| active_requests_after_timeout = len(pool._requests) | |
| recovery_status = None | |
| recovery_elapsed = None | |
| if completed and value == "PoolTimeout": | |
| recovery_start = time.perf_counter() | |
| with pool.stream("GET", server.url) as response_3: | |
| recovery_status = response_3.status | |
| recovery_elapsed = time.perf_counter() - recovery_start | |
| return { | |
| "completed": completed, | |
| "value": repr(value) if isinstance(value, BaseException) else value, | |
| "elapsed": elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "active_requests_after_timeout": active_requests_after_timeout, | |
| "recovery_status": recovery_status, | |
| "recovery_elapsed": recovery_elapsed, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| def sync_queue_released_before_timeout(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| with httpcore.ConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=1, | |
| ) as pool: | |
| with pool.stream("GET", server.url) as response_1: | |
| with pool.stream("GET", server.url) as response_2: | |
| result: dict[str, typing.Any] = {} | |
| def third_request() -> None: | |
| try: | |
| with pool.stream( | |
| "GET", | |
| server.url, | |
| extensions={"timeout": {"pool": timeout}}, | |
| ) as response_3: | |
| result["value"] = response_3.status | |
| except BaseException as exc: | |
| result["value"] = repr(exc) | |
| thread = threading.Thread(target=third_request, daemon=True) | |
| start = time.perf_counter() | |
| thread.start() | |
| queued = False | |
| while time.perf_counter() - start < timeout: | |
| if any(request.is_queued() for request in pool._requests): | |
| queued = True | |
| break | |
| time.sleep(0.001) | |
| release_start = time.perf_counter() | |
| response_2.close() | |
| thread.join(timeout=timeout) | |
| release_elapsed = time.perf_counter() - release_start | |
| return { | |
| "completed": not thread.is_alive(), | |
| "queued": queued, | |
| "value": result.get("value", "timeout"), | |
| "elapsed": time.perf_counter() - start, | |
| "release_elapsed": release_elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| async def async_open_extra_connection(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| async with httpcore.AsyncConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=3, | |
| ) as pool: | |
| async with pool.stream("GET", server.url) as response_1: | |
| async with pool.stream("GET", server.url) as response_2: | |
| start = time.perf_counter() | |
| try: | |
| async with asyncio.timeout(timeout): | |
| async with pool.stream("GET", server.url) as response_3: | |
| value: typing.Any = response_3.status | |
| completed = True | |
| except BaseException as exc: | |
| completed = not isinstance(exc, TimeoutError) | |
| value = repr(exc) | |
| elapsed = time.perf_counter() - start | |
| return { | |
| "completed": completed, | |
| "value": value, | |
| "elapsed": elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| async def async_queue_timeout(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| async with httpcore.AsyncConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=1, | |
| ) as pool: | |
| async with pool.stream("GET", server.url) as response_1: | |
| async with pool.stream("GET", server.url) as response_2: | |
| start = time.perf_counter() | |
| try: | |
| async with asyncio.timeout(timeout): | |
| await pool.request( | |
| "GET", | |
| server.url, | |
| extensions={"timeout": {"pool": timeout / 2}}, | |
| ) | |
| value: typing.Any = "completed" | |
| completed = True | |
| except httpcore.PoolTimeout: | |
| value = "PoolTimeout" | |
| completed = True | |
| except BaseException as exc: | |
| value = repr(exc) | |
| completed = not isinstance(exc, TimeoutError) | |
| elapsed = time.perf_counter() - start | |
| active_requests_after_timeout = len(pool._requests) | |
| recovery_status = None | |
| recovery_elapsed = None | |
| if completed and value == "PoolTimeout": | |
| recovery_start = time.perf_counter() | |
| async with pool.stream("GET", server.url) as response_3: | |
| recovery_status = response_3.status | |
| recovery_elapsed = time.perf_counter() - recovery_start | |
| return { | |
| "completed": completed, | |
| "value": value, | |
| "elapsed": elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "active_requests_after_timeout": active_requests_after_timeout, | |
| "recovery_status": recovery_status, | |
| "recovery_elapsed": recovery_elapsed, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| async def async_queue_released_before_timeout(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| async with httpcore.AsyncConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=1, | |
| ) as pool: | |
| async with pool.stream("GET", server.url) as response_1: | |
| async with pool.stream("GET", server.url) as response_2: | |
| async def third_request() -> int: | |
| async with pool.stream( | |
| "GET", | |
| server.url, | |
| extensions={"timeout": {"pool": timeout}}, | |
| ) as response_3: | |
| return response_3.status | |
| task = asyncio.create_task(third_request()) | |
| start = time.perf_counter() | |
| queued = False | |
| try: | |
| async with asyncio.timeout(timeout): | |
| while not any( | |
| request.is_queued() for request in pool._requests | |
| ): | |
| await asyncio.sleep(0) | |
| queued = True | |
| except TimeoutError: | |
| pass | |
| release_start = time.perf_counter() | |
| await response_2.aclose() | |
| try: | |
| value: typing.Any = await asyncio.wait_for(task, timeout) | |
| completed = True | |
| except BaseException as exc: | |
| value = repr(exc) | |
| completed = not isinstance(exc, TimeoutError) | |
| release_elapsed = time.perf_counter() - release_start | |
| return { | |
| "completed": completed, | |
| "queued": queued, | |
| "value": value, | |
| "elapsed": time.perf_counter() - start, | |
| "release_elapsed": release_elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| async def async_cancel_queued_request(timeout: float) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=2) as server: | |
| async with httpcore.AsyncConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=1, | |
| ) as pool: | |
| async with pool.stream("GET", server.url) as response_1: | |
| async with pool.stream("GET", server.url) as response_2: | |
| start = time.perf_counter() | |
| task = asyncio.create_task(pool.request("GET", server.url)) | |
| queued = False | |
| try: | |
| async with asyncio.timeout(timeout): | |
| while not any( | |
| request.is_queued() for request in pool._requests | |
| ): | |
| await asyncio.sleep(0) | |
| queued = True | |
| except TimeoutError: | |
| pass | |
| task.cancel() | |
| result = await asyncio.gather(task, return_exceptions=True) | |
| elapsed = time.perf_counter() - start | |
| active_requests_after_cancel = len(pool._requests) | |
| recovery_status = None | |
| recovery_elapsed = None | |
| if queued and isinstance(result[0], asyncio.CancelledError): | |
| recovery_start = time.perf_counter() | |
| async with pool.stream("GET", server.url) as response_3: | |
| recovery_status = response_3.status | |
| recovery_elapsed = time.perf_counter() - recovery_start | |
| return { | |
| "completed": queued | |
| and isinstance(result[0], asyncio.CancelledError), | |
| "value": type(result[0]).__name__, | |
| "elapsed": elapsed, | |
| "pool_connections": len(pool.connections), | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| "active_requests_after_cancel": active_requests_after_cancel, | |
| "recovery_status": recovery_status, | |
| "recovery_elapsed": recovery_elapsed, | |
| "statuses": [response_1.status, response_2.status], | |
| } | |
| def throughput_round(total_requests: int) -> dict[str, typing.Any]: | |
| with H2PriorKnowledgeServer(max_concurrent_streams=100, end_stream=True) as server: | |
| start = time.perf_counter() | |
| with httpcore.ConnectionPool( | |
| http1=False, | |
| http2=True, | |
| max_connections=10, | |
| ) as pool: | |
| for _ in range(total_requests): | |
| with pool.stream("GET", server.url) as response: | |
| if response.status != 200: | |
| raise RuntimeError(f"unexpected status {response.status}") | |
| elapsed = time.perf_counter() - start | |
| return { | |
| "elapsed": elapsed, | |
| "requests_per_second": total_requests / elapsed, | |
| "server_connections": server.connection_count, | |
| "server_requests": server.request_count, | |
| } | |
| def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--timeout", type=float, default=2.0) | |
| parser.add_argument("--bench-runs", type=int, default=0) | |
| parser.add_argument("--bench-requests", type=int, default=200) | |
| args = parser.parse_args() | |
| results: dict[str, typing.Any] = { | |
| "httpcore": getattr(httpcore, "__version__", "unknown"), | |
| "sync_open_extra_connection": sync_open_extra_connection(args.timeout), | |
| "sync_queue_timeout": sync_queue_timeout(args.timeout), | |
| "sync_queue_released_before_timeout": sync_queue_released_before_timeout( | |
| args.timeout | |
| ), | |
| "async_open_extra_connection": asyncio.run( | |
| async_open_extra_connection(args.timeout) | |
| ), | |
| "async_queue_timeout": asyncio.run(async_queue_timeout(args.timeout)), | |
| "async_queue_released_before_timeout": asyncio.run( | |
| async_queue_released_before_timeout(args.timeout) | |
| ), | |
| "async_cancel_queued_request": asyncio.run( | |
| async_cancel_queued_request(args.timeout) | |
| ), | |
| } | |
| if args.bench_runs: | |
| rounds = [throughput_round(args.bench_requests) for _ in range(args.bench_runs)] | |
| elapsed = [item["elapsed"] for item in rounds] | |
| rps = [item["requests_per_second"] for item in rounds] | |
| results["throughput"] = { | |
| "runs": rounds, | |
| "elapsed_mean": statistics.mean(elapsed), | |
| "elapsed_stdev": statistics.stdev(elapsed) if len(elapsed) > 1 else 0.0, | |
| "rps_mean": statistics.mean(rps), | |
| "rps_stdev": statistics.stdev(rps) if len(rps) > 1 else 0.0, | |
| } | |
| print(json.dumps(results, indent=2, sort_keys=True)) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment