diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index 0ef0b5b0..53528e06 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -21,16 +21,57 @@ import httpx2 IO_DEADLINE: ContextVar[float | None] = ContextVar("proofline_io_deadline", default=None) - - -def bounded_timeout(timeout: float | None) -> float | None: +CALLER_DEADLINE: ContextVar[float | None] = ContextVar( + "proofline_caller_deadline", + default=None, +) + +_CORE_TIMEOUT_MAP: tuple[ + tuple[type[httpcore2.TimeoutException], type[httpx2.TimeoutException]], ... +] = ( + (httpcore2.ConnectTimeout, httpx2.ConnectTimeout), + (httpcore2.ReadTimeout, httpx2.ReadTimeout), + (httpcore2.WriteTimeout, httpx2.WriteTimeout), + (httpcore2.PoolTimeout, httpx2.PoolTimeout), +) + + +def bounded_timeout_with_provenance( + timeout: float | None, + timeout_exc: type[httpcore2.TimeoutException] = httpcore2.ReadTimeout, +) -> tuple[float | None, bool]: + """Calculate the I/O timeout and whether the caller deadline bounds it.""" deadline = IO_DEADLINE.get() if deadline is None: - return timeout + return timeout, False + + caller = CALLER_DEADLINE.get() remaining = deadline - monotonic() + + caller_bounded = ( + caller is not None and caller <= deadline and (timeout is None or remaining <= timeout) + ) + if remaining <= 0: - raise httpcore2.ReadTimeout("The request deadline expired.") - return remaining if timeout is None else min(timeout, remaining) + error = timeout_exc("The request deadline expired.") + setattr(error, "_deadline_bounded", caller_bounded) + raise error + + enforced_timeout = remaining if timeout is None else min(timeout, remaining) + return enforced_timeout, caller_bounded + + +def bounded_timeout( + timeout: float | None, + timeout_exc: type[httpcore2.TimeoutException] = httpcore2.ReadTimeout, +) -> float | None: + enforced_timeout, _ = bounded_timeout_with_provenance(timeout, timeout_exc) + return enforced_timeout + + +def read_budget(timeout: float | None) -> tuple[float | None, bool]: + """Calculate the socket read budget and its caller-deadline provenance.""" + return bounded_timeout_with_provenance(timeout, httpcore2.ReadTimeout) class Lookup: @@ -68,8 +109,13 @@ def resolve(host: str, port: int, timeout: float | None) -> list[str]: ipaddress.ip_address(host) except ValueError: lookup = Lookup(host, port) - threading.Thread(target=lookup.run, name="proofline-dns", daemon=True).start() + threading.Thread( + target=lookup.run, + name="proofline-dns", + daemon=True, + ).start() return lookup.addresses(timeout) + return [host] @@ -78,10 +124,25 @@ def __init__(self, inner: httpcore2.NetworkStream) -> None: self._inner = inner def read(self, max_bytes: int, timeout: float | None = None) -> bytes: - return self._inner.read(max_bytes, bounded_timeout(timeout)) + enforced_timeout, caller_bounded = read_budget(timeout) + + try: + return self._inner.read(max_bytes, enforced_timeout) + except httpcore2.ReadTimeout as error: + setattr(error, "_deadline_bounded", caller_bounded) + raise def write(self, buffer: bytes, timeout: float | None = None) -> None: - self._inner.write(buffer, bounded_timeout(timeout)) + enforced_timeout, caller_bounded = bounded_timeout_with_provenance( + timeout, + httpcore2.WriteTimeout, + ) + + try: + self._inner.write(buffer, enforced_timeout) + except httpcore2.WriteTimeout as error: + setattr(error, "_deadline_bounded", caller_bounded) + raise def close(self) -> None: self._inner.close() @@ -92,10 +153,23 @@ def start_tls( server_hostname: str | None = None, timeout: float | None = None, ) -> httpcore2.NetworkStream: - return NetworkStream( - self._inner.start_tls(ssl_context, server_hostname, bounded_timeout(timeout)) + enforced_timeout, caller_bounded = bounded_timeout_with_provenance( + timeout, + httpcore2.ConnectTimeout, ) + try: + stream = self._inner.start_tls( + ssl_context, + server_hostname, + enforced_timeout, + ) + except httpcore2.ConnectTimeout as error: + setattr(error, "_deadline_bounded", caller_bounded) + raise + + return NetworkStream(stream) + def get_extra_info(self, info: str) -> Any: return self._inner.get_extra_info(info) @@ -110,15 +184,47 @@ def connect_tcp( socket_options: Iterable[Any] | None = None, ) -> httpcore2.NetworkStream: failure: httpcore2.ConnectError | httpcore2.ConnectTimeout | None = None - for address in resolve(host, port, bounded_timeout(timeout)): + + connect_timeout, lookup_caller_bounded = bounded_timeout_with_provenance( + timeout, + httpcore2.ConnectTimeout, + ) + + try: + addresses = iter(resolve(host, port, connect_timeout)) + except httpcore2.ConnectTimeout as error: + setattr(error, "_deadline_bounded", lookup_caller_bounded) + raise + + while True: + # First check whether another IP address is available. + try: + address = next(addresses) + except StopIteration: + break + + # Only calculate the deadline if there is an address to try. + address_timeout, caller_bounded = bounded_timeout_with_provenance( + timeout, + httpcore2.ConnectTimeout, + ) + try: stream = super().connect_tcp( - address, port, bounded_timeout(timeout), local_address, socket_options + address, + port, + address_timeout, + local_address, + socket_options, ) - except (httpcore2.ConnectError, httpcore2.ConnectTimeout) as error: + except httpcore2.ConnectTimeout as error: + setattr(error, "_deadline_bounded", caller_bounded) + failure = error + except httpcore2.ConnectError as error: failure = error else: return NetworkStream(stream) + raise failure or httpcore2.ConnectError("The host name did not resolve.") @@ -126,8 +232,20 @@ def connect_tcp( def mapped_errors() -> Iterator[None]: try: yield - except httpcore2.TimeoutException: - raise httpx2.ReadTimeout("The request deadline expired.") from None + except httpcore2.TimeoutException as error: + mapped_cls = next( + (httpx_cls for core_cls, httpx_cls in _CORE_TIMEOUT_MAP if isinstance(error, core_cls)), + httpx2.TimeoutException, + ) + + mapped_error = mapped_cls("The request deadline expired.") + + deadline_bounded = getattr(error, "_deadline_bounded", None) + if deadline_bounded is not None: + setattr(mapped_error, "_deadline_bounded", deadline_bounded) + + raise mapped_error from None + except (httpcore2.NetworkError, httpcore2.ProtocolError): raise httpx2.TransportError("The HTTP transport failed.") from None @@ -158,6 +276,7 @@ def __init__(self) -> None: def handle_request(self, request: httpx2.Request) -> httpx2.Response: if not isinstance(request.stream, httpx2.SyncByteStream): raise httpx2.TransportError("The synchronous request has an invalid stream.") + core_request = httpcore2.Request( method=request.method, url=httpcore2.URL( @@ -170,8 +289,10 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: content=request.stream, extensions=request.extensions, ) + with mapped_errors(): response = self._pool.handle_request(core_request) + return httpx2.Response( response.status, headers=response.headers, diff --git a/proofline/_transport.py b/proofline/_transport.py index b1ab7c67..7baba552 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -35,7 +35,7 @@ RunNowRefused, ) from ._generated.types import Unset -from ._sync_http import IO_DEADLINE +from ._sync_http import CALLER_DEADLINE, IO_DEADLINE from ._sync_http import Transport as SyncHTTPTransport VERSION = "9.3.0" @@ -65,6 +65,12 @@ | RunNowRefusalViewType9 ) DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None) +_TIMEOUT_PHASES: tuple[tuple[type[httpx2.TimeoutException], str], ...] = ( + (httpx2.ConnectTimeout, "connect"), + (httpx2.ReadTimeout, "read"), + (httpx2.WriteTimeout, "write"), + (httpx2.PoolTimeout, "pool"), +) class BearerAuth(httpx2.Auth): @@ -103,6 +109,7 @@ def __init__( self.title = title self.refusal = refusal self.repository_name = repository_name + self._deadline_bounded = False super().__init__(f"Proofline request failed (HTTP {status}).") def __repr__(self) -> str: @@ -153,11 +160,39 @@ def invalid_response() -> ProoflineError: ) -def network_error(error: httpx2.HTTPError) -> ProoflineError: +def timeout_error(*, deadline_bounded: bool = False) -> ProoflineError: + error = ProoflineError(0, "urn:proofline:sdk:timeout", "The request deadline expired.") + error._deadline_bounded = deadline_bounded + return error + + +def is_deadline_timeout(error: ProoflineError) -> bool: + return ( + error.status == 0 and error.type == "urn:proofline:sdk:timeout" and error._deadline_bounded + ) + + +def network_error( + error: httpx2.HTTPError, + *, + bounded_phases: frozenset[str] = frozenset(), +) -> ProoflineError: if isinstance(error, httpx2.TimeoutException): - return timeout_error() + deadline_bounded = getattr(error, "_deadline_bounded", None) + + if deadline_bounded is not None: + return timeout_error(deadline_bounded=bool(deadline_bounded)) + + phase = next( + (name for exc_type, name in _TIMEOUT_PHASES if isinstance(error, exc_type)), + None, + ) + return timeout_error(deadline_bounded=phase is not None and phase in bounded_phases) + return ProoflineError( - 0, "urn:proofline:sdk:transport-unavailable", "Could not reach the Proofline API." + 0, + "urn:proofline:sdk:transport-unavailable", + "Could not reach the Proofline API.", ) @@ -173,26 +208,62 @@ def operation_errors() -> Iterator[None]: raise invalid_response() from None -def timeout_error() -> ProoflineError: - return ProoflineError(0, "urn:proofline:sdk:timeout", "The request deadline expired.") - - def remaining() -> float | None: deadline = DEADLINE.get() return None if deadline is None else max(0.0, deadline - monotonic()) -def limit_timeout(request: httpx2.Request) -> None: - budget = remaining() - if budget is None: - return - if budget <= 0: +def limit_timeout( + request: httpx2.Request, + configured_timeouts: dict[str, float | None] | None = None, + *, + internal_deadline: float | None = None, +) -> frozenset[str]: + caller = DEADLINE.get() + now = monotonic() + caller_budget = None if caller is None else caller - now + internal_budget = None if internal_deadline is None else internal_deadline - now + + if ( + caller_budget is not None + and caller_budget <= 0 + and (internal_budget is None or caller_budget <= internal_budget) + ): + raise timeout_error(deadline_bounded=True) + if internal_budget is not None and internal_budget <= 0: raise timeout_error() - configured = request.extensions.get("timeout", {}) - request.extensions["timeout"] = { - field: budget if configured.get(field) is None else min(budget, configured[field]) - for field in ("connect", "read", "write", "pool") - } + + budgets = [budget for budget in (caller_budget, internal_budget) if budget is not None] + if not budgets: + return frozenset() + + effective_budget = min(budgets) + caller_dominates_internal = caller_budget is not None and ( + internal_budget is None or caller_budget <= internal_budget + ) + configured = ( + request.extensions.get("timeout", {}) + if configured_timeouts is None + else configured_timeouts + ) + + bounded: list[str] = [] + limited: dict[str, float] = {} + for field in ("connect", "read", "write", "pool"): + phase_timeout = configured.get(field) + if phase_timeout is None or effective_budget <= phase_timeout: + if ( + caller_dominates_internal + and caller_budget is not None + and (phase_timeout is None or caller_budget <= phase_timeout) + ): + bounded.append(field) + limited[field] = effective_budget + else: + limited[field] = phase_timeout + + request.extensions["timeout"] = limited + return frozenset(bounded) def retry_delay(value: str | None, attempt: int) -> float | None: @@ -364,11 +435,18 @@ def check_stream(size: int, status: int, deadline: float) -> None: raise ProoflineError( status, "urn:proofline:sdk:invalid-response", "The response exceeds 8 MiB." ) - budget = remaining() - if monotonic() >= deadline or (budget is not None and budget <= 0): + + caller = DEADLINE.get() + now = monotonic() + caller_expired = caller is not None and now >= caller + internal_expired = now >= deadline + + if caller_expired or internal_expired: # Retryable statuses time out as an expired read does; other problems keep their status. if 200 <= status < 300 or status in (429, 503): - raise timeout_error() + raise timeout_error( + deadline_bounded=caller_expired and caller is not None and caller <= deadline + ) raise unreadable_problem(status) @@ -377,55 +455,172 @@ def io_deadline(deadline: float) -> float: return deadline if caller is None else min(deadline, caller) + def io_budget(deadline: float) -> float: + caller = DEADLINE.get() + caller_bounded = caller is not None and caller <= deadline + budget = io_deadline(deadline) - monotonic() if budget <= 0: - raise httpx2.ReadTimeout("The request deadline expired.") + error = httpx2.ReadTimeout("The request deadline expired.") + setattr(error, "_deadline_bounded", caller_bounded) + raise error + return budget + class DeadlineStream(httpx2.SyncByteStream): - def __init__(self, inner: httpx2.SyncByteStream, status: int, deadline: float) -> None: + def __init__( + self, + inner: httpx2.SyncByteStream, + status: int, + deadline: float, + *, + read_bounded: bool = False, + ) -> None: self._inner = inner self._status = status self._deadline = deadline + self._read_bounded = read_bounded def __iter__(self) -> Iterator[bytes]: size = 0 - deadline = IO_DEADLINE.set(io_deadline(self._deadline)) + bounded = frozenset({"read"}) if self._read_bounded else frozenset() + try: - for chunk in self._inner: + # Install deadline context while creating the iterator too. + deadline_token = IO_DEADLINE.set(io_deadline(self._deadline)) + caller_token = CALLER_DEADLINE.set(DEADLINE.get()) + + try: + iterator = iter(self._inner) + finally: + CALLER_DEADLINE.reset(caller_token) + IO_DEADLINE.reset(deadline_token) + + while True: + # Set deadline context only while fetching the next chunk. + deadline_token = IO_DEADLINE.set(io_deadline(self._deadline)) + caller_token = CALLER_DEADLINE.set(DEADLINE.get()) + + try: + chunk = next(iterator) + except StopIteration: + break + finally: + # Restore the previous context before yielding. + CALLER_DEADLINE.reset(caller_token) + IO_DEADLINE.reset(deadline_token) + size += len(chunk) check_stream(size, self._status, self._deadline) yield chunk + check_stream(size, self._status, self._deadline) - finally: - IO_DEADLINE.reset(deadline) + + except httpx2.TimeoutException as error: + if not (200 <= self._status < 300 or self._status in (429, 503)): + raise unreadable_problem(self._status) from None + + read_bounded = getattr(error, "_deadline_bounded", None) + + if read_bounded is None: + read_bounded = "read" in bounded + + raise network_error( + error, + bounded_phases=(frozenset({"read"}) if read_bounded else frozenset()), + ) from None def close(self) -> None: self._inner.close() class AsyncDeadlineStream(httpx2.AsyncByteStream): - def __init__(self, inner: httpx2.AsyncByteStream, status: int, deadline: float) -> None: + def __init__( + self, + inner: httpx2.AsyncByteStream, + status: int, + deadline: float, + *, + read_bounded: bool = False, + ) -> None: self._inner = inner self._status = status self._deadline = deadline + self._read_bounded = read_bounded async def __aiter__(self) -> AsyncIterator[bytes]: size = 0 iterator = self._inner.__aiter__() + bounded = frozenset({"read"}) if self._read_bounded else frozenset() + while True: + # Take one clock reading so the remaining budget and + # timeout attribution are based on the same instant. + caller = DEADLINE.get() + now = monotonic() + + effective_deadline = self._deadline if caller is None else min(self._deadline, caller) + + budget = effective_deadline - now + + # Record which deadline actually limits this read. + scope_caller_bounded = caller is not None and caller <= self._deadline + + # The deadline may already have expired before we enter + # the AnyIO timeout scope. + if budget <= 0: + if not (200 <= self._status < 300 or self._status in (429, 503)): + raise unreadable_problem(self._status) from None + + raise timeout_error( + deadline_bounded=scope_caller_bounded, + ) from None + try: - with anyio.fail_after(io_budget(self._deadline)): + # The scope is limited by the earlier of the + # internal deadline and the caller's deadline. + with anyio.fail_after(budget) as scope: chunk = await anext(iterator) + except StopAsyncIteration: break + except TimeoutError: - raise httpx2.ReadTimeout("The request deadline expired.") from None + # Preserve non-retryable HTTP failures even if + # reading their response body raises a timeout. + if not (200 <= self._status < 300 or self._status in (429, 503)): + raise unreadable_problem(self._status) from None + + # Only classify this as our deadline timeout if + # this particular AnyIO scope caught the cancellation. + # Normalize an independent timeout without attributing it + # to the caller's deadline. + + if not scope.cancelled_caught: + raise timeout_error(deadline_bounded=False) from None + + raise timeout_error( + deadline_bounded=scope_caller_bounded, + ) from None + + except httpx2.TimeoutException as error: + # This is a transport-level timeout, so use the + # configured read-phase timeout provenance. + if not (200 <= self._status < 300 or self._status in (429, 503)): + raise unreadable_problem(self._status) from None + + raise network_error( + error, + bounded_phases=bounded, + ) from None + size += len(chunk) check_stream(size, self._status, self._deadline) yield chunk + check_stream(size, self._status, self._deadline) async def aclose(self) -> None: @@ -439,14 +634,24 @@ def __init__(self, token: SecretStr, timeout: float) -> None: self._inner = SyncHTTPTransport() def handle_request(self, request: httpx2.Request) -> httpx2.Response: + configured_timeouts = dict(request.extensions.get("timeout", {})) for attempt in range(4): - limit_timeout(request) deadline = monotonic() + self._timeout - marker = IO_DEADLINE.set(io_deadline(deadline)) + bounded = limit_timeout( + request, + configured_timeouts, + internal_deadline=deadline, + ) + caller = DEADLINE.get() + caller_marker = CALLER_DEADLINE.set(caller) + io_marker = IO_DEADLINE.set(io_deadline(deadline)) try: response = self._inner.handle_request(request) + except httpx2.TimeoutException as error: + raise network_error(error, bounded_phases=bounded) from None finally: - IO_DEADLINE.reset(marker) + IO_DEADLINE.reset(io_marker) + CALLER_DEADLINE.reset(caller_marker) if 300 <= response.status_code < 400: response.close() raise redirect_error(response.status_code) from None @@ -456,16 +661,25 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: if not isinstance(response.stream, httpx2.SyncByteStream): response.close() raise unreadable_problem(response.status_code) - response.stream = DeadlineStream(response.stream, response.status_code, deadline) + response.stream = DeadlineStream( + response.stream, + response.status_code, + deadline, + read_bounded="read" in bounded, + ) if 200 <= response.status_code < 300: return response try: response.read() - error = problem(response, self._token) + failure = problem(response, self._token) + except httpx2.TimeoutException as exc: + if response.status_code in (429, 503): + raise network_error(exc, bounded_phases=bounded) from None + failure = unreadable_problem(response.status_code) except httpx2.HTTPError: if response.status_code in (429, 503): raise - error = unreadable_problem(response.status_code) + failure = unreadable_problem(response.status_code) finally: response.close() delay = retry_delay(response.headers.get("Retry-After"), attempt) @@ -475,7 +689,7 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: or attempt == 3 or delay is None ): - raise error from None + raise failure from None sleep(delay_within_deadline(delay)) raise timeout_error() @@ -490,14 +704,25 @@ def __init__(self, token: SecretStr, timeout: float) -> None: self._inner = httpx2.AsyncHTTPTransport() async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response: + configured_timeouts = dict(request.extensions.get("timeout", {})) for attempt in range(4): - limit_timeout(request) deadline = monotonic() + self._timeout + bounded = limit_timeout( + request, + configured_timeouts, + internal_deadline=deadline, + ) + caller = DEADLINE.get() + deadline_bounded = caller is not None and caller <= deadline try: - with anyio.fail_after(io_budget(deadline)): + with anyio.fail_after(io_budget(deadline)) as scope: response = await self._inner.handle_async_request(request) except TimeoutError: - raise httpx2.ReadTimeout("The request deadline expired.") from None + raise timeout_error( + deadline_bounded=scope.cancelled_caught and deadline_bounded, + ) from None + except httpx2.TimeoutException as error: + raise network_error(error, bounded_phases=bounded) from None if 300 <= response.status_code < 400: await response.aclose() raise redirect_error(response.status_code) from None @@ -507,16 +732,25 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response if not isinstance(response.stream, httpx2.AsyncByteStream): await response.aclose() raise unreadable_problem(response.status_code) - response.stream = AsyncDeadlineStream(response.stream, response.status_code, deadline) + response.stream = AsyncDeadlineStream( + response.stream, + response.status_code, + deadline, + read_bounded="read" in bounded, + ) if 200 <= response.status_code < 300: return response try: await response.aread() - error = problem(response, self._token) + failure = problem(response, self._token) + except httpx2.TimeoutException as exc: + if response.status_code in (429, 503): + raise network_error(exc, bounded_phases=bounded) from None + failure = unreadable_problem(response.status_code) except httpx2.HTTPError: if response.status_code in (429, 503): raise - error = unreadable_problem(response.status_code) + failure = unreadable_problem(response.status_code) finally: await response.aclose() delay = retry_delay(response.headers.get("Retry-After"), attempt) @@ -526,7 +760,7 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response or attempt == 3 or delay is None ): - raise error from None + raise failure from None await async_sleep(delay_within_deadline(delay)) raise timeout_error() diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..775b93a4 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -568,7 +568,7 @@ def wait_for_review( try: last = self.get_review(organization_id, review_id) except ProoflineError as error: - if error.status == 0 and (_transport.remaining() or 0) <= 0: + if _transport.is_deadline_timeout(error): break raise if (_transport.remaining() or 0) <= 0: @@ -954,7 +954,7 @@ async def wait_for_review( try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: - if error.status == 0 and (_transport.remaining() or 0) <= 0: + if _transport.is_deadline_timeout(error): break raise if (_transport.remaining() or 0) <= 0: diff --git a/tests/http_server.py b/tests/http_server.py index 455674f7..384506ff 100644 --- a/tests/http_server.py +++ b/tests/http_server.py @@ -88,7 +88,7 @@ def dispatch(self) -> None: time.sleep(reply.pause) self.wfile.write(payload[split:]) self.wfile.flush() - except (BrokenPipeError, ConnectionResetError): + except (BrokenPipeError, ConnectionResetError, ConnectionAbortedError): pass self._server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..5e95b7c6 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import math import csv import gzip import inspect @@ -14,7 +15,7 @@ import time import tomllib import traceback -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Iterator from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -22,6 +23,8 @@ from urllib.parse import parse_qs, urlsplit from uuid import UUID +import anyio +import httpcore2 import httpx2 import pytest from pydantic import SecretStr @@ -1565,10 +1568,79 @@ async def count_async( assert len(server.requests) == 1 +@pytest.mark.anyio +async def test_async_body_timeout_preserves_nonretryable_http_status( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + + class IndependentTimeoutStream(httpx2.AsyncByteStream): + async def __aiter__(self) -> AsyncIterator[bytes]: + raise TimeoutError("independent body timeout") + yield b"" # Makes this an async generator. + + async def aclose(self) -> None: + pass + + stream = _transport.AsyncDeadlineStream( + IndependentTimeoutStream(), + status=401, + deadline=clock.now + 10, + ) + + with pytest.raises(ProoflineError) as raised: + async for _ in stream: + pass + + assert raised.value.status == 401 + +async def test_sync_read_timeout_uses_current_caller_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + with monkeypatch.context() as patch: + clock = Clock(patch) + original_read = _sync_http.NetworkStream.read + read_started = False + + def advance_before_read( + stream: _sync_http.NetworkStream, + max_bytes: int, + timeout: float | None = None, + ) -> bytes: + nonlocal read_started + if not read_started: + read_started = True + clock.now += 0.005 + return original_read(stream, max_bytes, timeout) + + patch.setattr(_sync_http.NetworkStream, "read", advance_before_read) + + with Server(lambda request, index: Reply(body=review(), header_pause=0.1)) as server: + async with session("sync", server.url, timeout=0.01) as client: + # Keep the internal request deadline later than the caller deadline. + client._http._transport._timeout = 5 + + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=0.012, + ) + + assert read_started + assert clock.now == pytest.approx(100.005) + assert result.status == "TIMED_OUT" + assert result.review is None + assert result.review_url == (f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}") + + @MODES async def test_streaming_and_resolution_keep_deadline_outcomes_explicit( mode: str, monkeypatch: pytest.MonkeyPatch ) -> None: + # 1. Caller deadline expires during streaming. + # Expected: wait_for_review returns TIMED_OUT. with Server(lambda request, index: Reply(body=review(), chunk_size=4, pause=0.01)) as server: async with session(mode, server.url) as client: started = time.monotonic() @@ -1576,6 +1648,18 @@ async def test_streaming_and_resolution_keep_deadline_outcomes_explicit( assert result.status == "TIMED_OUT" assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" assert time.monotonic() - started < 0.5 + + # 2. Internal HTTP timeout expires before the caller's deadline. + # Expected: SDK timeout error, NOT TIMED_OUT. + with Server(lambda request, index: Reply(body=review(), chunk_size=4, pause=0.01)) as server: + async with session(mode, server.url, timeout=0.06) as client: + started = time.monotonic() + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_review", ORG, REVIEW, timeout=1) + assert raised.value.type == "urn:proofline:sdk:timeout" + assert time.monotonic() - started < 0.5 + + # 3. Existing get_finding internal HTTP timeout coverage. with Server(lambda request, index: Reply(body=finding(), chunk_size=4, pause=0.01)) as server: async with session(mode, server.url, timeout=0.06) as client: started = time.monotonic() @@ -1584,6 +1668,7 @@ async def test_streaming_and_resolution_keep_deadline_outcomes_explicit( assert raised.value.type == "urn:proofline:sdk:timeout" assert time.monotonic() - started < 0.5 + # 4. DNS resolution timeout. original_resolution = socket.getaddrinfo resolution_started = threading.Event() resolution_released = threading.Event() @@ -1660,25 +1745,321 @@ def resolve(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: original = socket.getaddrinfo monkeypatch.setattr(socket, "getaddrinfo", resolve) + with Server(lambda request, index: Reply(body=finding())) as server: port = server.url.rsplit(":", 1)[1] + with httpx2.Client(transport=_sync_http.Transport()) as client: response = client.get(f"http://service.proofline.invalid:{port}/finding") assert response.json()["id"] == str(FINDING) - assert server.requests[0].headers["Host"] == f"service.proofline.invalid:{port}" + assert server.requests[0].headers["Host"] == (f"service.proofline.invalid:{port}") assert ("service.proofline.invalid", "proofline-dns") in lookups + response = client.get(f"http://scoped.proofline.invalid:{port}/finding") assert response.json()["id"] == str(FINDING) - assert server.requests[1].headers["Host"] == f"scoped.proofline.invalid:{port}" + assert server.requests[1].headers["Host"] == (f"scoped.proofline.invalid:{port}") assert ("scoped.proofline.invalid", "proofline-dns") in lookups assert scoped_connections == ["fe80::1%41", "fe80::1%42"] + with pytest.raises(httpx2.TransportError) as raised: client.get(f"http://missing.proofline.invalid:{port}/finding") assert not isinstance(raised.value, httpx2.TimeoutException) + with pytest.raises(httpx2.TransportError): client.get(f"http://127.0.0.1:{closed_port}/finding") + assert len(server.requests) == 2 +@pytest.mark.parametrize( + ("caller_offset", "internal_offset", "expected_bounded"), + [ + (1.0, 2.0, True), + (2.0, 1.0, False), + ], +) + +def test_io_budget_expired_timeout_preserves_deadline_provenance( + monkeypatch: pytest.MonkeyPatch, + caller_offset: float, + internal_offset: float, + expected_bounded: bool, +) -> None: + clock = Clock(monkeypatch) + + caller_token = _transport.DEADLINE.set(clock.now + caller_offset) + try: + # Move past both deadlines before calculating the I/O budget. + clock.now += 3 + + with pytest.raises(httpx2.ReadTimeout) as raised: + _transport.io_budget(clock.now - 3 + internal_offset) + finally: + _transport.DEADLINE.reset(caller_token) + + assert getattr(raised.value, "_deadline_bounded", None) is expected_bounded + +def test_sync_transport_stops_address_retries_when_deadline_expires( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + attempted_addresses: list[str] = [] + requested_addresses: list[str] = [] + observed_timeouts: list[float | None] = [] + + def resolve( + host: str, + port: int, + timeout: float | None, + ) -> Iterator[str]: + for address in ("192.0.2.1", "192.0.2.2", "192.0.2.3"): + requested_addresses.append(address) + yield address + + monkeypatch.setattr(_sync_http, "resolve", resolve) + + def connect_tcp( + backend: Any, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: Any = None, + ) -> Any: + attempted_addresses.append(host) + observed_timeouts.append(timeout) + + # Simulate the first connection attempt consuming the deadline. + clock.now += 2 + raise httpcore2.ConnectError("Connection failed.") + + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + + token = _sync_http.IO_DEADLINE.set(clock.now + 1) + try: + with pytest.raises(httpcore2.ConnectTimeout): + _sync_http.NetworkBackend().connect_tcp( + "service.proofline.invalid", + 443, + timeout=10, + ) + finally: + _sync_http.IO_DEADLINE.reset(token) + + # The second address is retrieved, but the expired deadline + # prevents a second connection attempt. + assert requested_addresses == ["192.0.2.1", "192.0.2.2"] + assert attempted_addresses == ["192.0.2.1"] + assert observed_timeouts == [pytest.approx(1.0)] + + +def test_sync_transport_preserves_final_connection_failure_after_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + attempted_addresses: list[str] = [] + requested_addresses: list[str] = [] + + def resolve( + host: str, + port: int, + timeout: float | None, + ) -> Iterator[str]: + requested_addresses.append("192.0.2.1") + yield "192.0.2.1" + + monkeypatch.setattr(_sync_http, "resolve", resolve) + + def connect_tcp( + backend: Any, + host: str, + port: int, + timeout: float | None = None, + local_address: str | None = None, + socket_options: Any = None, + ) -> Any: + attempted_addresses.append(host) + + # The final connection attempt fails after the deadline expires. + clock.now += 2 + raise httpcore2.ConnectError("Connection failed.") + + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + + token = _sync_http.IO_DEADLINE.set(clock.now + 1) + try: + with pytest.raises( + httpcore2.ConnectError, + match="Connection failed.", + ): + _sync_http.NetworkBackend().connect_tcp( + "service.proofline.invalid", + 443, + timeout=10, + ) + finally: + _sync_http.IO_DEADLINE.reset(token) + + assert requested_addresses == ["192.0.2.1"] + assert attempted_addresses == ["192.0.2.1"] + + +@pytest.mark.parametrize( + ("caller_offset", "internal_offset", "expected"), + [ + (1, 10, True), # Caller deadline expires first. + (10, 1, False), # Internal deadline expires first. + ], +) +def test_sync_body_read_preserves_deadline_provenance( + caller_offset: float, + internal_offset: float, + expected: bool, + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + observed_timeouts: list[float | None] = [] + class FailingSocket: + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + observed_timeouts.append(timeout) + raise httpcore2.ReadTimeout("Simulated socket read timeout.") + class FailingBody(httpx2.SyncByteStream): + def __iter__(self) -> Any: + with _sync_http.mapped_errors(): + _sync_http.NetworkStream(FailingSocket()).read( + 1024, + timeout=10, + ) + yield b"" + + def close(self) -> None: + pass + + caller_deadline = clock.now + caller_offset + internal_deadline = clock.now + internal_offset + + token = _transport.DEADLINE.set(caller_deadline) + + try: + stream = _transport.DeadlineStream( + inner=FailingBody(), + status=200, + deadline=internal_deadline, + read_bounded=False, + ) + + with pytest.raises(ProoflineError) as raised: + list(stream) + + assert _transport.is_deadline_timeout(raised.value) is expected + assert observed_timeouts == [pytest.approx(1.0)] + + finally: + _transport.DEADLINE.reset(token) + + +def test_unannotated_pool_timeout_preserves_phase_fallback() -> None: + original_error = httpcore2.PoolTimeout("Pool wait timed out.") + + with pytest.raises(httpx2.PoolTimeout) as raised: + with _sync_http.mapped_errors(): + raise original_error + + assert not hasattr(raised.value, "_deadline_bounded") + + error = _transport.network_error( + raised.value, + bounded_phases=frozenset({"pool"}), + ) + + assert _transport.is_deadline_timeout(error) + +def test_deadline_stream_restores_context_between_chunks() -> None: + now = _transport.monotonic() + + caller_deadline = now + 30 + internal_deadline = now + 60 + previous_io_deadline = now + 90 + previous_caller_deadline = now + 120 + + io_token = _transport.IO_DEADLINE.set(previous_io_deadline) + caller_token = _transport.CALLER_DEADLINE.set(previous_caller_deadline) + deadline_token = _transport.DEADLINE.set(caller_deadline) + + try: + + def body() -> Iterator[bytes]: + # Deadline context must be active while fetching each chunk. + assert _transport.IO_DEADLINE.get() == caller_deadline + assert _transport.CALLER_DEADLINE.get() == caller_deadline + + yield b"first" + + # The context must be set again for the next read. + assert _transport.IO_DEADLINE.get() == caller_deadline + assert _transport.CALLER_DEADLINE.get() == caller_deadline + + yield b"second" + + stream = _transport.DeadlineStream( + inner=body(), + status=200, + deadline=internal_deadline, + ) + + received = [] + + for chunk in stream: + received.append(chunk) + + # Once a chunk reaches the caller, both previous + # ContextVar values must already have been restored. + assert _transport.IO_DEADLINE.get() == previous_io_deadline + assert _transport.CALLER_DEADLINE.get() == previous_caller_deadline + + assert received == [b"first", b"second"] + + finally: + _transport.DEADLINE.reset(deadline_token) + _transport.CALLER_DEADLINE.reset(caller_token) + _transport.IO_DEADLINE.reset(io_token) + +def test_deadline_stream_installs_context_during_iterator_creation() -> None: + now = _transport.monotonic() + + caller_deadline = now + 30 + internal_deadline = now + 60 + previous_io_deadline = now + 90 + previous_caller_deadline = now + 120 + + io_token = _transport.IO_DEADLINE.set(previous_io_deadline) + caller_token = _transport.CALLER_DEADLINE.set(previous_caller_deadline) + deadline_token = _transport.DEADLINE.set(caller_deadline) + + class InitializationCheckingBody: + def __iter__(self) -> Iterator[bytes]: + # Iterator creation itself must receive the deadline context. + assert _transport.IO_DEADLINE.get() == caller_deadline + assert _transport.CALLER_DEADLINE.get() == caller_deadline + + return iter([b"chunk"]) + + try: + stream = _transport.DeadlineStream( + inner=InitializationCheckingBody(), + status=200, + deadline=internal_deadline, + ) + + assert list(stream) == [b"chunk"] + + # Previous context must be restored after iterator creation and reading. + assert _transport.IO_DEADLINE.get() == previous_io_deadline + assert _transport.CALLER_DEADLINE.get() == previous_caller_deadline + + finally: + _transport.DEADLINE.reset(deadline_token) + _transport.CALLER_DEADLINE.reset(caller_token) + _transport.IO_DEADLINE.reset(io_token) @MODES async def test_cursor_pagination_preserves_filters_and_refuses_cycles_or_bounds(mode: str) -> None: @@ -2586,3 +2967,180 @@ def respond(request: Request, index: int) -> Reply: assert len(exported.rows) == 1 assert exported.rows[0]["claim"] == row["claim"] assert exported.next_cursor == "next-page" + + +@MODES +@pytest.mark.parametrize("status", [200, 403]) +async def test_body_timeout_early_preserves_caller_and_authority_semantics( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + observed_sync_timeouts: list[float | None] = [] + observed_async_budgets: list[float] = [] + + class FailingSocket: + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + observed_sync_timeouts.append(timeout) + raise httpcore2.ReadTimeout("Simulated socket read timeout.") + + class FailingSyncBody(httpx2.SyncByteStream): + def __iter__(self) -> Iterator[bytes]: + with _sync_http.mapped_errors(): + _sync_http.NetworkStream(FailingSocket()).read( + 1024, + timeout=10, + ) + yield b"" + + class FailingAsyncBody(httpx2.AsyncByteStream): + async def __aiter__(self) -> Any: + # Measure the remaining time in the actual AnyIO scope. + effective_deadline = anyio.current_effective_deadline() + assert math.isfinite(effective_deadline) + remaining = effective_deadline - anyio.current_time() + observed_async_budgets.append(remaining) + # Actually suspend so the AnyIO deadline can cancel this read. + await anyio.sleep(remaining + 1) + yield b"" + + # Replace only the underlying response body streams. + # The real DeadlineStream and AsyncDeadlineStream remain in use. + original_sync_handle = _transport.SyncHTTPTransport.handle_request + + def handle_sync_request( + self: _transport.SyncHTTPTransport, + request: Request, + ) -> httpx2.Response: + response = original_sync_handle(self, request) + response.stream.close() + response.stream = FailingSyncBody() + return response + + original_async_handle = httpx2.AsyncHTTPTransport.handle_async_request + + async def handle_async_request( + self: httpx2.AsyncHTTPTransport, + request: Request, + ) -> httpx2.Response: + response = await original_async_handle(self, request) + await response.stream.aclose() + response.stream = FailingAsyncBody() + return response + + monkeypatch.setattr( + _transport.SyncHTTPTransport, + "handle_request", + handle_sync_request, + ) + monkeypatch.setattr( + httpx2.AsyncHTTPTransport, + "handle_async_request", + handle_async_request, + ) + + body = review() if status == 200 else {"detail": PRIVATE} + + with Server(lambda request, index: Reply(status, body)) as server: + async with session(mode, server.url) as client: + if status == 200: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=0.3, + ) + assert result.status == "TIMED_OUT" + else: + with pytest.raises(ProoflineError) as raised: + await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=0.3, + ) + assert raised.value.status == 403 + + # Verify that the actual lower-level read received the caller's + # approximately 0.3-second budget. + if mode == "sync": + assert observed_sync_timeouts == [pytest.approx(0.3)] + assert observed_async_budgets == [] + else: + assert len(observed_async_budgets) == 1 + assert observed_async_budgets[0] == pytest.approx(0.3, abs=0.05) + assert observed_sync_timeouts == [] + + # Independent regression scenario: + # The caller's deadline expires BEFORE AsyncDeadlineStream starts reading. + class EmptyStream(httpx2.AsyncByteStream): + async def __aiter__(self) -> Any: + if False: + yield b"" + + caller_deadline = clock.now + 1 + internal_deadline = clock.now + 10 + + token = _transport.DEADLINE.set(caller_deadline) + try: + stream = _transport.AsyncDeadlineStream( + inner=EmptyStream(), + status=200, + deadline=internal_deadline, + read_bounded=False, + ) + + # Expire the caller's deadline before iteration starts. + clock.now = caller_deadline + 1 + + with pytest.raises(ProoflineError) as raised: + async for _ in stream: + pass + + assert _transport.is_deadline_timeout(raised.value) + finally: + _transport.DEADLINE.reset(token) + + +def test_sync_body_read_timeout_before_caller_deadline_is_sdk_timeout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + observed_timeouts: list[float | None] = [] + + class FailingSocket: + def read(self, max_bytes: int, timeout: float | None = None) -> bytes: + observed_timeouts.append(timeout) + raise httpcore2.ReadTimeout("Simulated internal read timeout.") + + class FailingBody(httpx2.SyncByteStream): + def __iter__(self) -> Iterator[bytes]: + with _sync_http.mapped_errors(): + _sync_http.NetworkStream(FailingSocket()).read( + 1024, + timeout=10, + ) + yield b"" + + # The caller has 10 seconds, but the internal read deadline is 1 second. + caller_deadline = clock.now + 10 + internal_deadline = clock.now + 1 + + token = _transport.DEADLINE.set(caller_deadline) + try: + stream = _transport.DeadlineStream( + inner=FailingBody(), + status=200, + deadline=internal_deadline, + read_bounded=False, + ) + + with pytest.raises(ProoflineError) as raised: + list(stream) + + assert raised.value.type == "urn:proofline:sdk:timeout" + assert not _transport.is_deadline_timeout(raised.value) + assert observed_timeouts == [pytest.approx(1.0)] + finally: + _transport.DEADLINE.reset(token) \ No newline at end of file