Skip to content
Merged
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
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ The `_*.py` modules are the foundation. Change them only together with the maint
- Every method is retried after an error where the request was never sent (connect, connect-timeout or pool errors), on 429 and on 503.
- A 429 waits at least 1 s. A 429 about the monthly quota is never retried.
- GET is also retried on 502, 504 and transport errors.
- `Retry-After` is not parsed. Redirects are not followed.
- A numeric `Retry-After` on a 429 is honored, clamped to `[MIN_RATE_LIMIT_RETRY_DELAY, MAX_RETRY_DELAY]`. Redirects
are not followed.
- **Errors:** each status maps to its class in `_exceptions.py`. The message is `body["error"]` for JSON, otherwise the response text. `Authorization` is redacted from `.request` and `.response`.
- **Logging:** use the `logging.getLogger("whitecircle")` logger with a `NullHandler`. `WHITECIRCLE_LOG` only sets its level, and importing never calls `basicConfig`. Never log, or put in exception messages, reprs or test output: API keys, `Authorization` headers, webhook secrets or signatures, request or response bodies, query strings, event content or user identifiers.

Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ All notable changes to this project are documented here. The format follows
Policy direction (for example `Event.tool_call(..., role="assistant")` so an assistant-only Policy judges an agent's
own tool calls).
- `artifacts.check()` now accepts optional `trace_id` and `span_id`.
- `EventsRateLimit` (`limit`, `remaining`, `reset`, `window`) on `EventCheckResult.rate_limit`,
`EventsCheckResult.rate_limit`, and `APIStatusError.rate_limit`, parsed from `x-ratelimit-events-*` response headers
(`None` when absent).
- HTTP `429` retries now honor a numeric `Retry-After` header (clamped between `MIN_RATE_LIMIT_RETRY_DELAY` and
`MAX_RETRY_DELAY`), falling back to exponential backoff when absent or non-numeric.

### Fixed

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,8 +203,8 @@ returns no machine-readable error code, so branch on the exception type.

**Retries.** A check is billed each time it reaches the server, so a POST is resent only when it was never sent
(connection errors before the request went out), or on `429` and `503`. Reads are also retried on `502`, `504` and
transport errors. A `429` waits at least 1 s, and the monthly-quota `429` is never retried. `Retry-After` is not
used and redirects are not followed.
transport errors. A `429` honors a numeric `Retry-After` header (clamped to 1–8 s) or waits at least 1 s, and the
monthly-quota `429` is never retried. Redirects are not followed.

## Async

Expand Down
41 changes: 39 additions & 2 deletions docs/errors-and-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,45 @@ quick = client.with_options(timeout=2.0, max_retries=0)

A check is billed each time it reaches the server. The client therefore resends a POST only when it was never sent
(connection errors before the request went out), or on `429` and `503`. GETs are also retried on `502`, `504` and
transport errors. The backoff is exponential, at least 1 s after a `429`, and a monthly-quota `429` is not retried.
`Retry-After` is not used, and redirects are not followed. The default timeout is 60 s, with 5 s to connect.
transport errors. The backoff is exponential; a `429` honors a numeric `Retry-After` header (clamped to 1–8 s) or waits
at least 1 s, and a monthly-quota `429` is not retried. Redirects are not followed. The default timeout is 60 s, with
5 s to connect.

## Rate limits

Projects with a per-second Event limit enforce a fixed one-second window across all API keys:

- **Counted:** once per Event sent to the API, including `skip=True` Events, and once per stream at start.
Reference-only Events are not counted.
- **Where a rejection shows up:** on `events.check()` (with or without `skip`) and normal `events.check_many()`
batches, a rate-limited Event comes back inside HTTP `200` with `status == "failed"` and `"Rate limit exceeded"` in
`note`. Only a `skip=True` batch on `events.check_many()` fails the whole request with HTTP `429`
(`RateLimitError`, carrying `Retry-After`, which the client retries automatically).
- **Inspecting the budget:** `result.rate_limit` on `EventCheckResult` and `EventsCheckResult` (and `error.rate_limit`
on `APIStatusError`) parses `x-ratelimit-events-{limit,remaining,reset,window}` into an `EventsRateLimit`, or `None`
when the project has no limit or no Event reached the limiter.

Resend rate-limited Events from a normal batch after `rate_limit.reset`:

```python
import time

from whitecircle import Event, WhiteCircle

client = WhiteCircle()
pending = [Event.user(f"message {i}") for i in range(10)]
batch = client.events.check_many(pending, external_session_id="conversation_456")

failed = [
event
for event, item in zip(pending, batch.results, strict=True)
if item.status == "failed" and "rate limit" in (item.note or "").lower()
]
if failed:
time.sleep(batch.rate_limit.reset if batch.rate_limit is not None else 1.0)
retried = client.events.check_many(failed, external_session_id="conversation_456")
print(retried.flagged, retried.rate_limit)
```

## Async

Expand Down
154 changes: 98 additions & 56 deletions src/whitecircle/_base_client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import functools
import math
import os
import random
import time
Expand Down Expand Up @@ -109,6 +110,17 @@ def _resolve_base_url(api_key: str, region: str | None, base_url: str | httpx2.U
return url


def _retry_after_seconds(headers: httpx2.Headers) -> float | None:
raw = headers.get("retry-after")
if raw is None:
return None
try:
seconds = float(raw.strip())
except ValueError:
return None
return seconds if math.isfinite(seconds) and seconds >= 0 else None


@functools.cache
def _adapter(cast_to: Any) -> TypeAdapter[Any]:
return TypeAdapter(cast_to)
Expand Down Expand Up @@ -206,6 +218,10 @@ def _process_response(self, response: httpx2.Response, cast_to: Any) -> Any:
return data if cast_to is None else _adapter(cast_to).validate_python(data)

def _retry_delay(self, attempt: int, error: APIStatusError | None = None) -> float:
if isinstance(error, RateLimitError):
retry_after = _retry_after_seconds(error.response.headers)
if retry_after is not None:
return min(max(retry_after, MIN_RATE_LIMIT_RETRY_DELAY), MAX_RETRY_DELAY)
delay = min(INITIAL_RETRY_DELAY * 2.0 ** min(attempt, 1000), MAX_RETRY_DELAY) * (1 - 0.25 * random.random())
return max(delay, MIN_RATE_LIMIT_RETRY_DELAY) if isinstance(error, RateLimitError) else delay

Expand Down Expand Up @@ -298,6 +314,45 @@ def __init__(
self._owns_client = http_client is None
self._client = http_client or httpx2.Client(limits=DEFAULT_CONNECTION_LIMITS, follow_redirects=False)

def _send_request(
self,
method: str,
path: str,
*,
params: Query | None = None,
body: Mapping[str, object] | None = None,
headers: Headers | None = None,
timeout: Timeout | NotGiven = not_given,
) -> httpx2.Response:
method = method.upper()
attempt = 0
while True:
request = self._build_request(
self._client, method, path, params=params, body=body, headers=headers, timeout=timeout
)
started = time.monotonic()
try:
response = self._client.send(request)
except httpx2.TransportError as error:
if not self._should_retry_error(error, method, attempt):
raise self._connection_error(error, request) from error
delay = self._retry_delay(attempt)
self._log_retry(request, attempt, delay, type(error).__name__)
_sleep(delay)
attempt += 1
continue
_log_response(response, started)
if response.is_success:
return response
status_error = make_status_error(response)
if not self._should_retry_status(status_error, method, attempt):
raise status_error
delay = self._retry_delay(attempt, status_error)
self._log_retry(request, attempt, delay, f"HTTP {response.status_code}")
response.close()
_sleep(delay)
attempt += 1

@overload
def request(
self,
Expand Down Expand Up @@ -334,34 +389,8 @@ def request(
cast_to: type[_T] | None = None,
) -> _T | object:
"""Call an endpoint this SDK doesn't wrap. ``cast_to`` validates the JSON body."""
method = method.upper()
attempt = 0
while True:
request = self._build_request(
self._client, method, path, params=params, body=body, headers=headers, timeout=timeout
)
started = time.monotonic()
try:
response = self._client.send(request)
except httpx2.TransportError as error:
if not self._should_retry_error(error, method, attempt):
raise self._connection_error(error, request) from error
delay = self._retry_delay(attempt)
self._log_retry(request, attempt, delay, type(error).__name__)
_sleep(delay)
attempt += 1
continue
_log_response(response, started)
if response.is_success:
return self._process_response(response, cast_to)
status_error = make_status_error(response)
if not self._should_retry_status(status_error, method, attempt):
raise status_error
delay = self._retry_delay(attempt, status_error)
self._log_retry(request, attempt, delay, f"HTTP {response.status_code}")
response.close()
_sleep(delay)
attempt += 1
response = self._send_request(method, path, params=params, body=body, headers=headers, timeout=timeout)
return self._process_response(response, cast_to)

def copy(
self,
Expand Down Expand Up @@ -433,6 +462,45 @@ def __init__(
self._owns_client = http_client is None
self._client = http_client or httpx2.AsyncClient(limits=DEFAULT_CONNECTION_LIMITS, follow_redirects=False)

async def _send_request(
self,
method: str,
path: str,
*,
params: Query | None = None,
body: Mapping[str, object] | None = None,
headers: Headers | None = None,
timeout: Timeout | NotGiven = not_given,
) -> httpx2.Response:
method = method.upper()
attempt = 0
while True:
request = self._build_request(
self._client, method, path, params=params, body=body, headers=headers, timeout=timeout
)
started = time.monotonic()
try:
response = await self._client.send(request)
except httpx2.TransportError as error:
if not self._should_retry_error(error, method, attempt):
raise self._connection_error(error, request) from error
delay = self._retry_delay(attempt)
self._log_retry(request, attempt, delay, type(error).__name__)
await _async_sleep(delay)
attempt += 1
continue
_log_response(response, started)
if response.is_success:
return response
status_error = make_status_error(response)
if not self._should_retry_status(status_error, method, attempt):
raise status_error
delay = self._retry_delay(attempt, status_error)
self._log_retry(request, attempt, delay, f"HTTP {response.status_code}")
await response.aclose()
await _async_sleep(delay)
attempt += 1

@overload
async def request(
self,
Expand Down Expand Up @@ -469,34 +537,8 @@ async def request(
cast_to: type[_T] | None = None,
) -> _T | object:
"""Call an endpoint this SDK doesn't wrap. ``cast_to`` validates the JSON body."""
method = method.upper()
attempt = 0
while True:
request = self._build_request(
self._client, method, path, params=params, body=body, headers=headers, timeout=timeout
)
started = time.monotonic()
try:
response = await self._client.send(request)
except httpx2.TransportError as error:
if not self._should_retry_error(error, method, attempt):
raise self._connection_error(error, request) from error
delay = self._retry_delay(attempt)
self._log_retry(request, attempt, delay, type(error).__name__)
await _async_sleep(delay)
attempt += 1
continue
_log_response(response, started)
if response.is_success:
return self._process_response(response, cast_to)
status_error = make_status_error(response)
if not self._should_retry_status(status_error, method, attempt):
raise status_error
delay = self._retry_delay(attempt, status_error)
self._log_retry(request, attempt, delay, f"HTTP {response.status_code}")
await response.aclose()
await _async_sleep(delay)
attempt += 1
response = await self._send_request(method, path, params=params, body=body, headers=headers, timeout=timeout)
return self._process_response(response, cast_to)

def copy(
self,
Expand Down
12 changes: 11 additions & 1 deletion src/whitecircle/_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import json
from copy import copy
from typing import Any, cast
from typing import TYPE_CHECKING, Any, cast

import httpx2

if TYPE_CHECKING:
from .types.events import EventsRateLimit

__all__ = [
"APIConnectionError",
"APIError",
Expand Down Expand Up @@ -104,6 +107,13 @@ def __init__(self, message: str, *, response: httpx2.Response, body: object | No
def __str__(self) -> str:
return f"{self.status_code}: {self.message}"

@property
def rate_limit(self) -> "EventsRateLimit | None":
"""Per-second Event limiter state from ``x-ratelimit-events-*`` headers, or ``None`` when absent."""
from .types.events import _parse_events_rate_limit

return _parse_events_rate_limit(self.response.headers)


class BadRequestError(APIStatusError):
pass
Expand Down
30 changes: 30 additions & 0 deletions src/whitecircle/_resource.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from collections.abc import Mapping
from typing import TYPE_CHECKING, TypeVar

import httpx2

from ._types import Headers, NotGiven, Query, Timeout, not_given

if TYPE_CHECKING:
Expand Down Expand Up @@ -42,6 +44,19 @@ def _post(
"POST", path, params=params, body=body, headers=headers, timeout=timeout, cast_to=cast_to
)

def _post_with_headers(
self,
path: str,
*,
body: Mapping[str, object] | None = None,
params: Query | None = None,
headers: Headers | None = None,
timeout: Timeout | NotGiven = not_given,
cast_to: type[_T],
) -> tuple[_T, httpx2.Headers]:
response = self._client._send_request("POST", path, params=params, body=body, headers=headers, timeout=timeout)
return self._client._process_response(response, cast_to), response.headers


class AsyncAPIResource:
_client: "AsyncWhiteCircle"
Expand Down Expand Up @@ -73,3 +88,18 @@ async def _post(
return await self._client.request(
"POST", path, params=params, body=body, headers=headers, timeout=timeout, cast_to=cast_to
)

async def _post_with_headers(
self,
path: str,
*,
body: Mapping[str, object] | None = None,
params: Query | None = None,
headers: Headers | None = None,
timeout: Timeout | NotGiven = not_given,
cast_to: type[_T],
) -> tuple[_T, httpx2.Headers]:
response = await self._client._send_request(
"POST", path, params=params, body=body, headers=headers, timeout=timeout
)
return self._client._process_response(response, cast_to), response.headers
Loading
Loading