From 4a5f4d2fb799699b51aedc9047cd68adbf86611b Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 17:49:49 +0530 Subject: [PATCH 1/7] feat: add failed-deploy trail result types and selection rules Co-authored-by: Cursor --- proofline/trail.py | 151 +++++++++++++++++++++++++++++++++++++++++ tests/fixtures.py | 45 ++++++++++++ tests/test_trail.py | 162 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 358 insertions(+) create mode 100644 proofline/trail.py create mode 100644 tests/test_trail.py diff --git a/proofline/trail.py b/proofline/trail.py new file mode 100644 index 00000000..c4bd0497 --- /dev/null +++ b/proofline/trail.py @@ -0,0 +1,151 @@ +"""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) + + +@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(page: ReviewPage, commit_sha: str) -> list[ReviewSummary]: + # A review is evidence only for the head commit it is pinned to. + return [ + summary + for summary in page.items + if isinstance(summary.head_commit_sha, str) + and summary.head_commit_sha.lower() == commit_sha + ] + + +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/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_trail.py b/tests/test_trail.py new file mode 100644 index 00000000..c96570ab --- /dev/null +++ b/tests/test_trail.py @@ -0,0 +1,162 @@ +"""Selection rules of the failed-deploy trail, without HTTP.""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from proofline import models +from proofline.trail import ( + MAX_EARLIER_COMMITS, + commit_evidence, + commit_reviews, + failed_deploy, + failing_check, + healthy_deploy, + trail_commits, +) + +from .fixtures import ( + DEPLOY_ENVIRONMENT, + FAILED_COMMIT, + HEALTHY_COMMIT, + MIDDLE_COMMITS, + OTHER_DEPLOY_ENVIRONMENT, + PRIVATE, + 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(), "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_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) From 5133d72c17ef89473125180a73109e46dd0c5915 Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 17:52:05 +0530 Subject: [PATCH 2/7] feat: add failed_deploy_trail to the sync and async clients Co-authored-by: Cursor --- proofline/client.py | 199 +++++++++++++++++++++++++++++++- scripts/contracts.py | 9 +- tests/test_http.py | 267 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 472 insertions(+), 3 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..dcf465d8 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,96 @@ 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, + ) -> FailedDeployTrail: + """Collect the evidence around a commit whose deploy failed. + + earlier_commits names the commits before commit_sha, newest first, such as + the output of `git rev-list --first-parent -n 50 ~1`. The API + lists no commit history, so the last healthy deploy is looked up only among + them. A read that fails becomes a gap in the trail instead of an exception. + """ + commits = trail_commits(commit_sha, earlier_commits) + 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] = [] + try: + page = self.list_reviews(organization_id, repository=repository_id, search=sha) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + else: + if page.truncated is True: + gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) + for summary in commit_reviews(page, 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), + ) + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -968,3 +1071,97 @@ 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, + ) -> FailedDeployTrail: + """Collect the evidence around a commit whose deploy failed. + + earlier_commits names the commits before commit_sha, newest first, such as + the output of `git rev-list --first-parent -n 50 ~1`. The API + lists no commit history, so the last healthy deploy is looked up only among + them. A read that fails becomes a gap in the trail instead of an exception. + """ + commits = trail_commits(commit_sha, earlier_commits) + 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] = [] + try: + page = await self.list_reviews( + organization_id, repository=repository_id, search=sha + ) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + else: + if page.truncated is True: + gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) + for summary in commit_reviews(page, 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), + ) 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/test_http.py b/tests/test_http.py index 0af9d60f..d4208ac4 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,258 @@ 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 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"} + return routes[f"reviews?search={query['search'][0]}"] + 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) + search = parse_qs(parts.query).get("search") + paths.append(f"reviews?search={search[0]}" if search else 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"), + ) + ), + f"reviews?search={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} + ), + f"reviews?search={middle}": Reply(body=commit_page()), + f"reviews?search={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] == ["PR", "DEPLOYMENT"] + 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), + f"reviews?search={FAILED_COMMIT}", + f"/api/v1/organizations/{ORG}/reviews/{REVIEW}", + f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment", + f"reviews?search={middle}", + f"reviews?search={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), + f"reviews?search={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} + ), + f"reviews?search={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, "REVIEW_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, + 500, + 404, + ] + assert trail.gaps[1].error.detail == f"{PRIVATE} [redacted]" + assert PRIVATE not in repr(trail) + assert TOKEN not in repr(trail) + assert trail_requests(server) == [ + deploys_path(FAILED_COMMIT), + deploys_path(middle), + f"reviews?search={FAILED_COMMIT}", + f"/api/v1/organizations/{ORG}/reviews/{REVIEW}", + f"reviews?search={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, + f"reviews?search={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), + f"reviews?search={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 in [ + (FAILED_COMMIT[:12], []), + (FAILED_COMMIT.upper(), []), + (FAILED_COMMIT, [FAILED_COMMIT]), + ]: + with pytest.raises(ValueError): + await call( + client, + "failed_deploy_trail", + ORG, + REPOSITORY, + commit, + earlier_commits=earlier, + ) + assert server.requests == [] From d3898f4742d62fbe361c2a91d92c7cc78e162ed8 Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 17:52:45 +0530 Subject: [PATCH 3/7] feat: export the failed-deploy trail types Co-authored-by: Cursor --- proofline/__init__.py | 4 ++++ tests/test_trail.py | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) 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/tests/test_trail.py b/tests/test_trail.py index c96570ab..c610dda0 100644 --- a/tests/test_trail.py +++ b/tests/test_trail.py @@ -6,7 +6,8 @@ import pytest -from proofline import models +import proofline +from proofline import models, trail from proofline.trail import ( MAX_EARLIER_COMMITS, commit_evidence, @@ -160,3 +161,9 @@ def test_trail_commits_keep_the_given_order_up_to_the_bound() -> None: ) bound = [f"{index:040x}" for index in range(MAX_EARLIER_COMMITS)] assert trail_commits(FAILED_COMMIT, bound) == (FAILED_COMMIT, *bound) + + +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) From 988889788a25ef05f39886e6ad76c9df046c2343 Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 18:19:22 +0530 Subject: [PATCH 4/7] fix: detach failed-read errors held by trail gaps Co-authored-by: Cursor --- proofline/trail.py | 6 ++++++ tests/test_http.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ tests/test_trail.py | 17 ++++++++++++++++- 3 files changed, 67 insertions(+), 1 deletion(-) diff --git a/proofline/trail.py b/proofline/trail.py index c4bd0497..6077a754 100644 --- a/proofline/trail.py +++ b/proofline/trail.py @@ -43,6 +43,12 @@ class TrailGap: 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: diff --git a/tests/test_http.py b/tests/test_http.py index d4208ac4..5e3ab7d2 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2771,6 +2771,10 @@ async def test_failed_deploy_trail_keeps_partial_evidence_when_reads_fail(mode: 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) == [ @@ -2851,3 +2855,44 @@ async def test_failed_deploy_trail_refuses_invalid_commits_before_any_request(mo earlier_commits=earlier, ) 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()), + f"reviews?search={FAILED_COMMIT}": Reply(body=commit_page()), + f"reviews?search={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)) diff --git a/tests/test_trail.py b/tests/test_trail.py index c610dda0..634e4e47 100644 --- a/tests/test_trail.py +++ b/tests/test_trail.py @@ -7,9 +7,10 @@ import pytest import proofline -from proofline import models, trail +from proofline import ProoflineError, models, trail from proofline.trail import ( MAX_EARLIER_COMMITS, + TrailGap, commit_evidence, commit_reviews, failed_deploy, @@ -163,6 +164,20 @@ def test_trail_commits_keep_the_given_order_up_to_the_bound() -> None: 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__ From 06f801fe527482caea357fd05eb8b76f395ea927 Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 18:21:19 +0530 Subject: [PATCH 5/7] feat: bound failed_deploy_trail with an overall timeout Co-authored-by: Cursor --- proofline/client.py | 286 +++++++++++++++++++++++--------------------- tests/test_http.py | 62 +++++++++- 2 files changed, 209 insertions(+), 139 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index dcf465d8..c94dd561 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -604,6 +604,7 @@ def failed_deploy_trail( *, earlier_commits: Sequence[str] = (), environment_id: UUID | None = None, + timeout: float = 120, ) -> FailedDeployTrail: """Collect the evidence around a commit whose deploy failed. @@ -612,79 +613,87 @@ def failed_deploy_trail( lists no commit history, so the last healthy deploy is looked up only among them. A read that fails becomes a gap in the trail instead of an exception. """ + 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) - 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 + deadline = _transport.DEADLINE.set(monotonic() + timeout) 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] = [] + 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: - page = self.list_reviews(organization_id, repository=repository_id, search=sha) + verifications = self.get_commit_deploy_verifications( + organization_id, repository_id, commit_sha + ) except ProoflineError as error: - gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + gaps.append(TrailGap(commit_sha, "DEPLOYS_UNAVAILABLE", error)) + walked.append((commit_sha, ())) else: - if page.truncated is True: - gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) - for summary in commit_reviews(page, sha): + 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: - if summary.kind == "DEPLOYMENT": - detail = self.get_deployment_review(organization_id, summary.public_key) - else: - detail = self.get_review(organization_id, summary.id) + earlier = self.get_commit_deploy_verifications( + organization_id, repository_id, sha + ) 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), - ) + # 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] = [] + try: + page = self.list_reviews(organization_id, repository=repository_id, search=sha) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + else: + if page.truncated is True: + gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) + for summary in commit_reviews(page, 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): @@ -1080,6 +1089,7 @@ async def failed_deploy_trail( *, earlier_commits: Sequence[str] = (), environment_id: UUID | None = None, + timeout: float = 120, ) -> FailedDeployTrail: """Collect the evidence around a commit whose deploy failed. @@ -1088,80 +1098,86 @@ async def failed_deploy_trail( lists no commit history, so the last healthy deploy is looked up only among them. A read that fails becomes a gap in the trail instead of an exception. """ + 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) - 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 + deadline = _transport.DEADLINE.set(monotonic() + timeout) 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] = [] + 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: - page = await self.list_reviews( - organization_id, repository=repository_id, search=sha + verifications = await self.get_commit_deploy_verifications( + organization_id, repository_id, commit_sha ) except ProoflineError as error: - gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + gaps.append(TrailGap(commit_sha, "DEPLOYS_UNAVAILABLE", error)) + walked.append((commit_sha, ())) else: - if page.truncated is True: - gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) - for summary in commit_reviews(page, sha): + 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: - 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) + earlier = await self.get_commit_deploy_verifications( + organization_id, repository_id, sha + ) 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), - ) + # 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] = [] + try: + page = await self.list_reviews( + organization_id, repository=repository_id, search=sha + ) + except ProoflineError as error: + gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) + else: + if page.truncated is True: + gaps.append(TrailGap(sha, "REVIEWS_TRUNCATED")) + for summary in commit_reviews(page, 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/tests/test_http.py b/tests/test_http.py index 5e3ab7d2..41a963fc 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2840,10 +2840,13 @@ async def test_failed_deploy_trail_without_a_failed_deploy_reads_no_earlier_comm 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 in [ - (FAILED_COMMIT[:12], []), - (FAILED_COMMIT.upper(), []), - (FAILED_COMMIT, [FAILED_COMMIT]), + 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( @@ -2853,6 +2856,7 @@ async def test_failed_deploy_trail_refuses_invalid_commits_before_any_request(mo REPOSITORY, commit, earlier_commits=earlier, + **extra, ) assert server.requests == [] @@ -2896,3 +2900,53 @@ async def test_failed_deploy_trail_turns_a_malformed_body_into_a_gap(mode: str) 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"), + (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", + ] + assert len(server.requests) == 2 + assert later not in "".join(request.path for request in server.requests) From 7d5150644f2f79aac3946626884e4d423976bbe2 Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 18:24:00 +0530 Subject: [PATCH 6/7] feat: look up each commit's deployment review explicitly Co-authored-by: Cursor --- proofline/client.py | 78 +++++++++++++------------ proofline/trail.py | 19 +++--- tests/test_http.py | 138 +++++++++++++++++++++++++++++++++++++------- tests/test_trail.py | 30 +++++++++- 4 files changed, 197 insertions(+), 68 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index c94dd561..57e385d9 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -663,25 +663,28 @@ def failed_deploy_trail( evidence: list[CommitEvidence] = [] for sha, deploys in walked: reviews: list[CustomerReviewDetail] = [] - try: - page = self.list_reviews(organization_id, repository=repository_id, search=sha) - except ProoflineError as error: - gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) - else: + 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")) - for summary in commit_reviews(page, 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) + 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, @@ -1148,27 +1151,30 @@ async def failed_deploy_trail( evidence: list[CommitEvidence] = [] for sha, deploys in walked: reviews: list[CustomerReviewDetail] = [] - try: - page = await self.list_reviews( - organization_id, repository=repository_id, search=sha - ) - except ProoflineError as error: - gaps.append(TrailGap(sha, "REVIEWS_UNAVAILABLE", error)) - else: + 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")) - for summary in commit_reviews(page, 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) + 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, diff --git a/proofline/trail.py b/proofline/trail.py index 6077a754..8db5f49c 100644 --- a/proofline/trail.py +++ b/proofline/trail.py @@ -133,14 +133,17 @@ def _task(deploy: CommitDeploy) -> str | None: return deploy.deployment_task if isinstance(deploy.deployment_task, str) else None -def commit_reviews(page: ReviewPage, commit_sha: str) -> list[ReviewSummary]: - # A review is evidence only for the head commit it is pinned to. - return [ - summary - for summary in page.items - if isinstance(summary.head_commit_sha, str) - and summary.head_commit_sha.lower() == commit_sha - ] +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( diff --git a/tests/test_http.py b/tests/test_http.py index 41a963fc..b60b75b5 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2605,6 +2605,13 @@ def deploys_path(commit: str) -> str: ) +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: @@ -2614,8 +2621,9 @@ def respond(request: Request, index: int) -> Reply: if parts.path == f"/api/v1/organizations/{ORG}/reviews": query = parse_qs(parts.query) assert query["repository"] == [str(REPOSITORY)] - assert set(query) == {"repository", "search"} - return routes[f"reviews?search={query['search'][0]}"] + 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 @@ -2625,8 +2633,13 @@ def trail_requests(server: Server) -> list[str]: paths: list[str] = [] for request in server.requests: parts = urlsplit(request.path) - search = parse_qs(parts.query).get("search") - paths.append(f"reviews?search={search[0]}" if search else parts.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 @@ -2666,9 +2679,8 @@ async def test_failed_deploy_trail_collects_failing_check_healthy_commit_and_ran deploy("VERIFIED_UNTIL_SUPERSEDED"), ) ), - f"reviews?search={FAILED_COMMIT}": Reply( - body=commit_page(pull_request, deployment, elsewhere) - ), + 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(), @@ -2679,8 +2691,10 @@ async def test_failed_deploy_trail_collects_failing_check_healthy_commit_and_ran f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment": Reply( body={**review(), **deployment} ), - f"reviews?search={middle}": Reply(body=commit_page()), - f"reviews?search={unrecorded}": Reply(body=commit_page()), + 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: @@ -2700,7 +2714,7 @@ async def test_failed_deploy_trail_collects_failing_check_healthy_commit_and_ran 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] == ["PR", "DEPLOYMENT"] + 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) == ((), (), ()) @@ -2709,11 +2723,14 @@ async def test_failed_deploy_trail_collects_failing_check_healthy_commit_and_ran deploys_path(middle), deploys_path(unrecorded), deploys_path(HEALTHY_COMMIT), - f"reviews?search={FAILED_COMMIT}", - f"/api/v1/organizations/{ORG}/reviews/{REVIEW}", + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), f"/api/v1/organizations/{ORG}/reviews/deployments/rev_deployment", - f"reviews?search={middle}", - f"reviews?search={unrecorded}", + 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) @@ -2730,13 +2747,19 @@ async def test_failed_deploy_trail_keeps_partial_evidence_when_reads_fail(mode: routes = { deploys_path(FAILED_COMMIT): Reply(body=verifications(deploy("FAILED", results=()))), deploys_path(middle): Reply(403, refused), - f"reviews?search={FAILED_COMMIT}": Reply( + 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} ), - f"reviews?search={middle}": Reply( + 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."} ), } @@ -2759,16 +2782,20 @@ async def test_failed_deploy_trail_keeps_partial_evidence_when_reads_fail(mode: (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: @@ -2780,9 +2807,11 @@ async def test_failed_deploy_trail_keeps_partial_evidence_when_reads_fail(mode: assert trail_requests(server) == [ deploys_path(FAILED_COMMIT), deploys_path(middle), - f"reviews?search={FAILED_COMMIT}", + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), f"/api/v1/organizations/{ORG}/reviews/{REVIEW}", - f"reviews?search={middle}", + reviews_route(middle, "DEPLOYMENT"), + reviews_route(middle), ] @@ -2813,7 +2842,8 @@ async def test_failed_deploy_trail_without_a_failed_deploy_reads_no_earlier_comm ) -> None: routes = { deploys_path(FAILED_COMMIT): reply, - f"reviews?search={FAILED_COMMIT}": Reply(body=commit_page()), + 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: @@ -2832,7 +2862,8 @@ async def test_failed_deploy_trail_without_a_failed_deploy_reads_no_earlier_comm assert [(gap.commit_sha, gap.reason) for gap in trail.gaps] == [(FAILED_COMMIT, reason)] assert trail_requests(server) == [ deploys_path(FAILED_COMMIT), - f"reviews?search={FAILED_COMMIT}", + reviews_route(FAILED_COMMIT, "DEPLOYMENT"), + reviews_route(FAILED_COMMIT), ] @@ -2875,8 +2906,10 @@ async def test_failed_deploy_trail_turns_a_malformed_body_into_a_gap(mode: str) ) ), deploys_path(middle): Reply(body=f"not json {PRIVATE}".encode()), - f"reviews?search={FAILED_COMMIT}": Reply(body=commit_page()), - f"reviews?search={middle}": Reply(body=commit_page()), + 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: @@ -2940,6 +2973,8 @@ def respond(request: Request, index: int) -> Reply: (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] == [ @@ -2947,6 +2982,65 @@ def respond(request: Request, index: int) -> Reply: 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 index 634e4e47..2b7a704e 100644 --- a/tests/test_trail.py +++ b/tests/test_trail.py @@ -21,11 +21,13 @@ from .fixtures import ( DEPLOY_ENVIRONMENT, + DEPLOYMENT_REVIEW, FAILED_COMMIT, HEALTHY_COMMIT, MIDDLE_COMMITS, OTHER_DEPLOY_ENVIRONMENT, PRIVATE, + REVIEW, assessment, code_assessment, commit_page, @@ -105,16 +107,40 @@ 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(), "head_commit_sha": FAILED_COMMIT.upper()}, + {**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) + 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( { From a61626f69e71fded09ab636535454cfb7344c74a Mon Sep 17 00:00:00 2001 From: shrijacked Date: Fri, 27 Nov 2026 18:24:44 +0530 Subject: [PATCH 7/7] docs: state failed_deploy_trail rules in its docstrings Co-authored-by: Cursor --- proofline/client.py | 34 ++++++++++++++++++++++++++-------- 1 file changed, 26 insertions(+), 8 deletions(-) diff --git a/proofline/client.py b/proofline/client.py index 57e385d9..9b495892 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -608,10 +608,19 @@ def failed_deploy_trail( ) -> FailedDeployTrail: """Collect the evidence around a commit whose deploy failed. - earlier_commits names the commits before commit_sha, newest first, such as - the output of `git rev-list --first-parent -n 50 ~1`. The API - lists no commit history, so the last healthy deploy is looked up only among - them. A read that fails becomes a gap in the trail instead of an exception. + 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.") @@ -1096,10 +1105,19 @@ async def failed_deploy_trail( ) -> FailedDeployTrail: """Collect the evidence around a commit whose deploy failed. - earlier_commits names the commits before commit_sha, newest first, such as - the output of `git rev-list --first-parent -n 50 ~1`. The API - lists no commit history, so the last healthy deploy is looked up only among - them. A read that fails becomes a gap in the trail instead of an exception. + 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.")