Skip to content

The agent that grows with you

test: close the review gaps on the merged relay, classifier and prompt-cache tests

kshitijk4poor716bab6967be
diff --git a/tests/agent/test_error_classifier_observed.py b/tests/agent/test_error_classifier_observed.py
index 096a06e6dd5..6a81f9dbd8e 100644
--- a/tests/agent/test_error_classifier_observed.py
+++ b/tests/agent/test_error_classifier_observed.py
@@ -5,11 +5,12 @@ and account data), raised as the exception class the OpenAI SDK / httpx raises f
classifier change is checked against what providers really send rather than hand-written
strings. Add a row whenever a new production body shows up in a bug report or trace.
-The last two tests are bodies main still mishandles; each is a run-time xfail keyed on the current
-wrong outcome, so it turns into a passing regression test the moment its fix lands:
+OpenRouter's "can only afford N tokens" 402 (#49769) stays ``billing`` here; the main loop's
+recovery chain retries it once with the lowered cap (see that test's docstring).
+
+The last test is a body main still mishandles, as a run-time xfail keyed on the current wrong
+outcome, so it turns into a passing regression test the moment its fix lands:
-* #49769 — OpenRouter's "can only afford N tokens" 402 is recoverable by lowering max_tokens,
- but the main loop classifies it as terminal billing and abandons the provider.
* #85005 — "<model> is not a multimodal model" (vLLM/text-only endpoints) is not recognised as
an image rejection, so the image is never stripped and every retry fails identically.
"""
@@ -78,13 +79,16 @@ def test_observed_body_routes_to_its_recovery(provider, error, reason, retryable
assert (result.reason, result.retryable, result.should_fallback) == (reason, retryable, fallback)
-def test_affordable_402_is_retried_on_the_same_provider():
- result = classify_api_error(_status(openai.APIStatusError, 402, AFFORD_402), provider="openrouter",
- model="anthropic/claude-opus-5.5")
- outcome = f"reason={result.reason.name} retryable={result.retryable}"
- with known_failure(r"reason=billing retryable=False", "#49769: affordable-tokens 402 treated as terminal billing"):
- assert result.retryable and result.reason != FailoverReason.billing, (
- f"402 'can only afford N' must be retried on this provider, not abandoned as billing: {outcome}")
+def test_affordable_402_classifies_as_billing_with_a_parseable_budget():
+ """#49769 is recovered in the main loop, not by the classifier: the 402 stays ``billing`` and the
+ recovery chain retries once with the cap lowered to the budget it names
+ (``tests/agent/test_affordable_402_main_loop.py`` drives that retry end to end)."""
+ from agent.auxiliary_client import _affordable_max_tokens_from_error
+
+ error = _status(openai.APIStatusError, 402, AFFORD_402)
+ result = classify_api_error(error, provider="openrouter", model="anthropic/claude-opus-5.5")
+ assert result.reason == FailoverReason.billing
+ assert _affordable_max_tokens_from_error(error) == 81664 - 64
def test_not_a_multimodal_model_is_an_image_rejection():
diff --git a/tests/agent/test_prompt_cache_prefix_contract.py b/tests/agent/test_prompt_cache_prefix_contract.py
index 0edb11dcd5e..4ec5abd99e6 100644
--- a/tests/agent/test_prompt_cache_prefix_contract.py
+++ b/tests/agent/test_prompt_cache_prefix_contract.py
@@ -8,9 +8,8 @@ the same content as the plain string it decorates (production telemetry: plain s
full previous prefix on 99.5% of consecutive calls). Splitting one string into several parts is a
content change.
-The cells mirror what real sessions do on the two cache layouts Hermes emits (OpenAI-wire envelope
-markers: OpenRouter / Nous Portal / custom relays; native Anthropic Messages content-block markers)
-and were chosen from per-call cache telemetry (``agent.log`` ``cache=R/T write=W``): consecutive
+The cells run the OpenAI-wire envelope layout (OpenRouter / Nous Portal / custom relays) and were
+chosen from per-call cache telemetry (``agent.log`` ``cache=R/T write=W``): consecutive
calls in one session reuse the whole previous prefix except where these cells say otherwise.
Regression pinned here (#133715): a skill turn's first user message must go out as the same
@@ -47,8 +46,9 @@ def _cache_content(value: Any) -> Any:
def _prefix_breaks(requests: list[dict[str, Any]]) -> list[tuple[int, str]]:
- """``prefix_breaks`` over what the cache keys on, after asserting markers reached the wire."""
- assert any("cache_control" in canon(r) for r in requests), "caching route sent no cache_control markers"
+ """``prefix_breaks`` over what the cache keys on, after asserting every request carried markers."""
+ unmarked = [i for i, r in enumerate(requests) if "cache_control" not in canon(r)]
+ assert not unmarked, f"caching route sent requests without cache_control markers: {unmarked}"
return prefix_breaks([_cache_content(r) for r in requests])
diff --git a/tests/agent/test_relay_llm.py b/tests/agent/test_relay_llm.py
index ac6e6b3acae..be8cdc59ce6 100644
--- a/tests/agent/test_relay_llm.py
+++ b/tests/agent/test_relay_llm.py
@@ -580,6 +580,25 @@ def test_anthropic_stream_accumulator_merges_plain_provider_object():
assert response.usage.input_tokens == 10
+def test_anthropic_stream_accumulator_null_delta_usage_keeps_message_start_counts():
+ """The SDK's ``MessageDeltaUsage`` serializes the fields message_delta omits as null; they
+ must not erase the input / cache counts message_start reported (span token counts went null)."""
+ accumulator = relay_llm.AnthropicStreamAccumulator()
+ accumulator.observe({"type": "message_start", "message": {
+ "id": "message-1", "type": "message", "role": "assistant", "model": "claude-test",
+ "usage": {"input_tokens": 12, "cache_read_input_tokens": 3000, "cache_creation_input_tokens": 200,
+ "output_tokens": 1},
+ }})
+ accumulator.observe({"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {
+ "output_tokens": 42, "input_tokens": None, "cache_read_input_tokens": None,
+ "cache_creation_input_tokens": None,
+ }})
+
+ assert accumulator.finalize()["usage"] == {
+ "input_tokens": 12, "cache_read_input_tokens": 3000, "cache_creation_input_tokens": 200, "output_tokens": 42,
+ }
+
+
def test_jsonable_does_not_probe_dynamic_attributes():
class DynamicProviderObject:
def __getattr__(self, name):