diff --git a/AGENTS.md b/AGENTS.md index b2ff08b..8284a41 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,7 @@ Guidance for coding agents and contributors working in `whitecircle-python`. `CL ```text src/whitecircle/ _constants.py API version, region URLs, key-prefix map, timeouts, retry delays, env var names - _types.py omit / not_given sentinels, internal null, Headers, Query, Body, Timeout + _types.py omit / not_given sentinels, internal null, Headers, Query, Timeout _models.py BaseModel (extra="allow") and prepare_body() _exceptions.py WhiteCircleError > APIError > APIStatusError (one class per status), APIConnectionError _logs.py the "whitecircle" logger, WHITECIRCLE_LOG, header redaction @@ -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/CHANGELOG.md b/CHANGELOG.md index 50de2b5..6f79df5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,49 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +### Breaking changes + +- Removed `applies_to`, `content_type`, `AppliesTo` and `ContentType` from `policies` and `metrics` (`create()`, + `update()`, `list()`), the `Policy` model and type exports. Target Policies with `event_selector_list` and + `role_list` instead: + - `applies_to="output"` -> `role_list=["assistant"]`; `applies_to="input"` -> `role_list=["user"]`; + `applies_to="any"` -> `role_list=[]`. Note that `tool/arguments` defaults to the user side: `role_list=[]` or + `["user"]` judges tool-call arguments as is, or pass `role="assistant"` on `Event.tool_call(...)` so an + assistant-only Policy judges the agent's own tool calls. + - `content_type="artifact"` -> `event_selector_list=[EventSelector(type="artifact")]`; `content_type="session"` -> + `event_selector_list=[EventSelector(type="message", field="content"), EventSelector(type="message", field="delta")]`; + `content_type="any"` -> both (the server default when `event_selector_list` is omitted). + - `list(applies_to=...)` / `list(content_type=...)` -> filter `list()` on `role_list` / `event_selector_list`. +- Removed `"reset"` from `SelectorType` (the API rejects `"reset"` selectors). +- `EventSelector` now validates `type` and `field` at construction: non-`artifact` selectors require `field` to be one + of that type's allowed fields, and `artifact` selectors reject `field` (use `kind` instead), raising + `ValidationError` (a `ValueError`). +- `policies.create()` and `metrics.create()` now require a non-empty `rules` sequence (omitting `rules` raises + `TypeError`; passing `[]` raises `ValueError`). +- `Event.reference()` now rejects `"reset"` (statically via `SelectorType` and at runtime with `ValueError`). +- `Field.is_in()` and `Field.not_in()` now reject bare `str`, `bytes` and `bytearray` values (statically and with + `TypeError`) instead of iterating characters. + +### Added + +- `Event.tool_call()`, `tool_result()`, `tool_definition()`, and `agent()` now accept optional `role=` to override + 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 + +- `Webhooks.parse()` no longer attaches the raw `pydantic.ValidationError` as `__cause__`, keeping webhook payload + content out of formatted tracebacks. +- Streaming: `close()` now clears the socket so post-close calls raise `WhiteCircleError`; binary WebSocket frames + raise `StreamError("invalid_frame", ...)` instead of leaking `httpx2` exceptions; `connect()` honors the client read + timeout while waiting for `ready`. + ## [0.1.0] - 2026-11-29 0.1.0 is the first published release. It targets API version `2026-06-01` only and provides sync and async diff --git a/README.md b/README.md index 4b51117..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 @@ -234,8 +234,8 @@ The SDK logs method, path, status, duration and retries on the standard `whiteci until you configure it or set `WHITECIRCLE_LOG=debug` (or `info`, `warning`, `error`). It never logs API keys, bodies or query strings. -To call an endpoint the SDK does not wrap, `client.request("GET", "/api/usage", params={"period": 7})` returns the -parsed JSON. +To call an endpoint the SDK does not wrap, `client.request("GET", "/api/some/new/endpoint", params={"x": 1})` returns +the parsed JSON. ## Contributing diff --git a/docs/README.md b/docs/README.md index 5668982..4797ffc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -20,7 +20,8 @@ live at https://whitecircle.com/docs. | [Streaming replies](streaming.md) | Show only checked text while the model generates it | | [Images](images.md) | Check standalone images and images inside a conversation | | [Managing Policies](managing-policies.md) | Create Policies, Metrics and Conditions; shadow mode to production | -| [Strikes and webhooks](strikes-and-webhooks.md) | User risk, strikes, appeals, verifying webhooks | +| [Strikes and webhooks](strikes-and-webhooks.md) | User risk, strikes, appeals, user properties, verifying webhooks | +| [Usage](usage.md) | Read billed usage and cost per Event type (`client.billing.usage()`) | | [Errors and testing](errors-and-testing.md) | Exceptions, retries, timeouts, logging, testing your code | | [Recipe: support chatbot](chatbot.md) | All of the above in one async integration | diff --git a/docs/agents-and-tools.md b/docs/agents-and-tools.md index d4bdf16..3f7f84c 100644 --- a/docs/agents-and-tools.md +++ b/docs/agents-and-tools.md @@ -18,6 +18,12 @@ Event.tool_result("send_email", {"status": "sent"}, call_id="call_1") `function` Events work the same way: `Event(type="function", name="...", arguments={...})`. +Default Policy selectors cover only `message` and `artifact` Events, so tool, function, agent and reasoning Events are +skipped until a Policy selects their type and field. `tool/arguments` defaults to the user side (`role_list=[]` or +`["user"]` judges it as is); pass `role="assistant"` on `Event.tool_call(...)` so an assistant-only Policy judges your +agent's own tool calls (recommended for agents that log their own tool calls). See +[Judge tool calls](managing-policies.md#judge-tool-calls). + ## Pair a call with its result Send the same `call_id` on both, or set the result's `parent_event_id` to the call's `event_id`: @@ -73,6 +79,7 @@ from datetime import UTC, datetime from whitecircle import Event, WhiteCircle client = WhiteCircle() +run = "run_pr_1234" started = datetime.now(UTC) output = run_search() client.events.check( diff --git a/docs/context.md b/docs/context.md index a762aff..db52bb3 100644 --- a/docs/context.md +++ b/docs/context.md @@ -29,6 +29,7 @@ with the `system` role. In a `check_many()` batch, list order is context order. from whitecircle import Event, WhiteCircle client = WhiteCircle() +session = "conversation_456" client.events.check(Event.reset(), external_session_id=session) client.events.check(Event.reset("The user disputes a charge on order 4815."), external_session_id=session) ``` @@ -44,9 +45,12 @@ replaces anything stored before: ```python from whitecircle import Event, WhiteCircle +from whitecircle.types import Role client = WhiteCircle() -events = [Event.reset()] + [Event.message(m.text, role=m.role) for m in previous_messages] +session = "conversation_456" +previous_messages: list[tuple[Role, str]] = [("user", "Hi"), ("assistant", "Hello!")] +events = [Event.reset()] + [Event.message(text, role=role) for role, text in previous_messages] for start in range(0, len(events), 50): client.events.check_many(events[start : start + 50], external_session_id=session, skip=True) ``` diff --git a/docs/errors-and-testing.md b/docs/errors-and-testing.md index 2dad371..192d5e3 100644 --- a/docs/errors-and-testing.md +++ b/docs/errors-and-testing.md @@ -7,11 +7,11 @@ such as a missing `environment_id` or two user identifiers at once, raise `Value ```python import whitecircle -from whitecircle import WhiteCircle +from whitecircle import Event, WhiteCircle client = WhiteCircle() try: - result = client.events.check(event) + result = client.events.check(Event.user("hello")) except whitecircle.AuthenticationError: # 401 ... except whitecircle.PermissionDeniedError: # 403: the key cannot use this endpoint, or the IP is not allowed @@ -40,6 +40,8 @@ import whitecircle from whitecircle import Event, WhiteCircle client = WhiteCircle() +FAIL_OPEN = False +meta = {"app": "support-bot"} def is_allowed(text: str) -> bool: @@ -63,8 +65,65 @@ 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. + +Resending only failed Events or only the latest batch either checks them after Events they preceded or drops earlier +conversation context; replay the whole conversation under a fresh `external_session_id` in batches no larger than +`rate_limit.limit`, waiting `rate_limit.reset` between batches, and read verdicts only once no Event failed: + +```python +import time + +from whitecircle import Event, WhiteCircle +from whitecircle.types import EventResult + +client = WhiteCircle() +conversation = [Event.user(f"turn {i}") for i in range(10)] + + +def check_conversation(events: list[Event], session: str) -> list[EventResult]: + chunk_size = 50 + for attempt in range(5): + current_session = session if attempt == 0 else f"{session}_retry_{attempt}" + results: list[EventResult] = [] + reset = 1.0 + for start in range(0, len(events), chunk_size): + if start > 0: + time.sleep(reset) + batch = client.events.check_many(events[start : start + chunk_size], external_session_id=current_session) + if batch.rate_limit is not None: + chunk_size = min(50, max(1, batch.rate_limit.limit)) + reset = batch.rate_limit.reset + if any(item.status == "failed" and "rate limit" in (item.note or "").lower() for item in batch.results): + time.sleep(reset) + break + results.extend(batch.results) + else: + if all(item.status != "failed" for item in results): + return results + raise RuntimeError("One or more Events failed for a non-rate-limit reason") + raise RuntimeError("Conversation still rate-limited after retries") + + +results = check_conversation(conversation, "conversation_456") +print(any(item.flagged for item in results)) +``` ## Async diff --git a/docs/getting-started.md b/docs/getting-started.md index 0bbfeea..0191e23 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -36,10 +36,10 @@ Events and run-graph calls need an Environment. Pass `environment_id=` to overri with neither, the call raises `ValueError`: ```python -from whitecircle import WhiteCircle +from whitecircle import Event, WhiteCircle client = WhiteCircle() -client.events.check(event, environment_id="env_staging") +client.events.check(Event.user("hello"), environment_id="env_staging") ``` For several settings at once, make a copy that shares the connection pool: @@ -73,6 +73,10 @@ result.event.internal_event_id # store it to fetch the result later ``` ```python +from whitecircle import Event, WhiteCircle + +client = WhiteCircle() +result = client.events.check(Event.user("Hello, can you help me prescribe antibiotics?")) if result.flagged: reply = "Sorry, I can't help with that." elif not result.checked: @@ -87,7 +91,7 @@ Fetch a stored result later: from whitecircle import WhiteCircle client = WhiteCircle() -client.events.get(internal_event_id) +client.events.get("01930000-0000-7000-8000-000000000001") client.events.get_latest(run_id="run_1", event_id="evt_user_1") ``` diff --git a/docs/images.md b/docs/images.md index 24eabde..0ae55ad 100644 --- a/docs/images.md +++ b/docs/images.md @@ -20,9 +20,10 @@ inline = ArtifactContent.from_bytes(Path("upload.jpg").read_bytes()) # sent as ## Standalone images ```python -from whitecircle import WhiteCircle +from whitecircle import ArtifactContent, WhiteCircle client = WhiteCircle() +by_url = ArtifactContent.from_url("https://cdn.example.com/avatar.png") result = client.artifacts.check(by_url, role="user", external_artifact_id="upload_123") if result.flagged: reject_upload() @@ -31,18 +32,22 @@ client.artifacts.get(result.internal_artifact_id) client.artifacts.get_by_external_id("upload_123") # the latest check with this ID ``` -`role` selects Policies by their Applies To setting: `"assistant"` runs *output* and *any* Policies, any other role -runs *input* and *any*, and no role runs only *any*. `environment_id` is optional here; the key's Environment is -used. The API supports only images, not video or website pages, and checks them before it answers. +`role` matches each Policy's `role_list`: `"assistant"` runs Policies whose `role_list` is `[]` or contains +`"assistant"`, any other role runs `[]` or `"user"`, and no role runs only `role_list=[]`. `environment_id` is +optional here; the key's Environment is used. The API supports only images, not video or website pages, and checks them before it answers. Right after a check, `get()` and `get_by_external_id()` can raise `NotFoundError` for a few seconds while the result is stored. ## Images in a conversation ```python -from whitecircle import Event, WhiteCircle +from pathlib import Path + +from whitecircle import ArtifactContent, Event, WhiteCircle client = WhiteCircle() +inline = ArtifactContent.from_bytes(Path("upload.jpg").read_bytes()) +meta = {"app": "pharmacy-bot"} session = "conversation_456" client.events.check(Event.user("Is this rash serious?", metadata=meta), external_session_id=session) client.events.check( diff --git a/docs/inline-policies.md b/docs/inline-policies.md index 7752768..7f44ed5 100644 --- a/docs/inline-policies.md +++ b/docs/inline-policies.md @@ -22,6 +22,15 @@ An inline Policy's verdict is in `result.policies` like any other. It is keyed b and named by your `name`. Its `enabled_by_conditions` is `None`, because no Condition selected it. ```python +from whitecircle import Event, InlinePolicy, Rule, WhiteCircle + +client = WhiteCircle() +refund_policy = InlinePolicy( + external_id="refund-policy", + name="Refund policy", + rules=[Rule.flag("Requests to bypass refund approval")], +) +result = client.events.check(Event.user("Approve my refund without a receipt"), inline_policies=[refund_policy]) for policy_id, verdict in result.flagged_policies.items(): print(policy_id, verdict.name) ``` diff --git a/docs/managing-policies.md b/docs/managing-policies.md index aa2b0c6..1efcf8e 100644 --- a/docs/managing-policies.md +++ b/docs/managing-policies.md @@ -14,15 +14,69 @@ policy = client.policies.create( Rule.flag("Providing medical advice, diagnoses or dosages"), Rule.allow("Answering whether a medicine is in stock"), ], - event_selector_list=[EventSelector(type="message")], - applies_to="output", # input: user content, output: assistant content, any: both + event_selector_list=[ + EventSelector(type="message", field="content"), + EventSelector(type="message", field="delta"), + ], + role_list=["assistant"], mode="shadow", ) ``` -At least one rule must flag. `event_selector_list` picks Event types and fields, for example -`EventSelector(type="tool", field="output")`, `EventSelector(type="agent", field="state")` or -`EventSelector(type="artifact")`. +At least one rule must flag. Two fields decide which Events a Policy evaluates: + +- `event_selector_list` picks Event types and fields. Omitting it defaults to `message/content`, `message/delta` and + `artifact`; when passed, it must be non-empty. Every selector requires `field` except `artifact` (which takes an + optional `kind`, such as `"image"`): + - `message`: `content`, `delta` + - `tool` / `function`: `arguments`, `output`, `definition` + - `agent`: `input`, `instructions`, `output`, `state` + - `reasoning`: `content`, `delta` + - `artifact`: no `field` (optional `kind`, for example `EventSelector(type="artifact", kind="image")`) +- `role_list` restricts roles: `[]` (default) evaluates every role, `["user"]` checks user-side content and + `["assistant"]` checks assistant-side content. + +## Judge tool calls + +Tool Events are skipped unless you select them explicitly. By default, `tool/arguments` is classified on the user side, +so `role_list=[]` or `["user"]` judges tool-call arguments as they are while `role_list=["assistant"]` skips them. To +have an assistant-only Policy judge your agent's own tool calls (without also judging user messages), pass +`role="assistant"` on `Event.tool_call(...)` — recommended for agents that log their own tool calls: + +```python +from whitecircle import Event, EventSelector, Rule, WhiteCircle, field + +client = WhiteCircle() +tool_policy = client.policies.create( + name="No unsafe tool calls", + rules=[Rule.flag("SQL injection or destructive shell commands in tool calls")], + event_selector_list=[ + EventSelector(type="message", field="content"), + EventSelector(type="message", field="delta"), + EventSelector(type="tool", field="arguments"), + EventSelector(type="tool", field="output"), + ], + role_list=["assistant"], + mode="shadow", +) +client.conditions.create( + name="SQL agent", + conditions=field("app") == "sql-agent", + environment_ids=["env_prod"], + policy_ids=[tool_policy.id], + state="Active", +) +result = client.events.check( + Event.tool_call( + "run_sql", + {"query": "SELECT * FROM orders"}, + role="assistant", + call_id="c1", + metadata={"app": "sql-agent"}, + ), + include_shadow=True, +) +``` ## Shadow mode to production @@ -32,11 +86,15 @@ A shadow Policy is evaluated but never changes `flagged`. Ask for its results wi from whitecircle import Event, WhiteCircle client = WhiteCircle() -result = client.events.check(Event.user(sample_prompt, metadata=meta), include_shadow=True) +result = client.events.check( + Event.assistant("Take 400 mg of ibuprofen every 4 hours", metadata={"app": "pharmacy-bot"}), + include_shadow=True, +) for policy_result in (result.policies or {}).values(): if policy_result.shadow: print(policy_result.name, "would flag" if policy_result.flagged else "would pass") +policy = next(item for item in client.policies.list(mode="shadow") if item.name == "No medical advice") client.policies.update(policy.id, mode="prod") ``` @@ -49,7 +107,7 @@ Only the fields you pass change; `None` means "keep". `rules` replaces the whole from whitecircle import Rule, WhiteCircle client = WhiteCircle() -policy = client.policies.get(policy.id) +policy = client.policies.get("pol_123") client.policies.update(policy.id, rules=[*policy.rules, Rule.allow("Store opening hours")]) client.policies.update(policy.id, severity_level_id=None) # the one field None clears ``` @@ -67,10 +125,10 @@ condition = client.conditions.create( name="Pharmacy bot", conditions=field("app") == "pharmacy-bot", environment_ids=["env_prod"], - policy_ids=[policy.id], + policy_ids=["pol_123"], state="Active", ) -client.conditions.update(condition.id, policy_ids=[policy.id, other_policy.id]) +client.conditions.update(condition.id, policy_ids=["pol_123", "pol_456"]) client.conditions.update(condition.id, state="Inactive") ``` @@ -88,7 +146,7 @@ from whitecircle import Rule, WhiteCircle client = WhiteCircle() metric = client.metrics.create(name="Escalation risk", rules=[Rule.flag("The user threatens to churn or escalate")]) -client.conditions.update(condition.id, metric_ids=[metric.id]) +client.conditions.update("cond_123", metric_ids=[metric.id]) ``` ## Sync from a file diff --git a/docs/metadata-and-conditions.md b/docs/metadata-and-conditions.md index 3e0ec1a..d48e43b 100644 --- a/docs/metadata-and-conditions.md +++ b/docs/metadata-and-conditions.md @@ -39,7 +39,7 @@ condition = client.conditions.create( name="EU pro users", conditions=(field("user.region") == "eu") & (field("user.plan") == "pro"), environment_ids=["env_prod"], - policy_ids=[policy.id], + policy_ids=["pol_123"], state="Active", ) ``` @@ -66,6 +66,7 @@ Combine with `&`, not `and`: `and` raises `TypeError` instead of silently droppi from whitecircle import Event, WhiteCircle client = WhiteCircle() +meta = {"app": "support-bot"} result = client.events.check(Event.user("My card number is 4111 1111 1111 1111", metadata=meta)) for policy_result in (result.policies or {}).values(): @@ -91,8 +92,8 @@ A stream does not report "not checked": with no matching Condition every batch p 2. The path matches exactly: `user.region` needs `{"user": {"region": ...}}`, not `{"user.region": ...}`. A missing field never matches, except with `.not_exists()`. 3. The type matches: `field("user.age") >= 18` needs a number, not `"18"`. -4. The Policy selects this Event type and field, and its Applies To fits the role (`output` Policies skip user - messages). +4. The Policy selects this Event type and field, and its `role_list` is empty or includes the Event's role + (`["assistant"]` skips user messages and `tool/arguments` sent without `role="assistant"`). ## Inline Policies diff --git a/docs/streaming.md b/docs/streaming.md index f84c536..49d3942 100644 --- a/docs/streaming.md +++ b/docs/streaming.md @@ -42,19 +42,24 @@ your model call stops generating. Text from the flagged batch is never released. ## From an OpenAI stream ```python +from collections.abc import Iterable, Iterator +from typing import Any + from whitecircle import WhiteCircle client = WhiteCircle() -def openai_tokens(stream): +def openai_tokens(stream: Iterable[Any]) -> Iterator[str]: for chunk in stream: if chunk.choices and (delta := chunk.choices[0].delta.content): yield delta -stream = openai_client.chat.completions.create(model=model, messages=messages, stream=True) -for text in client.events.check_stream(openai_tokens(stream), external_session_id=conversation_id): +stream = openai_client.chat.completions.create( + model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}], stream=True +) +for text in client.events.check_stream(openai_tokens(stream), external_session_id="conversation_456"): send_to_user(text) ``` @@ -67,8 +72,9 @@ was not fully checked: treat unreleased text as unsafe and, if you retry, send t from whitecircle import StreamClosedError, StreamError, WhiteCircle client = WhiteCircle() +tokens = ["Hello, ", "world!"] try: - for text in client.events.check_stream(tokens, external_session_id=conversation_id): + for text in client.events.check_stream(tokens, external_session_id="conversation_456"): send_to_user(text) except StreamError as error: if error.retryable: # capacity, server_shutdown, processing_failed, rate_limited @@ -91,6 +97,7 @@ Opening the stream raises the usual HTTP errors: `AuthenticationError` (401), `P from whitecircle import WhiteCircle client = WhiteCircle() +meta = {"user": {"region": "eu"}} with client.events.stream(external_session_id="conversation_456", metadata=meta) as stream: for token in model_tokens(): stream.append(token) diff --git a/docs/strikes-and-webhooks.md b/docs/strikes-and-webhooks.md index b5b2e5e..6a41b80 100644 --- a/docs/strikes-and-webhooks.md +++ b/docs/strikes-and-webhooks.md @@ -10,7 +10,7 @@ from whitecircle import Event, WhiteCircle client = WhiteCircle() meta = {"user": {"id": "user-123", "email": "user@example.com", "ip": "203.0.113.10"}} -client.events.check(Event.user(text, metadata=meta), external_session_id="conversation_456") +client.events.check(Event.user("Hello, can you help?", metadata=meta), external_session_id="conversation_456") ``` ## Read a user's risk @@ -36,8 +36,8 @@ from whitecircle import WhiteCircle client = WhiteCircle() created = client.users.strikes.create( - policy_id=policy.id, - severity_level_id=severity_level_id, # must be the Policy's current severity_level_id + policy_id="pol_123", + severity_level_id="sev_high", # must be the Policy's current severity_level_id user_id="user-123", external_session_id="conversation_456", ) @@ -46,6 +46,27 @@ print(created.action) Pass exactly one of `user_id` or `email`, and exactly one of `external_session_id` or `internal_session_id`. +## User properties + +Read or merge custom properties stored on existing users with `client.users.properties`: + +```python +from whitecircle import WhiteCircle +from whitecircle.types import UserProperties + +client = WhiteCircle() +props = client.users.properties.get(user_id="user-123") # pass exactly one of user_id, email or ip +print(props) + +updated = client.users.properties.update( + [UserProperties(user_id="user-123", properties={"plan": "pro", "old_flag": None})] +) +print(updated.users, updated.not_found) +``` + +`update()` merges properties into 1 to 100 existing users; setting a key to `None` removes it, and unknown user IDs +are reported in `not_found`. + ## Appeals Strikes have no public ID; appeal one through its session: diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..ade6176 --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,21 @@ +# Usage + +Read billed usage and cost across every Environment with `client.billing.usage()`. + +```python +from datetime import date + +from whitecircle import WhiteCircle + +client = WhiteCircle() + +last_week = client.billing.usage(period=7) # trailing days (1-365, default 30) +print(last_week.total_micros, last_week.message.count, last_week.tool.count) + +window = client.billing.usage(from_date=date(2026, 6, 1), to_date=date(2026, 6, 7)) +print(window.from_, window.to, window.artifact.image.cost_micros) +``` + +- Pass either `period` or both `from_date` and `to_date` (an inclusive UTC date range), not both. +- Costs (`total_micros`, `*.cost_micros`) are integers in millionths of one USD. +- `artifact.video` and `artifact.website` are counted, not billed. diff --git a/src/whitecircle/_base_client.py b/src/whitecircle/_base_client.py index 6f1b39c..2331d92 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 @@ -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, @@ -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, @@ -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, @@ -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, diff --git a/src/whitecircle/_exceptions.py b/src/whitecircle/_exceptions.py index 5418d1c..8a4ee76 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/_types.py b/src/whitecircle/_types.py index 3d90e52..6c27c94 100644 --- a/src/whitecircle/_types.py +++ b/src/whitecircle/_types.py @@ -4,7 +4,6 @@ import httpx2 __all__ = [ - "Body", "Headers", "NotGiven", "Omit", @@ -54,7 +53,6 @@ def __repr__(self) -> str: Timeout = float | httpx2.Timeout | None Headers = Mapping[str, str | Omit] Query = Mapping[str, object] -Body = object _T_co = TypeVar("_T_co", covariant=True) diff --git a/src/whitecircle/expressions.py b/src/whitecircle/expressions.py index d823a99..e158e97 100644 --- a/src/whitecircle/expressions.py +++ b/src/whitecircle/expressions.py @@ -5,13 +5,22 @@ """ from collections.abc import Iterable +from collections.abc import Set as AbstractSet from typing import Any +from ._types import SequenceNotStr + __all__ = ["Comparison", "Expression", "Field", "Group", "field"] _NO_VALUE_OPERATORS = frozenset({"exists", "not_exists"}) +def _values(values: SequenceNotStr[object] | AbstractSet[object]) -> list[object]: + if isinstance(values, str | bytes | bytearray): + raise TypeError("Pass a collection of values, not a single string or bytes object.") + return list(values) + + class Expression: def to_dict(self) -> dict[str, Any]: raise NotImplementedError @@ -20,6 +29,8 @@ def _comparisons(self) -> list["Comparison"]: raise NotImplementedError def __and__(self, other: "Expression") -> "Group": + if not isinstance(other, Expression): # runtime guard for untyped callers # pyright: ignore[reportUnnecessaryIsInstance] + return NotImplemented return Group([*self._comparisons(), *other._comparisons()]) def __bool__(self) -> bool: @@ -86,11 +97,11 @@ def __lt__(self, value: object) -> Comparison: def __le__(self, value: object) -> Comparison: return Comparison(self.path, "lte", value) - def is_in(self, values: Iterable[object]) -> Comparison: - return Comparison(self.path, "in", list(values)) + def is_in(self, values: SequenceNotStr[object] | AbstractSet[object]) -> Comparison: + return Comparison(self.path, "in", _values(values)) - def not_in(self, values: Iterable[object]) -> Comparison: - return Comparison(self.path, "not_in", list(values)) + def not_in(self, values: SequenceNotStr[object] | AbstractSet[object]) -> Comparison: + return Comparison(self.path, "not_in", _values(values)) def contains(self, value: object) -> Comparison: """Substring of a string, item of an array, or key of an object.""" diff --git a/src/whitecircle/lib/streaming.py b/src/whitecircle/lib/streaming.py index 16fe029..4e41286 100644 --- a/src/whitecircle/lib/streaming.py +++ b/src/whitecircle/lib/streaming.py @@ -1,6 +1,7 @@ import asyncio import contextlib import json +import time from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Iterable, Iterator, Mapping from typing import Any, cast @@ -9,6 +10,7 @@ AsyncWebSocketSession, HTTPXWSException, WebSocketDisconnect, + WebSocketInvalidTypeReceived, WebSocketNetworkError, WebSocketSession, WebSocketUpgradeError, @@ -25,6 +27,7 @@ make_status_error, ) from .._models import prepare_body +from .._types import Timeout from ..types.streaming import StreamCheck, StreamCompleted, StreamMessage, StreamReady, StreamResult, StreamWarning __all__ = ["AsyncCheckedStream", "AsyncEventStream", "CheckedStream", "EventStream"] @@ -84,8 +87,7 @@ def handle(self, text: str) -> StreamMessage | None: except ValueError: data = None if not isinstance(data, dict): - self.done = True - raise StreamError("invalid_frame", "The server sent a frame that is not a JSON object.") + raise self.invalid_frame("The server sent a frame that is not a JSON object.") data = cast(dict[str, Any], data) kind = data.get("type") if kind == "error": @@ -128,6 +130,10 @@ def _release_through(self, last_chunk_id: int | str) -> str: self._released = max(self._released, end) return text + def invalid_frame(self, message: str) -> StreamError: + self.done = True + return StreamError("invalid_frame", message) + def closed(self, close_code: int | None) -> StreamClosedError: self.done = True return StreamClosedError( @@ -161,6 +167,20 @@ def _not_open() -> WhiteCircleError: return WhiteCircleError("The stream is not open; use it with `with` or call connect().") +def _ready_deadline(timeout: Timeout) -> float | None: + read = timeout.read if isinstance(timeout, httpx2.Timeout) else timeout + return None if read is None else time.monotonic() + read + + +def _remaining(deadline: float | None, url: str) -> float | None: + if deadline is None: + return None + left = deadline - time.monotonic() + if left <= 0: + raise APITimeoutError(httpx2.Request("GET", url)) + return left + + class EventStream: def __init__( self, @@ -202,14 +222,17 @@ def connect(self) -> "EventStream": raise _connect_error(error, url) from error try: self._send(self._protocol.start) + deadline = _ready_deadline(self._client.timeout) while not self.done and self.result.internal_event_id is None: - self.receive() + if self.receive(timeout=_remaining(deadline, url)) is None and not self.done: + raise APITimeoutError(httpx2.Request("GET", url)) except BaseException: self.close() raise return self def close(self) -> None: + self._ws = None self._stack.close() def __enter__(self) -> "EventStream": @@ -236,15 +259,24 @@ def receive(self, timeout: float | None = None) -> StreamMessage | None: """ if self._ws is None: raise _not_open() + deadline = None if timeout is None or timeout <= 0 else time.monotonic() + timeout while not self.done: + if deadline is None: + wait = timeout + else: + wait = deadline - time.monotonic() + if wait <= 0: + return None try: - text = self._ws.receive_text(timeout) + text = self._ws.receive_text(wait) except TimeoutError: return None except WebSocketDisconnect as error: raise self._protocol.closed(error.code) from error except WebSocketNetworkError as error: raise self._protocol.closed(None) from error + except WebSocketInvalidTypeReceived as error: + raise self._protocol.invalid_frame("The server sent a non-text WebSocket frame.") from error message = self._protocol.handle(text) if message is not None: return message @@ -304,14 +336,17 @@ async def connect(self) -> "AsyncEventStream": raise _connect_error(error, url) from error try: await self._send(self._protocol.start) + deadline = _ready_deadline(self._client.timeout) while not self.done and self.result.internal_event_id is None: - await self.receive() + if await self.receive(timeout=_remaining(deadline, url)) is None and not self.done: + raise APITimeoutError(httpx2.Request("GET", url)) except BaseException: await self.close() raise return self async def close(self) -> None: + self._ws = None if self._pending is not None: self._pending.cancel() with contextlib.suppress(asyncio.CancelledError, HTTPXWSException): @@ -344,11 +379,18 @@ async def receive(self, timeout: float | None = None) -> StreamMessage | None: """ if self._ws is None: raise _not_open() + deadline = None if timeout is None or timeout <= 0 else time.monotonic() + timeout while not self.done: + if deadline is None: + wait = timeout + else: + wait = deadline - time.monotonic() + if wait <= 0: + return None # httpx2's async receive(timeout=0) always times out, so one read task outlives timeouts instead. if self._pending is None: self._pending = asyncio.create_task(self._ws.receive_text()) - done, _ = await asyncio.wait({self._pending}, timeout=timeout) + done, _ = await asyncio.wait({self._pending}, timeout=wait) if not done: return None read, self._pending = self._pending, None @@ -358,6 +400,8 @@ async def receive(self, timeout: float | None = None) -> StreamMessage | None: raise self._protocol.closed(error.code) from error except WebSocketNetworkError as error: raise self._protocol.closed(None) from error + except WebSocketInvalidTypeReceived as error: + raise self._protocol.invalid_frame("The server sent a non-text WebSocket frame.") from error message = self._protocol.handle(text) if message is not None: return message diff --git a/src/whitecircle/resources/artifacts.py b/src/whitecircle/resources/artifacts.py index 6fbb8f9..fb939d4 100644 --- a/src/whitecircle/resources/artifacts.py +++ b/src/whitecircle/resources/artifacts.py @@ -17,11 +17,13 @@ def check( external_session_id: str | None = None, internal_session_id: str | None = None, role: Role | None = None, + trace_id: str | None = None, + span_id: str | None = None, metadata: ArtifactMetadata | None = None, timeout: Timeout | NotGiven = not_given, ) -> ArtifactCheckResult: - """Check an image. ``role`` selects Policies by Applies To: ``"assistant"`` runs output and any, - another role runs input and any, no role runs only any. + """Check an image. ``role`` matches each Policy's ``role_list``: ``"assistant"`` runs ``[]`` or + ``"assistant"``, another role runs ``[]`` or ``"user"``, and no role runs only ``[]``. ``metadata`` groups scalars by name, such as ``{"user": {"id": "u_1"}}``. The API supports only images and checks them before it answers. @@ -33,6 +35,8 @@ def check( "external_session_id": external_session_id, "internal_session_id": internal_session_id, "role": role, + "trace_id": trace_id, + "span_id": span_id, "metadata": metadata, } return self._post("/api/artifact", body=body, timeout=timeout, cast_to=ArtifactCheckResult) @@ -76,11 +80,13 @@ async def check( external_session_id: str | None = None, internal_session_id: str | None = None, role: Role | None = None, + trace_id: str | None = None, + span_id: str | None = None, metadata: ArtifactMetadata | None = None, timeout: Timeout | NotGiven = not_given, ) -> ArtifactCheckResult: - """Check an image. ``role`` selects Policies by Applies To: ``"assistant"`` runs output and any, - another role runs input and any, no role runs only any. + """Check an image. ``role`` matches each Policy's ``role_list``: ``"assistant"`` runs ``[]`` or + ``"assistant"``, another role runs ``[]`` or ``"user"``, and no role runs only ``[]``. ``metadata`` groups scalars by name, such as ``{"user": {"id": "u_1"}}``. The API supports only images and checks them before it answers. @@ -92,6 +98,8 @@ async def check( "external_session_id": external_session_id, "internal_session_id": internal_session_id, "role": role, + "trace_id": trace_id, + "span_id": span_id, "metadata": metadata, } return await self._post("/api/artifact", body=body, timeout=timeout, cast_to=ArtifactCheckResult) diff --git a/src/whitecircle/resources/events.py b/src/whitecircle/resources/events.py index e097678..5ccd033 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/resources/policies.py b/src/whitecircle/resources/policies.py index 9fddf33..2d6d4d4 100644 --- a/src/whitecircle/resources/policies.py +++ b/src/whitecircle/resources/policies.py @@ -2,7 +2,7 @@ from .._resource import AsyncAPIResource, SyncAPIResource from .._types import NotGiven, Omit, SequenceNotStr, Timeout, not_given, null, omit -from ..types.policies import AppliesTo, ContentType, EventSelector, Policy, PolicyMode, PolicyRole +from ..types.policies import EventSelector, Policy, PolicyMode, PolicyRole from ..types.shared import Rule __all__ = ["AsyncMetrics", "AsyncPolicies", "Metrics", "Policies"] @@ -24,22 +24,20 @@ def _rules(rules: SequenceNotStr[Rule] | None, *, with_ids: bool) -> list[dict[s def _create_body( name: str, - rules: SequenceNotStr[Rule] | None, - content_type: ContentType | None, + rules: SequenceNotStr[Rule], event_selector_list: SequenceNotStr[EventSelector] | None, role_list: SequenceNotStr[PolicyRole] | None, - applies_to: AppliesTo | None, mode: PolicyMode | None, country_codes: SequenceNotStr[str] | None, severity_level_id: str | None, ) -> dict[str, object]: + if not rules: + raise ValueError("rules must contain at least one Rule") return { "name": name, "rules": _rules(rules, with_ids=False), - "content_type": content_type, "event_selector_list": event_selector_list, "role_list": role_list, - "applies_to": applies_to, "mode": mode, "country_codes": country_codes, "severity_level_id": severity_level_id, @@ -50,10 +48,8 @@ def _update_body( id: str, name: str | None, rules: SequenceNotStr[Rule] | None, - content_type: ContentType | None, event_selector_list: SequenceNotStr[EventSelector] | None, role_list: SequenceNotStr[PolicyRole] | None, - applies_to: AppliesTo | None, mode: PolicyMode | None, country_codes: SequenceNotStr[str] | None, severity_level_id: str | None | Omit, @@ -63,22 +59,14 @@ def _update_body( "id": id, "name": name, "rules": _rules(rules, with_ids=True), - "content_type": content_type, "event_selector_list": event_selector_list, "role_list": role_list, - "applies_to": applies_to, "mode": mode, "country_codes": country_codes, "severity_level_id": null if severity_level_id is None else severity_level_id, } -def _list_params( - content_type: ContentType | None, applies_to: AppliesTo | None, mode: PolicyMode | None -) -> dict[str, object]: - return {"content_type": content_type, "applies_to": applies_to, "mode": mode} - - class Policies(SyncAPIResource): _path = "/api/policy" @@ -86,11 +74,9 @@ def create( self, *, name: str, - rules: SequenceNotStr[Rule] | None = None, - content_type: ContentType | None = None, + rules: SequenceNotStr[Rule], event_selector_list: SequenceNotStr[EventSelector] | None = None, role_list: SequenceNotStr[PolicyRole] | None = None, - applies_to: AppliesTo | None = None, mode: PolicyMode | None = None, country_codes: SequenceNotStr[str] | None = None, severity_level_id: str | None = None, @@ -99,10 +85,8 @@ def create( body = _create_body( name, rules, - content_type, event_selector_list, role_list, - applies_to, mode, country_codes, severity_level_id, @@ -115,10 +99,8 @@ def update( *, name: str | None = None, rules: SequenceNotStr[Rule] | None = None, - content_type: ContentType | None = None, event_selector_list: SequenceNotStr[EventSelector] | None = None, role_list: SequenceNotStr[PolicyRole] | None = None, - applies_to: AppliesTo | None = None, mode: PolicyMode | None = None, country_codes: SequenceNotStr[str] | None = None, severity_level_id: str | None | Omit = omit, @@ -129,10 +111,8 @@ def update( id, name, rules, - content_type, event_selector_list, role_list, - applies_to, mode, country_codes, severity_level_id, @@ -148,17 +128,10 @@ def get(self, id: str, *, timeout: Timeout | NotGiven = not_given) -> Policy: def list( self, *, - content_type: ContentType | None = None, - applies_to: AppliesTo | None = None, mode: PolicyMode | None = None, timeout: Timeout | NotGiven = not_given, ) -> list[Policy]: - return self._get( - f"{self._path}/list", - params=_list_params(content_type, applies_to, mode), - timeout=timeout, - cast_to=list[Policy], - ) + return self._get(f"{self._path}/list", params={"mode": mode}, timeout=timeout, cast_to=list[Policy]) class Metrics(Policies): @@ -172,11 +145,9 @@ async def create( self, *, name: str, - rules: SequenceNotStr[Rule] | None = None, - content_type: ContentType | None = None, + rules: SequenceNotStr[Rule], event_selector_list: SequenceNotStr[EventSelector] | None = None, role_list: SequenceNotStr[PolicyRole] | None = None, - applies_to: AppliesTo | None = None, mode: PolicyMode | None = None, country_codes: SequenceNotStr[str] | None = None, severity_level_id: str | None = None, @@ -185,10 +156,8 @@ async def create( body = _create_body( name, rules, - content_type, event_selector_list, role_list, - applies_to, mode, country_codes, severity_level_id, @@ -201,10 +170,8 @@ async def update( *, name: str | None = None, rules: SequenceNotStr[Rule] | None = None, - content_type: ContentType | None = None, event_selector_list: SequenceNotStr[EventSelector] | None = None, role_list: SequenceNotStr[PolicyRole] | None = None, - applies_to: AppliesTo | None = None, mode: PolicyMode | None = None, country_codes: SequenceNotStr[str] | None = None, severity_level_id: str | None | Omit = omit, @@ -215,10 +182,8 @@ async def update( id, name, rules, - content_type, event_selector_list, role_list, - applies_to, mode, country_codes, severity_level_id, @@ -234,17 +199,10 @@ async def get(self, id: str, *, timeout: Timeout | NotGiven = not_given) -> Poli async def list( self, *, - content_type: ContentType | None = None, - applies_to: AppliesTo | None = None, mode: PolicyMode | None = None, timeout: Timeout | NotGiven = not_given, ) -> list[Policy]: - return await self._get( - f"{self._path}/list", - params=_list_params(content_type, applies_to, mode), - timeout=timeout, - cast_to=list[Policy], - ) + return await self._get(f"{self._path}/list", params={"mode": mode}, timeout=timeout, cast_to=list[Policy]) class AsyncMetrics(AsyncPolicies): diff --git a/src/whitecircle/types/__init__.py b/src/whitecircle/types/__init__.py index cab05b4..6824441 100644 --- a/src/whitecircle/types/__init__.py +++ b/src/whitecircle/types/__init__.py @@ -13,12 +13,11 @@ EventLookupResult, EventResult, EventsCheckResult, + EventsRateLimit, EventStatus, EventType, ) from .policies import ( - AppliesTo, - ContentType, EventSelector, Policy, PolicyMode, @@ -67,7 +66,6 @@ "Appeal", "AppealCreateResult", "AppealStatus", - "AppliesTo", "ArtifactCheckResult", "ArtifactContent", "ArtifactMetadata", @@ -78,7 +76,6 @@ "Condition", "ConditionState", "ContentField", - "ContentType", "EdgeKind", "EnabledByCondition", "Event", @@ -92,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 321697d..b9bf007 100644 --- a/src/whitecircle/types/events.py +++ b/src/whitecircle/types/events.py @@ -1,11 +1,14 @@ +import math from collections.abc import Mapping from datetime import datetime from typing import Any, Literal, Self, TypeAlias, TypedDict, Unpack, get_args +import httpx2 import pydantic from .._models import BaseModel from .artifacts import ArtifactContent +from .policies import SelectorType from .shared import PolicyResults, PolicyResultsMixin, Role, _given __all__ = [ @@ -22,6 +25,7 @@ "EventStatus", "EventType", "EventsCheckResult", + "EventsRateLimit", ] EventType: TypeAlias = Literal["message", "artifact", "tool", "function", "agent", "reasoning", "reset"] @@ -119,22 +123,32 @@ def assistant(cls, content: Any, **fields: Unpack[EventFields]) -> Self: return cls.message(content, role="assistant", **fields) @classmethod - def tool_call(cls, name: str, arguments: Any, **fields: Unpack[EventFields]) -> Self: + def tool_call(cls, name: str, arguments: Any, *, role: Role | None = None, **fields: Unpack[EventFields]) -> Self: """Pair it with its result through the same ``call_id``.""" - return cls(type="tool", name=name, arguments=arguments, **fields) + return cls(type="tool", name=name, arguments=arguments, **_given(role=role), **fields) @classmethod - def tool_result(cls, name: str, output: Any, **fields: Unpack[EventFields]) -> Self: - return cls(type="tool", name=name, output=output, **fields) + def tool_result(cls, name: str, output: Any, *, role: Role | None = None, **fields: Unpack[EventFields]) -> Self: + return cls(type="tool", name=name, output=output, **_given(role=role), **fields) @classmethod - def tool_definition(cls, name: str, definition: Any, **fields: Unpack[EventFields]) -> Self: - return cls(type="tool", name=name, definition=definition, **fields) + def tool_definition( + cls, name: str, definition: Any, *, role: Role | None = None, **fields: Unpack[EventFields] + ) -> Self: + return cls(type="tool", name=name, definition=definition, **_given(role=role), **fields) @classmethod - def agent(cls, value: Any, *, field: AgentField, name: str | None = None, **fields: Unpack[EventFields]) -> Self: + def agent( + cls, + value: Any, + *, + field: AgentField, + name: str | None = None, + role: Role | None = None, + **fields: Unpack[EventFields], + ) -> Self: """An agent's ``input`` (checked as user direction), ``instructions`` (system), ``output`` or ``state``.""" - return cls(type="agent", **{field: value}, **_given(name=name), **fields) + return cls(type="agent", **{field: value}, **_given(name=name, role=role), **fields) @classmethod def image( @@ -158,14 +172,51 @@ def reset(cls, summary: str | None = None, **fields: Unpack[EventFields]) -> Sel return cls(type="reset", **_given(content=summary), **fields) @classmethod - def reference(cls, type: EventType, event_id: str, *, run_id: str | None = None) -> Self: + def reference(cls, type: SelectorType, event_id: str, *, run_id: str | None = None) -> Self: """The latest stored Event with this ``event_id``, ``run_id`` and ``type``, used without a new check. An Event checked a moment ago may not be stored yet; the reference then comes back ``not_found``. """ + if type == "reset": # runtime guard for untyped callers # pyright: ignore[reportUnnecessaryComparison] + raise ValueError("a reset Event cannot be a reference") 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.""" + + +# 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") + 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 @@ -180,6 +231,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): @@ -204,6 +257,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/src/whitecircle/types/policies.py b/src/whitecircle/types/policies.py index 349e73e..23607f7 100644 --- a/src/whitecircle/types/policies.py +++ b/src/whitecircle/types/policies.py @@ -1,12 +1,13 @@ +from collections.abc import Mapping from datetime import datetime -from typing import Literal, TypeAlias +from typing import Any, Literal, Self, TypeAlias, cast + +import pydantic from .._models import BaseModel from .shared import Rule __all__ = [ - "AppliesTo", - "ContentType", "EventSelector", "Policy", "PolicyMode", @@ -15,21 +16,45 @@ "SelectorType", ] -ContentType: TypeAlias = Literal["session", "artifact", "any"] -AppliesTo: TypeAlias = Literal["input", "output", "any"] PolicyMode: TypeAlias = Literal["prod", "shadow"] PolicyState: TypeAlias = Literal["active", "inactive", "draft"] PolicyRole: TypeAlias = Literal["user", "assistant"] -SelectorType: TypeAlias = Literal["message", "tool", "function", "agent", "artifact", "reasoning", "reset"] +SelectorType: TypeAlias = Literal["message", "tool", "function", "agent", "artifact", "reasoning"] + +_ALLOWED_SELECTOR_FIELDS: dict[SelectorType, tuple[str, ...]] = { + "message": ("content", "delta"), + "tool": ("arguments", "output", "definition"), + "function": ("arguments", "output", "definition"), + "agent": ("input", "instructions", "output", "state"), + "reasoning": ("content", "delta"), + "artifact": (), +} class EventSelector(BaseModel): - """Which Event type, and optionally which field, a Policy evaluates.""" + """Which Event type and field a Policy evaluates. + + ``field`` is required for every type except ``artifact``, which takes an optional ``kind`` (such as ``"image"``) + instead. + """ - type: SelectorType | str + type: SelectorType field: str | None = None kind: str | None = None + @pydantic.model_validator(mode="after") + def _check_field(self) -> Self: + allowed = _ALLOWED_SELECTOR_FIELDS.get(self.type) + if allowed is None: + raise ValueError(f"unknown EventSelector type: {self.type!r}") + if self.type == "artifact": + if self.field is not None: + raise ValueError("an artifact EventSelector does not take field (use kind instead)") + elif self.field not in allowed: + fields = ", ".join(allowed) + raise ValueError(f"a {self.type} EventSelector requires field to be one of: {fields}") + return self + class Policy(BaseModel): """A Policy or a Metric; both have this shape.""" @@ -37,14 +62,42 @@ class Policy(BaseModel): id: str name: str rules: list[Rule] - content_type: ContentType | str event_selector_list: list[EventSelector] role_list: list[PolicyRole | str] """Empty means every role.""" - applies_to: AppliesTo | str mode: PolicyMode | str """``shadow`` Policies are evaluated but never affect ``flagged``.""" created_at: datetime state: PolicyState | str country_codes: list[str] severity_level_id: str | None = None + + @pydantic.field_validator("event_selector_list", mode="wrap") + @classmethod + def _parse_selectors(cls, value: object, handler: pydantic.ValidatorFunctionWrapHandler) -> list[EventSelector]: + try: + return cast(list[EventSelector], handler(value)) + except pydantic.ValidationError: + if not isinstance(value, list): + raise + # Keep response parsing tolerant of unknown future selector types or fields from the server. + out: list[EventSelector] = [] + for item in cast(list[object], value): + if isinstance(item, EventSelector): + out.append(item) + elif isinstance(item, Mapping): + raw = cast(Mapping[str, Any], item) + try: + out.append(EventSelector.model_validate(raw)) + except pydantic.ValidationError: + if ( + isinstance(raw.get("type"), str) + and isinstance(raw.get("field"), str | None) + and isinstance(raw.get("kind"), str | None) + ): + out.append(EventSelector.model_construct(_fields_set=set(raw), **raw)) + else: + raise + else: + raise + return out diff --git a/src/whitecircle/types/users.py b/src/whitecircle/types/users.py index ef08fa2..fe8a5ca 100644 --- a/src/whitecircle/types/users.py +++ b/src/whitecircle/types/users.py @@ -47,9 +47,9 @@ class Strike(BaseModel): class UserRisk(BaseModel): - total_strike_points: int + total_strike_points: int = 0 """All active strikes. The action threshold counts only the highest strike per session, so it can be lower.""" - strikes: list[Strike] + strikes: list[Strike] = [] """Active strikes only.""" action: str | None = None """Title of the effective action as configured for the team (``"Suspend"``), or ``None``.""" diff --git a/src/whitecircle/webhooks.py b/src/whitecircle/webhooks.py index fa1a4d8..18ddf7d 100644 --- a/src/whitecircle/webhooks.py +++ b/src/whitecircle/webhooks.py @@ -63,4 +63,4 @@ def parse(body: bytes | str) -> WebhookEvent: f"{'.'.join(map(str, problem['loc'])) or 'body'}: {problem['msg']}" for problem in error.errors(include_input=False, include_url=False) ) - raise WebhookVerificationError(f"Webhook body is not a valid event: {problems}") from error + raise WebhookVerificationError(f"Webhook body is not a valid event: {problems}") from None diff --git a/tests/live/conftest.py b/tests/live/conftest.py index 0e10c6c..a958563 100644 --- a/tests/live/conftest.py +++ b/tests/live/conftest.py @@ -103,12 +103,17 @@ def metadata(tag: str, condition: Condition) -> dict[str, Any]: return {"sdk_live": tag, "user": {"id": f"{tag}-user"}} +_IGNORED_EXTRA: dict[type[pydantic.BaseModel], frozenset[str]] = { + # The API still returns applies_to and content_type on Policy payloads, which the SDK intentionally omits. + Policy: frozenset({"applies_to", "content_type"}), +} + + def assert_known_fields(value: object, path: str = "") -> None: """Fail on response fields the SDK model does not declare (extra="allow" would hide them) and naive datetimes.""" if isinstance(value, pydantic.BaseModel): - assert not value.model_extra, ( - f"undeclared fields at {path or type(value).__name__}: {sorted(value.model_extra)}" - ) + extra = set(value.model_extra or ()) - _IGNORED_EXTRA.get(type(value), frozenset()) + assert not extra, f"undeclared fields at {path or type(value).__name__}: {sorted(extra)}" for name in type(value).model_fields: assert_known_fields(getattr(value, name), f"{path}.{name}" if path else name) elif isinstance(value, datetime): diff --git a/tests/live/test_policies.py b/tests/live/test_policies.py index 52b2ca4..f2a4dde 100644 --- a/tests/live/test_policies.py +++ b/tests/live/test_policies.py @@ -2,7 +2,7 @@ import pytest -from whitecircle import NotFoundError, Rule, WhiteCircle +from whitecircle import Event, EventSelector, NotFoundError, Rule, WhiteCircle, field from ..conftest import Call from .conftest import assert_known_fields, assert_same_stored @@ -56,3 +56,56 @@ def test_update_keeps_or_clears_the_severity_level( async def test_get_unknown_raises_not_found(call: Call) -> None: with pytest.raises(NotFoundError): await call("policies", "get", str(uuid.uuid4())) + + +def test_tool_arguments_targeting( + client: WhiteCircle, created: list[tuple[str, str]], tag: str, environment_id: str +) -> None: + marker = f"{tag}-tool-args" + made = client.policies.create( + name=marker, + rules=[Rule.flag("Any mention of pineapples")], + event_selector_list=[EventSelector(type="tool", field="arguments")], + role_list=[], + mode="shadow", + ) + created.append(("policies", made.id)) + assert_known_fields(made) + assert [(selector.type, selector.field) for selector in made.event_selector_list] == [("tool", "arguments")] + assert made.role_list == [] + + cond = client.conditions.create( + name=f"{marker}-cond", + conditions=field("sdk_live") == marker, + environment_ids=[environment_id], + policy_ids=[made.id], + state="Active", + ) + created.append(("conditions", cond.id)) + + event = Event.tool_call("order_fruit", {"item": "pineapples"}, call_id="c1", metadata={"sdk_live": marker}) + + shadow_result = client.events.check(event, run_id=f"{marker}-shadow", include_shadow=True) + assert_known_fields(shadow_result) + assert shadow_result.policies is not None + assert shadow_result.policies[made.id].shadow is True + + client.policies.update(made.id, mode="prod") + prod_result = client.events.check(event, run_id=f"{marker}-prod") + assert_known_fields(prod_result) + assert prod_result.policies is not None + assert prod_result.policies[made.id].shadow is False + + # Without role="assistant", tool/arguments defaults to the user side so role_list=["assistant"] skips it. + client.policies.update(made.id, role_list=["assistant"]) + excluded_result = client.events.check(event, run_id=f"{marker}-assistant") + assert_known_fields(excluded_result) + assert made.id not in (excluded_result.policies or {}) + + assistant_event = Event.tool_call( + "order_fruit", {"item": "pineapples"}, role="assistant", call_id="c2", metadata={"sdk_live": marker} + ) + override_result = client.events.check(assistant_event, run_id=f"{marker}-assistant-override") + assert_known_fields(override_result) + assert override_result.policies is not None + assert override_result.policies[made.id].shadow is False diff --git a/tests/test_artifacts.py b/tests/test_artifacts.py index 7576656..226ebda 100644 --- a/tests/test_artifacts.py +++ b/tests/test_artifacts.py @@ -24,6 +24,8 @@ async def test_check_sends_content_and_context(call: Call, api: MockAPI) -> None ArtifactContent.from_bytes(b"\x89PNG", mime_type="image/png"), role="user", external_artifact_id="upload_1", + trace_id="trace_1", + span_id="span_1", metadata={"upload": {"source": "avatar"}}, ) assert (api.last.method, api.last.url.path) == ("POST", "/api/artifact") @@ -32,6 +34,8 @@ async def test_check_sends_content_and_context(call: Call, api: MockAPI) -> None "environment_id": "env_test", "external_artifact_id": "upload_1", "role": "user", + "trace_id": "trace_1", + "span_id": "span_1", "metadata": {"upload": {"source": "avatar"}}, } assert checked.flagged diff --git a/tests/test_client.py b/tests/test_client.py index 099be19..05daec0 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -1,4 +1,5 @@ import enum +import json import logging import pickle import uuid @@ -27,6 +28,7 @@ WhiteCircleError, omit, ) +from whitecircle._base_client import path_param from whitecircle._logs import SensitiveHeadersFilter, logger, setup_logging from whitecircle._models import BaseModel, prepare_body from whitecircle._types import null @@ -128,8 +130,8 @@ def test_custom_and_per_request_headers(api: MockAPI) -> None: def test_body_and_params_are_prepared(client: WhiteCircle, api: MockAPI) -> None: api.json(body=[]) - client.request("GET", "/api/policy/list", params={"mode": "prod", "applies_to": None, "content_type": omit}) - assert dict(api.last.url.params) == {"mode": "prod"} + client.request("GET", "/api/run/graph", params={"run_id": "run_1", "limit": None, "after": omit}) + assert dict(api.last.url.params) == {"run_id": "run_1"} api.json(body={}) client.request("POST", "/api/condition/create", body={"name": "n", "description": None, "state": omit}) @@ -218,11 +220,71 @@ def test_rate_limit_waits_at_least_one_second(client: WhiteCircle, api: MockAPI, assert sleeps == [1.0] -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 _assert_replayed( + requests: list[httpx2.Request], count: int, method: str, path: str, body: dict[str, object] | None = None +) -> None: + assert len(requests) == count + for request in requests: + assert (request.method, request.url.path) == (method, path) + if body is None: + assert request.content == b"" + else: + assert json.loads(request.content) == body + + +@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={"n": 1}) + assert sleeps == [expected] + _assert_replayed(api.requests, 2, "POST", "/api/event", {"n": 1}) + + +@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={"n": 2}) + assert sleeps[0] == 1.0 + assert sleeps[1] == 1.0 + assert 1.5 <= sleeps[2] <= 2.0 + _assert_replayed(api.requests, 4, "POST", "/api/event", {"n": 2}) + + +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={"events": []}) == {"ok": True} + assert sleeps == [2.5] + _assert_replayed(api.requests, 2, "POST", "/api/events", {"events": []}) + + +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 + client.request("POST", "/api/event", body={"n": 3}) + _assert_replayed(api.requests, 1, "POST", "/api/event", {"n": 3}) + 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={"n": 4}) + assert len(sleeps) == 1 + assert 0.375 <= sleeps[0] <= 0.5 + _assert_replayed(api.requests, 2, "POST", "/api/event", {"n": 4}) @pytest.mark.parametrize("error", [httpx2.ReadTimeout("slow"), httpx2.ReadError("reset"), httpx2.WriteError("x")]) @@ -380,22 +442,52 @@ def test_default_timeout(client: WhiteCircle, api: MockAPI) -> None: assert api.last.extensions["timeout"] == {"connect": None, "read": None, "write": None, "pool": None} -async def test_async_request_retry_and_errors(async_client: AsyncWhiteCircle, api: MockAPI) -> None: +async def test_async_request_retry_and_errors( + async_client: AsyncWhiteCircle, api: MockAPI, sleeps: list[float] +) -> None: api.json(503, {"error": "busy"}) api.json(200, {"ok": True}) assert await async_client.request("POST", "/api/event", body={"a": 1}) == {"ok": True} - assert len(api.requests) == 2 + _assert_replayed(api.requests, 2, "POST", "/api/event", {"a": 1}) assert api.last.headers["whitecircle-version"] == "2026-06-01" api.reply(httpx2.ReadTimeout("slow")) with pytest.raises(APITimeoutError): - await async_client.request("POST", "/api/event", body={}) + await async_client.request("POST", "/api/event", body={"k": "timeout"}) api.json(429, {"error": "Monthly request quota exceeded for promotional plan."}) with pytest.raises(RateLimitError): - await async_client.request("POST", "/api/event", body={}) + await async_client.request("POST", "/api/event", body={"k": "quota"}) assert len(api.requests) == 4 + # GET retries 502 and 504; 429 waits at least 1s; ConnectError retries on POST. + start = len(api.requests) + api.json(502, {}) + api.json(504, {}) + api.json(200, {"ok": "get"}) + assert await async_client.request("GET", "/api/usage") == {"ok": "get"} + _assert_replayed(api.requests[start:], 3, "GET", "/api/usage") + + start = len(api.requests) + before_429 = len(sleeps) + api.json(429, {"error": "Too many requests"}) + api.json(200, {"ok": "429"}) + assert await async_client.request("POST", "/api/event", body={"k": "429"}) == {"ok": "429"} + assert sleeps[before_429] >= 1.0 + _assert_replayed(api.requests[start:], 2, "POST", "/api/event", {"k": "429"}) + + start = len(api.requests) + api.reply(httpx2.ConnectError("refused")) + api.json(200, {"ok": "conn"}) + assert await async_client.request("POST", "/api/event", body={"k": "conn"}) == {"ok": "conn"} + _assert_replayed(api.requests[start:], 2, "POST", "/api/event", {"k": "conn"}) + + +def test_path_param_rejects_empty_and_escapes_slashes() -> None: + with pytest.raises(ValueError): + path_param("") + assert path_param("a/b c") == "a%2Fb%20c" + async def test_async_copy_and_close() -> None: client = AsyncWhiteCircle(api_key=API_KEY) diff --git a/tests/test_events.py b/tests/test_events.py index fe6bc87..f5b8df0 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -1,3 +1,4 @@ +import inspect from datetime import UTC, datetime from typing import Any @@ -5,7 +6,18 @@ import pytest from pydantic import ValidationError -from whitecircle import ArtifactContent, AsyncWhiteCircle, Event, EventLink, InlinePolicy, Rule, WhiteCircle +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 @@ -153,7 +165,22 @@ async def test_events_require_an_environment(method: str, args: tuple[Any, ...], async with httpx2.AsyncClient(transport=transport) as async_http_client: events = AsyncWhiteCircle(api_key=API_KEY, http_client=async_http_client).events with pytest.raises(ValueError, match="environment_id"): - await getattr(events, method)(*args, **kwargs) + result = getattr(events, method)(*args, **kwargs) + if inspect.isawaitable(result): + await result + + +def test_shadow_only_result_is_not_checked() -> None: + result = EventCheckResult.model_validate( + { + "flagged": False, + "policies": {"pol_shadow": {"flagged": True, "name": "Shadow", "shadow": True}}, + "event": {"type": "message", "status": "completed", "event_id": "evt_1"}, + "run_id": "run_1", + } + ) + assert result.checked is False + assert result.flagged_policies == {} def test_constructors_set_one_content_field() -> None: @@ -232,7 +259,118 @@ def test_event_rejects_a_wrong_content_field(fields: dict[str, Any]) -> None: Event.model_validate(fields) +def test_event_reference_rejects_reset() -> None: + with pytest.raises(ValueError, match="reset"): + Event.reference("reset", "evt_1") # pyright: ignore[reportArgumentType] + + def test_event_helper_types_are_exported() -> None: from whitecircle import types assert {"AgentField", "EventFields"} <= set(types.__all__) + + +def test_tool_and_agent_constructors_accept_role() -> None: + assert Event.tool_call("lookup", {"id": 1}, role="assistant").model_dump(exclude_unset=True) == { + "type": "tool", + "name": "lookup", + "arguments": {"id": 1}, + "role": "assistant", + } + assert Event.tool_result("lookup", {"ok": True}, role="tool").model_dump(exclude_unset=True) == { + "type": "tool", + "name": "lookup", + "output": {"ok": True}, + "role": "tool", + } + assert Event.tool_definition("lookup", {"type": "function"}, role="system").model_dump(exclude_unset=True) == { + "type": "tool", + "name": "lookup", + "definition": {"type": "function"}, + "role": "system", + } + assert Event.agent("done", field="output", name="worker", role="assistant").model_dump(exclude_unset=True) == { + "type": "agent", + "output": "done", + "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"}, + {**RATE_LIMIT_HEADERS, "x-ratelimit-events-window": "0"}, + ], +) +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 + + +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) diff --git a/tests/test_expressions.py b/tests/test_expressions.py index a954933..dd6d37a 100644 --- a/tests/test_expressions.py +++ b/tests/test_expressions.py @@ -40,6 +40,12 @@ def test_misuse_raises() -> None: (field("a") == 1) and (field("b") == 2) # must raise # pyright: ignore[reportUnusedExpression] with pytest.raises(TypeError): (field("a") == 1) | (field("b") == 2) # | is unsupported # pyright: ignore[reportOperatorIssue, reportUnusedExpression] + with pytest.raises(TypeError): + (field("a") == 1) & True # non-Expression operand # pyright: ignore[reportOperatorIssue, reportUnusedExpression] + with pytest.raises(TypeError): + field("plan").is_in("pro") # bare string must fail # pyright: ignore[reportArgumentType] + with pytest.raises(TypeError): + field("plan").not_in(b"pro") # bare bytes must fail # pyright: ignore[reportArgumentType] with pytest.raises(TypeError): hash(field("a")) with pytest.raises(ValueError): diff --git a/tests/test_policies.py b/tests/test_policies.py index ff8cf71..306371d 100644 --- a/tests/test_policies.py +++ b/tests/test_policies.py @@ -1,7 +1,10 @@ import pytest +from pydantic import ValidationError -from whitecircle import EventSelector, Rule +import whitecircle +from whitecircle import EventSelector, Rule, types from whitecircle.types import Policy +from whitecircle.types import policies as policy_types from .conftest import Call, MockAPI @@ -10,7 +13,7 @@ "name": "No PII", "rules": [{"id": "11111111-1111-4111-8111-111111111111", "flagged_content": "Sharing PII"}], "content_type": "any", - "event_selector_list": [{"type": "message"}], + "event_selector_list": [{"type": "message", "field": "content"}], "role_list": [], "applies_to": "any", "mode": "prod", @@ -31,16 +34,22 @@ async def test_create_sends_rules_without_ids_or_unknown_keys( "create", name="No PII", rules=[copied, Rule.allow("Order numbers")], - event_selector_list=[EventSelector(type="tool", field="output")], + event_selector_list=[EventSelector(type="tool", field="output"), EventSelector(type="artifact", kind="image")], + role_list=[], mode="shadow", + country_codes=["DE", "FR"], + severity_level_id="sev_1", ) assert isinstance(policy, Policy) assert (api.last.method, api.last.url.path) == ("POST", f"{prefix}/create") assert api.last_json() == { "name": "No PII", "rules": [{"flagged_content": "Sharing PII"}, {"allowed_content": "Order numbers"}], - "event_selector_list": [{"type": "tool", "field": "output"}], + "event_selector_list": [{"type": "tool", "field": "output"}, {"type": "artifact", "kind": "image"}], + "role_list": [], "mode": "shadow", + "country_codes": ["DE", "FR"], + "severity_level_id": "sev_1", } @@ -57,8 +66,24 @@ async def test_update_keeps_rule_ids_and_gives_new_rules_one(call: Call, api: Mo async def test_update_sends_only_given_fields(call: Call, api: MockAPI) -> None: api.json(200, POLICY) - await call("policies", "update", "pol_1", name=None, rules=None, mode="prod") - assert api.last_json() == {"id": "pol_1", "mode": "prod"} + await call( + "policies", + "update", + "pol_1", + name=None, + rules=None, + event_selector_list=[EventSelector(type="tool", field="arguments")], + role_list=["assistant"], + country_codes=["US"], + mode="prod", + ) + assert api.last_json() == { + "id": "pol_1", + "event_selector_list": [{"type": "tool", "field": "arguments"}], + "role_list": ["assistant"], + "country_codes": ["US"], + "mode": "prod", + } async def test_update_clears_severity_level_only_when_asked(call: Call, api: MockAPI) -> None: @@ -71,21 +96,140 @@ async def test_update_clears_severity_level_only_when_asked(call: Call, api: Moc assert api.last_json() == {"id": "met_1", "severity_level_id": "sev_1"} -async def test_delete_get_and_list(call: Call, api: MockAPI) -> None: +@pytest.mark.parametrize(("resource", "prefix"), [("policies", "/api/policy"), ("metrics", "/api/metric")]) +async def test_delete_get_and_list(call: Call, api: MockAPI, resource: str, prefix: str) -> None: api.json(200, POLICY) api.json(200, POLICY) api.json(200, [POLICY, POLICY]) - await call("policies", "delete", "pol_1") - assert (api.last.method, api.last.url.path, api.last_json()) == ("POST", "/api/policy/delete", {"id": "pol_1"}) - await call("policies", "get", "pol_1") - assert (api.last.method, api.last.url.raw_path) == ("GET", b"/api/policy/get_by_id?id=pol_1") - policies = await call("policies", "list", mode="shadow") - assert api.last.url.raw_path == b"/api/policy/list?mode=shadow" - assert [policy.id for policy in policies] == ["pol_1", "pol_1"] - assert policies[0].rules[0].flagged_content == "Sharing PII" + await call(resource, "delete", "pol_1") + assert (api.last.method, api.last.url.path, api.last_json()) == ("POST", f"{prefix}/delete", {"id": "pol_1"}) + await call(resource, "get", "pol_1") + assert (api.last.method, api.last.url.raw_path) == ("GET", f"{prefix}/get_by_id?id=pol_1".encode()) + items = await call(resource, "list", mode="shadow") + assert api.last.url.raw_path == f"{prefix}/list?mode=shadow".encode() + assert [item.id for item in items] == ["pol_1", "pol_1"] + assert items[0].rules[0].flagged_content == "Sharing PII" async def test_policy_routes_never_get_an_environment(call: Call, api: MockAPI) -> None: api.json(200, []) await call("policies", "list") assert api.last.url.raw_path == b"/api/policy/list" + + +def test_policy_parses_server_payload_carrying_removed_targeting_fields() -> None: + policy = Policy.model_validate(POLICY) + assert policy.id == "pol_1" + assert policy.role_list == [] + assert "applies_to" not in Policy.model_fields + assert "content_type" not in Policy.model_fields + assert policy.model_extra == {"content_type": "any", "applies_to": "any"} + for name in ("AppliesTo", "ContentType"): + assert not hasattr(whitecircle, name) + assert not hasattr(types, name) + assert not hasattr(policy_types, name) + + +@pytest.mark.parametrize("resource", ["policies", "metrics"]) +@pytest.mark.parametrize(("param", "value"), [("applies_to", "output"), ("content_type", "any")]) +async def test_removed_targeting_parameters_raise_type_error(call: Call, resource: str, param: str, value: str) -> None: + with pytest.raises(TypeError, match=param): + await call(resource, "create", name="No PII", rules=[Rule.flag("Sharing PII")], **{param: value}) + with pytest.raises(TypeError, match=param): + await call(resource, "update", "pol_1", **{param: value}) + with pytest.raises(TypeError, match=param): + await call(resource, "list", **{param: value}) + + +@pytest.mark.parametrize("resource", ["policies", "metrics"]) +async def test_create_requires_non_empty_rules(call: Call, api: MockAPI, resource: str) -> None: + with pytest.raises(TypeError, match="rules"): + await call(resource, "create", name="No PII") + with pytest.raises(ValueError, match="at least one Rule"): + await call(resource, "create", name="No PII", rules=[]) + assert not api.requests + + +@pytest.mark.parametrize("bad_type", ["reset", "unknown"]) +def test_event_selector_rejects_unknown_type(bad_type: str) -> None: + with pytest.raises(ValidationError): + EventSelector.model_validate({"type": bad_type, "field": "content"}) + + +@pytest.mark.parametrize( + ("selector_type", "expected_fields"), + [ + ("message", "content, delta"), + ("tool", "arguments, output, definition"), + ("function", "arguments, output, definition"), + ("agent", "input, instructions, output, state"), + ("reasoning", "content, delta"), + ], +) +def test_event_selector_requires_allowed_field_for_non_artifact(selector_type: str, expected_fields: str) -> None: + with pytest.raises(ValueError, match=expected_fields): + EventSelector.model_validate({"type": selector_type}) + with pytest.raises(ValueError, match=expected_fields): + EventSelector.model_validate({"type": selector_type, "field": "invalid"}) + + +def test_event_selector_rejects_field_on_artifact() -> None: + with pytest.raises(ValueError, match="artifact EventSelector does not take field"): + EventSelector(type="artifact", field="content") + assert EventSelector(type="artifact").model_dump(exclude_unset=True) == {"type": "artifact"} + assert EventSelector(type="artifact", kind="image").model_dump(exclude_unset=True) == { + "type": "artifact", + "kind": "image", + } + + +def test_policy_parses_unknown_future_selector_types_and_fields() -> None: + payload = { + **POLICY, + "event_selector_list": [ + {"type": "message", "field": "content"}, + {"type": "future_surface", "field": "summary", "extra_attr": 1}, + {"type": "message", "field": "future_field"}, + ], + } + policy = Policy.model_validate(payload) + assert [(s.type, s.field) for s in policy.event_selector_list] == [ + ("message", "content"), + ("future_surface", "summary"), + ("message", "future_field"), + ] + assert policy.event_selector_list[1].model_extra == {"extra_attr": 1} + + rebuilt = Policy( + id=policy.id, + name=policy.name, + rules=policy.rules, + event_selector_list=policy.event_selector_list, + role_list=policy.role_list, + mode=policy.mode, + created_at=policy.created_at, + state=policy.state, + country_codes=policy.country_codes, + ) + assert [(s.type, s.field) for s in rebuilt.event_selector_list] == [ + ("message", "content"), + ("future_surface", "summary"), + ("message", "future_field"), + ] + assert rebuilt.event_selector_list[1].model_extra == {"extra_attr": 1} + + +@pytest.mark.parametrize( + "bad_item", + [ + {"field": "content"}, + {"type": 123, "field": "content"}, + "message", + {"type": "future_surface", "field": 123}, + {"type": "message", "field": 123}, + {"type": "future_surface", "kind": 123}, + ], +) +def test_policy_rejects_malformed_selectors(bad_item: object) -> None: + with pytest.raises(ValidationError): + Policy.model_validate({**POLICY, "event_selector_list": [bad_item]}) diff --git a/tests/test_streaming.py b/tests/test_streaming.py index 3e3c2ab..b661c6e 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -3,7 +3,8 @@ import json import socket import threading -from collections.abc import AsyncIterator, Iterator, MutableMapping +import time +from collections.abc import AsyncGenerator, AsyncIterator, Iterator, MutableMapping from typing import Any, Literal import httpx2 @@ -14,6 +15,7 @@ from httpx2.websockets import ASGIWebSocketTransport from whitecircle import ( + APITimeoutError, AsyncWhiteCircle, AuthenticationError, StreamClosedError, @@ -80,7 +82,7 @@ def receive_text() -> str | None: return None return None - with sock: + with sock, contextlib.suppress(OSError): # the client may close early (e.g. connect timeout) for step, arg in self.script: if step == "recv": for _ in range(arg): @@ -91,14 +93,16 @@ def receive_text() -> str | None: sock.sendall(connection.send(wsproto.events.TextMessage(json.dumps(arg)))) elif step == "raw": sock.sendall(connection.send(wsproto.events.TextMessage(arg))) + elif step == "bytes": + sock.sendall(connection.send(wsproto.events.BytesMessage(arg))) + elif step == "sleep": + time.sleep(arg) else: - with contextlib.suppress(OSError): # the client may already have dropped the socket - sock.sendall(connection.send(wsproto.events.CloseConnection(arg))) + sock.sendall(connection.send(wsproto.events.CloseConnection(arg))) self.close_sent = True break - with contextlib.suppress(OSError): # the client may drop the socket right after its close frame - while receive_text() is not None: - pass + while receive_text() is not None: + pass self.closed = True async def app(self, scope: MutableMapping[str, Any], receive: Any, send: Any) -> None: @@ -116,22 +120,30 @@ async def app(self, scope: MutableMapping[str, Any], receive: Any, send: Any) -> await send({"type": "websocket.http.response.body", "body": b'{"error": "Invalid API key"}'}) return await send({"type": "websocket.accept"}) - for step, arg in self.script: - if step == "recv": - for _ in range(arg): - message = await receive() - self.received.append(json.loads(message["text"])) - elif step == "send": - await send({"type": "websocket.send", "text": json.dumps(arg)}) - elif step == "raw": - await send({"type": "websocket.send", "text": arg}) - else: - await send({"type": "websocket.close", "code": arg, "reason": ""}) - self.close_sent = True - return - while (await receive())["type"] != "websocket.disconnect": + try: + for step, arg in self.script: + if step == "recv": + for _ in range(arg): + message = await receive() + self.received.append(json.loads(message["text"])) + elif step == "send": + await send({"type": "websocket.send", "text": json.dumps(arg)}) + elif step == "raw": + await send({"type": "websocket.send", "text": arg}) + elif step == "bytes": + await send({"type": "websocket.send", "bytes": arg}) + elif step == "sleep": + await asyncio.sleep(arg) + else: + await send({"type": "websocket.close", "code": arg, "reason": ""}) + self.close_sent = True + return + while (await receive())["type"] != "websocket.disconnect": + pass + except Exception: pass - self.closed = True + finally: + self.closed = True async def wait_for(self, flag: Literal["closed", "close_sent"]) -> None: for _ in range(200): @@ -396,3 +408,128 @@ async def tokens() -> AsyncIterator[str]: client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client) reply = AsyncCheckedStream(AsyncEventStream(client, environment_id=ENVIRONMENT_ID), tokens()) assert [text async for text in reply] == ["ab"] + + +async def test_append_after_close_raises_not_open(mode: Mode) -> None: + server = Server(("recv", 1), READY) + if mode == "sync": + with httpx2.Client(transport=SocketTransport(server)) as sync_http: + sync_client = WhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=sync_http) + with EventStream(sync_client, environment_id=ENVIRONMENT_ID) as stream: + pass + with pytest.raises(WhiteCircleError, match="not open"): + stream.append("late") + return + async with async_http(server) as http_client: + client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client) + async with AsyncEventStream(client, environment_id=ENVIRONMENT_ID) as async_stream: + pass + with pytest.raises(WhiteCircleError, match="not open"): + await async_stream.append("late") + + +async def test_binary_frame_raises_stream_error(mode: Mode) -> None: + server = Server(("recv", 1), READY, ("recv", 1), ("bytes", b"\x00\x01"), CLOSE) + + with pytest.raises(StreamError) as raised: + await checked(mode, server, iter(["Hi"])) + + assert raised.value.code == "invalid_frame" + assert not raised.value.retryable + + +async def test_connect_times_out_waiting_for_ready(mode: Mode) -> None: + server = Server(("recv", 1)) + if mode == "sync": + with httpx2.Client(transport=SocketTransport(server)) as sync_http: + sync_client = WhiteCircle( + api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=sync_http, timeout=0.05 + ) + with pytest.raises(APITimeoutError): + EventStream(sync_client, environment_id=ENVIRONMENT_ID).connect() + await server.wait_for("closed") + return + async with async_http(server) as http_client: + client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client, timeout=0.05) + with pytest.raises(APITimeoutError): + await AsyncEventStream(client, environment_id=ENVIRONMENT_ID).connect() + await server.wait_for("closed") + + +async def test_connect_deadline_survives_ignored_frames(mode: Mode) -> None: + server = Server( + ("recv", 1), + ("sleep", 0.04), + ("send", {"type": "unknown_future_frame"}), + ("sleep", 0.04), + READY, + ) + if mode == "sync": + with httpx2.Client(transport=SocketTransport(server)) as sync_http: + sync_client = WhiteCircle( + api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=sync_http, timeout=0.06 + ) + with pytest.raises(APITimeoutError): + EventStream(sync_client, environment_id=ENVIRONMENT_ID).connect() + await server.wait_for("closed") + return + async with async_http(server) as http_client: + client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client, timeout=0.06) + with pytest.raises(APITimeoutError): + await AsyncEventStream(client, environment_id=ENVIRONMENT_ID).connect() + await server.wait_for("closed") + + +async def test_client_events_stream_and_check_stream_wiring(mode: Mode) -> None: + server1 = Server(("recv", 1), READY, ("recv", 2), check(1), FINISHED) + server2 = Server(("recv", 1), READY, ("recv", 2), check(1), FINISHED) + + if mode == "sync": + with httpx2.Client(transport=SocketTransport(server1)) as sync_http: + sync_client = WhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=sync_http) + with sync_client.events.stream(external_session_id="conv_1") as stream: + stream.append("Hi") + stream.finish() + assert [msg.type for msg in stream] == ["check", "completed"] + with httpx2.Client(transport=SocketTransport(server2)) as sync_http: + sync_client = WhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=sync_http) + reply = sync_client.events.check_stream(iter(["Hi"]), external_session_id="conv_1") + assert list(reply) == ["Hi"] + assert reply.result.outcome == "finish" + return + + async with async_http(server1) as http_client: + client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client) + async with client.events.stream(external_session_id="conv_1") as async_stream: + await async_stream.append("Hi") + await async_stream.finish() + assert [msg.type async for msg in async_stream] == ["check", "completed"] + async with async_http(server2) as http_client: + client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client) + async_reply = client.events.check_stream(iter(["Hi"]), external_session_id="conv_1") + assert [text async for text in async_reply] == ["Hi"] + assert async_reply.result.outcome == "finish" + + +async def test_async_checked_stream_closes_async_generator_when_flagged() -> None: + produced = 0 + closed = False + + async def tokens() -> AsyncGenerator[str]: + nonlocal produced, closed + try: + for produced in range(100_000): + yield f"t{produced} " + finally: + closed = True + + flagged = ("send", {"type": "completed", "code": "flagged"}) + server = Server(("recv", 1), READY, ("recv", 2), check(1), check(2, flagged=True), flagged, CLOSE) + async with async_http(server) as http_client: + client = AsyncWhiteCircle(api_key=API_KEY, environment_id=ENVIRONMENT_ID, http_client=http_client) + reply = client.events.check_stream(tokens()) + released = [text async for text in reply] + assert released == ["t0 "] + assert reply.result.flagged + assert closed + assert produced < 99_999 diff --git a/tests/test_users.py b/tests/test_users.py index 2e6a236..8fe5df1 100644 --- a/tests/test_users.py +++ b/tests/test_users.py @@ -74,6 +74,11 @@ async def test_appeals(call: Call, api: MockAPI) -> None: assert appeal.current_level == "high" +def test_user_risk_defaults_when_optional_fields_omitted() -> None: + risk = UserRisk.model_validate({}) + assert (risk.total_strike_points, risk.strikes, risk.action, risk.action_expires_at) == (0, [], None, None) + + async def test_responses_parse_when_the_server_omits_nulls(call: Call, api: MockAPI) -> None: strike = {key: value for key, value in STRIKE.items() if value is not None} del strike["external_session_id"] diff --git a/tests/test_webhooks.py b/tests/test_webhooks.py index 2a18924..748957b 100644 --- a/tests/test_webhooks.py +++ b/tests/test_webhooks.py @@ -1,8 +1,8 @@ import json import time +import traceback from typing import Any -import pydantic import pytest from whitecircle import Webhooks, WebhookVerificationError @@ -184,11 +184,13 @@ def test_parse_unknown_event_keeps_fields() -> None: def test_parse_invalid_body_raises_verification_error(body: bytes) -> None: with pytest.raises(WebhookVerificationError, match="not a valid event") as caught: Webhooks.parse(body) - assert isinstance(caught.value.__cause__, pydantic.ValidationError) + assert caught.value.__cause__ is None def test_unwrap_signed_invalid_envelope_raises_verification_error() -> None: body, headers = signed({"event_type": "session.violated", "session": {"internal_id": "secret-user-text"}}) with pytest.raises(WebhookVerificationError, match=r"session\.violation: Field required") as caught: Webhooks(SECRET).unwrap(body, headers) - assert "secret-user-text" not in str(caught.value) + assert caught.value.__cause__ is None + formatted = "".join(traceback.format_exception(caught.value)) + assert "secret-user-text" not in formatted