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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop llama-server crashing on macOS on Ctrl+C (#13782)
Nilayb16a7cee8c4d
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 53892591172..519ffc43278 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -8293,6 +8293,7 @@ def _local_ssl_context() -> ssl.SSLContext:# Freeing a large model's GPU memory on a busy driver took over 5 s after SIGKILL; this only bounds a stuck process._SIGKILL_REAP_TIMEOUT_S = 30+_QUIT_SIGNAL_EXIT_GRACE_S = 2class LlamaCppBackend:@@ -35349,6 +35350,32 @@ class LlamaCppBackend:return Nonereturn pgid if pgid == pid else None+ @staticmethod+ def _quit_signal_grace_left(pid) -> Optional[float]:+ if not _is_signalable_pid(pid) or not hasattr(os, "getpgid"):+ return None+ from utils.process_lifetime import seconds_since_quit_signal++ elapsed = seconds_since_quit_signal()+ try:+ if elapsed is None or os.getpgid(pid) != os.getpgrp():+ return None+ except OSError:+ return None+ return max(0.0, _QUIT_SIGNAL_EXIT_GRACE_S - elapsed)++ def _still_listening(self) -> bool:+ port = getattr(self, "_port", None)+ if not port:+ return True+ try:+ with socket.create_connection(("127.0.0.1", port), timeout = 0.5):+ return True+ except ConnectionRefusedError:+ return False+ except OSError:+ return True+@staticmethoddef _kill_process_group(pgid):"""Take down what the leader left behind, if anything is still there."""@@ -35640,6 +35667,16 @@ class LlamaCppBackend:self._torn_down_process = self._processtry:if terminable:+ _grace = self._quit_signal_grace_left(_pid)+ if _grace is not None:+ # The quit signal already reached it; a second one aborts llama-server on Metal.+ try:+ self._process.wait(timeout = _grace)+ except subprocess.TimeoutExpired:+ # Still listening: our signal never reached it (a stop sent to Studio alone).+ if not self._still_listening():+ self._process.kill()+ self._process.wait(timeout = _SIGKILL_REAP_TIMEOUT_S)self._process.terminate()self._process.wait(timeout = 5)except subprocess.TimeoutExpired:diff --git a/studio/backend/run.py b/studio/backend/run.pyindex dc4a32d93d8..9996dd45797 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -1511,6 +1511,11 @@ def _install_windows_console_handler(shutdown) -> bool:return False+def _note_quit_signal():+ from utils.process_lifetime import mark_quit_signal_received+ mark_quit_signal_received()++def _graceful_shutdown(server = None):"""Shut down all subprocess backends and the uvicorn server. Called from signal handlers to clean upchildren before exit; critical on Windows where atexit handlers are unreliable after Ctrl+C."""@@ -3302,6 +3307,7 @@ if __name__ == "__main__":signal.signal(signal.SIGTERM, signal.SIG_DFL)if hasattr(signal, "SIGBREAK"):signal.signal(signal.SIGBREAK, signal.SIG_DFL)+ _note_quit_signal()_graceful_shutdown(_server)_shutdown_event.set()diff --git a/studio/backend/tests/test_llama_cpp_shutdown_signal.py b/studio/backend/tests/test_llama_cpp_shutdown_signal.pynew file mode 100644index 00000000000..12d194425f3--- /dev/null+++ b/studio/backend/tests/test_llama_cpp_shutdown_signal.py@@ -0,0 +1,125 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++import os+import signal+import subprocess+import sys+import time++import pytest++_backend = os.path.join(os.path.dirname(__file__), "..")+sys.path.insert(0, _backend)++from core.inference.llama_cpp import LlamaCppBackend # noqa: E402+from utils.process_lifetime import mark_process_shutting_down, mark_quit_signal_received # noqa: E402++pytestmark = pytest.mark.skipif(sys.platform == "win32", reason = "POSIX process groups")++_LLAMA_SERVER_LIKE = r"""+import os, signal, socket, sys, time+listener = socket.create_server(("127.0.0.1", 0))+seen = []+def handler(signum, frame):+ if seen:+ os._exit(1)+ seen.append(signum)+ listener.close()+signal.signal(signal.SIGINT, handler)+signal.signal(signal.SIGTERM, handler)+print(listener.getsockname()[1], flush = True)+while not seen:+ time.sleep(0.01)+time.sleep(float(sys.argv[1]))+sys.exit(0)+"""+++def _backend_holding(proc) -> LlamaCppBackend:+ backend = LlamaCppBackend.__new__(LlamaCppBackend)+ backend._process = proc+ backend._port = proc.port+ backend._healthy = True+ backend._owns_pidfile = False+ return backend+++def _spawn(shutdown_s = 0.5):+ proc = subprocess.Popen(+ [sys.executable, "-c", _LLAMA_SERVER_LIKE, str(shutdown_s)],+ stdout = subprocess.PIPE,+ text = True,+ )+ proc.port = int(proc.stdout.readline())+ assert os.getpgid(proc.pid) == os.getpgrp()+ return proc+++def test_ctrl_c_shutdown_lets_llama_server_exit_on_its_own():+ proc = _spawn()+ try:+ os.kill(proc.pid, signal.SIGINT)+ mark_quit_signal_received()+ _backend_holding(proc)._kill_process(teardown = True)+ assert proc.returncode == 0, "llama-server got a second signal mid-shutdown"+ finally:+ proc.kill()+ proc.wait()+ proc.stdout.close()+++def test_llama_server_stuck_after_ctrl_c_is_killed_not_signalled_twice():+ proc = _spawn(shutdown_s = 30)+ try:+ os.kill(proc.pid, signal.SIGINT)+ mark_quit_signal_received()+ _backend_holding(proc)._kill_process(teardown = True)+ assert proc.returncode == -signal.SIGKILL+ finally:+ proc.kill()+ proc.wait()+ proc.stdout.close()+++def test_unloading_a_model_still_stops_llama_server_at_once():+ proc = _spawn()+ try:+ started = time.monotonic()+ _backend_holding(proc)._kill_process()+ assert proc.returncode == 0+ assert time.monotonic() - started < 1.5+ finally:+ proc.kill()+ proc.wait()+ proc.stdout.close()+++def test_quit_without_a_signal_still_stops_llama_server_at_once():+ proc = _spawn()+ try:+ mark_process_shutting_down()+ started = time.monotonic()+ _backend_holding(proc)._kill_process(teardown = True)+ assert proc.returncode == 0+ assert time.monotonic() - started < 1.5+ finally:+ proc.kill()+ proc.wait()+ proc.stdout.close()+++def test_servers_share_one_grace_period():+ procs = [_spawn(), _spawn()]+ try:+ mark_quit_signal_received()+ started = time.monotonic()+ for proc in procs:+ _backend_holding(proc)._kill_process(teardown = True)+ assert proc.returncode == 0+ assert time.monotonic() - started < 4+ finally:+ for proc in procs:+ proc.kill()+ proc.wait()+ proc.stdout.close()diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.pyindex 5fb08552b7f..2a88ee977e7 100644--- a/studio/backend/utils/process_lifetime.py+++ b/studio/backend/utils/process_lifetime.py@@ -2016,6 +2016,19 @@ def is_process_shutting_down() -> bool:return _shutdown_latch.is_set()+_quit_signal_at: Optional[float] = None+++def mark_quit_signal_received() -> None:+ global _quit_signal_at+ if _quit_signal_at is None:+ _quit_signal_at = time.monotonic()+++def seconds_since_quit_signal() -> Optional[float]:+ return None if _quit_signal_at is None else time.monotonic() - _quit_signal_at++def begin_process_lifecycle() -> None:"""Clear the latch for an embedded host that calls run_server again.@@ -2023,7 +2036,9 @@ def begin_process_lifecycle() -> None:reuse the interpreter, and a latch that never cleared would refuse every spawn ofthe second session."""+ global _quit_signal_at_shutdown_latch.clear()+ _quit_signal_at = Nonedef terminate_all(timeout: float = 5.0) -> "list[int]":diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex a173bf6867e..fa84f510536 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -2250,6 +2250,7 @@ def studio_default(while True:time.sleep(1)except KeyboardInterrupt:+ getattr(run_mod, "_note_quit_signal", lambda: None)()run_mod._graceful_shutdown(run_mod._server)typer.echo("\nShutting down...")finally:@@ -3064,6 +3065,7 @@ def run(while True:time.sleep(1)except KeyboardInterrupt:+ getattr(run_mod, "_note_quit_signal", lambda: None)()run_mod._graceful_shutdown(run_mod._server)typer.echo("\nShutting down...")finally: