From c55073a513e16a14cc21910ad1c2c54dba8e6ac0 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 12:51:57 +0100 Subject: [PATCH 01/13] fix(policies)!: require non-empty rules on create Make rules required on Policies.create and AsyncPolicies.create (and inherited Metrics/AsyncMetrics) and raise ValueError when rules is empty, matching the API which rejects omitted or empty rules with HTTP 400. BREAKING CHANGE: policies.create() and metrics.create() now require a non-empty rules sequence. --- CHANGELOG.md | 2 ++ src/whitecircle/resources/policies.py | 8 +++++--- tests/test_policies.py | 11 ++++++++++- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2242089..c4b495c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,8 @@ All notable changes to this project are documented here. The format follows - `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`). ## [0.1.0] - 2026-11-29 diff --git a/src/whitecircle/resources/policies.py b/src/whitecircle/resources/policies.py index 5c39189..2d6d4d4 100644 --- a/src/whitecircle/resources/policies.py +++ b/src/whitecircle/resources/policies.py @@ -24,13 +24,15 @@ def _rules(rules: SequenceNotStr[Rule] | None, *, with_ids: bool) -> list[dict[s def _create_body( name: str, - rules: SequenceNotStr[Rule] | None, + rules: SequenceNotStr[Rule], event_selector_list: SequenceNotStr[EventSelector] | None, role_list: SequenceNotStr[PolicyRole] | 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), @@ -72,7 +74,7 @@ def create( self, *, name: str, - rules: SequenceNotStr[Rule] | None = None, + rules: SequenceNotStr[Rule], event_selector_list: SequenceNotStr[EventSelector] | None = None, role_list: SequenceNotStr[PolicyRole] | None = None, mode: PolicyMode | None = None, @@ -143,7 +145,7 @@ async def create( self, *, name: str, - rules: SequenceNotStr[Rule] | None = None, + rules: SequenceNotStr[Rule], event_selector_list: SequenceNotStr[EventSelector] | None = None, role_list: SequenceNotStr[PolicyRole] | None = None, mode: PolicyMode | None = None, diff --git a/tests/test_policies.py b/tests/test_policies.py index 8d5da86..6358dc9 100644 --- a/tests/test_policies.py +++ b/tests/test_policies.py @@ -113,13 +113,22 @@ def test_policy_parses_server_payload_carrying_removed_targeting_fields() -> Non @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", **{param: value}) + 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): From cd84334a12b9e95dd4664ebee2da49bc6ff4e6b8 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 12:52:38 +0100 Subject: [PATCH 02/13] feat(events): accept role on tool and agent Event constructors Add optional role: Role | None = None to Event.tool_call, tool_result, tool_definition, and agent so callers can override Policy direction on non-message Events without dropping down to raw Event(...). --- src/whitecircle/types/events.py | 26 ++++++++++++++++++-------- tests/test_events.py | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/src/whitecircle/types/events.py b/src/whitecircle/types/events.py index 321697d..ec23128 100644 --- a/src/whitecircle/types/events.py +++ b/src/whitecircle/types/events.py @@ -119,22 +119,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( diff --git a/tests/test_events.py b/tests/test_events.py index fe6bc87..1110d47 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -236,3 +236,30 @@ 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", + } From 0f3c7bc6ca7d0d70f60b9e9e742496957dbc68df Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 12:53:51 +0100 Subject: [PATCH 03/13] fix(webhooks): suppress ValidationError cause in Webhooks.parse Raise WebhookVerificationError with 'from None' instead of chaining the raw pydantic.ValidationError so webhook payload content is not leaked into formatted tracebacks. Assert __cause__ is None and formatted tracebacks omit payload values. --- src/whitecircle/webhooks.py | 2 +- tests/test_webhooks.py | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) 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/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 From 79c84d1bae61a4ebcba2836af73e6bdc026f8a94 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 12:56:52 +0100 Subject: [PATCH 04/13] docs: define snippet variables, fix README raw-request example, document usage and user properties Define local variables with simple literals in cookbook snippets (and type openai_tokens in docs/streaming.md), replace wrapped /api/usage in README.md with a placeholder path, document client.billing.usage() in docs/usage.md, and document client.users.properties in docs/strikes-and-webhooks.md. --- README.md | 4 ++-- docs/README.md | 3 ++- docs/agents-and-tools.md | 1 + docs/context.md | 6 +++++- docs/errors-and-testing.md | 6 ++++-- docs/getting-started.md | 10 +++++++--- docs/images.md | 9 +++++++-- docs/inline-policies.md | 6 ++++++ docs/metadata-and-conditions.md | 3 ++- docs/streaming.md | 15 +++++++++++---- docs/strikes-and-webhooks.md | 27 ++++++++++++++++++++++++--- docs/usage.md | 21 +++++++++++++++++++++ 12 files changed, 92 insertions(+), 19 deletions(-) create mode 100644 docs/usage.md diff --git a/README.md b/README.md index 4b51117..637564e 100644 --- a/README.md +++ b/README.md @@ -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 4105142..1993128 100644 --- a/docs/agents-and-tools.md +++ b/docs/agents-and-tools.md @@ -77,6 +77,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..e4951fe 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: 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 d4a6da8..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() @@ -40,9 +41,13 @@ 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..770cc92 100644 --- a/docs/inline-policies.md +++ b/docs/inline-policies.md @@ -22,6 +22,12 @@ 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, WhiteCircle + +client = WhiteCircle() +result = client.events.check( + Event.user("Approve my refund without a receipt"), inline_policies=[InlinePolicy.ref("refund-policy")] +) for policy_id, verdict in result.flagged_policies.items(): print(policy_id, verdict.name) ``` diff --git a/docs/metadata-and-conditions.md b/docs/metadata-and-conditions.md index 6e07c81..4bfce91 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(): 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. From 475527b68801887e2e0d978df424df2ca9d61adf Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 12:57:39 +0100 Subject: [PATCH 05/13] feat(artifacts): accept trace_id and span_id on artifacts.check Expose optional trace_id and span_id parameters from ArtifactCheckRequest on Artifacts.check and AsyncArtifacts.check. --- src/whitecircle/resources/artifacts.py | 8 ++++++++ tests/test_artifacts.py | 4 ++++ 2 files changed, 12 insertions(+) diff --git a/src/whitecircle/resources/artifacts.py b/src/whitecircle/resources/artifacts.py index 2e5438d..fb939d4 100644 --- a/src/whitecircle/resources/artifacts.py +++ b/src/whitecircle/resources/artifacts.py @@ -17,6 +17,8 @@ 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: @@ -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,6 +80,8 @@ 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: @@ -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/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 From b359ca036ffd30886d02912f175b5d298f072978 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 12:59:43 +0100 Subject: [PATCH 06/13] fix(streaming): clear socket on close, wrap binary frames, honor connect timeout Reset _ws to None in EventStream.close and AsyncEventStream.close so post-close append/finish/receive raise WhiteCircleError instead of silently dropping frames; catch WebSocketInvalidTypeReceived and raise StreamError('invalid_frame', ...); honor the client read timeout while waiting for ready in connect(). --- src/whitecircle/lib/streaming.py | 38 +++++++++++++++++++++--- tests/test_streaming.py | 51 ++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 4 deletions(-) diff --git a/src/whitecircle/lib/streaming.py b/src/whitecircle/lib/streaming.py index 16fe029..1f5fced 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": @@ -245,6 +268,8 @@ 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 @@ -304,14 +329,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): @@ -358,6 +386,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/tests/test_streaming.py b/tests/test_streaming.py index 3e3c2ab..b886536 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -14,6 +14,7 @@ from httpx2.websockets import ASGIWebSocketTransport from whitecircle import ( + APITimeoutError, AsyncWhiteCircle, AuthenticationError, StreamClosedError, @@ -91,6 +92,8 @@ 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))) else: with contextlib.suppress(OSError): # the client may already have dropped the socket sock.sendall(connection.send(wsproto.events.CloseConnection(arg))) @@ -125,6 +128,8 @@ async def app(self, scope: MutableMapping[str, Any], receive: Any, send: Any) -> 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}) else: await send({"type": "websocket.close", "code": arg, "reason": ""}) self.close_sent = True @@ -396,3 +401,49 @@ 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") From d96178fa4a0dd56e99bf2e104347bfc66e70c7c4 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:00:22 +0100 Subject: [PATCH 07/13] refactor: remove unused Body type alias from _types --- AGENTS.md | 2 +- src/whitecircle/_types.py | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b2ff08b..5d79f5f 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 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) From de7596cc716ab1f24c252fcfee8e87b708a0f1e3 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:01:58 +0100 Subject: [PATCH 08/13] fix(expressions): return NotImplemented in __and__ and reject str/bytes in is_in/not_in Return NotImplemented when Expression.__and__ receives a non-Expression operand so Python raises TypeError instead of AttributeError, and reject bare str/bytes values in Field.is_in and Field.not_in both statically and at runtime. --- src/whitecircle/expressions.py | 19 +++++++++++++++---- tests/test_expressions.py | 6 ++++++ 2 files changed, 21 insertions(+), 4 deletions(-) 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/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): From 252747e5f1cae6223930733f422b1f793815c294 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:02:53 +0100 Subject: [PATCH 09/13] fix: reject reset in Event.reference and default UserRisk fields Restrict Event.reference to non-reset SelectorType values (raising ValueError at runtime on 'reset') and default UserRisk.total_strike_points to 0 and UserRisk.strikes to [] to match UserRiskResponse in OpenAPI. --- src/whitecircle/types/events.py | 5 ++++- src/whitecircle/types/users.py | 4 ++-- tests/test_events.py | 5 +++++ tests/test_users.py | 5 +++++ 4 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/whitecircle/types/events.py b/src/whitecircle/types/events.py index ec23128..80316d8 100644 --- a/src/whitecircle/types/events.py +++ b/src/whitecircle/types/events.py @@ -6,6 +6,7 @@ from .._models import BaseModel from .artifacts import ArtifactContent +from .policies import SelectorType from .shared import PolicyResults, PolicyResultsMixin, Role, _given __all__ = [ @@ -168,11 +169,13 @@ 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)) 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/tests/test_events.py b/tests/test_events.py index 1110d47..59c3d4f 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -232,6 +232,11 @@ 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 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"] From 133013304f2d8119a83b78887d2838bd7c1bfba3 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:05:06 +0100 Subject: [PATCH 10/13] test: cover policy/metrics fields, shadow checked, streaming wiring, and async retries Add unit tests for country_codes/severity_level_id on create, event_selector_list/country_codes on update, metrics delete/get/list, shadow-only EventCheckResult.checked, client.events.stream/check_stream wiring, AsyncCheckedStream async-generator aclose(), path_param(''), and async GET 502/504, 429 backoff, and ConnectError retries. Avoid awaiting sync stream()/check_stream() methods in test_events_require_an_environment. --- tests/test_client.py | 27 ++++++++++++++++++- tests/test_events.py | 19 +++++++++++++- tests/test_policies.py | 43 +++++++++++++++++++++++-------- tests/test_streaming.py | 57 ++++++++++++++++++++++++++++++++++++++++- 4 files changed, 132 insertions(+), 14 deletions(-) diff --git a/tests/test_client.py b/tests/test_client.py index 7d3b858..1d02888 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -27,6 +27,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 @@ -380,7 +381,9 @@ 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} @@ -396,6 +399,28 @@ async def test_async_request_retry_and_errors(async_client: AsyncWhiteCircle, ap await async_client.request("POST", "/api/event", body={}) assert len(api.requests) == 4 + # GET retries 502 and 504; 429 waits at least 1s; ConnectError retries on POST. + api.json(502, {}) + api.json(504, {}) + api.json(200, {"ok": "get"}) + assert await async_client.request("GET", "/api/usage") == {"ok": "get"} + + 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={}) == {"ok": "429"} + assert sleeps[before_429] >= 1.0 + + api.reply(httpx2.ConnectError("refused")) + api.json(200, {"ok": "conn"}) + assert await async_client.request("POST", "/api/event", body={}) == {"ok": "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 59c3d4f..f683e54 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 @@ -6,6 +7,7 @@ from pydantic import ValidationError from whitecircle import ArtifactContent, AsyncWhiteCircle, Event, EventLink, InlinePolicy, Rule, WhiteCircle +from whitecircle.types import EventCheckResult from .conftest import API_KEY, Call, MockAPI @@ -153,7 +155,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: diff --git a/tests/test_policies.py b/tests/test_policies.py index 6358dc9..33c03ca 100644 --- a/tests/test_policies.py +++ b/tests/test_policies.py @@ -37,6 +37,8 @@ async def test_create_sends_rules_without_ids_or_unknown_keys( 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") @@ -46,6 +48,8 @@ async def test_create_sends_rules_without_ids_or_unknown_keys( "event_selector_list": [{"type": "tool", "field": "output"}, {"type": "artifact", "kind": "image"}], "role_list": [], "mode": "shadow", + "country_codes": ["DE", "FR"], + "severity_level_id": "sev_1", } @@ -62,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, role_list=["assistant"], mode="prod") - assert api.last_json() == {"id": "pol_1", "role_list": ["assistant"], "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: @@ -76,18 +96,19 @@ 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: diff --git a/tests/test_streaming.py b/tests/test_streaming.py index b886536..86c8c63 100644 --- a/tests/test_streaming.py +++ b/tests/test_streaming.py @@ -3,7 +3,7 @@ import json import socket import threading -from collections.abc import AsyncIterator, Iterator, MutableMapping +from collections.abc import AsyncGenerator, AsyncIterator, Iterator, MutableMapping from typing import Any, Literal import httpx2 @@ -447,3 +447,58 @@ async def test_connect_times_out_waiting_for_ready(mode: Mode) -> None: 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 From af69831c63de4bc8f90e4a6364083fdc9f73b136 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:09:18 +0100 Subject: [PATCH 11/13] docs(policies): document role='assistant' override for tool calls Document that tool/arguments defaults to the user side (so role_list=[] or ['user'] judges it as is) and recommend passing role='assistant' on Event.tool_call(...) so an assistant-only Policy judges an agent's own tool calls. Update CHANGELOG.md and extend test_tool_arguments_targeting to verify the role='assistant' override live. --- CHANGELOG.md | 11 +++++++++-- docs/agents-and-tools.md | 6 ++++-- docs/managing-policies.md | 16 ++++++++++------ docs/metadata-and-conditions.md | 2 +- tests/live/test_policies.py | 10 +++++++++- 5 files changed, 33 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c4b495c..117148f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,9 @@ All notable changes to this project are documented here. The format follows `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 `role_list=["assistant"]` excludes tool-call arguments today; use - `role_list=[]` (or avoid restricting to `["assistant"]`) to judge `tool/arguments`. + `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). @@ -24,6 +25,12 @@ All notable changes to this project are documented here. The format follows - `policies.create()` and `metrics.create()` now require a non-empty `rules` sequence (omitting `rules` raises `TypeError`; passing `[]` raises `ValueError`). +### 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). + ## [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/docs/agents-and-tools.md b/docs/agents-and-tools.md index 1993128..3f7f84c 100644 --- a/docs/agents-and-tools.md +++ b/docs/agents-and-tools.md @@ -19,8 +19,10 @@ 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 (and does not restrict `role_list` to `["assistant"]` for -`tool/arguments`). See [Judge tool calls](managing-policies.md#judge-tool-calls). +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 diff --git a/docs/managing-policies.md b/docs/managing-policies.md index 54c34ab..87b3116 100644 --- a/docs/managing-policies.md +++ b/docs/managing-policies.md @@ -38,13 +38,13 @@ At least one rule must flag. Two fields decide which Events a Policy evaluates: ## Judge tool calls -Tool Events are skipped unless you select them explicitly. Today, the API classifies tool-call arguments on the user -side, so `role_list=["assistant"]` checks assistant messages and `tool/output` but skips `tool/arguments`. To judge -tool-call arguments alongside assistant replies and tool outputs, avoid restricting `role_list` to `["assistant"]` -(use `role_list=[]`): +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 EventSelector, Rule, WhiteCircle +from whitecircle import Event, EventSelector, Rule, WhiteCircle client = WhiteCircle() tool_policy = client.policies.create( @@ -56,9 +56,13 @@ tool_policy = client.policies.create( EventSelector(type="tool", field="arguments"), EventSelector(type="tool", field="output"), ], - role_list=[], + role_list=["assistant"], mode="shadow", ) +result = client.events.check( + Event.tool_call("run_sql", {"query": "SELECT * FROM orders"}, role="assistant", call_id="c1"), + include_shadow=True, +) ``` ## Shadow mode to production diff --git a/docs/metadata-and-conditions.md b/docs/metadata-and-conditions.md index 4bfce91..d48e43b 100644 --- a/docs/metadata-and-conditions.md +++ b/docs/metadata-and-conditions.md @@ -93,7 +93,7 @@ A stream does not report "not checked": with no matching Condition every batch p 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 `role_list` is empty or includes the Event's role - (`["assistant"]` skips user messages and `tool/arguments`). + (`["assistant"]` skips user messages and `tool/arguments` sent without `role="assistant"`). ## Inline Policies diff --git a/tests/live/test_policies.py b/tests/live/test_policies.py index 2040a06..f2a4dde 100644 --- a/tests/live/test_policies.py +++ b/tests/live/test_policies.py @@ -96,8 +96,16 @@ def test_tool_arguments_targeting( assert prod_result.policies is not None assert prod_result.policies[made.id].shadow is False - # role_list=["assistant"] excludes tool/arguments today. + # 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 From 7cce99a24dd5b9fe986b5b815d1eaf6e06899f9a Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:15:17 +0100 Subject: [PATCH 12/13] docs(changelog): list remaining PR 5 changes under Unreleased --- CHANGELOG.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 117148f..71074ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,12 +24,24 @@ All notable changes to this project are documented here. The format follows `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`. + +### 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 From 54f0b29ca3ca8c09c4bac4ea723e501ce644bfe4 Mon Sep 17 00:00:00 2001 From: DeevsDeevs Date: Wed, 2 Dec 2026 13:16:09 +0100 Subject: [PATCH 13/13] fix(policies): guard field and kind types in Policy._parse_selectors fallback Only fall back to EventSelector.model_construct when field and kind are None or str, so malformed items with non-string field or kind raise ValidationError. Add parametrized tests covering malformed selector items. --- src/whitecircle/types/policies.py | 6 +++++- tests/test_policies.py | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/whitecircle/types/policies.py b/src/whitecircle/types/policies.py index cd3ae70..47a9b1b 100644 --- a/src/whitecircle/types/policies.py +++ b/src/whitecircle/types/policies.py @@ -88,7 +88,11 @@ def _parse_selectors(cls, value: object, handler: pydantic.ValidatorFunctionWrap try: out.append(EventSelector.model_validate(raw)) except pydantic.ValidationError: - if isinstance(raw.get("type"), str): + 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 diff --git a/tests/test_policies.py b/tests/test_policies.py index 33c03ca..4ec3662 100644 --- a/tests/test_policies.py +++ b/tests/test_policies.py @@ -199,3 +199,19 @@ def test_policy_parses_unknown_future_selector_types_and_fields() -> None: ("message", "future_field"), ] assert policy.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]})