diff --git a/proofline/fixes.py b/proofline/fixes.py index 85e437b5..0b99045f 100644 --- a/proofline/fixes.py +++ b/proofline/fixes.py @@ -2,10 +2,38 @@ from __future__ import annotations +import math +from time import sleep from typing import Any +from anyio import sleep as async_sleep + +from . import _transport from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools +_ACTIVE_REVERIFICATION_STATES = frozenset(("PENDING", "QUEUED", "RUNNING", "IN_PROGRESS")) + + +def _validate_wait_args(request_id: str, timeout: float, poll_interval: float) -> None: + if not isinstance(request_id, str) or not request_id.strip(): + raise ValueError("request_id must be a non-empty string.") + if not math.isfinite(timeout) or timeout < 0: + raise ValueError( + "The reverification timeout must be a finite nonnegative number of seconds." + ) + if not math.isfinite(poll_interval) or poll_interval <= 0: + raise ValueError("The poll interval must be a finite positive number of seconds.") + + +def _is_active_reverification(result: KnowledgeResult) -> bool: + if result.get("isError"): + return False + structured = result.get("structuredContent") + if not isinstance(structured, dict): + return False + status = structured.get("status") + return isinstance(status, str) and status.upper() in _ACTIVE_REVERIFICATION_STATES + class FixesClient(McpTools): def list_open_findings( @@ -49,6 +77,38 @@ def get_reverification( "get_reverification", {"request_id": request_id}, organization_id=organization_id ) + def wait_for_reverification( + self, + request_id: str, + *, + timeout: float = 300, + poll_interval: float = 5.0, + organization_id: str | None = None, + ) -> KnowledgeResult: + """Poll get_reverification until it reaches a terminal state or raises TimeoutError.""" + + _validate_wait_args(request_id, timeout, poll_interval) + interval = poll_interval + max_interval = max(60.0, poll_interval) + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + result = self.get_reverification(request_id, organization_id=organization_id) + except _transport.RetryDeadlineExceeded: + break + except _transport.ProoflineError as error: + if timeout > 0 and error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + if not _is_active_reverification(result): + return result + budget = _transport.remaining() + if timeout == 0 or not budget: + break + sleep(min(interval, budget)) + interval = min(max_interval, interval * 2) + raise TimeoutError(f"Reverification {request_id!r} did not complete within {timeout}s.") + class AsyncFixesClient(AsyncMcpTools): async def list_open_findings( @@ -91,3 +151,37 @@ async def get_reverification( return await self._call( "get_reverification", {"request_id": request_id}, organization_id=organization_id ) + + async def wait_for_reverification( + self, + request_id: str, + *, + timeout: float = 300, + poll_interval: float = 5.0, + organization_id: str | None = None, + ) -> KnowledgeResult: + """Poll get_reverification until it reaches a terminal state or raises TimeoutError.""" + + _validate_wait_args(request_id, timeout, poll_interval) + interval = poll_interval + max_interval = max(60.0, poll_interval) + with _transport.review_wait_budget(timeout): + while timeout == 0 or (_transport.remaining() or 0) > 0: + try: + result = await self.get_reverification( + request_id, organization_id=organization_id + ) + except _transport.RetryDeadlineExceeded: + break + except _transport.ProoflineError as error: + if timeout > 0 and error.status == 0 and (_transport.remaining() or 0) <= 0: + break + raise + if not _is_active_reverification(result): + return result + budget = _transport.remaining() + if timeout == 0 or not budget: + break + await async_sleep(min(interval, budget)) + interval = min(max_interval, interval * 2) + raise TimeoutError(f"Reverification {request_id!r} did not complete within {timeout}s.") diff --git a/tests/test_fixes_wait.py b/tests/test_fixes_wait.py new file mode 100644 index 00000000..cad7e1fa --- /dev/null +++ b/tests/test_fixes_wait.py @@ -0,0 +1,208 @@ +from __future__ import annotations + +import json +from collections.abc import Callable +from typing import Any + +import pytest + +from proofline import AsyncProoflineClient, ProoflineClient, _transport +from proofline import fixes as fixes_module +from proofline._mcp import PROTOCOL +from tests.http_server import Reply, Server + + +def _json_reply(payload: dict[str, Any]) -> Reply: + return Reply(200, json.dumps(payload).encode(), {"Content-Type": "application/json"}) + + +def _mcp_server_handler( + on_call: Callable[[dict[str, Any]], dict[str, Any]], +) -> Callable[[Any, int], Reply]: + def respond(request: Any, _index: int) -> Reply: + body = json.loads(request.body) + method = body.get("method") + if method == "initialize": + return _json_reply( + { + "jsonrpc": "2.0", + "id": body["id"], + "result": { + "protocolVersion": PROTOCOL, + "capabilities": {}, + "serverInfo": {"name": "test", "version": "1"}, + }, + } + ) + if method == "notifications/initialized": + return Reply(202, b"", {}) + result = on_call(body["params"]["arguments"]) + return _json_reply({"jsonrpc": "2.0", "id": body["id"], "result": result}) + + return respond + + +def _status_payload(status: str, *, is_error: bool = False) -> dict[str, Any]: + payload: dict[str, Any] = { + "content": [{"type": "text", "text": f"status: {status}"}], + "structuredContent": {"request_id": "req-1", "status": status}, + } + if is_error: + payload["isError"] = True + return payload + + +def test_wait_for_reverification_polls_until_terminal_sync( + monkeypatch: pytest.MonkeyPatch, +) -> None: + statuses = iter(["PENDING", "RUNNING", "COMPLETED"]) + sleeps: list[float] = [] + seen_args: list[dict[str, Any]] = [] + + def on_call(args: dict[str, Any]) -> dict[str, Any]: + seen_args.append(args) + return _status_payload(next(statuses)) + + monkeypatch.setattr(fixes_module, "sleep", sleeps.append) + + with ( + Server(_mcp_server_handler(on_call)) as server, + ProoflineClient("test-token", base_url=server.url) as client, + ): + result = client.fixes.wait_for_reverification( + "req-1", timeout=30, poll_interval=2.0, organization_id="org-1" + ) + + assert result["structuredContent"] == {"request_id": "req-1", "status": "COMPLETED"} + assert sleeps == [2.0, 4.0] + assert len(seen_args) == 3 + assert all(arg == {"request_id": "req-1", "organization_id": "org-1"} for arg in seen_args) + + +@pytest.mark.asyncio +async def test_wait_for_reverification_polls_until_terminal_async( + monkeypatch: pytest.MonkeyPatch, +) -> None: + statuses = iter(["QUEUED", "IN_PROGRESS", "FAILED"]) + sleeps: list[float] = [] + + def on_call(_args: dict[str, Any]) -> dict[str, Any]: + return _status_payload(next(statuses)) + + async def fake_async_sleep(delay: float) -> None: + sleeps.append(delay) + + monkeypatch.setattr(fixes_module, "async_sleep", fake_async_sleep) + + with Server(_mcp_server_handler(on_call)) as server: + async with AsyncProoflineClient("test-token", base_url=server.url) as client: + result = await client.fixes.wait_for_reverification( + "req-1", timeout=30, poll_interval=1.5 + ) + + assert result["structuredContent"] == {"request_id": "req-1", "status": "FAILED"} + assert sleeps == [1.5, 3.0] + + +def test_wait_for_reverification_returns_immediately_on_tool_error() -> None: + calls = 0 + + def on_call(_args: dict[str, Any]) -> dict[str, Any]: + nonlocal calls + calls += 1 + return _status_payload("PENDING", is_error=True) + + with ( + Server(_mcp_server_handler(on_call)) as server, + ProoflineClient("test-token", base_url=server.url) as client, + ): + result = client.fixes.wait_for_reverification("req-1", timeout=30, poll_interval=1.0) + + assert result.get("isError") is True + assert calls == 1 + + +def test_wait_for_reverification_times_out_when_still_pending() -> None: + def on_call(_args: dict[str, Any]) -> dict[str, Any]: + return _status_payload("PENDING") + + with ( + Server(_mcp_server_handler(on_call)) as server, + ProoflineClient("test-token", base_url=server.url) as client, + ): + with pytest.raises(TimeoutError, match="req-1"): + client.fixes.wait_for_reverification("req-1", timeout=0, poll_interval=1.0) + + +def test_wait_for_reverification_preserves_large_poll_interval( + monkeypatch: pytest.MonkeyPatch, +) -> None: + statuses = iter(["PENDING", "RUNNING", "COMPLETED"]) + sleeps: list[float] = [] + + def on_call(_args: dict[str, Any]) -> dict[str, Any]: + return _status_payload(next(statuses)) + + monkeypatch.setattr(fixes_module, "sleep", sleeps.append) + + with ( + Server(_mcp_server_handler(on_call)) as server, + ProoflineClient("test-token", base_url=server.url) as client, + ): + result = client.fixes.wait_for_reverification("req-1", timeout=300, poll_interval=90.0) + + assert result["structuredContent"] == {"request_id": "req-1", "status": "COMPLETED"} + assert sleeps == [90.0, 90.0] + + +@pytest.mark.asyncio +async def test_wait_for_reverification_times_out_when_budget_exhausted_async( + monkeypatch: pytest.MonkeyPatch, +) -> None: + now = 100.0 + slept = False + + def fake_monotonic() -> float: + return now + + def on_call(_args: dict[str, Any]) -> dict[str, Any]: + nonlocal now + # Advance the fake clock past the 5.0s deadline during the status call. + now += 6.0 + return _status_payload("RUNNING") + + async def fake_async_sleep(_delay: float) -> None: + nonlocal slept + slept = True + + monkeypatch.setattr(_transport, "monotonic", fake_monotonic) + monkeypatch.setattr(fixes_module, "async_sleep", fake_async_sleep) + + with Server(_mcp_server_handler(on_call)) as server: + async with AsyncProoflineClient("test-token", base_url=server.url) as client: + with pytest.raises(TimeoutError, match="req-1"): + await client.fixes.wait_for_reverification("req-1", timeout=5.0, poll_interval=1.0) + + assert not slept + + +@pytest.mark.parametrize( + ("request_id", "timeout", "poll_interval"), + [ + ("", 10, 1.0), + (" ", 10, 1.0), + ("req-1", -1, 1.0), + ("req-1", float("nan"), 1.0), + ("req-1", 10, 0.0), + ("req-1", 10, -2.0), + ("req-1", 10, float("inf")), + ], +) +def test_wait_for_reverification_validates_arguments( + request_id: str, timeout: float, poll_interval: float +) -> None: + with ProoflineClient("test-token") as client: + with pytest.raises(ValueError): + client.fixes.wait_for_reverification( + request_id, timeout=timeout, poll_interval=poll_interval + )