Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: run /generate/stream's sync generator off the event loop to avoid blocking it (#6466)

Parvesh Saini17e9714a98a3
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b3f112a944f..4b068941b8d 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3127,9 +3127,13 @@ async def generate_stream(
log = logger,
)
+ cancel_event = threading.Event()
+
async def stream():
+ gen = None
+ completed = False
try:
- for chunk in backend.generate_chat_response(
+ gen = backend.generate_chat_response(
messages = request.messages,
system_prompt = request.system_prompt,
image = image,
@@ -3138,14 +3142,35 @@ async def generate_stream(
top_k = request.top_k,
max_new_tokens = request.max_new_tokens,
repetition_penalty = request.repetition_penalty,
- ):
+ cancel_event = cancel_event,
+ )
+ _DONE = object()
+ while True:
+ chunk = await asyncio.to_thread(next, gen, _DONE)
+ if chunk is _DONE:
+ break
yield f"data: {json.dumps({'content': chunk})}\n\n"
+ completed = True
yield "data: [DONE]\n\n"
+ except asyncio.CancelledError:
+ cancel_event.set()
+ backend.reset_generation_state()
+ raise
except Exception as e:
+ cancel_event.set()
backend.reset_generation_state()
logger.error(f"Error during generation: {e}", exc_info = True)
yield f"data: {json.dumps({'error': _friendly_error(e)})}\n\n"
+ finally:
+ if not completed and not cancel_event.is_set():
+ cancel_event.set()
+ backend.reset_generation_state()
+ if gen is not None:
+ try:
+ await asyncio.to_thread(gen.close)
+ except (RuntimeError, ValueError):
+ pass
return StreamingResponse(
stream(),
diff --git a/tests/studio/test_stream_cancel_registration_timing.py b/tests/studio/test_stream_cancel_registration_timing.py
index 8d12fd528e8..2e6b5f14da8 100644
--- a/tests/studio/test_stream_cancel_registration_timing.py
+++ b/tests/studio/test_stream_cancel_registration_timing.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import ast
import asyncio
+import json
import threading
import time
from pathlib import Path
@@ -453,6 +454,147 @@ def test_audio_input_stream_offloads_blocking_next_to_thread():
)
+def test_generate_stream_offloads_blocking_next_to_thread():
+ outer = None
+ for fn in ast.walk(_TREE):
+ if isinstance(fn, ast.AsyncFunctionDef) and fn.name == "generate_stream":
+ outer = fn
+ break
+ assert outer is not None, "generate_stream handler missing"
+
+ inner = None
+ for sub in ast.walk(outer):
+ if isinstance(sub, ast.AsyncFunctionDef) and sub.name == "stream":
+ inner = sub
+ break
+ assert inner is not None, "generate_stream inner stream() generator missing"
+
+ for sub in ast.walk(inner):
+ if isinstance(sub, (ast.For, ast.AsyncFor)):
+ it_src = ast.unparse(sub.iter)
+ assert "generate_chat_response" not in it_src, (
+ "generate_stream's inner stream() must not iterate "
+ "backend.generate_chat_response() directly -- that blocks the event "
+ "loop on every blocking subprocess read between tokens. Use "
+ "`await asyncio.to_thread(next, gen, _DONE)` inside a `while True` "
+ "loop instead"
+ )
+
+ found_to_thread_next = False
+ for sub in ast.walk(inner):
+ if not isinstance(sub, ast.Call):
+ continue
+ fn_expr = sub.func
+ if not (
+ isinstance(fn_expr, ast.Attribute)
+ and fn_expr.attr == "to_thread"
+ and isinstance(fn_expr.value, ast.Name)
+ and fn_expr.value.id == "asyncio"
+ ):
+ continue
+ if sub.args and isinstance(sub.args[0], ast.Name) and sub.args[0].id == "next":
+ found_to_thread_next = True
+ break
+ assert found_to_thread_next, (
+ "generate_stream's inner stream() must call "
+ "`asyncio.to_thread(next, gen, _DONE)` to keep the event loop free while the "
+ "worker subprocess produces the next token"
+ )
+
+
+def test_generate_stream_cancels_backend_on_stream_cancelled_error():
+ outer = None
+ for fn in ast.walk(_TREE):
+ if isinstance(fn, ast.AsyncFunctionDef) and fn.name == "generate_stream":
+ outer = fn
+ break
+ assert outer is not None, "generate_stream handler missing"
+
+ outer_src = ast.unparse(outer)
+ assert "cancel_event = threading.Event()" in outer_src
+
+ inner = None
+ for sub in ast.walk(outer):
+ if isinstance(sub, ast.AsyncFunctionDef) and sub.name == "stream":
+ inner = sub
+ break
+ assert inner is not None, "generate_stream inner stream() generator missing"
+
+ def _awaits_to_thread_gen_close(node: ast.AST) -> bool:
+ for sub in ast.walk(node):
+ if not isinstance(sub, ast.Await):
+ continue
+ call = sub.value
+ if not isinstance(call, ast.Call):
+ continue
+ fn_expr = call.func
+ if not (
+ isinstance(fn_expr, ast.Attribute)
+ and fn_expr.attr == "to_thread"
+ and isinstance(fn_expr.value, ast.Name)
+ and fn_expr.value.id == "asyncio"
+ ):
+ continue
+ if not call.args:
+ continue
+ close_expr = call.args[0]
+ if (
+ isinstance(close_expr, ast.Attribute)
+ and close_expr.attr == "close"
+ and isinstance(close_expr.value, ast.Name)
+ and close_expr.value.id == "gen"
+ ):
+ return True
+ return False
+
+ found_cancel_kwarg = False
+ found_cancel_handler = False
+ found_finally_cleanup = False
+ for sub in ast.walk(inner):
+ if isinstance(sub, ast.Call):
+ call_src = ast.unparse(sub.func)
+ if call_src.endswith("generate_chat_response"):
+ found_cancel_kwarg = any(
+ kw.arg == "cancel_event"
+ and isinstance(kw.value, ast.Name)
+ and kw.value.id == "cancel_event"
+ for kw in sub.keywords
+ )
+ if isinstance(sub, ast.ExceptHandler):
+ exc_src = ast.unparse(sub.type) if sub.type is not None else ""
+ if exc_src != "asyncio.CancelledError":
+ continue
+ body_src = "\n".join(ast.unparse(stmt) for stmt in sub.body)
+ found_cancel_handler = (
+ "cancel_event.set()" in body_src
+ and "backend.reset_generation_state()" in body_src
+ and any(isinstance(stmt, ast.Raise) and stmt.exc is None for stmt in sub.body)
+ )
+ if isinstance(sub, ast.Try) and sub.finalbody:
+ final_src = "\n".join(ast.unparse(stmt) for stmt in sub.finalbody)
+ found_finally_cleanup = (
+ "not completed" in final_src
+ and "not cancel_event.is_set()" in final_src
+ and "cancel_event.set()" in final_src
+ and "backend.reset_generation_state()" in final_src
+ and _awaits_to_thread_gen_close(sub)
+ )
+
+ assert found_cancel_kwarg, (
+ "generate_stream must pass cancel_event into backend.generate_chat_response "
+ "so cancelled streams can stop backend generation"
+ )
+ assert found_cancel_handler, (
+ "generate_stream must catch asyncio.CancelledError, set cancel_event, "
+ "reset backend state, and re-raise"
+ )
+ assert found_finally_cleanup, (
+ "generate_stream cleanup must cancel/reset incomplete streams and "
+ "offload gen.close() with asyncio.to_thread so backend joins cannot "
+ "block the event loop"
+ )
+
+
def test_stream_chunks_cancel_branch_resets_backend_state():
# The cancel branch must call backend.reset_generation_state() to flush
# GPU/KV-cache state, else cancel-via-POST leaves the subprocess dirty.
@@ -542,6 +684,106 @@ def test_unsloth_stream_loop_breaks_on_external_cancel_event():
)
+def test_generate_stream_stays_responsive_under_blocking_next():
+ # Same sync-generator shape as generate_stream, with resp_queue.get modeled
+ # by sleep. The output must stay unchanged while next() moves off-loop.
+ chunks = ["alpha", "beta", "gamma", "delta"]
+
+ def _generate_chat_response():
+ for chunk in chunks:
+ time.sleep(0.08)
+ yield chunk
+
+ def _sse(chunk):
+ return f"data: {json.dumps({'content': chunk})}\n\n"
+
+ async def _direct_loop():
+ out = []
+ for chunk in _generate_chat_response():
+ out.append(_sse(chunk))
+ out.append("data: [DONE]\n\n")
+ return out
+
+ async def _to_thread_loop():
+ _DONE = object()
+ gen = _generate_chat_response()
+ out = []
+ try:
+ while True:
+ chunk = await asyncio.to_thread(next, gen, _DONE)
+ if chunk is _DONE:
+ break
+ out.append(_sse(chunk))
+ out.append("data: [DONE]\n\n")
+ return out
+ finally:
+ try:
+ gen.close()
+ except (RuntimeError, ValueError):
+ pass
+
+ async def _run_with_heartbeat(loop_coro):
+ ticks = 0
+ max_gap = 0.0
+
+ async def _heartbeat():
+ nonlocal ticks, max_gap
+ last = time.monotonic()
+ while True:
+ await asyncio.sleep(0.01)
+ now = time.monotonic()
+ max_gap = max(max_gap, now - last)
+ last = now
+ ticks += 1
+
+ heartbeat = asyncio.create_task(_heartbeat())
+ await asyncio.sleep(0)
+ try:
+ out = await loop_coro()
+ finally:
+ heartbeat.cancel()
+ try:
+ await heartbeat
+ except asyncio.CancelledError:
+ pass
+ return out, ticks, max_gap
+
+ async def _main():
+ direct_out, direct_ticks, direct_max_gap = await _run_with_heartbeat(_direct_loop)
+ threaded_out, threaded_ticks, threaded_max_gap = await _run_with_heartbeat(_to_thread_loop)
+ return (
+ direct_out,
+ direct_ticks,
+ direct_max_gap,
+ threaded_out,
+ threaded_ticks,
+ threaded_max_gap,
+ )
+
+ (
+ direct_out,
+ direct_ticks,
+ direct_max_gap,
+ threaded_out,
+ threaded_ticks,
+ threaded_max_gap,
+ ) = asyncio.run(_main())
+
+ assert threaded_out == direct_out == [_sse(chunk) for chunk in chunks] + ["data: [DONE]\n\n"]
+ assert direct_ticks == 0, (
+ f"direct generate_stream loop should block the event loop; "
+ f"got {direct_ticks} heartbeat ticks and max gap {direct_max_gap:.3f}s"
+ )
+ assert threaded_ticks >= 8, (
+ f"to_thread generate_stream loop should let the event loop run; "
+ f"got {threaded_ticks} heartbeat ticks"
+ )
+ assert threaded_max_gap < 0.06, (
+ f"to_thread generate_stream loop should avoid long heartbeat gaps; "
+ f"got {threaded_max_gap:.3f}s"
+ )
+
+
def test_audio_stream_stays_responsive_under_blocking_next():
# Assert the pre-fix `for chunk in audio_input_generate()` pattern blocks the
# event loop, then confirm the post-fix pattern exits promptly.