Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion proofline/_sync_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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]:
Expand All @@ -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:
Expand Down
62 changes: 46 additions & 16 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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))
Expand All @@ -459,16 +484,16 @@ 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:
response.close()
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
Expand All @@ -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:
Expand All @@ -510,16 +540,16 @@ 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:
await response.aclose()
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
Expand Down
15 changes: 13 additions & 2 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__(
Expand All @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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(
Expand All @@ -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)
Expand Down
90 changes: 89 additions & 1 deletion tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
Loading