Fall back on stream errors raised before the first event in `FallbackModel`

Merged
DO
2mo ago
+277-28

FallbackModel.request_stream used to hand a candidate's stream over as soon as its request_stream() context was entered. Some providers accept a streamed request and only then report a failure, before any output:

  • an OpenAI Responses (or Codex) stream that sends response.created, maybe response.in_progress, and then response.failed (server_is_overloaded) (#10123)
  • a Bedrock ConverseStream whose first event is a throttlingException (or another error event), since BedrockConverseModel.request_stream yields before reading anything (#10364)
  • an OpenRouter chunk with null choices and no error envelope, which test_openrouter_null_choices_streaming_does_not_trigger_fallback had pinned as not falling back

In each case the ModelAPIError was raised while the caller consumed the stream. By then fallback was no longer possible, even though the caller hadn't seen any output.

FallbackModel now waits for each candidate's stream to produce its first event before handing it over, both for the fallback chain and for a pinned continuation. An error raised before that first event is raised inside the candidate's own stream context and goes through the usual fallback_on handling, so it is recorded in failed_attempts and its attempt span, and a pinned continuation rewinds. The first event is then replayed, so the consumer sees the same stream. Provider events that produce no ModelResponseStreamEvent (response.created, in_progress, an empty chunk) don't count as output. The first PartStartEvent does. Errors after that still propagate, and a stream that ends without any event is accepted as it was before. Models used without FallbackModel are unchanged.

This fixes both issues for every provider without per-adapter peeking, so BedrockConverseModel itself is unchanged.

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
  • PR title is fit for the release changelog.

šŸ¤– Generated with Claude Code