diff --git a/README.md b/README.md index 721949da..5c772ce4 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,36 @@ 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. +## Deploy verification + +`wait_for_deploy_verifications` waits until Proofline records a check of the deploys of one commit, then returns what those checks recorded. It follows the same rules as `proofline ci deploy`. + +```python +from proofline import DeploySelector + +outcome = client.wait_for_deploy_verifications( + organization_id, + repository_id, + commit_sha, + until="MINUTES_20", + selector=DeploySelector(github_environment="production", deployment_task="deploy:web"), + timeout=1800, +) +if outcome.status != "NO_REGRESSION": + print(outcome.status, outcome.reason) +``` + +`until` is the check to wait for: `LANDING` (the default), `MINUTES_20`, `HOUR_1` or `DAY_1`, and the checks before it count too. `commit_sha` is a full 40-character lowercase SHA; any other value raises `ValueError` before a request. `selector` narrows the deploys by `environment_id`, `github_environment`, `deployment_task`, `github_deployment_id`, `workflow_run_id`, `workflow_run_attempt` or `aws_run_id`; without it every recorded deploy of the commit counts. + +The outcome's `status` is one of: + +- `REGRESSED`: a selected deploy failed or any of its checks recorded `REGRESSED`. This ends the wait at once. +- `NO_REGRESSION`: every check through `until` recorded `HEALTHY` with no gap. This means no regression was observed, not that the deploy is free of problems. +- `INCOMPLETE`: the check will not be recorded, or it is recorded but does not establish the result, for example a gap, a superseded or inactive deploy, deploy checks that ended early, or a state this SDK does not know. +- `TIMED_OUT`: the check was not recorded, or no selected deploy was recorded, before `timeout` seconds passed. + +`outcome.readings` holds each selected deploy with its own reading, and `reason` explains any status other than `NO_REGRESSION`. To judge a single read yourself, pass the result of `get_commit_deploy_verifications` to `judge_deploy_verifications(read, until, selector)`; a check not recorded yet then reads `INCOMPLETE`. `AsyncProoflineClient` offers the same methods with `await`. + ## 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..001f1e61 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -6,6 +6,8 @@ from ._generated.models import ( AgentSession, AgentVendor, + CommitDeploy, + CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, @@ -13,6 +15,7 @@ CustomerAssessmentDetail, CustomerFinding, CustomerReviewDetail, + DeployCheckpoint, FileReviewRequest, FileReviewResponse, PatchReviewRequest, @@ -34,6 +37,12 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .deploys import ( + DeployReading, + DeploySelector, + DeployVerificationOutcome, + judge_deploy_verifications, +) from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -44,6 +53,8 @@ "AssessmentGap", "AsyncProoflineClient", "CheckGap", + "CommitDeploy", + "CommitDeployVerifications", "CommitReviewRequest", "CommitReviewResponse", "CoverageUploadRequest", @@ -51,6 +62,10 @@ "CustomerAssessmentDetail", "CustomerFinding", "CustomerReviewDetail", + "DeployCheckpoint", + "DeployReading", + "DeploySelector", + "DeployVerificationOutcome", "ExportDataset", "ExportFormat", "ExportPage", @@ -79,5 +94,6 @@ "StopResponse", "UploadedReport", "__version__", + "judge_deploy_verifications", "models", ] diff --git a/proofline/_generated/api/operations.py b/proofline/_generated/api/operations.py index 227215e7..9a9a1240 100644 --- a/proofline/_generated/api/operations.py +++ b/proofline/_generated/api/operations.py @@ -5,33 +5,14 @@ from ... import _transport from ..client import AuthenticatedClient -from ..models.commit_deploy_verifications import CommitDeployVerifications from ..models.scan_request_body import ScanRequestBody from ..models.scan_response import ScanResponse -from .default import get_commit_deploy_verifications as operation_get_commit_deploy_verifications from .default import request_scan as operation_request_scan class Operations: _api: AuthenticatedClient - def get_commit_deploy_verifications( - self, - org_id: UUID, - repo_id: UUID, - commit_sha: str, - ) -> CommitDeployVerifications: - with _transport.operation_errors(): - response = operation_get_commit_deploy_verifications.sync_detailed( - client=self._api, - org_id=org_id, - repo_id=repo_id, - commit_sha=commit_sha, - ) - if not (response.status_code == 200): - raise _transport.invalid_response() - return cast(CommitDeployVerifications, response.parsed) - def request_scan( self, org_id: UUID, @@ -54,23 +35,6 @@ def request_scan( class AsyncOperations: _api: AuthenticatedClient - async def get_commit_deploy_verifications( - self, - org_id: UUID, - repo_id: UUID, - commit_sha: str, - ) -> CommitDeployVerifications: - with _transport.operation_errors(): - response = await operation_get_commit_deploy_verifications.asyncio_detailed( - client=self._api, - org_id=org_id, - repo_id=repo_id, - commit_sha=commit_sha, - ) - if not (response.status_code == 200): - raise _transport.invalid_response() - return cast(CommitDeployVerifications, response.parsed) - async def request_scan( self, org_id: UUID, diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..a6687707 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -20,6 +20,7 @@ get_agent_session, get_agent_session_prompt, get_assessment, + get_commit_deploy_verifications, get_deployment_review, get_finding, get_finding_fix_prompt, @@ -44,6 +45,7 @@ from ._generated.models.agent_session import AgentSession from ._generated.models.agent_session_prompt_type_0 import AgentSessionPromptType0 from ._generated.models.agent_session_prompt_type_1 import AgentSessionPromptType1 +from ._generated.models.commit_deploy_verifications import CommitDeployVerifications from ._generated.models.commit_review_request import CommitReviewRequest from ._generated.models.commit_review_response import CommitReviewResponse from ._generated.models.coverage_upload_request import CoverageUploadRequest @@ -51,6 +53,7 @@ from ._generated.models.customer_assessment_detail import CustomerAssessmentDetail from ._generated.models.customer_finding import CustomerFinding from ._generated.models.customer_review_detail import CustomerReviewDetail +from ._generated.models.deploy_checkpoint import DeployCheckpoint from ._generated.models.file_review_request import FileReviewRequest from ._generated.models.file_review_response import FileReviewResponse from ._generated.models.finding_fix_prompt_type_0 import FindingFixPromptType0 @@ -72,6 +75,13 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError +from .deploys import ( + Checkpoint, + DeploySelector, + DeployVerificationOutcome, + checkpoint_name, + conclude, +) from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient @@ -163,6 +173,23 @@ def _head_commit(value: str | None) -> None: raise ValueError("The head commit must be a full 40 or 64 character hexadecimal SHA.") +def _commit_sha(value: str) -> None: + # The deploy route accepts only a full lowercase SHA; refuse anything else before a request. + if ( + not isinstance(value, str) + or len(value) != 40 + or any(character not in "0123456789abcdef" for character in value) + ): + raise ValueError("The commit must be a full 40 character lowercase hexadecimal SHA.") + + +def _deploy_wait(timeout: float, commit_sha: str, until: str) -> Checkpoint: + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The deploy timeout must be a finite nonnegative number of seconds.") + _commit_sha(commit_sha) + return checkpoint_name(until) + + def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None: if not isinstance(page.truncated, bool): raise _transport.invalid_response() @@ -539,6 +566,59 @@ def iter_reviews( params["cursor"] = cursor raise _pagination_limit() + def get_commit_deploy_verifications( + self, organization_id: UUID, repository_id: UUID, commit_sha: str + ) -> CommitDeployVerifications: + _commit_sha(commit_sha) + return self._call( + get_commit_deploy_verifications.sync_detailed, + CommitDeployVerifications, + organization_id, + repository_id, + commit_sha, + ) + + def wait_for_deploy_verifications( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + until: Checkpoint | DeployCheckpoint = "LANDING", + selector: DeploySelector | None = None, + timeout: float = 1800, + ) -> DeployVerificationOutcome: + """Wait until the selected deploys record the `until` check, or return TIMED_OUT. + + A regression ends the wait at once. NO_REGRESSION means every check + through `until` recorded HEALTHY with no gap; any other settled read is + INCOMPLETE. + """ + checkpoint = _deploy_wait(timeout, commit_sha, until) + last: CommitDeployVerifications | None = None + deadline = _transport.DEADLINE.set(monotonic() + timeout) + interval = 5.0 + try: + while (_transport.remaining() or 0) > 0: + try: + last = self.get_commit_deploy_verifications( + organization_id, repository_id, commit_sha + ) + except ProoflineError as error: + if error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + result = conclude(last, checkpoint, selector, None) + if result is not None: + return result + sleep(min(interval, _transport.remaining() or 0)) + interval = min(60, interval * 2) + return cast( + DeployVerificationOutcome, conclude(last, checkpoint, selector, "TIMED_OUT") + ) + finally: + _transport.DEADLINE.reset(deadline) + def wait_for_review( self, organization_id: UUID, @@ -934,6 +1014,53 @@ async def iter_reviews( params["cursor"] = cursor raise _pagination_limit() + async def get_commit_deploy_verifications( + self, organization_id: UUID, repository_id: UUID, commit_sha: str + ) -> CommitDeployVerifications: + _commit_sha(commit_sha) + return await self._call( + get_commit_deploy_verifications.asyncio_detailed, + CommitDeployVerifications, + organization_id, + repository_id, + commit_sha, + ) + + async def wait_for_deploy_verifications( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + until: Checkpoint | DeployCheckpoint = "LANDING", + selector: DeploySelector | None = None, + timeout: float = 1800, + ) -> DeployVerificationOutcome: + checkpoint = _deploy_wait(timeout, commit_sha, until) + last: CommitDeployVerifications | None = None + deadline = _transport.DEADLINE.set(monotonic() + timeout) + interval = 5.0 + try: + while (_transport.remaining() or 0) > 0: + try: + last = await self.get_commit_deploy_verifications( + organization_id, repository_id, commit_sha + ) + except ProoflineError as error: + if error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + result = conclude(last, checkpoint, selector, None) + if result is not None: + return result + await async_sleep(min(interval, _transport.remaining() or 0)) + interval = min(60, interval * 2) + return cast( + DeployVerificationOutcome, conclude(last, checkpoint, selector, "TIMED_OUT") + ) + finally: + _transport.DEADLINE.reset(deadline) + async def wait_for_review( self, organization_id: UUID, diff --git a/proofline/deploys.py b/proofline/deploys.py new file mode 100644 index 00000000..aea79a33 --- /dev/null +++ b/proofline/deploys.py @@ -0,0 +1,226 @@ +"""Deploy verification follows the checks Proofline recorded for one commit's deploys. + +The rules match `proofline ci deploy`: a result is "no regression observed", +never a claim about the deploy itself, and anything Proofline did not +establish reads as INCOMPLETE. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal +from uuid import UUID + +from ._generated.models.commit_deploy import CommitDeploy +from ._generated.models.commit_deploy_verifications import CommitDeployVerifications +from ._generated.models.deploy_checkpoint import DeployCheckpoint +from ._generated.types import Unset +from ._transport import invalid_response + +Checkpoint = Literal["LANDING", "MINUTES_20", "HOUR_1", "DAY_1"] +DeployStatus = Literal["NO_REGRESSION", "REGRESSED", "INCOMPLETE", "TIMED_OUT"] +ReadingKind = Literal[ + "REGRESSED", + "WAITING", + "SUPERSEDED", + "UNVERIFIED", + "INACTIVE", + "ENDED", + "NOT_ESTABLISHED", + "UNKNOWN_STATE", + "NO_REGRESSION", +] + +CHECKPOINTS: tuple[Checkpoint, ...] = ("LANDING", "MINUTES_20", "HOUR_1", "DAY_1") +# A state a newer server adds may mean what no check here shows. +KNOWN_STATES = frozenset( + ( + "VERIFIED", + "VERIFIED_UNTIL_SUPERSEDED", + "SUPERSEDED", + "INCOMPLETE", + "UNRECORDED", + "NOT_YET_DUE", + "UNVERIFIED", + "FAILED", + "INACTIVE", + ) +) +_REASONS: dict[str, str] = { + "UNKNOWN_STATE": "A selected deploy reads a state this SDK does not know.", + "INACTIVE": "A selected deploy never landed, so the {until} check will not be recorded.", + "SUPERSEDED": "A later deploy replaced a selected deploy before the {until} check.", + "ENDED": "Deploy checks ended without recording the {until} check.", + "UNVERIFIED": "Proofline has no deploy checks of a selected deploy.", + "NOT_ESTABLISHED": "A check through {until} did not record HEALTHY, or names a gap.", +} + + +@dataclass(frozen=True) +class DeploySelector: + """Which deploys of the commit count. Fields left as None match every deploy.""" + + environment_id: UUID | None = None + github_environment: str | None = None + deployment_task: str | None = None + github_deployment_id: int | None = None + workflow_run_id: int | None = None + workflow_run_attempt: int | None = None + aws_run_id: str | None = None + + def __post_init__(self) -> None: + if self.workflow_run_attempt is not None and self.workflow_run_id is None: + raise ValueError("workflow_run_attempt names an attempt of workflow_run_id.") + + def selects(self, deploy: CommitDeploy) -> bool: + def same(wanted: object, value: object) -> bool: + return wanted is None or wanted == value + + def holds(wanted: int | None, values: object) -> bool: + # A deploy that lists no IDs or attempts never matches one. + return wanted is None or (isinstance(values, list) and wanted in values) + + return ( + same(self.environment_id, deploy.environment_id) + and same(self.github_environment, deploy.github_environment) + and same(self.deployment_task, deploy.deployment_task) + and same(self.workflow_run_id, deploy.workflow_run_id) + and same(self.aws_run_id, deploy.aws_run_id) + and holds(self.github_deployment_id, deploy.github_deployment_ids) + and holds(self.workflow_run_attempt, deploy.workflow_run_attempts) + ) + + +@dataclass(frozen=True) +class DeployReading: + """What one selected deploy's checks through the target checkpoint say.""" + + deploy: CommitDeploy = field(repr=False) + reading: ReadingKind + + +@dataclass(frozen=True) +class DeployVerificationOutcome: + status: DeployStatus + checkpoint: Checkpoint + readings: tuple[DeployReading, ...] = () + verifications: CommitDeployVerifications | None = field(default=None, repr=False) + reason: str | None = None + + +def checkpoint_name(value: str) -> Checkpoint: + if value not in CHECKPOINTS: + raise ValueError("until must be LANDING, MINUTES_20, HOUR_1 or DAY_1.") + return CHECKPOINTS[CHECKPOINTS.index(value)] + + +def _check(deploy: CommitDeploy, at: Checkpoint) -> tuple[str | None, tuple[str, ...]]: + # Older servers report only the deploy-wide gaps. + for check in deploy.checkpoints: + if check.checkpoint == at: + result = check.result if isinstance(check.result, str) else None + gaps = check.gaps if isinstance(check.gaps, list) else deploy.gaps + return result, tuple(gaps) + return None, tuple(deploy.gaps) + + +def _read(deploy: CommitDeploy, until: Checkpoint) -> ReadingKind: + through = CHECKPOINTS[: CHECKPOINTS.index(until) + 1] + # A regression at any checkpoint, even a later one, decides first. + if ( + deploy.state == "FAILED" + or deploy.regressed + or any(check.result == "REGRESSED" for check in deploy.checkpoints) + ): + return "REGRESSED" + if deploy.state == "UNVERIFIED": + return "UNVERIFIED" + if deploy.state == "INACTIVE": + return "INACTIVE" + if any(_check(deploy, at)[0] == "SUPERSEDED" for at in through): + return "SUPERSEDED" + if _check(deploy, until)[0] is None: + return "ENDED" if deploy.verification_ended is True else "WAITING" + if deploy.state not in KNOWN_STATES: + return "UNKNOWN_STATE" + if all(_check(deploy, at) == ("HEALTHY", ()) for at in through): + return "NO_REGRESSION" + return "NOT_ESTABLISHED" + + +def _validate(verifications: CommitDeployVerifications) -> None: + if not isinstance(verifications, CommitDeployVerifications) or not isinstance( + verifications.deploys, list + ): + raise invalid_response() + for deploy in verifications.deploys: + if ( + not isinstance(deploy, CommitDeploy) + or not isinstance(deploy.state, str) + or type(deploy.regressed) is not bool + or not isinstance(deploy.checkpoints, list) + or not isinstance(deploy.gaps, list) + or any(not isinstance(gap, str) for gap in deploy.gaps) + or any(not isinstance(check.result, str | Unset | None) for check in deploy.checkpoints) + ): + raise invalid_response() + + +def conclude( + verifications: CommitDeployVerifications | None, + until: Checkpoint, + selector: DeploySelector | None, + pending: Literal["INCOMPLETE", "TIMED_OUT"] | None, +) -> DeployVerificationOutcome | None: + """The outcome of one read; None while a check may still come and pending is None.""" + if verifications is None: + if pending is None: + return None + return DeployVerificationOutcome(pending, until, reason="No deploy read is available.") + _validate(verifications) + readings = tuple( + DeployReading(deploy, _read(deploy, until)) + for deploy in verifications.deploys + if selector is None or selector.selects(deploy) + ) + kinds = {reading.reading for reading in readings} + status: DeployStatus + if "REGRESSED" in kinds: + status, reason = "REGRESSED", "A selected deploy failed or a check recorded REGRESSED." + elif not readings or "WAITING" in kinds: + if pending is None: + return None + status = pending + if readings: + reason = f"The {until} check is not recorded." + elif verifications.deploys: + reason = "No recorded deploy matches the selector." + else: + reason = "No deploy of the commit is recorded." + elif kinds == {"NO_REGRESSION"}: + return DeployVerificationOutcome("NO_REGRESSION", until, readings, verifications) + else: + others = kinds - {"NO_REGRESSION"} + if "UNKNOWN_STATE" in others: + kind = "UNKNOWN_STATE" + elif len(others) == 1: + kind = others.pop() + else: + kind = "NOT_ESTABLISHED" + status, reason = "INCOMPLETE", _REASONS[kind].format(until=until) + return DeployVerificationOutcome(status, until, readings, verifications, reason) + + +def judge_deploy_verifications( + verifications: CommitDeployVerifications, + until: Checkpoint | DeployCheckpoint = "LANDING", + selector: DeploySelector | None = None, +) -> DeployVerificationOutcome: + """Judge one read of a commit's deploys through `until`. + + A check that is not recorded yet reads INCOMPLETE; use + `wait_for_deploy_verifications` to wait for it. + """ + result = conclude(verifications, checkpoint_name(until), selector, "INCOMPLETE") + assert result is not None + return result diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..dc84a3aa 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -42,7 +42,14 @@ def main() -> None: raise SystemExit("ReviewFilters differs from the list_reviews query parameters.") for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_reviews", + "wait_for_deploy_verifications", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..27427299 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -28,6 +28,7 @@ from proofline import ( AsyncProoflineClient, + CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, @@ -35,6 +36,8 @@ CustomerAssessmentDetail, CustomerFinding, CustomerReviewDetail, + DeployCheckpoint, + DeploySelector, FileReviewRequest, FileReviewResponse, PatchReviewRequest, @@ -52,6 +55,7 @@ UploadedReport, _sync_http, _transport, + judge_deploy_verifications, models, ) from proofline import client as client_module @@ -2586,3 +2590,251 @@ 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" + + +DEPLOY_COMMIT = "89abcdef0123456789abcdef0123456789abcdef" +DEPLOY_PATH = ( + f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}" + f"/commits/{DEPLOY_COMMIT}/deploy-verifications" +) + + +def deploy(*results: str | None, **fields: Any) -> dict[str, Any]: + """A deploy of one task in run 7 whose checks recorded `results` in order, the rest not yet.""" + checkpoints = ("LANDING", "MINUTES_20", "HOUR_1", "DAY_1") + return { + "environment_id": str(ASSESSMENT), + "github_environment": "production", + "deployment_task": "deploy", + "workflow_run_id": 7, + "workflow_run_attempts": [1], + "state": "NOT_YET_DUE", + "regressed": "REGRESSED" in results, + "checkpoints": [ + {"checkpoint": name, "result": result, "due_at": "2026-11-21T00:00:00Z"} + for name, result in zip(checkpoints, (*results, None, None, None, None)) + ], + "gaps": [], + **fields, + } + + +def verifications(*deploys: dict[str, Any]) -> dict[str, Any]: + return {"recorded": bool(deploys), "deploys": list(deploys)} + + +def gap_at_minutes_20() -> dict[str, Any]: + # Newer servers report each check's own gaps beside the deploy-wide ones. + recorded = deploy("HEALTHY", "HEALTHY", "HEALTHY", gaps=["SIGNAL_NO_DATA"]) + for index, check in enumerate(recorded["checkpoints"]): + check["gaps"] = ["SIGNAL_NO_DATA"] if index == 1 else [] + return recorded + + +HEALTHY = deploy("HEALTHY", "HEALTHY", "HEALTHY") +ENDED = deploy("HEALTHY", "HEALTHY", state="UNRECORDED", verification_ended=True) + + +@MODES +@pytest.mark.parametrize( + ("until", "recorded", "status"), + [ + ("LANDING", HEALTHY, "NO_REGRESSION"), + ("HOUR_1", HEALTHY, "NO_REGRESSION"), + ("LANDING", deploy("REGRESSED"), "REGRESSED"), + ("LANDING", deploy("HEALTHY", "REGRESSED"), "REGRESSED"), + ("LANDING", deploy("HEALTHY", state="FAILED"), "REGRESSED"), + ("LANDING", deploy("HEALTHY", gaps=["SIGNAL_NO_DATA"]), "INCOMPLETE"), + ("LANDING", gap_at_minutes_20(), "NO_REGRESSION"), + ("MINUTES_20", gap_at_minutes_20(), "INCOMPLETE"), + ("HOUR_1", gap_at_minutes_20(), "INCOMPLETE"), + ("LANDING", deploy("INCOMPLETE"), "INCOMPLETE"), + ("LANDING", deploy("SUPERSEDED"), "INCOMPLETE"), + ("HOUR_1", deploy("HEALTHY", "SUPERSEDED"), "INCOMPLETE"), + ("LANDING", deploy(state="UNVERIFIED"), "INCOMPLETE"), + ("LANDING", deploy(state="INACTIVE"), "INCOMPLETE"), + ("HOUR_1", ENDED, "INCOMPLETE"), + ("MINUTES_20", ENDED, "NO_REGRESSION"), + ("LANDING", deploy("HEALTHY", state="ROLLING_OUT"), "INCOMPLETE"), + ("LANDING", deploy("HEALTHY", "REGRESSED", state="ROLLING_OUT"), "REGRESSED"), + ("LANDING", deploy("HEALTHY", "INCOMPLETE", state="INCOMPLETE"), "NO_REGRESSION"), + ], + ids=[ + "healthy", + "healthy-at-1h", + "regressed-at-landing", + "regressed-after-the-named-check", + "failed", + "deploy-wide-gap", + "gap-after-the-named-check", + "gap-at-the-named-check", + "gap-before-the-named-check", + "incomplete", + "superseded", + "superseded-before-1h", + "unverified", + "inactive", + "checks-ended-before-1h", + "checks-ended-after-20m", + "unknown-state", + "unknown-state-regressed", + "later-incomplete-on-known-state", + ], +) +async def test_deploy_wait_settles_each_reading_on_the_first_read( + mode: str, until: str, recorded: dict[str, Any], status: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server(lambda request, index: Reply(body=verifications(recorded))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_deploy_verifications", ORG, REPOSITORY, DEPLOY_COMMIT, until=until + ) + assert result.status == status + assert result.checkpoint == until + assert (result.reason is None) == (status == "NO_REGRESSION") + assert len(result.readings) == 1 + assert len(server.requests) == 1 + + +@MODES +async def test_deploy_wait_polls_until_the_check_is_recorded_or_times_out( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + answers = [ + verifications(), + verifications(deploy("HEALTHY")), + verifications(deploy("HEALTHY", "HEALTHY")), + ] + with Server(lambda request, index: Reply(body=answers[index])) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_deploy_verifications", + ORG, + REPOSITORY, + DEPLOY_COMMIT, + until=DeployCheckpoint.MINUTES_20, + ) + assert result.status == "NO_REGRESSION" + assert clock.delays == [5.0, 10.0] + assert [request.path for request in server.requests] == [DEPLOY_PATH] * 3 + assert server.requests[0].headers["Authorization"] == f"Bearer {TOKEN}" + + clock.delays.clear() + with Server(lambda request, index: Reply(body=verifications(deploy()))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_deploy_verifications", ORG, REPOSITORY, DEPLOY_COMMIT, timeout=30 + ) + assert result.status == "TIMED_OUT" + assert result.reason == "The LANDING check is not recorded." + assert clock.delays == [5.0, 10.0, 15.0] + assert len(server.requests) == 3 + result = await call( + client, "wait_for_deploy_verifications", ORG, REPOSITORY, DEPLOY_COMMIT, timeout=0 + ) + assert result.status == "TIMED_OUT" + assert len(server.requests) == 3 + + +@MODES +async def test_deploy_reads_refuse_bad_arguments_before_a_request(mode: str) -> None: + with Server(lambda request, index: Reply(body=verifications())) as server: + async with session(mode, server.url) as client: + for sha in ( + "main", + DEPLOY_COMMIT[:12], + DEPLOY_COMMIT.upper(), + DEPLOY_COMMIT + "0", + "g" * 40, + "a" * 64, + ): + for operation in ( + "get_commit_deploy_verifications", + "wait_for_deploy_verifications", + ): + with pytest.raises(ValueError, match="commit"): + await call(client, operation, ORG, REPOSITORY, sha) + for kwargs in ({"until": "2h"}, {"timeout": -1}, {"timeout": float("inf")}): + with pytest.raises(ValueError): + await call( + client, + "wait_for_deploy_verifications", + ORG, + REPOSITORY, + DEPLOY_COMMIT, + **kwargs, + ) + assert not server.requests + with pytest.raises(ValueError, match="workflow_run_id"): + DeploySelector(workflow_run_attempt=2) + + +@MODES +async def test_deploy_read_decodes_the_commit_and_refuses_malformed_deploys(mode: str) -> None: + malformed = [ + deploy(state=7), + deploy(regressed="no"), + deploy(gaps=[7]), + {**deploy(), "checkpoints": [{"checkpoint": "HOUR_2", "due_at": "2026-11-21T00:00:00Z"}]}, + ] + bodies = [verifications(deploy("HEALTHY", rolled_back=True))] + [ + verifications(body) for body in malformed + ] + with Server(lambda request, index: Reply(body=bodies[index])) as server: + async with session(mode, server.url) as client: + read = await call( + client, "get_commit_deploy_verifications", ORG, REPOSITORY, DEPLOY_COMMIT + ) + assert isinstance(read, CommitDeployVerifications) + assert read.recorded is True + assert read.deploys[0].rolled_back is True + for _ in malformed: + with pytest.raises(ProoflineError) as raised: + await call( + client, "wait_for_deploy_verifications", ORG, REPOSITORY, DEPLOY_COMMIT + ) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + assert len(server.requests) == len(bodies) + + +def test_deploy_selector_decides_which_deploys_count() -> None: + web = deploy("HEALTHY", deployment_task="deploy:web", github_deployment_ids=[101]) + api = deploy( + "REGRESSED", + deployment_task="deploy:api", + workflow_run_attempts=[1, 2], + github_deployment_ids=[102], + ) + # An older server omits github_deployment_ids, so no deployment ID selects this one. + aws = deploy( + "HEALTHY", + environment_id=str(REVIEW), + aws_provider="AWS_CODEPIPELINE", + aws_run_id="execution-1", + workflow_run_id=None, + workflow_run_attempts=[], + ) + read = CommitDeployVerifications.from_dict(verifications(web, api, aws)) + for selector, status, tasks in [ + (None, "REGRESSED", ["deploy:web", "deploy:api", "deploy"]), + (DeploySelector(deployment_task="deploy:web"), "NO_REGRESSION", ["deploy:web"]), + (DeploySelector(github_deployment_id=102), "REGRESSED", ["deploy:api"]), + (DeploySelector(github_deployment_id=103), "INCOMPLETE", []), + (DeploySelector(workflow_run_id=7, workflow_run_attempt=2), "REGRESSED", ["deploy:api"]), + (DeploySelector(workflow_run_id=7, workflow_run_attempt=3), "INCOMPLETE", []), + (DeploySelector(aws_run_id="execution-1"), "NO_REGRESSION", ["deploy"]), + (DeploySelector(environment_id=REVIEW), "NO_REGRESSION", ["deploy"]), + (DeploySelector(github_environment="staging"), "INCOMPLETE", []), + ]: + result = judge_deploy_verifications(read, "LANDING", selector) + assert result.status == status, selector + assert [reading.deploy.deployment_task for reading in result.readings] == tasks + empty = judge_deploy_verifications(read, "LANDING", DeploySelector(github_environment="x")) + assert empty.reason == "No recorded deploy matches the selector." + pending = judge_deploy_verifications( + CommitDeployVerifications.from_dict(verifications(deploy())), DeployCheckpoint.HOUR_1 + ) + assert (pending.status, pending.reason) == ("INCOMPLETE", "The HOUR_1 check is not recorded.")