From 10d5ee415f6f6728d139f786d69f5e52161e47e0 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 16:34:10 +0100 Subject: [PATCH 1/6] feat(events): parse x-ratelimit-events-* headers onto results and APIStatusError Add frozen EventsRateLimit(limit, remaining, reset, window) in types/events.py and export it from whitecircle.types. Populate rate_limit on EventCheckResult and EventsCheckResult in sync and async events.check/check_many via an internal _send_request/_post_with_headers hook (leaving public request() unchanged), and expose APIStatusError.rate_limit from error.response.headers. --- src/whitecircle/_base_client.py | 46 ++++++++++++++---- src/whitecircle/_exceptions.py | 12 ++++- src/whitecircle/_resource.py | 30 ++++++++++++ src/whitecircle/resources/events.py | 36 ++++++++++---- src/whitecircle/types/__init__.py | 2 + src/whitecircle/types/events.py | 40 ++++++++++++++++ tests/test_events.py | 73 ++++++++++++++++++++++++++++- 7 files changed, 218 insertions(+), 21 deletions(-) diff --git a/src/whitecircle/_base_client.py b/src/whitecircle/_base_client.py index 6f1b39c..c60f5fe 100644 --- a/src/whitecircle/_base_client.py +++ b/src/whitecircle/_base_client.py @@ -322,7 +322,7 @@ def request( timeout: Timeout | NotGiven = ..., cast_to: None = ..., ) -> object: ... - def request( + def _send_request( self, method: str, path: str, @@ -331,9 +331,7 @@ def request( body: Mapping[str, object] | None = None, headers: Headers | None = None, timeout: Timeout | NotGiven = not_given, - cast_to: type[_T] | None = None, - ) -> _T | object: - """Call an endpoint this SDK doesn't wrap. ``cast_to`` validates the JSON body.""" + ) -> httpx2.Response: method = method.upper() attempt = 0 while True: @@ -353,7 +351,7 @@ def request( continue _log_response(response, started) if response.is_success: - return self._process_response(response, cast_to) + return response status_error = make_status_error(response) if not self._should_retry_status(status_error, method, attempt): raise status_error @@ -363,6 +361,21 @@ def request( _sleep(delay) attempt += 1 + def 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, + cast_to: type[_T] | None = None, + ) -> _T | object: + """Call an endpoint this SDK doesn't wrap. ``cast_to`` validates the JSON body.""" + response = self._send_request(method, path, params=params, body=body, headers=headers, timeout=timeout) + return self._process_response(response, cast_to) + def copy( self, *, @@ -457,7 +470,7 @@ async def request( timeout: Timeout | NotGiven = ..., cast_to: None = ..., ) -> object: ... - async def request( + async def _send_request( self, method: str, path: str, @@ -466,9 +479,7 @@ async def request( body: Mapping[str, object] | None = None, headers: Headers | None = None, timeout: Timeout | NotGiven = not_given, - cast_to: type[_T] | None = None, - ) -> _T | object: - """Call an endpoint this SDK doesn't wrap. ``cast_to`` validates the JSON body.""" + ) -> httpx2.Response: method = method.upper() attempt = 0 while True: @@ -488,7 +499,7 @@ async def request( continue _log_response(response, started) if response.is_success: - return self._process_response(response, cast_to) + return response status_error = make_status_error(response) if not self._should_retry_status(status_error, method, attempt): raise status_error @@ -498,6 +509,21 @@ async def request( await _async_sleep(delay) attempt += 1 + async def 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, + cast_to: type[_T] | None = None, + ) -> _T | object: + """Call an endpoint this SDK doesn't wrap. ``cast_to`` validates the JSON body.""" + 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, *, diff --git a/src/whitecircle/_exceptions.py b/src/whitecircle/_exceptions.py index 5418d1c..907b168 100644 --- a/src/whitecircle/_exceptions.py +++ b/src/whitecircle/_exceptions.py @@ -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", @@ -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 diff --git a/src/whitecircle/_resource.py b/src/whitecircle/_resource.py index d001c04..1fcfa8c 100644 --- a/src/whitecircle/_resource.py +++ b/src/whitecircle/_resource.py @@ -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: @@ -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" @@ -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 diff --git a/src/whitecircle/resources/events.py b/src/whitecircle/resources/events.py index e097678..e3bf447 100644 --- a/src/whitecircle/resources/events.py +++ b/src/whitecircle/resources/events.py @@ -1,10 +1,19 @@ from collections.abc import AsyncIterable, Iterable, Mapping, Sequence -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, TypeVar + +import httpx2 from .._base_client import path_param from .._resource import AsyncAPIResource, SyncAPIResource from .._types import NotGiven, Timeout, not_given -from ..types.events import Event, EventCheckResult, EventLookupResult, EventsCheckResult, EventType +from ..types.events import ( + Event, + EventCheckResult, + EventLookupResult, + EventsCheckResult, + EventType, + parse_events_rate_limit, +) from ..types.shared import InlinePolicy, Role if TYPE_CHECKING: @@ -12,6 +21,13 @@ __all__ = ["AsyncEvents", "Events"] +_RateLimited = TypeVar("_RateLimited", EventCheckResult, EventsCheckResult) + + +def _with_rate_limit(result: _RateLimited, headers: httpx2.Headers) -> _RateLimited: + result.rate_limit = parse_events_rate_limit(headers) + return result + def _envelope( environment_id: str, @@ -78,7 +94,10 @@ def check( inline_policies, skip, ) - return self._post("/api/event", body={**envelope, "event": event}, timeout=timeout, cast_to=EventCheckResult) + result, headers = self._post_with_headers( + "/api/event", body={**envelope, "event": event}, timeout=timeout, cast_to=EventCheckResult + ) + return _with_rate_limit(result, headers) def check_many( self, @@ -106,10 +125,10 @@ def check_many( inline_policies, skip, ) - result = self._post( + result, headers = self._post_with_headers( "/api/events", body={**envelope, "events": events}, timeout=timeout, cast_to=EventsCheckResult ) - return _in_submission_order(result, events) + return _with_rate_limit(_in_submission_order(result, events), headers) def get( self, @@ -203,9 +222,10 @@ async def check( inline_policies, skip, ) - return await self._post( + result, headers = await self._post_with_headers( "/api/event", body={**envelope, "event": event}, timeout=timeout, cast_to=EventCheckResult ) + return _with_rate_limit(result, headers) async def check_many( self, @@ -233,10 +253,10 @@ async def check_many( inline_policies, skip, ) - result = await self._post( + result, headers = await self._post_with_headers( "/api/events", body={**envelope, "events": events}, timeout=timeout, cast_to=EventsCheckResult ) - return _in_submission_order(result, events) + return _with_rate_limit(_in_submission_order(result, events), headers) async def get( self, diff --git a/src/whitecircle/types/__init__.py b/src/whitecircle/types/__init__.py index 6a970ff..6824441 100644 --- a/src/whitecircle/types/__init__.py +++ b/src/whitecircle/types/__init__.py @@ -13,6 +13,7 @@ EventLookupResult, EventResult, EventsCheckResult, + EventsRateLimit, EventStatus, EventType, ) @@ -88,6 +89,7 @@ "EventStatus", "EventType", "EventsCheckResult", + "EventsRateLimit", "GraphEdge", "GraphNode", "GraphNodeRef", diff --git a/src/whitecircle/types/events.py b/src/whitecircle/types/events.py index 80316d8..996301d 100644 --- a/src/whitecircle/types/events.py +++ b/src/whitecircle/types/events.py @@ -1,3 +1,4 @@ +import math from collections.abc import Mapping from datetime import datetime from typing import Any, Literal, Self, TypeAlias, TypedDict, Unpack, get_args @@ -23,6 +24,7 @@ "EventStatus", "EventType", "EventsCheckResult", + "EventsRateLimit", ] EventType: TypeAlias = Literal["message", "artifact", "tool", "function", "agent", "reasoning", "reset"] @@ -179,6 +181,40 @@ def reference(cls, type: SelectorType, event_id: str, *, run_id: str | None = No return cls(type=type, event_id=event_id, **_given(run_id=run_id)) +class EventsRateLimit(BaseModel): + """Per-second Event limiter state from ``x-ratelimit-events-*`` response headers.""" + + model_config = pydantic.ConfigDict(frozen=True, extra="allow", defer_build=True, populate_by_name=True) + + limit: int + """Events the project may send per window.""" + remaining: int + """Events left in the window, from the highest count any Event of this request saw.""" + reset: float + """Seconds until the current window ends.""" + window: float + """Window length in seconds.""" + + +def parse_events_rate_limit(headers: Mapping[str, str]) -> EventsRateLimit | None: + raw_limit = headers.get("x-ratelimit-events-limit") + raw_remaining = headers.get("x-ratelimit-events-remaining") + raw_reset = headers.get("x-ratelimit-events-reset") + raw_window = headers.get("x-ratelimit-events-window") + if raw_limit is None or raw_remaining is None or raw_reset is None or raw_window is None: + return None + try: + limit = int(raw_limit) + remaining = int(raw_remaining) + reset = float(raw_reset) + window = float(raw_window) + except ValueError: + return None + if limit < 0 or remaining < 0 or not math.isfinite(reset) or reset < 0 or not math.isfinite(window) or window < 0: + return None + return EventsRateLimit(limit=limit, remaining=remaining, reset=reset, window=window) + + class CheckedEvent(BaseModel): type: EventType | str status: EventStatus | str @@ -193,6 +229,8 @@ class EventCheckResult(PolicyResultsMixin, BaseModel): """``None`` when nothing was checked: a reference, a failure, a skip or no selected Policy (see ``note``).""" policies: PolicyResults | None = None note: str | None = None + rate_limit: EventsRateLimit | None = None + """Per-second Event limiter state from response headers, or ``None`` when absent.""" class EventResult(PolicyResultsMixin, BaseModel): @@ -217,6 +255,8 @@ class EventsCheckResult(BaseModel): agents: list[EventResult] = [] reasoning: list[EventResult] = [] resets: list[EventResult] = [] + rate_limit: EventsRateLimit | None = None + """Per-second Event limiter state from response headers, or ``None`` when absent.""" _submitted_types: list[EventType] = pydantic.PrivateAttr(default_factory=list[EventType]) diff --git a/tests/test_events.py b/tests/test_events.py index f683e54..76508f0 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -6,8 +6,18 @@ import pytest from pydantic import ValidationError -from whitecircle import ArtifactContent, AsyncWhiteCircle, Event, EventLink, InlinePolicy, Rule, WhiteCircle -from whitecircle.types import EventCheckResult +from whitecircle import ( + ArtifactContent, + AsyncWhiteCircle, + Event, + EventLink, + InlinePolicy, + InternalServerError, + RateLimitError, + Rule, + WhiteCircle, +) +from whitecircle.types import EventCheckResult, EventsRateLimit from .conftest import API_KEY, Call, MockAPI @@ -285,3 +295,62 @@ def test_tool_and_agent_constructors_accept_role() -> None: "name": "worker", "role": "assistant", } + + +RATE_LIMIT_HEADERS = { + "x-ratelimit-events-limit": "5", + "x-ratelimit-events-remaining": "3", + "x-ratelimit-events-reset": "1", + "x-ratelimit-events-window": "1", +} + + +async def test_check_and_check_many_parse_rate_limit_headers(call: Call, api: MockAPI) -> None: + api.json(200, CHECK_RESPONSE, headers={k.title(): v for k, v in RATE_LIMIT_HEADERS.items()}) + single = await call("events", "check", Event.user("hi")) + assert single.rate_limit == EventsRateLimit(limit=5, remaining=3, reset=1.0, window=1.0) + with pytest.raises(ValidationError): + single.rate_limit.remaining = 0 # frozen model + + api.json( + 200, + {"flagged": False, "run_id": "run_1", "messages": [result("message", "evt_1")]}, + headers={**RATE_LIMIT_HEADERS, "x-ratelimit-events-remaining": "0", "x-ratelimit-events-reset": "0.5"}, + ) + batch = await call("events", "check_many", [Event.user("hi", event_id="evt_1")]) + assert batch.rate_limit == EventsRateLimit(limit=5, remaining=0, reset=0.5, window=1.0) + + +@pytest.mark.parametrize( + "headers", + [ + {}, + {"x-ratelimit-limit": "350", "x-ratelimit-remaining": "349", "x-ratelimit-reset": "1"}, + {"x-ratelimit-events-limit": "5", "x-ratelimit-events-remaining": "3"}, + {**RATE_LIMIT_HEADERS, "x-ratelimit-events-limit": "not-an-int"}, + {**RATE_LIMIT_HEADERS, "x-ratelimit-events-reset": "nan"}, + {**RATE_LIMIT_HEADERS, "x-ratelimit-events-remaining": "-1"}, + ], +) +async def test_rate_limit_is_none_when_headers_absent_or_invalid( + call: Call, api: MockAPI, headers: dict[str, str] +) -> None: + api.json(200, CHECK_RESPONSE, headers=headers) + checked = await call("events", "check", Event.user("hi")) + assert checked.rate_limit is None + + +async def test_api_status_error_exposes_rate_limit_headers(call: Call, api: MockAPI) -> None: + api.json( + 429, + {"error": "Monthly request quota exceeded"}, + headers={**RATE_LIMIT_HEADERS, "x-ratelimit-events-remaining": "0"}, + ) + with pytest.raises(RateLimitError) as caught_429: + await call("events", "check_many", [Event.user("hi")], skip=True) + assert caught_429.value.rate_limit == EventsRateLimit(limit=5, remaining=0, reset=1.0, window=1.0) + + api.json(500, {"error": "boom"}) + with pytest.raises(InternalServerError) as caught_500: + await call("events", "check", Event.user("hi")) + assert caught_500.value.rate_limit is None From 075c6ec9a6d15793af0e9b9b9cbd6e57d084d3dc Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 16:35:19 +0100 Subject: [PATCH 2/6] feat(client): honor numeric Retry-After header on 429 responses Parse numeric Retry-After seconds on HTTP 429 responses and clamp the retry delay to [MIN_RATE_LIMIT_RETRY_DELAY, MAX_RETRY_DELAY], falling back to exponential backoff when Retry-After is absent or non-numeric. Update README, docs/errors-and-testing.md, and AGENTS.md. --- AGENTS.md | 3 ++- README.md | 4 ++-- docs/errors-and-testing.md | 5 +++-- src/whitecircle/_base_client.py | 16 ++++++++++++++++ tests/test_client.py | 31 +++++++++++++++++++++++++++++++ 5 files changed, 54 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5d79f5f..8284a41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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. diff --git a/README.md b/README.md index 637564e..671101e 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/errors-and-testing.md b/docs/errors-and-testing.md index e4951fe..c495c4c 100644 --- a/docs/errors-and-testing.md +++ b/docs/errors-and-testing.md @@ -65,8 +65,9 @@ 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. ## Async diff --git a/src/whitecircle/_base_client.py b/src/whitecircle/_base_client.py index c60f5fe..a9f3834 100644 --- a/src/whitecircle/_base_client.py +++ b/src/whitecircle/_base_client.py @@ -1,5 +1,6 @@ import asyncio import functools +import math import os import random import time @@ -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) @@ -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 diff --git a/tests/test_client.py b/tests/test_client.py index 1d02888..6f88566 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -219,6 +219,37 @@ def test_rate_limit_waits_at_least_one_second(client: WhiteCircle, api: MockAPI, assert sleeps == [1.0] +@pytest.mark.parametrize(("header", "expected"), [("0", 1.0), ("0.2", 1.0), ("1", 1.0), ("3.5", 3.5), ("30", 8.0)]) +def test_rate_limit_honors_and_clamps_retry_after( + client: WhiteCircle, api: MockAPI, sleeps: list[float], header: str, expected: float +) -> None: + api.json(429, {"error": "Rate limit exceeded"}, headers={"Retry-After": header}) + api.json(200, {}) + client.request("POST", "/api/event", body={}) + assert sleeps == [expected] + + +@pytest.mark.parametrize("header", ["Wed, 21 Oct 2026 07:28:00 GMT", "soon", "-2", "nan", "inf"]) +def test_non_numeric_retry_after_falls_back_to_backoff(api: MockAPI, sleeps: list[float], header: str) -> None: + client = make_client(api, max_retries=3) + for _ in range(3): + api.json(429, {"error": "Rate limit exceeded"}, headers={"Retry-After": header}) + api.json(200, {}) + client.request("POST", "/api/event", body={}) + assert sleeps[0] == 1.0 + assert sleeps[1] == 1.0 + assert 1.5 <= sleeps[2] <= 2.0 + + +async def test_async_rate_limit_honors_retry_after( + async_client: AsyncWhiteCircle, api: MockAPI, sleeps: list[float] +) -> None: + api.json(429, {"error": "Rate limit exceeded"}, headers={"retry-after": "2.5"}) + api.json(200, {"ok": True}) + assert await async_client.request("POST", "/api/events", body={}) == {"ok": True} + assert sleeps == [2.5] + + def test_monthly_quota_429_is_not_retried(client: WhiteCircle, api: MockAPI) -> None: api.json(429, {"error": "Monthly request quota exceeded for promotional plan."}) with pytest.raises(RateLimitError, match="quota"): From 669e32bd96321137e9062465152e2850d3c3b3ea Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 16:36:50 +0100 Subject: [PATCH 3/6] docs: document Events rate limits and changelog entries Add a Rate limits section to docs/errors-and-testing.md covering what counts toward the per-second Event limit, where rejections appear (200 failed vs 429 on skip batches), reading result.rate_limit and error.rate_limit, and resending failed Events after rate_limit.reset. Add Unreleased Added entries to CHANGELOG.md. --- CHANGELOG.md | 5 +++++ docs/errors-and-testing.md | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 71074ff..6f79df5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/errors-and-testing.md b/docs/errors-and-testing.md index c495c4c..5ca5cc7 100644 --- a/docs/errors-and-testing.md +++ b/docs/errors-and-testing.md @@ -69,6 +69,42 @@ transport errors. The backoff is exponential; a `429` honors a numeric `Retry-Af 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 ```python From ec3a5aadf4f171bcfeb678f522607278ff4f9d9c Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 16:44:23 +0100 Subject: [PATCH 4/6] fix(client): keep @overload request declarations contiguous with implementation Move _send_request above @overload def request on SyncAPIClient and AsyncAPIClient so each overload group immediately precedes its implementation as required by PEP 484 and mypy. --- src/whitecircle/_base_client.py | 96 ++++++++++++++++----------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/src/whitecircle/_base_client.py b/src/whitecircle/_base_client.py index a9f3834..2331d92 100644 --- a/src/whitecircle/_base_client.py +++ b/src/whitecircle/_base_client.py @@ -314,30 +314,6 @@ def __init__( self._owns_client = http_client is None self._client = http_client or httpx2.Client(limits=DEFAULT_CONNECTION_LIMITS, follow_redirects=False) - @overload - def request( - self, - method: str, - path: str, - *, - params: Query | None = ..., - body: Mapping[str, object] | None = ..., - headers: Headers | None = ..., - timeout: Timeout | NotGiven = ..., - cast_to: type[_T], - ) -> _T: ... - @overload - def request( - self, - method: str, - path: str, - *, - params: Query | None = ..., - body: Mapping[str, object] | None = ..., - headers: Headers | None = ..., - timeout: Timeout | NotGiven = ..., - cast_to: None = ..., - ) -> object: ... def _send_request( self, method: str, @@ -377,6 +353,30 @@ def _send_request( _sleep(delay) attempt += 1 + @overload + def request( + self, + method: str, + path: str, + *, + params: Query | None = ..., + body: Mapping[str, object] | None = ..., + headers: Headers | None = ..., + timeout: Timeout | NotGiven = ..., + cast_to: type[_T], + ) -> _T: ... + @overload + def request( + self, + method: str, + path: str, + *, + params: Query | None = ..., + body: Mapping[str, object] | None = ..., + headers: Headers | None = ..., + timeout: Timeout | NotGiven = ..., + cast_to: None = ..., + ) -> object: ... def request( self, method: str, @@ -462,30 +462,6 @@ def __init__( self._owns_client = http_client is None self._client = http_client or httpx2.AsyncClient(limits=DEFAULT_CONNECTION_LIMITS, follow_redirects=False) - @overload - async def request( - self, - method: str, - path: str, - *, - params: Query | None = ..., - body: Mapping[str, object] | None = ..., - headers: Headers | None = ..., - timeout: Timeout | NotGiven = ..., - cast_to: type[_T], - ) -> _T: ... - @overload - async def request( - self, - method: str, - path: str, - *, - params: Query | None = ..., - body: Mapping[str, object] | None = ..., - headers: Headers | None = ..., - timeout: Timeout | NotGiven = ..., - cast_to: None = ..., - ) -> object: ... async def _send_request( self, method: str, @@ -525,6 +501,30 @@ async def _send_request( await _async_sleep(delay) attempt += 1 + @overload + async def request( + self, + method: str, + path: str, + *, + params: Query | None = ..., + body: Mapping[str, object] | None = ..., + headers: Headers | None = ..., + timeout: Timeout | NotGiven = ..., + cast_to: type[_T], + ) -> _T: ... + @overload + async def request( + self, + method: str, + path: str, + *, + params: Query | None = ..., + body: Mapping[str, object] | None = ..., + headers: Headers | None = ..., + timeout: Timeout | NotGiven = ..., + cast_to: None = ..., + ) -> object: ... async def request( self, method: str, From 40e514d0623c9f84051692bf3202df1f4b1783a7 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 16:45:38 +0100 Subject: [PATCH 5/6] refactor(events): narrow _parse_events_rate_limit to httpx2.Headers and reject window <= 0 --- src/whitecircle/_exceptions.py | 4 ++-- src/whitecircle/resources/events.py | 4 ++-- src/whitecircle/types/events.py | 6 ++++-- tests/test_events.py | 1 + 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/whitecircle/_exceptions.py b/src/whitecircle/_exceptions.py index 907b168..8a4ee76 100644 --- a/src/whitecircle/_exceptions.py +++ b/src/whitecircle/_exceptions.py @@ -110,9 +110,9 @@ def __str__(self) -> str: @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 + from .types.events import _parse_events_rate_limit - return parse_events_rate_limit(self.response.headers) + return _parse_events_rate_limit(self.response.headers) class BadRequestError(APIStatusError): diff --git a/src/whitecircle/resources/events.py b/src/whitecircle/resources/events.py index e3bf447..5ccd033 100644 --- a/src/whitecircle/resources/events.py +++ b/src/whitecircle/resources/events.py @@ -12,7 +12,7 @@ EventLookupResult, EventsCheckResult, EventType, - parse_events_rate_limit, + _parse_events_rate_limit, ) from ..types.shared import InlinePolicy, Role @@ -25,7 +25,7 @@ def _with_rate_limit(result: _RateLimited, headers: httpx2.Headers) -> _RateLimited: - result.rate_limit = parse_events_rate_limit(headers) + result.rate_limit = _parse_events_rate_limit(headers) return result diff --git a/src/whitecircle/types/events.py b/src/whitecircle/types/events.py index 996301d..b9bf007 100644 --- a/src/whitecircle/types/events.py +++ b/src/whitecircle/types/events.py @@ -3,6 +3,7 @@ from datetime import datetime from typing import Any, Literal, Self, TypeAlias, TypedDict, Unpack, get_args +import httpx2 import pydantic from .._models import BaseModel @@ -196,7 +197,8 @@ class EventsRateLimit(BaseModel): """Window length in seconds.""" -def parse_events_rate_limit(headers: Mapping[str, str]) -> EventsRateLimit | None: +# Imported by resources/events.py and _exceptions.py. +def _parse_events_rate_limit(headers: httpx2.Headers) -> EventsRateLimit | None: # pyright: ignore[reportUnusedFunction] raw_limit = headers.get("x-ratelimit-events-limit") raw_remaining = headers.get("x-ratelimit-events-remaining") raw_reset = headers.get("x-ratelimit-events-reset") @@ -210,7 +212,7 @@ def parse_events_rate_limit(headers: Mapping[str, str]) -> EventsRateLimit | Non window = float(raw_window) except ValueError: return None - if limit < 0 or remaining < 0 or not math.isfinite(reset) or reset < 0 or not math.isfinite(window) or window < 0: + if limit < 0 or remaining < 0 or not math.isfinite(reset) or reset < 0 or not math.isfinite(window) or window <= 0: return None return EventsRateLimit(limit=limit, remaining=remaining, reset=reset, window=window) diff --git a/tests/test_events.py b/tests/test_events.py index 76508f0..5df1a72 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -330,6 +330,7 @@ async def test_check_and_check_many_parse_rate_limit_headers(call: Call, api: Mo {**RATE_LIMIT_HEADERS, "x-ratelimit-events-limit": "not-an-int"}, {**RATE_LIMIT_HEADERS, "x-ratelimit-events-reset": "nan"}, {**RATE_LIMIT_HEADERS, "x-ratelimit-events-remaining": "-1"}, + {**RATE_LIMIT_HEADERS, "x-ratelimit-events-window": "0"}, ], ) async def test_rate_limit_is_none_when_headers_absent_or_invalid( From f026241e822d21611cc3e03befbc070856477c4a Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 16:46:41 +0100 Subject: [PATCH 6/6] test: cover 503 Retry-After, quota 429 Retry-After, and skip-batch 429 retry Verify Retry-After is ignored on HTTP 503, monthly-quota 429 with Retry-After is still not retried, and events.check_many(..., skip=True) retries a 429 with Retry-After and attaches rate_limit from the subsequent 200 response. --- tests/test_client.py | 17 +++++++++++++++-- tests/test_events.py | 19 +++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 6f88566..a302740 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -250,11 +250,24 @@ async def test_async_rate_limit_honors_retry_after( assert sleeps == [2.5] -def test_monthly_quota_429_is_not_retried(client: WhiteCircle, api: MockAPI) -> None: - api.json(429, {"error": "Monthly request quota exceeded for promotional plan."}) +def test_monthly_quota_429_is_not_retried(client: WhiteCircle, api: MockAPI, sleeps: list[float]) -> None: + api.json( + 429, + {"error": "Monthly request quota exceeded for promotional plan."}, + headers={"Retry-After": "1"}, + ) with pytest.raises(RateLimitError, match="quota"): client.request("POST", "/api/event", body={}) assert len(api.requests) == 1 + assert sleeps == [] + + +def test_retry_after_is_ignored_on_503(client: WhiteCircle, api: MockAPI, sleeps: list[float]) -> None: + api.json(503, {"error": "busy"}, headers={"Retry-After": "5"}) + api.json(200, {}) + client.request("POST", "/api/event", body={}) + assert len(sleeps) == 1 + assert 0.375 <= sleeps[0] <= 0.5 @pytest.mark.parametrize("error", [httpx2.ReadTimeout("slow"), httpx2.ReadError("reset"), httpx2.WriteError("x")]) diff --git a/tests/test_events.py b/tests/test_events.py index 5df1a72..f5b8df0 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -355,3 +355,22 @@ async def test_api_status_error_exposes_rate_limit_headers(call: Call, api: Mock with pytest.raises(InternalServerError) as caught_500: await call("events", "check", Event.user("hi")) assert caught_500.value.rate_limit is None + + +async def test_check_many_skip_retries_429_with_retry_after_and_attaches_rate_limit( + call: Call, api: MockAPI, sleeps: list[float] +) -> None: + api.json( + 429, + {"error": "Rate limit exceeded"}, + headers={**RATE_LIMIT_HEADERS, "x-ratelimit-events-remaining": "0", "retry-after": "2"}, + ) + api.json( + 200, + {"flagged": False, "run_id": "run_1", "messages": [result("message", "evt_1")]}, + headers={**RATE_LIMIT_HEADERS, "x-ratelimit-events-remaining": "4"}, + ) + batch = await call("events", "check_many", [Event.user("hi", event_id="evt_1")], skip=True) + assert len(api.requests) == 2 + assert sleeps == [2.0] + assert batch.rate_limit == EventsRateLimit(limit=5, remaining=4, reset=1.0, window=1.0)