Skip to content
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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.
Comment on lines 44 to +46

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · MCP body-read deadlines surface as generic transport errors

The new README promises a timeout when a 429 or 503 body read misses its deadline, but MCP helpers wrap that read timeout as a generic transport error.

MCP callers receive urn:proofline:sdk:transport and cannot distinguish the deadline from other transport failures.

Map MCP timeouts separately or explicitly limit the README guarantee to REST calls.

View finding in Proofline

Also at:


```python
from proofline import ProoflineError
Expand Down
34 changes: 28 additions & 6 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,17 @@ 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 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
Comment on lines +87 to +90

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Fully read 429 and 503 responses can lack retry metadata

The docstring promises retryability after a full read within the deadline, but deeply nested problem bodies can raise RecursionError before either transport attaches metadata.

Callers receive a generic invalid-response error without retry metadata.

Limit the documented guarantee to errors that reach the retry policy after problem parsing.

View finding in Proofline

Comment on lines +87 to +90

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Deeply nested error bodies suppress retry metadata

After reading a 429 or 503 within the deadline, both transports parse and redact the body before setting retry metadata, so RecursionError skips the new assignments.

Callers receive an invalid-response error instead of the HTTP status and retry metadata.

Catch RecursionError during decoding and redaction and use the status-preserving about:blank fallback.

Details

The parser could already raise before this change, but the base did not promise or expose retry metadata.

View finding in Proofline

read, such as an encoded one, is not retryable, and a deadline that
passes first raises the timeout instead.
"""

retryable: bool = False
retry_after: float | None = None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Review waits poll before Retry-After on encoded responses

Both transports reject encoded 429 and 503 responses before attaching Retry-After, but this change makes both waits retry those errors by status alone.

With enough time remaining, a first encoded response asking for 90 seconds can trigger another poll after five seconds.

Preserve Retry-After on encoding errors without reading the rejected body.

View finding in Proofline

Also at:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still present in this version: Proofline found the issue again. Proofline's finding in this version: Retry documentation leaves malformed 429 and 503 bodies ambiguous. View review


def __init__(
self,
status: int,
Expand Down Expand Up @@ -199,12 +207,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)
Comment on lines 207 to +210

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Review waits poll early when a valid Retry-After overflows

A valid decimal Retry-After that overflows float becomes None, so both waits fall back to their normal polling interval.

After a readable 429 or 503, either wait can poll again after five seconds instead of returning TIMED_OUT without another request.

Distinguish overflowing delays from missing or invalid headers and suppress polling until the wait deadline for overflowing delays.

View finding in Proofline

Also at:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still present in this version: Proofline found the issue again. Proofline's finding in this version: Oversized Retry-After values expose undocumented infinity. View review

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still present in this version: Proofline found the issue again. Proofline's finding in this version: A 429 or 503 can time out after its last chunk without retry metadata. View review

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
Expand All @@ -229,7 +243,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:
Expand Down Expand Up @@ -475,6 +489,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()
Expand Down Expand Up @@ -526,6 +544,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()
Expand Down
31 changes: 29 additions & 2 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Comment thread
prooflinedev[bot] marked this conversation as resolved.
Resolved
Expand All @@ -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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · An expiring retry hold can start a review read after the deadline

Both wait loops check the deadline before sampling the clock for the retry hold. If that sample is past both cutoffs, they call get_review with no time left.

The wait enters the review-read path instead of exiting immediately.

Use the same monotonic timestamp to check the deadline and the retry hold before polling.

Details

The built-in transports reject the expired read before network I/O. The specific retry-hold trigger was absent before this change because service errors ended the wait rather than setting a hold.

View finding in Proofline

Also at:

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)
Expand Down Expand Up @@ -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.
Comment on lines 969 to +972

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Long Retry-After crashes review polling under Trio

The new retry hold calls asyncio.sleep after a fully read 429 or 503 with a Retry-After above 60 seconds. Trio has no running asyncio loop for that sleep.

The wait raises RuntimeError instead of polling again or returning TIMED_OUT.

Use anyio.sleep for the async retry hold.

Details

Before this change, the wait re-raised the HTTP error before reaching its asyncio-only polling sleep. This change reaches that sleeper even when the first read fails, provided time remains in the wait budget.

View finding in Proofline

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)
Expand Down
203 changes: 203 additions & 0 deletions tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Comment thread
prooflinedev[bot] marked this conversation as resolved.
Resolved

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"<html>Service Unavailable</html>", {"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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Metadata test misses Retry-After loss after GET retries

The metadata test uses Retry-After: 75, above the 60-second cap, so the GET raises before exhausting its retries.

Dropping retry_after only on the final GET attempt leaves the metadata test green.

Use Retry-After: 0 in the retry-count test and assert retry_after == 0 on the error after four attempts.

Details

The existing retry-count test already catches an incorrectly retried POST with an in-cap header. Its GET case checks the status and attempt count, but not the retry metadata.

View finding in Proofline

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"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning · Last-review test passes even if a 503 ends the wait early

The test checks only TIMED_OUT and the retained RUNNING review, both returned if the retryable 503 branch exits immediately after a successful poll.

A regression that skips the retry hold would pass in both client modes.

Assert that the fake clock reaches the deadline and verify the expected requests and sleep intervals.

View finding in Proofline

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(
Expand Down