Debian Codegraph @

tests/lib/test_refusal_fallback_streaming.py

raw
1 from __future__ import annotations
2
3 import os
4 import re
5 import json
6 import logging
7 from typing import Any, List, Protocol, cast
8 from pathlib import Path
9
10 import httpx2
11 import pytest
12 from respx import MockRouter
13
14 from anthropic import (
15 Omit,
16 Stream,
17 Anthropic,
18 APIRequest,
19 APIResponse,
20 AsyncStream,
21 AnthropicError,
22 AsyncAnthropic,
23 BetaFallbackState,
24 BetaRefusalFallbackMiddleware,
25 omit,
26 )
27 from anthropic._models import FinalRequestOptions
28 from anthropic.types.beta import BetaMessage, BetaFallbackParam, BetaRawMessageStreamEvent
29 from anthropic.types.anthropic_beta_param import AnthropicBetaParam
30
31 base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
32 api_key = "my-anthropic-api-key"
33
34 LOGGER_NAME = "anthropic.lib.middleware"
35
36
37 def error_logs(caplog: pytest.LogCaptureFixture) -> list[str]:
38 """Messages the middleware logged at ERROR — refusals surfaced rather than retried."""
39 return [
40 record.getMessage()
41 for record in caplog.records
42 if record.name == LOGGER_NAME and record.levelno >= logging.ERROR
43 ]
44
45
46 FIXTURES = Path(__file__).parent.parent / "fixtures" / "fable-fallback"
47 FALLBACK_MODEL = "claude-opus-4-8"
48 SECOND_MODEL = "claude-sonnet-4-6"
49 FALLBACKS: List[BetaFallbackParam] = [{"model": FALLBACK_MODEL}]
50 TWO_FALLBACKS: List[BetaFallbackParam] = [{"model": FALLBACK_MODEL}, {"model": SECOND_MODEL}]
51
52 # Wire-shaped synthetic capture — the primary refuses after a thinking +
53 # partial-text block and mints a credit token; the fallback then completes
54 # the message.
55 STREAM_A = (FIXTURES / "stream-a-refusal.sse").read_text()
56 STREAM_B = (FIXTURES / "stream-b-fallback.sse").read_text()
57
58 # Server-tool wire (synthetic, wire-shaped): server_tool_use streams its input
59 # via input_json_delta after an empty `input:{}`, the web_search_tool_result
60 # arrives as a single content_block_start carrying full content, and the
61 # refusal terminal (message_delta + token) lands mid-tool-loop, after a
62 # partial text block. The token is never redeemed (the mock serves the next
63 # leg).
64 STREAM_A_TOOL = (FIXTURES / "stream-a-toolrefusal.sse").read_text()
65
66 PARAMS: dict[str, Any] = {
67 "model": "claude-fable-5",
68 "max_tokens": 1024,
69 "messages": [{"role": "user", "content": "Hey claudius! Can you tell me what a solar eclipse is?"}],
70 }
71
72
73 def make_sync_client(**kwargs: Any) -> Anthropic:
74 return Anthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=0, **kwargs)
75
76
77 def make_async_client(**kwargs: Any) -> AsyncAnthropic:
78 return AsyncAnthropic(base_url=base_url, api_key=api_key, _strict_response_validation=True, max_retries=0, **kwargs)
79
80
81 def make_lenient_client(**kwargs: Any) -> Anthropic:
82 """A client with the default (non-strict) response validation.
83
84 The fixture wire's terminal refusal delta self-reports a `{type: "message"}`
85 iteration without a `model` key, which the generated
86 `BetaMessageIterationUsage` type marks required — strict validation rejects
87 it. Tests where that wire reaches the parser verbatim (pass-through
88 refusals, synthetic closes reusing the refusal's usage) use this client.
89 """
90 return Anthropic(base_url=base_url, api_key=api_key, max_retries=0, **kwargs)
91
92
93 def sse_response(body: str) -> httpx2.Response:
94 return httpx2.Response(200, headers={"content-type": "text/event-stream"}, content=body.encode("utf-8"))
95
96
97 def json_response(body: Any, status: int) -> httpx2.Response:
98 return httpx2.Response(status, json=body)
99
100
101 def error_response(message: str, status: int) -> httpx2.Response:
102 return json_response({"type": "error", "error": {"type": "invalid_request_error", "message": message}}, status)
103
104
105 def ev(data: dict[str, Any]) -> str:
106 """Serialize one event payload as an SSE frame (its `type` is the event name)."""
107 return f"event: {data['type']}\ndata: {json.dumps(data)}\n\n"
108
109
110 def message_start() -> str:
111 return ev(
112 {
113 "type": "message_start",
114 "message": {
115 "id": "msg_a",
116 "type": "message",
117 "role": "assistant",
118 "model": "claude-fable-5",
119 "content": [],
120 "stop_reason": None,
121 "stop_sequence": None,
122 "usage": {"input_tokens": 12, "output_tokens": 1},
123 },
124 }
125 )
126
127
128 def refusal_delta(token: str | None = "tok_abc", has_prefill_claim: bool = True) -> str:
129 return ev(
130 {
131 "type": "message_delta",
132 "delta": {
133 "stop_reason": "refusal",
134 "stop_sequence": None,
135 "stop_details": {
136 "type": "refusal",
137 "category": None,
138 "explanation": None,
139 "fallback_credit_token": token,
140 "fallback_has_prefill_claim": has_prefill_claim if token is not None else None,
141 },
142 },
143 "usage": {"output_tokens": 20},
144 }
145 )
146
147
148 def redeemed_token(token: str) -> dict[str, str]:
149 """The request-body form of a redeemed credit token — the object shape, best-effort mode."""
150 return {"token": token, "mode": "best_effort"}
151
152
153 def collect(stream: Stream[BetaRawMessageStreamEvent]) -> list[BetaRawMessageStreamEvent]:
154 return list(stream)
155
156
157 class MockRequestCall(Protocol):
158 request: httpx2.Request
159
160
161 def request_bodies(respx_mock: MockRouter) -> list[dict[str, Any]]:
162 calls = cast("list[MockRequestCall]", respx_mock.calls)
163 return [cast("dict[str, Any]", json.loads(call.request.content)) for call in calls]
164
165
166 def beta_headers(respx_mock: MockRouter) -> list[str | None]:
167 calls = cast("list[MockRequestCall]", respx_mock.calls)
168 return [call.request.headers.get("anthropic-beta") for call in calls]
169
170
171 def skeleton(events: list[BetaRawMessageStreamEvent]) -> list[str]:
172 """Compact structural skeleton of a spliced stream — no text content."""
173 out: list[str] = []
174 for event in events:
175 if event.type == "content_block_start":
176 block = event.content_block
177 if block.type == "fallback":
178 label = f"fallback{{{block.from_.model}->{block.to.model}}}"
179 else:
180 label = block.type
181 out.append(f"start[{event.index}] {label}")
182 elif event.type == "content_block_delta":
183 out.append(f"delta[{event.index}] {event.delta.type}")
184 elif event.type == "content_block_stop":
185 out.append(f"stop[{event.index}]")
186 elif event.type == "message_delta":
187 iterations = ",".join(f"{i.type}:{i.model}" for i in (event.usage.iterations or [])) # type: ignore[union-attr]
188 out.append(f"message_delta {event.delta.stop_reason} iter=[{iterations}]")
189 else:
190 out.append(event.type)
191 return out
192
193
194 def block_starts(events: list[BetaRawMessageStreamEvent]) -> list[tuple[int, str]]:
195 return [(e.index, e.content_block.type) for e in events if e.type == "content_block_start"]
196
197
198 def create_stream(
199 client: Anthropic, *, betas: List[AnthropicBetaParam] | Omit = omit
200 ) -> Stream[BetaRawMessageStreamEvent]:
201 return client.beta.messages.create(
202 model="claude-fable-5",
203 max_tokens=1024,
204 messages=[{"role": "user", "content": "Hey claudius! Can you tell me what a solar eclipse is?"}],
205 betas=betas,
206 stream=True,
207 )
208
209
210 async def create_stream_async(client: AsyncAnthropic) -> "AsyncStream[BetaRawMessageStreamEvent]":
211 return await client.beta.messages.create(
212 model="claude-fable-5",
213 max_tokens=1024,
214 messages=[{"role": "user", "content": "Hey claudius! Can you tell me what a solar eclipse is?"}],
215 stream=True,
216 )
217
218
219 # --- happy path -----------------------------------------------------------
220
221
222 class TestShapeBContinuation:
223 @pytest.mark.respx(base_url=base_url)
224 def test_splices_the_fallback_onto_the_refused_stream(self, respx_mock: MockRouter) -> None:
225 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
226 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
227
228 events = collect(create_stream(client))
229
230 # A's thinking + text are forwarded, a fallback boundary block is emitted
231 # at the next monotonic index, then B's blocks continue after it.
232 assert block_starts(events) == [
233 (0, "thinking"),
234 (1, "text"),
235 (2, "fallback"),
236 (3, "text"),
237 ]
238
239 # The fallback block carries the from/to model transition.
240 fallback = next(
241 e.content_block for e in events if e.type == "content_block_start" and e.content_block.type == "fallback"
242 )
243 assert fallback.from_.model == "claude-fable-5"
244 assert fallback.to.model == FALLBACK_MODEL
245
246 # Exactly one message_start (A's) and one message_stop reach the client —
247 # B's message_start is suppressed.
248 assert len([e for e in events if e.type == "message_start"]) == 1
249 assert len([e for e in events if e.type == "message_stop"]) == 1
250 assert len([e for e in events if e.type == "message_delta"]) == 1
251
252 # B's message_start (not re-emitted) has no `input_transformations`, so
253 # the emitted message_delta gains none.
254 delta = next(e for e in events if e.type == "message_delta")
255 assert "input_transformations" not in delta.to_dict()
256
257 @pytest.mark.respx(base_url=base_url)
258 def test_usage_iterations_is_the_two_entry_server_shape(self, respx_mock: MockRouter) -> None:
259 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
260 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
261
262 events = collect(create_stream(client))
263
264 message_delta = next(e for e in events if e.type == "message_delta")
265 assert message_delta.delta.stop_reason == "end_turn"
266 iterations = message_delta.usage.iterations or []
267 # the 2-entry server shape, with no spurious `message: None` entry
268 assert [(i.type, i.model) for i in iterations] == [ # type: ignore[union-attr]
269 ("message", "claude-fable-5"),
270 ("fallback_message", FALLBACK_MODEL),
271 ]
272
273 @pytest.mark.respx(base_url=base_url)
274 def test_builds_request_b_as_a_shape_b_continuation(self, respx_mock: MockRouter) -> None:
275 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
276 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
277
278 collect(create_stream(client))
279
280 bodies = request_bodies(respx_mock)
281 assert len(bodies) == 2
282 body_b = bodies[1]
283
284 # Model swapped to the fallback, credit token from A's stop_details set.
285 assert body_b["model"] == FALLBACK_MODEL
286 credit = cast("dict[str, Any]", body_b["fallback_credit_token"])
287 assert credit["mode"] == "best_effort"
288 assert len(credit["token"]) > 0
289
290 # Mutually exclusive with server-side fallback — both spellings absent.
291 assert "fallback" not in body_b
292 assert "fallbacks" not in body_b
293
294 # max_tokens untouched (any render-shaping change would 400).
295 assert body_b["max_tokens"] == 1024
296
297 # Original turn preserved; one assistant turn appended carrying the
298 # [thinking, text] partial output as-is — the prefill claim authorizes
299 # it verbatim, so no client-side filtering or trimming.
300 assert len(body_b["messages"]) == 2
301 assert body_b["messages"][0] == PARAMS["messages"][0]
302 appended = body_b["messages"][1]
303 assert appended["role"] == "assistant"
304 assert [block["type"] for block in appended["content"]] == ["thinking", "text"]
305 assert "signature" in appended["content"][0]
306
307 @pytest.mark.respx(base_url=base_url)
308 def test_appends_the_fallback_credit_beta_to_both_the_original_and_hop_requests(
309 self, respx_mock: MockRouter
310 ) -> None:
311 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
312 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
313
314 # the request already carries a beta header; the default is appended to it.
315 collect(create_stream(client, betas=["interleaved-thinking-2025-05-14"]))
316
317 assert beta_headers(respx_mock) == [
318 "interleaved-thinking-2025-05-14,fallback-credit-2026-07-01",
319 "interleaved-thinking-2025-05-14,fallback-credit-2026-07-01",
320 ]
321
322 @pytest.mark.respx(base_url=base_url)
323 def test_the_betas_option_replaces_the_default_on_every_request(self, respx_mock: MockRouter) -> None:
324 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
325 client = make_sync_client(
326 middleware=[BetaRefusalFallbackMiddleware(FALLBACKS, betas=["fallback-credit-2027-01-01"])]
327 )
328
329 collect(create_stream(client, betas=["fallback-credit-2026-06-01"]))
330
331 assert beta_headers(respx_mock) == [
332 "fallback-credit-2026-06-01,fallback-credit-2027-01-01",
333 "fallback-credit-2026-06-01,fallback-credit-2027-01-01",
334 ]
335
336
337 # --- edge cases -----------------------------------------------------------
338
339
340 class TestEdgeCases:
341 @pytest.mark.respx(base_url=base_url)
342 def test_a_refusal_without_a_prefill_claim_falls_back_to_shape_a(self, respx_mock: MockRouter) -> None:
343 # fallback_has_prefill_claim: false — the partial output may not be
344 # resent, so the middleware omits the prefill and resends the original
345 # body with just the token attached.
346 no_claim = "".join(
347 [
348 message_start(),
349 ev(
350 {
351 "type": "content_block_start",
352 "index": 0,
353 "content_block": {"type": "thinking", "thinking": "", "signature": ""},
354 }
355 ),
356 ev(
357 {
358 "type": "content_block_delta",
359 "index": 0,
360 "delta": {"type": "thinking_delta", "thinking": "considering the request"},
361 }
362 ),
363 ev(
364 {
365 "type": "content_block_delta",
366 "index": 0,
367 "delta": {"type": "signature_delta", "signature": "sig=="},
368 }
369 ),
370 ev({"type": "content_block_stop", "index": 0}),
371 refusal_delta("tok_abc", False),
372 ev({"type": "message_stop"}),
373 ]
374 )
375 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(no_claim), sse_response(STREAM_B)])
376 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
377
378 collect(create_stream(client))
379
380 bodies = request_bodies(respx_mock)
381 assert bodies[1]["fallback_credit_token"] == redeemed_token("tok_abc")
382 # No appended assistant turn — identical body (shape-A).
383 assert bodies[1]["messages"] == PARAMS["messages"]
384
385 @pytest.mark.respx(base_url=base_url)
386 def test_refusal_with_no_credit_token_passes_a_through_and_logs_an_error(
387 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
388 ) -> None:
389 no_token = re.sub(r'"fallback_credit_token":"[^"]*"', '"fallback_credit_token":null', STREAM_A)
390 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(no_token)])
391 client = make_lenient_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
392
393 events = collect(create_stream(client))
394
395 # Only the original request was made — no fallback.
396 assert len(respx_mock.calls) == 1
397 errors = error_logs(caplog)
398 assert len(errors) == 1
399 assert "no fallback_credit_token" in errors[0]
400
401 # A passes through unchanged, ending in its own refusal (no fallback block).
402 assert not any(e.type == "content_block_start" and e.content_block.type == "fallback" for e in events)
403 assert next(e for e in events if e.type == "message_delta").delta.stop_reason == "refusal"
404
405 @pytest.mark.respx(base_url=base_url)
406 def test_a_400_on_the_prefill_form_retries_the_same_hop_without_the_partial(
407 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
408 ) -> None:
409 respx_mock.post("/v1/messages").mock(
410 side_effect=[
411 sse_response(STREAM_A),
412 error_response("bad prefill", 400),
413 sse_response(STREAM_B),
414 ]
415 )
416 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
417
418 events = collect(create_stream(client))
419
420 # Attempt 1 appends A's partial; the 400 drops it and attempt 2 redeems
421 # the same token against the unchanged body.
422 bodies = request_bodies(respx_mock)
423 assert len(bodies) == 3
424 assert len(bodies[1]["messages"]) == 2
425 assert bodies[2]["model"] == FALLBACK_MODEL
426 assert bodies[2]["fallback_credit_token"] == bodies[1]["fallback_credit_token"]
427 assert bodies[2]["messages"] == PARAMS["messages"]
428
429 # The recovered hop is not a failure: one boundary, a normal completion.
430 assert error_logs(caplog) == []
431 boundaries = [e for e in events if e.type == "content_block_start" and e.content_block.type == "fallback"]
432 assert len(boundaries) == 1
433 assert next(e for e in events if e.type == "message_delta").delta.stop_reason == "end_turn"
434
435 @pytest.mark.respx(base_url=base_url)
436 def test_a_failed_fallback_request_replays_the_refusal_and_logs_an_error(
437 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
438 ) -> None:
439 respx_mock.post("/v1/messages").mock(
440 side_effect=[
441 sse_response(STREAM_A),
442 # the prefill form 400s, the same-body retry 400s too — only
443 # then does the hop count as failed
444 error_response("nope", 400),
445 error_response("nope", 400),
446 ]
447 )
448 client = make_lenient_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
449
450 events = collect(create_stream(client))
451
452 assert len(respx_mock.calls) == 3
453 errors = error_logs(caplog)
454 assert len(errors) == 1
455 assert "HTTP 400" in errors[0]
456 assert FALLBACK_MODEL in errors[0]
457
458 # The failed hop was never reached, so it leaves no seam; A's suppressed
459 # refusal is replayed — its credit token intact for a manual retry, with
460 # no model recommendation (the failure was not a capacity error) — then
461 # message_stop closes the stream.
462 assert not any(e.type == "content_block_start" and e.content_block.type == "fallback" for e in events)
463 delta = next(e for e in events if e.type == "message_delta")
464 assert delta.delta.stop_reason == "refusal"
465 assert delta.delta.stop_details is not None
466 assert delta.delta.stop_details.fallback_credit_token is not None
467 assert delta.delta.stop_details.recommended_model is None
468 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
469 ("message", "claude-fable-5"),
470 ]
471 assert events[-1].type == "message_stop"
472
473 @pytest.mark.respx(base_url=base_url)
474 def test_a_capacity_failed_fallback_request_stamps_the_recommended_model(
475 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
476 ) -> None:
477 respx_mock.post("/v1/messages").mock(
478 side_effect=[
479 sse_response(STREAM_A),
480 json_response({"type": "error", "error": {"type": "overloaded_error", "message": "later"}}, 529),
481 ]
482 )
483 client = make_lenient_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
484
485 events = collect(create_stream(client))
486
487 errors = error_logs(caplog)
488 assert len(errors) == 1
489 assert "HTTP 529" in errors[0]
490 # a capacity failure (429/529) stamps the failed model as the recommendation
491 delta = next(e for e in events if e.type == "message_delta")
492 assert delta.delta.stop_details is not None
493 assert delta.delta.stop_details.recommended_model == FALLBACK_MODEL
494
495 @pytest.mark.respx(base_url=base_url)
496 def test_a_fallback_request_that_raises_replays_the_refusal(
497 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
498 ) -> None:
499 respx_mock.post("/v1/messages").mock(
500 side_effect=[sse_response(STREAM_A), httpx2.ConnectError("connection reset")]
501 )
502 client = make_lenient_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
503
504 events = collect(create_stream(client))
505
506 errors = error_logs(caplog)
507 assert len(errors) == 1
508 # the raised error reaches the log as the SDK's connection error
509 assert "Connection error." in errors[0]
510 assert FALLBACK_MODEL in errors[0]
511
512 # The stream still closes cleanly: A's refusal is replayed and
513 # message_stop follows — not a hard stream error.
514 assert next(e for e in events if e.type == "message_delta").delta.stop_reason == "refusal"
515 assert events[-1].type == "message_stop"
516
517 @pytest.mark.respx(base_url=base_url)
518 def test_pass_through_preserves_sse_fields_beyond_event_and_data(self, respx_mock: MockRouter) -> None:
519 wire = (
520 "retry: 1500\nevent: message_start\ndata: "
521 + json.dumps(
522 {
523 "type": "message_start",
524 "message": {
525 "id": "msg_a",
526 "type": "message",
527 "role": "assistant",
528 "model": "claude-fable-5",
529 "content": [],
530 "stop_reason": None,
531 "stop_sequence": None,
532 "usage": {"input_tokens": 10, "output_tokens": 1},
533 },
534 }
535 )
536 + "\n\n"
537 + ": keep-alive\nid: 42\nevent: message_delta\ndata: "
538 + json.dumps(
539 {
540 "type": "message_delta",
541 "delta": {"stop_reason": "end_turn", "stop_sequence": None},
542 "usage": {"output_tokens": 3},
543 }
544 )
545 + "\n\n"
546 + "event: message_stop\ndata: "
547 + json.dumps({"type": "message_stop"})
548 + "\n\n"
549 )
550 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(wire)])
551 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
552
553 stream = create_stream(client)
554 raw = stream.response.read()
555
556 assert raw.decode("utf-8") == wire
557
558 @pytest.mark.respx(base_url=base_url)
559 def test_a_non_refusal_stream_is_passed_through_untouched(
560 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
561 ) -> None:
562 normal = "".join(
563 [
564 message_start(),
565 ev({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
566 ev(
567 {
568 "type": "content_block_delta",
569 "index": 0,
570 "delta": {"type": "text_delta", "text": "Sure!"},
571 }
572 ),
573 ev({"type": "content_block_stop", "index": 0}),
574 ev(
575 {
576 "type": "message_delta",
577 "delta": {"stop_reason": "end_turn", "stop_sequence": None},
578 "usage": {"output_tokens": 3},
579 }
580 ),
581 ev({"type": "message_stop"}),
582 ]
583 )
584 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(normal)])
585 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
586
587 events = collect(create_stream(client))
588
589 assert len(respx_mock.calls) == 1
590 assert error_logs(caplog) == []
591 assert skeleton(events) == [
592 "message_start",
593 "start[0] text",
594 "delta[0] text_delta",
595 "stop[0]",
596 "message_delta end_turn iter=[]",
597 "message_stop",
598 ]
599
600 @pytest.mark.respx(base_url=base_url, assert_all_called=False)
601 def test_server_side_fallbacks_raise_an_error(self, respx_mock: MockRouter) -> None:
602 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A)])
603 client = make_lenient_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
604
605 with pytest.raises(
606 AnthropicError, match=r"Sending the `fallbacks:` request param is not supported when using the `BetaRefusalFallbackMiddleware`\. You should either remove the middleware and send `fallbacks:` with the `server-side-fallback-2026-07-01` beta header to let the API handle refusal fallbacks, or omit the `fallbacks:` param if you'd like `BetaRefusalFallbackMiddleware` to handle fallbacks on the client side\."
607 ):
608 client.beta.messages.create(
609 model="claude-fable-5",
610 max_tokens=1024,
611 messages=[{"role": "user", "content": "Hey claudius! Can you tell me what a solar eclipse is?"}],
612 fallbacks=[{"model": "server-fallback"}],
613 stream=True,
614 )
615 # the error is raised before any request is sent
616 assert len(respx_mock.calls) == 0
617
618
619 # --- fallback state pinning -------------------------------------------------
620
621
622 class TestFallbackState:
623 @pytest.mark.respx(base_url=base_url)
624 def test_pins_the_state_to_the_hop_that_served(self, respx_mock: MockRouter) -> None:
625 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
626 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
627
628 state = BetaFallbackState()
629 with state:
630 collect(create_stream(client))
631
632 assert state.index == 0
633
634 @pytest.mark.respx(base_url=base_url)
635 def test_a_pinned_state_starts_on_the_pinned_entry_and_chains_past_it(self, respx_mock: MockRouter) -> None:
636 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
637 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
638
639 state = BetaFallbackState()
640 state.index = 0
641 with state:
642 collect(create_stream(client))
643
644 bodies = request_bodies(respx_mock)
645 assert len(bodies) == 2
646 # The initial request already carries the pinned entry's params; the
647 # mid-stream refusal then chains to the entry after the pin.
648 assert bodies[0]["model"] == FALLBACK_MODEL
649 assert bodies[1]["model"] == SECOND_MODEL
650 assert state.index == 1
651
652 @pytest.mark.respx(base_url=base_url)
653 def test_warns_once_when_falling_back_without_a_state(
654 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
655 ) -> None:
656 respx_mock.post("/v1/messages").mock(
657 side_effect=[
658 sse_response(STREAM_A),
659 sse_response(STREAM_B),
660 sse_response(STREAM_A),
661 sse_response(STREAM_B),
662 ]
663 )
664 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
665
666 with caplog.at_level(logging.WARNING, logger=LOGGER_NAME):
667 # drain the spliced stream so the fallback actually fires
668 collect(create_stream(client))
669 collect(create_stream(client))
670
671 warnings = [record for record in caplog.records if record.name == LOGGER_NAME]
672 assert len(warnings) == 1
673 assert "BetaFallbackState" in warnings[0].getMessage()
674
675
676 # --- fallback chain ---------------------------------------------------------
677
678
679 def hop_refusal(token: str | None = "tok_b", has_prefill_claim: bool = True) -> str:
680 """A fallback hop that contributes one text block, then refuses with a fresh token."""
681 return "".join(
682 [
683 message_start(),
684 ev({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
685 ev(
686 {
687 "type": "content_block_delta",
688 "index": 0,
689 "delta": {"type": "text_delta", "text": "Partial from B. "},
690 }
691 ),
692 ev({"type": "content_block_stop", "index": 0}),
693 refusal_delta(token, has_prefill_claim),
694 ev({"type": "message_stop"}),
695 ]
696 )
697
698
699 class TestFallbackChain:
700 @pytest.mark.respx(base_url=base_url)
701 def test_a_refused_hop_splices_its_partial_and_chains_to_the_next_entry(self, respx_mock: MockRouter) -> None:
702 respx_mock.post("/v1/messages").mock(
703 side_effect=[sse_response(STREAM_A), sse_response(hop_refusal()), sse_response(STREAM_B)]
704 )
705 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
706
707 events = collect(create_stream(client))
708
709 bodies = request_bodies(respx_mock)
710 assert len(bodies) == 3
711
712 # Hop 1 redeems A's token; hop 2 redeems the fresh token minted by hop 1's
713 # refusal, with hop 1's partial extending the same turn as-is.
714 assert bodies[1]["model"] == FALLBACK_MODEL
715 assert bodies[2]["model"] == SECOND_MODEL
716 assert bodies[2]["fallback_credit_token"] == redeemed_token("tok_b")
717 assert bodies[2]["fallback_credit_token"] != bodies[1]["fallback_credit_token"]
718 assert bodies[2]["messages"][1]["content"] == [
719 *bodies[1]["messages"][1]["content"],
720 {"type": "text", "text": "Partial from B. "},
721 ]
722
723 # One continuous message: A's blocks, boundary, hop 1's partial, boundary,
724 # hop 2's blocks — indices stay monotonic across all three streams.
725 assert block_starts(events) == [
726 (0, "thinking"),
727 (1, "text"),
728 (2, "fallback"),
729 (3, "text"),
730 (4, "fallback"),
731 (5, "text"),
732 ]
733 boundaries = [
734 e.content_block for e in events if e.type == "content_block_start" and e.content_block.type == "fallback"
735 ]
736 assert (boundaries[0].from_.model, boundaries[0].to.model) == ("claude-fable-5", FALLBACK_MODEL)
737 assert (boundaries[1].from_.model, boundaries[1].to.model) == (FALLBACK_MODEL, SECOND_MODEL)
738
739 # Hop 1's refusal delta is suppressed; the terminal delta carries every hop.
740 deltas = [e for e in events if e.type == "message_delta"]
741 assert len(deltas) == 1
742 assert deltas[0].delta.stop_reason == "end_turn"
743 assert [(i.type, i.model) for i in (deltas[0].usage.iterations or [])] == [ # type: ignore[union-attr]
744 ("message", "claude-fable-5"),
745 ("message", FALLBACK_MODEL),
746 ("fallback_message", SECOND_MODEL),
747 ]
748 assert len([e for e in events if e.type == "message_stop"]) == 1
749
750 @pytest.mark.respx(base_url=base_url)
751 def test_a_refused_hop_without_a_prefill_claim_drops_its_partial_from_the_next_request(
752 self, respx_mock: MockRouter
753 ) -> None:
754 respx_mock.post("/v1/messages").mock(
755 side_effect=[
756 sse_response(STREAM_A),
757 sse_response(hop_refusal("tok_b", False)),
758 sse_response(STREAM_B),
759 ]
760 )
761 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
762
763 collect(create_stream(client))
764
765 bodies = request_bodies(respx_mock)
766 assert len(bodies) == 3
767 assert bodies[2]["fallback_credit_token"] == redeemed_token("tok_b")
768 # Hop 2 redeems the fresh token against the body it was minted for —
769 # hop 1's request, including its appended turn — without hop 1's own
770 # (unclaimed) partial output.
771 assert bodies[2]["messages"] == bodies[1]["messages"]
772
773 @pytest.mark.respx(base_url=base_url)
774 def test_an_http_failed_hop_is_skipped_and_the_unredeemed_token_carries_to_the_next_entry(
775 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
776 ) -> None:
777 respx_mock.post("/v1/messages").mock(
778 side_effect=[
779 sse_response(STREAM_A),
780 json_response({"type": "error", "error": {"type": "overloaded_error", "message": "later"}}, 529),
781 sse_response(STREAM_B),
782 ]
783 )
784 client = make_sync_client(
785 middleware=[BetaRefusalFallbackMiddleware([{"model": FALLBACK_MODEL}, {"model": SECOND_MODEL}])]
786 )
787
788 events = collect(create_stream(client))
789
790 errors = error_logs(caplog)
791 assert len(errors) == 1
792 assert "HTTP 529" in errors[0]
793 assert FALLBACK_MODEL in errors[0]
794 assert len(respx_mock.calls) == 3
795
796 # Same token and continuation — the failed hop never redeemed them.
797 bodies = request_bodies(respx_mock)
798 assert bodies[2]["model"] == SECOND_MODEL
799 assert bodies[2]["fallback_credit_token"] == bodies[1]["fallback_credit_token"]
800 assert bodies[2]["messages"] == bodies[1]["messages"]
801
802 # The failed hop was never reached: no seam for it — one boundary, from
803 # A straight to the entry that served.
804 boundaries = [
805 e.content_block for e in events if e.type == "content_block_start" and e.content_block.type == "fallback"
806 ]
807 assert [(b.from_.model, b.to.model) for b in boundaries] == [
808 ("claude-fable-5", SECOND_MODEL),
809 ]
810
811 # The failed hop is absent from iterations (no usage came back).
812 delta = next(e for e in events if e.type == "message_delta")
813 assert delta.delta.stop_reason == "end_turn"
814 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
815 ("message", "claude-fable-5"),
816 ("fallback_message", SECOND_MODEL),
817 ]
818
819 @pytest.mark.respx(base_url=base_url)
820 def test_a_terminal_refusal_with_no_entries_left_is_emitted_with_the_full_iteration_chain(
821 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
822 ) -> None:
823 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(hop_refusal())])
824 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
825
826 events = collect(create_stream(client))
827
828 assert len(respx_mock.calls) == 2
829 errors = error_logs(caplog)
830 assert len(errors) == 1
831 assert "no fallback entries remain" in errors[0]
832 delta = next(e for e in events if e.type == "message_delta")
833 assert delta.delta.stop_reason == "refusal"
834 # The fresh token reaches the client for a manual retry.
835 assert delta.delta.stop_details is not None
836 assert delta.delta.stop_details.fallback_credit_token == "tok_b"
837 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
838 ("message", "claude-fable-5"),
839 ("fallback_message", FALLBACK_MODEL),
840 ]
841
842 @pytest.mark.respx(base_url=base_url)
843 def test_a_token_less_refusal_on_the_final_hop_is_still_logged(
844 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
845 ) -> None:
846 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(hop_refusal(None))])
847 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
848
849 events = collect(create_stream(client))
850
851 errors = error_logs(caplog)
852 assert len(errors) == 1
853 assert "no fallback_credit_token" in errors[0]
854 assert next(e for e in events if e.type == "message_delta").delta.stop_reason == "refusal"
855
856 def test_an_empty_chain_passes_the_stream_through_untouched(self, caplog: pytest.LogCaptureFixture) -> None:
857 middleware = BetaRefusalFallbackMiddleware([])
858 client = make_sync_client()
859
860 options = FinalRequestOptions.construct(
861 method="post", url="/v1/messages?beta=true", json_data=dict(PARAMS), headers={}
862 )
863 request = APIRequest(
864 options=options,
865 cast_to=BetaMessage,
866 stream=True,
867 stream_cls=Stream[BetaRawMessageStreamEvent],
868 )
869 response = APIResponse(
870 raw=sse_response(STREAM_A),
871 cast_to=BetaMessage,
872 client=client,
873 stream=True,
874 stream_cls=Stream[BetaRawMessageStreamEvent],
875 options=options,
876 )
877
878 calls: list[APIRequest] = []
879
880 def call_next(req: APIRequest) -> APIResponse[Any]:
881 calls.append(req)
882 return response
883
884 out = middleware.handle(request, call_next)
885
886 # With nothing to hop to, the response isn't even wrapped — no per-event
887 # decode/re-encode overhead, and no error: this is the steady state of an
888 # exhausted or fully-pinned chain.
889 assert out is response
890 assert len(calls) == 1
891 assert error_logs(caplog) == []
892
893 @pytest.mark.respx(base_url=base_url)
894 def test_a_hop_whose_request_raises_is_skipped_and_the_unredeemed_token_carries(
895 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
896 ) -> None:
897 respx_mock.post("/v1/messages").mock(
898 side_effect=[
899 sse_response(STREAM_A),
900 httpx2.ConnectError("connection reset"),
901 sse_response(STREAM_B),
902 ]
903 )
904 client = make_sync_client(
905 middleware=[BetaRefusalFallbackMiddleware([{"model": FALLBACK_MODEL}, {"model": SECOND_MODEL}])]
906 )
907
908 events = collect(create_stream(client))
909
910 errors = error_logs(caplog)
911 assert len(errors) == 1
912 assert "Connection error." in errors[0]
913 assert FALLBACK_MODEL in errors[0]
914 assert len(respx_mock.calls) == 3
915
916 # Same token — the raising hop never redeemed it.
917 bodies = request_bodies(respx_mock)
918 assert bodies[2]["model"] == SECOND_MODEL
919 assert bodies[2]["fallback_credit_token"] == bodies[1]["fallback_credit_token"]
920
921 # The stream completes normally from the next entry.
922 delta = next(e for e in events if e.type == "message_delta")
923 assert delta.delta.stop_reason == "end_turn"
924 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
925 ("message", "claude-fable-5"),
926 ("fallback_message", SECOND_MODEL),
927 ]
928
929
930 # --- pre-stream refusals ------------------------------------------------------
931
932
933 def serving_stream(model: str = FALLBACK_MODEL, message_id: str = "msg_b") -> str:
934 return "".join(
935 [
936 ev(
937 {
938 "type": "message_start",
939 "message": {
940 "id": message_id,
941 "type": "message",
942 "role": "assistant",
943 "model": model,
944 "content": [],
945 "stop_reason": None,
946 "stop_sequence": None,
947 "usage": {"input_tokens": 12, "output_tokens": 1},
948 },
949 }
950 ),
951 ev({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
952 ev({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Happy to help."}}),
953 ev({"type": "content_block_stop", "index": 0}),
954 ev(
955 {
956 "type": "message_delta",
957 "delta": {"stop_reason": "end_turn", "stop_sequence": None},
958 "usage": {"output_tokens": 9},
959 }
960 ),
961 ev({"type": "message_stop"}),
962 ]
963 )
964
965
966 TRANSFORMS: List[dict[str, Any]] = [
967 {"type": "thinking_dropped", "path": "messages.1.content.0", "reason": "model_binding_mismatch"}
968 ]
969
970
971 def transforming_stream(
972 *, delta_transformations: List[dict[str, Any]] | None = None, terminal: str | None = None
973 ) -> str:
974 """A hop whose message_start reports `input_transformations`. It serves —
975 its terminal message_delta carrying `delta_transformations` only when given —
976 unless `terminal` supplies the closing message_delta frame instead."""
977 delta: dict[str, Any] = {
978 "type": "message_delta",
979 "delta": {"stop_reason": "end_turn", "stop_sequence": None},
980 "usage": {"output_tokens": 9},
981 }
982 if delta_transformations is not None:
983 delta["input_transformations"] = delta_transformations
984 return "".join(
985 [
986 ev(
987 {
988 "type": "message_start",
989 "message": {
990 "id": "msg_b",
991 "type": "message",
992 "role": "assistant",
993 "model": FALLBACK_MODEL,
994 "content": [],
995 "stop_reason": None,
996 "stop_sequence": None,
997 "input_transformations": TRANSFORMS,
998 "usage": {"input_tokens": 12, "output_tokens": 1},
999 },
1000 }
1001 ),
1002 ev({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
1003 ev({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Happy to help."}}),
1004 ev({"type": "content_block_stop", "index": 0}),
1005 terminal if terminal is not None else ev(delta),
1006 ev({"type": "message_stop"}),
1007 ]
1008 )
1009
1010
1011 class TestPreStreamRefusals:
1012 """A refusal that arrives before any output streamed: the retry is free and
1013 invisible, so it fires even without a credit token, and the serving hop's
1014 message_start opens the wire carrying the primary's message id."""
1015
1016 pre_stream_refusal = "".join([message_start(), refusal_delta("tok_abc", False), ev({"type": "message_stop"})])
1017
1018 @pytest.mark.respx(base_url=base_url)
1019 def test_the_serving_start_opens_the_wire_with_the_primary_message_id(self, respx_mock: MockRouter) -> None:
1020 respx_mock.post("/v1/messages").mock(
1021 side_effect=[sse_response(self.pre_stream_refusal), sse_response(serving_stream())]
1022 )
1023 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1024
1025 events = collect(create_stream(client))
1026
1027 # The refused hop's message_start never reaches the client; the serving
1028 # hop's opens the wire, rewritten to the primary's message id.
1029 starts = [e for e in events if e.type == "message_start"]
1030 assert len(starts) == 1
1031 assert starts[0].message.model == FALLBACK_MODEL
1032 assert starts[0].message.id == "msg_a"
1033
1034 # One seam at index 0, then the serving hop's content after it.
1035 assert block_starts(events) == [(0, "fallback"), (1, "text")]
1036 delta = next(e for e in events if e.type == "message_delta")
1037 assert delta.delta.stop_reason == "end_turn"
1038 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
1039 ("message", "claude-fable-5"),
1040 ("fallback_message", FALLBACK_MODEL),
1041 ]
1042
1043 @pytest.mark.respx(base_url=base_url)
1044 def test_a_token_less_pre_stream_refusal_still_retries(
1045 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
1046 ) -> None:
1047 token_less = "".join([message_start(), refusal_delta(None), ev({"type": "message_stop"})])
1048 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(token_less), sse_response(serving_stream())])
1049 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1050
1051 events = collect(create_stream(client))
1052
1053 # nothing had streamed, so the retry fired despite the missing token
1054 assert error_logs(caplog) == []
1055 bodies = request_bodies(respx_mock)
1056 assert len(bodies) == 2
1057 assert bodies[1]["model"] == FALLBACK_MODEL
1058 assert "fallback_credit_token" not in bodies[1]
1059 assert next(e for e in events if e.type == "message_delta").delta.stop_reason == "end_turn"
1060
1061 @pytest.mark.respx(base_url=base_url)
1062 def test_a_chain_of_pre_stream_declines_queues_every_seam_in_order(self, respx_mock: MockRouter) -> None:
1063 respx_mock.post("/v1/messages").mock(
1064 side_effect=[
1065 sse_response(self.pre_stream_refusal),
1066 sse_response("".join([message_start(), refusal_delta("tok_b"), ev({"type": "message_stop"})])),
1067 sse_response(serving_stream(SECOND_MODEL)),
1068 ]
1069 )
1070 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
1071
1072 events = collect(create_stream(client))
1073
1074 # serving start first, then both seams, then the serving content
1075 assert events[0].type == "message_start"
1076 assert events[0].message.id == "msg_a"
1077 starts = [(e.index, e.content_block) for e in events if e.type == "content_block_start"]
1078 assert [(i, b.type) for i, b in starts] == [(0, "fallback"), (1, "fallback"), (2, "text")]
1079 seam_one, seam_two = starts[0][1], starts[1][1]
1080 assert seam_one.type == "fallback" and seam_two.type == "fallback"
1081 assert (seam_one.from_.model, seam_one.to.model) == ("claude-fable-5", FALLBACK_MODEL)
1082 assert (seam_two.from_.model, seam_two.to.model) == (FALLBACK_MODEL, SECOND_MODEL)
1083 delta = next(e for e in events if e.type == "message_delta")
1084 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
1085 ("message", "claude-fable-5"),
1086 ("message", FALLBACK_MODEL),
1087 ("fallback_message", SECOND_MODEL),
1088 ]
1089
1090
1091 # --- history seam replay ------------------------------------------------------
1092
1093
1094 class TestSplicedInputTransformations:
1095 """A mid-stream fallback's message_start is not re-emitted, so its
1096 `input_transformations` are copied onto the emitted message_delta, matching
1097 what a server-side fallback sends. A list already on the delta is kept."""
1098
1099 @pytest.mark.respx(base_url=base_url)
1100 def test_the_suppressed_starts_list_is_forwarded_on_the_terminal(self, respx_mock: MockRouter) -> None:
1101 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(transforming_stream())])
1102 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1103
1104 events = collect(create_stream(client))
1105
1106 assert len([e for e in events if e.type == "message_start"]) == 1
1107 delta = next(e for e in events if e.type == "message_delta")
1108 assert delta.to_dict()["input_transformations"] == TRANSFORMS
1109
1110 @pytest.mark.respx(base_url=base_url)
1111 def test_a_list_already_on_the_delta_is_kept(self, respx_mock: MockRouter) -> None:
1112 respx_mock.post("/v1/messages").mock(
1113 side_effect=[sse_response(STREAM_A), sse_response(transforming_stream(delta_transformations=[]))]
1114 )
1115 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1116
1117 events = collect(create_stream(client))
1118
1119 delta = next(e for e in events if e.type == "message_delta")
1120 assert delta.to_dict()["input_transformations"] == []
1121
1122 @pytest.mark.respx(base_url=base_url)
1123 def test_the_list_is_forwarded_on_a_degraded_chains_replayed_refusal(
1124 self, respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
1125 ) -> None:
1126 # the spliced fallback refuses with a token and every later entry fails
1127 # over HTTP: its held-back refusal is replayed as the final message_delta,
1128 # with the list on it
1129 respx_mock.post("/v1/messages").mock(
1130 side_effect=[
1131 sse_response(STREAM_A),
1132 sse_response(transforming_stream(terminal=refusal_delta("tok_b", False))),
1133 error_response("down", 503),
1134 ]
1135 )
1136 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
1137
1138 events = collect(create_stream(client))
1139
1140 assert len(respx_mock.calls) == 3
1141 assert len(error_logs(caplog)) == 1
1142 assert len([e for e in events if e.type == "message_start"]) == 1
1143 delta = next(e for e in events if e.type == "message_delta")
1144 assert delta.delta.stop_reason == "refusal"
1145 assert delta.to_dict()["input_transformations"] == TRANSFORMS
1146 assert events[-1].type == "message_stop"
1147
1148 @pytest.mark.respx(base_url=base_url)
1149 def test_an_emitted_start_leaves_the_delta_untouched(self, respx_mock: MockRouter) -> None:
1150 # a pre-stream refusal: the fallback's message_start is emitted itself,
1151 # so nothing is copied onto the message_delta
1152 pre_stream_refusal = "".join([message_start(), refusal_delta("tok_abc", False), ev({"type": "message_stop"})])
1153 respx_mock.post("/v1/messages").mock(
1154 side_effect=[sse_response(pre_stream_refusal), sse_response(transforming_stream())]
1155 )
1156 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1157
1158 events = collect(create_stream(client))
1159
1160 start = next(e for e in events if e.type == "message_start")
1161 assert start.message.to_dict()["input_transformations"] == TRANSFORMS
1162 delta = next(e for e in events if e.type == "message_delta")
1163 assert "input_transformations" not in delta.to_dict()
1164
1165
1166 class TestHistorySeamReplay:
1167 """Pinning is explicit-state-only: a `fallback` seam block replayed in the
1168 request history never pins — without a `BetaFallbackState` the first request
1169 goes to the original model. The seam blocks themselves are this middleware's
1170 client-side markers, so they are filtered out of the wire request, and an
1171 assistant turn that was only a seam is dropped whole — `content: []` is an
1172 invalid body."""
1173
1174 @pytest.mark.respx(base_url=base_url)
1175 def test_a_history_seam_without_a_state_does_not_pin(self, respx_mock: MockRouter) -> None:
1176 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(serving_stream("claude-fable-5"))])
1177 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
1178
1179 stream = client.beta.messages.create(
1180 model="claude-fable-5",
1181 max_tokens=1024,
1182 messages=[
1183 {"role": "user", "content": "hello"},
1184 {
1185 "role": "assistant",
1186 "content": [
1187 {
1188 "type": "fallback",
1189 "from": {"model": "claude-fable-5"},
1190 "to": {"model": FALLBACK_MODEL},
1191 },
1192 {"type": "text", "text": "earlier turn"},
1193 ],
1194 },
1195 {"role": "user", "content": "and again?"},
1196 ],
1197 stream=True,
1198 )
1199 collect(stream)
1200
1201 bodies = request_bodies(respx_mock)
1202 assert len(bodies) == 1
1203 # no state, no pin — the first request goes to the original model
1204 assert bodies[0]["model"] == "claude-fable-5"
1205 # the seam block is the middleware's own marker — filtered off the wire
1206 assert bodies[0]["messages"][1]["content"] == [{"type": "text", "text": "earlier turn"}]
1207 assert beta_headers(respx_mock) == ["fallback-credit-2026-07-01"]
1208
1209 @pytest.mark.respx(base_url=base_url)
1210 def test_a_seam_only_assistant_turn_is_dropped_whole(self, respx_mock: MockRouter) -> None:
1211 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(serving_stream("claude-fable-5"))])
1212 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1213
1214 stream = client.beta.messages.create(
1215 model="claude-fable-5",
1216 max_tokens=1024,
1217 messages=[
1218 {"role": "user", "content": "hello"},
1219 {
1220 "role": "assistant",
1221 "content": [
1222 {
1223 "type": "fallback",
1224 "from": {"model": "claude-fable-5"},
1225 "to": {"model": FALLBACK_MODEL},
1226 }
1227 ],
1228 },
1229 {"role": "user", "content": "and again?"},
1230 ],
1231 stream=True,
1232 )
1233 collect(stream)
1234
1235 bodies = request_bodies(respx_mock)
1236 assert len(bodies) == 1
1237 # stripping left the assistant turn empty, so the turn is omitted —
1238 # not sent as `content: []`, which the server rejects
1239 assert bodies[0]["messages"] == [
1240 {"role": "user", "content": "hello"},
1241 {"role": "user", "content": "and again?"},
1242 ]
1243 # the rest of the request is intact
1244 assert bodies[0]["model"] == "claude-fable-5"
1245 assert bodies[0]["max_tokens"] == 1024
1246 assert beta_headers(respx_mock) == ["fallback-credit-2026-07-01"]
1247
1248
1249 # --- per-hop overrides ----------------------------------------------------------
1250
1251
1252 class TestPerHopOverrides:
1253 @pytest.mark.respx(base_url=base_url)
1254 def test_entry_overrides_apply_to_the_hop_request(self, respx_mock: MockRouter) -> None:
1255 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
1256 client = make_sync_client(
1257 middleware=[BetaRefusalFallbackMiddleware([{"model": FALLBACK_MODEL, "max_tokens": 32}])]
1258 )
1259
1260 collect(create_stream(client))
1261
1262 bodies = request_bodies(respx_mock)
1263 assert bodies[0]["max_tokens"] == 1024
1264 # the entry's overrides are merged over the hop's body, applied to the
1265 # serving hop only
1266 assert bodies[1]["max_tokens"] == 32
1267 assert bodies[1]["model"] == FALLBACK_MODEL
1268
1269
1270 # --- cancellation -----------------------------------------------------------
1271
1272
1273 class TestCancellation:
1274 @pytest.mark.respx(base_url=base_url)
1275 def test_closing_the_stream_mid_passthrough_tears_down_without_a_fallback_request(
1276 self, respx_mock: MockRouter
1277 ) -> None:
1278 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A)])
1279 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1280
1281 stream = create_stream(client)
1282 seen = 0
1283 for _event in stream:
1284 seen += 1
1285 if seen == 2:
1286 break
1287 stream.close()
1288
1289 # The splice never reached A's refusal, so no hop request was issued and
1290 # teardown released the underlying response without error.
1291 assert len(respx_mock.calls) == 1
1292
1293
1294 # --- tool-use refusals ----------------------------------------------------
1295 #
1296 # Synthetic SSE (web_search-shaped) built from the documented wire shapes:
1297 # server_tool_use streams its input via input_json_delta after an empty
1298 # `input:{}`, and *_tool_result blocks arrive as a single content_block_start
1299 # with full content (no deltas). The server decides prefillability and
1300 # signals it via `fallback_has_prefill_claim`; the client's only rewrite is
1301 # reassembling tool inputs from their accumulated JSON deltas.
1302
1303 TOOL_USE_ID = "srvtoolu_01"
1304
1305
1306 class TestToolUseRefusals:
1307 @pytest.mark.respx(base_url=base_url)
1308 def test_refusal_after_a_completed_server_tool(self, respx_mock: MockRouter) -> None:
1309 stream_a = "".join(
1310 [
1311 message_start(),
1312 ev(
1313 {
1314 "type": "content_block_start",
1315 "index": 0,
1316 "content_block": {"type": "thinking", "thinking": "", "signature": ""},
1317 }
1318 ),
1319 ev(
1320 {
1321 "type": "content_block_delta",
1322 "index": 0,
1323 "delta": {"type": "thinking_delta", "thinking": "let me look this up"},
1324 }
1325 ),
1326 ev(
1327 {
1328 "type": "content_block_delta",
1329 "index": 0,
1330 "delta": {"type": "signature_delta", "signature": "sig=="},
1331 }
1332 ),
1333 ev({"type": "content_block_stop", "index": 0}),
1334 # server_tool_use: real input arrives via input_json_delta, not content_block_start.
1335 ev(
1336 {
1337 "type": "content_block_start",
1338 "index": 1,
1339 "content_block": {
1340 "type": "server_tool_use",
1341 "id": TOOL_USE_ID,
1342 "name": "web_search",
1343 "input": {},
1344 },
1345 }
1346 ),
1347 ev(
1348 {
1349 "type": "content_block_delta",
1350 "index": 1,
1351 "delta": {"type": "input_json_delta", "partial_json": '{"query":"solar eclipse"}'},
1352 }
1353 ),
1354 ev({"type": "content_block_stop", "index": 1}),
1355 # web_search_tool_result: full content in the start frame, no deltas.
1356 ev(
1357 {
1358 "type": "content_block_start",
1359 "index": 2,
1360 "content_block": {
1361 "type": "web_search_tool_result",
1362 "tool_use_id": TOOL_USE_ID,
1363 "content": [
1364 {
1365 "type": "web_search_result",
1366 "url": "https://example.com",
1367 "title": "x",
1368 "encrypted_content": "e",
1369 "page_age": None,
1370 }
1371 ],
1372 },
1373 }
1374 ),
1375 ev({"type": "content_block_stop", "index": 2}),
1376 ev({"type": "content_block_start", "index": 3, "content_block": {"type": "text", "text": ""}}),
1377 ev(
1378 {
1379 "type": "content_block_delta",
1380 "index": 3,
1381 "delta": {"type": "text_delta", "text": "Based on that, "},
1382 }
1383 ),
1384 ev({"type": "content_block_stop", "index": 3}),
1385 refusal_delta(),
1386 ev({"type": "message_stop"}),
1387 ]
1388 )
1389 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(stream_a), sse_response(STREAM_B)])
1390 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1391
1392 events = collect(create_stream(client))
1393
1394 # A's four blocks forwarded, fallback boundary at index 4, B continues at 5.
1395 assert block_starts(events) == [
1396 (0, "thinking"),
1397 (1, "server_tool_use"),
1398 (2, "web_search_tool_result"),
1399 (3, "text"),
1400 (4, "fallback"),
1401 (5, "text"),
1402 ]
1403
1404 appended = request_bodies(respx_mock)[1]["messages"][1]
1405 assert appended["role"] == "assistant"
1406 assert [block["type"] for block in appended["content"]] == [
1407 "thinking",
1408 "server_tool_use",
1409 "web_search_tool_result",
1410 "text",
1411 ]
1412 # The tool input is the parsed input_json_delta payload, not the empty
1413 # `{}` from content_block_start.
1414 assert appended["content"][1] == {
1415 "type": "server_tool_use",
1416 "id": TOOL_USE_ID,
1417 "name": "web_search",
1418 "input": {"query": "solar eclipse"},
1419 }
1420 # The result keeps its pairing id and content.
1421 assert appended["content"][2]["tool_use_id"] == TOOL_USE_ID
1422
1423 @pytest.mark.respx(base_url=base_url)
1424 def test_full_fixture_tool_wire(self, respx_mock: MockRouter) -> None:
1425 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A_TOOL), sse_response(STREAM_B)])
1426 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1427
1428 events = collect(create_stream(client))
1429
1430 assert block_starts(events) == [
1431 (0, "server_tool_use"),
1432 (1, "web_search_tool_result"),
1433 (2, "text"),
1434 (3, "fallback"),
1435 (4, "text"),
1436 ]
1437
1438 appended = request_bodies(respx_mock)[1]["messages"][1]
1439 assert [block["type"] for block in appended["content"]] == [
1440 "server_tool_use",
1441 "web_search_tool_result",
1442 "text",
1443 ]
1444 # Tool input reassembled from the accumulated input_json_delta chunks.
1445 assert appended["content"][0] == {
1446 "type": "server_tool_use",
1447 "id": "srvtoolu_fixture_a_0001",
1448 "name": "web_search",
1449 "input": {"query": "solar eclipse viewing safety news 2026"},
1450 }
1451 # The result block keeps its pairing id.
1452 assert appended["content"][1]["tool_use_id"] == "srvtoolu_fixture_a_0001"
1453 assert appended["content"][1]["type"] == "web_search_tool_result"
1454
1455 @pytest.mark.respx(base_url=base_url)
1456 def test_mid_loop_refusal_ending_in_thinking_strips_the_trailing_thinking_block(
1457 self, respx_mock: MockRouter
1458 ) -> None:
1459 # [server_tool_use, result, thinking] — the server granted a prefill
1460 # claim, but an assistant turn cannot end in a thinking block (the
1461 # server 400s it), so the trailing thinking is stripped from the
1462 # appended turn while everything before it is resent verbatim.
1463 stream_a = "".join(
1464 [
1465 message_start(),
1466 ev(
1467 {
1468 "type": "content_block_start",
1469 "index": 0,
1470 "content_block": {
1471 "type": "server_tool_use",
1472 "id": TOOL_USE_ID,
1473 "name": "web_search",
1474 "input": {},
1475 },
1476 }
1477 ),
1478 ev(
1479 {
1480 "type": "content_block_delta",
1481 "index": 0,
1482 "delta": {"type": "input_json_delta", "partial_json": '{"query":"x"}'},
1483 }
1484 ),
1485 ev({"type": "content_block_stop", "index": 0}),
1486 ev(
1487 {
1488 "type": "content_block_start",
1489 "index": 1,
1490 "content_block": {
1491 "type": "web_search_tool_result",
1492 "tool_use_id": TOOL_USE_ID,
1493 "content": [],
1494 },
1495 }
1496 ),
1497 ev({"type": "content_block_stop", "index": 1}),
1498 ev(
1499 {
1500 "type": "content_block_start",
1501 "index": 2,
1502 "content_block": {"type": "thinking", "thinking": "", "signature": ""},
1503 }
1504 ),
1505 ev(
1506 {
1507 "type": "content_block_delta",
1508 "index": 2,
1509 "delta": {"type": "thinking_delta", "thinking": "hmm"},
1510 }
1511 ),
1512 ev(
1513 {
1514 "type": "content_block_delta",
1515 "index": 2,
1516 "delta": {"type": "signature_delta", "signature": "sig=="},
1517 }
1518 ),
1519 ev({"type": "content_block_stop", "index": 2}),
1520 refusal_delta(),
1521 ev({"type": "message_stop"}),
1522 ]
1523 )
1524 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(stream_a), sse_response(STREAM_B)])
1525 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1526
1527 collect(create_stream(client))
1528
1529 body_b = request_bodies(respx_mock)[1]
1530 assert body_b["fallback_credit_token"] == redeemed_token("tok_abc")
1531 appended = body_b["messages"][1]
1532 assert appended["role"] == "assistant"
1533 assert [block["type"] for block in appended["content"]] == [
1534 "server_tool_use",
1535 "web_search_tool_result",
1536 ]
1537
1538 @pytest.mark.respx(base_url=base_url)
1539 def test_a_partial_of_only_thinking_falls_back_to_the_same_body_form(self, respx_mock: MockRouter) -> None:
1540 # The refusal cut the stream while only a thinking block had streamed:
1541 # stripping the trailing thinking empties the continuation, so no
1542 # assistant turn is appended and the token is redeemed against the
1543 # same body.
1544 stream_a = "".join(
1545 [
1546 message_start(),
1547 ev(
1548 {
1549 "type": "content_block_start",
1550 "index": 0,
1551 "content_block": {"type": "thinking", "thinking": "", "signature": ""},
1552 }
1553 ),
1554 ev(
1555 {
1556 "type": "content_block_delta",
1557 "index": 0,
1558 "delta": {"type": "thinking_delta", "thinking": "hmm"},
1559 }
1560 ),
1561 ev({"type": "content_block_stop", "index": 0}),
1562 refusal_delta(),
1563 ev({"type": "message_stop"}),
1564 ]
1565 )
1566 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(stream_a), sse_response(STREAM_B)])
1567 client = make_sync_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1568
1569 collect(create_stream(client))
1570
1571 body_b = request_bodies(respx_mock)[1]
1572 assert body_b["fallback_credit_token"] == redeemed_token("tok_abc")
1573 assert body_b["messages"] == PARAMS["messages"]
1574
1575
1576 # --- async ------------------------------------------------------------------
1577
1578
1579 class TestAsyncSplicing:
1580 @pytest.mark.respx(base_url=base_url)
1581 async def test_splices_the_fallback_onto_the_refused_stream(self, respx_mock: MockRouter) -> None:
1582 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(STREAM_B)])
1583 client = make_async_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1584
1585 state = BetaFallbackState()
1586 with state:
1587 stream = await create_stream_async(client)
1588 events: List[BetaRawMessageStreamEvent] = [event async for event in stream]
1589
1590 assert block_starts(events) == [
1591 (0, "thinking"),
1592 (1, "text"),
1593 (2, "fallback"),
1594 (3, "text"),
1595 ]
1596 assert len([e for e in events if e.type == "message_start"]) == 1
1597 assert len([e for e in events if e.type == "message_stop"]) == 1
1598 delta = next(e for e in events if e.type == "message_delta")
1599 assert delta.delta.stop_reason == "end_turn"
1600 assert [(i.type, i.model) for i in (delta.usage.iterations or [])] == [ # type: ignore[union-attr]
1601 ("message", "claude-fable-5"),
1602 ("fallback_message", FALLBACK_MODEL),
1603 ]
1604 assert state.index == 0
1605
1606 bodies = request_bodies(respx_mock)
1607 assert bodies[1]["model"] == FALLBACK_MODEL
1608 assert isinstance(bodies[1]["fallback_credit_token"], dict)
1609 assert bodies[1]["fallback_credit_token"]["mode"] == "best_effort"
1610 appended = bodies[1]["messages"][1]
1611 assert appended["role"] == "assistant"
1612 assert [block["type"] for block in appended["content"]] == ["thinking", "text"]
1613
1614 @pytest.mark.respx(base_url=base_url)
1615 async def test_the_suppressed_starts_input_transformations_are_forwarded_on_the_terminal(
1616 self, respx_mock: MockRouter
1617 ) -> None:
1618 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A), sse_response(transforming_stream())])
1619 client = make_async_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1620
1621 stream = await create_stream_async(client)
1622 events: List[BetaRawMessageStreamEvent] = [event async for event in stream]
1623
1624 delta = next(e for e in events if e.type == "message_delta")
1625 assert delta.to_dict()["input_transformations"] == TRANSFORMS
1626
1627 @pytest.mark.respx(base_url=base_url)
1628 async def test_a_refused_hop_splices_its_partial_and_chains_to_the_next_entry(self, respx_mock: MockRouter) -> None:
1629 respx_mock.post("/v1/messages").mock(
1630 side_effect=[sse_response(STREAM_A), sse_response(hop_refusal()), sse_response(STREAM_B)]
1631 )
1632 client = make_async_client(middleware=[BetaRefusalFallbackMiddleware(TWO_FALLBACKS)])
1633
1634 stream = await create_stream_async(client)
1635 events: List[BetaRawMessageStreamEvent] = [event async for event in stream]
1636
1637 assert block_starts(events) == [
1638 (0, "thinking"),
1639 (1, "text"),
1640 (2, "fallback"),
1641 (3, "text"),
1642 (4, "fallback"),
1643 (5, "text"),
1644 ]
1645 deltas = [e for e in events if e.type == "message_delta"]
1646 assert len(deltas) == 1
1647 assert [(i.type, i.model) for i in (deltas[0].usage.iterations or [])] == [ # type: ignore[union-attr]
1648 ("message", "claude-fable-5"),
1649 ("message", FALLBACK_MODEL),
1650 ("fallback_message", SECOND_MODEL),
1651 ]
1652 bodies = request_bodies(respx_mock)
1653 assert bodies[2]["fallback_credit_token"] == redeemed_token("tok_b")
1654
1655 @pytest.mark.respx(base_url=base_url)
1656 async def test_closing_the_stream_mid_passthrough_tears_down_without_a_fallback_request(
1657 self, respx_mock: MockRouter
1658 ) -> None:
1659 respx_mock.post("/v1/messages").mock(side_effect=[sse_response(STREAM_A)])
1660 client = make_async_client(middleware=[BetaRefusalFallbackMiddleware(FALLBACKS)])
1661
1662 stream = await create_stream_async(client)
1663 seen = 0
1664 async for _event in stream:
1665 seen += 1
1666 if seen == 2:
1667 break
1668 await stream.close()
1669
1670 assert len(respx_mock.calls) == 1