From 70ed20e4f0297b3dc19cc7ca63c8fbf95561a264 Mon Sep 17 00:00:00 2001 From: Thirumal Janakiraman Date: Tue, 17 Nov 2026 23:12:44 +0100 Subject: [PATCH 1/2] Add scan_revision to retry scans under one request_id Starts a scan on a ref or exact commit on the sync and async clients, sending the same request_id on every attempt so a retry resolves to the first scan. Retries 429, 502 to 504, timeouts and connection failures, four attempts with jittered backoff. With commit_sha and wait=True the wait is held to that commit, as in wait_for_review. --- README.md | 34 +++++++ proofline/client.py | 96 ++++++++++++++++++++ proofline/scans.py | 51 +++++++++++ tests/test_http.py | 215 ++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 396 insertions(+) create mode 100644 proofline/scans.py diff --git a/README.md b/README.md index 3c7a6ca9..0fe14aca 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,40 @@ if outcome.status != "COMPLETED": `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +## Scanning a revision + +`scan_revision` starts a scan of a ref or an exact commit. Every scan request carries a `request_id`, and the API resolves a repeated `request_id` to its first resolution, so repeating the request cannot scan or spend credits twice. The helper relies on this to retry safely. + +```python +scan = client.scan_revision( + organization_id, + repository_id, + budget_credits=50, + commit_sha=commit_sha, +) +if scan.outcome == "REPOSITORY_UNAVAILABLE": + print("The repository is not available to scan.") +``` + +Name exactly one of `ref` or `commit_sha`; `budget_credits` must be a nonnegative integer. Both are checked before any request, and so is `timeout` when `wait=True`. The helper sends one `request_id` on every attempt and retries HTTP 429, 502, 503 and 504, a request timeout and a connection failure, up to four attempts with exponential backoff and jitter. It does not read `Retry-After`. Other problems are raised at once. Other POST operations still never retry. + +If every attempt fails, the last error is raised with the `request_id` attached as a note. To make a scan safe to resume after a crash or a CI rerun, derive the id from values that do not change and pass it yourself: + +```python +request_id = uuid.uuid5(uuid.NAMESPACE_URL, f"{repository_id}:{commit_sha}:{job_id}") +client.scan_revision( + organization_id, + repository_id, + budget_credits=50, + commit_sha=commit_sha, + request_id=request_id, +) +``` + +A repeated id returns the first resolution (the outcome is `EXISTING`), so include an attempt number in the key if a rerun should scan again. Reusing an id for a different scan request, for example another `budget_credits`, is refused with HTTP 400 and is not retried. + +With `wait=True` the helper then calls `wait_for_review` on the created review, with the same `timeout`, and returns its outcome. `timeout` bounds that wait only, not the retries. When you pass `commit_sha`, the wait is held to that commit as described above, so `commit_sha` must be a full SHA. `REPOSITORY_UNAVAILABLE` returns without waiting. + ## Review exports `export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`. diff --git a/proofline/client.py b/proofline/client.py index dd5106f6..df166bc1 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -67,6 +67,7 @@ from ._generated.models.review_summary import ReviewSummary from ._generated.models.run_now_request import RunNowRequest from ._generated.models.run_now_response import RunNowResponse +from ._generated.models.scan_response import ScanResponse from ._generated.models.start_session import StartSession from ._generated.models.stop_response import StopResponse from ._generated.types import UNSET, Response, Unset @@ -76,6 +77,7 @@ from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome +from .scans import ATTEMPTS, backoff, scan_body, should_retry T = TypeVar("T") AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 @@ -582,6 +584,53 @@ def wait_for_review( finally: _transport.DEADLINE.reset(deadline) + def scan_revision( + self, + organization_id: UUID, + repository_id: UUID, + *, + budget_credits: int, + ref: str | None = None, + commit_sha: str | None = None, + request_id: UUID | None = None, + wait: bool = False, + timeout: float = 300, + ) -> ScanResponse | ReviewOutcome: + """Scan a ref or an exact commit, retrying safely when the API is unavailable. + + One request id is sent on every attempt, and the API resolves a repeated + id to its first result, so a retry never starts a second scan. + Pass your own request_id to resume later. If every attempt fails, the + last problem is raised with the request id attached as a note. A timed + out request is retried too. Retry-After is not honoured: the delay is + 1, 2 then 4 seconds with jitter. + + With commit_sha and wait=True the wait is held to that commit, which + must then be a full SHA. timeout bounds the wait only, not the retries. + + wait=True waits for the created review, as wait_for_review does. + REPOSITORY_UNAVAILABLE returns without waiting. + """ + + body = scan_body(budget_credits, ref, commit_sha, request_id, timeout, wait) + head = (commit_sha or "").strip() or None + if wait: + _head_commit(head) + for attempt in range(ATTEMPTS): + try: + response = self.request_scan(organization_id, repository_id, body=body) + break + except ProoflineError as error: + if attempt == ATTEMPTS - 1 or not should_retry(error): + error.add_note(f"scan request_id: {body.request_id}") + raise + sleep(backoff(attempt)) + if wait and isinstance(response.review_id, UUID): + return self.wait_for_review( + organization_id, response.review_id, timeout=timeout, head_commit_sha=head + ) + return response + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -967,3 +1016,50 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) + + async def scan_revision( + self, + organization_id: UUID, + repository_id: UUID, + *, + budget_credits: int, + ref: str | None = None, + commit_sha: str | None = None, + request_id: UUID | None = None, + wait: bool = False, + timeout: float = 300, + ) -> ScanResponse | ReviewOutcome: + """Scan a ref or an exact commit, retrying safely when the API is unavailable. + + One request id is sent on every attempt, and the API resolves a repeated + id to its first result, so a retry never starts a second scan. + Pass your own request_id to resume later. If every attempt fails, the + last problem is raised with the request id attached as a note. A timed + out request is retried too. Retry-After is not honoured: the delay is + 1, 2 then 4 seconds with jitter. + + With commit_sha and wait=True the wait is held to that commit, which + must then be a full SHA. timeout bounds the wait only, not the retries. + + wait=True waits for the created review, as wait_for_review does. + REPOSITORY_UNAVAILABLE returns without waiting. + """ + + body = scan_body(budget_credits, ref, commit_sha, request_id, timeout, wait) + head = (commit_sha or "").strip() or None + if wait: + _head_commit(head) + for attempt in range(ATTEMPTS): + try: + response = await self.request_scan(organization_id, repository_id, body=body) + break + except ProoflineError as error: + if attempt == ATTEMPTS - 1 or not should_retry(error): + error.add_note(f"scan request_id: {body.request_id}") + raise + await async_sleep(backoff(attempt)) + if wait and isinstance(response.review_id, UUID): + return await self.wait_for_review( + organization_id, response.review_id, timeout=timeout, head_commit_sha=head + ) + return response diff --git a/proofline/scans.py b/proofline/scans.py new file mode 100644 index 00000000..2bd99d80 --- /dev/null +++ b/proofline/scans.py @@ -0,0 +1,51 @@ +"""A scan request names its own resolution, so repeating it cannot scan twice.""" + +from __future__ import annotations + +import math +import random +from uuid import UUID, uuid4 + +from ._generated.models.scan_request_body import ScanRequestBody +from ._transport import ProoflineError + +ATTEMPTS = 4 +RETRYABLE_STATUSES = frozenset((429, 502, 503, 504)) +# A timed out POST may have been accepted; the repeated request_id makes retrying it safe. +RETRYABLE_TYPES = frozenset( + ("urn:proofline:sdk:transport-unavailable", "urn:proofline:sdk:timeout") +) + + +def scan_body( + budget_credits: int, + ref: str | None, + commit_sha: str | None, + request_id: UUID | None, + timeout: float, + wait: bool, +) -> ScanRequestBody: + """Reject a bad call before any request that could spend credits.""" + + ref = ref.strip() if ref else None + commit_sha = commit_sha.strip() if commit_sha else None + if bool(ref) == bool(commit_sha): + raise ValueError("Name exactly one of ref or commit_sha.") + if type(budget_credits) is not int or budget_credits < 0: + raise ValueError("budget_credits must be a nonnegative integer.") + if wait and (not math.isfinite(timeout) or timeout < 0): + raise ValueError("The review timeout must be a finite nonnegative number of seconds.") + return ScanRequestBody( + budget_credits=budget_credits, + request_id=request_id or uuid4(), + ref=ref or None, + commit_sha=commit_sha or None, + ) + + +def should_retry(error: ProoflineError) -> bool: + return error.status in RETRYABLE_STATUSES or error.type in RETRYABLE_TYPES + + +def backoff(attempt: int) -> float: + return 2**attempt * random.uniform(0.5, 1) diff --git a/tests/test_http.py b/tests/test_http.py index 7b922c34..cbec946e 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2534,3 +2534,218 @@ 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" + + +SCAN_PATH = f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/scans" +RESOLUTION = UUID("00000000-0000-4000-8000-000000000007") + + +def scan(outcome: str = "CREATED", review_id: UUID | None = REVIEW) -> dict[str, Any]: + return { + "outcome": outcome, + "resolution_id": str(RESOLUTION), + "review_id": None if review_id is None else str(review_id), + } + + +def scan_ids(server: Server) -> set[str]: + return {json.loads(request.body)["request_id"] for request in server.requests} + + +@MODES +async def test_scan_revision_retries_with_one_request_id( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: ( + Reply(503, {"detail": "Unavailable."}) if index < 2 else Reply(body=scan()) + ) + ) as server: + async with session(mode, server.url) as client: + result = await call( + client, "scan_revision", ORG, REPOSITORY, budget_credits=50, ref="main" + ) + assert result.outcome == "CREATED" + assert result.review_id == REVIEW + assert [request.method for request in server.requests] == ["POST"] * 3 + assert {request.path for request in server.requests} == {SCAN_PATH} + assert len(scan_ids(server)) == 1 + UUID(scan_ids(server).pop()) + assert json.loads(server.requests[0].body)["budget_credits"] == 50 + assert json.loads(server.requests[0].body)["ref"] == "main" + assert len(clock.delays) == 2 + + +@MODES +async def test_scan_revision_keeps_a_caller_request_id(mode: str) -> None: + request_id = UUID("00000000-0000-4000-8000-0000000000aa") + with Server(lambda request, index: Reply(body=scan("EXISTING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "scan_revision", + ORG, + REPOSITORY, + budget_credits=1, + commit_sha="a" * 40, + request_id=request_id, + ) + assert result.outcome == "EXISTING" + assert scan_ids(server) == {str(request_id)} + assert json.loads(server.requests[0].body)["commit_sha"] == "a" * 40 + + +@MODES +@pytest.mark.parametrize("status", [429, 502, 503, 504]) +async def test_scan_revision_retry_is_bounded( + mode: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server(lambda request, index: Reply(status, {"detail": "Unavailable."})) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "scan_revision", ORG, REPOSITORY, budget_credits=1, ref="main") + assert raised.value.status == status + assert raised.value.__notes__ == [f"scan request_id: {scan_ids(server).copy().pop()}"] + assert len(server.requests) == 4 + assert len(scan_ids(server)) == 1 + + +@MODES +@pytest.mark.parametrize("status", [400, 401, 403, 404, 500]) +async def test_scan_revision_does_not_retry_other_problems(mode: str, status: int) -> None: + with Server(lambda request, index: Reply(status, {"detail": "No."})) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "scan_revision", ORG, REPOSITORY, budget_credits=1, ref="main") + assert raised.value.status == status + assert len(server.requests) == 1 + + +@MODES +async def test_scan_revision_waits_only_for_a_created_review(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + if request.method == "POST": + return Reply(body=scan()) + return Reply(body=review("COMPLETED")) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call( + client, "scan_revision", ORG, REPOSITORY, budget_credits=1, ref="main", wait=True + ) + assert result.review.id == REVIEW + assert [request.method for request in server.requests] == ["POST", "GET"] + + with Server(lambda request, index: Reply(body=scan("REPOSITORY_UNAVAILABLE", None))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "scan_revision", ORG, REPOSITORY, budget_credits=1, ref="main", wait=True + ) + assert result.outcome == "REPOSITORY_UNAVAILABLE" + assert len(server.requests) == 1 + + +def test_scan_retries_unreachable_api_and_timeouts_only() -> None: + from proofline import scans + + for kind in ("transport-unavailable", "timeout"): + assert scans.should_retry(ProoflineError(0, f"urn:proofline:sdk:{kind}", "Down.")) + assert not scans.should_retry(ProoflineError(0, "urn:proofline:sdk:invalid-response", "Bad.")) + + +@MODES +async def test_scan_revision_retries_a_timed_out_request_with_the_same_id( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server( + lambda request, index: ( + Reply(body=scan(), header_pause=0.5) if index == 0 else Reply(body=scan()) + ) + ) as server: + async with session(mode, server.url, timeout=0.1) as client: + result = await call( + client, "scan_revision", ORG, REPOSITORY, budget_credits=1, ref="main" + ) + assert result.outcome == "CREATED" + assert len(server.requests) == 2 + assert len(scan_ids(server)) == 1 + + +@MODES +@pytest.mark.parametrize( + "arguments", + [ + {}, + {"ref": "main", "commit_sha": "a" * 40}, + {"ref": ""}, + {"commit_sha": None}, + {"ref": " "}, + {"ref": "main", "budget_credits": -1}, + {"ref": "main", "budget_credits": True}, + {"ref": "main", "budget_credits": 1.5}, + {"ref": "main", "wait": True, "timeout": float("nan")}, + {"commit_sha": "abc123", "wait": True}, + ], +) +async def test_scan_revision_rejects_a_bad_call_before_any_request( + mode: str, arguments: dict[str, Any] +) -> None: + arguments = {"budget_credits": 1, **arguments} + with Server(lambda request, index: Reply(body=scan())) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError): + await call(client, "scan_revision", ORG, REPOSITORY, **arguments) + assert server.requests == [] + + +@MODES +async def test_scan_revision_ignores_timeout_when_not_waiting(mode: str) -> None: + with Server(lambda request, index: Reply(body=scan())) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "scan_revision", + ORG, + REPOSITORY, + budget_credits=1, + ref="main", + timeout=float("nan"), + ) + assert result.outcome == "CREATED" + + +@MODES +async def test_scan_revision_holds_the_wait_to_the_requested_commit(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + return ( + Reply(body=scan("EXISTING")) + if request.method == "POST" + else Reply(body=review_at(HEAD)) + ) + + with Server(respond) as server: + async with session(mode, server.url) as client: + same = await call( + client, + "scan_revision", + ORG, + REPOSITORY, + budget_credits=1, + commit_sha="a" * 40, + wait=True, + ) + other = await call( + client, + "scan_revision", + ORG, + REPOSITORY, + budget_credits=1, + commit_sha=OTHER_HEAD, + wait=True, + ) + assert same.status == "COMPLETED" + assert other.status == "INCOMPLETE" + assert gap_facts(other) == [PINNED_ELSEWHERE] From f6c7bc1ec75f1819f3e6a240edb6781b6a41e288 Mon Sep 17 00:00:00 2001 From: Thirumal Janakiraman Date: Tue, 17 Nov 2026 23:12:44 +0100 Subject: [PATCH 2/2] Register scan_revision as a client helper in the contract check --- scripts/contracts.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/scripts/contracts.py b/scripts/contracts.py index e8e4e73a..cb8d7141 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -31,7 +31,14 @@ def main() -> None: from proofline import AsyncProoflineClient, ProoflineClient for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_reviews", + "scan_revision", + "wait_for_review", + } exposed = { name for name in dir(client)