diff --git a/README.md b/README.md index 250fb32e..1c788e70 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 many reviews under one shared deadline: a release train, a nightly re-review sweep, or any batch that must not run past a cutoff. + +```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 its own polling, retry and commit-pin policy; the batch shares one deadline. A review that starts after the deadline has passed returns `TIMED_OUT` without a request, and an error on one review records a `FAILED` outcome carrying the error's detail while the others keep going. `timeout=0` reads each review once. `head_commit_shas` maps a review ID to the commit to pin, as `head_commit_sha` does for one review, and a review named twice is waited on once. The async client waits concurrently; the sync client waits in the order given. + ## 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 49e1a9e1..a4a24fd5 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 @@ -585,6 +586,49 @@ 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 several reviews under one shared deadline. + + Every review keeps its own polling, retry and commit-pin policy; the + batch holds all of them to one deadline. A review that starts after + that deadline has passed returns TIMED_OUT without a request, and an + error on one review records a FAILED outcome for that review while + the others keep going. The sync client waits in the order given; the + async client waits concurrently. A review named twice is waited on + once. + """ + + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The review timeout must be a finite nonnegative number of seconds.") + shas = head_commit_shas or {} + for sha in shas.values(): + _head_commit(sha) + results: dict[UUID, ReviewOutcome] = {} + deadline = _transport.monotonic() + timeout + for review_id in dict.fromkeys(review_ids): + url = _review_url(self._base_url, organization_id, review_id) + budget = timeout if timeout == 0 else max(0.0, deadline - _transport.monotonic()) + if timeout == 0 or budget > 0: + 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)) + else: + results[review_id] = ReviewOutcome("TIMED_OUT", url) + return results + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -972,3 +1016,47 @@ 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]: + """Wait for several reviews under one shared deadline, concurrently. + + The same contract as the sync `wait_for_reviews`; the waits run at + the same time, so one slow review cannot delay the others past the + deadline they all share. + """ + + if not math.isfinite(timeout) or timeout < 0: + raise ValueError("The review timeout must be a finite nonnegative number of seconds.") + shas = head_commit_shas or {} + for sha in shas.values(): + _head_commit(sha) + results: dict[UUID, ReviewOutcome] = {} + deadline = _transport.monotonic() + timeout + + async def wait_one(review_id: UUID) -> None: + url = _review_url(self._base_url, organization_id, review_id) + budget = timeout if timeout == 0 else max(0.0, deadline - _transport.monotonic()) + if timeout == 0 or budget > 0: + 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)) + else: + results[review_id] = ReviewOutcome("TIMED_OUT", url) + + async with anyio.create_task_group() as tasks: + for review_id in dict.fromkeys(review_ids): + tasks.start_soon(wait_one, review_id) + return results diff --git a/tests/test_wait_reviews.py b/tests/test_wait_reviews.py new file mode 100644 index 00000000..3fff23bb --- /dev/null +++ b/tests/test_wait_reviews.py @@ -0,0 +1,150 @@ +"""Tests for waiting on several reviews under one shared deadline.""" + +from __future__ import annotations + +import asyncio +import inspect +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from typing import Any +from uuid import UUID + +import pytest +from pydantic import SecretStr + +from proofline import AsyncProoflineClient, ProoflineClient, _sync_http, _transport +from proofline import client as client_module + +from .fixtures import FINDING, ORG, REVIEW, code_assessment, review +from .http_server import Reply, Request, Server + +Client = ProoflineClient | AsyncProoflineClient +MODES = pytest.mark.parametrize("mode", ["sync", "async"]) + + +@asynccontextmanager +async def session(mode: str, url: str) -> AsyncIterator[Client]: + if mode == "sync": + with ProoflineClient(SecretStr("t"), base_url=url) as client: + yield client + else: + async with AsyncProoflineClient(SecretStr("t"), base_url=url) as async_client: + yield async_client + + +async def call(client: Client, name: str, *args: Any, **kwargs: Any) -> Any: + result = getattr(client, name)(*args, **kwargs) + return await result if inspect.isawaitable(result) else result + + +class Clock: + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self.now = 100.0 + self.delays: list[float] = [] + 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) + + +def requested_review(request: Request) -> UUID: + for review_id in (REVIEW, FINDING): + if request.path.endswith(f"/reviews/{review_id}"): + return review_id + raise AssertionError(f"Unexpected request path {request.path}.") + + +@MODES +async def test_wait_for_reviews_waits_for_each_review_under_one_deadline( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + pending = review("PENDING") + other = review() + other["id"] = str(FINDING) + + def respond(request: Request, index: int) -> Reply: + if request.path.endswith(f"/reviews/{FINDING}"): + return Reply(body=other) + return Reply(body=pending if index == 0 else review()) + + with Server(respond) as server: + async with session(mode, server.url) as client: + results = await call( + client, "wait_for_reviews", ORG, [REVIEW, REVIEW, FINDING], timeout=100 + ) + assert sorted(results, key=str) == sorted([REVIEW, FINDING], key=str) + assert results[REVIEW].status == "COMPLETED" + assert results[REVIEW].review.id == REVIEW + assert results[REVIEW].review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{REVIEW}" + assert results[FINDING].status == "COMPLETED" + assert results[FINDING].review.id == FINDING + assert results[FINDING].review_url == f"{server.url}/orgs/by-id/{ORG}/reviews/{FINDING}" + assert len(server.requests) == 3 + assert clock.delays == [5] + + +@MODES +async def test_wait_for_reviews_shared_deadline_ends_the_unreached_waits( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + + def running(review_id: UUID) -> dict[str, Any]: + body = review("RUNNING") + body["id"] = str(review_id) + body.update(assessment_count=0, assessments=[], code_assessment=code_assessment("RUNNING")) + return body + + bodies = {REVIEW: running(REVIEW), FINDING: running(FINDING)} + with Server(lambda request, index: Reply(body=bodies[requested_review(request)])) 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[FINDING].status == "TIMED_OUT" + assert results[REVIEW].review.id == REVIEW + if mode == "sync": + # The first wait spends the whole deadline; the next starts after + # it and is answered without a request. + assert clock.delays == [5, 7] + assert all(request.path.endswith(f"/reviews/{REVIEW}") for request in server.requests) + assert len(server.requests) == (4 if mode == "async" else 2) + + +@MODES +async def test_wait_for_reviews_records_one_error_per_review(mode: str) -> None: + def respond(request: Request, index: int) -> Reply: + if request.path.endswith(f"/reviews/{FINDING}"): + return Reply(404, {"detail": "No such review."}) + return Reply(body=review()) + + with Server(respond) as server: + async with session(mode, server.url) as client: + results = await call(client, "wait_for_reviews", ORG, [REVIEW, FINDING]) + assert results[REVIEW].status == "COMPLETED" + assert results[FINDING].status == "FAILED" + assert "404" in (results[FINDING].reason or "") + + +@MODES +async def test_wait_for_reviews_rejects_bad_timeouts_and_commits_first(mode: str) -> None: + with Server(lambda request, index: Reply(body=review())) as server: + async with session(mode, server.url) as client: + for kwargs in [ + {"timeout": -1}, + {"timeout": float("nan")}, + {"head_commit_shas": {REVIEW: "z" * 64}}, + ]: + with pytest.raises(ValueError): + await call(client, "wait_for_reviews", ORG, [REVIEW], **kwargs) + assert server.requests == []