Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
3 changes: 3 additions & 0 deletions proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -56,6 +57,8 @@
"ExportPage",
"FileReviewRequest",
"FileReviewResponse",
"GateResult",
"gate_review",
"KnowledgeResult",
"PatchReviewRequest",
"PatchReviewResponse",
Expand Down
95 changes: 95 additions & 0 deletions proofline/gate.py
Original file line number Diff line number Diff line change
@@ -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)
13 changes: 9 additions & 4 deletions proofline/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
Loading