diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..2f02effb 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -37,6 +37,7 @@ from .exports import ExportDataset, ExportFormat, ExportPage from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome +from .trail import CommitEvidence, FailedDeployTrail, TrailGap __all__ = [ "AgentSession", @@ -44,6 +45,7 @@ "AssessmentGap", "AsyncProoflineClient", "CheckGap", + "CommitEvidence", "CommitReviewRequest", "CommitReviewResponse", "CoverageUploadRequest", @@ -54,6 +56,7 @@ "ExportDataset", "ExportFormat", "ExportPage", + "FailedDeployTrail", "FileReviewRequest", "FileReviewResponse", "KnowledgeResult", @@ -77,6 +80,7 @@ "SecretStr", "StartSession", "StopResponse", + "TrailGap", "UploadedReport", "__version__", "models", diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..9b495892 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -4,7 +4,7 @@ import math from asyncio import sleep as async_sleep -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Sequence from string import hexdigits from time import monotonic, sleep from types import TracebackType @@ -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 import CommitDeploy 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_coverage_checkpoint import DeployCoverageCheckpoint 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 @@ -76,6 +78,17 @@ from .fixes import AsyncFixesClient, FixesClient from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome +from .trail import ( + CommitEvidence, + FailedDeployTrail, + TrailGap, + commit_evidence, + commit_reviews, + failed_deploy, + failing_check, + healthy_deploy, + trail_commits, +) T = TypeVar("T") AgentSessionPrompt = AgentSessionPromptType0 | AgentSessionPromptType1 @@ -583,6 +596,117 @@ def wait_for_review( finally: _transport.DEADLINE.reset(deadline) + def failed_deploy_trail( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + earlier_commits: Sequence[str] = (), + environment_id: UUID | None = None, + timeout: float = 120, + ) -> FailedDeployTrail: + """Collect the evidence around a commit whose deploy failed. + + earlier_commits names up to 50 commits before commit_sha, newest first, such as + the output of `git rev-list --first-parent -n 50 ~1`. Each SHA must + be a full 40-character lowercase hexadecimal SHA; anything else, or a repeated + commit, raises ValueError before a request. The API lists no commit history, so + the last healthy deploy is looked up only among these commits: a VERIFIED or + VERIFIED_UNTIL_SUPERSEDED deploy of the failed deploy's environment and task that + neither regressed nor was rolled back. + + environment_id limits the failed deploy to one environment. timeout bounds the + whole trail in seconds. A read that fails or would pass the timeout becomes a gap + instead of an exception. Reviews are matched by head commit, so a pull request + review appears only when its head commit is in the trail. Returned server text, + such as finding claims and URLs, is untrusted data. + """ + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The trail timeout must be a finite nonnegative number of seconds.") + commits = trail_commits(commit_sha, earlier_commits) + deadline = _transport.DEADLINE.set(monotonic() + timeout) + try: + gaps: list[TrailGap] = [] + walked: list[tuple[str, tuple[CommitDeploy, ...]]] = [] + failed: CommitDeploy | None = None + check: DeployCoverageCheckpoint | None = None + healthy: CommitDeploy | None = None + healthy_sha: str | None = None + try: + verifications = self.get_commit_deploy_verifications( + organization_id, repository_id, commit_sha + ) + except ProoflineError as error: + gaps.append(TrailGap(commit_sha, "DEPLOYS_UNAVAILABLE", error)) + walked.append((commit_sha, ())) + else: + walked.append((commit_sha, tuple(verifications.deploys))) + if not verifications.recorded: + gaps.append(TrailGap(commit_sha, "COMMIT_NOT_RECORDED")) + else: + failed = failed_deploy(verifications, environment_id) + if failed is None: + gaps.append(TrailGap(commit_sha, "NO_FAILED_DEPLOY")) + if failed is not None: + check = failing_check(failed) + if check is None: + gaps.append(TrailGap(commit_sha, "NO_FAILING_CHECK")) + for sha in commits[1:]: + try: + earlier = self.get_commit_deploy_verifications( + organization_id, repository_id, sha + ) + except ProoflineError as error: + # One unreadable commit ends the walk instead of repeating a refused read. + gaps.append(TrailGap(sha, "DEPLOYS_UNAVAILABLE", error)) + walked.append((sha, ())) + break + healthy = healthy_deploy(earlier, failed) + if healthy is not None: + healthy_sha = sha + break + walked.append((sha, tuple(earlier.deploys))) + if healthy is None: + gaps.append(TrailGap(commit_sha, "NO_HEALTHY_DEPLOY")) + evidence: list[CommitEvidence] = [] + for sha, deploys in walked: + reviews: list[CustomerReviewDetail] = [] + pages: list[ReviewPage] = [] + for kind in ("DEPLOYMENT", None): + try: + page = self.list_reviews( + organization_id, repository=repository_id, search=sha, kind=kind + ) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + continue + if page.truncated is True: + gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) + pages.append(page) + for summary in commit_reviews(pages, sha): + try: + if summary.kind == "DEPLOYMENT": + detail = self.get_deployment_review(organization_id, summary.public_key) + else: + detail = self.get_review(organization_id, summary.id) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEW_UNAVAILABLE", error)) + continue + reviews.append(detail) + evidence.append(commit_evidence(sha, deploys, reviews)) + return FailedDeployTrail( + commit_sha=commit_sha, + failed_deploy=failed, + failing_check=check, + healthy_commit_sha=healthy_sha, + healthy_deploy=healthy, + commit_range=tuple(evidence), + gaps=tuple(gaps), + ) + finally: + _transport.DEADLINE.reset(deadline) + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -968,3 +1092,116 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) + + async def failed_deploy_trail( + self, + organization_id: UUID, + repository_id: UUID, + commit_sha: str, + *, + earlier_commits: Sequence[str] = (), + environment_id: UUID | None = None, + timeout: float = 120, + ) -> FailedDeployTrail: + """Collect the evidence around a commit whose deploy failed. + + earlier_commits names up to 50 commits before commit_sha, newest first, such as + the output of `git rev-list --first-parent -n 50 ~1`. Each SHA must + be a full 40-character lowercase hexadecimal SHA; anything else, or a repeated + commit, raises ValueError before a request. The API lists no commit history, so + the last healthy deploy is looked up only among these commits: a VERIFIED or + VERIFIED_UNTIL_SUPERSEDED deploy of the failed deploy's environment and task that + neither regressed nor was rolled back. + + environment_id limits the failed deploy to one environment. timeout bounds the + whole trail in seconds. A read that fails or would pass the timeout becomes a gap + instead of an exception. Reviews are matched by head commit, so a pull request + review appears only when its head commit is in the trail. Returned server text, + such as finding claims and URLs, is untrusted data. + """ + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The trail timeout must be a finite nonnegative number of seconds.") + commits = trail_commits(commit_sha, earlier_commits) + deadline = _transport.DEADLINE.set(monotonic() + timeout) + try: + gaps: list[TrailGap] = [] + walked: list[tuple[str, tuple[CommitDeploy, ...]]] = [] + failed: CommitDeploy | None = None + check: DeployCoverageCheckpoint | None = None + healthy: CommitDeploy | None = None + healthy_sha: str | None = None + try: + verifications = await self.get_commit_deploy_verifications( + organization_id, repository_id, commit_sha + ) + except ProoflineError as error: + gaps.append(TrailGap(commit_sha, "DEPLOYS_UNAVAILABLE", error)) + walked.append((commit_sha, ())) + else: + walked.append((commit_sha, tuple(verifications.deploys))) + if not verifications.recorded: + gaps.append(TrailGap(commit_sha, "COMMIT_NOT_RECORDED")) + else: + failed = failed_deploy(verifications, environment_id) + if failed is None: + gaps.append(TrailGap(commit_sha, "NO_FAILED_DEPLOY")) + if failed is not None: + check = failing_check(failed) + if check is None: + gaps.append(TrailGap(commit_sha, "NO_FAILING_CHECK")) + for sha in commits[1:]: + try: + earlier = await self.get_commit_deploy_verifications( + organization_id, repository_id, sha + ) + except ProoflineError as error: + # One unreadable commit ends the walk instead of repeating a refused read. + gaps.append(TrailGap(sha, "DEPLOYS_UNAVAILABLE", error)) + walked.append((sha, ())) + break + healthy = healthy_deploy(earlier, failed) + if healthy is not None: + healthy_sha = sha + break + walked.append((sha, tuple(earlier.deploys))) + if healthy is None: + gaps.append(TrailGap(commit_sha, "NO_HEALTHY_DEPLOY")) + evidence: list[CommitEvidence] = [] + for sha, deploys in walked: + reviews: list[CustomerReviewDetail] = [] + pages: list[ReviewPage] = [] + for kind in ("DEPLOYMENT", None): + try: + page = await self.list_reviews( + organization_id, repository=repository_id, search=sha, kind=kind + ) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + continue + if page.truncated is True: + gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) + pages.append(page) + for summary in commit_reviews(pages, sha): + try: + if summary.kind == "DEPLOYMENT": + detail = await self.get_deployment_review( + organization_id, summary.public_key + ) + else: + detail = await self.get_review(organization_id, summary.id) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEW_UNAVAILABLE", error)) + continue + reviews.append(detail) + evidence.append(commit_evidence(sha, deploys, reviews)) + return FailedDeployTrail( + commit_sha=commit_sha, + failed_deploy=failed, + failing_check=check, + healthy_commit_sha=healthy_sha, + healthy_deploy=healthy, + commit_range=tuple(evidence), + gaps=tuple(gaps), + ) + finally: + _transport.DEADLINE.reset(deadline) diff --git a/proofline/trail.py b/proofline/trail.py new file mode 100644 index 00000000..8db5f49c --- /dev/null +++ b/proofline/trail.py @@ -0,0 +1,160 @@ +"""Evidence for a failed deploy: its failing check, last healthy deploy and the commits between.""" + +from __future__ import annotations + +from collections.abc import Sequence +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.customer_code_assessment import CustomerCodeAssessment +from ._generated.models.customer_finding import CustomerFinding +from ._generated.models.customer_review_detail import CustomerReviewDetail +from ._generated.models.deploy_coverage_checkpoint import DeployCoverageCheckpoint +from ._generated.models.review_page import ReviewPage +from ._generated.models.review_summary import ReviewSummary +from ._transport import ProoflineError + +TrailGapReason = Literal[ + "COMMIT_NOT_RECORDED", + "NO_FAILED_DEPLOY", + "NO_FAILING_CHECK", + "NO_HEALTHY_DEPLOY", + "DEPLOYS_UNAVAILABLE", + "REVIEWS_UNAVAILABLE", + "REVIEWS_TRUNCATED", + "REVIEW_UNAVAILABLE", +] +MAX_EARLIER_COMMITS = 50 +_HEALTHY_STATES = frozenset(("VERIFIED", "VERIFIED_UNTIL_SUPERSEDED")) +_LOWER_HEX = frozenset("0123456789abcdef") + + +@dataclass(frozen=True) +class TrailGap: + """What the trail could not establish for one commit. + + error is the ProoflineError of the read that failed, when a read failed. + """ + + commit_sha: str + reason: TrailGapReason + error: ProoflineError | None = field(default=None, repr=False) + + def __post_init__(self) -> None: + # A gap outlives its failed read; the error must not keep that read's frames or body. + if self.error is not None: + self.error.__traceback__ = None + self.error.__context__ = None + + +@dataclass(frozen=True) +class CommitEvidence: + """One commit of the range with its recorded deploys, reviews and their findings.""" + + commit_sha: str + deploys: tuple[CommitDeploy, ...] = field(repr=False) + reviews: tuple[CustomerReviewDetail, ...] = field(repr=False) + findings: tuple[CustomerFinding, ...] = field(repr=False) + + +@dataclass(frozen=True) +class FailedDeployTrail: + """The evidence around a commit whose deploy failed. + + commit_range starts with the failed commit and runs back, newest first, to the + commit just after healthy_commit_sha, or to the last earlier commit read when no + healthy deploy was found. gaps names everything the trail could not establish. + """ + + commit_sha: str + failed_deploy: CommitDeploy | None = field(repr=False) + failing_check: DeployCoverageCheckpoint | None = field(repr=False) + healthy_commit_sha: str | None + healthy_deploy: CommitDeploy | None = field(repr=False) + commit_range: tuple[CommitEvidence, ...] = field(repr=False) + gaps: tuple[TrailGap, ...] + + +def _commit(value: object) -> str: + if not isinstance(value, str) or len(value) != 40 or not set(value) <= _LOWER_HEX: + raise ValueError("A trail commit must be a full 40-character lowercase hexadecimal SHA.") + return value + + +def trail_commits(commit_sha: str, earlier_commits: Sequence[str]) -> tuple[str, ...]: + # The deploy route accepts only full lowercase SHA-1s, and each commit costs a request. + if isinstance(earlier_commits, str) or len(earlier_commits) > MAX_EARLIER_COMMITS: + raise ValueError( + f"earlier_commits takes a sequence of at most {MAX_EARLIER_COMMITS} commit SHAs." + ) + commits = (_commit(commit_sha), *(_commit(sha) for sha in earlier_commits)) + if len(set(commits)) != len(commits): + raise ValueError("A commit can appear only once in a trail.") + return commits + + +def failed_deploy( + verifications: CommitDeployVerifications, environment_id: UUID | None +) -> CommitDeploy | None: + # Deploys are listed earliest landing first, so the last match is the latest failure. + failures = [ + deploy + for deploy in verifications.deploys + if (environment_id is None or deploy.environment_id == environment_id) + and (deploy.state == "FAILED" or deploy.regressed is True) + ] + return failures[-1] if failures else None + + +def failing_check(deploy: CommitDeploy) -> DeployCoverageCheckpoint | None: + # The four checks are listed in order, so this is the earliest regression. + return next((check for check in deploy.checkpoints if check.result == "REGRESSED"), None) + + +def healthy_deploy( + verifications: CommitDeployVerifications, failed: CommitDeploy +) -> CommitDeploy | None: + matches = [ + deploy + for deploy in verifications.deploys + if deploy.environment_id == failed.environment_id + and _task(deploy) == _task(failed) + and deploy.state in _HEALTHY_STATES + and deploy.regressed is False + and deploy.rolled_back is not True + ] + return matches[-1] if matches else None + + +def _task(deploy: CommitDeploy) -> str | None: + return deploy.deployment_task if isinstance(deploy.deployment_task, str) else None + + +def commit_reviews(pages: Sequence[ReviewPage], commit_sha: str) -> list[ReviewSummary]: + # A review is evidence only for the head commit it is pinned to, and is read once. + found: dict[UUID, ReviewSummary] = {} + for page in pages: + for summary in page.items: + if ( + isinstance(summary.head_commit_sha, str) + and summary.head_commit_sha.lower() == commit_sha + ): + found.setdefault(summary.id, summary) + return list(found.values()) + + +def commit_evidence( + commit_sha: str, deploys: tuple[CommitDeploy, ...], reviews: list[CustomerReviewDetail] +) -> CommitEvidence: + findings = [finding for review in reviews for finding in _findings(review)] + return CommitEvidence(commit_sha, deploys, tuple(reviews), tuple(findings)) + + +def _findings(review: CustomerReviewDetail) -> list[CustomerFinding]: + findings = [finding for assessment in review.assessments for finding in assessment.findings] + if isinstance(review.code_assessment, CustomerCodeAssessment): + findings.extend(review.code_assessment.findings) + return findings diff --git a/scripts/contracts.py b/scripts/contracts.py index 6e6255a2..ad5f9514 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", + "failed_deploy_trail", + "iter_export_pages", + "iter_reviews", + "wait_for_review", + } exposed = { name for name in dir(client) diff --git a/tests/fixtures.py b/tests/fixtures.py index 70982ba0..9cf5a5d2 100644 --- a/tests/fixtures.py +++ b/tests/fixtures.py @@ -13,6 +13,13 @@ FINDING = UUID("00000000-0000-4000-8000-000000000005") TOKEN = "pln_test_sdk_credential_canary" PRIVATE = "synthetic-finding-body-canary" +DEPLOY_ENVIRONMENT = UUID("00000000-0000-4000-8000-000000000007") +OTHER_DEPLOY_ENVIRONMENT = UUID("00000000-0000-4000-8000-000000000008") +DEPLOYMENT_REVIEW = UUID("00000000-0000-4000-8000-000000000009") +FAILED_COMMIT = "f" * 40 +MIDDLE_COMMITS = ("e" * 40, "d" * 40) +HEALTHY_COMMIT = "c" * 40 +CHECKPOINTS = ("LANDING", "MINUTES_20", "HOUR_1", "DAY_1") def finding() -> dict[str, Any]: @@ -96,3 +103,41 @@ def page(*, cursor: str | None = None, truncated: bool = False) -> dict[str, Any "truncated": truncated, "next_cursor": cursor, } + + +def deploy( + state: str, + *, + regressed: bool = False, + rolled_back: bool = False, + environment: UUID = DEPLOY_ENVIRONMENT, + task: str | None = "deploy", + results: tuple[str | None, ...] = ("HEALTHY", "HEALTHY", "HEALTHY", "HEALTHY"), +) -> dict[str, Any]: + return { + "environment_id": str(environment), + "state": state, + "regressed": regressed, + "rolled_back": rolled_back, + "gaps": [], + "checkpoints": [ + {"checkpoint": name, "due_at": "2026-11-01T00:00:00Z", "result": result, "gaps": []} + for name, result in zip(CHECKPOINTS, results) + ], + "deployment_task": task, + "github_environment": "synthetic-environment", + "deploy_url": "https://proofline.example/deploys/synthetic", + } + + +def verifications(*deploys: dict[str, Any]) -> dict[str, Any]: + return {"recorded": bool(deploys), "deploys": list(deploys)} + + +def commit_page(*items: dict[str, Any], truncated: bool = False) -> dict[str, Any]: + return { + "items": list(items), + "filters": {"repositories": [], "environments": [], "authors": []}, + "truncated": truncated, + "next_cursor": "synthetic-cursor" if truncated else None, + } diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..b60b75b5 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -14,7 +14,7 @@ import time import tomllib import traceback -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -65,17 +65,27 @@ from .fixtures import ( ASSESSMENT, CODE_ASSESSMENT, + DEPLOY_ENVIRONMENT, + DEPLOYMENT_REVIEW, + FAILED_COMMIT, FINDING, + HEALTHY_COMMIT, + MIDDLE_COMMITS, ORG, + OTHER_DEPLOY_ENVIRONMENT, PRIVATE, REPOSITORY, REVIEW, TOKEN, assessment, code_assessment, + commit_page, + deploy, finding, page, review, + summary, + verifications, ) from .http_server import Reply, Request, Server @@ -2586,3 +2596,451 @@ 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" + + +def deploys_path(commit: str) -> str: + return ( + f"/api/v1/organizations/{ORG}/repositories/{REPOSITORY}" + f"/commits/{commit}/deploy-verifications" + ) + + +def reviews_route(commit: str, kind: str | None = None) -> str: + route = f"reviews?search={commit}" + if kind is not None: + route += f"&kind={kind}" + return route + + +def trail_peer(routes: dict[str, Reply]) -> Callable[[Request, int], Reply]: + # An unrouted request gets no reply, so it surfaces as a gap the test rejects. + def respond(request: Request, index: int) -> Reply: + assert request.method == "GET" + assert request.headers["Authorization"] == f"Bearer {TOKEN}" + parts = urlsplit(request.path) + if parts.path == f"/api/v1/organizations/{ORG}/reviews": + query = parse_qs(parts.query) + assert query["repository"] == [str(REPOSITORY)] + assert set(query) <= {"repository", "search", "kind"} + kind = query["kind"][0] if "kind" in query else None + return routes[reviews_route(query["search"][0], kind)] + return routes[parts.path] + + return respond + + +def trail_requests(server: Server) -> list[str]: + paths: list[str] = [] + for request in server.requests: + parts = urlsplit(request.path) + query = parse_qs(parts.query) + search = query.get("search") + if search: + kind = query["kind"][0] if "kind" in query else None + paths.append(reviews_route(search[0], kind)) + else: + paths.append(parts.path) + return paths + + +@MODES +async def test_failed_deploy_trail_collects_failing_check_healthy_commit_and_range( + mode: str, +) -> None: + middle, unrecorded = MIDDLE_COMMITS + pull_request = {**summary(), "head_commit_sha": FAILED_COMMIT} + deployment = { + **summary(), + "id": str(DEPLOYMENT_REVIEW), + "public_key": "rev_deployment", + "kind": "DEPLOYMENT", + "head_commit_sha": FAILED_COMMIT, + } + elsewhere = {**summary(), "head_commit_sha": "9" * 40} + routes = { + deploys_path(FAILED_COMMIT): Reply( + body=verifications( + deploy( + "VERIFIED", + regressed=True, + results=("HEALTHY", "REGRESSED", "REGRESSED", "HEALTHY"), + ) + ) + ), + deploys_path(middle): Reply( + body=verifications( + deploy("VERIFIED", environment=OTHER_DEPLOY_ENVIRONMENT), deploy("INCOMPLETE") + ) + ), + deploys_path(unrecorded): Reply(body=verifications()), + deploys_path(HEALTHY_COMMIT): Reply( + body=verifications( + deploy("VERIFIED_UNTIL_SUPERSEDED", task="deploy:web"), + deploy("VERIFIED_UNTIL_SUPERSEDED"), + ) + ), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"): Reply(body=commit_page(deployment)), + reviews_route(FAILED_COMMIT): Reply(body=commit_page(pull_request, deployment, elsewhere)), + f"/api/v1/organizations/{ORG}/reviews/{REVIEW}": Reply( + body={ + **review(), + "head_commit_sha": FAILED_COMMIT, + "assessments": [{**assessment(), "findings": [finding()]}], + } + ), + f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment": Reply( + body={**review(), **deployment} + ), + reviews_route(middle, "DEPLOYMENT"): Reply(body=commit_page()), + reviews_route(middle): Reply(body=commit_page()), + reviews_route(unrecorded, "DEPLOYMENT"): Reply(body=commit_page()), + reviews_route(unrecorded): Reply(body=commit_page()), + } + with Server(trail_peer(routes)) as server: + async with session(mode, server.url) as client: + trail = await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + FAILED_COMMIT, + earlier_commits=[middle, unrecorded, HEALTHY_COMMIT, "0" * 40], + ) + assert trail.gaps == () + assert trail.commit_sha == FAILED_COMMIT + assert trail.failed_deploy.regressed is True + assert trail.failing_check.checkpoint is models.DeployCheckpoint.MINUTES_20 + assert trail.healthy_commit_sha == HEALTHY_COMMIT + assert trail.healthy_deploy.deployment_task == "deploy" + assert [item.commit_sha for item in trail.commit_range] == [FAILED_COMMIT, middle, unrecorded] + failed, between, empty = trail.commit_range + assert [item.kind for item in failed.reviews] == ["DEPLOYMENT", "PR"] + assert [item.claim for item in failed.findings] == [PRIVATE] + assert [item.state for item in between.deploys] == ["VERIFIED", "INCOMPLETE"] + assert (empty.deploys, empty.reviews, empty.findings) == ((), (), ()) + assert trail_requests(server) == [ + deploys_path(FAILED_COMMIT), + deploys_path(middle), + deploys_path(unrecorded), + deploys_path(HEALTHY_COMMIT), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), + f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment", + f"/api/v1/organizations/{ORG}/reviews/{REVIEW}", + reviews_route(middle, "DEPLOYMENT"), + reviews_route(middle), + reviews_route(unrecorded, "DEPLOYMENT"), + reviews_route(unrecorded), + ] + assert PRIVATE not in repr(trail) + assert TOKEN not in repr(trail) + + +@MODES +async def test_failed_deploy_trail_keeps_partial_evidence_when_reads_fail(mode: str) -> None: + middle, never_read = MIDDLE_COMMITS + refused = { + "type": "urn:proofline:forbidden", + "title": "forbidden", + "detail": f"{PRIVATE} {TOKEN}", + } + routes = { + deploys_path(FAILED_COMMIT): Reply(body=verifications(deploy("FAILED", results=()))), + deploys_path(middle): Reply(403, refused), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"): Reply( + body=commit_page({**summary(), "head_commit_sha": FAILED_COMMIT}, truncated=True) + ), + reviews_route(FAILED_COMMIT): Reply( + body=commit_page({**summary(), "head_commit_sha": FAILED_COMMIT}, truncated=True) + ), + f"/api/v1/organizations/{ORG}/reviews/{REVIEW}": Reply( + 500, {"title": "internal error", "status": 500, "detail": None} + ), + reviews_route(middle, "DEPLOYMENT"): Reply( + 404, {"title": "not found", "status": 404, "detail": "No such repository."} + ), + reviews_route(middle): Reply( + 404, {"title": "not found", "status": 404, "detail": "No such repository."} + ), + } + with Server(trail_peer(routes)) as server: + async with session(mode, server.url) as client: + trail = await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + FAILED_COMMIT, + earlier_commits=[middle, never_read, HEALTHY_COMMIT], + ) + assert trail.failed_deploy.state == "FAILED" + assert trail.failing_check is None + assert (trail.healthy_commit_sha, trail.healthy_deploy) == (None, None) + assert [item.commit_sha for item in trail.commit_range] == [FAILED_COMMIT, middle] + assert [(gap.commit_sha, gap.reason) for gap in trail.gaps] == [ + (FAILED_COMMIT, "NO_FAILING_CHECK"), + (middle, "DEPLOYS_UNAVAILABLE"), + (FAILED_COMMIT, "NO_HEALTHY_DEPLOY"), + (FAILED_COMMIT, "REVIEWS_TRUNCATED"), + (FAILED_COMMIT, "REVIEWS_TRUNCATED"), + (FAILED_COMMIT, "REVIEW_UNAVAILABLE"), + (middle, "REVIEWS_UNAVAILABLE"), + (middle, "REVIEWS_UNAVAILABLE"), + ] + assert [gap.error.status if gap.error is not None else None for gap in trail.gaps] == [ + None, + 403, + None, + None, + None, + 500, + 404, + 404, + ] + assert trail.gaps[1].error.detail == f"{PRIVATE} [redacted]" + for gap in trail.gaps: + if gap.error is not None: + assert gap.error.__traceback__ is None + assert gap.error.__context__ is None + assert PRIVATE not in repr(trail) + assert TOKEN not in repr(trail) + assert trail_requests(server) == [ + deploys_path(FAILED_COMMIT), + deploys_path(middle), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), + f"/api/v1/organizations/{ORG}/reviews/{REVIEW}", + reviews_route(middle, "DEPLOYMENT"), + reviews_route(middle), + ] + + +@MODES +@pytest.mark.parametrize( + ("reply", "environment_id", "reason"), + [ + (Reply(body=verifications()), None, "COMMIT_NOT_RECORDED"), + (Reply(body=verifications(deploy("VERIFIED"))), None, "NO_FAILED_DEPLOY"), + ( + Reply( + body=verifications( + deploy("FAILED", environment=OTHER_DEPLOY_ENVIRONMENT, results=()) + ) + ), + DEPLOY_ENVIRONMENT, + "NO_FAILED_DEPLOY", + ), + ( + Reply(404, {"title": "not found", "status": 404, "detail": "No such repository."}), + None, + "DEPLOYS_UNAVAILABLE", + ), + ], +) +async def test_failed_deploy_trail_without_a_failed_deploy_reads_no_earlier_commit( + mode: str, reply: Reply, environment_id: UUID | None, reason: str +) -> None: + routes = { + deploys_path(FAILED_COMMIT): reply, + reviews_route(FAILED_COMMIT, "DEPLOYMENT"): Reply(body=commit_page()), + reviews_route(FAILED_COMMIT): Reply(body=commit_page()), + } + with Server(trail_peer(routes)) as server: + async with session(mode, server.url) as client: + trail = await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + FAILED_COMMIT, + earlier_commits=[HEALTHY_COMMIT], + environment_id=environment_id, + ) + assert (trail.failed_deploy, trail.failing_check) == (None, None) + assert (trail.healthy_commit_sha, trail.healthy_deploy) == (None, None) + assert [item.commit_sha for item in trail.commit_range] == [FAILED_COMMIT] + assert [(gap.commit_sha, gap.reason) for gap in trail.gaps] == [(FAILED_COMMIT, reason)] + assert trail_requests(server) == [ + deploys_path(FAILED_COMMIT), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), + ] + + +@MODES +async def test_failed_deploy_trail_refuses_invalid_commits_before_any_request(mode: str) -> None: + with Server(lambda request, index: Reply(body=verifications())) as server: + async with session(mode, server.url) as client: + for commit, earlier, extra in [ + (FAILED_COMMIT[:12], [], {}), + (FAILED_COMMIT.upper(), [], {}), + (FAILED_COMMIT, [FAILED_COMMIT], {}), + (FAILED_COMMIT, [], {"timeout": -1}), + (FAILED_COMMIT, [], {"timeout": float("nan")}), + (FAILED_COMMIT, [], {"timeout": float("inf")}), + ]: + with pytest.raises(ValueError): + await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + commit, + earlier_commits=earlier, + **extra, + ) + assert server.requests == [] + + +@MODES +async def test_failed_deploy_trail_turns_a_malformed_body_into_a_gap(mode: str) -> None: + middle, later = MIDDLE_COMMITS + routes = { + deploys_path(FAILED_COMMIT): Reply( + body=verifications( + deploy( + "FAILED", + regressed=True, + results=("REGRESSED", "HEALTHY", "HEALTHY", "HEALTHY"), + ) + ) + ), + deploys_path(middle): Reply(body=f"not json {PRIVATE}".encode()), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"): Reply(body=commit_page()), + reviews_route(FAILED_COMMIT): Reply(body=commit_page()), + reviews_route(middle, "DEPLOYMENT"): Reply(body=commit_page()), + reviews_route(middle): Reply(body=commit_page()), + } + with Server(trail_peer(routes)) as server: + async with session(mode, server.url) as client: + trail = await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + FAILED_COMMIT, + earlier_commits=[middle, later], + ) + assert [(gap.commit_sha, gap.reason) for gap in trail.gaps] == [ + (middle, "DEPLOYS_UNAVAILABLE"), + (FAILED_COMMIT, "NO_HEALTHY_DEPLOY"), + ] + error = trail.gaps[0].error + assert error is not None + assert error.type == "urn:proofline:sdk:invalid-response" + assert error.__traceback__ is None + assert error.__context__ is None + assert PRIVATE not in error.detail + assert PRIVATE not in repr(trail) + assert later not in "".join(trail_requests(server)) + + +@MODES +async def test_failed_deploy_trail_stops_reading_at_its_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + middle, later = MIDDLE_COMMITS + + def respond(request: Request, index: int) -> Reply: + clock.now += 10 + if urlsplit(request.path).path == deploys_path(FAILED_COMMIT): + return Reply( + body=verifications( + deploy( + "FAILED", + regressed=True, + results=("REGRESSED", "HEALTHY", "HEALTHY", "HEALTHY"), + ) + ) + ) + return Reply(body=verifications(deploy("VERIFIED"))) + + with Server(respond) as server: + async with session(mode, server.url) as client: + trail = await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + FAILED_COMMIT, + earlier_commits=[middle, later], + timeout=15, + ) + assert trail.failing_check is not None + assert trail.failing_check.checkpoint is models.DeployCheckpoint.LANDING + assert [(gap.commit_sha, gap.reason) for gap in trail.gaps] == [ + (middle, "DEPLOYS_UNAVAILABLE"), + (FAILED_COMMIT, "NO_HEALTHY_DEPLOY"), + (FAILED_COMMIT, "REVIEWS_UNAVAILABLE"), + (FAILED_COMMIT, "REVIEWS_UNAVAILABLE"), + (middle, "REVIEWS_UNAVAILABLE"), + (middle, "REVIEWS_UNAVAILABLE"), + ] + assert [gap.error.type if gap.error is not None else None for gap in trail.gaps] == [ + "urn:proofline:sdk:timeout", + None, + "urn:proofline:sdk:timeout", + "urn:proofline:sdk:timeout", + "urn:proofline:sdk:timeout", + "urn:proofline:sdk:timeout", + ] + assert len(server.requests) == 2 + assert later not in "".join(request.path for request in server.requests) + + +@MODES +async def test_failed_deploy_trail_reports_an_unreadable_deployment_review(mode: str) -> None: + deployment = { + **summary(), + "id": str(DEPLOYMENT_REVIEW), + "public_key": "rev_deployment", + "kind": "DEPLOYMENT", + "head_commit_sha": FAILED_COMMIT, + } + routes = { + deploys_path(FAILED_COMMIT): Reply( + body=verifications( + deploy( + "FAILED", + regressed=True, + results=("REGRESSED", "HEALTHY", "HEALTHY", "HEALTHY"), + ) + ) + ), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"): Reply(body=commit_page(deployment)), + reviews_route(FAILED_COMMIT): Reply(body=commit_page()), + f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment": Reply( + 403, + { + "type": "urn:proofline:forbidden", + "title": "forbidden", + "detail": f"{PRIVATE} {TOKEN}", + }, + ), + } + with Server(trail_peer(routes)) as server: + async with session(mode, server.url) as client: + trail = await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + FAILED_COMMIT, + earlier_commits=[], + ) + assert [(gap.commit_sha, gap.reason) for gap in trail.gaps] == [ + (FAILED_COMMIT, "NO_HEALTHY_DEPLOY"), + (FAILED_COMMIT, "REVIEW_UNAVAILABLE"), + ] + assert trail.gaps[1].error is not None + assert trail.gaps[1].error.status == 403 + assert trail.gaps[1].error.__traceback__ is None + assert PRIVATE not in repr(trail) + assert TOKEN not in repr(trail) + assert trail_requests(server) == [ + deploys_path(FAILED_COMMIT), + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), + f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment", + ] diff --git a/tests/test_trail.py b/tests/test_trail.py new file mode 100644 index 00000000..2b7a704e --- /dev/null +++ b/tests/test_trail.py @@ -0,0 +1,210 @@ +"""Selection rules of the failed-deploy trail, without HTTP.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +import proofline +from proofline import ProoflineError, models, trail +from proofline.trail import ( + MAX_EARLIER_COMMITS, + TrailGap, + commit_evidence, + commit_reviews, + failed_deploy, + failing_check, + healthy_deploy, + trail_commits, +) + +from .fixtures import ( + DEPLOY_ENVIRONMENT, + DEPLOYMENT_REVIEW, + FAILED_COMMIT, + HEALTHY_COMMIT, + MIDDLE_COMMITS, + OTHER_DEPLOY_ENVIRONMENT, + PRIVATE, + REVIEW, + assessment, + code_assessment, + commit_page, + deploy, + finding, + review, + summary, + verifications, +) + + +def recorded(*deploys: dict[str, Any]) -> models.CommitDeployVerifications: + return models.CommitDeployVerifications.from_dict(verifications(*deploys)) + + +def test_failed_deploy_is_the_latest_failure_in_the_requested_environment() -> None: + deploys = recorded( + deploy("FAILED", task="first", results=()), + deploy("INCOMPLETE", regressed=True, task="second"), + deploy("VERIFIED"), + deploy("FAILED", environment=OTHER_DEPLOY_ENVIRONMENT, task="other", results=()), + ) + latest = failed_deploy(deploys, None) + scoped = failed_deploy(deploys, DEPLOY_ENVIRONMENT) + assert latest is not None and latest.deployment_task == "other" + assert scoped is not None and scoped.deployment_task == "second" + assert failed_deploy(recorded(deploy("VERIFIED"), deploy("INCOMPLETE")), None) is None + + +def test_failing_check_is_the_earliest_regressed_checkpoint() -> None: + regressed = models.CommitDeploy.from_dict( + deploy( + "VERIFIED", + regressed=True, + results=("HEALTHY", "INCOMPLETE", "REGRESSED", "REGRESSED"), + ) + ) + check = failing_check(regressed) + assert check is not None + assert check.checkpoint is models.DeployCheckpoint.HOUR_1 + assert check.result == "REGRESSED" + assert failing_check(models.CommitDeploy.from_dict(deploy("FAILED", results=()))) is None + + +@pytest.mark.parametrize( + ("candidate", "matches"), + [ + (deploy("VERIFIED"), True), + (deploy("VERIFIED_UNTIL_SUPERSEDED"), True), + (deploy("VERIFIED", regressed=True), False), + (deploy("VERIFIED", rolled_back=True), False), + (deploy("INCOMPLETE"), False), + (deploy("SUPERSEDED"), False), + (deploy("NOT_YET_DUE"), False), + (deploy("LATER_STATE"), False), + (deploy("VERIFIED", environment=OTHER_DEPLOY_ENVIRONMENT), False), + (deploy("VERIFIED", task="deploy:web"), False), + (deploy("VERIFIED", task=None), False), + ], +) +def test_healthy_deploy_needs_an_unregressed_verification_of_the_same_task( + candidate: dict[str, Any], matches: bool +) -> None: + failed = models.CommitDeploy.from_dict(deploy("FAILED", results=())) + assert (healthy_deploy(recorded(candidate), failed) is not None) is matches + + +def test_healthy_deploy_is_the_latest_match() -> None: + failed = models.CommitDeploy.from_dict(deploy("FAILED", results=())) + found = healthy_deploy( + recorded(deploy("VERIFIED"), deploy("VERIFIED_UNTIL_SUPERSEDED")), failed + ) + assert found is not None and found.state == "VERIFIED_UNTIL_SUPERSEDED" + + +def test_commit_reviews_keep_only_reviews_pinned_to_the_commit() -> None: + page = models.ReviewPage.from_dict( + commit_page( + {**summary(), "head_commit_sha": FAILED_COMMIT}, + {**summary(), "id": str(DEPLOYMENT_REVIEW), "head_commit_sha": FAILED_COMMIT.upper()}, + {**summary(), "head_commit_sha": HEALTHY_COMMIT}, + {**summary(), "head_commit_sha": None}, + summary(), + ) + ) + kept = commit_reviews([page], FAILED_COMMIT) + assert [item.head_commit_sha for item in kept] == [FAILED_COMMIT, FAILED_COMMIT.upper()] + + +def test_commit_reviews_read_each_review_once_across_pages() -> None: + deployment = { + **summary(), + "id": str(REVIEW), + "kind": "DEPLOYMENT", + "head_commit_sha": FAILED_COMMIT, + } + pull_request = { + **summary(), + "id": str(DEPLOYMENT_REVIEW), + "kind": "PR", + "head_commit_sha": FAILED_COMMIT, + } + pages = [ + models.ReviewPage.from_dict(commit_page(deployment)), + models.ReviewPage.from_dict(commit_page(pull_request, deployment)), + ] + kept = commit_reviews(pages, FAILED_COMMIT) + assert [(item.id, item.kind) for item in kept] == [ + (REVIEW, "DEPLOYMENT"), + (DEPLOYMENT_REVIEW, "PR"), + ] + + +def test_commit_evidence_collects_environment_and_code_findings() -> None: + detail = models.CustomerReviewDetail.from_dict( + { + **review(), + "assessments": [{**assessment(), "findings": [finding()]}], + "code_assessment": {**code_assessment(), "findings": [finding()]}, + } + ) + evidence = commit_evidence(FAILED_COMMIT, (), [detail]) + assert (evidence.commit_sha, evidence.deploys, evidence.reviews) == ( + FAILED_COMMIT, + (), + (detail,), + ) + assert [item.claim for item in evidence.findings] == [PRIVATE, PRIVATE] + assert PRIVATE not in repr(evidence) + + +@pytest.mark.parametrize( + ("commit", "earlier"), + [ + (FAILED_COMMIT[:12], []), + (FAILED_COMMIT.upper(), []), + ("f" * 64, []), + ("g" * 40, []), + (FAILED_COMMIT, [HEALTHY_COMMIT[:7]]), + (FAILED_COMMIT, [FAILED_COMMIT]), + (FAILED_COMMIT, [HEALTHY_COMMIT, HEALTHY_COMMIT]), + (FAILED_COMMIT, HEALTHY_COMMIT), + (FAILED_COMMIT, [f"{index:040x}" for index in range(MAX_EARLIER_COMMITS + 1)]), + ], +) +def test_trail_commits_refuse_anything_but_distinct_full_lowercase_shas( + commit: str, earlier: Any +) -> None: + with pytest.raises(ValueError): + trail_commits(commit, earlier) + + +def test_trail_commits_keep_the_given_order_up_to_the_bound() -> None: + assert trail_commits(FAILED_COMMIT, [*MIDDLE_COMMITS, HEALTHY_COMMIT]) == ( + FAILED_COMMIT, + *MIDDLE_COMMITS, + HEALTHY_COMMIT, + ) + bound = [f"{index:040x}" for index in range(MAX_EARLIER_COMMITS)] + assert trail_commits(FAILED_COMMIT, bound) == (FAILED_COMMIT, *bound) + + +def test_trail_gap_detaches_the_failed_read() -> None: + try: + try: + raise ValueError(PRIVATE) + except ValueError: + raise ProoflineError(0, "urn:proofline:sdk:invalid-response", "static") from None + except ProoflineError as error: + gap = TrailGap(FAILED_COMMIT, "DEPLOYS_UNAVAILABLE", error) + assert gap.error is not None + assert gap.error.__traceback__ is None + assert gap.error.__context__ is None + assert PRIVATE not in repr(gap) + + +def test_trail_types_are_public() -> None: + for name in ("CommitEvidence", "FailedDeployTrail", "TrailGap"): + assert name in proofline.__all__ + assert getattr(proofline, name) is getattr(trail, name)