diff --git a/README.md b/README.md index 1bc220e3..8e5eac4b 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,21 @@ except ProoflineError as error: print(error.detail) ``` +## Holding a wait to a commit + +`request_review` names a pull request, and its response names no commit: the review belongs to the head the pull request has when the request arrives. To accept a result only for the commit you hold, pass that commit to `wait_for_review`. + +```python +requested = client.request_review(organization_id, repository_id, 12) +outcome = client.wait_for_review( + organization_id, requested.review_id, head_commit_sha=head_commit_sha, +) +if outcome.status != "COMPLETED": + print(outcome.status, outcome.reason) +``` + +`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. + ## Review exports `export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`. diff --git a/proofline/client.py b/proofline/client.py index 0a8239b4..57114842 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -5,6 +5,7 @@ import math from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from string import hexdigits from time import monotonic, sleep from types import TracebackType from typing import Any, Self, TypedDict, TypeVar, Unpack, cast @@ -151,6 +152,16 @@ def _page_limits(page_size: int, max_pages: int, max_items: int) -> None: ) +def _head_commit(value: str | None) -> None: + # Only a full SHA names one exact commit; a branch or an abbreviation does not. + if value is not None and ( + not isinstance(value, str) + or len(value) not in (40, 64) + or any(character not in hexdigits for character in value) + ): + raise ValueError("The head commit must be a full 40 or 64 character hexadecimal SHA.") + + def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None: if not isinstance(page.truncated, bool): raise _transport.invalid_response() @@ -476,16 +487,25 @@ def iter_reviews( raise _pagination_limit() def wait_for_review( - self, organization_id: UUID, review_id: UUID, *, timeout: float = 300 + self, + organization_id: UUID, + review_id: UUID, + *, + timeout: float = 300, + head_commit_sha: str | None = None, ) -> ReviewOutcome: """Wait for recorded review completion or return TIMED_OUT. A name lookup still running at the deadline returns TIMED_OUT; it never reports completion. + + 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. """ 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) url = _review_url(self._base_url, organization_id, review_id) last: CustomerReviewDetail | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) @@ -500,12 +520,13 @@ def wait_for_review( raise if (_transport.remaining() or 0) <= 0: break - result = outcome(last, url, review_id=review_id) + 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) - return outcome(last, url, "TIMED_OUT") or ReviewOutcome("TIMED_OUT", url) + timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) + return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) @@ -830,10 +851,16 @@ async def iter_reviews( raise _pagination_limit() async def wait_for_review( - self, organization_id: UUID, review_id: UUID, *, timeout: float = 300 + self, + organization_id: UUID, + review_id: UUID, + *, + timeout: float = 300, + head_commit_sha: 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) url = _review_url(self._base_url, organization_id, review_id) last: CustomerReviewDetail | None = None deadline = _transport.DEADLINE.set(monotonic() + timeout) @@ -848,11 +875,12 @@ async def wait_for_review( raise if (_transport.remaining() or 0) <= 0: break - result = outcome(last, url, review_id=review_id) + 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) - return outcome(last, url, "TIMED_OUT") or ReviewOutcome("TIMED_OUT", url) + timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) + return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) diff --git a/proofline/outcomes.py b/proofline/outcomes.py index e76c171c..3d551fa6 100644 --- a/proofline/outcomes.py +++ b/proofline/outcomes.py @@ -18,6 +18,10 @@ ("PENDING", "RUNNING", "COMPLETED", "INCOMPLETE", "FAILED", "STOPPED", "SUPERSEDED", "EXCLUDED") ) _WITHHELD_MARKER = "[withheld: environment value]" +_HEAD_REASONS = { + "HEAD_COMMIT_MISMATCH": "The review is pinned to another head commit.", + "HEAD_COMMIT_UNAVAILABLE": "The review names no head commit.", +} @dataclass(frozen=True) @@ -131,12 +135,23 @@ def _validate(review: CustomerReviewDetail, review_id: UUID | None) -> None: raise _invalid() +def _head_gap(review: CustomerReviewDetail, head_commit_sha: str | None) -> str | None: + # A result is evidence only for the head the review is pinned to. + if head_commit_sha is None: + return None + head = text(review.head_commit_sha) + if head is None: + return "HEAD_COMMIT_UNAVAILABLE" + return None if head.lower() == head_commit_sha.lower() else "HEAD_COMMIT_MISMATCH" + + def outcome( review: CustomerReviewDetail | None, review_url: str, forced: OutcomeStatus | None = None, *, review_id: UUID | None = None, + head_commit_sha: str | None = None, ) -> ReviewOutcome | None: gaps: list[AssessmentGap] = [] if review is None: @@ -196,8 +211,13 @@ 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) if forced is not None: status = forced + elif head_gap == "HEAD_COMMIT_MISMATCH": + # A pinned head does not change, so nothing this review records later + # can speak for the commit the caller named. + status = "INCOMPLETE" elif review.status in ("PENDING", "RUNNING"): return None elif review.status == "FAILED": @@ -205,9 +225,12 @@ def outcome( elif review.status in ("STOPPED", "SUPERSEDED"): status = "STOPPED" elif review.status == "COMPLETED": - status = "INCOMPLETE" if gaps else "COMPLETED" + status = "INCOMPLETE" if gaps or head_gap else "COMPLETED" else: status = "INCOMPLETE" if not gaps: gaps.append(AssessmentGap(None, review.status, ("REVIEW_STATE_UNAVAILABLE",))) - return ReviewOutcome(status, review_url, review, tuple(gaps)) + if head_gap is None: + return ReviewOutcome(status, review_url, review, tuple(gaps)) + gaps.append(AssessmentGap(None, "UNKNOWN", (head_gap,))) + return ReviewOutcome(status, review_url, review, tuple(gaps), _HEAD_REASONS[head_gap]) diff --git a/tests/test_http.py b/tests/test_http.py index f62d93f6..3cc45f2c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1207,6 +1207,154 @@ async def test_failure_and_stop_remain_distinct( assert len(server.requests) == 1 +HEAD = "a" * 40 +OTHER_HEAD = "c" * 40 +PINNED_ELSEWHERE = (None, "UNKNOWN", ("HEAD_COMMIT_MISMATCH",)) +NO_HEAD = (None, "UNKNOWN", ("HEAD_COMMIT_UNAVAILABLE",)) + + +def review_at(head: Any, status: str = "COMPLETED") -> dict[str, Any]: + return {**review(status), "head_commit_sha": head} + + +def gap_facts(result: Any) -> list[tuple[Any, str, tuple[str, ...]]]: + return [(gap.assessment_id, gap.status, gap.reason_codes) for gap in result.gaps] + + +@MODES +async def test_wait_held_to_a_head_commit_never_completes_for_another( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(lambda request, index: Reply(body=review_at(HEAD))) as server: + async with session(mode, server.url) as client: + for held in (HEAD, HEAD.upper()): + result = await call(client, "wait_for_review", ORG, REVIEW, head_commit_sha=held) + assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) + result = await call(client, "wait_for_review", ORG, REVIEW, head_commit_sha=OTHER_HEAD) + assert result.status == "INCOMPLETE" + assert gap_facts(result) == [PINNED_ELSEWHERE] + assert result.reason == "The review is pinned to another head commit." + assert result.review.head_commit_sha == HEAD + assert result.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert HEAD not in repr(result) and OTHER_HEAD not in repr(result) + # Without the keyword the same record completes, as it always has. + result = await call(client, "wait_for_review", ORG, REVIEW) + assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) + assert len(server.requests) == 4 + assert clock.delays == [] + + +@MODES +async def test_wait_ends_on_the_read_that_names_another_head( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + responses = [review("PENDING"), review_at(HEAD, "RUNNING"), review_at(HEAD)] + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, head_commit_sha=HEAD + ) + assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) + assert len(server.requests) == 3 + assert clock.delays == [5, 10] + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=100, head_commit_sha=OTHER_HEAD + ) + assert result.status == "INCOMPLETE" + assert result.review.status == "RUNNING" + assert gap_facts(result) == [PINNED_ELSEWHERE] + assert result.reason == "The review is pinned to another head commit." + # The second read names the head, so the review that would complete is never read. + assert len(server.requests) == 2 + assert clock.delays == [5, 10, 5] + + +@MODES +async def test_a_review_of_another_head_is_incomplete_whatever_its_own_status( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + statuses = ["FAILED", "STOPPED", "SUPERSEDED"] + with Server(lambda request, index: Reply(body=review_at(HEAD, statuses[index // 2]))) as server: + async with session(mode, server.url) as client: + for status in statuses: + result = await call( + client, "wait_for_review", ORG, REVIEW, head_commit_sha=OTHER_HEAD + ) + assert (result.status, gap_facts(result)) == ("INCOMPLETE", [PINNED_ELSEWHERE]) + assert result.review.status == status + result = await call(client, "wait_for_review", ORG, REVIEW, head_commit_sha=HEAD) + assert result.status == ("FAILED" if status == "FAILED" else "STOPPED") + assert (result.gaps, result.reason) == ((), None) + assert len(server.requests) == 6 + + +@MODES +async def test_a_review_that_names_no_head_never_completes_for_a_named_commit( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + bodies = [ + review(), + review_at(None), + review_at(""), + review_at(7), + review_at(None, "FAILED"), + review_at(None, "SUPERSEDED"), + ] + expected = ["INCOMPLETE", "INCOMPLETE", "INCOMPLETE", "INCOMPLETE", "FAILED", "STOPPED"] + with Server(lambda request, index: Reply(body=bodies[index])) as server: + async with session(mode, server.url) as client: + for status in expected: + result = await call(client, "wait_for_review", ORG, REVIEW, head_commit_sha=HEAD) + assert result.status == status + assert gap_facts(result) == [NO_HEAD] + assert result.reason == "The review names no head commit." + assert len(server.requests) == len(bodies) + assert clock.delays == [] + # A review that is still pending may name its head later, so the wait goes on. + with Server(lambda request, index: Reply(body=review("PENDING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=12, head_commit_sha=HEAD + ) + assert result.status == "TIMED_OUT" + assert gap_facts(result) == [NO_HEAD] + assert result.reason == "The review names no head commit." + assert len(server.requests) == 2 + assert clock.delays == [5, 7] + + +@MODES +async def test_head_commit_must_be_a_full_sha_before_any_request(mode: str) -> None: + refused = [ + "main", + "a" * 7, + "a" * 39, + "a" * 41, + "g" * 40, + "\u0661" * 40, + HEAD + "\n", + " " + HEAD[1:], + "", + 7, + HEAD.encode(), + ] + with Server(lambda request, index: Reply(body=review_at("d" * 64))) as server: + async with session(mode, server.url) as client: + for value in refused: + with pytest.raises(ValueError, match="full 40 or 64 character"): + await call(client, "wait_for_review", ORG, REVIEW, head_commit_sha=value) + assert server.requests == [] + result = await call(client, "wait_for_review", ORG, REVIEW, head_commit_sha="D" * 64) + assert (result.status, result.gaps, result.reason) == ("COMPLETED", (), None) + assert len(server.requests) == 1 + + @MODES async def test_polling_backoff_and_timeout_keep_review_url_and_last_record( mode: str, monkeypatch: pytest.MonkeyPatch