Skip to content
Open
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
21 changes: 18 additions & 3 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

VERSION = "9.0.0"
MAX_RESPONSE_BYTES = 8 * 1024 * 1024
TIMEOUT_TYPE = "urn:proofline:sdk:timeout"
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 All @@ -65,6 +66,10 @@
| RunNowRefusalViewType9
)
DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None)
# Whether DEADLINE, not the attempt's own timeout, bounds the latest attempt. A wait
# reads it to learn which deadline ended a request: its clock can trail the clock the
# request stopped on, by up to 15.6 ms on Windows before Python 3.13.
DEADLINE_BOUND: ContextVar[bool] = ContextVar("proofline_deadline_bound", default=False)


class BearerAuth(httpx2.Auth):
Expand Down Expand Up @@ -174,7 +179,7 @@ def operation_errors() -> Iterator[None]:


def timeout_error() -> ProoflineError:
return ProoflineError(0, "urn:proofline:sdk:timeout", "The request deadline expired.")
return ProoflineError(0, TIMEOUT_TYPE, "The request deadline expired.")


def remaining() -> float | None:
Expand All @@ -187,6 +192,8 @@ def limit_timeout(request: httpx2.Request) -> None:
if budget is None:
return
if budget <= 0:
# Only the caller's budget is spent here, so DEADLINE ends this attempt.
DEADLINE_BOUND.set(True)
raise timeout_error()
configured = request.extensions.get("timeout", {})
request.extensions["timeout"] = {
Expand Down Expand Up @@ -377,6 +384,14 @@ def io_deadline(deadline: float) -> float:
return deadline if caller is None else min(deadline, caller)


def attempt_deadline(timeout: float) -> float:
"""Return an attempt's own deadline and record whether DEADLINE comes first."""
deadline = monotonic() + timeout
caller = DEADLINE.get()
DEADLINE_BOUND.set(caller is not None and caller <= deadline)
return deadline


def io_budget(deadline: float) -> float:
budget = io_deadline(deadline) - monotonic()
if budget <= 0:
Expand Down Expand Up @@ -441,7 +456,7 @@ def __init__(self, token: SecretStr, timeout: float) -> None:
def handle_request(self, request: httpx2.Request) -> httpx2.Response:
for attempt in range(4):
limit_timeout(request)
deadline = monotonic() + self._timeout
deadline = attempt_deadline(self._timeout)
marker = IO_DEADLINE.set(io_deadline(deadline))
try:
response = self._inner.handle_request(request)
Expand Down Expand Up @@ -492,7 +507,7 @@ def __init__(self, token: SecretStr, timeout: float) -> None:
async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response:
for attempt in range(4):
limit_timeout(request)
deadline = monotonic() + self._timeout
deadline = attempt_deadline(self._timeout)
try:
with anyio.fail_after(io_budget(deadline)):
response = await self._inner.handle_async_request(request)
Expand Down
24 changes: 22 additions & 2 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,13 +562,22 @@ def wait_for_review(
url = _review_url(self._base_url, organization_id, review_id)
last: CustomerReviewDetail | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
bound = _transport.DEADLINE_BOUND.set(False)
interval = 5.0
try:
while (_transport.remaining() or 0) > 0:
# Only this poll's own attempts can show that the wait deadline ended it.
_transport.DEADLINE_BOUND.set(False)
try:
last = self.get_review(organization_id, review_id)
except ProoflineError as error:
if error.status == 0 and (_transport.remaining() or 0) <= 0:
# TIMED_OUT only when the wait deadline, not the request's timeout, ended
# it. An HTTP problem can carry any type, so the SDK's timeout has status 0.
if (
error.status == 0
and error.type == _transport.TIMEOUT_TYPE
and _transport.DEADLINE_BOUND.get()
):
break
raise
if (_transport.remaining() or 0) <= 0:
Expand All @@ -581,6 +590,7 @@ def wait_for_review(
timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha)
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
_transport.DEADLINE_BOUND.reset(bound)
_transport.DEADLINE.reset(deadline)


Expand Down Expand Up @@ -948,13 +958,22 @@ async def wait_for_review(
url = _review_url(self._base_url, organization_id, review_id)
last: CustomerReviewDetail | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
bound = _transport.DEADLINE_BOUND.set(False)
interval = 5.0
try:
while (_transport.remaining() or 0) > 0:
# Only this poll's own attempts can show that the wait deadline ended it.
_transport.DEADLINE_BOUND.set(False)
try:
last = await self.get_review(organization_id, review_id)
except ProoflineError as error:
if error.status == 0 and (_transport.remaining() or 0) <= 0:
# TIMED_OUT only when the wait deadline, not the request's timeout, ended
# it. An HTTP problem can carry any type, so the SDK's timeout has status 0.
if (
error.status == 0
and error.type == _transport.TIMEOUT_TYPE
and _transport.DEADLINE_BOUND.get()
):
break
raise
if (_transport.remaining() or 0) <= 0:
Expand All @@ -967,4 +986,5 @@ async def wait_for_review(
timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha)
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
_transport.DEADLINE_BOUND.reset(bound)
_transport.DEADLINE.reset(deadline)
193 changes: 193 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -1430,6 +1430,199 @@ async def test_retry_after_is_bounded_by_wait_deadline(
assert clock.delays == [10]


@MODES
@pytest.mark.parametrize(
("wait", "retry", "timed_out"),
[
(10, False, True), # The wait deadline ends the only attempt.
(40, True, True), # It ends the retry of a 503, not the first attempt.
(300, False, False), # The request's own 30 s timeout ends it mid-wait.
],
)
async def test_a_request_the_wait_deadline_ends_is_timed_out_while_the_clock_lags(
mode: str, wait: float, retry: bool, timed_out: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
# A request stops on its own clock. The wait's clock can trail it by a few
# milliseconds, as Windows' 15.6 ms monotonic ticks do before Python 3.13, so
# the wait cannot read its clock to learn which deadline ended the request.
clock = Clock(monkeypatch)
lag = 0.004
attempts = 0
bounds: list[bool] = []
sync_request = _sync_http.Transport.handle_request
async_request = httpx2.AsyncHTTPTransport.handle_async_request

def expired() -> httpx2.ReadTimeout:
caller = _transport.DEADLINE.get()
assert caller is not None
# The attempt runs until its I/O deadline, the wait's or its own, by a
# request clock that is lag ahead of the clock the wait reads.
clock.now = min(caller, clock.now + 30) - lag
return httpx2.ReadTimeout("The request deadline expired.")

def reaches_server() -> bool:
nonlocal attempts
attempts += 1
bounds.append(_transport.DEADLINE_BOUND.get())
return retry and attempts == 1

def stop_sync(transport: _sync_http.Transport, request: httpx2.Request) -> httpx2.Response:
if reaches_server():
return sync_request(transport, request)
raise expired()

async def stop_async(
transport: httpx2.AsyncHTTPTransport, request: httpx2.Request
) -> httpx2.Response:
if reaches_server():
return await async_request(transport, request)
raise expired()

monkeypatch.setattr(_sync_http.Transport, "handle_request", stop_sync)
monkeypatch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", stop_async)
with Server(
lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": "20"})
) as server:
async with session(mode, server.url) as client:
if timed_out:
result = await call(client, "wait_for_review", ORG, REVIEW, timeout=wait)
assert result.status == "TIMED_OUT"
assert result.review is None
assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}"
else:
with pytest.raises(ProoflineError) as raised:
await call(client, "wait_for_review", ORG, REVIEW, timeout=wait)
assert raised.value.type == "urn:proofline:sdk:timeout"
# The wait leaves no deadline state behind for the caller's next request.
assert _transport.DEADLINE.get() is None
assert _transport.DEADLINE_BOUND.get() is False
assert attempts == (2 if retry else 1)
# The first attempt of the retry case ends at its own deadline; only the retry
# starts within 30 s of the wait deadline.
assert bounds == ([False, True] if retry else [timed_out])
assert len(server.requests) == (1 if retry else 0)
assert clock.delays == ([20] if retry else [])


@MODES
async def test_a_wait_budget_spent_before_the_attempt_starts_is_timed_out(
mode: str, monkeypatch: pytest.MonkeyPatch
) -> None:
# The wait's 40 s deadline is later than an attempt's own 30 s one, but the wait
# budget runs out before limit_timeout() lets the attempt start.
clock = Clock(monkeypatch)
limit_timeout = _transport.limit_timeout

def expire_then_clamp(request: httpx2.Request) -> None:
assert not _transport.DEADLINE_BOUND.get()
caller = _transport.DEADLINE.get()
assert caller is not None
clock.now = caller + 1
limit_timeout(request)

monkeypatch.setattr(_transport, "limit_timeout", expire_then_clamp)
with Server(lambda request, index: Reply(body=review("RUNNING"))) as server:
async with session(mode, server.url) as client:
result = await call(client, "wait_for_review", ORG, REVIEW, timeout=40)
assert result.status == "TIMED_OUT"
assert result.review is None
assert server.requests == []


@MODES
async def test_an_attempt_deadline_starts_after_its_clamp(
mode: str, monkeypatch: pytest.MonkeyPatch
) -> None:
# Time spent in limit_timeout() is not charged to the attempt: its own 30 s
# deadline starts after the clamp, so the wait's 33 s deadline bounds it.
clock = Clock(monkeypatch)
limit_timeout = _transport.limit_timeout
bounds: list[bool] = []

def slow_clamp(request: httpx2.Request) -> None:
clock.now += 5
limit_timeout(request)

def expired() -> httpx2.ReadTimeout:
bounds.append(_transport.DEADLINE_BOUND.get())
caller = _transport.DEADLINE.get()
assert caller is not None
clock.now = caller
return httpx2.ReadTimeout("The request deadline expired.")

def stop_sync(transport: _sync_http.Transport, request: httpx2.Request) -> httpx2.Response:
raise expired()

async def stop_async(
transport: httpx2.AsyncHTTPTransport, request: httpx2.Request
) -> httpx2.Response:
raise expired()

monkeypatch.setattr(_transport, "limit_timeout", slow_clamp)
monkeypatch.setattr(_sync_http.Transport, "handle_request", stop_sync)
monkeypatch.setattr(httpx2.AsyncHTTPTransport, "handle_async_request", stop_async)
with Server(lambda request, index: Reply(body=review("RUNNING"))) as server:
async with session(mode, server.url) as client:
result = await call(client, "wait_for_review", ORG, REVIEW, timeout=33)
assert result.status == "TIMED_OUT"
assert bounds == [True]
assert server.requests == []


@MODES
async def test_a_poll_that_never_reaches_the_transport_is_not_bound_by_the_wait(
mode: str, monkeypatch: pytest.MonkeyPatch
) -> None:
# The first poll's attempt is bounded by the wait deadline. A second poll that
# raises the SDK timeout before any attempt must not inherit that flag.
clock = Clock(monkeypatch)
polls = 0
with Server(lambda request, index: Reply(body=review("RUNNING"))) as server:
async with session(mode, server.url) as client:
if isinstance(client, ProoflineClient):
read = client.get_review

def local_timeout(organization_id: UUID, review_id: UUID) -> Any:
nonlocal polls
polls += 1
if polls == 1:
return read(organization_id, review_id)
raise _transport.timeout_error()

monkeypatch.setattr(client, "get_review", local_timeout)
else:
async_read = client.get_review

async def async_local_timeout(organization_id: UUID, review_id: UUID) -> Any:
nonlocal polls
polls += 1
if polls == 1:
return await async_read(organization_id, review_id)
raise _transport.timeout_error()

monkeypatch.setattr(client, "get_review", async_local_timeout)
with pytest.raises(ProoflineError) as raised:
await call(client, "wait_for_review", ORG, REVIEW, timeout=20)
assert raised.value.type == "urn:proofline:sdk:timeout"
assert polls == 2
assert len(server.requests) == 1
assert clock.delays == [5]


@MODES
async def test_an_http_problem_named_like_the_sdk_timeout_is_not_timed_out(mode: str) -> None:
# The problem type comes from the server's document, so only a status-0 error is
# the SDK's own timeout, even while the wait deadline bounds the attempt.
problem = {"type": "urn:proofline:sdk:timeout", "title": "forbidden", "detail": PRIVATE}
with Server(lambda request, index: Reply(403, problem)) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await call(client, "wait_for_review", ORG, REVIEW, timeout=10)
assert raised.value.status == 403
assert raised.value.type == "urn:proofline:sdk:timeout"
assert len(server.requests) == 1


@MODES
@pytest.mark.parametrize("status", [429, 503, 403])
async def test_deadline_expiring_with_a_received_problem_chunk_keeps_retry_policy(
Expand Down