diff --git a/README.md b/README.md index 1bc220e3..e894fc3d 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,25 @@ with ProoflineClient() as client: The response names the recorded report and its covered and instrumented line counts. An identical upload returns that report with `created=False`. Refused reports raise `ProoflineError`. Uploading a report does not establish a check verdict. +## Review progress notifications + +Pass `on_update` to `wait_for_review` to update a CI status display or collect progress +without implementing another polling loop: + +```python +result = client.wait_for_review( + organization_id, review_id, + on_update=lambda review: print(review.status), +) +``` + +The callback receives each validated `CustomerReviewDetail` returned by a poll, +including the terminal review. The asynchronous client accepts either a synchronous +callback or an async callback, and awaits async callbacks before polling again. +Callbacks run inline, their time counts toward the wait timeout, and their exceptions +propagate to the caller. The SDK does not add requests or change its polling backoff. +Keep callbacks short and do not mutate the review they receive. + ## MCP organization selection With an MCP OAuth credential approved for several organizations, discover its currently authorized targets with `client.mcp.list_organizations()`. It returns a `KnowledgeResult`; inspect `isError` before reading `structuredContent["data"]["organizations"]`. Each entry contains `organization_id`, `github_login`, and `scopes`. diff --git a/proofline/client.py b/proofline/client.py index 0a8239b4..98613aa7 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 inspect import isawaitable from time import monotonic, sleep from types import TracebackType from typing import Any, Self, TypedDict, TypeVar, Unpack, cast @@ -476,12 +477,20 @@ 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, + on_update: Callable[[CustomerReviewDetail], None] | 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. + + on_update receives each validated poll, including the terminal review. + It runs inline within the wait deadline; callback exceptions propagate. """ if not math.isfinite(timeout) or timeout < 0: @@ -501,6 +510,10 @@ def wait_for_review( if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id) + if on_update is not None: + on_update(last) + if (_transport.remaining() or 0) <= 0: + break if result is not None: return result sleep(min(interval, _transport.remaining() or 0)) @@ -830,8 +843,18 @@ 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, + on_update: Callable[[CustomerReviewDetail], Awaitable[None] | None] | None = None, ) -> ReviewOutcome: + """Wait with an optional inline synchronous or asynchronous progress callback. + + on_update receives each validated poll, including the terminal review. + Its execution counts toward timeout and its exceptions propagate. + """ if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") url = _review_url(self._base_url, organization_id, review_id) @@ -849,6 +872,12 @@ async def wait_for_review( if (_transport.remaining() or 0) <= 0: break result = outcome(last, url, review_id=review_id) + if on_update is not None: + update = on_update(last) + if isawaitable(update): + await update + if (_transport.remaining() or 0) <= 0: + break if result is not None: return result await async_sleep(min(interval, _transport.remaining() or 0)) diff --git a/tests/test_http.py b/tests/test_http.py index d308af0f..a4bf0ae8 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -990,6 +990,104 @@ async def test_wait_retains_evidence_gaps_after_running_review( assert clock.delays == [5, 10] +@MODES +async def test_wait_progress_reports_validated_polls_without_extra_requests( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + updates: list[CustomerReviewDetail] = [] + responses = [review("PENDING"), review("RUNNING"), review()] + 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, on_update=updates.append + ) + assert [update.status for update in updates] == ["PENDING", "RUNNING", "COMPLETED"] + assert all(update.id == REVIEW for update in updates) + assert result.status == "COMPLETED" + assert result.review is updates[-1] + assert len(server.requests) == 3 + assert clock.delays == [5, 10] + + +async def test_async_wait_awaits_progress_callback(monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + updates: list[str] = [] + responses = [review("RUNNING"), review()] + + async def update(detail: CustomerReviewDetail) -> None: + await asyncio.sleep(0) + updates.append(detail.status) + + def respond(request: Request, index: int) -> Reply: + if index: + assert updates == ["RUNNING"] + return Reply(body=responses[index]) + + with Server(respond) as server: + async with session("async", server.url) as client: + result = await call(client, "wait_for_review", ORG, REVIEW, on_update=update) + assert updates == ["RUNNING", "COMPLETED"] + assert result.status == "COMPLETED" + assert clock.delays == [5] + + +@MODES +async def test_wait_callback_error_propagates_and_restores_deadline( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + previous_deadline = _transport.DEADLINE.get() + + def update(detail: CustomerReviewDetail) -> None: + raise RuntimeError("status display failed") + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + with pytest.raises(RuntimeError, match="status display failed"): + await call(client, "wait_for_review", ORG, REVIEW, on_update=update) + assert _transport.DEADLINE.get() == previous_deadline + assert len(server.requests) == 1 + + +@MODES +async def test_wait_progress_obeys_deadline_including_callback_time( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + updates: list[str] = [] + + def update(detail: CustomerReviewDetail) -> None: + updates.append(detail.status) + clock.now += 2 + + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with session(mode, server.url) as client: + empty = await call(client, "wait_for_review", ORG, REVIEW, timeout=0, on_update=update) + assert empty.status == "TIMED_OUT" + assert updates == [] + assert server.requests == [] + result = await call(client, "wait_for_review", ORG, REVIEW, timeout=1, on_update=update) + assert result.status == "TIMED_OUT" + assert updates == ["RUNNING"] + assert len(server.requests) == 1 + assert clock.delays == [] + + +@MODES +async def test_wait_does_not_publish_invalid_review_to_callback( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + updates: list[CustomerReviewDetail] = [] + wrong_review = {**review(), "id": str(UUID(int=42))} + with Server(lambda request, index: Reply(body=wrong_review)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError): + await call(client, "wait_for_review", ORG, REVIEW, on_update=updates.append) + assert updates == [] + + @MODES async def test_code_only_outcomes_retain_recorded_kind_and_env_precedence( mode: str, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture