agents icon indicating copy to clipboard operation
agents copied to clipboard

FallbackAdapter attempt_timeout is a read (inter-byte) timeout, not time-to-first-token — a provider that stalls before its first token causes long dead air with no failover

Open ZaafirRizwan opened this issue 5 months ago • 4 comments

Bug Description

llm.FallbackAdapter(attempt_timeout=...) does not bound time-to-first-token — it ends up as an HTTP read (inter-byte) timeout, not a total or first-token budget.

If a provider accepts the request and keeps the SSE stream alive (periodic keep-alive frames, or a role-only delta with empty content) but never emits a real content/tool token, the read timeout is continually reset, no ChatChunk is ever produced, and the FallbackAdapter never fails over to the next provider. The turn hangs far beyond attempt_timeout (we saw ~60s, bounded only by the upstream's own timeout / the user hanging up), even though healthy fallback providers are configured — which defeats the purpose of the adapter.

Root cause chain:

  1. FallbackAdapter(attempt_timeout=5.0) → FallbackAdapterStream._try_generate passes it as conn_options.timeout.
  2. The OpenAI plugin applies it as timeout=httpx.Timeout(self._conn_options.timeout) on client.chat.completions.create(..., stream=True) (agents/inference/llm.py). A scalar httpx.Timeout is a per-read (inter-byte) timeout.
  3. The stream loop only forwards chunks with real content; empty/role-only/keep-alive frames yield no ChatChunk.

So a provider that trickles bytes without ever producing a token keeps the read timeout from firing, the attempt never raises, and _try_generate's except APIError/asyncio.TimeoutError failover path is never reached. (Proof it's a trickle and not a dead socket: a silent socket would trip the read timeout at attempt_timeout; in our case the request stayed open ~60s.)

Expected Behavior

If a provider produces no first token within the configured budget, the attempt should be aborted and FallbackAdapter should fail over to the next provider — instead of hanging indefinitely with no output. The adapter's core promise (route around a non-responsive provider) should hold even when the provider keeps the connection alive without emitting tokens.

Reproduction Steps

1. Start an OpenAI-compatible mock that emits a role chunk then trickles empty keep-alives forever (never a real token):


# mock_stall.py  — run on :8999
import asyncio, json, time
from aiohttp import web

async def chat(req):
    r = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
    await r.prepare(req)
    def sse(delta):
        return f'data: {json.dumps({"id":"x","object":"chat.completion.chunk","created":int(time.time()),"model":"m","choices":[{"index":0,"delta":delta,"finish_reason":None}]})}\n\n'.encode()
    await r.write(sse({"role": "assistant", "content": ""}))   # not a real token
    while True:                                                # keep-alive trickle, no content
        await asyncio.sleep(1.5); await r.write(sse({"content": ""}))
    return r

app = web.Application(); app.router.add_post("/v1/chat/completions", chat)
web.run_app(app, port=8999)

2. Put the stalling endpoint as the primary in a FallbackAdapter with a healthy fallback and a short attempt_timeout:

# repro.py
import asyncio
from livekit.agents import llm
from livekit.plugins import openai

async def main():
    stalling = openai.LLM(model="m", base_url="http://localhost:8999/v1", api_key="x")
    healthy  = openai.LLM(model="gpt-4o-mini")  # real OPENAI_API_KEY
    fb = llm.FallbackAdapter([stalling, healthy], attempt_timeout=5.0)
    async with fb.chat(chat_ctx=llm.ChatContext.empty()) as s:
        async for chunk in s:
            print(chunk)

asyncio.run(main())

3. Observe: nothing is printed for far longer than attempt_timeout=5s; the adapter never fails over to healthy. Expected: failover within ~5s and a response from healthy.

Operating System

Windows 11 (platform-independent — the behavior is in the async/HTTP layer, not OS-specific)

Models Used

LLM: OpenAI-compatible endpoint (originally observed with Azure OpenAI gpt-4.1 and an OpenAI-compatible proxy). STT/TTS not relevant — bug is in llm.FallbackAdapter.

Package Versions

livekit==1.1.8
livekit-agents==1.5.12
livekit-api==1.1.0
livekit-plugins-openai==1.5.12
livekit-protocol==1.1.15

Session/Room/Call IDs

N/A — fully reproducible locally with the snippet above; not tied to a LiveKit Cloud session.

Proposed Solution

### Proposed Solution

Bound time-to-first-token per attempt inside `FallbackAdapterStream._try_generate`: wrap the wait for the first real chunk in `asyncio.timeout(...)` and raise a retryable `APITimeoutError` on expiry, so the existing `except APIError` path fails over. Two options:

- (a) Reuse `attempt_timeout` as a first-token deadline (pure behavior fix, but changes timing for existing users), or
- (b) Add an opt-in `first_token_timeout: float | None = None` param so default behavior is unchanged.

I'd lean toward (b) for backward-compat. The guard should disarm after the first real token (content **or** tool-call delta) so mid-stream behavior is untouched, and close the inner stream on timeout to release the hung connection. Happy to open a PR once a maintainer confirms the preferred option (a vs b).

Additional Context

No response

Screenshots and Recordings

No response

ZaafirRizwan avatar Jun 20 '26 12:06 ZaafirRizwan

With timeout, the risk is a single provider going down with no circuit breaker.

npx ai-api-check@latest --json

Audits your provider integrations for missing circuit breakers and health endpoints.

michaeltahu12 avatar Jun 20 '26 12:06 michaeltahu12

Hi, I'd like to work on this. I'll submit a PR shortly.

nightcityblade avatar Jun 20 '26 15:06 nightcityblade

With timeout, the risk is a single provider going down with no circuit breaker.

npx ai-api-check@latest --json Audits your provider integrations for missing circuit breakers and health endpoints.

Good call-out on the breaker, though FallbackAdapter already has one: a failed attempt flips that provider's _status.available to False and kicks off a background recovery probe, so after the first stall the provider is skipped entirely until it recovers, rather than paying the timeout on every request. The first-token timeout just feeds that existing mechanism — it raises a retryable error, which marks the provider down. So it's "a timeout that trips the breaker," not "a timeout instead of one."

ZaafirRizwan avatar Jun 20 '26 16:06 ZaafirRizwan

We hit this in production. Our case adds one detail: the slow attempt was the last provider in the chain, so the adapter had nothing left to fail over to.

Setup: llm.FallbackAdapter with the default attempt_timeout` (5 s) and livekit inference as primary and openrouter model of the same LLM as fallback. The turn was a tool-calling turn with about 19k input tokens.

Timeline for one user turn (from our logs):

  • Primary (LiveKit Inference): failed with "Request timed out" after about 5.1 s. The read timeout fired as documented, and failover started.
  • OpenRouter fallback: first chunk arrived after 10.8 s. The response then completed normally with a tool call.
  • Background recovery probe to the primary: succeeded after about 3.8 s.
  • The agent was silent for about 11 s before playback started.

Why the 10.8 s wasn't caught: the 5 s read timeout should fire if no bytes arrive for 5 s. It didn't. One explanation consistent with that is that the stream carried SSE keepalive comments (OpenRouter's streaming docs describe : OPENROUTER PROCESSING comments sent "to prevent connection timeouts"). Comments would reset the read timer without producing a ChatChunk. We haven't verified this for this request, because the generation record isn't available to us, so treat it as an inference from the timing.

Why a first-token deadline would help:

  • attempt_timeout reads as a per-attempt budget, so users will expect a 5 s bound. The 10.8 s attempt ran past it without an error.
  • In our chain, a first-token deadline would have failed the OpenRouter attempt at 5 s. With no next provider, that alone only turns the wait into an error. With a third provider, it would have produced a reply about 5 s sooner.

bml1g12 avatar Nov 19 '26 15:11 bml1g12