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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,17 @@ outcome = client.wait_for_review(
organization_id,
requested.review_id,
head_commit_sha=head_commit_sha,
on_poll=lambda detail: print(detail.status),
)
if outcome.status != "COMPLETED":
print(outcome.status, outcome.reason)
print(outcome.status, outcome.reason, outcome.gap_codes)
for gap in outcome.gaps:
print(gap.environment, [(item.domain, item.status) for item in gap.domains])
for item in outcome.recorded_findings(severity="SERIOUS", unresolved_only=True):
print(item.environment_display_name, item.finding.claim)
```

`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.
`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. Pass `poll_interval`, `max_poll_interval`, or `on_poll` to observe non-terminal polls before sleeping, and call `outcome.recorded_findings(...)` to inspect findings with their assessment provenance (`code_assessment` is used only when `assessment_count == 0`). Each gap names the environment it came from, and `outcome.environments` lists those distinct names in recorded order. A gap also carries the assessment's risk-domain coverage in `gap.domains` (`CONSIDERED` or `SKIPPED` with the recorded reason), and each unresolved check carries the files the evaluator cited in `check.files`, each with the revision it was read at, plus `check.evaluated_at`.

## Review exports

Expand Down
4 changes: 3 additions & 1 deletion proofline/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from .client import AsyncProoflineClient, ProoflineClient, ReviewFilters
from .exports import ExportDataset, ExportFormat, ExportPage
from .knowledge import KnowledgeResult
from .outcomes import AssessmentGap, CheckGap, ReviewOutcome
from .outcomes import AssessmentGap, CheckGap, DomainCoverage, RecordedFinding, ReviewOutcome

__all__ = [
"AgentSession",
Expand All @@ -51,6 +51,7 @@
"CustomerAssessmentDetail",
"CustomerFinding",
"CustomerReviewDetail",
"DomainCoverage",
"ExportDataset",
"ExportFormat",
"ExportPage",
Expand All @@ -62,6 +63,7 @@
"PatchTriggerSource",
"ProoflineClient",
"ProoflineError",
"RecordedFinding",
"RepositoryGuidance",
"RepositoryNames",
"RerunResponse",
Expand Down
65 changes: 53 additions & 12 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import inspect
import math
from asyncio import sleep as async_sleep
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
Expand Down Expand Up @@ -163,6 +164,29 @@ def _head_commit(value: str | None) -> None:
raise ValueError("The head commit must be a full 40 or 64 character hexadecimal SHA.")


def _wait_limits(
timeout: float,
head_commit_sha: str | None,
poll_interval: float,
max_poll_interval: float,
) -> None:
if isinstance(timeout, bool) or not math.isfinite(timeout) or timeout < 0:
raise ValueError("The review timeout must be a finite nonnegative number of seconds.")
if (
isinstance(poll_interval, bool)
or isinstance(max_poll_interval, bool)
or not math.isfinite(poll_interval)
or not math.isfinite(max_poll_interval)
or poll_interval <= 0
or max_poll_interval < poll_interval
):
raise ValueError(
"Polling intervals must be finite positive numbers "
"with max_poll_interval >= poll_interval."
)
_head_commit(head_commit_sha)


def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None:
if not isinstance(page.truncated, bool):
raise _transport.invalid_response()
Expand Down Expand Up @@ -546,6 +570,9 @@ def wait_for_review(
*,
timeout: float = 300,
head_commit_sha: str | None = None,
poll_interval: float = 5.0,
max_poll_interval: float = 60.0,
on_poll: Callable[[CustomerReviewDetail], object] | None = None,
) -> ReviewOutcome:
"""Wait for recorded review completion or return TIMED_OUT.

Expand All @@ -554,15 +581,16 @@ def wait_for_review(

head_commit_sha holds the outcome to that commit. A review pinned to
another head ends the wait on that read and is never COMPLETED.

on_poll runs after each non-terminal poll while waiting, receiving the
latest CustomerReviewDetail before sleeping.
"""

if not math.isfinite(timeout) or timeout < 0:
raise ValueError("The review timeout must be a finite nonnegative number of seconds.")
_head_commit(head_commit_sha)
_wait_limits(timeout, head_commit_sha, poll_interval, max_poll_interval)
url = _review_url(self._base_url, organization_id, review_id)
last: CustomerReviewDetail | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
interval = 5.0
interval = float(poll_interval)
try:
while (_transport.remaining() or 0) > 0:
try:
Expand All @@ -576,8 +604,13 @@ def wait_for_review(
result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha)
if result is not None:
return result
sleep(min(interval, _transport.remaining() or 0))
interval = min(60, interval * 2)
if on_poll is not None:
on_poll(last)
left = _transport.remaining() or 0
if left <= 0:
break
sleep(min(interval, left))
interval = min(float(max_poll_interval), interval * 2)
timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha)
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
Expand Down Expand Up @@ -941,14 +974,15 @@ async def wait_for_review(
*,
timeout: float = 300,
head_commit_sha: str | None = None,
poll_interval: float = 5.0,
max_poll_interval: float = 60.0,
on_poll: Callable[[CustomerReviewDetail], object] | None = None,
) -> ReviewOutcome:
if not math.isfinite(timeout) or timeout < 0:
raise ValueError("The review timeout must be a finite nonnegative number of seconds.")
_head_commit(head_commit_sha)
_wait_limits(timeout, head_commit_sha, poll_interval, max_poll_interval)
url = _review_url(self._base_url, organization_id, review_id)
last: CustomerReviewDetail | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
interval = 5.0
interval = float(poll_interval)
try:
while (_transport.remaining() or 0) > 0:
try:
Expand All @@ -962,8 +996,15 @@ async def wait_for_review(
result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha)
if result is not None:
return result
await async_sleep(min(interval, _transport.remaining() or 0))
interval = min(60, interval * 2)
if on_poll is not None:
polled = on_poll(last)
if inspect.isawaitable(polled):
await polled
left = _transport.remaining() or 0
if left <= 0:
break
await async_sleep(min(interval, left))
interval = min(float(max_poll_interval), interval * 2)
timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha)
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
Expand Down
123 changes: 122 additions & 1 deletion proofline/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@
from typing import Literal
from uuid import UUID

from ._generated.models.check_file import CheckFile
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.domain_view import DomainView
from ._generated.types import Unset
from ._transport import ProoflineError

OutcomeStatus = Literal["COMPLETED", "INCOMPLETE", "FAILED", "STOPPED", "TIMED_OUT"]
COMPLETE_CHECKS = frozenset(("READY", "BLOCKED", "NOT_APPLICABLE"))
COMPLETE_LIFECYCLES = frozenset(("GATING", "SHADOW", "QUARANTINED", "RETIRED"))
_SEVERITY_RANK = {"SERIOUS": 0, "WARNING": 1}
_KNOWN_ASSESSMENTS = frozenset(
("PENDING", "RUNNING", "COMPLETED", "INCOMPLETE", "FAILED", "STOPPED", "SUPERSEDED", "EXCLUDED")
)
Expand All @@ -24,13 +28,24 @@
}


@dataclass(frozen=True)
class DomainCoverage:
"""One risk domain an assessment evaluated, with its recorded status and reason."""

domain: str
status: str
reason: str = field(repr=False)


@dataclass(frozen=True)
class CheckGap:
name: str = field(repr=False)
outcome: str
lifecycle: str
unresolved_reason: str | None = field(default=None, repr=False)
detail: str | None = field(default=None, repr=False)
files: tuple[CheckFile, ...] = field(default=(), repr=False)
evaluated_at: str | None = field(default=None, repr=False)


@dataclass(frozen=True)
Expand All @@ -41,6 +56,18 @@ class AssessmentGap:
incompleteness_kind: str | None = None
release_evidence_gap: str | None = field(default=None, repr=False)
checks: tuple[CheckGap, ...] = field(default=(), repr=False)
environment: str | None = field(default=None, repr=False)
domains: tuple[DomainCoverage, ...] = field(default=(), repr=False)


@dataclass(frozen=True)
class RecordedFinding:
"""One recorded finding paired with the assessment or code review that produced it."""

finding: CustomerFinding
assessment_id: UUID | None = None
environment_display_name: str | None = None
from_code_assessment: bool = False


@dataclass(frozen=True)
Expand All @@ -51,11 +78,71 @@ class ReviewOutcome:
gaps: tuple[AssessmentGap, ...] = field(default=(), repr=False)
reason: str | None = None

@property
def gap_codes(self) -> tuple[str, ...]:
"""Deduplicated gap and unresolved-check reason codes in recorded order."""
codes: list[str] = []
for gap in self.gaps:
codes.extend(gap.reason_codes)
for check in gap.checks:
if check.unresolved_reason:
codes.append(check.unresolved_reason)
return tuple(dict.fromkeys(codes))

@property
def environments(self) -> tuple[str, ...]:
"""Distinct environments whose gaps kept the outcome from completing, in recorded order."""
names: list[str] = []
for gap in self.gaps:
if gap.environment and gap.environment not in names:
names.append(gap.environment)
return tuple(names)

def recorded_findings(
self,
*,
severity: str | None = None,
unresolved_only: bool = False,
) -> tuple[RecordedFinding, ...]:
"""Collect recorded findings with provenance, ordered by severity then lifecycle state."""
if self.review is None:
return ()
collected: list[RecordedFinding] = []
if self.review.assessments:
for item in self.review.assessments:
env_name = text(item.environment_display_name)
for found in item.findings:
if found.risk_domain == _WITHHELD_MARKER:
continue
collected.append(RecordedFinding(found, item.id, env_name, False))
else:
code = _code_assessment(self.review)
if code is not None:
for found in code.findings:
collected.append(RecordedFinding(found, code.id, None, True))
if severity is not None:
collected = [item for item in collected if item.finding.severity == severity]
if unresolved_only:
collected = [item for item in collected if item.finding.lifecycle_state != "RESOLVED"]
collected.sort(
key=lambda item: (
_SEVERITY_RANK.get(item.finding.severity, len(_SEVERITY_RANK)),
1 if item.finding.lifecycle_state == "RESOLVED" else 0,
)
)
return tuple(collected)


def text(value: object) -> str | None:
return value if isinstance(value, str) and value else None


def _environment(value: object) -> str | None:
# A withheld environment value carries no name a caller may act on.
name = text(value)
return None if name == _WITHHELD_MARKER else name


def _invalid() -> ProoflineError:
return ProoflineError(
0,
Expand Down Expand Up @@ -118,6 +205,8 @@ def _validate(review: CustomerReviewDetail, review_id: UUID | None) -> None:
if (
not isinstance(assessment.id, UUID)
or not isinstance(assessment.status, str)
or not isinstance(assessment.environment_display_name, str)
or not isinstance(assessment.domains, list)
or not isinstance(assessment.checks.status, str)
or type(assessment.checks.receipt_recorded) is not bool
or not isinstance(assessment.checks.families, list)
Expand All @@ -130,15 +219,32 @@ def _validate(review: CustomerReviewDetail, review_id: UUID | None) -> None:
seen.add(assessment.id)
if not _optional_texts(assessment.reason_codes):
raise _invalid()
for domain in assessment.domains:
if (
not isinstance(domain, DomainView)
or not isinstance(domain.domain, str)
or not isinstance(domain.status, str)
or not isinstance(domain.reason, str)
):
raise _invalid()
for check in assessment.checks.families:
if (
not isinstance(check.name, str)
or not isinstance(check.outcome, str)
or not isinstance(check.lifecycle, str)
or not _optional_text(check.detail)
or not _optional_text(check.unresolved_reason)
or not _optional_text(check.evaluated_at)
or not isinstance(check.files, list)
):
raise _invalid()
for evidence in check.files:
if (
not isinstance(evidence, CheckFile)
or evidence.revision not in ("BASE_CODE_REVISION", "PROPOSED_CODE_REVISION")
or not isinstance(evidence.path.untrusted_text, str)
):
raise _invalid()


def _head_gap(review: CustomerReviewDetail, head_commit_sha: str | None) -> str | None:
Expand Down Expand Up @@ -200,6 +306,8 @@ def outcome(
check.lifecycle,
text(check.unresolved_reason),
text(check.detail),
tuple(check.files),
text(check.evaluated_at),
)
for check in assessment.checks.families
if check.outcome not in COMPLETE_CHECKS or check.lifecycle not in COMPLETE_LIFECYCLES
Expand All @@ -216,7 +324,20 @@ def outcome(
else "UNKNOWN_ASSESSMENT_STATUS",
)
gaps.append(
AssessmentGap(assessment.id, assessment.status, reasons, kind, evidence, checks)
AssessmentGap(
assessment.id,
assessment.status,
reasons,
kind,
evidence,
checks,
_environment(assessment.environment_display_name),
tuple(
DomainCoverage(domain.domain, domain.status, domain.reason)
for domain in assessment.domains
if domain.domain != _WITHHELD_MARKER
),
)
)
if review.assessment_count != len(review.assessments):
gaps.append(AssessmentGap(None, "UNKNOWN", ("ASSESSMENT_HISTORY_UNAVAILABLE",)))
Expand Down
Loading