diff --git a/README.md b/README.md index ce3b3f1e..e3d6977f 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,18 @@ the wait returns `TIMED_OUT` immediately. `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. +## Waiting for several reviews + +`wait_for_reviews` waits for several reviews under one deadline and returns each review's `ReviewOutcome` by review ID, in the order given. + +```python +outcomes = client.wait_for_reviews(organization_id, review_ids, timeout=600) +for review_id, outcome in outcomes.items(): + print(review_id, outcome.status, outcome.reason) +``` + +Each review keeps the polling, retry and commit-pin policy of `wait_for_review`. The sync client waits in the order given and gives each review what is left of the deadline, so a review it reaches after the deadline is `TIMED_OUT` with no `review` and no request, even if it has finished. The async client waits for all of them at once, so it can report the same review `COMPLETED`. An error reading one review makes its outcome `FAILED` with no `review` and a `reason` that names only the HTTP status, and the others keep going. `timeout=0` reads each review once. A review named twice is waited on once. `head_commit_shas` maps a review ID in the batch to the commit to pin, as `head_commit_sha` does for one review. A review ID that is not a `UUID`, or a pin for a review outside the batch, raises `ValueError` before a request. + ## 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 72f2514e..73f3f492 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -3,7 +3,7 @@ from __future__ import annotations import math -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Iterator, Mapping from string import hexdigits from time import sleep from types import TracebackType @@ -11,6 +11,7 @@ from urllib.parse import quote from uuid import UUID +import anyio import httpx2 from anyio import sleep as async_sleep from pydantic import SecretStr @@ -164,6 +165,27 @@ def _head_commit(value: str | None) -> None: raise ValueError("The head commit must be a full 40 or 64 character hexadecimal SHA.") +def _review_batch( + review_ids: Iterable[UUID], timeout: float, head_commit_shas: Mapping[UUID, str] | None +) -> tuple[list[UUID], Mapping[UUID, str]]: + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The review timeout must be a finite nonnegative number of seconds.") + named = list(review_ids) + if not all(isinstance(review_id, UUID) for review_id in named): + raise ValueError("Each review ID must be a UUID.") + ids = list(dict.fromkeys(named)) + shas = head_commit_shas or {} + if not set(shas) <= set(ids): + raise ValueError("Each head commit must name a review in the batch.") + for sha in shas.values(): + _head_commit(sha) + return ids, shas + + +def _unread(url: str) -> ReviewOutcome: + return outcome(None, url, "TIMED_OUT") or ReviewOutcome("TIMED_OUT", url) + + def _next_cursor(page: ReviewPage, seen: set[str]) -> str | None: if not isinstance(page.truncated, bool): raise _transport.invalid_response() @@ -586,6 +608,42 @@ def wait_for_review( ) return timed_out or ReviewOutcome("TIMED_OUT", url) + def wait_for_reviews( + self, + organization_id: UUID, + review_ids: Iterable[UUID], + *, + timeout: float = 300, + head_commit_shas: Mapping[UUID, str] | None = None, + ) -> dict[UUID, ReviewOutcome]: + """Wait for each review in the order given under one shared deadline. + + Each review is held to wait_for_review's polling, retry and commit-pin + policy. A review reached after the deadline is TIMED_OUT without a read. + A read that raises ProoflineError makes that review FAILED, with no + review and a reason that names only the HTTP status. + """ + + ids, shas = _review_batch(review_ids, timeout, head_commit_shas) + deadline = _transport.monotonic() + timeout + results: dict[UUID, ReviewOutcome] = {} + for review_id in ids: + url = _review_url(self._base_url, organization_id, review_id) + budget = max(0.0, deadline - _transport.monotonic()) + if timeout and not budget: + results[review_id] = _unread(url) + continue + try: + results[review_id] = self.wait_for_review( + organization_id, + review_id, + timeout=budget, + head_commit_sha=shas.get(review_id), + ) + except ProoflineError as error: + results[review_id] = ReviewOutcome("FAILED", url, reason=str(error)) + return results + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -973,3 +1031,36 @@ async def wait_for_review( last, url, "TIMED_OUT", review_id=review_id, head_commit_sha=head_commit_sha ) return timed_out or ReviewOutcome("TIMED_OUT", url) + + async def wait_for_reviews( + self, + organization_id: UUID, + review_ids: Iterable[UUID], + *, + timeout: float = 300, + head_commit_shas: Mapping[UUID, str] | None = None, + ) -> dict[UUID, ReviewOutcome]: + ids, shas = _review_batch(review_ids, timeout, head_commit_shas) + deadline = _transport.monotonic() + timeout + results: dict[UUID, ReviewOutcome] = {} + + async def wait(review_id: UUID) -> None: + url = _review_url(self._base_url, organization_id, review_id) + budget = max(0.0, deadline - _transport.monotonic()) + if timeout and not budget: + results[review_id] = _unread(url) + return + try: + results[review_id] = await self.wait_for_review( + organization_id, + review_id, + timeout=budget, + head_commit_sha=shas.get(review_id), + ) + except ProoflineError as error: + results[review_id] = ReviewOutcome("FAILED", url, reason=str(error)) + + async with anyio.create_task_group() as tasks: + for review_id in ids: + tasks.start_soon(wait, review_id) + return {review_id: results[review_id] for review_id in ids} diff --git a/scripts/contracts.py b/scripts/contracts.py index a8cdda1f..48a49014 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -48,7 +48,14 @@ def main() -> None: "get_repo_config_with_revision", } for client in (ProoflineClient, AsyncProoflineClient): - helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"} + helpers = { + "close", + "aclose", + "iter_export_pages", + "iter_reviews", + "wait_for_review", + "wait_for_reviews", + } exposed = { name for name in dir(client) diff --git a/tests/test_http.py b/tests/test_http.py index c3ca12f0..e44e62c2 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -14,7 +14,7 @@ import time import tomllib import traceback -from collections.abc import AsyncIterator +from collections.abc import AsyncIterator, Callable from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -1689,6 +1689,211 @@ async def wait(url: str) -> None: assert len(server.requests) == len(replies) +def replies_by_review(sequences: dict[UUID, list[str]]) -> Callable[[Request, int], Reply]: + reads: dict[UUID, int] = {} + + def respond(request: Request, index: int) -> Reply: + review_id = UUID(request.path.rsplit("/", 1)[1]) + statuses = sequences[review_id] + read = reads.get(review_id, 0) + reads[review_id] = read + 1 + return Reply(body={**review(statuses[min(read, len(statuses) - 1)]), "id": str(review_id)}) + + return respond + + +def reads_of(server: Server, review_id: UUID) -> int: + return sum(request.path.endswith(f"/reviews/{review_id}") for request in server.requests) + + +@MODES +async def test_batch_wait_reads_each_named_review_once_in_the_order_given( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + respond = replies_by_review({REVIEW: ["PENDING", "COMPLETED"], FINDING: ["COMPLETED"]}) + with Server(respond) as server: + async with session(mode, server.url) as client: + results = await call( + client, "wait_for_reviews", ORG, [REVIEW, FINDING, REVIEW], timeout=100 + ) + assert list(results) == [REVIEW, FINDING] + assert [result.status for result in results.values()] == ["COMPLETED", "COMPLETED"] + assert results[FINDING].review.id == FINDING + assert results[FINDING].review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{FINDING}" + assert (reads_of(server, REVIEW), reads_of(server, FINDING)) == (2, 1) + if mode == "sync": + assert [request.path.rsplit("/", 1)[1] for request in server.requests] == [ + str(REVIEW), + str(REVIEW), + str(FINDING), + ] + assert clock.delays == [5] + + +async def test_sync_batch_wait_gives_later_reviews_what_is_left( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + with Server( + replies_by_review({REVIEW: ["PENDING", "COMPLETED"], FINDING: ["RUNNING"]}) + ) as server: + async with session("sync", server.url) as client: + results = await call(client, "wait_for_reviews", ORG, [REVIEW, FINDING], timeout=12) + assert (results[REVIEW].status, results[FINDING].status) == ("COMPLETED", "TIMED_OUT") + assert results[FINDING].review.id == FINDING + assert (reads_of(server, REVIEW), reads_of(server, FINDING)) == (2, 2) + assert clock.delays == [5, 5, 2] + assert clock.now == 112 + + +@MODES +async def test_sync_batch_skips_reviews_after_the_deadline_and_async_reads_them( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(replies_by_review({REVIEW: ["RUNNING"], FINDING: ["COMPLETED"]})) as server: + async with session(mode, server.url) as client: + results = await call(client, "wait_for_reviews", ORG, [REVIEW, FINDING], timeout=12) + assert results[REVIEW].status == "TIMED_OUT" + assert results[REVIEW].review.id == REVIEW + if mode == "sync": + skipped = results[FINDING] + assert (skipped.status, skipped.review) == ("TIMED_OUT", None) + assert skipped.reason == "No review result is available." + assert skipped.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{FINDING}" + assert reads_of(server, FINDING) == 0 + else: + assert reads_of(server, FINDING) == 1 + assert clock.delays == [5, 7] + + +@MODES +async def test_zero_batch_wait_reads_each_review_once( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(replies_by_review({REVIEW: ["RUNNING"], FINDING: ["COMPLETED"]})) as server: + async with session(mode, server.url) as client: + results = await call(client, "wait_for_reviews", ORG, [REVIEW, FINDING], timeout=0) + assert (results[REVIEW].status, results[FINDING].status) == ("TIMED_OUT", "COMPLETED") + assert results[REVIEW].review.id == REVIEW + assert (reads_of(server, REVIEW), reads_of(server, FINDING)) == (1, 1) + assert clock.delays == [] + + +@MODES +async def test_batch_wait_records_a_failed_read_and_keeps_going( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + polling = replies_by_review({REVIEW: ["PENDING", "COMPLETED"]}) + + def respond(request: Request, index: int) -> Reply: + if request.path.endswith(f"/reviews/{FINDING}"): + return Reply(404, {"type": "urn:proofline:not-found", "detail": PRIVATE}) + return polling(request, index) + + with Server(respond) as server: + async with session(mode, server.url) as client: + results = await call(client, "wait_for_reviews", ORG, [FINDING, REVIEW]) + failed = results[FINDING] + assert (failed.status, failed.review, failed.gaps) == ("FAILED", None, ()) + assert failed.reason == "Proofline request failed (HTTP 404)." + assert failed.review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{FINDING}" + assert PRIVATE not in repr(failed) and PRIVATE not in str(failed) + assert results[REVIEW].status == "COMPLETED" + assert (reads_of(server, FINDING), reads_of(server, REVIEW)) == (1, 2) + assert clock.delays == [5] + + +@MODES +async def test_batch_wait_keeps_each_review_retry_policy_inside_the_deadline( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + completed = replies_by_review({FINDING: ["COMPLETED"]}) + + def respond(request: Request, index: int) -> Reply: + if request.path.endswith(f"/reviews/{REVIEW}"): + return Reply(503, {"detail": "Unavailable."}, {"Retry-After": "30"}) + return completed(request, index) + + with Server(respond) as server: + async with session(mode, server.url) as client: + results = await call(client, "wait_for_reviews", ORG, [REVIEW, FINDING], timeout=20) + assert (results[REVIEW].status, results[REVIEW].review) == ("TIMED_OUT", None) + assert results[FINDING].status == "COMPLETED" + assert (reads_of(server, REVIEW), reads_of(server, FINDING)) == (1, 1) + assert clock.delays == [] + + +@MODES +async def test_batch_wait_holds_each_review_to_its_own_head(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + review_id = request.path.rsplit("/", 1)[1] + return Reply(body={**review_at(HEAD), "id": review_id}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + results = await call( + client, + "wait_for_reviews", + ORG, + [REVIEW, FINDING, ASSESSMENT], + head_commit_shas={REVIEW: OTHER_HEAD, FINDING: HEAD}, + ) + assert results[REVIEW].status == "INCOMPLETE" + assert gap_facts(results[REVIEW]) == [PINNED_ELSEWHERE] + assert results[REVIEW].reason == "The review is pinned to another head commit." + for review_id in (FINDING, ASSESSMENT): + assert (results[review_id].status, results[review_id].gaps) == ("COMPLETED", ()) + + +@MODES +async def test_batch_wait_refuses_bad_arguments_before_any_request(mode: str) -> None: + refused: list[tuple[Any, dict[str, Any], str]] = [ + ([REVIEW, FINDING], {"timeout": -1}, "finite nonnegative"), + ([REVIEW, FINDING], {"timeout": float("nan")}, "finite nonnegative"), + ([REVIEW, FINDING], {"timeout": float("inf")}, "finite nonnegative"), + ([REVIEW, str(FINDING)], {}, "must be a UUID"), + (str(REVIEW), {}, "must be a UUID"), + ([REVIEW, FINDING], {"head_commit_shas": {FINDING: "z" * 40}}, "full 40 or 64"), + ([REVIEW, FINDING], {"head_commit_shas": {ASSESSMENT: HEAD}}, "review in the batch"), + ([REVIEW, FINDING], {"head_commit_shas": {str(FINDING): HEAD}}, "review in the batch"), + ] + with Server(lambda request, index: Reply(body=review())) as server: + async with session(mode, server.url) as client: + for review_ids, kwargs, message in refused: + with pytest.raises(ValueError, match=message): + await call(client, "wait_for_reviews", ORG, review_ids, **kwargs) + assert server.requests == [] + + +@pytest.mark.parametrize("backend", ["asyncio", "trio"]) +def test_async_batch_wait_runs_on_anyio_backends( + backend: str, monkeypatch: pytest.MonkeyPatch +) -> None: + poll_sleep = client_module.async_sleep + + async def checkpoint(_delay: float) -> None: + await poll_sleep(0) + + monkeypatch.setattr(client_module, "async_sleep", checkpoint) + + async def wait(url: str) -> None: + async with AsyncProoflineClient(SecretStr(TOKEN), base_url=url) as client: + results = await client.wait_for_reviews(ORG, [REVIEW, FINDING]) + assert list(results) == [REVIEW, FINDING] + assert [result.status for result in results.values()] == ["COMPLETED", "COMPLETED"] + + with Server( + replies_by_review({REVIEW: ["RUNNING", "COMPLETED"], FINDING: ["COMPLETED"]}) + ) as server: + anyio.run(wait, server.url, backend=backend) + assert (reads_of(server, REVIEW), reads_of(server, FINDING)) == (2, 1) + + @MODES @pytest.mark.parametrize("retry_after", ["10", "20"]) async def test_retry_after_is_bounded_by_wait_deadline(