diff --git a/README.md b/README.md index eaad94e2..6bacc03d 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,28 @@ 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 on commit deploy verifications + +`wait_for_commit_deploy_verifications` polls `get_commit_deploy_verifications` for one exact 40-character lowercase commit SHA, optionally filtered by `environment_id`, `github_environment`, or `deployment_task`, and evaluates recorded evidence via `evaluate_deploy_verifications`. + +```python +from proofline import DeployCheckpoint, ProoflineClient + +with ProoflineClient() as client: + deploy = client.wait_for_commit_deploy_verifications( + organization_id, + repository_id, + commit_sha, + github_environment="production", + until_checkpoint=DeployCheckpoint.LANDING, + timeout=180, + ) + if deploy.status not in ("VERIFIED", "CHECKPOINT_VERIFIED"): + print(deploy.status, deploy.gaps, deploy.reason) +``` + +Pass `until_checkpoint` (`LANDING`, `MINUTES_20`, `HOUR_1`, or `DAY_1`) to settle once every checkpoint up to that window records a result, or omit it to wait for full deploy verification. Regressions (`REGRESSED`), rollbacks (`ROLLED_BACK`), and deployment failures (`FAILED`) short-circuit immediately when `fail_fast=True`, and recorded gaps never resolve as `VERIFIED` or `CHECKPOINT_VERIFIED`. + ## 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..28476020 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -6,6 +6,9 @@ from ._generated.models import ( AgentSession, AgentVendor, + CommitDeploy, + CommitDeployRollback, + CommitDeployVerifications, CommitReviewRequest, CommitReviewResponse, CoverageUploadRequest, @@ -13,6 +16,8 @@ CustomerAssessmentDetail, CustomerFinding, CustomerReviewDetail, + DeployCheckpoint, + DeployCoverageCheckpoint, FileReviewRequest, FileReviewResponse, PatchReviewRequest, @@ -34,6 +39,13 @@ from ._transport import VERSION as __version__ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters +from .deploy_outcomes import ( + DeployCheckpointGap, + DeployEvaluation, + DeployOutcomeStatus, + DeployVerificationOutcome, + evaluate_deploy_verifications, +) from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -44,6 +56,9 @@ "AssessmentGap", "AsyncProoflineClient", "CheckGap", + "CommitDeploy", + "CommitDeployRollback", + "CommitDeployVerifications", "CommitReviewRequest", "CommitReviewResponse", "CoverageUploadRequest", @@ -51,6 +66,12 @@ "CustomerAssessmentDetail", "CustomerFinding", "CustomerReviewDetail", + "DeployCheckpoint", + "DeployCheckpointGap", + "DeployCoverageCheckpoint", + "DeployEvaluation", + "DeployOutcomeStatus", + "DeployVerificationOutcome", "ExportDataset", "ExportFormat", "ExportPage", @@ -79,5 +100,6 @@ "StopResponse", "UploadedReport", "__version__", + "evaluate_deploy_verifications", "models", ] diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..43bab164 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -44,6 +44,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 +52,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 +74,11 @@ from ._generated.types import UNSET, Response, Unset from ._mcp import AsyncMcpClient, McpClient from ._transport import ProoflineError +from .deploy_outcomes import ( + DeployVerificationOutcome, + evaluate_deploy_verifications, + normalize_checkpoint, +) from .exports import ExportDataset, ExportFormat, ExportPage, decode_export from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient @@ -153,6 +160,9 @@ def _page_limits(page_size: int, max_pages: int, max_items: int) -> None: ) +_LOWER_HEX = frozenset("0123456789abcdef") + + def _head_commit(value: str | None) -> None: # Only a full SHA names one exact commit; a branch or an abbreviation does not. if value is not None and ( @@ -163,6 +173,28 @@ def _head_commit(value: str | None) -> None: raise ValueError("The head commit must be a full 40 or 64 character hexadecimal SHA.") +def _commit_sha40(value: str) -> None: + if ( + not isinstance(value, str) + or len(value) != 40 + or any(character not in _LOWER_HEX for character in value) + ): + raise ValueError("The commit SHA must be a full 40-character lowercase hexadecimal SHA.") + + +def _deploy_wait_inputs( + commit_sha: str, + timeout: float, + until_checkpoint: DeployCheckpoint | str | None, +) -> str | None: + if isinstance(timeout, bool) or not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The deploy verification timeout must be a finite nonnegative number of seconds." + ) + _commit_sha40(commit_sha) + return normalize_checkpoint(until_checkpoint) + + def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None: if not isinstance(page.truncated, bool): raise _transport.invalid_response() @@ -583,6 +615,63 @@ def wait_for_review( finally: _transport.DEADLINE.reset(deadline) + def wait_for_commit_deploy_verifications( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + timeout: float = 300, + environment_id: UUID | None = None, + github_environment: str | None = None, + deployment_task: str | None = None, + until_checkpoint: DeployCheckpoint | str | None = None, + fail_fast: bool = True, + ) -> DeployVerificationOutcome: + """Wait for a commit's deploy verifications to settle or reach a checkpoint.""" + target = _deploy_wait_inputs(commit_sha, timeout, until_checkpoint) + 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 = evaluate_deploy_verifications( + last, + commit_sha, + environment_id=environment_id, + github_environment=github_environment, + deployment_task=deployment_task, + until_checkpoint=target, + fail_fast=fail_fast, + ) + if result is not None: + return result + sleep(min(interval, _transport.remaining() or 0)) + interval = min(60, interval * 2) + timed_out = evaluate_deploy_verifications( + last, + commit_sha, + "TIMED_OUT", + environment_id=environment_id, + github_environment=github_environment, + deployment_task=deployment_task, + until_checkpoint=target, + fail_fast=fail_fast, + ) + return timed_out or DeployVerificationOutcome("TIMED_OUT", commit_sha, False) + finally: + _transport.DEADLINE.reset(deadline) + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -968,3 +1057,60 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) + + async def wait_for_commit_deploy_verifications( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + timeout: float = 300, + environment_id: UUID | None = None, + github_environment: str | None = None, + deployment_task: str | None = None, + until_checkpoint: DeployCheckpoint | str | None = None, + fail_fast: bool = True, + ) -> DeployVerificationOutcome: + """Wait for a commit's deploy verifications to settle or reach a checkpoint.""" + target = _deploy_wait_inputs(commit_sha, timeout, until_checkpoint) + 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 = evaluate_deploy_verifications( + last, + commit_sha, + environment_id=environment_id, + github_environment=github_environment, + deployment_task=deployment_task, + until_checkpoint=target, + fail_fast=fail_fast, + ) + if result is not None: + return result + await async_sleep(min(interval, _transport.remaining() or 0)) + interval = min(60, interval * 2) + timed_out = evaluate_deploy_verifications( + last, + commit_sha, + "TIMED_OUT", + environment_id=environment_id, + github_environment=github_environment, + deployment_task=deployment_task, + until_checkpoint=target, + fail_fast=fail_fast, + ) + return timed_out or DeployVerificationOutcome("TIMED_OUT", commit_sha, False) + finally: + _transport.DEADLINE.reset(deadline) diff --git a/proofline/deploy_outcomes.py b/proofline/deploy_outcomes.py new file mode 100644 index 00000000..d7daa58c --- /dev/null +++ b/proofline/deploy_outcomes.py @@ -0,0 +1,421 @@ +"""Deploy verification evaluation follows recorded deploy states and checkpoints.""" + +from __future__ import annotations + +import datetime +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.models.deploy_coverage_checkpoint import DeployCoverageCheckpoint +from ._generated.types import Unset +from ._transport import ProoflineError + +DeployOutcomeStatus = Literal[ + "VERIFIED", + "VERIFIED_UNTIL_SUPERSEDED", + "CHECKPOINT_VERIFIED", + "REGRESSED", + "ROLLED_BACK", + "FAILED", + "SUPERSEDED", + "INCOMPLETE", + "UNRECORDED", + "UNVERIFIED", + "INACTIVE", + "TIMED_OUT", +] + +CHECKPOINT_ORDER: tuple[str, ...] = ( + DeployCheckpoint.LANDING.value, + DeployCheckpoint.MINUTES_20.value, + DeployCheckpoint.HOUR_1.value, + DeployCheckpoint.DAY_1.value, +) + +_ADVERSE_STATUSES = frozenset(("REGRESSED", "ROLLED_BACK", "FAILED")) + +# Highest severity comes first so multi-environment rollups never hide regressions or gaps. +_STATUS_PRIORITY: dict[str, int] = { + "REGRESSED": 0, + "ROLLED_BACK": 1, + "FAILED": 2, + "INCOMPLETE": 3, + "UNRECORDED": 4, + "TIMED_OUT": 5, + "UNVERIFIED": 6, + "INACTIVE": 7, + "SUPERSEDED": 8, + "CHECKPOINT_VERIFIED": 9, + "VERIFIED_UNTIL_SUPERSEDED": 10, + "VERIFIED": 11, +} + + +@dataclass(frozen=True) +class DeployCheckpointGap: + checkpoint: str + due_at: datetime.datetime + result: str | None = None + gaps: tuple[str, ...] = field(default=(), repr=False) + + +@dataclass(frozen=True) +class DeployEvaluation: + environment_id: UUID + status: DeployOutcomeStatus + state: str + regressed: bool + rolled_back: bool + verification_ended: bool + gaps: tuple[str, ...] = field(default=(), repr=False) + checkpoints: tuple[DeployCheckpointGap, ...] = field(default=(), repr=False) + github_environment: str | None = None + deployment_task: str | None = None + 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 + recorded: bool + deploys: tuple[DeployEvaluation, ...] = field(default=(), repr=False) + gaps: tuple[str, ...] = field(default=(), repr=False) + reason: str | None = None + verifications: CommitDeployVerifications | None = field(default=None, repr=False) + + +def normalize_checkpoint(checkpoint: DeployCheckpoint | str | None) -> str | None: + if checkpoint is None: + return None + value = checkpoint.value if isinstance(checkpoint, DeployCheckpoint) else checkpoint + if not isinstance(value, str) or value not in CHECKPOINT_ORDER: + raise ValueError("Checkpoint must be one of LANDING, MINUTES_20, HOUR_1, or DAY_1.") + return value + + +def _text(value: object) -> str | None: + return value if isinstance(value, str) and value else None + + +def _optional_text(value: object) -> bool: + return value is None or isinstance(value, (str, Unset)) + + +def _flag(value: object) -> bool: + return value is True + + +def _invalid() -> ProoflineError: + return ProoflineError( + 0, + "urn:proofline:sdk:invalid-response", + "The deploy verification response has invalid identity or checkpoint metadata.", + ) + + +def _validate_checkpoint(item: DeployCoverageCheckpoint) -> None: + if ( + not isinstance(item.checkpoint, (DeployCheckpoint, str)) + or not isinstance(item.due_at, datetime.datetime) + or not _optional_text(item.result) + ): + raise _invalid() + if not isinstance(item.gaps, Unset) and ( + not isinstance(item.gaps, list) or not all(isinstance(gap, str) for gap in item.gaps) + ): + raise _invalid() + + +def _validate_verifications(verifications: CommitDeployVerifications) -> None: + if type(verifications.recorded) is not bool or not isinstance(verifications.deploys, list): + 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.gaps, list) + or not all(isinstance(gap, str) for gap in deploy.gaps) + or not isinstance(deploy.checkpoints, list) + or (not isinstance(deploy.rolled_back, Unset) and type(deploy.rolled_back) is not bool) + or ( + not isinstance(deploy.verification_ended, Unset) + and type(deploy.verification_ended) is not bool + ) + or not _optional_text(deploy.github_environment) + or not _optional_text(deploy.deployment_task) + or not _optional_text(deploy.deploy_url) + ): + raise _invalid() + for checkpoint in deploy.checkpoints: + _validate_checkpoint(checkpoint) + + +def _matches_filters( + deploy: CommitDeploy, + *, + environment_id: UUID | None, + github_environment: str | None, + deployment_task: str | None, +) -> bool: + if environment_id is not None and deploy.environment_id != environment_id: + return False + if github_environment is not None and deploy.github_environment != github_environment: + return False + if deployment_task is not None and deploy.deployment_task != deployment_task: + return False + return True + + +def _dedupe(items: list[str]) -> tuple[str, ...]: + return tuple(dict.fromkeys(items)) + + +def _checkpoint_records( + deploy: CommitDeploy, +) -> list[tuple[str, datetime.datetime, str | None, tuple[str, ...]]]: + records: list[tuple[str, datetime.datetime, str | None, tuple[str, ...]]] = [] + for item in deploy.checkpoints: + name = ( + item.checkpoint.value + if isinstance(item.checkpoint, DeployCheckpoint) + else str(item.checkpoint) + ) + result = _text(item.result) + gaps = tuple(item.gaps) if isinstance(item.gaps, list) else () + records.append((name, item.due_at, result, gaps)) + return records + + +def _evaluate_single_deploy( + deploy: CommitDeploy, + *, + until_checkpoint: str | None, + forced: DeployOutcomeStatus | None, +) -> DeployEvaluation | None: + rolled_back = _flag(deploy.rolled_back) + verification_ended = _flag(deploy.verification_ended) + records = _checkpoint_records(deploy) + regressed = deploy.regressed or any(result == "REGRESSED" for _, _, result, _ in records) + + all_gaps: list[str] = list(deploy.gaps) + checkpoint_gaps: list[DeployCheckpointGap] = [] + for name, due_at, result, cp_gaps in records: + all_gaps.extend(cp_gaps) + if cp_gaps or result in ("REGRESSED", "INCOMPLETE") or result is None: + checkpoint_gaps.append(DeployCheckpointGap(name, due_at, result, cp_gaps)) + deduped_gaps = _dedupe(all_gaps) + + status: DeployOutcomeStatus | None = None + if regressed: + status = "REGRESSED" + elif rolled_back: + status = "ROLLED_BACK" + elif deploy.state == "FAILED": + status = "FAILED" + elif deploy.state == "SUPERSEDED": + status = "SUPERSEDED" + elif deploy.state == "INCOMPLETE": + status = "INCOMPLETE" + elif deploy.state == "INACTIVE": + status = "INACTIVE" + elif deploy.state == "UNVERIFIED": + status = "UNVERIFIED" + elif deploy.state == "VERIFIED": + status = "INCOMPLETE" if deduped_gaps else "VERIFIED" + elif deploy.state == "VERIFIED_UNTIL_SUPERSEDED": + status = "INCOMPLETE" if deduped_gaps else "VERIFIED_UNTIL_SUPERSEDED" + elif deploy.state == "UNRECORDED": + if verification_ended: + status = "UNRECORDED" + elif forced is not None: + status = forced + elif deploy.state == "NOT_YET_DUE": + if until_checkpoint is not None: + target_names = CHECKPOINT_ORDER[: CHECKPOINT_ORDER.index(until_checkpoint) + 1] + by_name = {name: (result, cp_gaps) for name, _, result, cp_gaps in records} + if all(name in by_name and by_name[name][0] is not None for name in target_names): + target_results = [by_name[name][0] for name in target_names] + target_gaps = [ + gap + for name in target_names + for gap in by_name[name][1] + if by_name[name][0] != "SUPERSEDED" + ] + if "INCOMPLETE" in target_results or target_gaps: + status = "INCOMPLETE" + elif "SUPERSEDED" in target_results: + status = "SUPERSEDED" + elif all(result == "HEALTHY" for result in target_results): + status = "CHECKPOINT_VERIFIED" + else: + status = "INCOMPLETE" + if status is None and forced is not None: + status = forced + else: + # Unknown future states never silently claim verification. + status = "INCOMPLETE" + + if status is None: + return None + + return DeployEvaluation( + environment_id=deploy.environment_id, + status=status, + state=deploy.state, + regressed=regressed, + rolled_back=rolled_back, + verification_ended=verification_ended, + gaps=deduped_gaps, + checkpoints=tuple(checkpoint_gaps), + github_environment=_text(deploy.github_environment), + deployment_task=_text(deploy.deployment_task), + deploy_url=_text(deploy.deploy_url), + deploy=deploy, + ) + + +def _worst_status(statuses: list[DeployOutcomeStatus]) -> DeployOutcomeStatus: + return min(statuses, key=lambda item: _STATUS_PRIORITY.get(item, 3)) + + +def _reason_for( + status: DeployOutcomeStatus, + recorded: bool, + matched_count: int, + *, + until_checkpoint: str | None, +) -> str | None: + if not recorded: + return "No deploy of this commit has been recorded." + if matched_count == 0: + return "No recorded deploy matched the requested environment or task filters." + if status == "REGRESSED": + return "At least one deploy verification check recorded REGRESSED." + if status == "ROLLED_BACK": + return "A deploy verification check observed the service serving an earlier commit." + if status == "FAILED": + return "A deployment failed before verification completed." + if status == "TIMED_OUT": + if until_checkpoint is not None: + return f"Timed out waiting for checkpoint {until_checkpoint} to record a result." + return "Timed out waiting for deploy verifications to settle." + if status == "CHECKPOINT_VERIFIED" and until_checkpoint is not None: + return f"All checks through {until_checkpoint} recorded HEALTHY with no gaps." + return None + + +def evaluate_deploy_verifications( + verifications: CommitDeployVerifications | None, + commit_sha: str, + forced: DeployOutcomeStatus | None = None, + *, + environment_id: UUID | None = None, + github_environment: str | None = None, + deployment_task: str | None = None, + until_checkpoint: DeployCheckpoint | str | None = None, + fail_fast: bool = True, +) -> DeployVerificationOutcome | None: + """Evaluate recorded deploy verifications without masking regressions or gaps. + + Returns None while matching deploys are still pending unless forced is set + (for example TIMED_OUT when a polling deadline expires) or fail_fast is true + and an adverse state (REGRESSED, ROLLED_BACK, FAILED) is already recorded. + """ + target_checkpoint = normalize_checkpoint(until_checkpoint) + if verifications is None: + if forced is None: + return None + return DeployVerificationOutcome( + status=forced, + commit_sha=commit_sha, + recorded=False, + reason="No deploy verification response was recorded before the deadline expired.", + ) + + _validate_verifications(verifications) + matching = [ + deploy + for deploy in verifications.deploys + if _matches_filters( + deploy, + environment_id=environment_id, + github_environment=github_environment, + deployment_task=deployment_task, + ) + ] + + if not verifications.recorded or not matching: + if forced is None: + return None + return DeployVerificationOutcome( + status=forced, + commit_sha=commit_sha, + recorded=verifications.recorded, + reason=_reason_for( + forced, + verifications.recorded, + len(matching), + until_checkpoint=target_checkpoint, + ), + verifications=verifications, + ) + + evaluated: list[DeployEvaluation] = [] + pending = False + for deploy in matching: + item = _evaluate_single_deploy( + deploy, + until_checkpoint=target_checkpoint, + forced=forced, + ) + if item is None: + pending = True + else: + evaluated.append(item) + + if pending: + adverse = [item for item in evaluated if item.status in _ADVERSE_STATUSES] + if not (fail_fast and adverse): + return None + # Fill remaining pending deploys with TIMED_OUT snapshot only if forced; otherwise keep only + # the already-evaluated deploys so callers never misread pending deploys as settled. + status = _worst_status([item.status for item in adverse]) + gaps = _dedupe([gap for item in evaluated for gap in item.gaps]) + return DeployVerificationOutcome( + status=status, + commit_sha=commit_sha, + recorded=verifications.recorded, + deploys=tuple(evaluated), + gaps=gaps, + reason=_reason_for( + status, + verifications.recorded, + len(matching), + until_checkpoint=target_checkpoint, + ), + verifications=verifications, + ) + + status = _worst_status([item.status for item in evaluated]) + gaps = _dedupe([gap for item in evaluated for gap in item.gaps]) + return DeployVerificationOutcome( + status=status, + commit_sha=commit_sha, + recorded=verifications.recorded, + deploys=tuple(evaluated), + gaps=gaps, + reason=_reason_for( + status, + verifications.recorded, + len(matching), + until_checkpoint=target_checkpoint, + ), + verifications=verifications, + ) diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..81d2c2ee 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_commit_deploy_verifications", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/scripts/install_smoke.py b/scripts/install_smoke.py index 3509074c..7143e7fe 100644 --- a/scripts/install_smoke.py +++ b/scripts/install_smoke.py @@ -13,12 +13,20 @@ from uuid import UUID import proofline -from proofline import AsyncProoflineClient, ProoflineClient, ReviewFilters, SecretStr +from proofline import ( + AsyncProoflineClient, + DeployCheckpoint, + ProoflineClient, + ReviewFilters, + SecretStr, +) ORG = UUID("00000000-0000-4000-8000-000000000001") REVIEW = UUID("00000000-0000-4000-8000-000000000002") ASSESSMENT = UUID("00000000-0000-4000-8000-000000000003") FINDING = UUID("00000000-0000-4000-8000-000000000004") +REPOSITORY = UUID("00000000-0000-4000-8000-000000000005") +COMMIT_SHA = "a" * 40 TOKEN = "pln_synthetic_installed_package_token" QUERY = '(status:COMPLETED OR status:FAILED) AND -author:"release bot"' @@ -76,6 +84,28 @@ def main() -> None: ], } + deploy_verifications = { + "recorded": True, + "deploys": [ + { + "environment_id": str(ASSESSMENT), + "github_environment": "production", + "deployment_task": "deploy", + "state": "NOT_YET_DUE", + "regressed": False, + "gaps": [], + "checkpoints": [ + { + "checkpoint": "LANDING", + "due_at": "2026-01-01T00:05:00Z", + "result": "HEALTHY", + "gaps": [], + } + ], + } + ], + } + class Handler(BaseHTTPRequestHandler): def log_message(self, format: str, *args: object) -> None: pass @@ -84,7 +114,10 @@ def do_GET(self) -> None: assert self.headers["Authorization"] == f"Bearer {TOKEN}" assert self.headers["User-Agent"] == f"proofline-python/{package_version}" calls.append(self.path) - body = finding if "/findings/" in self.path else review + if "/deploy-verifications" in self.path: + body: object = deploy_verifications + else: + body = finding if "/findings/" in self.path else review path = urlsplit(self.path) if path.path in ( f"/api/v1/organizations/{ORG}/reviews", @@ -119,6 +152,15 @@ async def asynchronous() -> None: result = await client.wait_for_review(ORG, REVIEW, timeout=2) assert result.status == "INCOMPLETE" assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE" + deploy = await client.wait_for_commit_deploy_verifications( + ORG, + REPOSITORY, + COMMIT_SHA, + github_environment="production", + until_checkpoint=DeployCheckpoint.LANDING, + timeout=2, + ) + assert deploy.status == "CHECKPOINT_VERIFIED" assert TOKEN not in repr(client) try: @@ -131,9 +173,18 @@ async def asynchronous() -> None: result = client.wait_for_review(ORG, REVIEW, timeout=2) assert result.status == "INCOMPLETE" assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE" + deploy = client.wait_for_commit_deploy_verifications( + ORG, + REPOSITORY, + COMMIT_SHA, + github_environment="production", + until_checkpoint=DeployCheckpoint.LANDING, + timeout=2, + ) + assert deploy.status == "CHECKPOINT_VERIFIED" assert TOKEN not in repr(client) asyncio.run(asynchronous()) - assert len(calls) == 10 + assert len(calls) == 12 finally: server.shutdown() server.server_close() diff --git a/tests/test_deploy_outcomes.py b/tests/test_deploy_outcomes.py new file mode 100644 index 00000000..b3ff7f44 --- /dev/null +++ b/tests/test_deploy_outcomes.py @@ -0,0 +1,374 @@ +from __future__ import annotations + +import asyncio +from typing import Any +from uuid import UUID + +import pytest + +from proofline import ( + CommitDeployVerifications, + DeployCheckpoint, + ProoflineError, + _sync_http, + _transport, + evaluate_deploy_verifications, +) +from proofline import client as client_module + +from .fixtures import ORG, REPOSITORY, TOKEN +from .http_server import Reply, Request, Server +from .test_http import MODES, call, session + +COMMIT_SHA = "a" * 40 +ENV_STAGING = UUID("00000000-0000-4000-8000-000000000011") +ENV_PROD = UUID("00000000-0000-4000-8000-000000000012") + + +class DeployClock: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.now = 100.0 + self.delays: list[float] = [] + monkeypatch.setattr(client_module, "monotonic", lambda: self.now) + monkeypatch.setattr(_transport, "monotonic", lambda: self.now) + monkeypatch.setattr(_sync_http, "monotonic", lambda: self.now) + monkeypatch.setattr(client_module, "sleep", self.sleep) + monkeypatch.setattr(_transport, "sleep", self.sleep) + monkeypatch.setattr(client_module, "async_sleep", self.async_sleep) + monkeypatch.setattr(_transport, "async_sleep", self.async_sleep) + + def sleep(self, delay: float) -> None: + self.delays.append(delay) + self.now += delay + + async def async_sleep(self, delay: float) -> None: + self.sleep(delay) + await asyncio.sleep(0) + + +def deploy_payload( + *, + environment_id: UUID = ENV_PROD, + state: str = "VERIFIED", + regressed: bool = False, + rolled_back: bool = False, + verification_ended: bool = False, + gaps: list[str] | None = None, + checkpoints: list[dict[str, Any]] | None = None, + github_environment: str | None = "production", + deployment_task: str | None = "deploy", +) -> dict[str, Any]: + return { + "environment_id": str(environment_id), + "state": state, + "regressed": regressed, + "rolled_back": rolled_back, + "verification_ended": verification_ended, + "gaps": gaps or [], + "checkpoints": checkpoints or [], + "github_environment": github_environment, + "deployment_task": deployment_task, + "deploy_url": f"https://proofline.sh/deploys/{environment_id}", + } + + +def checkpoint_payload( + name: str, + result: str | None = "HEALTHY", + *, + gaps: list[str] | None = None, +) -> dict[str, Any]: + return { + "checkpoint": name, + "due_at": "2026-11-01T00:05:00Z", + "result": result, + "gaps": gaps or [], + } + + +def verifications_payload(*deploys: dict[str, Any], recorded: bool = True) -> dict[str, Any]: + return {"recorded": recorded, "deploys": list(deploys)} + + +def test_evaluate_deploy_verifications_never_masks_gaps_or_regressions() -> None: + verified_with_gap = CommitDeployVerifications.from_dict( + verifications_payload( + deploy_payload( + state="VERIFIED", + gaps=["SIGNAL_NO_DATA"], + checkpoints=[checkpoint_payload("LANDING", "HEALTHY", gaps=["SIGNAL_NO_DATA"])], + ) + ) + ) + outcome = evaluate_deploy_verifications(verified_with_gap, COMMIT_SHA) + assert outcome is not None + assert outcome.status == "INCOMPLETE" + assert outcome.gaps == ("SIGNAL_NO_DATA",) + + regressed = CommitDeployVerifications.from_dict( + verifications_payload( + deploy_payload( + state="VERIFIED", + regressed=True, + checkpoints=[checkpoint_payload("LANDING", "REGRESSED")], + ) + ) + ) + regressed_outcome = evaluate_deploy_verifications(regressed, COMMIT_SHA) + assert regressed_outcome is not None + assert regressed_outcome.status == "REGRESSED" + + rolled_back = CommitDeployVerifications.from_dict( + verifications_payload(deploy_payload(state="VERIFIED_UNTIL_SUPERSEDED", rolled_back=True)) + ) + rolled_back_outcome = evaluate_deploy_verifications(rolled_back, COMMIT_SHA) + assert rolled_back_outcome is not None + assert rolled_back_outcome.status == "ROLLED_BACK" + + future_state = CommitDeployVerifications.from_dict( + verifications_payload(deploy_payload(state="FUTURE_UNSEEN_STATE")) + ) + future_outcome = evaluate_deploy_verifications(future_state, COMMIT_SHA) + assert future_outcome is not None + assert future_outcome.status == "INCOMPLETE" + + +@MODES +async def test_wait_for_commit_deploy_verifications_polls_until_checkpoint( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = DeployClock(monkeypatch) + responses = [ + verifications_payload(recorded=False), + verifications_payload( + deploy_payload( + state="NOT_YET_DUE", + checkpoints=[ + checkpoint_payload("LANDING", None), + checkpoint_payload("MINUTES_20", None), + ], + ) + ), + verifications_payload( + deploy_payload( + state="NOT_YET_DUE", + checkpoints=[ + checkpoint_payload("LANDING", "HEALTHY"), + checkpoint_payload("MINUTES_20", "HEALTHY"), + checkpoint_payload("HOUR_1", None), + ], + ) + ), + ] + + def respond(request: Request, index: int) -> Reply: + assert request.path == ( + f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}" + f"/commits/{COMMIT_SHA}/deploy-verifications" + ) + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + return Reply(body=responses[index]) + + with Server(respond) as server: + async with session(mode, server.url) as client: + outcome = await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + until_checkpoint=DeployCheckpoint.MINUTES_20, + timeout=60, + ) + assert outcome.status == "CHECKPOINT_VERIFIED" + assert outcome.recorded is True + assert len(outcome.deploys) == 1 + assert outcome.deploys[0].deploy_url == f"https://proofline.sh/deploys/{ENV_PROD}" + assert clock.delays == [5.0, 10.0] + + +@MODES +async def test_wait_for_commit_deploy_verifications_filters_and_fail_fast( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + DeployClock(monkeypatch) + staging = deploy_payload( + environment_id=ENV_STAGING, + github_environment="staging", + deployment_task="deploy:api", + state="NOT_YET_DUE", + regressed=True, + gaps=["BASELINE_HELD_REGRESSION"], + checkpoints=[checkpoint_payload("LANDING", "REGRESSED", gaps=["BASELINE_HELD_REGRESSION"])], + ) + prod_pending = deploy_payload( + environment_id=ENV_PROD, + github_environment="production", + deployment_task="deploy:web", + state="NOT_YET_DUE", + checkpoints=[checkpoint_payload("LANDING", None)], + ) + prod_verified = deploy_payload( + environment_id=ENV_PROD, + github_environment="production", + deployment_task="deploy:web", + state="VERIFIED", + checkpoints=[checkpoint_payload("LANDING", "HEALTHY")], + ) + + with Server( + lambda request, index: Reply( + body=verifications_payload(staging, prod_pending if index == 0 else prod_verified) + ) + ) as server: + async with session(mode, server.url) as client: + fast = await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + fail_fast=True, + ) + assert fast.status == "REGRESSED" + assert fast.gaps == ("BASELINE_HELD_REGRESSION",) + assert len(server.requests) == 1 + + with Server( + lambda request, index: Reply( + body=verifications_payload(staging, prod_pending if index == 0 else prod_verified) + ) + ) as server: + async with session(mode, server.url) as client: + filtered = await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + environment_id=ENV_PROD, + github_environment="production", + deployment_task="deploy:web", + ) + assert filtered.status == "VERIFIED" + assert [d.environment_id for d in filtered.deploys] == [ENV_PROD] + assert len(server.requests) == 2 + + with Server( + lambda request, index: Reply( + body=verifications_payload(staging, prod_pending if index == 0 else prod_verified) + ) + ) as server: + async with session(mode, server.url) as client: + waited_all = await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + fail_fast=False, + ) + assert waited_all.status == "REGRESSED" + assert len(waited_all.deploys) == 2 + assert len(server.requests) == 2 + + +@MODES +async def test_wait_for_commit_deploy_verifications_timeout_retains_snapshot( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = DeployClock(monkeypatch) + body = verifications_payload( + deploy_payload( + state="UNRECORDED", + verification_ended=False, + gaps=["RUNTIME_ROLLOUT_UNSETTLED"], + checkpoints=[checkpoint_payload("LANDING", None)], + ) + ) + with Server(lambda request, index: Reply(body=body)) as server: + async with session(mode, server.url) as client: + outcome = await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + timeout=12, + ) + assert outcome.status == "TIMED_OUT" + assert outcome.recorded is True + assert outcome.gaps == ("RUNTIME_ROLLOUT_UNSETTLED",) + assert outcome.verifications is not None + assert clock.delays == [5.0, 7.0] + + ended = verifications_payload(deploy_payload(state="UNRECORDED", verification_ended=True)) + with Server(lambda request, index: Reply(body=ended)) as server: + async with session(mode, server.url) as client: + outcome = await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + timeout=30, + ) + assert outcome.status == "UNRECORDED" + assert len(server.requests) == 1 + + +@MODES +@pytest.mark.parametrize( + "kwargs", + [ + {"commit_sha": "A" * 40}, + {"commit_sha": "a" * 64}, + {"commit_sha": "short"}, + {"commit_sha": "g" * 40}, + {"commit_sha": COMMIT_SHA, "timeout": -1}, + {"commit_sha": COMMIT_SHA, "timeout": float("nan")}, + {"commit_sha": COMMIT_SHA, "timeout": True}, + {"commit_sha": COMMIT_SHA, "until_checkpoint": "UNKNOWN_WINDOW"}, + ], +) +async def test_wait_for_commit_deploy_verifications_validates_inputs_before_request( + mode: str, kwargs: dict[str, Any] +) -> None: + with Server(lambda request, index: Reply(body=verifications_payload())) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError): + await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + **kwargs, + ) + assert not server.requests + + +@MODES +async def test_wait_for_commit_deploy_verifications_rejects_invalid_payload(mode: str) -> None: + malformed = { + "recorded": True, + "deploys": [ + { + "environment_id": str(ENV_PROD), + "state": "VERIFIED", + "regressed": "nope", + "gaps": [], + "checkpoints": [], + } + ], + } + with Server(lambda request, index: Reply(body=malformed)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call( + client, + "wait_for_commit_deploy_verifications", + ORG, + REPOSITORY, + COMMIT_SHA, + ) + assert raised.value.type == "urn:proofline:sdk:invalid-response"