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: follow up #9201 across non-streaming sibling paths (#9312)

oobabooga9a45830e47d2
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 6370619c574..dacefe7a93f 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -3171,36 +3171,107 @@ async def _stop_local_disconnect_cancel_watcher(
pass
-async def _drain_pending_next_task(task, cancel_event) -> None:
- """Wait for a pending ``asyncio.to_thread(next, gen, ...)`` task to finish
- before its generator is closed.
-
- On disconnect a ``next(gen)`` call may still run in a worker thread;
- cancelling the awaiting task does NOT stop it, and ``gen.close()`` mid-
- ``next(gen)`` raises ``ValueError: generator already executing``, leaking the
- generator's cleanup. So re-set the cancel flag (the generator polls it) and
- shield the task until the worker returns. No-op when there is no pending task.
+async def _drain_pending_worker(worker, cancel_event) -> None:
+ """Wait for a pending blocking worker before its resources are released.
+
+ ``worker`` is the task or future the request awaits: a streaming
+ ``next(gen)`` step, or a whole non-streaming generation. Cancelling it does
+ NOT stop the thread behind it. Re-set the cancel flag (the generator polls
+ it) and shield the worker until it returns, so admission and generation
+ tracking still cover its real lifetime. No-op when there is no pending
+ worker.
"""
- if task is None:
+ if worker is None:
return
if cancel_event is not None:
cancel_event.set()
- while not task.done():
+ while not worker.done():
try:
- await asyncio.shield(task)
+ await asyncio.shield(worker)
except asyncio.CancelledError:
if cancel_event is not None:
cancel_event.set()
continue
except Exception:
break
- if task.done():
+ if worker.done():
try:
- task.exception()
+ worker.exception()
except (asyncio.CancelledError, Exception):
pass
+def _settle_daemon_worker(future: "asyncio.Future", succeeded: bool, value) -> None:
+ """Publish a daemon worker outcome unless its event loop has moved on."""
+ if future.done():
+ return
+ if succeeded:
+ future.set_result(value)
+ else:
+ future.set_exception(value)
+
+
+def _start_daemon_worker(fn, *, name: str) -> "asyncio.Future":
+ """Start blocking request work without adding an interpreter-exit join.
+
+ ``asyncio.to_thread`` uses the loop's non-daemon default executor. A local
+ generation can be inside a cancellation-ignoring tool for its full timeout,
+ so that executor would defeat the launcher's bounded server-thread join and
+ keep the process alive. The request still awaits this future during ordinary
+ cancellation; daemon status only preserves the process shutdown boundary.
+ """
+ loop = asyncio.get_running_loop()
+ future = loop.create_future()
+ context = contextvars.copy_context()
+
+ def _run() -> None:
+ try:
+ value = context.run(fn)
+ except BaseException as exc: # noqa: BLE001 - delivered to the awaiting request
+ outcome = (False, exc)
+ else:
+ outcome = (True, value)
+ try:
+ loop.call_soon_threadsafe(_settle_daemon_worker, future, *outcome)
+ except RuntimeError:
+ pass # the daemon may finish after process shutdown closed the loop
+
+ try:
+ threading.Thread(target = _run, name = name, daemon = True).start()
+ except BaseException as exc: # noqa: BLE001 - mirror executor submission failures
+ future.set_exception(exc)
+ return future
+
+
+async def _run_blocking_generation(
+ fn,
+ cancel_event,
+ *,
+ name: str,
+ daemon: bool = False,
+):
+ """Run one synchronous generation unit without blocking the event loop.
+
+ Shield the worker so task cancellation cannot shorten the tracker or
+ admission-lease lifetime. Use a daemon only for server-tool loops that may
+ ignore cancellation; ordinary generation stays on the bounded default pool.
+
+ Unlike the streaming paths, which release their default-executor thread
+ between tokens, a non-daemon unit holds one for the whole generation. Keep
+ unrelated blocking work off that pool (see _STATUS_PROBE_EXECUTOR).
+ """
+ worker = (
+ _start_daemon_worker(fn, name = name)
+ if daemon
+ else asyncio.create_task(asyncio.to_thread(fn))
+ )
+ try:
+ return await asyncio.shield(worker)
+ except asyncio.CancelledError:
+ await _drain_pending_worker(worker, cancel_event)
+ raise
+
+
# Centralized local/server tool nudge. Keep render_html guidance gated to turns
# where the canvas tool is actually present in the tool schema; otherwise
# small local models can hallucinate a missing tool call instead of following
@@ -13683,13 +13754,28 @@ async def openai_chat_completions(
_tracker = _TrackedCancel.for_payload(cancel_event, payload, *_cancel_keys)
_tracker.__enter__()
try:
- full_text = ""
- for chunk_text in audio_input_generate():
- if isinstance(chunk_text, GenStreamError):
- _msg = _friendly_gen_stream_error(chunk_text)
- api_monitor.fail(monitor_id, _msg)
- raise HTTPException(status_code = 500, detail = _msg)
- full_text += chunk_text
+
+ def _drain_audio_input():
+ text_parts = []
+ for chunk_text in audio_input_generate():
+ if isinstance(chunk_text, GenStreamError):
+ return chunk_text
+ text_parts.append(chunk_text)
+ return "".join(text_parts)
+
+ full_text = await _run_blocking_generation(
+ _drain_audio_input,
+ cancel_event,
+ name = "openai-audio-input-nonstream",
+ )
+ if isinstance(full_text, GenStreamError):
+ _msg = _friendly_gen_stream_error(full_text)
+ api_monitor.fail(monitor_id, _msg)
+ raise HTTPException(status_code = 500, detail = _msg)
+ except asyncio.CancelledError:
+ cancel_event.set()
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except HTTPException:
raise
except Exception as e:
@@ -15849,7 +15935,7 @@ async def openai_chat_completions(
# Drain a still-running next(gen) worker before closing: closing
# mid-next(gen) raises ValueError('generator already executing') and
# skips the generator's cleanup finally. Matches the GGUF tool stream.
- await _drain_pending_next_task(_sf_next_task, cancel_event)
+ await _drain_pending_worker(_sf_next_task, cancel_event)
if gen is not None:
try:
# Offload the close so the generator's cleanup runs off the event
@@ -16327,7 +16413,7 @@ async def openai_chat_completions(
# Drain a still-running next(gen) worker before closing: closing
# mid-next(gen) raises ValueError('generator already executing') and
# skips the generator's cleanup finally. Matches the safetensors stream.
- await _drain_pending_next_task(_next_task, cancel_event)
+ await _drain_pending_worker(_next_task, cancel_event)
if gen is not None:
try:
# Offload the close so the generator's cleanup runs off the event
@@ -16357,14 +16443,25 @@ async def openai_chat_completions(
_tracker = _TrackedCancel.for_payload(cancel_event, payload, *_cancel_keys)
_tracker.__enter__()
try:
- full_text = ""
- for token in generate():
- if isinstance(token, GenStreamError):
- backend.reset_generation_state(cancel_event)
- _msg = _friendly_gen_stream_error(token)
- api_monitor.fail(monitor_id, _msg)
- raise HTTPException(status_code = 500, detail = _msg)
- full_text = token
+
+ def _drain_generate(messages_override = None):
+ final = ""
+ for token in generate(messages_override):
+ if isinstance(token, GenStreamError):
+ return token
+ final = token
+ return final
+
+ full_text = await _run_blocking_generation(
+ _drain_generate,
+ cancel_event,
+ name = "openai-chat-nonstream",
+ )
+ if isinstance(full_text, GenStreamError):
+ backend.reset_generation_state(cancel_event)
+ _msg = _friendly_gen_stream_error(full_text)
+ api_monitor.fail(monitor_id, _msg)
+ raise HTTPException(status_code = 500, detail = _msg)
# Split prefilled <think> reasoning (GGUF parity); also covers MLX via
# the shared generate(). Client-tool healing then runs on the visible
@@ -16398,11 +16495,15 @@ async def openai_chat_completions(
# and restore them if the retry is discarded.
_first_stats = stats_holder.get("stats")
try:
- retry_text = ""
- for token in generate(
- [*gen_kwargs["messages"], *nudge_messages(_data, _sf_heal)]
- ):
- retry_text = token
+ retry_messages = [
+ *gen_kwargs["messages"],
+ *nudge_messages(_data, _sf_heal),
+ ]
+ retry_text = await _run_blocking_generation(
+ lambda: _drain_generate(retry_messages),
+ cancel_event,
+ name = "openai-chat-nudge-nonstream",
+ )
# Re-split reasoning on the retry so its visible text is
# what heals into a call (and reaches the monitor).
# The nudge retry appends messages, so it is not a
@@ -16475,6 +16576,11 @@ async def openai_chat_completions(
api_monitor.finish(monitor_id)
return _model_json_response(response)
+ except asyncio.CancelledError:
+ cancel_event.set()
+ backend.reset_generation_state(cancel_event)
+ api_monitor.finish(monitor_id, "cancelled")
+ raise
except HTTPException:
raise
except GenStreamErrorRaised as exc:
@@ -20727,7 +20833,7 @@ async def _anthropic_tool_stream(
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
# Drain a still-running next(gen) worker first, so a mid-prefill disconnect releases
# its resources; closing first races into 'already executing'.
- await _drain_pending_next_task(_next_task, cancel_event)
+ await _drain_pending_worker(_next_task, cancel_event)
if gen is not None:
try:
await asyncio.to_thread(gen.close)
@@ -20825,7 +20931,7 @@ async def _anthropic_plain_stream(
await _stop_local_disconnect_cancel_watcher(disconnect_watcher)
# Drain a still-running next(gen) worker first, so a mid-prefill disconnect releases
# its resources; closing first races into 'already executing'.
- await _drain_pending_next_task(_next_task, cancel_event)
+ await _drain_pending_worker(_next_task, cancel_event)
if gen is not None:
try:
await asyncio.to_thread(gen.close)
@@ -20858,19 +20964,12 @@ def _anthropic_map_generation_error(e: Exception) -> HTTPException:
return HTTPException(status_code = 500, detail = _friendly_error(e))
-async def _collect_anthropic_events(run_gen, cancel_event = None) -> list:
+def _collect_anthropic_events(run_gen) -> list:
"""Drain the generator into a list, mapping an upstream 4xx / context
overflow to a clean Anthropic 400 instead of leaking a 500."""
- def _drain():
- return list(run_gen())
-
- drain_task = asyncio.create_task(asyncio.to_thread(_drain))
try:
- return await asyncio.shield(drain_task)
- except asyncio.CancelledError:
- await _drain_pending_next_task(drain_task, cancel_event)
- raise
+ return list(run_gen())
except HTTPException:
raise
except Exception as e:
@@ -20896,15 +20995,14 @@ def _anthropic_message_json_response(
)
-async def _anthropic_tool_non_streaming(
- run_gen,
+def _anthropic_tool_response_from_events(
+ events,
message_id,
model_name,
disable_parallel_tool_use = False,
openai_tools = None,
- cancel_event = None,
):
- """Non-streaming response for the tool-calling path.
+ """Reduce collected tool events into one non-streaming response.
Builds ``content_blocks`` in generation order (text → tool_use → text →
tool_use → ...), mirroring the streaming emitter. Deltas within one
@@ -20928,8 +21026,6 @@ async def _anthropic_tool_non_streaming(
# trailing text. See the stop_reason mapping below.
ends_on_tool_use = False
- events = await _collect_anthropic_events(run_gen, cancel_event)
-
for event in events:
etype = event.get("type", "")
if etype == "content":
@@ -21000,20 +21096,40 @@ async def _anthropic_tool_non_streaming(
)
-async def _anthropic_plain_non_streaming(
+async def _anthropic_tool_non_streaming(
run_gen,
message_id,
model_name,
+ disable_parallel_tool_use = False,
+ openai_tools = None,
cancel_event = None,
):
- """Non-streaming response for the no-tool path."""
+ """Generate and reduce a tool response entirely off the event loop."""
+
+ def _drain_and_build():
+ return _anthropic_tool_response_from_events(
+ _collect_anthropic_events(run_gen),
+ message_id,
+ model_name,
+ disable_parallel_tool_use = disable_parallel_tool_use,
+ openai_tools = openai_tools,
+ )
+
+ return await _run_blocking_generation(
+ _drain_and_build,
+ cancel_event,
+ name = "anthropic-tool-nonstream",
+ daemon = True,
+ )
+
+
+def _anthropic_plain_response_from_events(events, message_id, model_name):
+ """Reduce collected plain events into one non-streaming response."""
text_parts = []
usage = {}
prev_text = ""
captured_finish_reason = None
- events = await _collect_anthropic_events(run_gen, cancel_event)
-
for cumulative in events:
if isinstance(cumulative, dict):
if cumulative.get("type") == "metadata":
@@ -21039,6 +21155,28 @@ async def _anthropic_plain_non_streaming(
)
+async def _anthropic_plain_non_streaming(
+ run_gen,
+ message_id,
+ model_name,
+ cancel_event = None,
+):
+ """Generate and reduce a plain response entirely off the event loop."""
+
+ def _drain_and_build():
+ return _anthropic_plain_response_from_events(
+ _collect_anthropic_events(run_gen),
+ message_id,
+ model_name,
+ )
+
+ return await _run_blocking_generation(
+ _drain_and_build,
+ cancel_event,
+ name = "anthropic-plain-nonstream",
+ )
+
+
# =====================================================================
# Client-side tool pass-through (Anthropic-native tools field)
# =====================================================================
diff --git a/studio/backend/tests/test_anthropic_messages.py b/studio/backend/tests/test_anthropic_messages.py
index e1daa1fc084..e9a764da6e7 100644
--- a/studio/backend/tests/test_anthropic_messages.py
+++ b/studio/backend/tests/test_anthropic_messages.py
@@ -7,6 +7,7 @@ import sys
import os
import json
import threading
+import time
import httpx
import pytest
@@ -948,20 +949,64 @@ class TestAnthropicToolNonStreaming:
pytest.param(_anthropic_plain_non_streaming, "ok", id = "plain"),
],
)
- def test_generator_is_drained_off_the_event_loop(self, helper, event):
+ def test_complete_response_build_keeps_event_loop_responsive(self, helper, event):
loop_thread = threading.current_thread()
generator_threads = []
def _run_gen():
generator_threads.append(threading.current_thread())
+ time.sleep(0.08)
yield event
- response = asyncio.run(helper(_run_gen, "msg_1", "m"))
+ async def _run():
+ task = asyncio.create_task(helper(_run_gen, "msg_1", "m"))
+ await asyncio.sleep(0)
+ heartbeat_ticks = 0
+ while not task.done():
+ heartbeat_ticks += 1
+ await asyncio.sleep(0.005)
+ return await task, heartbeat_ticks
+
+ response, heartbeat_ticks = asyncio.run(_run())
assert response.status_code == 200
+ assert heartbeat_ticks > 0
assert len(generator_threads) == 1
assert generator_threads[0] is not loop_thread
+ def test_tool_event_reduction_keeps_event_loop_responsive(self, monkeypatch):
+ import routes.inference as inf_mod
+
+ reduction_threads = []
+ real_strip = inf_mod._strip_tool_xml_for_display
+
+ def _slow_strip(*args, **kwargs):
+ reduction_threads.append(threading.current_thread())
+ time.sleep(0.08)
+ return real_strip(*args, **kwargs)
+
+ monkeypatch.setattr(inf_mod, "_strip_tool_xml_for_display", _slow_strip)
+
+ def _run_gen():
+ yield {"type": "content", "text": "ok"}
+
+ async def _run():
+ task = asyncio.create_task(_anthropic_tool_non_streaming(_run_gen, "msg_1", "m"))
+ await asyncio.sleep(0)
+ heartbeat_ticks = 0
+ while not task.done():
+ heartbeat_ticks += 1
+ await asyncio.sleep(0.005)
+ return await task, heartbeat_ticks
+
+ response, heartbeat_ticks = asyncio.run(_run())
+
+ assert response.status_code == 200
+ assert heartbeat_ticks > 0
+ assert len(reduction_threads) == 1
+ assert reduction_threads[0] is not threading.current_thread()
+ assert reduction_threads[0].daemon is True
+
@pytest.mark.parametrize(
("helper", "event"),
[
diff --git a/studio/backend/tests/test_openai_tool_passthrough.py b/studio/backend/tests/test_openai_tool_passthrough.py
index 4d3e3f32fa2..810e46d0686 100644
--- a/studio/backend/tests/test_openai_tool_passthrough.py
+++ b/studio/backend/tests/test_openai_tool_passthrough.py
@@ -6715,6 +6715,75 @@ class TestApiMonitorSafetensorsUsage:
url = SimpleNamespace(path = "/v1/chat/completions")
method = "POST"
+ def test_non_streaming_safetensors_keeps_event_loop_responsive(self, monkeypatch):
+ async def _run():
+ import routes.inference as inf_mod
+
+ generation_started = threading.Event()
+ generation_finished = threading.Event()
+ generation_threads = []
+
+ class DummyBackend:
+ active_model_name = "safe-model"
+ models = {"safe-model": {"context_length": 2048}}
+
+ def generate_chat_response(self, **_kwargs):
+ generation_threads.append(threading.current_thread())
+ generation_started.set()
+ try:
+ time.sleep(0.08)
+ yield "safe reply"
+ finally:
+ generation_finished.set()
+
+ def reset_generation_state(self, caller_cancel_event = None):
+ pass
+
+ monkeypatch.setattr(
+ inf_mod,
+ "get_llama_cpp_backend",
+ lambda: SimpleNamespace(
+ is_loaded = False,
+ supports_tools = False,
+ is_vision = False,
+ context_length = None,
+ ),
+ )
+ monkeypatch.setattr(inf_mod, "get_inference_backend", lambda: DummyBackend())
+ monkeypatch.setattr(
+ inf_mod,
+ "_detect_safetensors_features",
+ lambda *_args, **_kwargs: {"supports_tools": False},
+ )
+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "hi")],
+ )
+ heartbeat_ticks = 0
+
+ async def _heartbeat():
+ nonlocal heartbeat_ticks
+ while not generation_finished.is_set():
+ await asyncio.sleep(0.005)
+ if generation_started.is_set() and not generation_finished.is_set():
+ heartbeat_ticks += 1
+
+ heartbeat = asyncio.create_task(_heartbeat())
+ response = await openai_chat_completions(
+ payload,
+ request = self._Request(),
+ current_subject = "test",
+ )
+ await heartbeat
+
+ assert response.status_code == 200
+ assert heartbeat_ticks > 0
+ assert len(generation_threads) == 1
+ assert generation_threads[0] is not threading.current_thread()
+
+ asyncio.run(_run())
+
def test_non_streaming_safetensors_records_usage(self, monkeypatch):
async def _run():
import routes.inference as inf_mod
@@ -6990,6 +7059,57 @@ class TestApiMonitorAudioInput:
asyncio.run(_run())
+ def test_audio_input_non_streaming_keeps_event_loop_responsive(self, monkeypatch):
+ async def _run():
+ generation_started = threading.Event()
+ generation_finished = threading.Event()
+ generation_threads = []
+
+ def _chunks():
+ generation_threads.append(threading.current_thread())
+ generation_started.set()
+ try:
+ time.sleep(0.08)
+ yield "hello"
+ finally:
+ generation_finished.set()
+
+ inf_mod = self._patch_audio_backend(monkeypatch, _chunks())
+ monkeypatch.setattr(inf_mod, "api_monitor", ApiMonitor(max_entries = 3))
+ payload = ChatCompletionRequest(
+ model = "default",
+ messages = [ChatMessage(role = "user", content = "describe this audio")],
+ audio_base64 = "ZmFrZQ==",
+ )
+ request = SimpleNamespace(
+ state = SimpleNamespace(),
+ url = SimpleNamespace(path = "/v1/chat/completions"),
+ method = "POST",
+ )
+ heartbeat_ticks = 0
+
+ async def _heartbeat():
+ nonlocal heartbeat_ticks
+ while not generation_finished.is_set():
+ await asyncio.sleep(0.005)
+ if generation_started.is_set() and not generation_finished.is_set():
+ heartbeat_ticks += 1
+
+ heartbeat = asyncio.create_task(_heartbeat())
+ response = await openai_chat_completions(
+ payload,
+ request = request,
+ current_subject = "test",
+ )
+ await heartbeat
+
+ assert response.status_code == 200
+ assert heartbeat_ticks > 0
+ assert len(generation_threads) == 1
+ assert generation_threads[0] is not threading.current_thread()
+
+ asyncio.run(_run())
+
def test_audio_input_streaming_records_monitor_reply(self, monkeypatch):
async def _run():
inf_mod = self._patch_audio_backend(monkeypatch, ["hello", " world"])
diff --git a/studio/backend/tests/test_tool_stream_generator_drain.py b/studio/backend/tests/test_tool_stream_generator_drain.py
index e1d751ab095..01e1b0a98a6 100644
--- a/studio/backend/tests/test_tool_stream_generator_drain.py
+++ b/studio/backend/tests/test_tool_stream_generator_drain.py
@@ -6,7 +6,7 @@
Tool streams run ``next(gen)`` in an ``asyncio.to_thread`` worker. Closing the
generator while that worker is still inside ``next`` raises ``ValueError:
generator already executing`` and skips the generator's ``finally`` (tool
-cleanup); the routes drain the pending task first (``_drain_pending_next_task``),
+cleanup); the routes drain the pending task first (``_drain_pending_worker``),
which these tests exercise.
"""
@@ -17,7 +17,7 @@ import threading
import pytest
-from routes.inference import _drain_pending_next_task
+from routes.inference import _drain_pending_worker
def test_drain_before_close_avoids_generator_already_executing():
@@ -46,7 +46,7 @@ def test_drain_before_close_avoids_generator_already_executing():
# Draining sets the cancel flag so the worker returns; then close is
# clean and the generator's finally runs.
- await _drain_pending_next_task(next_task, cancel_event)
+ await _drain_pending_worker(next_task, cancel_event)
gen.close()
return
@@ -54,15 +54,15 @@ def test_drain_before_close_avoids_generator_already_executing():
assert finally_ran.is_set()
-def test_drain_pending_next_task_is_noop_without_task():
+def test_drain_pending_worker_is_noop_without_task():
# None (task already consumed): draining is a no-op, cancel flag untouched.
cancel_event = threading.Event()
- asyncio.run(_drain_pending_next_task(None, cancel_event))
+ asyncio.run(_drain_pending_worker(None, cancel_event))
assert not cancel_event.is_set()
-def test_drain_pending_next_task_returns_when_worker_finishes():
+def test_drain_pending_worker_returns_when_worker_finishes():
# A worker finishing on its own drains without error; the cancel flag stays
# set (the caller is tearing the stream down).
cancel_event = threading.Event()
@@ -76,7 +76,7 @@ def test_drain_pending_next_task_returns_when_worker_finishes():
g = gen()
task = asyncio.create_task(asyncio.to_thread(next, g, object()))
release.set() # let the worker complete before draining
- await _drain_pending_next_task(task, cancel_event)
+ await _drain_pending_worker(task, cancel_event)
assert task.done()
asyncio.run(scenario())