Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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`.
Expand Down
93 changes: 83 additions & 10 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -476,23 +544,28 @@ 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:
self._inner.close()


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)
Expand Down Expand Up @@ -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:
Expand Down
45 changes: 42 additions & 3 deletions proofline/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."
)
Expand Down Expand Up @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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.

Expand All @@ -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:
Expand All @@ -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)
Expand All @@ -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(
Expand All @@ -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)
Expand Down Expand Up @@ -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.")
Expand All @@ -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)
Expand Down
Loading