diff --git a/README.md b/README.md index 250fb32e..7e3ddd94 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,25 @@ the wait returns `TIMED_OUT` immediately. `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. +## Merge gate decisions + +A review completing is not the same as the merge gate deciding. The gate is a separate state machine (`REQUESTED` and `EVALUATING` before a verdict; `ALLOWED`, `BLOCKED`, `BYPASSED` or `SUPERSEDED` after), so a completed review can still be evaluating. `wait_for_merge_gate` waits for a terminal verdict and returns a `MergeGateDecision` that a CI job can act on directly. + +```python +requested = client.request_review(organization_id, repository_id, 12) +decision = client.wait_for_merge_gate( + organization_id, + requested.review_id, + head_commit_sha=head_commit_sha, +) +if not decision.allowed: + raise SystemExit(f"Merge blocked: {decision.status} ({decision.blocking_finding_count} findings)") +``` + +`allowed` is `True` only when the gate's own decision is `ALLOWED`, so it fails closed: `BYPASSED` (a human override), `SUPERSEDED`, an undecided gate at the deadline (`TIMED_OUT`), and a head with no captured gate (`UNAVAILABLE`) all leave `allowed` false. The decision also carries `blocking_severity`, `blocking_finding_count`, `policy_version`, `reason_code`, and the raw `gate`. + +`head_commit_sha` holds the verdict to that commit exactly as `wait_for_review` does: a gate pinned to another head is `UNAVAILABLE`, never `ALLOWED`. In a GitHub Actions `pull_request` job, pass the pull request's head, not `GITHUB_SHA`. Set `timeout=0` for a single read. Use `await` with `AsyncProoflineClient`. + ## Review exports `export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..ff2a79c9 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -35,6 +35,7 @@ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters from .exports import ExportDataset, ExportFormat, ExportPage +from .gates import MergeGateDecision from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -57,6 +58,7 @@ "FileReviewRequest", "FileReviewResponse", "KnowledgeResult", + "MergeGateDecision", "PatchReviewRequest", "PatchReviewResponse", "PatchTriggerSource", diff --git a/proofline/client.py b/proofline/client.py index 49e1a9e1..9288eb71 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -74,6 +74,7 @@ from ._transport import ProoflineError from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient +from .gates import MergeGateDecision, merge_gate_decision from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome @@ -585,6 +586,50 @@ def wait_for_review( ) return timed_out or ReviewOutcome("TIMED_OUT", url) + def wait_for_merge_gate( + self, + organization_id: UUID, + review_id: UUID, + *, + timeout: float = 300, + head_commit_sha: str | None = None, + ) -> MergeGateDecision: + """Wait for the merge gate to reach a terminal verdict or return TIMED_OUT. + + The gate decides after the review settles, so a completed review whose + gate is still EVALUATING keeps the wait open. + + head_commit_sha holds the verdict to that commit. A gate for another + head is never ALLOWED. + """ + + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The gate timeout must be a finite nonnegative number of seconds.") + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + last: CustomerReviewDetail | None = None + interval = 5.0 + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + last = self.get_review(organization_id, review_id) + except _transport.RetryDeadlineExceeded: + break + except ProoflineError as error: + if timeout > 0 and error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + result = merge_gate_decision(last, url, head_commit_sha=head_commit_sha) + if result is not None: + return result + budget = _transport.remaining() + if timeout == 0 or not budget: + break + sleep(min(interval, budget)) + interval = min(60, interval * 2) + timed_out = merge_gate_decision(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) + return timed_out or MergeGateDecision("TIMED_OUT", url, False) + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -972,3 +1017,38 @@ async def wait_for_review( last, url, "TIMED_OUT", review_id=review_id, head_commit_sha=head_commit_sha ) return timed_out or ReviewOutcome("TIMED_OUT", url) + + async def wait_for_merge_gate( + self, + organization_id: UUID, + review_id: UUID, + *, + timeout: float = 300, + head_commit_sha: str | None = None, + ) -> MergeGateDecision: + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The gate timeout must be a finite nonnegative number of seconds.") + _head_commit(head_commit_sha) + url = _review_url(self._base_url, organization_id, review_id) + last: CustomerReviewDetail | None = None + interval = 5.0 + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + last = await self.get_review(organization_id, review_id) + except _transport.RetryDeadlineExceeded: + break + except ProoflineError as error: + if timeout > 0 and error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + result = merge_gate_decision(last, url, head_commit_sha=head_commit_sha) + if result is not None: + return result + budget = _transport.remaining() + if timeout == 0 or not budget: + break + await async_sleep(min(interval, budget)) + interval = min(60, interval * 2) + timed_out = merge_gate_decision(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) + return timed_out or MergeGateDecision("TIMED_OUT", url, False) diff --git a/proofline/gates.py b/proofline/gates.py new file mode 100644 index 00000000..280776d1 --- /dev/null +++ b/proofline/gates.py @@ -0,0 +1,102 @@ +"""A pull request's merge-gate verdict, read from the recorded gate decision.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal + +from ._generated.models.customer_review_detail import CustomerReviewDetail +from ._generated.models.gate_status import GateStatus +from ._generated.models.pull_request_merge_gate import PullRequestMergeGate +from .outcomes import text + +GateVerdict = Literal["ALLOWED", "BLOCKED", "BYPASSED", "SUPERSEDED", "UNAVAILABLE", "TIMED_OUT"] +_TERMINAL: dict[GateStatus, GateVerdict] = { + GateStatus.ALLOWED: "ALLOWED", + GateStatus.BLOCKED: "BLOCKED", + GateStatus.BYPASSED: "BYPASSED", + GateStatus.SUPERSEDED: "SUPERSEDED", +} +_PENDING_REVIEW = ("PENDING", "RUNNING") +_UNDECIDED = "The merge gate was not decided before the deadline." + + +@dataclass(frozen=True) +class MergeGateDecision: + status: GateVerdict + review_url: str + allowed: bool + head_sha: str | None = None + blocking_severity: str | None = field(default=None, repr=False) + blocking_finding_count: int | None = field(default=None, repr=False) + policy_version: str | None = field(default=None, repr=False) + reason_code: str | None = field(default=None, repr=False) + gate: PullRequestMergeGate | None = field(default=None, repr=False) + reason: str | None = None + + +def _from_gate( + status: GateVerdict, + review_url: str, + gate: PullRequestMergeGate, + head_sha: str | None, + reason: str | None = None, +) -> MergeGateDecision: + return MergeGateDecision( + status, + review_url, + status == "ALLOWED", + head_sha, + text(gate.blocking_severity), + gate.finding_count if type(gate.finding_count) is int else None, + text(gate.policy_version), + text(gate.reason_code), + gate, + reason, + ) + + +def _head_mismatch(review: CustomerReviewDetail, head_commit_sha: str | None) -> bool: + if head_commit_sha is None: + return False + head = text(review.head_commit_sha) + return head is None or head.lower() != head_commit_sha.lower() + + +def merge_gate_decision( + review: CustomerReviewDetail | None, + review_url: str, + forced: GateVerdict | None = None, + *, + head_commit_sha: str | None = None, +) -> MergeGateDecision | None: + if review is None: + if forced is None: + return None + return MergeGateDecision(forced, review_url, False, reason="No review result is available.") + head_sha = text(review.head_commit_sha) + if _head_mismatch(review, head_commit_sha): + reason = "The review is pinned to another head commit." + return MergeGateDecision("UNAVAILABLE", review_url, False, head_sha, reason=reason) + gate = review.merge_gate + if not isinstance(gate, PullRequestMergeGate): + if review.status in _PENDING_REVIEW: + if forced is None: + return None + return MergeGateDecision(forced, review_url, False, head_sha, reason=_UNDECIDED) + reason = "This head has no captured merge gate." + return MergeGateDecision("UNAVAILABLE", review_url, False, head_sha, reason=reason) + gate_head = text(gate.head_sha) + if head_commit_sha is not None and ( + gate_head is None or gate_head.lower() != head_commit_sha.lower() + ): + reason = "The merge gate decides another head commit." + return MergeGateDecision( + "UNAVAILABLE", review_url, False, head_sha, gate=gate, reason=reason + ) + verdict = _TERMINAL.get(gate.status) + if verdict is not None: + return _from_gate(verdict, review_url, gate, head_sha) + if forced is not None: + return _from_gate("TIMED_OUT", review_url, gate, head_sha, _UNDECIDED) + return None diff --git a/tests/test_http.py b/tests/test_http.py index 68c6228e..1251e68c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1863,6 +1863,89 @@ def respond(request: Request, index: int) -> Reply: assert raised.value.type == "urn:proofline:sdk:pagination-limit" +def merge_gate(status: str, *, head: str = HEAD, severity: str = "SERIOUS", **extra: Any) -> dict: + return { + "blocking_severity": severity, + "head_sha": head, + "id": str(ASSESSMENT), + "policy_version": "2026-10-01", + "pull_request_number": 42, + "status": status, + **extra, + } + + +def review_with_gate(gate: dict | None, status: str = "COMPLETED", head: str = HEAD) -> dict: + body = review_at(head, status) + if gate is not None: + body["merge_gate"] = gate + return body + + +@MODES +async def test_wait_for_merge_gate_returns_the_servers_terminal_verdict( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + responses = [ + review_with_gate(merge_gate("REQUESTED"), "RUNNING"), + review_with_gate(merge_gate("EVALUATING")), + review_with_gate(merge_gate("ALLOWED", finding_count=0, decision="ALLOW")), + ] + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_merge_gate", ORG, REVIEW, timeout=100) + assert (result.status, result.allowed) == ("ALLOWED", True) + assert result.head_sha == HEAD + assert result.blocking_finding_count == 0 + assert result.policy_version == "2026-10-01" + assert clock.delays == [5, 10] + assert len(server.requests) == 3 + + blocked = merge_gate("BLOCKED", finding_count=3, decision="BLOCK", reason_code="FINDINGS_OPEN") + with Server(lambda request, index: Reply(body=review_with_gate(blocked))) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_merge_gate", ORG, REVIEW) + assert (result.status, result.allowed) == ("BLOCKED", False) + assert (result.blocking_severity, result.blocking_finding_count) == ("SERIOUS", 3) + assert result.reason_code == "FINDINGS_OPEN" + + for status in ("BYPASSED", "SUPERSEDED"): + body = review_with_gate(merge_gate(status)) + with Server(lambda request, index, body=body: Reply(body=body)) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_merge_gate", ORG, REVIEW) + assert (result.status, result.allowed) == (status, False) + + +@MODES +async def test_wait_for_merge_gate_bounds_absent_pending_and_mismatched_heads( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server(lambda request, index: Reply(body=review_with_gate(None))) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_merge_gate", ORG, REVIEW) + assert (result.status, result.allowed) == ("UNAVAILABLE", False) + assert result.reason == "This head has no captured merge gate." + assert len(server.requests) == 1 + + with Server(lambda request, index: Reply(body=review_with_gate(merge_gate("ALLOWED")))) as s: + async with session(mode, s.url) as client: + result = await call( + client, "wait_for_merge_gate", ORG, REVIEW, head_commit_sha=OTHER_HEAD + ) + assert (result.status, result.allowed) == ("UNAVAILABLE", False) + assert result.reason == "The review is pinned to another head commit." + + with Server(lambda request, index: Reply(body=review_with_gate(merge_gate("EVALUATING")))) as s: + async with session(mode, s.url) as client: + result = await call(client, "wait_for_merge_gate", ORG, REVIEW, timeout=0) + assert (result.status, result.allowed) == ("TIMED_OUT", False) + assert result.reason == "The merge gate was not decided before the deadline." + assert result.head_sha == HEAD + + def test_token_environment_and_https_origin_rejection(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("PROOFLINE_TOKEN", TOKEN) with ProoflineClient() as client: