Skip to content

Studio: fix mid-stream stall watchdog so a stalled generation times out in ~2 min not ~20 min - #7002

Closed
oobabooga wants to merge 4 commits into
unslothai:mainfrom
oobabooga:stream-stall-watchdog
Closed

oobabooga wants to merge 4 commits into
unslothai:mainfrom
oobabooga:stream-stall-watchdog

Conversation

@oobabooga

Copy link
Copy Markdown
Member

When a GGUF generation goes quiet mid-response (for example the context window fills up), the chat stays stuck on "running" for about 20 minutes before anything happens, and Stop does nothing in the meantime. Reported on Discord: a reply stopped mid-sentence and the button sat running for 30 minutes.

There is supposed to be a safeguard here: if a stream produces nothing for 2 minutes, give up and show an error. It never actually fired, so any mid-stream stall hung for the full ~20 minute first-token budget instead.

Fix

  • A stalled generation now ends after ~2 minutes with a clear error, and the UI leaves "running" instead of hanging.
  • Applies to both the local chat UI and the OpenAI/Anthropic compatible API streams.
  • A slow prefill still gets the full ~20 minutes to produce its first token, so nothing legitimate is cut short.
  • A slow or backgrounded client no longer counts against the 2 minute window, so a laggy tab can't falsely kill a healthy generation.
  • The browser has its own backstop too, so the UI can recover even if the backend never sends a final event.

Verification

Added regression tests that run a real stream which sends one token then goes silent, and confirm the generation now stops at the 2 minute mark instead of 20. Added tests that a client pausing longer than the stall window does not trip it. Confirmed these fail on the old code and pass now. Existing streaming and passthrough suites stay green, and the frontend typecheck is clean.

@oobabooga
oobabooga requested a review from danielhanchen as a code owner July 9, 2026 01:46

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request addresses an issue where mid-stream stalls cannot be caught by lowering the httpx read timeout mid-stream due to httpcore binding the timeout once at the start of body iteration. To resolve this, a background watchdog thread is introduced in the synchronous llama_cpp backend to monitor elapsed time and close active sockets if a stall occurs. In the asynchronous routes, an asyncio cancel scope is used to enforce the stall window. Additionally, a client-side inactivity timeout is added to the frontend as a backstop, and a comprehensive test suite is introduced. The reviewer identified a critical bug in the watchdog implementation where httpx.ReadTimeout exceptions (triggered by the client's default 0.5s read timeout) are immediately re-raised instead of being ignored/continued, which would prematurely crash healthy streams.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment on lines +8362 to +8377
except (httpx.RequestError, httpx.StreamError) as exc:
# The watchdog (or a cancel) closes the response to abort a
# blocked read: a watchdog close is the stall/first-token
# timeout, a cancel close is a clean stop, and anything else
# is a genuine upstream error that must propagate.
if watch_state["timed_out"]:
if watch_state["got_first_chunk"]:
raise httpx.ReadTimeout(
"The model stopped producing tokens mid-response."
) from exc
raise httpx.ReadTimeout(
"The model did not produce a first token in time."
) from exc
if cancel_event is not None and cancel_event.is_set():
return
raise

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.

critical

The client's default read timeout is set to 0.5 seconds in _open_stream. In the previous implementation, _iter_text_cancellable caught httpx.ReadTimeout and continued/retried the read, using the 0.5s timeout as a polling interval.

However, the new implementation catches httpx.RequestError (which includes httpx.ReadTimeout) and immediately re-raises it if watch_state["timed_out"] is False. This means any read that takes longer than 0.5 seconds (such as during prefill or normal token generation) will raise a httpx.ReadTimeout and immediately crash the stream, rather than waiting for the watchdog thread's 2-minute or 20-minute deadlines.

To fix this, we should explicitly check if the caught exception is a httpx.ReadTimeout and continue the loop if the watchdog has not timed out yet.

Suggested change
except (httpx.RequestError, httpx.StreamError) as exc:
# The watchdog (or a cancel) closes the response to abort a
# blocked read: a watchdog close is the stall/first-token
# timeout, a cancel close is a clean stop, and anything else
# is a genuine upstream error that must propagate.
if watch_state["timed_out"]:
if watch_state["got_first_chunk"]:
raise httpx.ReadTimeout(
"The model stopped producing tokens mid-response."
) from exc
raise httpx.ReadTimeout(
"The model did not produce a first token in time."
) from exc
if cancel_event is not None and cancel_event.is_set():
return
raise
except (httpx.RequestError, httpx.StreamError) as exc:
# The watchdog (or a cancel) closes the response to abort a
# blocked read: a watchdog close is the stall/first-token
# timeout, a cancel close is a clean stop, and anything else
# is a genuine upstream error that must propagate.
if watch_state["timed_out"]:
if watch_state["got_first_chunk"]:
raise httpx.ReadTimeout(
"The model stopped producing tokens mid-response."
) from exc
raise httpx.ReadTimeout(
"The model did not produce a first token in time."
) from exc
if cancel_event is not None and cancel_event.is_set():
return
if isinstance(exc, httpx.ReadTimeout):
continue
raise

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The client-default read=0.5 is never in effect here: the per-request timeout= passed to client.stream() overrides the client default (httpx USE_CLIENT_DEFAULT semantics; httpcore's _receive_response_body reads timeouts from request.extensions["timeout"], bound once per request), and the real per-request read timeout mirrors prefill_timeout (~1200s). Verified empirically against a live slow-streaming server (a 2s gap did not raise ReadTimeout under a 10s per-request timeout with a 0.5s client default) plus the PR's own test suite (6/6 pass). Applying the suggested catch-and-continue would also reset reading_since on every retry, silently disabling the stall watchdog this PR adds.

@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 9e1c1cbb46

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: b3e7e3fd78

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member Author

Closing this in favor of a narrower fix (#7117).

The diagnosis here is right: the 2 min mid-stream stall guard never fires, because httpcore binds the read timeout once when body iteration starts, so lowering it mid-stream is a no-op and a stall hangs for the full ~20 min first-token budget.

The problem is the remedy. It adds an automatic 2 min kill window, but over the socket a wedged model and a slow one are indistinguishable: both are silence. So this is a pure threshold bet. 2 min cuts short exactly the slow-hardware case we cater to (big MoE models mmap'd off SSD, minutes per token), and the cost is asymmetric: a false kill throws away an hours-long run, while a true stall only surfaces late. The env override also doesn't cover the local chat path.

The real sting in the report was that Stop did nothing during the stall. #7117 fixes just that: the cancel watcher now shuts the socket down so Stop interrupts a blocked mid-stream read immediately, and the person watching decides when to give up. No auto-kill, so nothing slow gets cut off.

@oobabooga oobabooga closed this Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant