Repository navigation
Conversation
|
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. |
|
| 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
left a comment
There was a problem hiding this comment.
Review posted as a comment above.
There was a problem hiding this comment.
💡 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".
| return list(run_gen()) | ||
|
|
||
| try: | ||
| return await asyncio.to_thread(_drain) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
Fixed in 8768498: cancellation now sets the generation flag and drains the shielded worker before tracker and admission teardown.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
This fixes the non-streaming |
Summary
asyncio.to_threadRoot 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/livenessor/api/healthresponses.Validation
python -m pytest -q studio/backend/tests/test_anthropic_messages.py— 140 passedpython -m ruff check studio/backend/routes/inference.py studio/backend/tests/test_anthropic_messages.pystream=false, 512 output tokens:Fixes #8916