Skip to content

Commit 18e8b99

Browse files
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.
1 parent 31b55f7 commit 18e8b99

5 files changed

Lines changed: 329 additions & 4 deletions

File tree

‎README.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# proofline-sdk
22

3-
`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.
3+
`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.
44

55
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/`.
66

@@ -188,6 +188,16 @@ if result.get("isError"):
188188
raise RuntimeError("Re-verification was refused.")
189189
```
190190

191+
`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.
192+
193+
```python
194+
settled = client.wait_for_reverification(request_id)
195+
if settled.get("isError"):
196+
raise RuntimeError("Re-verification was refused.")
197+
```
198+
199+
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`.
200+
191201
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.
192202

193203
## Development

‎proofline/client.py‎

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,10 +70,10 @@
7070
from ._generated.models.start_session import StartSession
7171
from ._generated.models.stop_response import StopResponse
7272
from ._generated.types import UNSET, Response, Unset
73-
from ._mcp import AsyncMcpClient, McpClient
73+
from ._mcp import AsyncMcpClient, KnowledgeResult, McpClient
7474
from ._transport import ProoflineError
7575
from .exports import ExportDataset, ExportFormat, ExportPage, decode_export
76-
from .fixes import AsyncFixesClient, FixesClient
76+
from .fixes import AsyncFixesClient, FixesClient, _reverification_in_progress
7777
from .knowledge import AsyncKnowledgeClient, KnowledgeClient
7878
from .outcomes import ReviewOutcome, outcome
7979

@@ -582,6 +582,51 @@ def wait_for_review(
582582
finally:
583583
_transport.DEADLINE.reset(deadline)
584584

585+
def wait_for_reverification(
586+
self,
587+
request_id: str,
588+
*,
589+
timeout: float = 300,
590+
organization_id: str | None = None,
591+
) -> KnowledgeResult:
592+
"""Wait until a re-verification records a finished outcome.
593+
594+
Polls fixes.get_reverification, waiting 5 seconds at first and doubling
595+
up to 60. PENDING means the review is still running. RESOLVED_VERIFIED,
596+
STILL_PRESENT and NOT_VERIFIED finish the wait. NOT_VERIFIED does not
597+
establish a fix. A result with isError returns immediately. Any other
598+
ProoflineError propagates. The deadline raises ProoflineError with type
599+
urn:proofline:sdk:timeout.
600+
"""
601+
602+
if not math.isfinite(timeout) or timeout < 0:
603+
raise ValueError(
604+
"The re-verification timeout must be a finite nonnegative number of seconds."
605+
)
606+
deadline = _transport.DEADLINE.set(monotonic() + timeout)
607+
interval = 5.0
608+
try:
609+
while (_transport.remaining() or 0) > 0:
610+
try:
611+
result = self.fixes.get_reverification(
612+
request_id, organization_id=organization_id
613+
)
614+
except ProoflineError as error:
615+
if error.status == 0 and (_transport.remaining() or 0) <= 0:
616+
break
617+
raise
618+
if result.get("isError"):
619+
return result
620+
if (_transport.remaining() or 0) <= 0:
621+
break
622+
if not _reverification_in_progress(result):
623+
return result
624+
sleep(min(interval, _transport.remaining() or 0))
625+
interval = min(60, interval * 2)
626+
raise _transport.timeout_error()
627+
finally:
628+
_transport.DEADLINE.reset(deadline)
629+
585630

586631
class AsyncProoflineClient(AsyncOperations):
587632
def __init__(
@@ -967,3 +1012,38 @@ async def wait_for_review(
9671012
return timed_out or ReviewOutcome("TIMED_OUT", url)
9681013
finally:
9691014
_transport.DEADLINE.reset(deadline)
1015+
1016+
async def wait_for_reverification(
1017+
self,
1018+
request_id: str,
1019+
*,
1020+
timeout: float = 300,
1021+
organization_id: str | None = None,
1022+
) -> KnowledgeResult:
1023+
if not math.isfinite(timeout) or timeout < 0:
1024+
raise ValueError(
1025+
"The re-verification timeout must be a finite nonnegative number of seconds."
1026+
)
1027+
deadline = _transport.DEADLINE.set(monotonic() + timeout)
1028+
interval = 5.0
1029+
try:
1030+
while (_transport.remaining() or 0) > 0:
1031+
try:
1032+
result = await self.fixes.get_reverification(
1033+
request_id, organization_id=organization_id
1034+
)
1035+
except ProoflineError as error:
1036+
if error.status == 0 and (_transport.remaining() or 0) <= 0:
1037+
break
1038+
raise
1039+
if result.get("isError"):
1040+
return result
1041+
if (_transport.remaining() or 0) <= 0:
1042+
break
1043+
if not _reverification_in_progress(result):
1044+
return result
1045+
await async_sleep(min(interval, _transport.remaining() or 0))
1046+
interval = min(60, interval * 2)
1047+
raise _transport.timeout_error()
1048+
finally:
1049+
_transport.DEADLINE.reset(deadline)

‎proofline/fixes.py‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,68 @@
44

55
from typing import Any
66

7+
from ._generated.models.local_reverification_outcome import LocalReverificationOutcome
78
from ._mcp import AsyncMcpTools, KnowledgeResult, McpTools
89

10+
# The public contract's only in-progress re-verification value. The other
11+
# LocalReverificationOutcome values are recorded results.
12+
_PENDING = LocalReverificationOutcome.PENDING.value
13+
_TERMINAL_OUTCOMES = frozenset(
14+
member.value for member in LocalReverificationOutcome if member.value != _PENDING
15+
)
16+
17+
18+
def _reverification_payload(result: KnowledgeResult) -> dict[str, Any]:
19+
content = result.get("structuredContent")
20+
if not isinstance(content, dict):
21+
return {}
22+
data = content.get("data")
23+
if content.get("ok") is True and isinstance(data, dict):
24+
return data
25+
return content
26+
27+
28+
def _collect_finding_outcomes(value: object, found: list[str]) -> None:
29+
if isinstance(value, list):
30+
for item in value:
31+
_collect_finding_outcomes(item, found)
32+
return
33+
if not isinstance(value, dict):
34+
return
35+
if "finding_id" in value:
36+
outcome = value.get("outcome")
37+
# A listed finding with no outcome has not recorded a result yet.
38+
found.append(outcome if isinstance(outcome, str) else _PENDING)
39+
for child in value.values():
40+
_collect_finding_outcomes(child, found)
41+
42+
43+
def _reverification_in_progress(result: KnowledgeResult) -> bool:
44+
"""True while this get_reverification read is still running.
45+
46+
LocalReverificationOutcome describes PENDING as the review still running,
47+
and RESOLVED_VERIFIED, STILL_PRESENT and NOT_VERIFIED as recorded results.
48+
A string outside that enum is not a recorded result. An isError result is
49+
not in progress; the caller returns it.
50+
"""
51+
52+
if result.get("isError"):
53+
return False
54+
payload = _reverification_payload(result)
55+
outcomes: list[str] = []
56+
if "finding_id" not in payload:
57+
outcome = payload.get("outcome")
58+
if isinstance(outcome, str):
59+
outcomes.append(outcome)
60+
_collect_finding_outcomes(payload, outcomes)
61+
if any(outcome not in _TERMINAL_OUTCOMES for outcome in outcomes):
62+
return True
63+
if payload.get("status") == _PENDING:
64+
return True
65+
if outcomes or isinstance(payload.get("status"), str):
66+
return False
67+
return True
68+
969

1070
class FixesClient(McpTools):
1171
def list_open_findings(

‎scripts/contracts.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,14 @@ def main() -> None:
3131
from proofline import AsyncProoflineClient, ProoflineClient
3232

3333
for client in (ProoflineClient, AsyncProoflineClient):
34-
helpers = {"close", "aclose", "iter_export_pages", "iter_reviews", "wait_for_review"}
34+
helpers = {
35+
"close",
36+
"aclose",
37+
"iter_export_pages",
38+
"iter_reviews",
39+
"wait_for_review",
40+
"wait_for_reverification",
41+
}
3542
exposed = {
3643
name
3744
for name in dir(client)

‎tests/test_http.py‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2249,6 +2249,173 @@ async def invoke(name: str, *args: Any, **kwargs: Any) -> Any:
22492249
assert len(observed) == 5
22502250

22512251

2252+
def mcp_tool_reply(
2253+
request: Request,
2254+
result: dict[str, Any] | None = None,
2255+
*,
2256+
status: int = 200,
2257+
problem: dict[str, Any] | None = None,
2258+
) -> Reply:
2259+
message = json.loads(request.body)
2260+
if message["method"] == "initialize":
2261+
return Reply(body={"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2025-11-25"}})
2262+
if message["method"] == "notifications/initialized":
2263+
return Reply(status=202, body=b"")
2264+
if status != 200:
2265+
return Reply(status, problem or {"detail": "unavailable"})
2266+
return Reply(body={"jsonrpc": "2.0", "id": 2, "result": result})
2267+
2268+
2269+
def reverification_result(
2270+
*outcomes: str,
2271+
status: str | None = None,
2272+
error: bool = False,
2273+
wrapped: bool = False,
2274+
) -> dict[str, Any]:
2275+
payload: dict[str, Any] = {}
2276+
if outcomes:
2277+
payload["findings"] = [
2278+
{"finding_id": str(FINDING), "outcome": outcome, "checks": []} for outcome in outcomes
2279+
]
2280+
if status is not None:
2281+
payload["status"] = status
2282+
structured = {"ok": True, "data": payload} if wrapped else payload
2283+
result: dict[str, Any] = {
2284+
"content": [{"type": "text", "text": "untrusted source"}],
2285+
"structuredContent": structured,
2286+
}
2287+
if error:
2288+
result["isError"] = True
2289+
return result
2290+
2291+
2292+
def tool_params(server: Server) -> list[dict[str, Any]]:
2293+
params = []
2294+
for request in server.requests:
2295+
message = json.loads(request.body)
2296+
if message.get("method") == "tools/call":
2297+
params.append(message["params"])
2298+
return params
2299+
2300+
2301+
@MODES
2302+
async def test_wait_for_reverification_returns_after_pending_polls(
2303+
mode: str, monkeypatch: pytest.MonkeyPatch
2304+
) -> None:
2305+
clock = Clock(monkeypatch)
2306+
request_id = str(REVIEW)
2307+
organization_id = str(ORG)
2308+
responses = [
2309+
reverification_result("PENDING", status="PENDING"),
2310+
reverification_result("RESOLVED_VERIFIED", "PENDING", status="PENDING"),
2311+
reverification_result("RESOLVED_VERIFIED", "NOT_VERIFIED"),
2312+
]
2313+
seen = 0
2314+
2315+
def respond(request: Request, index: int) -> Reply:
2316+
nonlocal seen
2317+
message = json.loads(request.body)
2318+
if message["method"] == "tools/call":
2319+
result = responses[seen]
2320+
seen += 1
2321+
else:
2322+
result = None
2323+
return mcp_tool_reply(request, result)
2324+
2325+
with Server(respond) as server:
2326+
async with session(mode, server.url) as client:
2327+
result = await call(
2328+
client,
2329+
"wait_for_reverification",
2330+
request_id,
2331+
timeout=100,
2332+
organization_id=organization_id,
2333+
)
2334+
assert result == responses[2]
2335+
assert (
2336+
tool_params(server)
2337+
== [
2338+
{
2339+
"name": "get_reverification",
2340+
"arguments": {"request_id": request_id, "organization_id": organization_id},
2341+
}
2342+
]
2343+
* 3
2344+
)
2345+
assert clock.delays == [5, 10]
2346+
# A finished outcome, including one that does not establish a fix, returns on that read.
2347+
for outcome in ("STILL_PRESENT", "NOT_VERIFIED"):
2348+
body = reverification_result(outcome, wrapped=True)
2349+
with Server(lambda request, index: mcp_tool_reply(request, body)) as server:
2350+
async with session(mode, server.url) as client:
2351+
assert await call(client, "wait_for_reverification", request_id) == body
2352+
assert len(tool_params(server)) == 1
2353+
unavailable = reverification_result(status="UNAVAILABLE")
2354+
with Server(lambda request, index: mcp_tool_reply(request, unavailable)) as server:
2355+
async with session(mode, server.url) as client:
2356+
assert await call(client, "wait_for_reverification", request_id) == unavailable
2357+
assert len(tool_params(server)) == 1
2358+
assert clock.delays == [5, 10]
2359+
2360+
2361+
@MODES
2362+
async def test_wait_for_reverification_returns_tool_errors_immediately(
2363+
mode: str, monkeypatch: pytest.MonkeyPatch
2364+
) -> None:
2365+
clock = Clock(monkeypatch)
2366+
refused = reverification_result("PENDING", status="PENDING", error=True)
2367+
with Server(lambda request, index: mcp_tool_reply(request, refused)) as server:
2368+
async with session(mode, server.url) as client:
2369+
assert await call(client, "wait_for_reverification", str(REVIEW)) == refused
2370+
assert tool_params(server) == [
2371+
{"name": "get_reverification", "arguments": {"request_id": str(REVIEW)}}
2372+
]
2373+
assert clock.delays == []
2374+
2375+
2376+
@MODES
2377+
async def test_wait_for_reverification_raises_proofline_error(
2378+
mode: str, monkeypatch: pytest.MonkeyPatch
2379+
) -> None:
2380+
clock = Clock(monkeypatch)
2381+
2382+
def respond(request: Request, index: int) -> Reply:
2383+
return mcp_tool_reply(request, status=503, problem={"detail": "unavailable"})
2384+
2385+
with Server(respond) as server:
2386+
async with session(mode, server.url) as client:
2387+
with pytest.raises(ProoflineError) as raised:
2388+
await call(client, "wait_for_reverification", str(REVIEW), timeout=100)
2389+
assert raised.value.status == 503
2390+
assert raised.value.type == "about:blank"
2391+
assert raised.value.detail == "unavailable"
2392+
assert len(tool_params(server)) == 1
2393+
assert clock.delays == []
2394+
2395+
2396+
@MODES
2397+
async def test_wait_for_reverification_backs_off_until_timeout(
2398+
mode: str, monkeypatch: pytest.MonkeyPatch
2399+
) -> None:
2400+
clock = Clock(monkeypatch)
2401+
pending = reverification_result("PENDING", status="PENDING")
2402+
with Server(lambda request, index: mcp_tool_reply(request, pending)) as server:
2403+
async with session(mode, server.url) as client:
2404+
with pytest.raises(ValueError, match="finite nonnegative"):
2405+
await call(client, "wait_for_reverification", str(REVIEW), timeout=float("nan"))
2406+
with pytest.raises(ProoflineError) as raised:
2407+
await call(client, "wait_for_reverification", str(REVIEW), timeout=0)
2408+
assert raised.value.status == 0
2409+
assert raised.value.type == "urn:proofline:sdk:timeout"
2410+
assert server.requests == []
2411+
with pytest.raises(ProoflineError) as raised:
2412+
await call(client, "wait_for_reverification", str(REVIEW), timeout=260)
2413+
assert raised.value.type == "urn:proofline:sdk:timeout"
2414+
assert raised.value.status == 0
2415+
assert clock.delays == [5, 10, 20, 40, 60, 60, 60, 5]
2416+
assert len(tool_params(server)) == 8
2417+
2418+
22522419
@MODES
22532420
async def test_shared_review_outcome_contract(mode: str, monkeypatch: pytest.MonkeyPatch) -> None:
22542421
Clock(monkeypatch)
@@ -2478,6 +2645,7 @@ def test_mcp_public_types_accept_legacy_and_targeted_calls(tmp_path: Path) -> No
24782645
'fixes.get_fix_context("finding-id")',
24792646
'fixes.request_reverification("review-id", ["finding-id"], "a" * 40, note="fixed")',
24802647
'fixes.get_reverification("request-id")',
2648+
'wait_for_reverification("request-id", timeout=30)',
24812649
]
24822650
for prefix, kind, wait in [
24832651
("", "ProoflineClient", ""),

0 commit comments

Comments
 (0)