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