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
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.

```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
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

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)
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:
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)
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.
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())

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