From 7d66d2c43ddf94bde0518696dc436b8b6e978475 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 24 Nov 2026 16:44:11 +0530 Subject: [PATCH] feat: add gate_review to measure a review against a severity threshold Ports the CLI's ci review --fail-on rule to the Python SDK: completeness decides first, then the server's open-finding counts, then a complete CODE assessment's own findings by lifecycle and severity. Refactors _code_assessment into _recorded_code (validation only) and _code_assessment (adds the assessment_count guard), matching the TypeScript SDK's recordedCode/codeAssessment split so gate_review can read CODE findings beside complete environments. --- README.md | 24 ++++ proofline/__init__.py | 3 + proofline/gate.py | 95 ++++++++++++++++ proofline/outcomes.py | 13 ++- tests/test_gate.py | 253 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 384 insertions(+), 4 deletions(-) create mode 100644 proofline/gate.py create mode 100644 tests/test_gate.py diff --git a/README.md b/README.md index 721949da..e122f6e0 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,30 @@ if outcome.status != "COMPLETED": `head_commit_sha` is a full SHA of 40 or 64 hexadecimal characters; any other value raises `ValueError` before a request. A review pinned to another head ends the wait on the read that names it. Its outcome is `INCOMPLETE` whatever the review's own status, its last gap has the reason code `HEAD_COMMIT_MISMATCH`, and `reason` says that the review is pinned to another head commit. A settled review that names no head has `HEAD_COMMIT_UNAVAILABLE` instead and is not `COMPLETED` either. `outcome.review.head_commit_sha` is the commit the review is pinned to. A patch review's head is a derived revision ID, so no commit matches it. In a GitHub Actions `pull_request` job, `GITHUB_SHA` is the merge commit; pass the pull request's head. +## Failing a job on open findings + +`gate_review(outcome, *, fail_on)` measures a `ReviewOutcome` against a `WARNING` or `SERIOUS` threshold with the rules of `proofline ci review --fail-on`, so a Python pipeline fails the same way the CLI does. + +```python +import sys +from proofline import ProoflineClient, gate_review + +with ProoflineClient() as client: + requested = client.request_review(organization_id, repository_id, 12) + outcome = client.wait_for_review(organization_id, requested.review_id) + result = gate_review(outcome, fail_on="SERIOUS") + if result != "NOT_REACHED": + print(f"Proofline: {result}, {outcome.review_url}") + sys.exit({"REACHED": 3, "NOT_COMPLETE": 2, "UNAVAILABLE": 4}[result]) +``` + +- `REACHED`: the completed review has an open finding at or above the threshold. +- `NOT_REACHED`: the completed review has none. +- `NOT_COMPLETE`: the review is incomplete, failed, or stopped, whatever it found. +- `UNAVAILABLE`: the wait timed out, or the completed review lacks valid open-finding counts, so the threshold cannot be measured. + +The server counts open findings from their current decisions, so dismissed findings and unexpired risk acceptances do not count. A code-only finding counts while it is not `RESOLVED` and its complete CODE assessment is of the review's own commits. A severity the SDK does not know reaches every threshold. The exit codes above are the CLI's. The threshold is the caller's and applies to any review; it is separate from the server's opt-in `merge_gate` decision. + ## Review exports `export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`. diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..ca83db76 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -35,6 +35,7 @@ from ._transport import ProoflineError, RunNowRefusal from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters from .exports import ExportDataset, ExportFormat, ExportPage +from .gate import GateResult, gate_review from .knowledge import KnowledgeResult from .outcomes import AssessmentGap, CheckGap, ReviewOutcome @@ -56,6 +57,8 @@ "ExportPage", "FileReviewRequest", "FileReviewResponse", + "GateResult", + "gate_review", "KnowledgeResult", "PatchReviewRequest", "PatchReviewResponse", diff --git a/proofline/gate.py b/proofline/gate.py new file mode 100644 index 00000000..10370b95 --- /dev/null +++ b/proofline/gate.py @@ -0,0 +1,95 @@ +"""Measure a review outcome against a severity threshold. + +``gate_review`` applies the same rule as ``proofline ci review --fail-on`` +in the CLI: completeness decides first, then the server's open-finding counts, +then a complete CODE assessment's own findings by lifecycle and severity. +""" + +from __future__ import annotations + +from typing import Literal + +from ._generated.models.open_items_view import OpenItemsView +from .outcomes import ReviewOutcome, _recorded_code, text + +GateResult = Literal["REACHED", "NOT_REACHED", "NOT_COMPLETE", "UNAVAILABLE"] +SeverityThreshold = Literal["WARNING", "SERIOUS"] + +# Least severe first, matching ``Severity::as_str`` in the CLI's ``severity.rs``. +_SEVERITIES: tuple[str, ...] = ("WARNING", "SERIOUS") + + +def gate_review( + result: ReviewOutcome, + *, + fail_on: SeverityThreshold, +) -> GateResult: + """Measure ``result`` against a severity ``threshold``. + + Returns one of four verdicts that match the CLI's exit codes + (3, 0, 2, 4 respectively): + + - ``"REACHED"``: the completed review has an open finding at or above + the threshold. + - ``"NOT_REACHED"``: the completed review has none. + - ``"NOT_COMPLETE"``: the review is incomplete, failed, or stopped, + whatever it found. + - ``"UNAVAILABLE"``: the wait timed out, or the completed review lacks + valid open-finding counts, so the threshold cannot be measured. + + Raises ``ValueError`` if ``fail_on`` is not ``"WARNING"`` or ``"SERIOUS"``. + """ + if fail_on not in _SEVERITIES: + raise ValueError("fail_on must be WARNING or SERIOUS") + if result.status == "TIMED_OUT": + return "UNAVAILABLE" + if result.status != "COMPLETED": + return "NOT_COMPLETE" + review = result.review + if review is None: + return "UNAVAILABLE" + counts = review.open_items + if not isinstance(counts, OpenItemsView): + return "UNAVAILABLE" + if not _is_count(counts.open_findings) or not _is_count(counts.serious_findings): + return "UNAVAILABLE" + # The server counts open findings from their current decisions, so + # dismissed findings and unexpired risk acceptances do not count. + if fail_on == "SERIOUS": + if counts.serious_findings > 0: + return "REACHED" + else: + if counts.open_findings > 0: + return "REACHED" + # CODE findings have no projected decisions, so their lifecycle and + # severity decide. A partial CODE assessment's findings are not its + # whole result. + code = _recorded_code(review) + if ( + code is not None + and code.status == "COMPLETED" + and not text(code.incompleteness_kind) + and any( + finding.lifecycle_state != "RESOLVED" and _reaches(finding.severity, fail_on) + for finding in code.findings + ) + ): + return "REACHED" + return "NOT_REACHED" + + +def _is_count(value: object) -> bool: + """Whether ``value`` is a non-negative integer that is not a bool.""" + return isinstance(value, int) and not isinstance(value, bool) and value >= 0 + + +def _reaches(severity: object, threshold: SeverityThreshold) -> bool: + """Whether ``severity`` is at or above ``threshold``. + + An unknown severity, which a newer server can send, is never read as + below a threshold. + """ + if not isinstance(severity, str): + return True + index = _SEVERITIES.index(severity) if severity in _SEVERITIES else -1 + return index < 0 or index >= _SEVERITIES.index(threshold) diff --git a/proofline/outcomes.py b/proofline/outcomes.py index fa363b32..4f236b78 100644 --- a/proofline/outcomes.py +++ b/proofline/outcomes.py @@ -76,10 +76,8 @@ def _optional_texts(value: object) -> bool: ) -def _code_assessment(review: CustomerReviewDetail) -> CustomerCodeAssessment | None: - # A CODE result cannot replace a missing ENV result or its check receipts. - if review.assessment_count != 0 or review.assessments: - return None +def _recorded_code(review: CustomerReviewDetail) -> CustomerCodeAssessment | None: + # The CODE record of this review's own commits with published findings. code = review.code_assessment if ( not isinstance(code, CustomerCodeAssessment) @@ -103,6 +101,13 @@ def _code_assessment(review: CustomerReviewDetail) -> CustomerCodeAssessment | N return code +def _code_assessment(review: CustomerReviewDetail) -> CustomerCodeAssessment | None: + # A CODE result cannot replace a missing ENV result or its check receipts. + if review.assessment_count != 0 or review.assessments: + return None + return _recorded_code(review) + + def _validate(review: CustomerReviewDetail, review_id: UUID | None) -> None: if ( not isinstance(review.id, UUID) diff --git a/tests/test_gate.py b/tests/test_gate.py new file mode 100644 index 00000000..f0080112 --- /dev/null +++ b/tests/test_gate.py @@ -0,0 +1,253 @@ +"""Tests for ``gate_review`` — the CI gating rule. + +These tests port the CLI's ``ci_verdict`` test table and the TypeScript +SDK's ``gateReview`` tests. They build ``ReviewOutcome`` objects directly +from synthetic review data and measure them against WARNING and SERIOUS +thresholds. +""" + +from __future__ import annotations + +from typing import Any +from uuid import UUID + +import pytest + +from proofline import gate_review +from proofline.outcomes import ReviewOutcome, outcome + +ORG = UUID("00000000-0000-4000-8000-000000000001") +REVIEW_ID = UUID("00000000-0000-4000-8000-000000000003") +ASSESSMENT_ID = UUID("00000000-0000-4000-8000-000000000004") +CODE_ID = UUID("00000000-0000-4000-8000-000000000006") +URL = "https://proofline.sh/orgs/by-id/" + str(ORG) + "/reviews/" + str(REVIEW_ID) + + +def _counts(open_findings: int = 0, serious_findings: int = 0) -> dict[str, Any]: + return { + "accepted_risks": 0, + "not_assessed": [], + "open_findings": open_findings, + "serious_findings": serious_findings, + } + + +def _assessment(status: str = "COMPLETED") -> dict[str, Any]: + return { + "id": str(ASSESSMENT_ID), + "environment_display_name": "production", + "status": status, + "domains": [], + "findings": [], + "checks": {"families": [], "receipt_recorded": True, "status": "READY"}, + } + + +def _review( + status: str = "COMPLETED", + extra: dict[str, Any] | None = None, + assessments: list[dict[str, Any]] | None = None, +) -> dict[str, Any]: + if assessments is None: + assessments = [_assessment()] + base: dict[str, Any] = { + "id": str(REVIEW_ID), + "public_key": "rev_" + str(REVIEW_ID).replace("-", ""), + "kind": "PULL_REQUEST", + "status": status, + "assessment_count": len(assessments), + "environment_display_names": ["production"], + "finding_count": 0, + "trigger_origin": "MANUAL", + "publication": "WITHHELD", + "created_at": "2026-09-30T12:00:00Z", + "stoppable": False, + "related_reviews": [], + "subjects": [], + "assessments": assessments, + "actions": { + "promote_findings": False, + "publish": False, + "rerun": False, + "stop": False, + "validate_findings": False, + }, + "head_commit_sha": "a" * 40, + "base_commit_sha": "b" * 40, + } + if extra: + base.update(extra) + return base + + +def _code_assessment( + findings: list[dict[str, Any]], + status: str = "COMPLETED", + extra: dict[str, Any] | None = None, +) -> dict[str, Any]: + base: dict[str, Any] = { + "id": str(CODE_ID), + "status": status, + "head_commit_sha": "a" * 40, + "base_commit_sha": "b" * 40, + "incompleteness_kind": None, + "findings": findings, + } + if extra: + base.update(extra) + return base + + +def _code_finding(severity: str, lifecycle_state: str = "NEW") -> dict[str, Any]: + return { + "id": str(CODE_ID), + "severity": severity, + "risk_domain": "code", + "claim": "claim", + "impact": "impact", + "lifecycle_state": lifecycle_state, + "evidence_refs": [], + "rule_refs": [], + "symbols": [], + "comment_reactions": [], + } + + +def _outcome(body: dict[str, Any]) -> ReviewOutcome: + """Build a real ReviewOutcome from synthetic review JSON.""" + from proofline._generated.models.customer_review_detail import CustomerReviewDetail + + review = CustomerReviewDetail.from_dict(body) + result = outcome(review, URL, review_id=REVIEW_ID) + assert result is not None + return result + + +# --- Completeness decides before the open-finding counts --- + + +def test_completeness_decides_before_open_finding_counts() -> None: + serious = {"open_items": _counts(1, 1)} + completed = _outcome(_review("COMPLETED", serious)) + assert completed.status == "COMPLETED" + assert gate_review(completed, fail_on="SERIOUS") == "REACHED" + + incomplete = _outcome(_review("COMPLETED", serious, [_assessment("INCOMPLETE")])) + assert incomplete.status == "INCOMPLETE" + assert gate_review(incomplete, fail_on="SERIOUS") == "NOT_COMPLETE" + + for status in ("INCOMPLETE", "FAILED", "STOPPED"): + result = _outcome(_review(status, serious)) + assert gate_review(result, fail_on="SERIOUS") == "NOT_COMPLETE", status + + # A gap decides before the missing counts do. + gap = _outcome(_review("COMPLETED", {"open_items": None}, [_assessment("INCOMPLETE")])) + assert gate_review(gap, fail_on="WARNING") == "NOT_COMPLETE" + + +def test_timed_out_is_unavailable() -> None: + timed_out = ReviewOutcome("TIMED_OUT", URL, review=None) + assert gate_review(timed_out, fail_on="WARNING") == "UNAVAILABLE" + + +def test_no_review_is_unavailable() -> None: + no_review = ReviewOutcome("COMPLETED", URL, review=None) + assert gate_review(no_review, fail_on="WARNING") == "UNAVAILABLE" + + +# --- A completed review is measured by the server's open-finding counts --- + + +@pytest.mark.parametrize( + ("open_items", "fail_on", "expected"), + [ + (_counts(1, 1), "WARNING", "REACHED"), + (_counts(1, 1), "SERIOUS", "REACHED"), + (_counts(1, 0), "WARNING", "REACHED"), + (_counts(1, 0), "SERIOUS", "NOT_REACHED"), + (_counts(0, 0), "WARNING", "NOT_REACHED"), + (_counts(0, 0), "SERIOUS", "NOT_REACHED"), + # A threshold that cannot be measured is never NOT_REACHED. + (None, "WARNING", "UNAVAILABLE"), + ({"open_findings": 0}, "WARNING", "UNAVAILABLE"), + (_counts("0", 0), "WARNING", "UNAVAILABLE"), # type: ignore[arg-type] + (_counts(0, -1), "SERIOUS", "UNAVAILABLE"), + (_counts(0.5, 0), "WARNING", "UNAVAILABLE"), # type: ignore[arg-type] + (_counts(True, 0), "WARNING", "UNAVAILABLE"), # type: ignore[arg-type] + ], +) +def test_completed_review_measured_by_open_finding_counts( + open_items: Any, fail_on: str, expected: str +) -> None: + body = _review("COMPLETED", {"open_items": open_items}) + result = _outcome(body) + assert result.status == "COMPLETED" + assert gate_review(result, fail_on=fail_on) == expected # type: ignore[arg-type] + + +# --- Complete CODE findings of the review's own commits reach by lifecycle and severity --- + + +@pytest.mark.parametrize( + ("severity", "lifecycle", "fail_on", "expected"), + [ + ("SERIOUS", "NEW", "SERIOUS", "REACHED"), + ("SERIOUS", "UNCHANGED", "WARNING", "REACHED"), + ("WARNING", "NEW", "WARNING", "REACHED"), + ("WARNING", "NEW", "SERIOUS", "NOT_REACHED"), + ("SERIOUS", "RESOLVED", "SERIOUS", "NOT_REACHED"), + # A severity a newer server sends is never read as below a threshold. + ("CRITICAL", "NEW", "SERIOUS", "REACHED"), + ("NOTE", "NEW", "SERIOUS", "REACHED"), + ], +) +def test_code_findings_reach_by_lifecycle_and_severity( + severity: str, lifecycle: str, fail_on: str, expected: str +) -> None: + code = _code_assessment([_code_finding(severity, lifecycle)]) + case = f"{severity} {lifecycle} {fail_on}" + # Code-only review. + code_only = _outcome( + _review("COMPLETED", {"code_assessment": code, "open_items": _counts()}, []) + ) + assert code_only.status == "COMPLETED", case + assert gate_review(code_only, fail_on=fail_on) == expected, case + # Beside complete environments, as the CLI measures it. + beside = _outcome(_review("COMPLETED", {"code_assessment": code, "open_items": _counts()})) + assert gate_review(beside, fail_on=fail_on) == expected, case + + +# --- Partial or foreign CODE records supply no findings --- + + +def test_partial_or_foreign_code_records_supply_no_findings() -> None: + serious = [_code_finding("SERIOUS")] + for code in [ + _code_assessment(serious, "INCOMPLETE", {"incompleteness_kind": "MODEL_BUDGET_EXHAUSTED"}), + _code_assessment(serious, "COMPLETED", {"incompleteness_kind": "EVIDENCE_UNAVAILABLE"}), + _code_assessment(serious, "RUNNING"), + _code_assessment(serious, "COMPLETED", {"head_commit_sha": "c" * 40}), + _code_assessment(serious, "COMPLETED", {"base_commit_sha": "c" * 40}), + ]: + result = _outcome(_review("COMPLETED", {"code_assessment": code, "open_items": _counts()})) + assert result.status == "COMPLETED" + assert gate_review(result, fail_on="WARNING") == "NOT_REACHED" + # A code-only review with such a record is not complete. + code_only = _outcome( + _review( + "COMPLETED", + {"code_assessment": _code_assessment(serious, "RUNNING"), "open_items": _counts()}, + [], + ) + ) + assert gate_review(code_only, fail_on="WARNING") == "NOT_COMPLETE" + + +# --- An invalid threshold throws instead of measuring --- + + +@pytest.mark.parametrize("fail_on", ["warning", "CRITICAL", "INFO", "", "serious"]) +def test_invalid_threshold_raises_value_error(fail_on: str) -> None: + result = _outcome(_review("COMPLETED", {"open_items": _counts()})) + with pytest.raises(ValueError): + gate_review(result, fail_on=fail_on) # type: ignore[arg-type]