diff --git a/README.md b/README.md index 721949da..af2195d0 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,33 @@ 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. +## Waiting for deploy verification + +After a deploy job, `wait_for_deploy_verification` holds the job until Proofline's checks of that commit's deploys settle. Name the full 40-character lowercase commit SHA the job deployed and, with `through`, the last check to wait for: `LANDING` (the default), `MINUTES_20`, `HOUR_1` or `DAY_1`. The token needs `reviews:read`. + +```python +import os +from uuid import UUID +from proofline import ProoflineClient + +with ProoflineClient() as client: + outcome = client.wait_for_deploy_verification( + UUID(os.environ["PROOFLINE_ORGANIZATION_ID"]), + UUID(os.environ["PROOFLINE_REPOSITORY_ID"]), + os.environ["DEPLOYED_SHA"], + through="MINUTES_20", + timeout=1800, + ) + for deploy in outcome.deploys: + print(deploy.environment_id, deploy.status, deploy.reason_codes, deploy.deploy_url) + if outcome.status != "HEALTHY": + raise SystemExit(f"Deploy verification: {outcome.status}") +``` + +A deploy settles once every check through `through` recorded a result, or once its verification ended. The outcome is `HEALTHY` only when each recorded deploy's checks recorded `HEALTHY` with no gap. A check that a later deploy replaced counts only after a healthy landing check, as `VERIFIED_UNTIL_SUPERSEDED` reads it. A regression ends the wait at once with `REGRESSED`, whichever check recorded it, even past `through` and while other deploys are still due. Once every deploy settles, a failed GitHub deployment gives `FAILED`, and a gap, an `INCOMPLETE` check, a check never recorded, an unverified or rolled-back deploy, or a result this SDK does not know gives `INCOMPLETE`. Each `DeployVerdict` names its environment, its `status`, the deploy's `state` and the `reason_codes` that leave it unproven. `environment_id` holds the wait to the deploys of one environment. Between reads the wait sleeps until the next check it needs is due, reading at least every five minutes so a failed or newly recorded deploy still ends it early; an overdue check falls back to the usual backoff. + +A commit with no recorded deploy keeps the wait open, because the deploy may still be recorded, and ends as `TIMED_OUT`, never `HEALTHY`. Any other wait still open at `timeout` also returns `TIMED_OUT` with each deploy's verdict so far; a deploy still due reads `PENDING`. Any other `commit_sha`, `through` or `timeout` raises `ValueError` before a request. + ## 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..d2316107 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -34,6 +34,7 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .deploys import DeployVerdict, DeployVerificationOutcome from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -51,6 +52,8 @@ "CustomerAssessmentDetail", "CustomerFinding", "CustomerReviewDetail", + "DeployVerdict", + "DeployVerificationOutcome", "ExportDataset", "ExportFormat", "ExportPage", diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..eb4d33ba 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,6 +5,7 @@ import math from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from datetime import UTC, datetime from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -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 @@ -72,6 +74,14 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError +from .deploys import ( + DeployCheckpointName, + DeployVerificationOutcome, + checkpoint_index, + deploy_commit, + next_due, +) +from .deploys import outcome as deploy_outcome from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient @@ -139,6 +149,33 @@ def _configuration( ) +# A check due later than this is still read at least this often, so a deploy that +# fails or is recorded between checks ends the wait without waiting for the check. +_DEPLOY_READ_CEILING = 300.0 + + +def utc_now() -> datetime: + return datetime.now(UTC) + + +def _deploy_delay( + verifications: CommitDeployVerifications | None, + through: int, + environment_id: UUID | None, + interval: float, +) -> float: + # Checks are recorded on a schedule the ledger already names, so sleeping until + # the next one is due replaces reads that could only return the same snapshot. + due = ( + None + if verifications is None + else next_due(verifications, through, environment_id=environment_id) + ) + if due is None: + return interval + return max(interval, min((due - utc_now()).total_seconds(), _DEPLOY_READ_CEILING)) + + def _review_url(base_url: str, organization_id: UUID, review_id: UUID) -> str: return ( f"{base_url}/orgs/by-id/{quote(str(organization_id), safe='')}" @@ -583,6 +620,58 @@ def wait_for_review( finally: _transport.DEADLINE.reset(deadline) + def wait_for_deploy_verification( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + through: DeployCheckpointName = "LANDING", + environment_id: UUID | None = None, + timeout: float = 1800, + ) -> DeployVerificationOutcome: + """Wait until every recorded deploy of a commit settles, or return TIMED_OUT. + + A deploy settles once each check through ``through`` recorded a result, + or its verification ended. A recorded regression ends the wait at once, + whichever check recorded it. A commit with no recorded deploy keeps the + wait open, since a deploy may still be recorded; it is never HEALTHY. + + environment_id holds the wait to the deploys of one environment. + """ + + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The deploy timeout must be a finite nonnegative number of seconds.") + deploy_commit(commit_sha) + index = checkpoint_index(through) + 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 + if (_transport.remaining() or 0) <= 0: + break + result = deploy_outcome(last, commit_sha, index, environment_id=environment_id) + if result is not None: + return result + delay = _deploy_delay(last, index, environment_id, interval) + sleep(min(delay, _transport.remaining() or 0)) + interval = min(60, interval * 2) + timed_out = deploy_outcome( + last, commit_sha, index, environment_id=environment_id, forced="TIMED_OUT" + ) + return timed_out or DeployVerificationOutcome("TIMED_OUT", commit_sha) + finally: + _transport.DEADLINE.reset(deadline) + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -968,3 +1057,45 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) + + async def wait_for_deploy_verification( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + through: DeployCheckpointName = "LANDING", + environment_id: UUID | None = None, + timeout: float = 1800, + ) -> DeployVerificationOutcome: + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The deploy timeout must be a finite nonnegative number of seconds.") + deploy_commit(commit_sha) + index = checkpoint_index(through) + 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 + if (_transport.remaining() or 0) <= 0: + break + result = deploy_outcome(last, commit_sha, index, environment_id=environment_id) + if result is not None: + return result + delay = _deploy_delay(last, index, environment_id, interval) + await async_sleep(min(delay, _transport.remaining() or 0)) + interval = min(60, interval * 2) + timed_out = deploy_outcome( + last, commit_sha, index, environment_id=environment_id, forced="TIMED_OUT" + ) + return timed_out or DeployVerificationOutcome("TIMED_OUT", commit_sha) + finally: + _transport.DEADLINE.reset(deadline) diff --git a/proofline/deploys.py b/proofline/deploys.py new file mode 100644 index 00000000..bdd0fcf0 --- /dev/null +++ b/proofline/deploys.py @@ -0,0 +1,222 @@ +"""Deploy verification outcomes follow each recorded deploy's checks.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from datetime import datetime +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.types import Unset +from ._transport import ProoflineError + +DeployCheckpointName = Literal["LANDING", "MINUTES_20", "HOUR_1", "DAY_1"] +DeployOutcomeStatus = Literal["HEALTHY", "REGRESSED", "FAILED", "INCOMPLETE", "TIMED_OUT"] +DeployVerdictStatus = Literal["HEALTHY", "REGRESSED", "FAILED", "INCOMPLETE", "PENDING"] + +CHECKPOINTS: tuple[DeployCheckpointName, ...] = ("LANDING", "MINUTES_20", "HOUR_1", "DAY_1") +_REASONS = { + "NOT_RECORDED": "No deploy of the commit was recorded.", + "REGRESSED": "A deploy of the commit regressed.", + "FAILED": "A deploy of the commit failed.", +} + + +@dataclass(frozen=True) +class DeployVerdict: + """Where one deploy stands against the checks the caller waits for.""" + + environment_id: UUID + status: DeployVerdictStatus + state: str + reason_codes: tuple[str, ...] = field(default=(), repr=False) + deploy_url: str | None = field(default=None, repr=False) + deploy: CommitDeploy | None = field(default=None, repr=False) + + +@dataclass(frozen=True) +class DeployVerificationOutcome: + status: DeployOutcomeStatus + commit_sha: str = field(repr=False) + deploys: tuple[DeployVerdict, ...] = field(default=(), repr=False) + verifications: CommitDeployVerifications | None = field(default=None, repr=False) + reason: str | None = None + + +def checkpoint_index(through: str) -> int: + if through not in CHECKPOINTS: + raise ValueError("through must be one of LANDING, MINUTES_20, HOUR_1 or DAY_1.") + return CHECKPOINTS.index(through) + + +def deploy_commit(value: str) -> None: + # The route names one exact commit: a full lowercase SHA-1, nothing else. + if ( + not isinstance(value, str) + or len(value) != 40 + or any(character not in "0123456789abcdef" for character in value) + ): + raise ValueError("The deploy commit must be a full 40-character lowercase hexadecimal SHA.") + + +def _invalid() -> ProoflineError: + return ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "The deploy verifications have invalid metadata.", + ) + + +def _text(value: object) -> str | None: + return value if isinstance(value, str) and value else None + + +def _validate(verifications: CommitDeployVerifications) -> None: + if type(verifications.recorded) is not bool or not isinstance(verifications.deploys, list): + raise _invalid() + if not verifications.recorded and verifications.deploys: + raise _invalid() + for deploy in verifications.deploys: + if ( + not isinstance(deploy.environment_id, UUID) + 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) + ): + raise _invalid() + names = [checkpoint.checkpoint for checkpoint in deploy.checkpoints] + if names and names != [*CHECKPOINTS[: len(names)]]: + raise _invalid() + for checkpoint in deploy.checkpoints: + if not isinstance(checkpoint.due_at, datetime) or not isinstance( + checkpoint.gaps, (list, Unset) + ): + raise _invalid() + + +def _gaps(value: object) -> tuple[str, ...]: + return tuple(gap for gap in value if isinstance(gap, str)) if isinstance(value, list) else () + + +def verdict(deploy: CommitDeploy, through: int) -> DeployVerdict: + """Settle one deploy against every check up to and including ``through``. + + A recorded regression settles a deploy whichever check recorded it. A check + replaced by a later deploy counts only after a healthy landing check, as + ``VERIFIED_UNTIL_SUPERSEDED`` reads it. + """ + + def settled(status: DeployVerdictStatus, *reasons: str) -> DeployVerdict: + return DeployVerdict( + deploy.environment_id, + status, + deploy.state, + tuple(dict.fromkeys(reasons)), + _text(deploy.deploy_url), + deploy, + ) + + ended = deploy.verification_ended is True + results = [checkpoint.result for checkpoint in deploy.checkpoints] + if deploy.regressed or "REGRESSED" in results: + return settled("REGRESSED", "CHECK_REGRESSED") + if deploy.state == "FAILED": + return settled("FAILED", "DEPLOYMENT_FAILED") + if deploy.state == "UNVERIFIED": + return settled("INCOMPLETE", "DEPLOY_UNVERIFIED") + window = deploy.checkpoints[: through + 1] + reasons: list[str] = [] + healthy_landing = False + for index in range(through + 1): + if index >= len(window): + if ended: + return settled("INCOMPLETE", *reasons, "CHECK_NEVER_RECORDED") + return settled("PENDING", *reasons, "CHECK_NOT_RECORDED") + checkpoint = window[index] + gaps = _gaps(checkpoint.gaps) + if checkpoint.result is None or isinstance(checkpoint.result, Unset): + if ended: + return settled("INCOMPLETE", *reasons, *gaps, "CHECK_NEVER_RECORDED") + return settled("PENDING", *reasons, *gaps, "CHECK_NOT_RECORDED") + if checkpoint.result == "SUPERSEDED": + if not healthy_landing: + reasons.append("SUPERSEDED_BEFORE_LANDING_CHECK") + break + if checkpoint.result == "HEALTHY" and not gaps: + healthy_landing = healthy_landing or index == 0 + continue + if checkpoint.result == "HEALTHY": + reasons.extend(gaps) + elif checkpoint.result == "INCOMPLETE": + reasons.extend((*gaps, "CHECK_INCOMPLETE")) + else: + # A result this SDK does not know proves nothing. + reasons.extend((*gaps, "UNKNOWN_CHECK_RESULT")) + if deploy.rolled_back is True: + # Healthy checks of a deploy its service no longer serves prove nothing now. + reasons.append("ROLLED_BACK") + if reasons: + return settled("INCOMPLETE", *reasons) + return settled("HEALTHY") + + +def next_due( + verifications: CommitDeployVerifications, + through: int, + *, + environment_id: UUID | None = None, +) -> datetime | None: + """The earliest due time of a check the wait still needs and that is not recorded.""" + + due: list[datetime] = [] + for deploy in verifications.deploys: + if environment_id is not None and deploy.environment_id != environment_id: + continue + for checkpoint in deploy.checkpoints[: through + 1]: + if checkpoint.result is None or isinstance(checkpoint.result, Unset): + due.append(checkpoint.due_at) + break + return min(due, default=None) + + +def outcome( + verifications: CommitDeployVerifications | None, + commit_sha: str, + through: int, + *, + environment_id: UUID | None = None, + forced: Literal["TIMED_OUT"] | None = None, +) -> DeployVerificationOutcome | None: + if verifications is None: + return DeployVerificationOutcome( + forced or "INCOMPLETE", + commit_sha, + reason="No deploy verification result is available.", + ) + _validate(verifications) + deploys = tuple( + verdict(deploy, through) + for deploy in verifications.deploys + if environment_id is None or deploy.environment_id == environment_id + ) + + def result(status: DeployOutcomeStatus, reason: str | None) -> DeployVerificationOutcome: + return DeployVerificationOutcome(status, commit_sha, deploys, verifications, reason) + + statuses = {deploy.status for deploy in deploys} + if "REGRESSED" in statuses: + # A regression is final evidence; nothing a later read records undoes it. + return result("REGRESSED", _REASONS["REGRESSED"]) + if forced is not None: + return result(forced, None if deploys else _REASONS["NOT_RECORDED"]) + if not deploys or "PENDING" in statuses: + # A deploy recorded later, or a check still due, can still settle the wait. + return None + if "FAILED" in statuses: + return result("FAILED", _REASONS["FAILED"]) + if "INCOMPLETE" in statuses: + return result("INCOMPLETE", None) + return result("HEALTHY", None) diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..8bbdb769 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_review", + "wait_for_deploy_verification", + } exposed = { name for name in dir(client) diff --git a/tests/test_deploys.py b/tests/test_deploys.py new file mode 100644 index 00000000..c698c20d --- /dev/null +++ b/tests/test_deploys.py @@ -0,0 +1,387 @@ +"""Waiting for a commit's deploy verifications against a real loopback peer.""" + +from __future__ import annotations + +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from typing import Any +from uuid import UUID + +import pytest + +from proofline import DeployVerdict, DeployVerificationOutcome, ProoflineError +from proofline import client as client_module + +from .fixtures import ORG, REPOSITORY +from .http_server import Reply, Request, Server +from .test_http import MODES, Clock, call, session + +SHA = "c" * 40 +PRODUCTION = UUID("00000000-0000-4000-8000-000000000010") +STAGING = UUID("00000000-0000-4000-8000-000000000011") +PATH = f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}/commits/{SHA}/deploy-verifications" +CHECKPOINTS = ("LANDING", "MINUTES_20", "HOUR_1", "DAY_1") +DUE = ( + "2026-11-01T00:05:00Z", + "2026-11-01T00:25:00Z", + "2026-11-01T01:05:00Z", + "2026-11-02T00:05:00Z", +) + + +def checks(*results: str | None, gaps: dict[int, list[str]] | None = None) -> list[dict[str, Any]]: + """The four checks in order; a result given as None is not recorded yet.""" + + padded = (*results, *(None,) * (4 - len(results))) + recorded = [] + for index, result in enumerate(padded): + check: dict[str, Any] = {"checkpoint": CHECKPOINTS[index], "due_at": DUE[index]} + if result is not None: + check["result"] = result + check["gaps"] = (gaps or {}).get(index, []) + recorded.append(check) + return recorded + + +def deploy( + state: str = "NOT_YET_DUE", + checkpoints: list[dict[str, Any]] | None = None, + *, + environment: UUID = PRODUCTION, + **extra: Any, +) -> dict[str, Any]: + return { + "environment_id": str(environment), + "state": state, + "regressed": False, + "gaps": [], + "checkpoints": checks("HEALTHY") if checkpoints is None else checkpoints, + "deploy_url": f"https://proofline.sh/deploys/{environment}", + **extra, + } + + +def verifications(*deploys: dict[str, Any]) -> dict[str, Any]: + return {"recorded": bool(deploys), "deploys": list(deploys)} + + +def replies(*bodies: dict[str, Any]) -> Callable[[Request, int], Reply]: + # The last body answers every read after the scripted ones. + return lambda request, index: Reply(body=bodies[min(index, len(bodies) - 1)]) + + +def verdicts(result: DeployVerificationOutcome) -> list[tuple[UUID, str, tuple[str, ...]]]: + return [(item.environment_id, item.status, item.reason_codes) for item in result.deploys] + + +@MODES +async def test_a_healthy_landing_check_settles_on_the_first_read( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(replies(verifications(deploy()))) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert (result.status, result.reason, result.commit_sha) == ("HEALTHY", None, SHA) + assert verdicts(result) == [(PRODUCTION, "HEALTHY", ())] + verdict = result.deploys[0] + assert isinstance(verdict, DeployVerdict) + assert verdict.state == "NOT_YET_DUE" + assert verdict.deploy_url == f"https://proofline.sh/deploys/{PRODUCTION}" + assert result.verifications.recorded is True + assert SHA not in repr(result) + assert [(request.method, request.path) for request in server.requests] == [("GET", PATH)] + assert clock.delays == [] + + +@MODES +async def test_the_wait_follows_checks_until_the_named_one_records( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + bodies = ( + verifications(deploy(checkpoints=[])), + verifications(deploy()), + verifications(deploy(checkpoints=checks("HEALTHY", "HEALTHY"))), + ) + with Server(replies(*bodies)) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_deploy_verification", + ORG, + REPOSITORY, + SHA, + through="MINUTES_20", + ) + assert result.status == "HEALTHY" + assert len(server.requests) == 3 + assert clock.delays == [5, 10] + + +@MODES +async def test_a_deploy_recorded_after_the_first_read_still_settles_the_wait( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(replies(verifications(), verifications(deploy()))) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert result.status == "HEALTHY" + assert clock.delays == [5] + + +@MODES +async def test_a_regression_ends_the_wait_whatever_check_recorded_it( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + # Staging is still due, and the regression is past the check the caller named. + body = verifications( + deploy("UNRECORDED", checks(None), environment=STAGING), + deploy("INCOMPLETE", checks("HEALTHY", "HEALTHY", "REGRESSED"), regressed=True), + ) + with Server(replies(body)) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert (result.status, result.reason) == ("REGRESSED", "A deploy of the commit regressed.") + assert verdicts(result) == [ + (STAGING, "PENDING", ("CHECK_NOT_RECORDED",)), + (PRODUCTION, "REGRESSED", ("CHECK_REGRESSED",)), + ] + assert len(server.requests) == 1 + assert clock.delays == [] + + +@MODES +async def test_a_failed_deploy_fails_once_every_deploy_settles( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + failed = deploy("FAILED", [], environment=STAGING) + bodies = ( + verifications(failed, deploy(checkpoints=[])), + verifications(failed, deploy()), + ) + with Server(replies(*bodies)) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert (result.status, result.reason) == ("FAILED", "A deploy of the commit failed.") + assert verdicts(result) == [ + (STAGING, "FAILED", ("DEPLOYMENT_FAILED",)), + (PRODUCTION, "HEALTHY", ()), + ] + assert clock.delays == [5] + + +@pytest.mark.parametrize( + ("record", "reasons"), + [ + ( + deploy("INCOMPLETE", checks("HEALTHY", gaps={0: ["SIGNAL_NO_DATA"]})), + ("SIGNAL_NO_DATA",), + ), + ( + deploy("INCOMPLETE", checks("INCOMPLETE", gaps={0: ["RUNTIME_INVENTORY_STALE"]})), + ("RUNTIME_INVENTORY_STALE", "CHECK_INCOMPLETE"), + ), + ( + deploy("UNRECORDED", checks(None), verification_ended=True), + ("CHECK_NEVER_RECORDED",), + ), + (deploy("UNVERIFIED", []), ("DEPLOY_UNVERIFIED",)), + (deploy("SUPERSEDED", checks("SUPERSEDED")), ("SUPERSEDED_BEFORE_LANDING_CHECK",)), + (deploy(checkpoints=checks("HEALTHY"), rolled_back=True), ("ROLLED_BACK",)), + (deploy("LATER_STATE", checks("LATER_RESULT")), ("UNKNOWN_CHECK_RESULT",)), + ], + ids=["gap", "incomplete", "never-recorded", "unverified", "superseded", "rolled-back", "later"], +) +@MODES +async def test_an_unproven_deploy_is_incomplete_with_its_reasons( + mode: str, monkeypatch: pytest.MonkeyPatch, record: dict[str, Any], reasons: tuple[str, ...] +) -> None: + Clock(monkeypatch) + with Server(replies(verifications(record))) as server: + async with session(mode, server.url) as client: + result = await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert (result.status, result.reason) == ("INCOMPLETE", None) + assert verdicts(result) == [(PRODUCTION, "INCOMPLETE", reasons)] + assert len(server.requests) == 1 + + +@MODES +async def test_a_check_replaced_after_a_healthy_landing_counts( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + replaced = deploy( + "VERIFIED_UNTIL_SUPERSEDED", checks("HEALTHY", "HEALTHY", "SUPERSEDED", "SUPERSEDED") + ) + with Server(replies(verifications(replaced))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA, through="DAY_1" + ) + assert result.status == "HEALTHY" + assert verdicts(result) == [(PRODUCTION, "HEALTHY", ())] + + +@MODES +async def test_environment_id_holds_the_wait_to_one_environment( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + staging_only = verifications(deploy(environment=STAGING)) + both = verifications(deploy(environment=STAGING), deploy("FAILED", [], environment=PRODUCTION)) + with Server(replies(staging_only, both)) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_deploy_verification", + ORG, + REPOSITORY, + SHA, + environment_id=PRODUCTION, + ) + # Staging's healthy deploy never stands in for the production deploy. + assert result.status == "FAILED" + assert verdicts(result) == [(PRODUCTION, "FAILED", ("DEPLOYMENT_FAILED",))] + assert clock.delays == [5] + + +@MODES +async def test_a_commit_never_recorded_times_out_and_never_reads_healthy( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(replies(verifications())) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA, timeout=60 + ) + assert (result.status, result.deploys) == ("TIMED_OUT", ()) + assert result.reason == "No deploy of the commit was recorded." + assert result.verifications.recorded is False + assert sum(clock.delays) == 60 + assert clock.delays == [5, 10, 20, 25] + + +@MODES +async def test_a_check_still_due_at_the_deadline_times_out_with_its_verdict( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + with Server(replies(verifications(deploy(checkpoints=checks(None))))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA, timeout=10 + ) + assert (result.status, result.reason) == ("TIMED_OUT", None) + assert verdicts(result) == [(PRODUCTION, "PENDING", ("CHECK_NOT_RECORDED",))] + + +@pytest.mark.parametrize( + ("arguments", "message"), + [ + ({"commit_sha": SHA.upper()}, "lowercase"), + ({"commit_sha": "c" * 12}, "40-character"), + ({"commit_sha": "main"}, "40-character"), + ({"commit_sha": "c" * 64}, "40-character"), + ({"through": "WEEK_1"}, "through"), + ({"timeout": -1}, "timeout"), + ({"timeout": float("nan")}, "timeout"), + ], +) +@MODES +async def test_invalid_arguments_are_refused_before_a_request( + mode: str, arguments: dict[str, Any], message: str +) -> None: + with Server(replies(verifications(deploy()))) as server: + async with session(mode, server.url) as client: + keywords = dict(arguments) + commit = keywords.pop("commit_sha", SHA) + with pytest.raises(ValueError, match=message): + await call( + client, "wait_for_deploy_verification", ORG, REPOSITORY, commit, **keywords + ) + assert server.requests == [] + + +@MODES +async def test_a_problem_ends_the_wait_as_an_error( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + problem = {"title": "not found", "status": 404, "detail": "No such repository."} + with Server( + lambda request, index: Reply(404, problem, {"Content-Type": "application/problem+json"}) + ) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert (raised.value.status, raised.value.title) == (404, "not found") + assert len(server.requests) == 1 + + +@MODES +async def test_an_inconsistent_ledger_is_an_invalid_response( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + body = {"recorded": False, "deploys": [deploy()]} + with Server(replies(body)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA) + assert raised.value.type == "urn:proofline:sdk:invalid-response" + + +@MODES +async def test_the_wait_sleeps_until_the_next_check_is_due( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + landed = datetime(2026, 11, 1, 0, 6, tzinfo=UTC) + # The wall clock moves with the monotonic one the Clock advances. + monkeypatch.setattr( + client_module, "utc_now", lambda: landed + timedelta(seconds=clock.now - 100.0) + ) + bodies = ( + *(verifications(deploy()),) * 4, + verifications(deploy(checkpoints=checks("HEALTHY", "HEALTHY"))), + ) + with Server(replies(*bodies)) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_deploy_verification", + ORG, + REPOSITORY, + SHA, + through="MINUTES_20", + ) + assert result.status == "HEALTHY" + # MINUTES_20 is due 19 minutes after the first read: reads at the five-minute + # ceiling, then the rest of the way, instead of one read a minute. + assert clock.delays == [300, 300, 300, 240] + assert len(server.requests) == 5 + + +@MODES +async def test_an_overdue_check_falls_back_to_backoff( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + monkeypatch.setattr(client_module, "utc_now", lambda: datetime(2026, 11, 1, 0, 30, tzinfo=UTC)) + bodies = ( + verifications(deploy()), + verifications(deploy()), + verifications(deploy(checkpoints=checks("HEALTHY", "HEALTHY"))), + ) + with Server(replies(*bodies)) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_deploy_verification", ORG, REPOSITORY, SHA, through="MINUTES_20" + ) + assert result.status == "HEALTHY" + assert clock.delays == [5, 10]