Skip to content

Studio: keep health checks responsive during Anthropic generation - #9201

Merged
oobabooga merged 4 commits into
unslothai:mainfrom
Imagineer99:fix/studio-anthropic-nonstreaming-liveness
Aug 19, 2026
Merged

oobabooga merged 4 commits into
unslothai:mainfrom
Imagineer99:fix/studio-anthropic-nonstreaming-liveness

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

Summary

  • drain non-streaming Anthropic generators with asyncio.to_thread
  • await the shared collector from both plain and tool-calling paths
  • add regression coverage that verifies generation runs off the event-loop thread

Root cause

The async Anthropic request handlers synchronously called list(run_gen()). Slow local GGUF generations therefore blocked the FastAPI event loop, preventing the desktop watchdog from receiving /api/liveness or /api/health responses.

Validation

  • python -m pytest -q studio/backend/tests/test_anthropic_messages.py — 140 passed
  • python -m ruff check studio/backend/routes/inference.py studio/backend/tests/test_anthropic_messages.py
  • Live local-model A/B with Qwen3 1.7B GGUF, CPU-only, stream=false, 512 output tokens:
    • base: 41.93s request; both health routes timed out 4 times at the watchdog's 10s probe budget
    • fix: 41.20s request; 82/82 probes succeeded, with 24ms maximum latency
    • both generations completed with HTTP 200 and the same response size

Fixes #8916

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits studio/backend/routes/inference.py where _collect_anthropic_events still drains the generator on the event loop, so long non-streaming /v1/messages calls stall the health endpoint and the watchdog kills the backend. Will get this reviewed.

@mahiatlinux

Copy link
Copy Markdown
Contributor

studio/backend/routes/inference.py:20783 the tool path still blocks the event loop, for longer than the watchdog tolerates

The drain moved off the loop but the reduction that consumes events did not. That loop calls _strip_tool_xml_for_display(event["text"], ...) once per content event, and generate_chat_completion_with_tools yields one cumulative string per token (core/inference/llama_cpp.py:22767, :22711, :22744). The strip therefore rescans a linearly growing string N times: quadratic, and now concentrated into one uninterrupted synchronous block after the drain returns.

Measured against the shipped helper, event shape matching the generator, with a 5 ms heartbeat task on the same loop:

answer loop blocked heartbeat ticks during the block
512 tokens (2 KB) 0.04 s 0
4000 tokens (15 KB) 2.45 s 0
8000 tokens (31 KB) 9.70 s 0
16000 tokens (62 KB) 39.16 s 0
32000 tokens (125 KB) 161.16 s 0

cProfile at 4000 events: 5.201 s of 5.211 s total in _strip_tool_xml_for_display into core/tool_healing.py:1176 strip_outside_think.

/api/liveness (studio/backend/main.py:1577) and /api/health (main.py:1611) are async def on that loop, so they are unanswerable for the whole window. HEALTH_WATCHDOG_INTERVAL is 15 s, HEALTH_PROBE_TIMEOUT 10 s and HEALTH_WATCHDOG_MAX_FAILURES 3 (studio/src-tauri/src/commands.rs:10, :25, :11), so a long tool answer still walks the backend into stop_backend at commands.rs:1429. _anthropic_plain_non_streaming is unaffected: its cumulative[len(prev_text):] is linear and stays under 10 ms at every size above.

The streaming sibling does not have this because it interleaves each strip with await asyncio.to_thread(next, gen, _sentinel) (inference.py:20509), so the loop breathes between events.

Build content_blocks, usage and stop_reason inside _drain so the reduction runs on the worker thread too. Collapsing to one strip per turn is not equivalent: _strip_tool_xml_for_display is not monotone, and new = clean[len(prev_text):] depends on the per-event diff.

studio/backend/routes/inference.py:20724 the drain is no longer bounded by the shutdown join

asyncio.to_thread runs on the loop's default ThreadPoolExecutor, and concurrent.futures.thread._python_exit joins those threads unconditionally at interpreter exit. run.py runs uvicorn on a daemon thread (run.py:2636) and caps the join at _SERVER_SHUTDOWN_JOIN_TIMEOUT = 5.0 (run.py:1555) precisely "so a stuck uvicorn shutdown cannot hang the terminal". Putting the generation on a non-daemon executor thread removes that bound. inference.py:7995 already names this hazard.

Same 8 s blocking call, daemon thread and 5 s join in both cases:

join returns process exits
inline on the loop (before) 5.01 s 5.08 s
await asyncio.to_thread(...) (after) 0.20 s 8.07 s

_graceful_shutdown kills llama-server before it sets the shutdown event, so the plain path's socket read fails quickly. The server-tool path does not: the drain can be parked inside stream_tool_execution (core/inference/tool_stream_exec.py:209-221), which yields a heartbeat when cancel_event is set but does not break, and killing llama-server does not stop a running terminal, python, web or MCP tool. tool_call_timeout is 300 (inference.py:20365).

The same hunk also drops the three things the sibling non-streaming GGUF drain has at inference.py:14535-14541 and 14484-14497: asyncio.create_task plus asyncio.shield, a cancel handler that re-sets cancel_event and awaits the shielded task, and gen.close() in a finally so the llama-server stream socket is released. _drain_pending_next_task at inference.py:3173 states the rule this hunk breaks: cancelling the awaiting task does not stop the worker. When it is cancelled, _tracked_anthropic_non_streaming's _tracker.__exit__ and _admitted_anthropic's finally: lease.release() (inference.py:20229) both run while the worker is still holding llama-server.

studio/backend/tests/test_anthropic_messages.py:963 the regression test asserts a proxy, not the property it is named for

It checks which thread the generator ran on, not that the loop stayed responsive. Replacing the drain with

_t = threading.Thread(target = _drain)
_t.start()
_t.join()

keeps the generator off the loop thread and starves the loop completely, and tests/test_anthropic_messages.py is 140 passed. The first finding above is the same gap in production: the generator runs off the loop and the loop is still blocked for 39 s.

Assert the responsiveness directly. Have _run_gen sleep briefly before it yields, run a concurrent task that increments a counter on asyncio.sleep, and assert the counter moved across the call.

studio/backend/routes/inference.py:20719 the new hunk is not formatted by the repo's canonical formatter

scripts/run_ruff_format.py, the formatter .pre-commit-config.yaml pins as ruff-format-with-kwargs, wants a blank line between the docstring and def _drain():. Running it over the whole file produces exactly that one hunk and nothing else, so the drift is this hunk's.

Insert a blank line after line 20719.

studio/backend/routes/inference.py:16238 the same shape survives on /v1/chat/completions, so the class of bug is not closed

async def openai_chat_completions (inference.py:13151) drains synchronous generators inline on the event loop in three places: :16238 (for token in generate():, the non-streaming safetensors and MLX path), :16279 (the nudge retry in the same block) and :13597 (for chunk_text in audio_input_generate():). generate at :15982 and :15996 returns backend.generate_chat_response(...), which reaches core/inference/orchestrator.py:1916 _generate_inner, a sync generator holding self._gen_lock across the whole token stream.

The same handler's streaming arm already offloads and says why at inference.py:16031: "Run the sync generator in a worker thread so it can't block the event loop." stream defaults to false, so :16238 is the default shape for a non-GGUF chat, and it is reachable from /v1/responses (:17979, :18015) and from the public preview surface: routes/preview.py:174 calls the handler and _sanitize_preview_payload (preview.py:100) pins tools, n and the token ceiling but not stream.

The comment at inference.py:16231 says "generate() holds the worker throughout". There is no worker on that branch; it holds the loop.

@mahiatlinux
mahiatlinux self-requested a review August 19, 2026 09:46

@mahiatlinux mahiatlinux 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.

Review posted as a comment above.

@Imagineer99
Imagineer99 marked this pull request as ready for review August 19, 2026 14:42

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1e166e3b3b

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/routes/inference.py Outdated
return list(run_gen())

try:
return await asyncio.to_thread(_drain)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep the lease until the worker has drained

When an in-progress non-streaming request task is cancelled, cancelling this to_thread await does not stop the already-running worker. The resulting CancelledError propagates through _monitored_anthropic, which sets the cancellation flag, but _tracked_anthropic_non_streaming then unregisters the generation and _admitted_anthropic releases its admission lease before the generator has actually returned. A model swap or another admitted request can therefore proceed while the cancelled generator is still using llama-server or executing a tool. Create an explicit task, shield it, and on cancellation set the flag and drain the worker before unwinding, as the existing GGUF non-streaming paths do.

Useful? React with 👍 / 👎.

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.

Fixed in 8768498: cancellation now sets the generation flag and drains the shielded worker before tracker and admission teardown.

@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 8768498fb4

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 1558fed57b

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@oobabooga

Copy link
Copy Markdown
Member

This fixes the non-streaming /v1/messages event-loop starvation in #8916, with the live A/B reproducing watchdog probe timeouts on the synchronous path and keeping every health probe responsive with the fix. Thanks @mahiatlinux for catching the cancellation-lifetime issue and surfacing the additional reduction and sibling paths tracked for follow-up.

@oobabooga
oobabooga merged commit 92d3f87 into unslothai:main Aug 19, 2026
36 of 40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Studio Bug] Studio crashes when Claude Code takes too long to generate a response

4 participants