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
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
96 changes: 96 additions & 0 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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__(
Expand Down Expand Up @@ -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
51 changes: 51 additions & 0 deletions proofline/scans.py
Original file line number Diff line number Diff line change
@@ -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)
9 changes: 8 additions & 1 deletion scripts/contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading