Skip to content

feat(llm): add first_token_timeout to FallbackAdapter - #8691

Merged
longcw merged 2 commits into
mainfrom
longc/fallback-first-token-timeout
Nov 26, 2026
Merged

longcw merged 2 commits into
mainfrom
longc/fallback-first-token-timeout

Conversation

@longcw

@longcw longcw commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

llm.FallbackAdapter fails over when an attempt errors, and attempt_timeout is the only time limit on an attempt. The OpenAI-compatible plugins pass that value to httpx as a read timeout, so any bytes reset it: SSE keep-alive comments such as OpenRouter's : OPENROUTER PROCESSING, a role-only first delta, or reasoning deltas that _parse_choice drops. A provider can hold an attempt open far past attempt_timeout with no ChatChunk, and the caller hears silence instead of the next provider.

attempt_timeout cannot carry this limit, because each plugin gives conn_options.timeout its own meaning: a read timeout in the OpenAI-compatible plugins, a total deadline in Google.

first_token_timeout sets a deadline from the start of each attempt to its first chunk with text or a tool call. When the deadline expires, the attempt raises asyncio.TimeoutError and the adapter fails over as it does for any other failed attempt.

Why it is a separate argument that defaults to off:

llm.FallbackAdapter([primary, fallback], first_token_timeout=4.0)

The value is in seconds, and it covers the internal retries of one attempt.

Fixes #6171. Alternative to #6173. Related to #6916.

Context for reviewing and coding agents

How to see it

test_first_token_timeout[stalled] in tests/test_llm_fallback.py fails on main when first_token_timeout is replaced with attempt_timeout: the primary sends a usage-only chunk each second, and the response never comes from the fallback. The [answered] case asserts that keep-alives after the first token do not cause a failover. The live repro is mock_stall.py in #6171.

Blast radius

The deadline lives in FallbackLLMStream._try_generate (llm/fallback_adapter.py:224). Its two callers are the serving loop in _run (llm/fallback_adapter.py:366) and the recovery probe in _try_recovery (llm/fallback_adapter.py:335). The STT, TTS and realtime fallback adapters are not changed.

Why not #6173

#6173 reuses attempt_timeout as the first-chunk deadline, so the 10.8 s fallback in #6171 would fail at 5 s and the whole request would error. It also stops the clock on any chunk, including usage-only chunks, and it conflicts with the current _try_generate.

Open design question

#6916 asks for a separate fallback_attempt_timeout for providers after the first. The two arguments should be decided together, so the constructor does not get overlapping timeout settings.

attempt_timeout reaches the OpenAI-compatible plugins as an httpx read
timeout, so SSE keep-alives and deltas that produce no ChatChunk keep an
attempt open with no output and no failover. first_token_timeout bounds
the time from the start of an attempt to its first chunk with text or a
tool call, and fails over when it expires. It defaults to None.
@longcw
longcw requested a review from a team as a code owner November 20, 2026 02:55

@devin-ai-integration devin-ai-integration Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

βœ… Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

@moz164164

moz164164 commented Nov 20, 2026 •

Copy link
Copy Markdown

@longcw
I find this PR only apply to llm. How about tts and stt FallbackAdapter? Do they have the same problem?

@longcw

longcw commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@longcw I find this PR only apply to llm. How about tts and stt FallbackAdapter? Do they have the same problem?

no, STT has no "first token" to wait for. in streaming TTS, how long the first audio takes depends on when the LLM sends text. A timer that starts with the attempt would fire whenever the LLM is slow. The timer would have to start at the first text sent or the first flush, so it's a different mechanism, not a copy of this one.

@chenghao-mou chenghao-mou left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

else:
# keep-alives reset the provider's read timeout, so bound the
# wait for the first output here
chunk = await asyncio.wait_for(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit from Codex:

python/cpython#86296 On Python 3.10 and 3.11, wait_for() can swallow cancellation if the chunk read has already completed when wait_for() handles the cancellation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real on 3.10/3.11, and it matters here: an interrupt before the first token is common (barge-in, preemptive generation), and a dropped cancel holds the speech until the 5 s interruption timeout.

Switched to a timeout scope ( asyncio.timeout_at ,  async_timeout  on 3.10)

asyncio.wait_for drops a cancel on Python 3.10 and 3.11 when the
awaited read finishes in the same loop iteration (cpython#86296). An
interrupt before the first token then leaves the fallback stream
reading the provider, which holds the speech until the interruption
timeout. A timeout scope runs in the reading task and keeps the cancel.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 new potential issues.

1 flag not posted on this PR by your GitHub settings β€” view it in Devin Review. (Configure)

Devin Review

Comment on lines +274 to +275
async with timeout_at(deadline):
chunk = await stream.__anext__()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 Lost stream cancellation on Python 3.10

When stream closure cancels the task after the timer fires but before it resumes, timeout_at swallows the cancellation. Closing the stream then waits while the adapter starts another model request.

Learn more

Closing an LLM stream calls LLMStream.aclose, which cancels its generation task and waits. On Python 3.10, the imported async-timeout scope cancels that same task when its deadline expires. If closure also cancels the task before it resumes, the scope sees its own expired state and converts the cancellation into TimeoutError. The serving loop handles that as a provider failure and keeps going while closure waits.

Example: A voice turn stops while the primary is still waiting for its first token. In one event-loop iteration the deadline cancels the task, then stream closure cancels it before it resumes. The adapter starts a fallback request instead of stopping.

Recommended fix: On Python 3.10, isolate the read in a child task and use asyncio.wait with the remaining deadline. Cancel and drain the child on timeout or external cancellation, and let an external CancelledError propagate. Test with both cancellation callbacks queued before the waiting task resumes.

Devin Review


Was this helpful? React with πŸ‘ or πŸ‘Ž to provide feedback.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, but only on 3.10 (async-timeout can't tell its own cancel from an outside one; 3.11+  asyncio.timeout_at  uses  uncancel()  and keeps it). It needs the cancel and the deadline in the same loop iteration.

3.10 is EOL, so I'd not adding a separate child-task path for it.

Comment on lines +274 to +275
async with timeout_at(deadline):
chunk = await stream.__anext__()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟑 Buffered output bypasses expired deadline

After the deadline expires, timeout_at can still accept a buffered first token. The read returns without yielding, so the adapter serves the late attempt instead of failing over.

Learn more

Both timeout implementations schedule a cancellation for a later event-loop turn when entered with an expired deadline. A read from LLMStream.anext can return immediately because tee_peer and the stream channel consume queued chunks without waiting. The scope exits before its cancellation runs. When that chunk contains text or a tool call, the adapter clears the deadline and commits to the provider.

Example: The adapter receives a metadata-only chunk just as the deadline comes due. On the next read the deadline has already passed, but a text chunk is queued and the read completes synchronously. The adapter accepts the text rather than treating the attempt as timed out.

Recommended fix: Check the monotonic clock before starting each pre-output read. Raise the same timeout the fallback loop already handles when no time remains, and keep the timeout scope for reads that need to wait.

Suggested change
async with timeout_at(deadline):
chunk = await stream.__anext__()
if asyncio.get_running_loop().time() >= deadline:
raise asyncio.TimeoutError
async with timeout_at(deadline):
chunk = await stream.__anext__()

Devin Review


Was this helpful? React with πŸ‘ or πŸ‘Ž to provide feedback.

@longcw
longcw merged commit d4fb363 into main Nov 26, 2026
25 of 26 checks passed
@longcw
longcw deleted the longc/fallback-first-token-timeout branch November 26, 2026 03:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants