From 060efd7a219618f1396c6e82e809e580b7e3693a Mon Sep 17 00:00:00 2001 From: Chethan Raj Date: Fri, 13 Nov 2026 13:10:02 +0530 Subject: [PATCH] feat: add native httpx retries to synchronous and asynchronous clients --- proofline/_sync_http.py | 10 ++- proofline/_transport.py | 62 ++++++++++++++----- proofline/client.py | 15 ++++- tests/test_http.py | 90 ++++++++++++++++++++++++++- tests/test_retry_transport.py | 111 ++++++++++++++++++++++++++++++++++ 5 files changed, 268 insertions(+), 20 deletions(-) create mode 100644 tests/test_retry_transport.py diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index f8273f3f..6b0f6f36 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -11,6 +11,7 @@ import socket import ssl import threading +import time from collections.abc import Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar @@ -121,6 +122,11 @@ def connect_tcp( return NetworkStream(stream) raise failure or httpcore.ConnectError("The host name did not resolve.") + def sleep(self, seconds: float) -> None: + # httpcore sleeps here between connection retries; keep that backoff within the deadline. + bounded = bounded_timeout(seconds) + time.sleep(seconds if bounded is None else bounded) + @contextmanager def mapped_errors() -> Iterator[None]: @@ -146,13 +152,15 @@ def close(self) -> None: class Transport(httpx.BaseTransport): - def __init__(self) -> None: + def __init__(self, retries: int = 0) -> None: + # `retries` re-attempts failed connections only, as httpx.HTTPTransport(retries=...) does. self._pool = httpcore.ConnectionPool( ssl_context=httpcore.default_ssl_context(), network_backend=NetworkBackend(), max_connections=100, max_keepalive_connections=20, keepalive_expiry=5, + retries=retries, ) def handle_request(self, request: httpx.Request) -> httpx.Response: diff --git a/proofline/_transport.py b/proofline/_transport.py index a3b9d688..1d3b31b8 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -40,6 +40,10 @@ VERSION = "5.1.0" MAX_RESPONSE_BYTES = 8 * 1024 * 1024 +DEFAULT_MAX_RETRIES = 3 +MAX_RETRY_DELAY = 60.0 +# Transient statuses a GET is retried on. Other methods are never retried after sending. +RETRYABLE_STATUSES = frozenset({429, 502, 503, 504}) WEEKDAY = r"(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)" FULL_WEEKDAY = r"(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)" MONTH = r"(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)" @@ -193,10 +197,21 @@ def limit_timeout(request: httpx.Request) -> None: } +def max_retries(value: int) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError("max_retries must be an int.") + if value < 0: + raise ValueError("max_retries must be zero or a positive integer.") + return value + + def retry_delay(value: str | None, attempt: int) -> float | None: - """An invalid or longer Retry-After returns the problem without an early retry.""" + """An invalid or longer Retry-After returns the problem without an early retry. + + Without Retry-After the delay doubles from one second (1, 2, 4, ...) up to a minute. + """ if value is None: - return float(2**attempt) + return min(MAX_RETRY_DELAY, 2.0 ** min(attempt, 6)) value = value.strip() if value.isascii() and value.isdigit(): try: @@ -227,7 +242,7 @@ def retry_delay(value: str | None, attempt: int) -> float | None: delay = max(0.0, (date - now).total_seconds()) except (ValueError, TypeError, OverflowError): return None - return delay if math.isfinite(delay) and delay <= 60 else None + return delay if math.isfinite(delay) and delay <= MAX_RETRY_DELAY else None def redacted(value: object, raw: str) -> object: @@ -363,7 +378,7 @@ def check_stream(size: int, status: int, deadline: float) -> None: budget = remaining() if monotonic() >= deadline or (budget is not None and budget <= 0): # Retryable statuses time out as an expired read does; other problems keep their status. - if 200 <= status < 300 or status in (429, 503): + if 200 <= status < 300 or status in RETRYABLE_STATUSES: raise timeout_error() raise unreadable_problem(status) @@ -429,13 +444,23 @@ async def aclose(self) -> None: class RetryTransport(httpx.BaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + """Retry failed connections for every method and transient statuses for GET. + + `max_retries` bounds both layers independently: the inner transport re-attempts a + connection that could not be opened (no request bytes were sent), and this loop + re-sends a GET that got a status in RETRYABLE_STATUSES. + """ + + def __init__( + self, token: SecretStr, timeout: float, max_retries: int = DEFAULT_MAX_RETRIES + ) -> None: self._token = token self._timeout = timeout - self._inner = SyncHTTPTransport() + self._max_retries = max_retries + self._inner = SyncHTTPTransport(retries=max_retries) def handle_request(self, request: httpx.Request) -> httpx.Response: - for attempt in range(4): + for attempt in range(self._max_retries + 1): limit_timeout(request) deadline = monotonic() + self._timeout marker = IO_DEADLINE.set(io_deadline(deadline)) @@ -459,7 +484,7 @@ def handle_request(self, request: httpx.Request) -> httpx.Response: response.read() error = problem(response, self._token) except httpx.HTTPError: - if response.status_code in (429, 503): + if response.status_code in RETRYABLE_STATUSES: raise error = unreadable_problem(response.status_code) finally: @@ -467,8 +492,8 @@ def handle_request(self, request: httpx.Request) -> httpx.Response: delay = retry_delay(response.headers.get("Retry-After"), attempt) if ( request.method != "GET" - or response.status_code not in (429, 503) - or attempt == 3 + or response.status_code not in RETRYABLE_STATUSES + or attempt == self._max_retries or delay is None ): raise error from None @@ -480,13 +505,18 @@ def close(self) -> None: class AsyncRetryTransport(httpx.AsyncBaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + """The asynchronous RetryTransport; `max_retries` bounds the same two layers.""" + + def __init__( + self, token: SecretStr, timeout: float, max_retries: int = DEFAULT_MAX_RETRIES + ) -> None: self._token = token self._timeout = timeout - self._inner = httpx.AsyncHTTPTransport() + self._max_retries = max_retries + self._inner = httpx.AsyncHTTPTransport(retries=max_retries) async def handle_async_request(self, request: httpx.Request) -> httpx.Response: - for attempt in range(4): + for attempt in range(self._max_retries + 1): limit_timeout(request) deadline = monotonic() + self._timeout try: @@ -510,7 +540,7 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: await response.aread() error = problem(response, self._token) except httpx.HTTPError: - if response.status_code in (429, 503): + if response.status_code in RETRYABLE_STATUSES: raise error = unreadable_problem(response.status_code) finally: @@ -518,8 +548,8 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: delay = retry_delay(response.headers.get("Retry-After"), attempt) if ( request.method != "GET" - or response.status_code not in (429, 503) - or attempt == 3 + or response.status_code not in RETRYABLE_STATUSES + or attempt == self._max_retries or delay is None ): raise error from None diff --git a/proofline/client.py b/proofline/client.py index 0a8239b4..2295e4fc 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -180,6 +180,11 @@ class ProoflineClient(Operations): Name resolution, connection, TLS and socket operations stop at the configured HTTP timeout and at a wait deadline. + + ``max_retries`` (default 3, ``0`` disables) bounds retries of connections that + could not be opened, for any method, and of GET requests answered with 429, 502, + 503 or 504. Status retries honour ``Retry-After`` up to 60 seconds and otherwise + back off exponentially (1s, 2s, 4s, ...). Other methods are never re-sent. """ def __init__( @@ -188,7 +193,9 @@ def __init__( *, base_url: str = "https://proofline.sh", timeout: float = 30, + max_retries: int = _transport.DEFAULT_MAX_RETRIES, ) -> None: + retries = _transport.max_retries(max_retries) self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) self._http = httpx.Client( @@ -201,7 +208,7 @@ def __init__( timeout=httpx.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.RetryTransport(self._api.token, timeout), + transport=_transport.RetryTransport(self._api.token, timeout, retries), ) self._api.set_httpx_client(self._http) self.mcp = McpClient(self._http) @@ -511,13 +518,17 @@ def wait_for_review( class AsyncProoflineClient(AsyncOperations): + """Asynchronous typed HTTP operations; options match ProoflineClient.""" + def __init__( self, token: str | SecretStr | None = None, *, base_url: str = "https://proofline.sh", timeout: float = 30, + max_retries: int = _transport.DEFAULT_MAX_RETRIES, ) -> None: + retries = _transport.max_retries(max_retries) self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) self._http = httpx.AsyncClient( @@ -530,7 +541,7 @@ def __init__( timeout=httpx.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.AsyncRetryTransport(self._api.token, timeout), + transport=_transport.AsyncRetryTransport(self._api.token, timeout, retries), ) self._api.set_async_httpx_client(self._http) self.mcp = AsyncMcpClient(self._http) diff --git a/tests/test_http.py b/tests/test_http.py index d308af0f..1ee3c9b8 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -796,7 +796,7 @@ def now(cls, tz: Any = None) -> datetime: @MODES -@pytest.mark.parametrize("status", [429, 503]) +@pytest.mark.parametrize("status", [429, 502, 503, 504]) async def test_retry_count_is_bounded_for_rate_limit_and_provider_unavailable( mode: str, status: int ) -> None: @@ -840,6 +840,94 @@ async def test_retry_count_is_bounded_for_rate_limit_and_provider_unavailable( assert json.loads(server.requests[0].body) == {"mode": "FULL"} +@MODES +@pytest.mark.parametrize("max_retries", [0, 1, 5]) +async def test_max_retries_bounds_status_retries(mode: str, max_retries: int) -> None: + with Server( + lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": "0"}) + ) as server: + async with session(mode, server.url, max_retries=max_retries) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "get_finding", ORG, FINDING) + assert raised.value.status == 503 + assert len(server.requests) == max_retries + 1 + + +@MODES +async def test_status_retry_without_retry_after_backs_off_exponentially( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: ( + Reply(502, {"detail": "Bad gateway."}) if index < 3 else Reply(body=finding()) + ) + ) as server: + async with session(mode, server.url) as client: + assert (await call(client, "get_finding", ORG, FINDING)).id == FINDING + assert len(server.requests) == 4 + assert clock.delays == [1, 2, 4] + + +def test_retry_backoff_is_capped() -> None: + assert _transport.retry_delay(None, 5) == 32 + assert _transport.retry_delay(None, 6) == 60 + assert _transport.retry_delay(None, 10_000) == 60 + + +@pytest.mark.parametrize( + ("value", "error"), [(-1, ValueError), (True, TypeError), (1.5, TypeError), ("3", TypeError)] +) +@pytest.mark.parametrize("factory", [ProoflineClient, AsyncProoflineClient]) +def test_max_retries_rejects_invalid_values( + factory: type[Client], value: Any, error: type[Exception] +) -> None: + with pytest.raises(error): + factory(SecretStr(TOKEN), max_retries=value) + + +@MODES +@pytest.mark.parametrize("max_retries", [0, 2]) +async def test_max_retries_bounds_connection_retries_for_every_method( + mode: str, max_retries: int, monkeypatch: pytest.MonkeyPatch +) -> None: + import httpcore + from httpcore._backends.auto import AutoBackend + + attempts: list[str] = [] + backend: Any = _sync_http.NetworkBackend if mode == "sync" else AutoBackend + connect = backend.connect_tcp + + def refuse(self: Any, *args: Any, **kwargs: Any) -> Any: + attempts.append("connect") + if len(attempts) <= 2: + raise httpcore.ConnectError("Connection refused.") + return connect(self, *args, **kwargs) + + async def async_refuse(self: Any, *args: Any, **kwargs: Any) -> Any: + attempts.append("connect") + if len(attempts) <= 2: + raise httpcore.ConnectError("Connection refused.") + return await connect(self, *args, **kwargs) + + monkeypatch.setattr(backend, "connect_tcp", refuse if mode == "sync" else async_refuse) + with Server( + lambda request, index: Reply(body={"public_key": "pk", "review_id": str(REVIEW)}) + ) as server: + async with session(mode, server.url, max_retries=max_retries) as client: + if max_retries == 0: + with pytest.raises(ProoflineError) as raised: + await call(client, "rerun_review", ORG, REVIEW) + assert raised.value.type == "urn:proofline:sdk:transport-unavailable" + assert attempts == ["connect"] + assert server.requests == [] + else: + # A refused connection sent nothing, so even a POST is safe to re-attempt. + await call(client, "rerun_review", ORG, REVIEW) + assert attempts == ["connect"] * 3 + assert [request.method for request in server.requests] == ["POST"] + + @MODES async def test_long_retry_after_is_not_retried_early( mode: str, monkeypatch: pytest.MonkeyPatch diff --git a/tests/test_retry_transport.py b/tests/test_retry_transport.py new file mode 100644 index 00000000..8086ca3d --- /dev/null +++ b/tests/test_retry_transport.py @@ -0,0 +1,111 @@ +"""Retry policy against a mocked inner httpx transport, with no network or real sleeps.""" + +from __future__ import annotations + +from collections.abc import Callable + +import httpx +import pytest +from pydantic import SecretStr + +from proofline import AsyncProoflineClient, ProoflineClient, ProoflineError, _sync_http, _transport + +from .fixtures import FINDING, ORG, TOKEN, finding + +Responder = Callable[[httpx.Request, int], httpx.Response] + + +def unavailable(request: httpx.Request, index: int) -> httpx.Response: + return httpx.Response(503, json={"detail": "Unavailable."}, request=request) + + +def recover_after(failures: int) -> Responder: + def respond(request: httpx.Request, index: int) -> httpx.Response: + if index < failures: + return unavailable(request, index) + return httpx.Response(200, json=finding(), request=request) + + return respond + + +class MockTransport: + """Stands in for the inner httpx transport each client's RetryTransport wraps.""" + + def __init__(self, monkeypatch: pytest.MonkeyPatch, respond: Responder) -> None: + self.requests: list[httpx.Request] = [] + self.delays: list[float] = [] + self._respond = respond + + def handle(_self: object, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + return self._respond(request, len(self.requests) - 1) + + async def handle_async(_self: object, request: httpx.Request) -> httpx.Response: + return handle(_self, request) + + async def async_sleep(delay: float) -> None: + self.delays.append(delay) + + monkeypatch.setattr(_sync_http.Transport, "handle_request", handle) + monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", handle_async) + monkeypatch.setattr(_transport, "sleep", self.delays.append) + monkeypatch.setattr(_transport, "async_sleep", async_sleep) + + +@pytest.mark.parametrize("max_retries", [0, 1, 3, 5]) +def test_sync_client_retries_503_up_to_max_retries( + monkeypatch: pytest.MonkeyPatch, max_retries: int +) -> None: + transport = MockTransport(monkeypatch, unavailable) + with ProoflineClient(SecretStr(TOKEN), max_retries=max_retries) as client: + with pytest.raises(ProoflineError) as raised: + client.get_finding(ORG, FINDING) + assert raised.value.status == 503 + assert len(transport.requests) == max_retries + 1 + assert all(request.method == "GET" for request in transport.requests) + assert transport.delays == [1, 2, 4, 8, 16][:max_retries] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("max_retries", [0, 1, 3, 5]) +async def test_async_client_retries_503_up_to_max_retries( + monkeypatch: pytest.MonkeyPatch, max_retries: int +) -> None: + transport = MockTransport(monkeypatch, unavailable) + async with AsyncProoflineClient(SecretStr(TOKEN), max_retries=max_retries) as client: + with pytest.raises(ProoflineError) as raised: + await client.get_finding(ORG, FINDING) + assert raised.value.status == 503 + assert len(transport.requests) == max_retries + 1 + assert transport.delays == [1, 2, 4, 8, 16][:max_retries] + + +def test_sync_client_succeeds_when_503_clears_within_max_retries( + monkeypatch: pytest.MonkeyPatch, +) -> None: + transport = MockTransport(monkeypatch, recover_after(2)) + with ProoflineClient(SecretStr(TOKEN), max_retries=2) as client: + assert client.get_finding(ORG, FINDING).id == FINDING + assert len(transport.requests) == 3 + assert transport.delays == [1, 2] + + +@pytest.mark.asyncio +async def test_async_client_succeeds_when_503_clears_within_max_retries( + monkeypatch: pytest.MonkeyPatch, +) -> None: + transport = MockTransport(monkeypatch, recover_after(2)) + async with AsyncProoflineClient(SecretStr(TOKEN), max_retries=2) as client: + assert (await client.get_finding(ORG, FINDING)).id == FINDING + assert len(transport.requests) == 3 + assert transport.delays == [1, 2] + + +@pytest.mark.asyncio +async def test_503_outlasting_max_retries_is_raised(monkeypatch: pytest.MonkeyPatch) -> None: + transport = MockTransport(monkeypatch, recover_after(2)) + async with AsyncProoflineClient(SecretStr(TOKEN), max_retries=1) as client: + with pytest.raises(ProoflineError) as raised: + await client.get_finding(ORG, FINDING) + assert raised.value.status == 503 + assert len(transport.requests) == 2