Skip to content

Commit 2018bfc

Browse files
authored
fix: 0.8.2 — coverage wire-shape (metadata nesting) + model fallback (#40)
* release: 0.7.6 — FastAPI integration + user-facing message catalog Additive patch on top of the 0.7.0 thin-client refactor. No breaking changes. Added ----- * nullrun.integrations.fastapi — one-line FastAPI integration that turns every NullRunDecision / NullRunInfrastructureError thrown by @nullrun.protect endpoints into a clean JSON response with the right HTTP status code. No per-endpoint except blocks required. Response shape: {"error_code": "NR-B004", "user_message": "You've reached the usage limit...", "category": "decision"} HTTP status mapping: * NR-B004 (budget), NR-L001 (loop), NR-R001 (rate) -> 429 with optional Retry-After * NR-T001 (tool blocked), NR-X001 (generic block) -> 403 * NR-W003 (paused) -> 503 with Retry-After * NR-W002 (killed) -> 503; WorkflowKilledInterrupt is a BaseException subclass so Starlette's add_exception_handler refuses it — handled via ASGI middleware instead (hybrid pattern, documented in module docstring). * NullRunInfrastructureError subclasses -> 503 (our side, not user's). * nullrun.messages — default user-facing message catalog. Every NR-* error code has an English default message owned by NULLRUN, not customer code. Customer Support Bots hitting a budget cap show the same wording across every NullRun-backed application. * format_user_message(exc) — render exception as user-facing string * set_user_message(code, text) — per-process override for branded variants * get_user_message(code) — raw lookup * reset_overrides() — clear all overrides (for tests) Changed ------- * Transport._send_batch canonical JSON serialization — route the /track/batch body through _signed_request_body for consistent compact-separator serialization. HMAC itself is unaffected, but consistent serialization removes a special-case from the wire-format contract tests. * Transport._send_batch actions response handling — backend renamed BatchTrackResponse.actions_taken (debug names) -> BatchTrackResponse.actions (ActionTaken structs). Read both for forward-compat; per-element try/except so one malformed entry doesn't abort the whole loop. * pyproject.toml metadata — long-form description with search keywords, Maintainer: populated via maintainers=[...], expanded classifiers (Linux / Windows / macOS, Python 3.13, CPython, Security / AI / WWW/HTTP topics), project URL expander. Tests ----- * tests/test_messages.py (new, 282 lines) — catalog completeness (every NR-* code has a default message), override / reset behavior, render path. * tests/test_integrations_fastapi.py (new, 289 lines) — HTTP status mapping per error code, response shape, ASGI middleware path for WorkflowKilledInterrupt, hybrid composition. * tests/test_decision_split.py (new, 199 lines) — pins the decision / infrastructure error split. * Updates to tests/test_runtime.py, tests/test_extractors.py reflecting transport canonical-JSON + actions-renamed changes. Release plumbing ---------------- * pyproject.toml: version bumped 0.7.0 -> 0.7.6 * src/nullrun/__version__.py: __version__ = "0.7.6" * CHANGELOG.md: full 0.7.6 entry covering additions, transport changes, metadata improvements Tests pass locally (per session log) — pytest on Windows / Python 3.14.2 is green. * ci: fix PR #35 — fastapi dep + Transport._send_batch typo + coverage padding PR #35 (release/0.7.6) failed all four CI jobs (test 3.10/3.11/3.12, coverage, codecov/patch) on the same root cause + one latent bug masked by it. This commit lands the fixes plus the last-mile tests that bring coverage above the 82% threshold. CI failure root --------------- * tests/test_integrations_fastapi.py does from fastapi import ... at module top-level. CI installs only pip install -e '.[dev]', and fastapi was declared as an *optional* [fastapi] extra, NOT in [dev]. Pytest collection aborted with ModuleNotFoundError: No module named 'fastapi' → all 4 jobs red. * Fix: add fastapi>=0.100,<1.0 to [dev]. Same precedent as langchain-core (already in [dev] for the same import-time contract: nullrun.instrumentation.langgraph is eager-imported from nullrun.decorators at collection time, so the test extras must cover the import chain). Latent bug surfaced by the first fix ------------------------------------ The same PR refactored Transport._send_batch_with_retry_info to route the /track/batch body through _signed_request_body for canonical-JSON serialization (matching /gate and /execute). The two sibling call sites use the module-level helper _signed_request_body (no self.); this one used self._signed_request_body by typo. Result: AttributeError on every batch flush, breaking 15 existing tests across test_transport.py / test_track_batch_retry.py / test_integration_contract.py / test_signal_safety.py. As long as the fastapi collection error aborted pytest, this was hidden. Fixed to _signed_request_body(...) with a docstring noting why it is module-level and what the bug looked like. Coverage padding (codecov/patch was failing on this too) -------------------------------------------------------- Total coverage on the failing CI run was 81.98% — 0.02pp under the fail-under=82 gate. After the two fixes above it would have recovered to ~82.0% on the dot, so I added minimal tests for the cheapest-to-cover gaps: * tests/test_breaker_main.py (new) — covers the 5 statements in nullrun.breaker.__main__.main() (0% → 100%). The module exists so python -m nullrun.breaker exits cleanly instead of failing with No module named nullrun.breaker.__main__; the previous fix-mechanism was return 0 after a print, but no test was exercising it. * tests/test_status.py — extends TestSummary with seven scenarios covering each conditional branch of NullRunStatus.summary() (organization_id, workflow_id, workflow_state != Normal, backend_reachable=False, ws_connected=False, recent_errors). status.py jumps 84.52% → 98.81%. * tests/test_integrations_fastapi.py — four tests on _build_headers covering non-numeric, zero, negative, and resume_after (the WorkflowPausedException code path). integrations/fastapi.py jumps 90.22% → 94.57%. After all three: TOTAL 81.98% → 82.46%, comfortably above the gate. Verification ------------ * Local pytest: 997 passed, 13 skipped, 0 failed (Windows / Python 3.14.2, 8m47s — same env the original commit was validated in). * python -m coverage report — 82.46%, no fail-under complaint. * test: cover Phase 4.1 instrumentation — finish_reason + cache/reasoning/tools Patch coverage on PR #35 was 62.38% against a 65% threshold (codecov target 70% / threshold 5pp). The two biggest delta-holders against master were auto.py (+286) and langgraph.py (+221), both dominated by Phase 4.1 additions: * auto._normalize_finish_reason + _FINISH_REASON_MAP * auto._openai_extractor second-tier fields (cache_read_tokens, cache_write_tokens, reasoning_tokens, finish_reason, tool_names) * auto._anthropic_extractor cache_read / cache_write * langgraph._safe_get_gen_message * langgraph._get_finish_reason (5-source fallback chain) * langgraph.extract_usage_from_response second-tier fields These are pure / near-pure functions with no network or vendor SDK calls. Coverage padding is cheap — pin the canonical wire shapes once and the backend ingest contract gets a free live spec. Local numbers: * auto.py 63.44% -> 64.01% (file-level, +57 statements) * langgraph.py 78.50% -> 86.01% (file-level, +32 statements) * TOTAL 82.46% -> 83.13% (already above 82% gate) 41 tests, all green. Existing test_extractors.py and test_langgraph_callback.py left untouched — these tests deliberately target the Phase 4.1 fields (cache_read / cache_write / reasoning / finish_reason / tool_names) that the older tests didn't pin. * fix(gate): forward real model + tools to /gate pre-flight (T4) Pre-0.7.7 every SDK /gate call for any workflow with a budget was hard-blocked because the runtime hard-coded the literal string "budget-precheck" as the model. The backend's PolicyEvaluationGraph treated any synthetic cost_limit rule with score > 0.8 as Block, so the pricing lookup never landed on a real model and the rule fired with the wrong score. This commit: * Adds nullrun.set_call_context(model=..., tools=[...]) plus get_call_model / get_call_tools helpers (and the underlying _call_model_var / _call_tools_var contextvars in nullrun.context). * Wires the call context into check_workflow_budget: the /gate payload now carries the real model name (or None when unset) and the user-supplied tool list. tools=[] vs missing-None are distinguished on the wire per gate/internal.rs::check_tool_block. * Transport.check forwards the tools key when set (it was silently dropped pre-fix). * tests/conftest.py reset_runtime clears the new contextvars so a test's set_call_context(...) doesn't leak into the next test's wire payload. * New tests/test_gate_real_path.py pins down the regression: default request allows a clean workflow, real block still honored, no policy-N residue on the wire, set_call_context flows into the body, no-context means no tools key, and the helpers are reachable from nullrun.*. Bumps version to 0.7.7. No breaking changes - new helpers default to None / empty so existing call sites keep working. * release: 0.7.8 — fail-loud on deprecated surface Two silent fail-OPEN footguns are converted to explicit DeprecationWarning / RuntimeError so misconfigurations show up at SDK init instead of being diagnosed from a missing proto trace. Deprecated: * NullRunRuntime.start_recording() and .stop_recording() now emit DeprecationWarning. They have been silent no-op stubs since Sprint 2.1 (0.4.0) — decision history is now on the backend dashboard at /control-center/decision-history. Both methods will be removed in 0.9.0. * NULLRUN_USE_GRPC=1 now raises RuntimeError at SDK init instead of silently falling back to HTTP with an info log. gRPC is on the roadmap but not implemented; unset the env var to use HTTP. Hardening (init path): * Transport._post_auth_with_retry (new) — retry transient 503 / 504 + network blips during /api/v1/auth/verify. Backend emits 503 + Retry-After: 5 on transient DB errors (handlers.rs:11346-51). Pre-fix the first 503 surfaced as NR-A001 to the user as if the API key were bad. Three attempts, exponential backoff (0.5s → 1s → 2s), honors Retry-After when present. Auth-key failures (401) are NOT retried — a wrong key on attempt 1 is a wrong key on attempt 3. Transport refactor: * Transport._add_hmac_headers (new) — pulls the HMAC header construction out of _signed_request_body so /track/batch, /gate, /check, /execute all share one source of truth for Content-Type / X-Signature / X-Signature-Timestamp / X-API-Key / Authorization headers. HMAC formula unchanged. * generate_hmac_signature + verify_hmac_signature accept str | bytes for body. Legacy str callers (and the FastAPI integration) keep working without an explicit .encode(). * actions_taken → actions on /track/batch response. Backend renamed BatchTrackResponse.actions_taken (debug names) → actions (ActionTaken structs with human-readable strings moved to messages). Read both keys for forward-compat. Test updates: * tests/test_framework_patches — alignment with retry + actions rename. * tests/test_high_reliability_fixes — re-pinned for _post_auth_with_retry. * tests/test_hmac_signing — expanded for str/bytes body + new _add_hmac_headers helper. * tests/test_integration_contract — backend actions rename covered. * tests/test_transport — retry semantics. Bumps version to 0.7.8. No breaking changes for callers who don't touch start_recording / stop_recording / NULLRUN_USE_GRPC. * test(grpc): align test_grpc_removed with 0.7.8 NULLRUN_USE_GRPC contract The 0.7.8 commit changed NULLRUN_USE_GRPC=1 from silent no-op + INFO log to an explicit RuntimeError, but the regression test in tests/test_grpc_removed.py still pinned the old behavior (``test_nullrun_use_grpc_does_not_crash_init`` asserting make_runtime() succeeded and an INFO line was logged). CI on PR #38 failed on this test: FAILED tests/test_grpc_removed.py::TestGrpcRemoved ::test_nullrun_use_grpc_does_not_crash_init E RuntimeError: NULLRUN_USE_GRPC is set but the gRPC transport is not yet implemented. ... This commit updates the test to pin the new 0.7.8 contract: the env var must raise RuntimeError, and the error message must name the offending variable + point at the docs page. The test is renamed from ``test_nullrun_use_grpc_does_not_crash_init`` to ``test_nullrun_use_grpc_raises_runtime_error`` so the test name itself documents the new contract. The module docstring (point 2 in the contract list) is updated to say "raises RuntimeError" instead of "does NOT crash init — it logs an INFO line and silently falls back to HTTP". The 0.3.1 -> 0.7.8 evolution is documented in the test docstring as a contract-evolution footnote for future maintainers. Imports: removed unused `import logging` and `caplog` parameter (no longer asserting on log records); added `import pytest` for `pytest.raises`. No production-code change. No version bump. The fix is self-contained to tests/test_grpc_removed.py. * style(runtime): sort stdlib imports (ruff I001) The 0.7.8 commit (fail-loud on deprecated surface) added ``import warnings`` mid-block in src/nullrun/runtime.py:34, breaking alphabetical order: asyncio logging os warnings <-- out of order threading time uuid Ruff on PR #38 CI (Run ruff check src/) flagged it as I001. Reorder to alphabetical: asyncio logging os threading time uuid warnings Verified: * ruff check src/ -> All checks passed! * pytest tests/test_grpc_removed.py tests/test_runtime_branches.py -> 47 passed No behavior change, no production logic touched. Pure lint fix. * release: 0.8.0 — SDK wire-format audit (model/provider extraction) Closes a class of silent-fail-OPEN path that was sending model=None or model="unknown" on /track for many LLM-vendor paths. Every such event cost the backend a model_pricing lookup that returned no row, fell through to DEFAULT_RATE (~$30/M), and emitted a fallback warning the operator couldn't reproduce because the offending observation was buried in another package's telemetry. No public-API break. No behavior change for callers whose instrumentation already populates model correctly. Pure wire-payload hygiene. runtime.py — track(): * Strips None values from the wire payload (pre-0.8.0 forwarded every key except _WIRE_STRIP_FIELDS, including keys whose value was None). Putting {"model": null} on the wire triggered backend unwrap_or("default") and a fallback warning. Dropping None keeps the diagnostic signal loud (the new WARN below fires on missing-key, which is what we want operators to see) instead of silent (the JSON-null case). * Adds logger.warning("track(): llm_call event missing 'model' field — backend will fall back to DEFAULT_RATE. event=...") — the single signal an operator needs to reproduce "which observation produced an llm_call without model set". Activated only for llm_call; other event types are silent. instrumentation/langgraph.py — NullRunCallback.on_llm_end: * New _extract_model_from_response + _extract_provider_from_response helpers (mirror _get_finish_reason's best-effort pattern). Fallback chain: invocation_params → response metadata → AIMessage response_metadata → llm_output → direct attribute. "unknown" is now a true last resort, not the common case. instrumentation/llama_index.py: * extract_from_event fallback chain: event.response.model → event.response.raw.model → usage['model']. Mock providers and adapter-style ChatResponse now ship a real model id. instrumentation/autogen.py: * on_messages fallback chain: self.model → result.model. OpenAI's response carries the actual model id (may differ from request if the server resolved an alias). instrumentation/auto.py — _emit_from_span (openai-agents): * span model fallback chain: span['model'] → usage['model'] → span['response_metadata']['model_name']. Some custom tracer configs leave span['model'] empty; the other two sources usually have it. Sets model on the event only when we have a real value (empty/None is dropped — relies on the new None-strip in track() to keep the operator warning loud). Bumps version to 0.8.0. No breaking changes for callers who don't touch the wire path directly. * fix: 0.8.2 — coverage wire-shape (metadata nesting) + model fallback Two coordinated fixes from the 0.8.0 wire-format audit: 1. Coverage counters under metadata - src/nullrun/runtime.py: track_coverage() emits seen/tracked/ streaming_skipped dicts under event.metadata instead of the top level. SdkTrackRequest uses explicit fields with no #[serde(flatten)] catchall, so top-level keys were silently dropped by serde and the dashboard's last_coverage_pct was permanently null. - tests/test_coverage_report.py: pin the wire shape (regression test). 2. Model name extraction fallback (Issue 2) - src/nullrun/instrumentation/auto.py: when the response body extractor returns None for model (OpenAI Responses API, Anthropic streaming edge cases), fall back to the model string the user embedded in the request body via ChatOpenAI(model='gpt-4.1-mini'). Without this, every such call was zero-billed (backend unwrap_or('default') + DEFAULT_RATE ≈ $0/call). - tests/test_model_fallback.py: unit-test the helper. 3. Backend batch response schema contract tests - tests/test_batch_response_parsing.py: pin the post-2026-06-27 BatchTrackResponse shape (actions: Vec<ActionTaken>, messages: Vec<String>) and document that the legacy actions_taken: Vec<String> field is intentionally dropped in 0.8.0.
1 parent b64ebe4 commit 2018bfc

5 files changed

Lines changed: 478 additions & 2 deletions

File tree

src/nullrun/instrumentation/auto.py

Lines changed: 55 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,40 @@ def _bedrock_extractor(body: bytes, status: int) -> ExtractedUsage | None:
476476
}
477477

478478

479+
def _extract_model_from_request_body(request: httpx.Request) -> str | None:
480+
"""2026-06-28 (Issue 2 fix): fall back to the ``model`` field embedded
481+
in the LLM request body when the response body extractor returned
482+
``None`` for ``model``.
483+
484+
The user typically passes ``ChatOpenAI(model="gpt-4.1-mini")`` and
485+
that string appears in the request body's ``model`` field — even if
486+
the response omits it (streaming edge cases, Responses API,
487+
middleware that strips model from responses). Returning the
488+
request-side model keeps the SDK's cost event attributable to the
489+
real catalog entry (``gpt-4.1-mini`` substring → 400 microcents /
490+
1M input in ``MODEL_RATES``) instead of falling through to
491+
``DEFAULT_RATE`` ($0 per call).
492+
493+
Returns ``None`` if the body is not JSON, has no ``model`` field,
494+
or has an empty ``model``. Callers must treat the result as
495+
optional and still surface the SDK's "missing model" warning when
496+
both response and request lookups fail.
497+
"""
498+
try:
499+
body = request.content
500+
if not body:
501+
return None
502+
payload = json.loads(body)
503+
except (json.JSONDecodeError, ValueError):
504+
return None
505+
if not isinstance(payload, dict):
506+
return None
507+
val = payload.get("model")
508+
if isinstance(val, str) and val:
509+
return val
510+
return None
511+
512+
479513
def _match_extractor(host: str) -> Callable[[bytes, int], ExtractedUsage | None] | None:
480514
"""Return the extractor for `host`, or None if the host is not a known
481515
LLM endpoint. We match exact host first, then any subdomain (e.g.
@@ -683,6 +717,26 @@ def _emit(
683717
# ``coverage_seen`` view in the dashboard would be empty for
684718
# the majority of customers.
685719
_safe_bump_coverage(self._runtime, "_coverage_seen", host)
720+
721+
# 2026-06-28 (Issue 2 fix): if the extractor returned ``None``
722+
# for ``model`` (response body lacked the field — observed for
723+
# some OpenAI Responses-API and Anthropic streaming edge cases),
724+
# fall back to the model name embedded in the request body. The
725+
# backend cost pipeline logs WARN and falls back to DEFAULT_RATE
726+
# (≈$0 per call) whenever ``model`` is missing — see
727+
# ``backend/src/cost/pipeline.rs:164`` ``unwrap_or("default")``
728+
# and ``backend/src/cost/constants.rs::rate_for``. Without
729+
# this fallback, every gpt-4.1-mini / claude-haiku-4 call where
730+
# the response body omits ``model`` was being silently
731+
# zero-billed. Request body is the next authoritative source:
732+
# SDK users pass ``model="gpt-4.1-mini"`` in the ChatOpenAI
733+
# constructor.
734+
model_from_response = usage.get("model")
735+
model_for_event = (
736+
model_from_response
737+
or _extract_model_from_request_body(request)
738+
)
739+
686740
try:
687741
# Phase 4.1: lift cache / reasoning / finish / tool names
688742
# out of raw_usage onto the event itself. The backend's
@@ -695,7 +749,7 @@ def _emit(
695749
"type": "llm_call",
696750
"provider": _provider_label(host),
697751
"host": host,
698-
"model": usage.get("model"),
752+
"model": model_for_event,
699753
"tokens": usage.get("total_tokens", 0),
700754
"input_tokens": usage.get("prompt_tokens", 0),
701755
"output_tokens": usage.get("completion_tokens", 0),

src/nullrun/runtime.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1556,6 +1556,19 @@ def track_coverage(self) -> dict[str, Any] | None:
15561556
15571557
Background emission is driven by ``start_coverage_reporter``;
15581558
most callers don't invoke this method directly.
1559+
1560+
Wire shape (2026-06-28 fix):
1561+
The per-host counter dicts live under ``metadata`` so the
1562+
backend's batch handler (backend/src/proxy/handlers.rs:5909
1563+
-5923) reads them from ``sdk_event.metadata``. The handler
1564+
was wired to that location when the SDK moved from the
1565+
deprecated ``POST /api/v1/coverage`` endpoint onto the
1566+
shared ``/api/v1/track/batch`` pipeline — placing the
1567+
counters at the event top level silently dropped them (the
1568+
``SdkTrackRequest`` struct uses explicit fields, no
1569+
``#[serde(flatten)]`` catchall, so unknown top-level keys
1570+
are discarded by serde). Nesting under ``metadata`` matches
1571+
what the handler reads.
15591572
"""
15601573
stats = self.coverage_report()
15611574
seen_total = sum(stats["seen"].values())
@@ -1564,7 +1577,7 @@ def track_coverage(self) -> dict[str, Any] | None:
15641577
return None
15651578
return self.track_event(
15661579
"coverage_report",
1567-
**{
1580+
metadata={
15681581
"seen": stats["seen"],
15691582
"tracked": stats["tracked"],
15701583
"streaming_skipped": stats["streaming_skipped"],
Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
"""Contract tests for backend BatchTrackResponse parsing.
2+
3+
Audit 2026-06-28: backend renamed `BatchTrackResponse.actions_taken`
4+
(Vec<String> of debug names) → `BatchTrackResponse.actions`
5+
(Vec<ActionTaken> structured) + `messages` (Vec<String> display-only).
6+
Single /track still uses `TrackResponse.actions_taken` (Vec<ActionTaken>)
7+
— separate endpoint, separate schema.
8+
9+
These tests pin both schemas so a future backend rename can't silently
10+
break the SDK. Forward-compat path (legacy `actions_taken` dropped in
11+
SDK 0.8.0 per CHANGELOG §0.8.0) is documented but no longer parsed.
12+
"""
13+
14+
from __future__ import annotations
15+
16+
import pytest
17+
import respx
18+
from httpx import Response
19+
20+
from nullrun.runtime import NullRunRuntime
21+
import nullrun.decorators as _dec
22+
import nullrun.actions as _act
23+
24+
25+
BASE_URL = "https://api.test.nullrun.io"
26+
27+
28+
@pytest.fixture
29+
def mock_api():
30+
"""Activate the global respx mock for the duration of the test and
31+
pre-register /api/v1/auth/verify (the auth handshake that
32+
NullRunRuntime.__init__ triggers). Each test pins its own
33+
/api/v1/track/batch response via ``respx.post(...).mock(...)``.
34+
35+
Why ``with respx.mock:`` and not ``with respx.mock(...) as router:``:
36+
parenthesised ``respx.mock(...)`` creates a *local* MockRouter, but
37+
``respx.post(...)`` is a module-level helper that always writes to
38+
the *global* router. The two don't share state, so per-test
39+
``respx.post(...)`` mocks wouldn't be visible to the local router.
40+
Bare ``respx.mock:`` re-uses the global router so module-level
41+
``respx.post(...)`` calls land on the active context — same pattern
42+
used by ``tests/conftest.py``.
43+
"""
44+
with respx.mock:
45+
respx.post(f"{BASE_URL}/api/v1/auth/verify").mock(
46+
return_value=Response(
47+
200,
48+
json={
49+
"organization_id": "ws-test",
50+
"workflow_id": "00000000-0000-0000-0000-000000000001",
51+
"plan": "pro",
52+
"features": [],
53+
"limits": {"max_cost_cents": 10000},
54+
},
55+
)
56+
)
57+
yield
58+
59+
60+
def _runtime(api_key: str = "test-key"):
61+
"""Build a runtime with the test API key and base URL.
62+
63+
Returns the constructed instance directly. ``NullRunRuntime.__init__``
64+
does NOT assign ``_instance`` — only ``get_instance()`` does that —
65+
so reading ``NullRunRuntime._instance`` after a direct constructor
66+
call returns ``None``.
67+
"""
68+
NullRunRuntime._instance = None
69+
_dec._runtime = None
70+
_act._action_handler = None
71+
rt = NullRunRuntime(
72+
api_key=api_key,
73+
api_url=BASE_URL,
74+
debug=True,
75+
polling=False,
76+
)
77+
# Keep _instance in sync with conftest.py's `make_runtime` so the
78+
# @protect decorator's lazy resolver finds this runtime too.
79+
NullRunRuntime._instance = rt
80+
_dec._runtime = rt
81+
return rt
82+
83+
84+
# -----------------------------------------------------------------------------
85+
# New schema (post 2026-06-27 backend rename)
86+
# -----------------------------------------------------------------------------
87+
88+
89+
def test_new_schema_actions_and_messages_processed(mock_api):
90+
"""Backend 2026-06-27+ sends `actions` (structured) + `messages` (strings)."""
91+
rt = _runtime()
92+
route = respx.post(f"{BASE_URL}/api/v1/track/batch").mock(
93+
return_value=Response(
94+
200,
95+
json={
96+
"processed": 3,
97+
"actions": [
98+
{"type": "rate_limit", "reason": "exceeded"},
99+
{"type": "budget_cap", "reason": "100 cents over"},
100+
],
101+
"messages": [
102+
"1 event rejected: budget cap exceeded",
103+
],
104+
"snapshots": [],
105+
"accepted_event_ids": ["e1", "e2"],
106+
"rejected_count": 0,
107+
"rejection_details": [],
108+
},
109+
)
110+
)
111+
112+
# Trigger a batch send (track_llm triggers batch flush internally)
113+
# NOTE: the fixture already wraps the test in `respx.mock(...)`, so
114+
# we must NOT add another `with mock_api:` here — re-entering the
115+
# router clears the auth/verify mock registered by the fixture
116+
# (respx's `__exit__` calls `rollback()` + `reset()`).
117+
rt._transport._send_batch_with_retry_info(
118+
batch=[
119+
{
120+
"event_type": "llm_call",
121+
"workflow_id": "wf-1",
122+
"model": "gpt-4",
123+
"tokens": 100,
124+
"cost_cents": 1,
125+
}
126+
]
127+
)
128+
129+
assert route.called
130+
131+
132+
def test_new_schema_messages_only_no_actions(mock_api):
133+
"""Display-only messages with empty actions should not raise."""
134+
rt = _runtime()
135+
respx.post(f"{BASE_URL}/api/v1/track/batch").mock(
136+
return_value=Response(
137+
200,
138+
json={
139+
"processed": 1,
140+
"actions": [],
141+
"messages": ["event accepted with warnings"],
142+
"snapshots": [],
143+
"accepted_event_ids": ["e1"],
144+
"rejected_count": 0,
145+
"rejection_details": [],
146+
},
147+
)
148+
)
149+
150+
rt._transport._send_batch_with_retry_info(
151+
batch=[
152+
{
153+
"event_type": "llm_call",
154+
"workflow_id": "wf-1",
155+
"model": "gpt-4",
156+
"tokens": 100,
157+
"cost_cents": 1,
158+
}
159+
]
160+
)
161+
# No exception = pass
162+
163+
164+
def test_new_schema_empty_actions_no_messages(mock_api):
165+
"""All-accepted batch with empty actions/messages must not raise."""
166+
rt = _runtime()
167+
respx.post(f"{BASE_URL}/api/v1/track/batch").mock(
168+
return_value=Response(
169+
200,
170+
json={
171+
"processed": 1,
172+
"actions": [],
173+
"messages": [],
174+
"snapshots": [],
175+
"accepted_event_ids": ["e1"],
176+
"rejected_count": 0,
177+
"rejection_details": [],
178+
},
179+
)
180+
)
181+
182+
rt._transport._send_batch_with_retry_info(
183+
batch=[
184+
{
185+
"event_type": "llm_call",
186+
"workflow_id": "wf-1",
187+
"model": "gpt-4",
188+
"tokens": 100,
189+
"cost_cents": 1,
190+
}
191+
]
192+
)
193+
194+
195+
# -----------------------------------------------------------------------------
196+
# Backward-compat: legacy `actions_taken` (Vec<String>) is intentionally dropped
197+
# -----------------------------------------------------------------------------
198+
199+
200+
def test_legacy_actions_taken_string_field_does_not_crash(mock_api):
201+
"""Old backend (pre-2026-06-27) sent `actions_taken: Vec<String>` of
202+
debug names. SDK 0.8.0 reads `actions` only. A legacy response must
203+
not crash — missing `actions` is treated as empty."""
204+
rt = _runtime()
205+
respx.post(f"{BASE_URL}/api/v1/track/batch").mock(
206+
return_value=Response(
207+
200,
208+
json={
209+
"processed": 1,
210+
# Legacy field — SDK should ignore it.
211+
"actions_taken": ["rate_limit_exceeded"],
212+
# New fields absent → empty defaults.
213+
"snapshots": [],
214+
"accepted_event_ids": ["e1"],
215+
"rejected_count": 0,
216+
"rejection_details": [],
217+
},
218+
)
219+
)
220+
221+
# Should NOT raise. The legacy `actions_taken` field is ignored
222+
# (per transport.py:1176-1177 comment, "legacy actions_taken
223+
# fallback was removed"). `actions = data.get("actions") or []`
224+
# returns [].
225+
rt._transport._send_batch_with_retry_info(
226+
batch=[
227+
{
228+
"event_type": "llm_call",
229+
"workflow_id": "wf-1",
230+
"model": "gpt-4",
231+
"tokens": 100,
232+
"cost_cents": 1,
233+
}
234+
]
235+
)

0 commit comments

Comments
 (0)