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
Desktop: exit the backend when the app that spawned it dies (#7655)
Nilay9ec91b54ac2b
diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 2cee4c33932..590d3850ca7 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -2055,6 +2055,18 @@ def run_server(# The headless `run --api-only` path opts out so it does not leak this line.if api_only and emit_tauri_port:print(f"TAURI_PORT={port}", flush = True)+ # Desktop-owned backends only (the owner env handshake): a headless+ # `unsloth studio --api-only` has no app to bind its lifetime to and+ # must survive its terminal (e.g. nohup). If the app dies without+ # running its cleanup, exit instead of orphaning on the port.+ from main import _desktop_owner+ if _desktop_owner() is not None:+ from utils.parent_watchdog import start_parent_watchdog+ owner_pid = os.environ.pop("UNSLOTH_STUDIO_DESKTOP_OWNER_PID", "")+ start_parent_watchdog(+ _trigger_shutdown,+ parent_pid = int(owner_pid) if owner_pid.isdigit() else None,+ )# Free trycloudflare.com tunnel for wildcard binds (the raw ip:port is often# unreachable). Started pre-banner and even when silent so the CLI banner candiff --git a/studio/backend/tests/test_parent_watchdog.py b/studio/backend/tests/test_parent_watchdog.pynew file mode 100644index 00000000000..871d6c0a7f6--- /dev/null+++ b/studio/backend/tests/test_parent_watchdog.py@@ -0,0 +1,122 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import os+from pathlib import Path+import subprocess+import sys+import threading+import time+import types as _types++import pytest+++_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)+if _BACKEND_DIR not in sys.path:+ sys.path.insert(0, _BACKEND_DIR)++_loggers_stub = _types.ModuleType("loggers")+_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)+sys.modules.setdefault("loggers", _loggers_stub)++from utils import parent_watchdog as pw+++def test_fires_when_reparented(monkeypatch):+ calls = {"n": 0}++ def _ppid():+ calls["n"] += 1+ return 4242 if calls["n"] < 3 else 1++ monkeypatch.setattr(pw.os, "getppid", _ppid)+ fired = threading.Event()+ pw._watch_unix(4242, fired.set, threading.Event(), poll_seconds = 0.01)+ assert fired.is_set()+++def test_fires_immediately_when_already_orphaned(monkeypatch):+ monkeypatch.setattr(pw.os, "getppid", lambda: 1)+ fired = threading.Event()+ assert pw.start_parent_watchdog(fired.set) is None+ assert fired.is_set()+++ sys.platform == "win32", reason = "dispatches to the Windows watcher, which opens the real pid"+)+def test_stop_event_ends_the_watch(monkeypatch):+ monkeypatch.setattr(pw.os, "getppid", lambda: 4242)+ fired = threading.Event()+ stop = pw.start_parent_watchdog(fired.set, poll_seconds = 0.01)+ assert stop is not None+ stop.set()+ time.sleep(0.05)+ assert not fired.is_set()+++def test_callback_exception_is_contained():+ def _boom():+ raise RuntimeError("shutdown failed")++ pw._fire(_boom) # must not raise+++def test_fires_immediately_when_the_owner_is_not_the_current_parent(monkeypatch):+ # Explicit owner pid but already reparented: the owner died during backend+ # startup (reaped or zombie alike). Must fire before the first wait.+ monkeypatch.setattr(pw.os, "getppid", lambda: 7777)+ fired = threading.Event()+ started = time.monotonic()+ pw._watch_unix(4242, fired.set, threading.Event(), poll_seconds = 30)+ assert fired.is_set()+ assert time.monotonic() - started < 1++[email protected](sys.platform == "win32", reason = "unix reparenting path")+def test_process_exits_when_parent_dies(tmp_path):+ # The callback writes a marker before exiting: liveness cannot be probed+ # with kill(pid, 0), which also succeeds while the child is an unreaped+ # zombie under a non-reaping init.+ marker = tmp_path / "fired"+ watcher = tmp_path / "watcher.py"+ watcher.write_text(+ f"""+import logging, os, sys, time, types+sys.path.insert(0, {_BACKEND_DIR!r})+stub = types.ModuleType("loggers")+stub.get_logger = lambda name: logging.getLogger(name)+sys.modules.setdefault("loggers", stub)+from utils.parent_watchdog import start_parent_watchdog++def _exit():+ open({str(marker)!r}, "w").write("fired")+ os._exit(0)++# Explicit owner pid, like the production handshake: under a child-subreaper+# the parent can die and reparent us before this line runs, and a getppid+# sample here would watch the subreaper forever.+start_parent_watchdog(_exit, parent_pid = int(sys.argv[1]), poll_seconds = 0.05)+time.sleep(30)+os._exit(1)+"""+ )+ parent = tmp_path / "parent.py"+ parent.write_text(+ f"""+import os, subprocess, sys+subprocess.Popen([sys.executable, {str(watcher)!r}, str(os.getpid())])+"""+ )++ # The intermediate parent spawns the watcher and exits immediately,+ # orphaning it; the watchdog must notice and exit the watcher.+ subprocess.run([sys.executable, str(parent)], check = True, timeout = 15)++ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ if marker.exists():+ return+ time.sleep(0.1)+ pytest.fail("watchdog never fired after the parent died")diff --git a/studio/backend/utils/parent_watchdog.py b/studio/backend/utils/parent_watchdog.pynew file mode 100644index 00000000000..47c395c6f51--- /dev/null+++ b/studio/backend/utils/parent_watchdog.py@@ -0,0 +1,99 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++# Exits a desktop-owned backend when the app that spawned it dies without+# running its cleanup. The orphan would otherwise keep the port and make the+# next launch's preflight refuse to start.++from __future__ import annotations++import os+import sys+import threading+from typing import Callable, Optional++from loggers import get_logger++logger = get_logger(__name__)++_DEFAULT_POLL_SECONDS = 2.0+++def _fire(on_parent_exit: Callable[[], None]) -> None:+ logger.info("parent_watchdog.parent_exited: shutting down")+ try:+ on_parent_exit()+ except Exception as exc:+ logger.warning("parent_watchdog: shutdown callback failed: %s", exc)+++def _watch_unix(parent_pid, on_parent_exit, stop, poll_seconds) -> None:+ # The app spawns the backend as its direct child on Unix, so "my parent is+ # no longer the owner pid" is the death signal: kernel truth, immune to pid+ # reuse, and indifferent to whether the corpse was reaped (a kill-0 probe+ # would count an unreaped zombie as alive). Checked before the first wait+ # so an owner that died during backend startup is caught immediately.+ while True:+ if os.getppid() != parent_pid:+ _fire(on_parent_exit)+ return+ if stop.wait(poll_seconds):+ return+++def _watch_windows(parent_pid, on_parent_exit, stop, poll_seconds) -> None:+ import ctypes+ from ctypes import wintypes++ kernel32 = ctypes.windll.kernel32+ # Explicit signatures: handles are pointer-sized and would be truncated by+ # the c_int defaults on 64-bit, leaving the wait on an invalid handle.+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)+ kernel32.WaitForSingleObject.restype = wintypes.DWORD+ kernel32.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD)+ kernel32.CloseHandle.restype = wintypes.BOOL+ kernel32.CloseHandle.argtypes = (wintypes.HANDLE,)++ SYNCHRONIZE = 0x00100000+ WAIT_OBJECT_0 = 0+ handle = kernel32.OpenProcess(SYNCHRONIZE, False, parent_pid)+ if not handle:+ # A same-user owner is always openable, so failure means the parent+ # already died and its pid went stale: exit, don't abandon the watch.+ _fire(on_parent_exit)+ return+ try:+ # Bounded waits so a stop request is honored.+ while not stop.is_set():+ if kernel32.WaitForSingleObject(handle, int(poll_seconds * 1000)) == WAIT_OBJECT_0:+ _fire(on_parent_exit)+ return+ finally:+ kernel32.CloseHandle(handle)+++# Watches parent_pid (the spawning app's own pid when it passes one, else the+# direct parent). Returns the stop event, or None when the parent was already+# gone at arm time, in which case the callback fires immediately.+def start_parent_watchdog(+ on_parent_exit: Callable[[], None],+ parent_pid: Optional[int] = None,+ poll_seconds: float = _DEFAULT_POLL_SECONDS,+) -> Optional[threading.Event]:+ if parent_pid is None:+ parent_pid = os.getppid()+ if parent_pid <= 1:+ _fire(on_parent_exit)+ return None+ stop = threading.Event()+ watch = _watch_windows if sys.platform == "win32" else _watch_unix+ thread = threading.Thread(+ target = watch,+ args = (parent_pid, on_parent_exit, stop, poll_seconds),+ name = "unsloth-parent-watchdog",+ daemon = True,+ )+ thread.start()+ logger.info("parent_watchdog.started ppid=%s", parent_pid)+ return stopdiff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rsindex 8a174a0731f..d3c529f28b2 100644--- a/studio/src-tauri/src/desktop_backend_owner.rs+++ b/studio/src-tauri/src/desktop_backend_owner.rs@@ -14,6 +14,9 @@ static TEST_METADATA: std::sync::Mutex<Option<DesktopBackendMetadata>> =pub(crate) const OWNER_TOKEN_ENV: &str = "UNSLOTH_STUDIO_DESKTOP_OWNER_TOKEN";pub(crate) const OWNER_KIND_ENV: &str = "UNSLOTH_STUDIO_DESKTOP_OWNER_KIND";+// The app's own pid, so the backend can watch the exact owner process instead+// of sampling getppid (racy under a subreaper when the app dies mid-startup).+pub(crate) const OWNER_PID_ENV: &str = "UNSLOTH_STUDIO_DESKTOP_OWNER_PID";pub(crate) const OWNER_KIND_TAURI: &str = "tauri";const METADATA_SCHEMA_VERSION: u8 = 1;diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 56d9dd2e216..15efbaa84b0 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -594,6 +594,10 @@ pub fn start_backend(crate::desktop_backend_owner::OWNER_KIND_ENV,crate::desktop_backend_owner::OWNER_KIND_TAURI,);+ cmd.env(+ crate::desktop_backend_owner::OWNER_PID_ENV,+ std::process::id().to_string(),+ );}// AppImage sets LD_LIBRARY_PATH to its bundled libs, which breaks the spawned