From 18e8b992ed76b2b86c65997b004e09b4bd31da1e Mon Sep 17 00:00:00 2001 From: Zaakir Hussain <43036631+ZaakirHussain5@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:46:50 +0000 Subject: [PATCH] Add wait_for_reverification to poll until a re-verification finishes Callers can wait on get_reverification with the same backoff as wait_for_review, on both the sync and async clients. --- README.md | 12 +++- proofline/client.py | 84 +++++++++++++++++++++- proofline/fixes.py | 60 ++++++++++++++++ scripts/contracts.py | 9 ++- tests/test_http.py | 168 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 329 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3c7a6ca9..ec17b232 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # proofline-sdk -`proofline-sdk` provides typed synchronous (`ProoflineClient`) and asynchronous (`AsyncProoflineClient`) Python clients for the [Proofline](https://proofline.sh) review API. The clients read and request reviews with a scoped API token, and include pagination, waiting for a review, retries, and typed errors. The import package is `proofline`. Python 3.11 or newer is required. +`proofline-sdk` provides typed synchronous (`ProoflineClient`) and asynchronous (`AsyncProoflineClient`) Python clients for the [Proofline](https://proofline.sh) review API. The clients read and request reviews with a scoped API token, and include pagination, waiting for a review or a re-verification, retries, and typed errors. The import package is `proofline`. Python 3.11 or newer is required. This repository is the published distribution of the Proofline Python SDK. The public OpenAPI contract in `openapi.public.json` generates the client and models in `proofline/_generated/`. [Open an issue](https://github.com/prooflinedev/sdk-python/issues) for changes to the OpenAPI contract, generated code, or workflows. Pull requests are welcome for the hand-written client in `proofline/client.py`, transport and helpers outside `proofline/_generated/`, and tests in `tests/`. @@ -188,6 +188,16 @@ if result.get("isError"): raise RuntimeError("Re-verification was refused.") ``` +`wait_for_reverification` polls `get_reverification` for the request id that call returned. It is a method on both clients; use `await` with `AsyncProoflineClient`. The optional `organization_id` keyword applies to every read in the wait. The first pause is 5 seconds, and each later pause doubles up to 60 seconds. The default `timeout` is 300 seconds. + +```python +settled = client.wait_for_reverification(request_id) +if settled.get("isError"): + raise RuntimeError("Re-verification was refused.") +``` + +The public contract records each finding's re-verification as `LocalReverificationOutcome`. `PENDING` means the review is still running, so the wait continues while any finding is `PENDING` or has not recorded an outcome. `RESOLVED_VERIFIED`, `STILL_PRESENT`, and `NOT_VERIFIED` are finished outcomes and stop the wait. `NOT_VERIFIED` does not establish a fix. A tool result with `isError` returns immediately. Any other `ProoflineError` propagates and is not retried. When the deadline expires first, the call raises `ProoflineError` with type `urn:proofline:sdk:timeout`. + Calls under `client.fixes` never retry. Results retain untrusted-text wrappers, availability, assessment gaps, and `isError`. `PENDING` and `NOT_VERIFIED` do not establish a fix, and a tool request never records a human disposition. ## Development diff --git a/proofline/client.py b/proofline/client.py index dd5106f6..004c3f1b 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -70,10 +70,10 @@ from ._generated.models.start_session import StartSession from ._generated.models.stop_response import StopResponse from ._generated.types import UNSET, Response, Unset -from ._mcp import AsyncMcpClient, McpClient +from ._mcp import AsyncMcpClient, KnowledgeResult, McpClient from ._transport import ProoflineError from .exports import ExportDataset, ExportFormat, ExportPage, decode_export -from .fixes import AsyncFixesClient, FixesClient +from .fixes import AsyncFixesClient, FixesClient, _reverification_in_progress from .knowledge import AsyncKnowledgeClient, KnowledgeClient from .outcomes import ReviewOutcome, outcome @@ -582,6 +582,51 @@ def wait_for_review( finally: _transport.DEADLINE.reset(deadline) + def wait_for_reverification( + self, + request_id: str, + *, + timeout: float = 300, + organization_id: str | None = None, + ) -> KnowledgeResult: + """Wait until a re-verification records a finished outcome. + + Polls fixes.get_reverification, waiting 5 seconds at first and doubling + up to 60. PENDING means the review is still running. RESOLVED_VERIFIED, + STILL_PRESENT and NOT_VERIFIED finish the wait. NOT_VERIFIED does not + establish a fix. A result with isError returns immediately. Any other + ProoflineError propagates. The deadline raises ProoflineError with type + urn:proofline:sdk:timeout. + """ + + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The re-verification timeout must be a finite nonnegative number of seconds." + ) + deadline = _transport.DEADLINE.set(monotonic() + timeout) + interval = 5.0 + try: + while (_transport.remaining() or 0) > 0: + try: + result = self.fixes.get_reverification( + request_id, organization_id=organization_id + ) + except ProoflineError as error: + if error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + if result.get("isError"): + return result + if (_transport.remaining() or 0) <= 0: + break + if not _reverification_in_progress(result): + return result + sleep(min(interval, _transport.remaining() or 0)) + interval = min(60, interval * 2) + raise _transport.timeout_error() + finally: + _transport.DEADLINE.reset(deadline) + class AsyncProoflineClient(AsyncOperations): def __init__( @@ -967,3 +1012,38 @@ async def wait_for_review( return timed_out or ReviewOutcome("TIMED_OUT", url) finally: _transport.DEADLINE.reset(deadline) + + async def wait_for_reverification( + self, + request_id: str, + *, + timeout: float = 300, + organization_id: str | None = None, + ) -> KnowledgeResult: + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The re-verification timeout must be a finite nonnegative number of seconds." + ) + deadline = _transport.DEADLINE.set(monotonic() + timeout) + interval = 5.0 + try: + while (_transport.remaining() or 0) > 0: + try: + result = await self.fixes.get_reverification( + request_id, organization_id=organization_id + ) + except ProoflineError as error: + if error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + if result.get("isError"): + return result + if (_transport.remaining() or 0) <= 0: + break + if not _reverification_in_progress(result): + return result + await async_sleep(min(interval, _transport.remaining() or 0)) + interval = min(60, interval * 2) + raise _transport.timeout_error() + finally: + _transport.DEADLINE.reset(deadline) diff --git a/proofline/fixes.py b/proofline/fixes.py index 85e437b5..d5300567 100644 --- a/proofline/fixes.py +++ b/proofline/fixes.py @@ -4,8 +4,68 @@ from typing import Any +from ._generated.models.local_reverification_outcome import LocalReverificationOutcome from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools +# The public contract's only in-progress re-verification value. The other +# LocalReverificationOutcome values are recorded results. +_PENDING = LocalReverificationOutcome.PENDING.value +_TERMINAL_OUTCOMES = frozenset( + member.value for member in LocalReverificationOutcome if member.value != _PENDING +) + + +def _reverification_payload(result: KnowledgeResult) -> dict[str, Any]: + content = result.get("structuredContent") + if not isinstance(content, dict): + return {} + data = content.get("data") + if content.get("ok") is True and isinstance(data, dict): + return data + return content + + +def _collect_finding_outcomes(value: object, found: list[str]) -> None: + if isinstance(value, list): + for item in value: + _collect_finding_outcomes(item, found) + return + if not isinstance(value, dict): + return + if "finding_id" in value: + outcome = value.get("outcome") + # A listed finding with no outcome has not recorded a result yet. + found.append(outcome if isinstance(outcome, str) else _PENDING) + for child in value.values(): + _collect_finding_outcomes(child, found) + + +def _reverification_in_progress(result: KnowledgeResult) -> bool: + """True while this get_reverification read is still running. + + LocalReverificationOutcome describes PENDING as the review still running, + and RESOLVED_VERIFIED, STILL_PRESENT and NOT_VERIFIED as recorded results. + A string outside that enum is not a recorded result. An isError result is + not in progress; the caller returns it. + """ + + if result.get("isError"): + return False + payload = _reverification_payload(result) + outcomes: list[str] = [] + if "finding_id" not in payload: + outcome = payload.get("outcome") + if isinstance(outcome, str): + outcomes.append(outcome) + _collect_finding_outcomes(payload, outcomes) + if any(outcome not in _TERMINAL_OUTCOMES for outcome in outcomes): + return True + if payload.get("status") == _PENDING: + return True + if outcomes or isinstance(payload.get("status"), str): + return False + return True + class FixesClient(McpTools): def list_open_findings( diff --git a/scripts/contracts.py b/scripts/contracts.py index e8e4e73a..90e96c7f 100644 --- a/scripts/contracts.py +++ b/scripts/contracts.py @@ -31,7 +31,14 @@ def main() -> None: from proofline import AsyncProoflineClient, ProoflineClient 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_reverification", + } exposed = { name for name in dir(client) diff --git a/tests/test_http.py b/tests/test_http.py index 7b922c34..07d5d497 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2249,6 +2249,173 @@ async def invoke(name: str, *args: Any, **kwargs: Any) -> Any: assert len(observed) == 5 +def mcp_tool_reply( + request: Request, + result: dict[str, Any] | None = None, + *, + status: int = 200, + problem: dict[str, Any] | None = None, +) -> Reply: + message = json.loads(request.body) + if message["method"] == "initialize": + return Reply(body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}}) + if message["method"] == "notifications/initialized": + return Reply(status=202, body=b"") + if status != 200: + return Reply(status, problem or {"detail": "unavailable"}) + return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result}) + + +def reverification_result( + *outcomes: str, + status: str | None = None, + error: bool = False, + wrapped: bool = False, +) -> dict[str, Any]: + payload: dict[str, Any] = {} + if outcomes: + payload["findings"] = [ + {"finding_id": str(FINDING), "outcome": outcome, "checks": []} for outcome in outcomes + ] + if status is not None: + payload["status"] = status + structured = {"ok": True, "data": payload} if wrapped else payload + result: dict[str, Any] = { + "content": [{"type": "text", "text": "untrusted source"}], + "structuredContent": structured, + } + if error: + result["isError"] = True + return result + + +def tool_params(server: Server) -> list[dict[str, Any]]: + params = [] + for request in server.requests: + message = json.loads(request.body) + if message.get("method") == "tools/call": + params.append(message["params"]) + return params + + +@MODES +async def test_wait_for_reverification_returns_after_pending_polls( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + request_id = str(REVIEW) + organization_id = str(ORG) + responses = [ + reverification_result("PENDING", status="PENDING"), + reverification_result("RESOLVED_VERIFIED", "PENDING", status="PENDING"), + reverification_result("RESOLVED_VERIFIED", "NOT_VERIFIED"), + ] + seen = 0 + + def respond(request: Request, index: int) -> Reply: + nonlocal seen + message = json.loads(request.body) + if message["method"] == "tools/call": + result = responses[seen] + seen += 1 + else: + result = None + return mcp_tool_reply(request, result) + + with Server(respond) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_reverification", + request_id, + timeout=100, + organization_id=organization_id, + ) + assert result == responses[2] + assert ( + tool_params(server) + == [ + { + "name": "get_reverification", + "arguments": {"request_id": request_id, "organization_id": organization_id}, + } + ] + * 3 + ) + assert clock.delays == [5, 10] + # A finished outcome, including one that does not establish a fix, returns on that read. + for outcome in ("STILL_PRESENT", "NOT_VERIFIED"): + body = reverification_result(outcome, wrapped=True) + with Server(lambda request, index: mcp_tool_reply(request, body)) as server: + async with session(mode, server.url) as client: + assert await call(client, "wait_for_reverification", request_id) == body + assert len(tool_params(server)) == 1 + unavailable = reverification_result(status="UNAVAILABLE") + with Server(lambda request, index: mcp_tool_reply(request, unavailable)) as server: + async with session(mode, server.url) as client: + assert await call(client, "wait_for_reverification", request_id) == unavailable + assert len(tool_params(server)) == 1 + assert clock.delays == [5, 10] + + +@MODES +async def test_wait_for_reverification_returns_tool_errors_immediately( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + refused = reverification_result("PENDING", status="PENDING", error=True) + with Server(lambda request, index: mcp_tool_reply(request, refused)) as server: + async with session(mode, server.url) as client: + assert await call(client, "wait_for_reverification", str(REVIEW)) == refused + assert tool_params(server) == [ + {"name": "get_reverification", "arguments": {"request_id": str(REVIEW)}} + ] + assert clock.delays == [] + + +@MODES +async def test_wait_for_reverification_raises_proofline_error( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + + def respond(request: Request, index: int) -> Reply: + return mcp_tool_reply(request, status=503, problem={"detail": "unavailable"}) + + with Server(respond) as server: + async with session(mode, server.url) as client: + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_reverification", str(REVIEW), timeout=100) + assert raised.value.status == 503 + assert raised.value.type == "about:blank" + assert raised.value.detail == "unavailable" + assert len(tool_params(server)) == 1 + assert clock.delays == [] + + +@MODES +async def test_wait_for_reverification_backs_off_until_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + pending = reverification_result("PENDING", status="PENDING") + with Server(lambda request, index: mcp_tool_reply(request, pending)) as server: + async with session(mode, server.url) as client: + with pytest.raises(ValueError, match="finite nonnegative"): + await call(client, "wait_for_reverification", str(REVIEW), timeout=float("nan")) + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_reverification", str(REVIEW), timeout=0) + assert raised.value.status == 0 + assert raised.value.type == "urn:proofline:sdk:timeout" + assert server.requests == [] + with pytest.raises(ProoflineError) as raised: + await call(client, "wait_for_reverification", str(REVIEW), timeout=260) + assert raised.value.type == "urn:proofline:sdk:timeout" + assert raised.value.status == 0 + assert clock.delays == [5, 10, 20, 40, 60, 60, 60, 5] + assert len(tool_params(server)) == 8 + + @MODES async def test_shared_review_outcome_contract(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: Clock(monkeypatch) @@ -2478,6 +2645,7 @@ def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> No 'fixes.get_fix_context("finding-id")', 'fixes.request_reverification("review-id", ["finding-id"], "a" * 40, note="fixed")', 'fixes.get_reverification("request-id")', + 'wait_for_reverification("request-id", timeout=30)', ] for prefix, kind, wait in [ ("", "ProoflineClient", ""),