From 18028babcbfc882c25d41de975a8e73ca683c0c0 Mon Sep 17 00:00:00 2001 From: Apoorva Rohilla <61989678+apoorvarohilla@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:51:56 +0530 Subject: [PATCH 1/2] Keep waiting for a review through rate limits and unavailability wait_for_review raised the 429 or 503 that ended one read's retries, even with most of its timeout left, so a CI wait failed on a brief rate limit or restart. A Retry-After over 60 seconds raised at once, while a shorter one that outlasted the deadline returned TIMED_OUT. The transport marks a 429 or 503 whose body it read as retryable and records its Retry-After. wait_for_review treats a retryable problem like an unfinished review: it holds the next read until the larger of its poll interval and the Retry-After has passed, sleeping toward it in steps of at most a minute within the deadline, then returns TIMED_OUT with the last review it read. Every other problem, and a 429 or 503 refused before its body is read, still raises. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- proofline/_transport.py | 33 +++++-- proofline/client.py | 31 +++++- tests/test_http.py | 203 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 260 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 721949da..47857fef 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The [SDK guide](https://proofline.sh/docs/sdks/) and [API reference](https://pro ## Errors and refusals -A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. The token is redacted from every text field, and `repr` and `str` show only the status. +A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. A 429 or 503 whose body the client received in full is `retryable`, even without a problem document, and its `retry_after` holds the seconds its valid `Retry-After` asked for (`inf` for more seconds than a float holds), or `None`. A 429 or 503 the client refuses before reading its body, such as an encoded one, is not retryable. `wait_for_review` does not end on a retryable problem: it polls again no sooner than that `Retry-After` and returns `TIMED_OUT` if its timeout passes first. The token is redacted from every text field, and `repr` and `str` show only the status. ```python from proofline import ProoflineError diff --git a/proofline/_transport.py b/proofline/_transport.py index 63d9dab5..2a4a4a5e 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -84,9 +84,16 @@ class ProoflineError(Exception): title names the server's problem class. A refused review request also carries the typed refusal, whose reason names the setting to change, and - the repository_name it refers to. + the repository_name it refers to. A 429 or 503 whose body was received in + full is retryable, even without a problem document, and retry_after holds + the seconds its valid Retry-After asked for (inf for more seconds than a + float holds), or None. A 429 or 503 refused before its body is read, such + as an encoded one, is not retryable. """ + retryable: bool = False + retry_after: float | None = None + def __init__( self, status: int, @@ -199,12 +206,18 @@ def retry_delay(value: str | None, attempt: int) -> float | None: """An invalid or longer Retry-After returns the problem without an early retry.""" if value is None: return float(2**attempt) + delay = retry_after(value) + return delay if delay is not None and delay <= 60 else None + + +def retry_after(value: str | None) -> float | None: + """The seconds a valid Retry-After asks the client to wait, or None.""" + if value is None: + return None value = value.strip() if value.isascii() and value.isdigit(): - try: - delay = float(value) - except (ValueError, OverflowError): - return None + # More digits than a float holds still ask for a delay: float() gives inf. + return float(value) else: if not any(pattern.fullmatch(value) for pattern in HTTP_DATES): return None @@ -229,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) else None def redacted(value: object, raw: str) -> object: @@ -475,6 +488,10 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: or attempt == 3 or delay is None ): + if response.status_code in (429, 503): + # Only a problem read through this retry policy may be retried later. + error.retryable = True + error.retry_after = retry_after(response.headers.get("Retry-After")) raise error from None sleep(delay_within_deadline(delay)) raise timeout_error() @@ -526,6 +543,10 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response or attempt == 3 or delay is None ): + if response.status_code in (429, 503): + # Only a problem read through this retry policy may be retried later. + error.retryable = True + error.retry_after = retry_after(response.headers.get("Retry-After")) raise error from None await async_sleep(delay_within_deadline(delay)) raise timeout_error() diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..0864411e 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -554,6 +554,9 @@ def wait_for_review( head_commit_sha holds the outcome to that commit. A review pinned to another head ends the wait on that read and is never COMPLETED. + + A retryable rate limit or unavailable service (429 or 503) does not end + the wait: it polls again no sooner than the Retry-After, until the deadline. """ if not math.isfinite(timeout) or timeout < 0: @@ -563,14 +566,26 @@ def wait_for_review( last: CustomerReviewDetail | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) interval = 5.0 + not_before = 0.0 try: while (_transport.remaining() or 0) > 0: + held = not_before - monotonic() + if held > 0: + # Sleep in bounded steps until the service's Retry-After passes. + sleep(min(held, 60, _transport.remaining() or 0)) + continue try: last = self.get_review(organization_id, review_id) except ProoflineError as error: if error.status == 0 and (_transport.remaining() or 0) <= 0: break - raise + if not error.retryable: + raise + # The read exhausted its own retries. The service asked to be + # polled later, so wait for that within this deadline. + not_before = monotonic() + max(interval, error.retry_after or 0) + interval = min(60, interval * 2) + continue if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) @@ -949,14 +964,26 @@ async def wait_for_review( last: CustomerReviewDetail | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) interval = 5.0 + not_before = 0.0 try: while (_transport.remaining() or 0) > 0: + held = not_before - monotonic() + if held > 0: + # Sleep in bounded steps until the service's Retry-After passes. + await async_sleep(min(held, 60, _transport.remaining() or 0)) + continue try: last = await self.get_review(organization_id, review_id) except ProoflineError as error: if error.status == 0 and (_transport.remaining() or 0) <= 0: break - raise + if not error.retryable: + raise + # The read exhausted its own retries. The service asked to be + # polled later, so wait for that within this deadline. + not_before = monotonic() + max(interval, error.retry_after or 0) + interval = min(60, interval * 2) + continue if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..20a5aded 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1430,6 +1430,209 @@ async def test_retry_after_is_bounded_by_wait_deadline( assert clock.delays == [10] +# A wait outlives one request's retry budget: a rate limit or an unavailable +# service is polled again within the wait's deadline, never earlier than the +# service asked, and only the deadline turns it into TIMED_OUT. +@MODES +@pytest.mark.parametrize("status", [429, 503]) +async def test_wait_keeps_polling_after_one_request_exhausts_its_retries( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + + def respond(request: Request, index: int) -> Reply: + if index < 5: + return Reply(status, {"detail": "Unavailable."}, {"Retry-After": "0"}) + return Reply(body=review()) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=300) + assert result.status == "COMPLETED" + # Four attempts in the first read, then the wait's own five-second poll. + assert len(server.requests) == 6 + assert clock.delays == [0, 0, 0, 5, 0] + + +@MODES +@pytest.mark.parametrize("status", [429, 503]) +async def test_wait_honors_a_retry_after_longer_than_one_request_retries( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + seen: list[float] = [] + + def respond(request: Request, index: int) -> Reply: + seen.append(clock.now) + # Completion is only offered once the asked-for 90 seconds have passed. + if clock.now < seen[0] + 90: + return Reply(status, {"detail": "Unavailable."}, {"Retry-After": "90"}) + return Reply(body=review()) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=300) + assert result.status == "COMPLETED" + assert seen == [seen[0], seen[0] + 90] + # Slept in steps of at most a minute. + assert clock.delays == [60, 30] + + +@MODES +async def test_wait_holds_a_retry_after_too_long_for_a_float_until_its_deadline( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": "9" * 400}) + ) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=150) + assert result.status == "TIMED_OUT" + assert len(server.requests) == 1 + assert clock.delays == [60, 60, 30] + + +@MODES +async def test_wait_retries_a_rate_limit_without_a_problem_document( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + + def respond(request: Request, index: int) -> Reply: + if index < 4: + return Reply(503, b"Service Unavailable", {"Content-Type": "text/html"}) + return Reply(body=review()) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=300) + assert result.status == "COMPLETED" + assert len(server.requests) == 5 + # The transport's own backoff (1, 2, 4), then the wait's hold (5) before read five. + assert clock.delays == [1, 2, 4, 5] + + +@MODES +async def test_wait_sleeps_a_very_long_retry_after_in_bounded_steps( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + + def respond(request: Request, index: int) -> Reply: + if index == 0: + return Reply(503, {"detail": "Unavailable."}, {"Retry-After": "100000"}) + return Reply(body=review()) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=1e12) + assert result.status == "COMPLETED" + assert len(server.requests) == 2 + # time.sleep overflows near 1e10 seconds, so no single sleep may grow with the header. + assert max(clock.delays) == 60 + assert sum(clock.delays) == 100000 + + +@MODES +@pytest.mark.parametrize("status", [429, 503]) +async def test_wait_raises_an_encoded_rate_limit_it_cannot_read( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + body = gzip.compress(json.dumps({"detail": "Unavailable."}).encode()) + with Server( + lambda request, index: Reply(status, body, {"Content-Encoding": "gzip", "Retry-After": "0"}) + ) 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=300) + assert raised.value.status == status + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert not raised.value.retryable + assert len(server.requests) == 1 + assert clock.delays == [] + + +@MODES +@pytest.mark.parametrize("status", [429, 503]) +async def test_a_rate_limit_problem_carries_its_retry_after(mode: str, status: int) -> None: + with Server( + lambda request, index: Reply(status, {"detail": "Later."}, {"Retry-After": "75"}) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "rerun_review", ORG, REVIEW) + assert raised.value.retryable + assert raised.value.retry_after == 75 + with pytest.raises(ProoflineError) as raised: + await call(client, "get_finding", ORG, FINDING) + assert raised.value.retryable + assert raised.value.retry_after == 75 + with Server(lambda request, index: Reply(403, {"detail": "No."})) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "get_finding", ORG, FINDING) + assert not raised.value.retryable + assert raised.value.retry_after is None + + +@MODES +@pytest.mark.parametrize("status", [429, 503]) +async def test_wait_times_out_when_retry_after_outlasts_its_deadline( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: Reply(status, {"detail": "Unavailable."}, {"Retry-After": "90"}) + ) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=60) + assert result.status == "TIMED_OUT" + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert len(server.requests) == 1 + assert clock.delays == [60] + + +@MODES +async def test_wait_keeps_the_last_review_read_before_the_service_was_unavailable( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + + def respond(request: Request, index: int) -> Reply: + if index == 0: + return Reply(body=review("RUNNING")) + return Reply(503, {"detail": "Unavailable."}, {"Retry-After": "90"}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=100) + assert result.status == "TIMED_OUT" + assert result.review is not None + assert result.review.status == "RUNNING" + # A poll, a 90-second hold, a second unavailable read, then the deadline. + assert len(server.requests) == 3 + assert clock.delays == [5, 60, 30, 5] + + +@MODES +@pytest.mark.parametrize("status", [400, 401, 403, 404, 500, 502]) +async def test_wait_still_raises_problems_that_are_not_retryable( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: Reply(status, {"detail": "No."}, {"Retry-After": "0"}) + ) 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=300) + assert raised.value.status == status + assert len(server.requests) == 1 + assert clock.delays == [] + + @MODES @pytest.mark.parametrize("status", [429, 503, 403]) async def test_deadline_expiring_with_a_received_problem_chunk_keeps_retry_policy( From 51048342975282f8e0b50e2390e2c3c47ce6a008 Mon Sep 17 00:00:00 2001 From: Apoorva Rohilla <61989678+apoorvarohilla@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:58:10 +0530 Subject: [PATCH 2/2] Say that a retryable problem is one read within the deadline Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- proofline/_transport.py | 11 ++++++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 47857fef..a4722c65 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The [SDK guide](https://proofline.sh/docs/sdks/) and [API reference](https://pro ## Errors and refusals -A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. A 429 or 503 whose body the client received in full is `retryable`, even without a problem document, and its `retry_after` holds the seconds its valid `Retry-After` asked for (`inf` for more seconds than a float holds), or `None`. A 429 or 503 the client refuses before reading its body, such as an encoded one, is not retryable. `wait_for_review` does not end on a retryable problem: it polls again no sooner than that `Retry-After` and returns `TIMED_OUT` if its timeout passes first. The token is redacted from every text field, and `repr` and `str` show only the status. +A refused request raises `ProoflineError` with the server problem's `status`, `type`, `title` and `detail`. When a review request creates nothing, the error also carries `refusal`, whose `reason` names the setting to change, such as `NO_LINKED_ENVIRONMENT` or `ENVIRONMENT_NOT_READY`, and `repository_name`. `RunNowRefusal` names the type of `refusal`. A refusal that does not match the public contract keeps its status, `title` and `detail` with the type `urn:proofline:sdk:invalid-response` and no `refusal`. Any other status, such as the 402 a review request answers when credits cannot pay, is a plain problem with no `refusal`. A 429 or 503 that the client finishes reading within its deadline is `retryable`, even without a problem document, and its `retry_after` holds the seconds its valid `Retry-After` asked for (`inf` for more seconds than a float holds), or `None`. A 429 or 503 the client refuses before reading its body, such as an encoded one, is not retryable, and a deadline that passes first raises the timeout instead. `wait_for_review` does not end on a retryable problem: it polls again no sooner than that `Retry-After` and returns `TIMED_OUT` if its timeout passes first. The token is redacted from every text field, and `repr` and `str` show only the status. ```python from proofline import ProoflineError diff --git a/proofline/_transport.py b/proofline/_transport.py index 2a4a4a5e..bb8bcc3d 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -84,11 +84,12 @@ class ProoflineError(Exception): title names the server's problem class. A refused review request also carries the typed refusal, whose reason names the setting to change, and - the repository_name it refers to. A 429 or 503 whose body was received in - full is retryable, even without a problem document, and retry_after holds - the seconds its valid Retry-After asked for (inf for more seconds than a - float holds), or None. A 429 or 503 refused before its body is read, such - as an encoded one, is not retryable. + the repository_name it refers to. A 429 or 503 read in full within the + deadline is retryable, even without a problem document, and retry_after + holds the seconds its valid Retry-After asked for (inf for more seconds + than a float holds), or None. A 429 or 503 refused before its body is + read, such as an encoded one, is not retryable, and a deadline that + passes first raises the timeout instead. """ retryable: bool = False