From 6ea9a40b577863cd1b51201cdabf4f48b5027259 Mon Sep 17 00:00:00 2001 From: juggernaut7777 Date: Sat, 28 Nov 2026 17:19:27 +0100 Subject: [PATCH 1/3] Add wait_for_review poll hooks and provenance-aware outcome findings --- README.md | 7 +- proofline/__init__.py | 3 +- proofline/client.py | 65 ++++++-- proofline/outcomes.py | 57 +++++++ tests/test_wait_and_outcomes.py | 280 ++++++++++++++++++++++++++++++++ 5 files changed, 397 insertions(+), 15 deletions(-) create mode 100644 tests/test_wait_and_outcomes.py diff --git a/README.md b/README.md index eaad94e2..97074f3a 100644 --- a/README.md +++ b/README.md @@ -90,12 +90,15 @@ 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 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`). ## Review exports diff --git a/proofline/__init__.py b/proofline/__init__.py index 689b454d..7429f115 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -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, RecordedFinding, ReviewOutcome __all__ = [ "AgentSession", @@ -62,6 +62,7 @@ "PatchTriggerSource", "ProoflineClient", "ProoflineError", + "RecordedFinding", "RepositoryGuidance", "RepositoryNames", "RerunResponse", diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..9a9502e1 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -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 @@ -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() @@ -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. @@ -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: @@ -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: @@ -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: @@ -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: diff --git a/proofline/outcomes.py b/proofline/outcomes.py index fa363b32..e19321b4 100644 --- a/proofline/outcomes.py +++ b/proofline/outcomes.py @@ -7,6 +7,7 @@ from uuid import UUID 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.types import Unset from ._transport import ProoflineError @@ -14,6 +15,7 @@ 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, "HIGH": 1, "WARNING": 2} _KNOWN_ASSESSMENTS = frozenset( ("PENDING", "RUNNING", "COMPLETED", "INCOMPLETE", "FAILED", "STOPPED", "SUPERSEDED", "EXCLUDED") ) @@ -43,6 +45,16 @@ class AssessmentGap: checks: tuple[CheckGap, ...] = 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) class ReviewOutcome: status: OutcomeStatus @@ -51,6 +63,51 @@ 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)) + + 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, 3), + 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 diff --git a/tests/test_wait_and_outcomes.py b/tests/test_wait_and_outcomes.py new file mode 100644 index 00000000..93ff763a --- /dev/null +++ b/tests/test_wait_and_outcomes.py @@ -0,0 +1,280 @@ +from __future__ import annotations + +import asyncio +import inspect +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any + +import pytest +from pydantic import SecretStr + +from proofline import ( + AsyncProoflineClient, + ProoflineClient, + RecordedFinding, + ReviewOutcome, + _sync_http, + _transport, +) +from proofline import client as client_module +from proofline._generated.models.customer_review_detail import CustomerReviewDetail +from proofline.outcomes import outcome + +from .fixtures import ( + ASSESSMENT, + CODE_ASSESSMENT, + FINDING, + ORG, + REVIEW, + TOKEN, + assessment, + code_assessment, + finding, + review, +) +from .http_server import Reply, Request, Server + +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) + + +@asynccontextmanager +async def session(mode: str, url: str) -> AsyncIterator[ProoflineClient | AsyncProoflineClient]: + if mode == "sync": + with ProoflineClient(SecretStr(TOKEN), base_url=url) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as client: + yield client + + +async def invoke( + client: ProoflineClient | AsyncProoflineClient, + *args: Any, + **kwargs: Any, +) -> ReviewOutcome: + result = client.wait_for_review(*args, **kwargs) + return await result if inspect.isawaitable(result) else result + + +class LocalClock: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.now = 100.0 + self.delays: list[float] = [] + monkeypatch.setattr(client_module, "monotonic", lambda: self.now) + monkeypatch.setattr(_transport, "monotonic", lambda: self.now) + monkeypatch.setattr(_sync_http, "monotonic", lambda: self.now) + monkeypatch.setattr(client_module, "sleep", self.sleep) + monkeypatch.setattr(_transport, "sleep", self.sleep) + monkeypatch.setattr(client_module, "async_sleep", self.async_sleep) + monkeypatch.setattr(_transport, "async_sleep", self.async_sleep) + + def sleep(self, delay: float) -> None: + self.delays.append(delay) + self.now += delay + + async def async_sleep(self, delay: float) -> None: + self.sleep(delay) + await asyncio.sleep(0) + + +@MODES +async def test_wait_custom_poll_interval_and_on_poll_callback( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = LocalClock(monkeypatch) + statuses = ["PENDING", "RUNNING", "RUNNING", "RUNNING", "COMPLETED"] + seen_statuses: list[str] = [] + + def respond(request: Request, index: int) -> Reply: + current = statuses[index] + body = review(current) + if current != "COMPLETED": + body["assessments"] = [assessment("RUNNING")] + return Reply(body=body) + + def on_poll(snapshot: CustomerReviewDetail) -> None: + seen_statuses.append(snapshot.status) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await invoke( + client, + ORG, + REVIEW, + timeout=30, + poll_interval=1.0, + max_poll_interval=4.0, + on_poll=on_poll, + ) + assert result.status == "COMPLETED" + assert seen_statuses == ["PENDING", "RUNNING", "RUNNING", "RUNNING"] + assert clock.delays == [1.0, 2.0, 4.0, 4.0] + assert len(server.requests) == 5 + + zero_calls: list[str] = [] + timed_out = await invoke( + client, + ORG, + REVIEW, + timeout=0, + poll_interval=1.0, + max_poll_interval=2.0, + on_poll=lambda snap: zero_calls.append(snap.status), + ) + assert timed_out.status == "TIMED_OUT" + assert zero_calls == [] + + +async def test_async_wait_supports_awaitable_on_poll_and_deadline_expiry( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = LocalClock(monkeypatch) + seen: list[str] = [] + + async def on_poll(snapshot: CustomerReviewDetail) -> None: + await asyncio.sleep(0) + seen.append(snapshot.status) + clock.now += 10.0 + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=server.url) as client: + result = await client.wait_for_review( + ORG, + REVIEW, + timeout=5.0, + poll_interval=1.0, + max_poll_interval=2.0, + on_poll=on_poll, + ) + assert result.status == "TIMED_OUT" + assert result.review is not None + assert seen == ["RUNNING"] + assert clock.delays == [] + assert len(server.requests) == 1 + + +@MODES +@pytest.mark.parametrize( + "kwargs", + [ + {"timeout": True}, + {"poll_interval": 0}, + {"poll_interval": -1.0}, + {"poll_interval": float("nan")}, + {"poll_interval": True}, + {"max_poll_interval": float("inf")}, + {"poll_interval": 10.0, "max_poll_interval": 5.0}, + {"max_poll_interval": True}, + ], +) +async def test_wait_validates_poll_arguments_before_requests( + mode: str, kwargs: dict[str, Any] +) -> None: + with Server(lambda request, index: Reply(body=review())) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError): + await invoke(client, ORG, REVIEW, **kwargs) + assert not server.requests + + +def test_recorded_findings_orders_by_severity_and_preserves_provenance() -> None: + f_warn = { + **finding(), + "id": "00000000-0000-4000-8000-000000000011", + "severity": "WARNING", + "lifecycle_state": "NEW", + } + f_serious_resolved = { + **finding(), + "id": "00000000-0000-4000-8000-000000000012", + "severity": "SERIOUS", + "lifecycle_state": "RESOLVED", + } + f_serious_open = { + **finding(), + "id": "00000000-0000-4000-8000-000000000013", + "severity": "SERIOUS", + "lifecycle_state": "REINTRODUCED", + } + env_a = { + **assessment(), + "id": str(ASSESSMENT), + "environment_display_name": "staging", + "findings": [f_warn, f_serious_resolved], + } + env_b_id = "00000000-0000-4000-8000-000000000099" + env_b = { + **assessment(), + "id": env_b_id, + "environment_display_name": "production", + "findings": [f_serious_open], + } + payload = review() + payload["assessment_count"] = 2 + payload["assessments"] = [env_a, env_b] + + detail = CustomerReviewDetail.from_dict(payload) + parsed = outcome(detail, f"https://proofline.sh/orgs/by-id/{ORG}/reviews/{REVIEW}") + assert parsed is not None + + all_findings = parsed.recorded_findings() + assert [str(item.finding.id) for item in all_findings] == [ + "00000000-0000-4000-8000-000000000013", + "00000000-0000-4000-8000-000000000012", + "00000000-0000-4000-8000-000000000011", + ] + assert all_findings[0] == RecordedFinding( + finding=all_findings[0].finding, + assessment_id=parsed.review.assessments[1].id if parsed.review else None, + environment_display_name="production", + from_code_assessment=False, + ) + unresolved_serious = parsed.recorded_findings(severity="SERIOUS", unresolved_only=True) + assert [str(item.finding.id) for item in unresolved_serious] == [ + "00000000-0000-4000-8000-000000000013" + ] + + +def test_recorded_findings_respects_code_only_precedence_and_withheld_guard() -> None: + code_payload = review() + code_payload["assessment_count"] = 0 + code_payload["assessments"] = [] + code_payload["code_assessment"] = {**code_assessment(), "findings": [finding()]} + + parsed = outcome( + CustomerReviewDetail.from_dict(code_payload), + f"https://proofline.sh/orgs/by-id/{ORG}/reviews/{REVIEW}", + ) + assert parsed is not None + items = parsed.recorded_findings() + assert len(items) == 1 + assert items[0].from_code_assessment is True + assert str(items[0].assessment_id) == str(CODE_ASSESSMENT) + assert items[0].environment_display_name is None + assert str(items[0].finding.id) == str(FINDING) + + # Withheld environment-protected code findings must never surface. + withheld_payload = dict(code_payload) + withheld_payload["code_assessment"] = { + **code_assessment(), + "findings": [{**finding(), "risk_domain": "[withheld: environment value]"}], + } + parsed_withheld = outcome( + CustomerReviewDetail.from_dict(withheld_payload), + f"https://proofline.sh/orgs/by-id/{ORG}/reviews/{REVIEW}", + ) + assert parsed_withheld is not None + assert parsed_withheld.recorded_findings() == () + + # Missing assessments never fall back to code_assessment. + mixed_payload = dict(code_payload) + mixed_payload["assessment_count"] = 1 + parsed_mixed = outcome( + CustomerReviewDetail.from_dict(mixed_payload), + f"https://proofline.sh/orgs/by-id/{ORG}/reviews/{REVIEW}", + ) + assert parsed_mixed is not None + assert parsed_mixed.recorded_findings() == () + assert parsed_mixed.gap_codes == ("ASSESSMENT_HISTORY_UNAVAILABLE",) + assert ReviewOutcome("TIMED_OUT", "https://proofline.sh/r/1").recorded_findings() == () From bb1f0ccff1c3b6fe7a63aeca7b8dca3689698b21 Mon Sep 17 00:00:00 2001 From: juggernaut7777 Date: Sat, 28 Nov 2026 19:30:49 +0100 Subject: [PATCH 2/3] Carry environment, domain coverage, and cited evidence on outcome gaps --- README.md | 4 +- proofline/__init__.py | 3 +- proofline/outcomes.py | 66 +++++++++++++++- tests/test_wait_and_outcomes.py | 132 ++++++++++++++++++++++++++++++++ 4 files changed, 202 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 97074f3a..32ab9272 100644 --- a/README.md +++ b/README.md @@ -94,11 +94,13 @@ outcome = client.wait_for_review( ) if outcome.status != "COMPLETED": 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. 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`). +`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 diff --git a/proofline/__init__.py b/proofline/__init__.py index 7429f115..270c14f6 100644 --- a/proofline/__init__.py +++ b/proofline/__init__.py @@ -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, RecordedFinding, ReviewOutcome +from .outcomes import AssessmentGap, CheckGap, DomainCoverage, RecordedFinding, ReviewOutcome __all__ = [ "AgentSession", @@ -51,6 +51,7 @@ "CustomerAssessmentDetail", "CustomerFinding", "CustomerReviewDetail", + "DomainCoverage", "ExportDataset", "ExportFormat", "ExportPage", diff --git a/proofline/outcomes.py b/proofline/outcomes.py index e19321b4..cc1316a2 100644 --- a/proofline/outcomes.py +++ b/proofline/outcomes.py @@ -6,9 +6,11 @@ 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 @@ -26,6 +28,15 @@ } +@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) @@ -33,6 +44,8 @@ class CheckGap: 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) @@ -43,6 +56,8 @@ 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) @@ -74,6 +89,15 @@ def gap_codes(self) -> tuple[str, ...]: 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, *, @@ -113,6 +137,12 @@ 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, @@ -175,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) @@ -187,6 +219,14 @@ 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) @@ -194,8 +234,17 @@ def _validate(review: CustomerReviewDetail, review_id: UUID | None) -> None: 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: @@ -257,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 @@ -273,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",))) diff --git a/tests/test_wait_and_outcomes.py b/tests/test_wait_and_outcomes.py index 93ff763a..b04dd53e 100644 --- a/tests/test_wait_and_outcomes.py +++ b/tests/test_wait_and_outcomes.py @@ -11,7 +11,9 @@ from proofline import ( AsyncProoflineClient, + DomainCoverage, ProoflineClient, + ProoflineError, RecordedFinding, ReviewOutcome, _sync_http, @@ -278,3 +280,133 @@ def test_recorded_findings_respects_code_only_precedence_and_withheld_guard() -> assert parsed_mixed.recorded_findings() == () assert parsed_mixed.gap_codes == ("ASSESSMENT_HISTORY_UNAVAILABLE",) assert ReviewOutcome("TIMED_OUT", "https://proofline.sh/r/1").recorded_findings() == () + + +def test_gap_attributes_environment_domains_and_check_evidence() -> None: + payload = review("COMPLETED") + payload["assessments"][0].update( + status="INCOMPLETE", + environment_display_name="production", + reason_codes=["WORLD_UNAVAILABLE"], + domains=[ + { + "domain": "SECURITY", + "status": "SKIPPED", + "reason": "No authentication change observed.", + }, + { + "domain": "PERFORMANCE", + "status": "CONSIDERED", + "reason": "Reviewed the query path.", + }, + ], + checks={ + "families": [ + { + "name": "Unit tests", + "outcome": "UNRESOLVED", + "lifecycle": "GATING", + "unresolved_reason": "NEEDS_EVIDENCE", + "evaluated_at": "2026-01-01T00:00:00Z", + "files": [ + { + "revision": "PROPOSED_CODE_REVISION", + "path": {"untrusted_text": "src/app.py"}, + }, + { + "revision": "BASE_CODE_REVISION", + "path": {"untrusted_text": "src/app.py"}, + }, + ], + } + ], + "receipt_recorded": True, + "status": "READY", + }, + ) + + parsed = outcome(CustomerReviewDetail.from_dict(payload), "https://proofline.sh/r/1") + assert parsed is not None + assert parsed.status == "INCOMPLETE" + + gap = parsed.gaps[0] + assert gap.environment == "production" + assert parsed.environments == ("production",) + assert gap.domains == ( + DomainCoverage("SECURITY", "SKIPPED", "No authentication change observed."), + DomainCoverage("PERFORMANCE", "CONSIDERED", "Reviewed the query path."), + ) + + check = gap.checks[0] + assert (check.name, check.outcome, check.lifecycle) == ("Unit tests", "UNRESOLVED", "GATING") + assert check.unresolved_reason == "NEEDS_EVIDENCE" + assert check.evaluated_at == "2026-01-01T00:00:00Z" + assert [(f.revision, f.path.untrusted_text) for f in check.files] == [ + ("PROPOSED_CODE_REVISION", "src/app.py"), + ("BASE_CODE_REVISION", "src/app.py"), + ] + + +def test_withheld_environment_and_domains_are_not_exposed() -> None: + payload = review("COMPLETED") + payload["assessments"][0].update( + status="INCOMPLETE", + environment_display_name="[withheld: environment value]", + reason_codes=["WORLD_UNAVAILABLE"], + domains=[ + { + "domain": "[withheld: environment value]", + "status": "CONSIDERED", + "reason": "Withheld.", + }, + {"domain": "SECURITY", "status": "SKIPPED", "reason": "Out of scope."}, + ], + ) + + parsed = outcome(CustomerReviewDetail.from_dict(payload), "https://proofline.sh/r/1") + assert parsed is not None + + gap = parsed.gaps[0] + assert gap.environment is None + assert parsed.environments == () + assert [domain.domain for domain in gap.domains] == ["SECURITY"] + + +@MODES +@pytest.mark.parametrize( + "assessment_override", + [ + { + "checks": { + "families": [ + { + "name": "Unit tests", + "outcome": "UNRESOLVED", + "lifecycle": "GATING", + "unresolved_reason": "NEEDS_EVIDENCE", + "evaluated_at": 42, + "files": [], + } + ], + "receipt_recorded": True, + "status": "READY", + } + }, + { + "domains": [{"domain": "SECURITY", "status": "SKIPPED", "reason": 7}], + }, + {"environment_display_name": 5}, + ], +) +async def test_invalid_gap_metadata_is_refused( + mode: str, assessment_override: dict[str, Any] +) -> None: + payload = review("COMPLETED") + payload["assessments"][0].update(status="INCOMPLETE", reason_codes=["WORLD_UNAVAILABLE"]) + payload["assessments"][0].update(assessment_override) + + with Server(lambda request, index: Reply(body=payload)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as error: + await invoke(client, ORG, REVIEW, timeout=5) + assert error.value.type == "urn:proofline:sdk:invalid-response" From 748809ad72893edbca7182a8a35ad6363ff59875 Mon Sep 17 00:00:00 2001 From: juggernaut7777 Date: Mon, 30 Nov 2026 17:02:25 +0100 Subject: [PATCH 3/3] Sort unknown finding severities last and drop the HIGH label The API only records SERIOUS and WARNING. Do not invent HIGH in the sort rank; keep the forward-compatible contract that any future label a server sends sorts after the known ones instead of raising. --- proofline/outcomes.py | 4 ++-- tests/test_wait_and_outcomes.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/proofline/outcomes.py b/proofline/outcomes.py index cc1316a2..b30d5575 100644 --- a/proofline/outcomes.py +++ b/proofline/outcomes.py @@ -17,7 +17,7 @@ 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, "HIGH": 1, "WARNING": 2} +_SEVERITY_RANK = {"SERIOUS": 0, "WARNING": 1} _KNOWN_ASSESSMENTS = frozenset( ("PENDING", "RUNNING", "COMPLETED", "INCOMPLETE", "FAILED", "STOPPED", "SUPERSEDED", "EXCLUDED") ) @@ -126,7 +126,7 @@ def recorded_findings( collected = [item for item in collected if item.finding.lifecycle_state != "RESOLVED"] collected.sort( key=lambda item: ( - _SEVERITY_RANK.get(item.finding.severity, 3), + _SEVERITY_RANK.get(item.finding.severity, len(_SEVERITY_RANK)), 1 if item.finding.lifecycle_state == "RESOLVED" else 0, ) ) diff --git a/tests/test_wait_and_outcomes.py b/tests/test_wait_and_outcomes.py index b04dd53e..0d4eff3c 100644 --- a/tests/test_wait_and_outcomes.py +++ b/tests/test_wait_and_outcomes.py @@ -238,6 +238,34 @@ def test_recorded_findings_orders_by_severity_and_preserves_provenance() -> None ] +def test_recorded_findings_sorts_unknown_severity_last() -> None: + known = { + **finding(), + "id": "00000000-0000-4000-8000-000000000021", + "severity": "WARNING", + "lifecycle_state": "NEW", + } + unknown = { + **finding(), + "id": "00000000-0000-4000-8000-000000000022", + "severity": "FUTURE_LABEL", + "lifecycle_state": "NEW", + } + payload = review() + payload["assessment_count"] = 1 + payload["assessments"] = [{**assessment(), "findings": [unknown, known]}] + + parsed = outcome( + CustomerReviewDetail.from_dict(payload), + f"https://proofline.sh/orgs/by-id/{ORG}/reviews/{REVIEW}", + ) + assert parsed is not None + assert [item.finding.severity for item in parsed.recorded_findings()] == [ + "WARNING", + "FUTURE_LABEL", + ] + + def test_recorded_findings_respects_code_only_precedence_and_withheld_guard() -> None: code_payload = review() code_payload["assessment_count"] = 0