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
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,39 @@ 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.

## Requiring an environment check

A pull-request review can finish for the expected commit after checking only staging. If a CI job needs production coverage, pass the production environment's Proofline key to `wait_for_review`. The key appears in the environment's console URL. This example reads it from a variable set by the job.

```python
import os

target_environment_key = os.environ["PROOFLINE_TARGET_ENVIRONMENT_KEY"]
outcome = client.wait_for_review(
organization_id,
review_id,
head_commit_sha=head_commit_sha,
required_environment_key=target_environment_key,
)
if outcome.status != "COMPLETED":
detail = outcome.reason or "Inspect the review's assessment gaps."
raise SystemExit(f"{outcome.status}: {detail} {outcome.review_url}")
```

Both clients compare `required_environment_key` with `environment_external_key` exactly, including case. A review must satisfy the usual commit and assessment checks to return `COMPLETED`. When a target is required, exactly one entry must also match its key and report `CHECKED`. Omitting the keyword or passing `None` preserves the usual behavior.

For a settled review, inspect `outcome.gaps` for the environment result:

| Environment gap code | Meaning |
| --- | --- |
| `REQUIRED_ENVIRONMENT_UNAVAILABLE` | The review has no entry for the requested key. |
| `REQUIRED_ENVIRONMENT_AMBIGUOUS` | More than one entry has that key. |
| `REQUIRED_ENVIRONMENT_NOT_CHECKED` | The matching entry reports `CHECKING`, `NOT_CHECKED`, or `NOT_APPLICABLE`. |

Any of these gaps makes an otherwise completed review `INCOMPLETE`. A running review can still record the check. If the target was skipped, the matching entry in `outcome.review.environments` can explain why. For `PULL_REQUEST_REVIEWS_OFF`, check the repository's link to the environment. For `READS_REFUSED`, its Setup page lists the reads the cloud role refused. A checked environment establishes coverage. Use the findings and your deployment policy to decide whether to ship.

A supplied key must be a nonempty string. Invalid arguments raise `ValueError` before the first request. A malformed key encountered during matching, or an unknown state on any environment entry during decoding, raises `ProoflineError` with type `urn:proofline:sdk:invalid-response`.

## Review exports

`export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`.
Expand Down
46 changes: 42 additions & 4 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,11 @@ def _head_commit(value: str | None) -> None:
raise ValueError("The head commit must be a full 40 or 64 character hexadecimal SHA.")


def _required_environment_key(value: str | None) -> None:
if value is not None and (not isinstance(value, str) or not value):
raise ValueError("The required environment key must be a nonempty string.")


def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None:
if not isinstance(page.truncated, bool):
raise _transport.invalid_response()
Expand Down Expand Up @@ -545,6 +550,7 @@ def wait_for_review(
*,
timeout: float = 300,
head_commit_sha: str | None = None,
required_environment_key: str | None = None,
) -> ReviewOutcome:
"""Wait for recorded review completion or return TIMED_OUT.

Expand All @@ -553,11 +559,15 @@ 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.

required_environment_key requires one environment with that exact
environment_external_key to have state CHECKED before COMPLETED is returned.
"""

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)
_required_environment_key(required_environment_key)
url = _review_url(self._base_url, organization_id, review_id)
last: CustomerReviewDetail | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
Expand All @@ -572,12 +582,25 @@ def wait_for_review(
raise
if (_transport.remaining() or 0) <= 0:
break
result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha)
result = outcome(
last,
url,
review_id=review_id,
head_commit_sha=head_commit_sha,
required_environment_key=required_environment_key,
)
if result is not None:
return result
sleep(min(interval, _transport.remaining() or 0))
interval = min(60, interval * 2)
timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha)
timed_out = outcome(
last,
url,
"TIMED_OUT",
review_id=review_id,
head_commit_sha=head_commit_sha,
required_environment_key=required_environment_key,
)
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
_transport.DEADLINE.reset(deadline)
Expand Down Expand Up @@ -940,10 +963,12 @@ async def wait_for_review(
*,
timeout: float = 300,
head_commit_sha: str | None = None,
required_environment_key: str | 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)
_required_environment_key(required_environment_key)
url = _review_url(self._base_url, organization_id, review_id)
last: CustomerReviewDetail | None = None
deadline = _transport.DEADLINE.set(monotonic() + timeout)
Expand All @@ -958,12 +983,25 @@ async def wait_for_review(
raise
if (_transport.remaining() or 0) <= 0:
break
result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha)
result = outcome(
last,
url,
review_id=review_id,
head_commit_sha=head_commit_sha,
required_environment_key=required_environment_key,
)
if result is not None:
return result
await async_sleep(min(interval, _transport.remaining() or 0))
interval = min(60, interval * 2)
timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha)
timed_out = outcome(
last,
url,
"TIMED_OUT",
review_id=review_id,
head_commit_sha=head_commit_sha,
required_environment_key=required_environment_key,
)
return timed_out or ReviewOutcome("TIMED_OUT", url)
finally:
_transport.DEADLINE.reset(deadline)
51 changes: 49 additions & 2 deletions proofline/outcomes.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@
"HEAD_COMMIT_MISMATCH": "The review is pinned to another head commit.",
"HEAD_COMMIT_UNAVAILABLE": "The review names no head commit.",
}
_ENVIRONMENT_REASONS = {
"REQUIRED_ENVIRONMENT_UNAVAILABLE": (
"The review has no recorded check for the required environment."
),
"REQUIRED_ENVIRONMENT_AMBIGUOUS": (
"The review records the required environment more than once."
),
"REQUIRED_ENVIRONMENT_NOT_CHECKED": (
"The required environment was not checked by this review."
),
}


@dataclass(frozen=True)
Expand Down Expand Up @@ -151,13 +162,41 @@ def _head_gap(review: CustomerReviewDetail, head_commit_sha: str | None) -> str
return None if head.lower() == head_commit_sha.lower() else "HEAD_COMMIT_MISMATCH"


def _environment_gap(
review: CustomerReviewDetail, required_environment_key: str | None
) -> str | None:
if required_environment_key is None:
return None
environments = review.environments
if isinstance(environments, Unset):
return "REQUIRED_ENVIRONMENT_UNAVAILABLE"
if not isinstance(environments, list):
raise _invalid()
match_count = 0
match_state: str | None = None
for environment in environments:
key = environment.environment_external_key
# Every key must identify a row before uniqueness can be established.
if not isinstance(key, str) or not key:
raise _invalid()
if key == required_environment_key:
match_count += 1
match_state = environment.state
if match_count == 0:
return "REQUIRED_ENVIRONMENT_UNAVAILABLE"
if match_count != 1:
return "REQUIRED_ENVIRONMENT_AMBIGUOUS"
return None if match_state == "CHECKED" else "REQUIRED_ENVIRONMENT_NOT_CHECKED"


def outcome(
review: CustomerReviewDetail | None,
review_url: str,
forced: OutcomeStatus | None = None,
*,
review_id: UUID | None = None,
head_commit_sha: str | None = None,
required_environment_key: str | None = None,
) -> ReviewOutcome | None:
gaps: list[AssessmentGap] = []
if review is None:
Expand Down Expand Up @@ -221,6 +260,11 @@ def outcome(
if review.assessment_count != len(review.assessments):
gaps.append(AssessmentGap(None, "UNKNOWN", ("ASSESSMENT_HISTORY_UNAVAILABLE",)))
head_gap = _head_gap(review, head_commit_sha)
environment_gap = (
None
if head_gap == "HEAD_COMMIT_MISMATCH"
else _environment_gap(review, required_environment_key)
)
if forced is not None:
status = forced
elif head_gap == "HEAD_COMMIT_MISMATCH":
Expand All @@ -234,12 +278,15 @@ def outcome(
elif review.status in ("STOPPED", "SUPERSEDED"):
status = "STOPPED"
elif review.status == "COMPLETED":
status = "INCOMPLETE" if gaps or head_gap else "COMPLETED"
status = "INCOMPLETE" if gaps or head_gap or environment_gap else "COMPLETED"
else:
status = "INCOMPLETE"
if not gaps:
gaps.append(AssessmentGap(None, review.status, ("REVIEW_STATE_UNAVAILABLE",)))
if environment_gap is not None:
gaps.append(AssessmentGap(None, "UNKNOWN", (environment_gap,)))
if head_gap is None:
return ReviewOutcome(status, review_url, review, tuple(gaps))
reason = _ENVIRONMENT_REASONS[environment_gap] if environment_gap is not None else None
return ReviewOutcome(status, review_url, review, tuple(gaps), reason)
gaps.append(AssessmentGap(None, "UNKNOWN", (head_gap,)))
return ReviewOutcome(status, review_url, review, tuple(gaps), _HEAD_REASONS[head_gap])
14 changes: 12 additions & 2 deletions scripts/install_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,14 @@ async def asynchronous() -> None:
assert history.items == []
assert [item async for item in client.iter_reviews(ORG, filters=filters)] == []
assert (await client.get_finding(ORG, FINDING)).id == FINDING
result = await client.wait_for_review(ORG, REVIEW, timeout=2)
result = await client.wait_for_review(
ORG, REVIEW, timeout=2, required_environment_key="production"
)
assert result.status == "INCOMPLETE"
assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE"
assert any(
"REQUIRED_ENVIRONMENT_UNAVAILABLE" in gap.reason_codes for gap in result.gaps
)
assert TOKEN not in repr(client)

try:
Expand All @@ -128,9 +133,14 @@ async def asynchronous() -> None:
assert history.items == []
assert list(client.iter_reviews(ORG, filters=filters)) == []
assert client.get_finding(ORG, FINDING).id == FINDING
result = client.wait_for_review(ORG, REVIEW, timeout=2)
result = client.wait_for_review(
ORG, REVIEW, timeout=2, required_environment_key="production"
)
assert result.status == "INCOMPLETE"
assert result.gaps[0].reason_codes[0] == "WORLD_UNAVAILABLE"
assert any(
"REQUIRED_ENVIRONMENT_UNAVAILABLE" in gap.reason_codes for gap in result.gaps
)
assert TOKEN not in repr(client)
asyncio.run(asynchronous())
assert len(calls) == 10
Expand Down
Loading