diff --git a/README.md b/README.md index 721949da..729bc833 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,15 @@ with ProoflineClient(os.environ["PROOFLINE_TOKEN"]) as client: When no token is passed, the clients read `PROOFLINE_TOKEN` from the environment, keep the token in memory, and redact it from diagnostic output. +Both clients accept `rate_limit` to pace HTTP request attempts, including retries and calls made through the shared MCP, knowledge, fixes, and export clients. The value is a finite positive number of attempts per second; `None` (the default) disables pacing. The limit applies to one client instance and is not shared across processes or separate client instances. Waiting for a request counts against the configured HTTP timeout and any active wait deadline. + +The configured HTTP `timeout` bounds a complete HTTP operation, including request pacing, retry attempts, retry waits, and response reading. An active `wait_for_review` deadline can shorten that budget. + +```python +with ProoflineClient(rate_limit=2.0) as client: + ... # At most one request attempt every 0.5 seconds on average. +``` + With `AsyncProoflineClient`, use `await` for a single result, such as `await client.list_reviews(organization_id)` for one page. Use `async for` with `iter_reviews` to read individual reviews across pages, or with `iter_export_pages` to read export pages. ```python @@ -76,6 +85,28 @@ if outcome.status != "COMPLETED": `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. +Pass `on_update` to receive each pending `CustomerReviewDetail` as the wait polls. The synchronous client takes a synchronous callback. The asynchronous client accepts either a synchronous callback or an `async` callback and awaits it. Callbacks do not run for terminal or timed-out results, and callback exceptions propagate to the caller. + +```python +def show_progress(review): + print(review.status) + + +with ProoflineClient() as client: + outcome = client.wait_for_review(organization_id, review_id, on_update=show_progress) +``` + +```python +async def show_progress(review): + print(review.status) + + +async with AsyncProoflineClient() as client: + outcome = await client.wait_for_review(organization_id, review_id, on_update=show_progress) +``` + +Callbacks run inline while the wait's deadline is active. Callback execution itself is not interrupted when the timeout expires, so keep callbacks quick; the wait checks the deadline again after the callback returns. + ## Review exports `export_reviews` reads one CSV or NDJSON page over the bounded transport. Export tokens require `analytics:read`. diff --git a/proofline/_transport.py b/proofline/_transport.py index 8736ee97..aa0fc70e 100644 --- a/proofline/_transport.py +++ b/proofline/_transport.py @@ -6,6 +6,7 @@ import math import os import re +import threading from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Callable, Generator, Iterator from contextlib import contextmanager @@ -67,6 +68,62 @@ DEADLINE: ContextVar[float | None] = ContextVar("proofline_request_deadline", default=None) +def validate_rate_limit(value: float | None) -> float | None: + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError("rate_limit must be a finite positive number of requests per second.") + try: + rate = float(value) + except OverflowError: + raise ValueError( + "rate_limit must be a finite positive number of requests per second." + ) from None + if not math.isfinite(rate) or rate <= 0: + raise ValueError("rate_limit must be a finite positive number of requests per second.") + return rate + + +class RequestPacer: + """Thread-safe per-instance schedule for request attempt start times.""" + + def __init__(self, rate_limit: float | None) -> None: + self._interval = 0.0 if rate_limit is None else 1.0 / rate_limit + self._next = 0.0 + self._lock = threading.Lock() + + def _reserve(self) -> float: + with self._lock: + now = monotonic() + scheduled = max(now, self._next) + self._next = scheduled + self._interval + return scheduled + + def wait_sync(self, deadline: float) -> None: + if self._interval == 0: + return + scheduled = self._reserve() + delay = scheduled - monotonic() + if delay > 0: + if delay >= deadline - monotonic(): + raise timeout_error() + sleep(delay) + if monotonic() >= deadline: + raise timeout_error() + + async def wait_async(self, deadline: float) -> None: + if self._interval == 0: + return + scheduled = self._reserve() + delay = scheduled - monotonic() + if delay > 0: + if delay >= deadline - monotonic(): + raise timeout_error() + await async_sleep(delay) + if monotonic() >= deadline: + raise timeout_error() + + class BearerAuth(httpx2.Auth): def __init__(self, token: SecretStr) -> None: self._token = token @@ -182,8 +239,11 @@ def remaining() -> float | None: return None if deadline is None else max(0.0, deadline - monotonic()) -def limit_timeout(request: httpx2.Request) -> None: +def limit_timeout(request: httpx2.Request, deadline: float | None = None) -> None: budget = remaining() + attempt_budget = None if deadline is None else max(0.0, deadline - monotonic()) + if attempt_budget is not None: + budget = attempt_budget if budget is None else min(budget, attempt_budget) if budget is None: return if budget <= 0: @@ -330,8 +390,11 @@ def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError: ) -def delay_within_deadline(delay: float) -> float: +def delay_within_deadline(delay: float, deadline: float | None = None) -> float: budget = remaining() + if deadline is not None: + operation_budget = max(0.0, deadline - monotonic()) + budget = operation_budget if budget is None else min(budget, operation_budget) return delay if budget is None else min(delay, budget) @@ -433,15 +496,20 @@ async def aclose(self) -> None: class RetryTransport(httpx2.BaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + def __init__(self, token: SecretStr, timeout: float, rate_limit: float | None = None) -> None: self._token = token self._timeout = timeout + self._pacer = RequestPacer(rate_limit) self._inner = SyncHTTPTransport() def handle_request(self, request: httpx2.Request) -> httpx2.Response: + deadline = monotonic() + self._timeout + caller_deadline = DEADLINE.get() + if caller_deadline is not None: + deadline = min(deadline, caller_deadline) for attempt in range(4): - limit_timeout(request) - deadline = monotonic() + self._timeout + self._pacer.wait_sync(deadline) + limit_timeout(request, deadline) marker = IO_DEADLINE.set(io_deadline(deadline)) try: response = self._inner.handle_request(request) @@ -476,7 +544,7 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response: or delay is None ): raise error from None - sleep(delay_within_deadline(delay)) + sleep(delay_within_deadline(delay, deadline)) raise timeout_error() def close(self) -> None: @@ -484,15 +552,20 @@ def close(self) -> None: class AsyncRetryTransport(httpx2.AsyncBaseTransport): - def __init__(self, token: SecretStr, timeout: float) -> None: + def __init__(self, token: SecretStr, timeout: float, rate_limit: float | None = None) -> None: self._token = token self._timeout = timeout + self._pacer = RequestPacer(rate_limit) self._inner = httpx2.AsyncHTTPTransport() async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response: + deadline = monotonic() + self._timeout + caller_deadline = DEADLINE.get() + if caller_deadline is not None: + deadline = min(deadline, caller_deadline) for attempt in range(4): - limit_timeout(request) - deadline = monotonic() + self._timeout + await self._pacer.wait_async(deadline) + limit_timeout(request, deadline) try: with anyio.fail_after(io_budget(deadline)): response = await self._inner.handle_async_request(request) @@ -527,7 +600,7 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response or delay is None ): raise error from None - await async_sleep(delay_within_deadline(delay)) + await async_sleep(delay_within_deadline(delay, deadline)) raise timeout_error() async def aclose(self) -> None: diff --git a/proofline/client.py b/proofline/client.py index 1d8c1519..52fe704c 100644 --- a/proofline/client.py +++ b/proofline/client.py @@ -2,6 +2,7 @@ from __future__ import annotations +import inspect import math from asyncio import sleep as async_sleep from collections.abc import AsyncIterator, Awaitable, Callable, Iterator @@ -147,7 +148,17 @@ def _review_url(base_url: str, organization_id: UUID, review_id: UUID) -> str: def _page_limits(page_size: int, max_pages: int, max_items: int) -> None: - if not 1 <= page_size <= 100 or not 1 <= max_pages <= 1_000 or not 1 <= max_items <= 100_000: + if ( + isinstance(page_size, bool) + or not isinstance(page_size, int) + or isinstance(max_pages, bool) + or not isinstance(max_pages, int) + or isinstance(max_items, bool) + or not isinstance(max_items, int) + or not 1 <= page_size <= 100 + or not 1 <= max_pages <= 1_000 + or not 1 <= max_items <= 100_000 + ): raise ValueError( "Pagination requires page_size 1..100, max_pages 1..1000, max_items 1..100000." ) @@ -221,7 +232,15 @@ def __init__( *, base_url: str = "https://proofline.sh", timeout: float = 30, + rate_limit: float | None = None, ) -> None: + """Create a synchronous client. + + ``rate_limit`` optionally caps average HTTP request attempts per second + for this client instance. The limit is not shared across processes or + separate clients. + """ + rate_limit = _transport.validate_rate_limit(rate_limit) self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) self._http = httpx2.Client( @@ -234,7 +253,7 @@ def __init__( timeout=httpx2.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.RetryTransport(self._api.token, timeout), + transport=_transport.RetryTransport(self._api.token, timeout, rate_limit), ) self._api.set_httpx_client(self._http) self.mcp = McpClient(self._http) @@ -546,6 +565,7 @@ def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + on_update: Callable[[CustomerReviewDetail], None] | None = None, ) -> ReviewOutcome: """Wait for recorded review completion or return TIMED_OUT. @@ -554,6 +574,10 @@ def wait_for_review( head_commit_sha holds the outcome to that commit. A review pinned to another head ends the wait on that read and is never COMPLETED. + + on_update is called with the current review after each poll while the + review is still pending. It is not called on a terminal or timed-out + result; inspect the returned ReviewOutcome for those. """ if not math.isfinite(timeout) or timeout < 0: @@ -576,6 +600,8 @@ def wait_for_review( result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result + if on_update is not None: + on_update(last) sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) @@ -591,7 +617,15 @@ def __init__( *, base_url: str = "https://proofline.sh", timeout: float = 30, + rate_limit: float | None = None, ) -> None: + """Create an asynchronous client. + + ``rate_limit`` optionally caps average HTTP request attempts per second + for this client instance. The limit is not shared across processes or + separate clients. + """ + rate_limit = _transport.validate_rate_limit(rate_limit) self._api = _configuration(token, base_url, timeout) self._base_url = _transport.base_url(base_url) self._http = httpx2.AsyncClient( @@ -604,7 +638,7 @@ def __init__( timeout=httpx2.Timeout(timeout), follow_redirects=False, trust_env=False, - transport=_transport.AsyncRetryTransport(self._api.token, timeout), + transport=_transport.AsyncRetryTransport(self._api.token, timeout, rate_limit), ) self._api.set_async_httpx_client(self._http) self.mcp = AsyncMcpClient(self._http) @@ -941,6 +975,7 @@ async def wait_for_review( *, timeout: float = 300, head_commit_sha: str | None = None, + on_update: Callable[[CustomerReviewDetail], Awaitable[None] | None] | None = None, ) -> ReviewOutcome: if not math.isfinite(timeout) or timeout < 0: raise ValueError("The review timeout must be a finite nonnegative number of seconds.") @@ -962,6 +997,10 @@ async def wait_for_review( result = outcome(last, url, review_id=review_id, head_commit_sha=head_commit_sha) if result is not None: return result + if on_update is not None: + update = on_update(last) + if inspect.isawaitable(update): + await update await async_sleep(min(interval, _transport.remaining() or 0)) interval = min(60, interval * 2) timed_out = outcome(last, url, "TIMED_OUT", head_commit_sha=head_commit_sha) diff --git a/tests/test_http.py b/tests/test_http.py index 0af9d60f..5174235e 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -15,6 +15,7 @@ import tomllib import traceback from collections.abc import AsyncIterator +from concurrent.futures import ThreadPoolExecutor from contextlib import asynccontextmanager from datetime import UTC, datetime, timedelta from pathlib import Path @@ -127,6 +128,264 @@ async def async_sleep(self, delay: float) -> None: await asyncio.sleep(0) +@MODES +async def test_wait_on_update_receives_pending_reviews_in_poll_order( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + updates: list[CustomerReviewDetail] = [] + previous_deadline = 10_000.0 + marker = _transport.DEADLINE.set(previous_deadline) + responses = [review("PENDING"), review("RUNNING"), review("COMPLETED")] + try: + 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 result.status == "COMPLETED" + assert [update.status for update in updates] == ["PENDING", "RUNNING"] + assert all(isinstance(update, CustomerReviewDetail) for update in updates) + assert all(update.id == REVIEW for update in updates) + assert len(server.requests) == 3 + assert _transport.DEADLINE.get() == previous_deadline + finally: + _transport.DEADLINE.reset(marker) + assert clock.delays == [5, 10] + + +@MODES +async def test_wait_on_update_is_not_called_when_timeout_has_expired( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + updates: list[CustomerReviewDetail] = [] + with Server(lambda request, index: Reply(body=review("PENDING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, "wait_for_review", ORG, REVIEW, timeout=0, on_update=updates.append + ) + assert result.status == "TIMED_OUT" + assert server.requests == [] + assert updates == [] + + +@MODES +async def test_wait_on_update_exception_propagates_and_resets_deadline( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + Clock(monkeypatch) + previous_deadline = 10_000.0 + marker = _transport.DEADLINE.set(previous_deadline) + + def fail(update: CustomerReviewDetail) -> None: + assert update.id == REVIEW + raise RuntimeError("callback failed") + + try: + with Server(lambda request, index: Reply(body=review("PENDING"))) as server: + async with session(mode, server.url) as client: + with pytest.raises(RuntimeError, match="callback failed"): + await call(client, "wait_for_review", ORG, REVIEW, on_update=fail) + assert _transport.DEADLINE.get() == previous_deadline + finally: + _transport.DEADLINE.reset(marker) + + +@pytest.mark.asyncio +async def test_async_wait_on_update_awaits_async_callback() -> None: + events: list[tuple[str, str]] = [] + + async def on_update(update: CustomerReviewDetail) -> None: + events.append(("started", update.status)) + await asyncio.sleep(0) + events.append(("finished", update.status)) + + responses = [review("PENDING"), review("COMPLETED")] + with Server(lambda request, index: Reply(body=responses[index])) as server: + async with AsyncProoflineClient(TOKEN, base_url=server.url) as client: + result = await client.wait_for_review(ORG, REVIEW, timeout=100, on_update=on_update) + assert result.status == "COMPLETED" + assert events == [("started", "PENDING"), ("finished", "PENDING")] + + +@pytest.mark.asyncio +async def test_async_wait_on_update_exception_propagates_and_resets_deadline( + monkeypatch: pytest.MonkeyPatch, +) -> None: + Clock(monkeypatch) + previous_deadline = 10_000.0 + marker = _transport.DEADLINE.set(previous_deadline) + + async def fail(update: CustomerReviewDetail) -> None: + assert update.id == REVIEW + await asyncio.sleep(0) + raise RuntimeError("async callback failed") + + try: + with Server(lambda request, index: Reply(body=review("RUNNING"))) as server: + async with AsyncProoflineClient(TOKEN, base_url=server.url) as client: + with pytest.raises(RuntimeError, match="async callback failed"): + await client.wait_for_review(ORG, REVIEW, on_update=fail) + assert _transport.DEADLINE.get() == previous_deadline + finally: + _transport.DEADLINE.reset(marker) + + +@MODES +async def test_wait_on_update_that_passes_deadline_finishes_then_times_out( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + completed: list[str] = [] + + def slow_callback(update: CustomerReviewDetail) -> None: + assert update.status == "PENDING" + clock.now += 6 + completed.append("finished") + + with Server(lambda request, index: Reply(body=review("PENDING"))) as server: + async with session(mode, server.url) as client: + result = await call( + client, + "wait_for_review", + ORG, + REVIEW, + timeout=5, + on_update=slow_callback, + ) + assert result.status == "TIMED_OUT" + assert completed == ["finished"] + assert len(server.requests) == 1 + assert clock.delays == [0] + + +@pytest.mark.asyncio +async def test_async_callback_can_finish_after_deadline_before_wait_times_out( + monkeypatch: pytest.MonkeyPatch, +) -> None: + clock = Clock(monkeypatch) + completed: list[str] = [] + + async def slow_callback(update: CustomerReviewDetail) -> None: + assert update.status == "PENDING" + clock.now += 6 + await asyncio.sleep(0) + completed.append("finished") + + with Server(lambda request, index: Reply(body=review("PENDING"))) as server: + async with AsyncProoflineClient(TOKEN, base_url=server.url) as client: + result = await client.wait_for_review(ORG, REVIEW, timeout=5, on_update=slow_callback) + assert result.status == "TIMED_OUT" + assert completed == ["finished"] + assert len(server.requests) == 1 + assert clock.delays == [0] + + +@MODES +async def test_rate_limit_paces_concurrent_shared_http_requests( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(lambda request, index: Reply(body={"ok": True})) as server: + async with session(mode, server.url, rate_limit=2.0) as client: + if mode == "sync": + with ThreadPoolExecutor(max_workers=2) as pool: + await asyncio.gather( + asyncio.to_thread(lambda: pool.submit(client._http.get, "/").result()), + asyncio.to_thread(lambda: pool.submit(client._http.get, "/").result()), + ) + else: + await asyncio.gather(client._http.get("/"), client._http.get("/")) + assert clock.delays == [0.5] + + +@MODES +async def test_rate_limit_none_does_not_wait(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + with Server(lambda request, index: Reply(body={"ok": True})) as server: + async with session(mode, server.url) as client: + if mode == "sync": + client._http.get("/") + else: + await client._http.get("/") + assert clock.delays == [] + + +@MODES +async def test_retry_attempt_obeys_rate_limit(mode: str, monkeypatch: pytest.MonkeyPatch) -> None: + clock = Clock(monkeypatch) + + def respond(request: Request, index: int) -> Reply: + if index == 0: + return Reply(429, {"detail": "Rate limited."}, {"Retry-After": "0"}) + return Reply(body={"ok": True}) + + with Server(respond) as server: + async with session(mode, server.url, rate_limit=2.0) as client: + if mode == "sync": + response = client._http.get("/") + else: + response = await client._http.get("/") + assert response.status_code == 200 + assert len(server.requests) == 2 + assert clock.delays == [0.0, 0.5] + + +@MODES +async def test_rate_limit_wait_counts_against_http_timeout( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(lambda request, index: Reply(body={"ok": True})) as server: + async with session(mode, server.url, timeout=0.1, rate_limit=1.0) as client: + if mode == "sync": + client._http.get("/") + with pytest.raises(ProoflineError) as raised: + client._http.get("/") + else: + await client._http.get("/") + with pytest.raises(ProoflineError) as raised: + await client._http.get("/") + assert raised.value.type == "urn:proofline:sdk:timeout" + assert len(server.requests) == 1 + assert clock.delays == [] + + +@MODES +@pytest.mark.parametrize("value", [True, 0, -1, float("nan"), float("inf"), -float("inf")]) +async def test_rate_limit_rejects_invalid_values(value: object, mode: str) -> None: + with pytest.raises(ValueError, match="rate_limit"): + if mode == "sync": + ProoflineClient(TOKEN, rate_limit=value) # type: ignore[arg-type] + else: + AsyncProoflineClient(TOKEN, rate_limit=value) # type: ignore[arg-type] + + +@MODES +async def test_rate_limit_wait_respects_caller_deadline( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server(lambda request, index: Reply(body={"ok": True})) as server: + async with session(mode, server.url, rate_limit=1.0) as client: + if mode == "sync": + client._http.get("/") + else: + await client._http.get("/") + marker = _transport.DEADLINE.set(clock.now + 0.5) + try: + with pytest.raises(ProoflineError) as raised: + if mode == "sync": + client._http.get("/") + else: + await client._http.get("/") + assert raised.value.type == "urn:proofline:sdk:timeout" + finally: + _transport.DEADLINE.reset(marker) + assert clock.delays == [] + + @MODES async def test_all_public_operations_use_generated_models_and_scoped_paths(mode: str) -> None: metadata = Path(__file__).resolve().parents[1] / "pyproject.toml" @@ -829,6 +1088,25 @@ def now(cls, tz: Any = None) -> datetime: assert len(server.requests) == 2 +@MODES +async def test_http_timeout_covers_retry_attempts_and_waits( + mode: str, monkeypatch: pytest.MonkeyPatch +) -> None: + clock = Clock(monkeypatch) + with Server( + lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": "2"}) + ) as server: + async with session(mode, server.url, timeout=5) as client: + with pytest.raises(ProoflineError) as raised: + if mode == "sync": + client._http.get("/") + else: + await client._http.get("/") + assert raised.value.type == "urn:proofline:sdk:timeout" + assert len(server.requests) == 3 + assert clock.delays == [2.0, 2.0, 1.0] + + @MODES @pytest.mark.parametrize("status", [429, 503]) async def test_retry_count_is_bounded_for_rate_limit_and_provider_unavailable(