# Failover when an LLM error arrives inside a 200 SSE stream

Treat the HTTP 200 only as the transport handshake, not as a successful completion. A proxy can return 200 and later send an error event or an error JSON object inside the stream.

## Commit and retry rule

Classify the stream at the point where an error is observed:

- **Before any model content has been exposed to the caller:** the attempt is uncommitted. Close that upstream, then try the next provider/model with a fresh request and a fresh attempt timeout. Retrying a 200-with-stream-error at this point is valid.
- **After model content has been exposed:** do not blindly replay. Replaying can duplicate tokens or produce a mixed answer from two models. Either report the upstream failure with `partial=true`, or abort the whole response and start a clean new response only if the API contract explicitly allows replacement and all previous buffered content is discarded. Never concatenate the partial text from the failed attempt with the next model's text.
- **Non-retryable application errors:** a 400 validation error, authentication failure, unsupported model, or malformed request should return immediately, not consume every fallback provider. Retry only timeouts, connection failures, rate limits/5xx, or stream failures covered by the commit rule.

For an API that only supports non-destructive completion, the safe contract is simple: retry only before the first visible content; after that, surface the partial-output failure instead of silently mixing providers.

## Cancellation and buffering

- Use a separate `AbortController` and time-to-first-token timeout for every upstream attempt.
- On error or timeout, cancel the reader, close the upstream body, and clear per-attempt buffers before the next attempt.
- Keep global deadline and per-attempt deadline separate; fallback must not extend the caller's total deadline indefinitely.
- Do not convert an upstream stream error into a normal `[DONE]` event. Preserve it as an error with the partial-output flag and cause.

## Verification

The independent reproduction in this directory passes six Node 22 cases:

1. Error after HTTP 200 before content: failover to the next model.
2. Role-only SSE delta: still uncommitted, so retry is allowed.
3. TTFT timeout: cancel and fail over.
4. Non-retryable HTTP 400: return the error without trying another model.
5. Content already committed: no replay and no duplicated output.
6. Last-model failure: return the original stream error instead of a false success.

That is the complete decision boundary: **HTTP status controls transport; visible content controls replay safety.**
