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: wake the dispatcher on stop instead of waiting out its queue poll (#16350)

Daniel Han879a00fe3c71
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index 51a25f27814..5c79b13a1f2 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -207,10 +207,16 @@ class _LoadCancelled(Exception):
_CTX = mp.get_context("spawn")
+def _is_dispatcher_wake(resp) -> bool:
+ return isinstance(resp, dict) and resp.get("type") == _DISPATCHER_WAKE
+
+
_DISPATCH_READ_TIMEOUT = 30.0
_STOP_NOTICE_INTERVAL = 0.1
_DISPATCH_POLL_INTERVAL = 0.5
+# Parent-sent reply that only wakes a dispatcher parked in its poll; no request_id, every reader skips it.
+_DISPATCHER_WAKE = "_dispatcher_wake"
_DISPATCH_STOP_TIMEOUT = 5.0
_DISPATCH_IDLE_TIMEOUT = 30.0
_CANCELLED_ROWS_GRACE = 5.0
@@ -1371,8 +1377,12 @@ class InferenceOrchestrator:
resp_queue = self._resp_queue
if resp_queue is None:
return None
+ started = time.monotonic()
try:
resp = resp_queue.get(timeout = timeout)
+ while _is_dispatcher_wake(resp):
+ left = None if timeout is None else max(started + timeout - time.monotonic(), 0.0)
+ resp = resp_queue.get(timeout = left)
return self._observe_response(resp, worker) if observe else resp
except queue.Empty:
return None
@@ -1449,11 +1459,13 @@ class InferenceOrchestrator:
return events
while True:
try:
- events.append(self._resp_queue.get_nowait())
+ resp = self._resp_queue.get_nowait()
except queue.Empty:
return events
except (EOFError, OSError, ValueError):
return events
+ if not _is_dispatcher_wake(resp):
+ events.append(resp)
def _direct_reader(
self,
@@ -1793,10 +1805,31 @@ class InferenceOrchestrator:
if thread is not None and self._dispatcher_thread is not thread:
return
self._dispatcher_stop.set()
+ if self._dispatcher_thread.is_alive():
+ self._wake_dispatcher()
self._dispatcher_thread.join(timeout = _DISPATCH_STOP_TIMEOUT)
self._dispatcher_thread = None
logger.debug("Dispatcher thread stopped")
+ def _wake_dispatcher(self) -> None:
+ """Best effort: on failure the dispatcher still stops on its next poll timeout."""
+ resp_queue = self._resp_queue
+ if resp_queue is None:
+ return
+ try:
+ # Pending data already wakes the reader; a dead writer may still hold the feeder lock.
+ if not resp_queue.empty():
+ return
+ # Interpreter exit must not wait on this put over a full or dead pipe.
+ cancel_join = getattr(resp_queue, "cancel_join_thread", None)
+ if cancel_join is not None:
+ cancel_join()
+ resp_queue.put_nowait({"type": _DISPATCHER_WAKE})
+ except Exception:
+ logger.debug(
+ "Dispatcher wake-up put failed; stopping on the poll timeout", exc_info = True
+ )
+
def _dispatcher_loop(self) -> None:
"""Background loop: read resp_queue and route to mailboxes by request_id."""
while not self._dispatcher_stop.is_set():
@@ -1810,6 +1843,8 @@ class InferenceOrchestrator:
continue
except (EOFError, OSError, ValueError):
break
+ if _is_dispatcher_wake(resp):
+ continue # loop condition rechecks the stop flag
# Sole consumer of the response queue; never let routing kill it, or every in-flight stream hangs.
try:
diff --git a/studio/backend/tests/test_orchestrator_dispatcher_wake.py b/studio/backend/tests/test_orchestrator_dispatcher_wake.py
new file mode 100644
index 00000000000..7ca0cc9cd27
--- /dev/null
+++ b/studio/backend/tests/test_orchestrator_dispatcher_wake.py
@@ -0,0 +1,150 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+"""Stopping the dispatcher wakes it at once instead of waiting out its response-queue poll."""
+
+import multiprocessing as mp
+import inspect
+import json
+import queue
+import subprocess
+import sys
+import textwrap
+import threading
+import time
+
+import pytest
+
+import core.inference.orchestrator as orch_mod
+from core.inference.orchestrator import InferenceOrchestrator
+
+_WAKE = {"type": "_dispatcher_wake"}
+
+
+def _with_queue(resp_queue):
+ o = InferenceOrchestrator()
+ o._resp_queue = resp_queue
+ return o
+
+
+def test_stop_does_not_wait_for_the_poll_timeout(monkeypatch):
+ monkeypatch.setattr(orch_mod, "_DISPATCH_POLL_INTERVAL", 60.0)
+ monkeypatch.setattr(orch_mod, "_DISPATCH_STOP_TIMEOUT", 10.0)
+ o = _with_queue(mp.get_context("spawn").Queue())
+ entered = threading.Event()
+ get = o._resp_queue.get
+
+ def parked_get(*args, **kwargs):
+ entered.set()
+ return get(*args, **kwargs)
+
+ monkeypatch.setattr(o._resp_queue, "get", parked_get)
+ thread = o._start_dispatcher()
+ assert entered.wait(5)
+ started = time.monotonic()
+ o._stop_dispatcher()
+ assert not thread.is_alive()
+ assert time.monotonic() - started < 5.0
+
+
+def test_failed_wake_still_stops_on_the_poll(monkeypatch):
+ monkeypatch.setattr(orch_mod, "_DISPATCH_POLL_INTERVAL", 0.1)
+
+ class _NoPut(queue.Queue):
+ def put_nowait(self, item):
+ raise OSError("closed")
+
+ o = _with_queue(_NoPut())
+ thread = o._start_dispatcher()
+ o._stop_dispatcher()
+ assert not thread.is_alive()
+
+
+def test_stray_wake_is_invisible_to_every_reader(monkeypatch):
+ q = queue.Queue()
+ o = _with_queue(q)
+ observed = []
+ monkeypatch.setattr(o, "_observe_response", lambda resp, worker: observed.append(resp) or resp)
+ q.put(_WAKE)
+ q.put({"type": "token", "request_id": "r1", "text": "a"})
+ q.put(_WAKE)
+ assert o._read_resp(timeout = 1.0) == {"type": "token", "request_id": "r1", "text": "a"}
+ assert o._read_resp(timeout = 0.05) is None # only a wake left: reads as empty
+ assert observed == [{"type": "token", "request_id": "r1", "text": "a"}]
+ q.put(_WAKE)
+ q.put({"type": "gen_done", "request_id": "r1"})
+ assert o._drain_queue() == [{"type": "gen_done", "request_id": "r1"}]
+
+
+def test_restarted_dispatcher_skips_a_stray_wake_and_keeps_order(monkeypatch):
+ monkeypatch.setattr(orch_mod, "_DISPATCH_POLL_INTERVAL", 0.05)
+ q = queue.Queue()
+ o = _with_queue(q)
+ mailbox = queue.Queue()
+ with o._mailbox_lock:
+ o._mailboxes["r1"] = mailbox
+ q.put(_WAKE)
+ q.put({"type": "token", "request_id": "r1", "text": "a"})
+ q.put(_WAKE)
+ q.put({"type": "gen_done", "request_id": "r1"})
+ thread = o._start_dispatcher()
+ got = [mailbox.get(timeout = 5) for _ in range(2)]
+ assert [r["type"] for r in got] == ["token", "gen_done"]
+ assert thread.is_alive()
+ o._stop_dispatcher()
+ assert not thread.is_alive() and mailbox.empty()
+
+
+def test_wake_is_sent_only_while_stopping_a_live_dispatcher():
+ q = queue.Queue()
+ o = _with_queue(q)
+ o._stop_dispatcher() # none running
+ assert q.empty()
+ stopped = threading.Thread(target = lambda: None)
+ stopped.start()
+ stopped.join()
+ o._dispatcher_thread = stopped
+ o._stop_dispatcher()
+ assert q.empty()
+
+
[email protected](sys.platform == "win32", reason = "Windows queues have no shared write lock")
+def test_pending_frame_from_dead_writer_does_not_start_a_parent_feeder(tmp_path):
+ script = tmp_path / "dead_writer_wake.py"
+ method = textwrap.dedent(inspect.getsource(InferenceOrchestrator._wake_dispatcher))
+ script.write_text(
+ "import json, logging, multiprocessing as mp, os, types\n"
+ f"METHOD = {method!r}\n"
+ "def worker(q):\n"
+ " q.put({'type': 'speech', 'request_id': 'r1', 'speech': 'x' * 1048576})\n"
+ " if not q._reader.poll(10):\n"
+ " os._exit(2)\n"
+ " os._exit(1)\n"
+ "if __name__ == '__main__':\n"
+ " q = mp.get_context('spawn').Queue()\n"
+ " proc = mp.get_context('spawn').Process(target=worker, args=(q,))\n"
+ " proc.start()\n"
+ " try:\n"
+ " proc.join(15)\n"
+ " assert proc.exitcode == 1, proc.exitcode\n"
+ " assert not q.empty()\n"
+ " scope = {'logger': logging.getLogger('test'), '_DISPATCHER_WAKE': '_dispatcher_wake'}\n"
+ " exec(METHOD, scope)\n"
+ " scope['_wake_dispatcher'](types.SimpleNamespace(_resp_queue=q))\n"
+ " feeder = q._thread\n"
+ " q._writer.close()\n"
+ " q._reader.close()\n"
+ " q.close()\n"
+ " if feeder is not None:\n"
+ " feeder.join(0.2)\n"
+ " print(json.dumps({'feeder_started': feeder is not None,\n"
+ " 'feeder_still_alive': feeder is not None and feeder.is_alive()}))\n"
+ " finally:\n"
+ " if proc.is_alive():\n"
+ " proc.kill()\n"
+ " proc.join(5)\n",
+ encoding = "utf-8",
+ )
+ result = subprocess.run(
+ [sys.executable, str(script)], capture_output = True, text = True, timeout = 30
+ )
+ assert result.returncode == 0, result.stderr
+ assert json.loads(result.stdout) == {"feeder_started": False, "feeder_still_alive": False}