From cb125b6d34d0e2545532e3fdc5003c62addf90f2 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 8 Aug 2026 11:51:16 +0000 Subject: [PATCH 1/5] Studio: stop leaking child processes on an abnormal exit A Windows user could not update Studio until they killed a stray python by hand: the tool sandbox runs its payload under a shell wrapper, the kill path reaped only the wrapper, and `unsloth studio update` then refused to run because a process still held the managed environment. - taskkill /T on Windows, so a tool payload cannot outlive its wrapper - a console-close handler, since CTRL_CLOSE_EVENT never becomes a Python signal and the graceful shutdown was skipped entirely when the window was closed - the desktop updater drains the app job before standing down crash cleanup, and re-arms it when the install never happens - children are recorded on disk and swept at the next startup, which is the only reaper macOS has after a crash or a force quit - the job status is logged instead of failing silently Also fixes a liveness probe that used os.kill(pid, 0); on Windows that is TerminateProcess, so it killed the process it was asking about. --- studio/backend/core/inference/llama_cpp.py | 17 ++ studio/backend/core/inference/tools.py | 50 +++- studio/backend/run.py | 67 ++++- .../tests/test_child_lifetime_boundary.py | 131 +++++++++ .../backend/tests/test_orphaned_children.py | 226 +++++++++++++++ studio/backend/utils/process_lifetime.py | 268 +++++++++++++++++- studio/frontend/src/hooks/use-tauri-update.ts | 3 + studio/src-tauri/src/desktop_updater.rs | 14 + studio/src-tauri/src/main.rs | 1 + studio/src-tauri/src/windows_job.rs | 101 ++++++- 10 files changed, 852 insertions(+), 26 deletions(-) create mode 100644 studio/backend/tests/test_child_lifetime_boundary.py create mode 100644 studio/backend/tests/test_orphaned_children.py diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py index 3e62d4edaa..9764cb2140 100644 --- a/studio/backend/core/inference/llama_cpp.py +++ b/studio/backend/core/inference/llama_cpp.py @@ -13411,6 +13411,15 @@ def _kill_process(self): if getattr(self, "_stats_logger", None) is not None: self._stats_logger.stop() self._stats_logger = None + # Drop it from the lifetime record before the reference goes, or a + # recycled pid could be signalled later. + _killed_pid = getattr(self._process, "pid", None) + if _killed_pid is not None: + try: + from utils.process_lifetime import forget_pid + forget_pid(_killed_pid) + except Exception: + pass self._process = None self._clear_server_pid() # Clear healthy so a /load during the replacement's warm-up can't @@ -13454,6 +13463,14 @@ def _record_server_pid(cls, pid: int) -> None: since been recycled to a different process (see ``_pid_start_identity``). A bare ``pid`` (no identity) is still accepted on read for compatibility. """ + # Track it generically too: the pidfile holds one server, while the + # process-lifetime record covers every child and is what the startup + # sweep reads where there is no parent-death signal (macOS). + try: + from utils.process_lifetime import adopt_pid + adopt_pid(pid) + except Exception as e: + logger.debug(f"Could not track llama-server for lifetime sweep: {e}") path = cls._server_pidfile_path() if path is None: return diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py index e6fc7f0b3b..0f7cb71f8b 100644 --- a/studio/backend/core/inference/tools.py +++ b/studio/backend/core/inference/tools.py @@ -9944,10 +9944,14 @@ def _capture_process_group(proc): """Return the setsid process-group id, or ``None`` when unavailable. Captured right after ``Popen`` so a later ``poll()`` / ``wait()`` that reaps - the leader cannot make ``os.getpgid(proc.pid)`` fail first. POSIX-only: - Windows has no process groups (and no ``os.getpgid``), so return ``None`` - there and let the single-pid ``proc.kill()`` fallback handle cleanup. + the leader cannot make ``os.getpgid(proc.pid)`` fail first. + + Windows has no process groups, so capture the wrapper pid instead, tagged + for ``_killpg_captured`` to reach with ``taskkill /T``; returning ``None`` + there left a payload that outlived its wrapper unsignalled. """ + if os.name == "nt": + return ("windows-tree", proc.pid) if os.name != "posix" or not hasattr(os, "getpgid"): return None try: @@ -9956,10 +9960,39 @@ def _capture_process_group(proc): return None +def _windows_taskkill_tree(pid: int) -> bool: + """``taskkill /T /F`` a pid and its descendants. True when it succeeded. + + Every tool call runs under a shell wrapper, and Windows has no process + groups, so a bare ``proc.kill()`` reaps the wrapper and orphans the payload + (usually the venv python), which then blocks `unsloth studio update`. + """ + if os.name != "nt": + return False + try: + completed = subprocess.run( + ["taskkill", "/PID", str(pid), "/T", "/F"], + capture_output = True, + timeout = 15, + creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0), + ) + except (OSError, subprocess.SubprocessError): + return False + return completed.returncode in (0, 128) # 128: already gone + + def _kill_process_tree(proc) -> None: """SIGKILL the setsid process group; fall back to single-pid kill.""" if proc.poll() is not None: return + if os.name == "nt": + if _windows_taskkill_tree(proc.pid): + return + try: + proc.kill() + except (ProcessLookupError, PermissionError): + pass + return pgid = None if hasattr(os, "getpgid"): try: @@ -9984,9 +10017,16 @@ def _killpg_captured(pgid) -> None: Once ``proc`` exits, ``os.getpgid(proc.pid)`` fails and ``_kill_process_tree`` short-circuits, so a stdout-holding grandchild that outlived the parent could not otherwise be signaled. The pre-captured setsid group id still targets the - whole tree. No-op with no ``os.killpg`` (Windows) or nothing captured. + whole tree. On Windows the capture is a tagged pid and the equivalent reach + is ``taskkill /T /F``. No-op when nothing was captured. """ - if pgid is None or not hasattr(os, "killpg"): + if pgid is None: + return + if isinstance(pgid, tuple): + _tag, pid = pgid + _windows_taskkill_tree(pid) + return + if not hasattr(os, "killpg"): return try: os.killpg(pgid, signal.SIGKILL) diff --git a/studio/backend/run.py b/studio/backend/run.py index 0f2ed42fec..155f6c0621 100644 --- a/studio/backend/run.py +++ b/studio/backend/run.py @@ -1136,6 +1136,57 @@ def _remove_pid_file(): pass +def _install_windows_console_handler(handler) -> bool: + """Run the graceful shutdown when the console window is closed. + + Closing the window raises CTRL_CLOSE_EVENT, which Python never turns into a + signal, so neither a signal handler nor atexit runs and cleanup is skipped. + Windows allows a few seconds here, enough to stop the sidecars that would + otherwise keep holding the install. No-op off Windows. + """ + if sys.platform != "win32": + return False + try: + import ctypes + from ctypes import wintypes + + CTRL_C_EVENT, CTRL_BREAK_EVENT = 0, 1 + CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT = 2, 5, 6 + HANDLER = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD) + + def _on_console_event(event: int) -> bool: + if event in (CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT): + try: + handler(signal.SIGTERM, None) + except Exception: + pass + return True + # Ctrl+C / Ctrl+Break already arrive as Python signals; pass them + # on rather than shutting down twice. + del CTRL_C_EVENT, CTRL_BREAK_EVENT + return False + + callback = HANDLER(_on_console_event) + kernel32 = ctypes.WinDLL("kernel32", use_last_error = True) + kernel32.SetConsoleCtrlHandler.argtypes = [HANDLER, wintypes.BOOL] + kernel32.SetConsoleCtrlHandler.restype = wintypes.BOOL + if not kernel32.SetConsoleCtrlHandler(callback, True): + logger.warning( + "Could not install the console-close handler (WinError %s); closing the " + "window will skip subprocess cleanup.", + ctypes.get_last_error(), + ) + return False + # Hold a reference: a collected callback leaves Windows calling into + # freed memory. + globals()["_WINDOWS_CONSOLE_HANDLER"] = callback + logger.info("Console-close handler installed") + return True + except Exception as error: + logger.warning("Could not install the console-close handler: %s", error) + return False + + def _graceful_shutdown(server = None): """Shut down all subprocess backends and the uvicorn server. @@ -1189,8 +1240,9 @@ def _graceful_shutdown(server = None): # 7. Backstop sweep for any adopted child the steps above missed. try: - from utils.process_lifetime import terminate_all + from utils.process_lifetime import clear_breadcrumb, terminate_all terminate_all() + clear_breadcrumb() # nothing left for the next startup to sweep except Exception as e: logger.warning("Error in process-lifetime sweep: %s", e) @@ -1849,9 +1901,18 @@ def run_server( # Reap every child if the parent dies abnormally (terminal close, Task # Manager kill, SIGKILL); must run before any child can spawn. - from utils.process_lifetime import initialize_parent_lifetime + from utils.process_lifetime import initialize_parent_lifetime, reap_recorded_children initialize_parent_lifetime() + # macOS has neither PR_SET_PDEATHSIG nor job objects, so a Studio that + # crashed left its sidecars running. Sweep before spawning anything: a + # leftover holds VRAM, a port, and the files an update has to replace. + try: + reaped = reap_recorded_children() + if reaped: + logger.warning("Reaped %d orphan(s) from a previous Studio: %s", len(reaped), reaped) + except Exception as e: + logger.warning("Could not sweep orphans from a previous run: %s", e) # --secure exposes ONLY the Cloudflare link: reject --secure --no-cloudflare, # then force a loopback bind so the raw port is never public (even -H 0.0.0.0). @@ -2488,6 +2549,8 @@ def _signal_handler(signum, frame): if hasattr(signal, "SIGBREAK"): signal.signal(signal.SIGBREAK, _signal_handler) + _install_windows_console_handler(_signal_handler) + # Keep running until shutdown signal. Event.wait() without a timeout blocks at # the C level on Linux, preventing SIGINT delivery; a short timeout in a loop # lets the interpreter process pending signals. diff --git a/studio/backend/tests/test_child_lifetime_boundary.py b/studio/backend/tests/test_child_lifetime_boundary.py new file mode 100644 index 0000000000..aa252d9c8f --- /dev/null +++ b/studio/backend/tests/test_child_lifetime_boundary.py @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""Where the Windows orphan guarantee holds, and where it stops. + +Children inherit a Job Object with KILL_ON_JOB_CLOSE. The desktop updater clears +that flag before launching the installer, so both sides are pinned here with +real processes. +""" + +import os +import subprocess +import sys +import textwrap +import time +from pathlib import Path + +import pytest + +IS_WINDOWS = sys.platform == "win32" +BACKEND = str(Path(__file__).resolve().parents[1]) + + +def _alive(pid: int) -> bool: + if IS_WINDOWS: + out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], + capture_output=True, text=True).stdout + return str(pid) in out + try: + os.kill(pid, 0) + except OSError: + return False + return True + + +def _kill(pid: int) -> None: + try: + if IS_WINDOWS: + subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True) + else: + os.kill(pid, 9) + except Exception: + pass + + +PARENT = textwrap.dedent( + """ + import os, subprocess, sys, time + sys.path.insert(0, sys.argv[1]) + if sys.argv[3] == "job": + from utils.process_lifetime import initialize_parent_lifetime + initialize_parent_lifetime() + from core.inference.tools import _get_shell_cmd + payload = ( + "import os,time,pathlib;" + "pathlib.Path(r'%s').write_text(str(os.getpid()));" + "time.sleep(180)" % sys.argv[2] + ) + argv = _get_shell_cmd('"%s" -c "%s"' % (sys.executable, payload)) + kw = {} + if sys.argv[3] == "job": + # The helper Studio's own spawns go through: PR_SET_PDEATHSIG on Linux, + # nothing on macOS, job inheritance on Windows. + from utils.process_lifetime import child_popen_kwargs + kw = child_popen_kwargs() + subprocess.Popen(argv, **kw) + time.sleep(180) + """ +) + + +def _run_case(tmp_path: Path, mode: str) -> bool: + """Start a parent, let it spawn a shell-wrapped payload, hard-kill the + parent, and report whether the payload survived.""" + pidfile = tmp_path / f"{mode}.pid" + script = tmp_path / f"parent_{mode}.py" + script.write_text(PARENT) + parent = subprocess.Popen([sys.executable, str(script), BACKEND, str(pidfile), mode]) + try: + for _ in range(200): + if pidfile.is_file() and pidfile.read_text().strip(): + break + time.sleep(0.1) + payload_pid = int(pidfile.read_text().strip()) + assert _alive(payload_pid) + + # Hard kill, no tree flag: exactly what "End Task" / a crash does. + if IS_WINDOWS: + subprocess.run(["taskkill", "/PID", str(parent.pid), "/F"], capture_output=True) + else: + os.kill(parent.pid, 9) + parent.wait(timeout=30) + time.sleep(5) + survived = _alive(payload_pid) + print(f"\n[{sys.platform}] mode={mode}: payload {payload_pid} survived = {survived}") + return survived + finally: + try: + _kill(int(pidfile.read_text().strip())) + except Exception: + pass + _kill(parent.pid) + + +@pytest.mark.skipif(not IS_WINDOWS, reason="job objects are Windows-only") +def test_job_object_reaps_the_whole_tree(tmp_path): + """With the guarantee in force, even a shell grandchild is reaped.""" + assert _run_case(tmp_path, "job") is False + + +@pytest.mark.skipif(not IS_WINDOWS, reason="job objects are Windows-only") +def test_without_the_job_the_grandchild_is_orphaned(tmp_path): + """This is the state the desktop updater leaves the app in: the job is + still there but KILL_ON_JOB_CLOSE has been cleared and nothing restores + it, so a hard exit leaks every child.""" + assert _run_case(tmp_path, "nojob") is True + + +@pytest.mark.skipif(IS_WINDOWS, reason="POSIX contrast") +def test_posix_orphan_behaviour(tmp_path): + """Linux reaps via PR_SET_PDEATHSIG on the direct child; macOS has no + equivalent and relies entirely on the cooperative shutdown path.""" + survived = _run_case(tmp_path, "job") + if sys.platform == "darwin": + assert survived, "macOS now reaps orphans -- update this repro" + else: + assert not survived + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-q", "-s"])) diff --git a/studio/backend/tests/test_orphaned_children.py b/studio/backend/tests/test_orphaned_children.py new file mode 100644 index 0000000000..dd0f87fde1 --- /dev/null +++ b/studio/backend/tests/test_orphaned_children.py @@ -0,0 +1,226 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0 + +"""No child outlives the Studio that spawned it. + +The chain this closes: a tool call runs under a shell wrapper, the kill path +reaped only the wrapper on Windows, and the orphaned venv python then made +`unsloth studio update` refuse to run until it was killed by hand. +""" + +import os +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +IS_WINDOWS = sys.platform == "win32" + + +def _alive(pid: int) -> bool: + if IS_WINDOWS: + out = subprocess.run( + ["tasklist", "/FI", f"PID eq {pid}", "/NH"], + capture_output=True, text=True, + ).stdout + return str(pid) in out + try: + os.kill(pid, 0) + except OSError: + return False + return True + + +def _kill(pid: int) -> None: + try: + if IS_WINDOWS: + subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True) + else: + os.kill(pid, 9) + except Exception: + pass + + +# --------------------------------------------------------------------------- +# 1. Killing a tool call takes the payload with it +# --------------------------------------------------------------------------- +def test_tool_kill_takes_the_shell_payload_with_it(tmp_path): + from core.inference.tools import _get_shell_cmd, _kill_process_tree + + pidfile = tmp_path / "child.pid" + payload = ( + f"import os,time,pathlib;" + f"pathlib.Path(r'{pidfile}').write_text(str(os.getpid()));" + f"time.sleep(120)" + ) + command = f'"{sys.executable}" -c "{payload}"' + argv = _get_shell_cmd(command) + print(f"\n[{sys.platform}] shell wrapper argv[0] = {argv[0]}") + + kwargs = {} + if not IS_WINDOWS: + kwargs["start_new_session"] = True # what the real spawn does on POSIX + proc = subprocess.Popen(argv, **kwargs) + + for _ in range(100): + if pidfile.is_file() and pidfile.read_text().strip(): + break + time.sleep(0.1) + grandchild = int(pidfile.read_text().strip()) + assert _alive(grandchild) + + try: + _kill_process_tree(proc) + proc.wait(timeout=10) + time.sleep(2.0) + survived = _alive(grandchild) + print(f"payload pid {grandchild} alive after _kill_process_tree: {survived}") + # Windows reaches the payload via taskkill /T /F, POSIX via killpg. It + # used to survive on Windows, orphaning the venv python that then blocked + # `unsloth studio update`. + assert not survived, "the payload under the shell wrapper was orphaned" + finally: + _kill(grandchild) + + +# --------------------------------------------------------------------------- +# 2. One surviving venv process blocks `unsloth studio update` (Windows) +# --------------------------------------------------------------------------- +@pytest.mark.skipif(not IS_WINDOWS, reason="the update gate is Windows-only") +def test_update_gate_blocks_on_a_single_orphan(tmp_path): + from unsloth_cli import _studio_runtime_gate + + studio_home = tmp_path / "studio_home" + venv = studio_home / "unsloth_studio" + subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(venv)], check=True) + venv_python = venv / "Scripts" / "python.exe" + assert venv_python.is_file() + + # No orphan: the gate lets the update through. + _studio_runtime_gate.ensure_managed_environment_is_idle(studio_home) + + orphan = subprocess.Popen([str(venv_python), "-c", "import time; time.sleep(120)"]) + try: + time.sleep(2.0) + with pytest.raises(RuntimeError) as excinfo: + _studio_runtime_gate.ensure_managed_environment_is_idle(studio_home) + print(f"\nupdate gate said: {excinfo.value}") + assert "in use by" in str(excinfo.value) + assert str(orphan.pid) in str(excinfo.value) + finally: + _kill(orphan.pid) + + +@pytest.mark.skipif(IS_WINDOWS, reason="contrast case for POSIX") +def test_update_gate_is_a_noop_on_posix(tmp_path): + """On Linux/macOS nothing checks for a running Studio before an update.""" + from unsloth_cli import _studio_runtime_gate + + _studio_runtime_gate.ensure_managed_environment_is_idle(tmp_path / "anything") + + +# --------------------------------------------------------------------------- +# 3. Shutdown paths that are not signals +# --------------------------------------------------------------------------- +def test_console_close_runs_the_graceful_shutdown(): + """Closing the console window is not a signal, so it needs its own handler.""" + import run + + assert hasattr(run, "_install_windows_console_handler") + if not IS_WINDOWS: + assert run._install_windows_console_handler(lambda *a: None) is False + return + + calls = [] + assert run._install_windows_console_handler(lambda *a: calls.append(a)) is True + + +def test_windows_job_status_is_reported(): + """A silent failure meant nobody could tell the guarantee was off.""" + from utils import process_lifetime + + process_lifetime.initialize_parent_lifetime() + in_force, detail = process_lifetime.windows_job_status() + print(f"\n[{sys.platform}] job status: in_force={in_force} detail={detail!r}") + assert detail != "not attempted" + if IS_WINDOWS or sys.platform.startswith("linux"): + assert in_force, detail + else: + # macOS: no kernel mechanism, so it must say so rather than imply cover. + assert not in_force + + +def test_macos_style_orphans_are_recorded_and_reaped(tmp_path, monkeypatch): + """The on-disk child record is the only reaper macOS has after a crash.""" + from utils import process_lifetime as pl + + record = tmp_path / "child_processes.json" + monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(record)) + pl._tracked_pids.clear() + + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) + try: + pl.adopt_pid(child.pid) + assert record.is_file(), "the child was not recorded" + + # Pretend a previous Studio wrote this and died. The identity is what + # decides, not the pid: a dead pid is recycled fast on a busy machine + # (macOS especially), and an owner whose start time no longer matches is + # a different process, so its recorded children are orphans. + import json + + payload = json.loads(record.read_text()) + payload["owner_identity"] = "a-previous-studio-that-is-gone" + record.write_text(json.dumps(payload)) + + reaped = pl.reap_recorded_children() + print(f"\nreaped: {reaped}") + assert child.pid in reaped + # Reap our own zombie so the liveness check means something. + child.wait(timeout=10) + assert not _alive(child.pid) + assert not record.exists(), "the record should be consumed" + finally: + _kill(child.pid) + + +def test_liveness_probe_does_not_kill_what_it_probes(): + """os.kill(pid, 0) is TerminateProcess on Windows, so the probe cannot use it.""" + from utils import process_lifetime as pl + + victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + try: + for _ in range(3): + assert pl._pid_alive(victim.pid) is True + time.sleep(0.3) + assert victim.poll() is None, "the liveness probe killed the process" + finally: + _kill(victim.pid) + + dead = subprocess.Popen([sys.executable, "-c", "pass"]) + dead.wait(timeout=30) + assert pl._pid_alive(dead.pid) is False + + +def test_a_live_owner_is_never_reaped(tmp_path, monkeypatch): + """Two Studios at once must not kill each other's children.""" + from utils import process_lifetime as pl + + record = tmp_path / "child_processes.json" + monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(record)) + pl._tracked_pids.clear() + + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + try: + pl.adopt_pid(child.pid) + # owner_pid is this process, which is very much alive. + assert pl.reap_recorded_children() == [] + assert _alive(child.pid) + finally: + _kill(child.pid) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "-q", "-s"])) diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py index 6c48e99394..acc35aec68 100644 --- a/studio/backend/utils/process_lifetime.py +++ b/studio/backend/utils/process_lifetime.py @@ -11,10 +11,14 @@ desktop app's job in studio/src-tauri/src/windows_job.rs. POSIX: each long-lived child sets prctl(PR_SET_PDEATHSIG) on Linux via a tiny -preexec hook (macOS has no equivalent and relies on the cooperative path + -terminate_all). Linux's signal is per-direct-child only, so multiprocessing +preexec hook. Linux's signal is per-direct-child only, so multiprocessing workers are also tracked for terminate_all. +macOS has neither mechanism, so tracked children are also recorded on disk and +the next startup sweeps whatever the previous run left behind +(reap_recorded_children). That record is the only reaper macOS has after a +crash, a Force Quit or a closed terminal. + Best-effort throughout: any failure degrades to today's behavior, never raises. Stdlib only. """ @@ -39,6 +43,47 @@ _tracked_pids: "dict[int, Optional[str]]" = {} # pid -> identity, reaped by terminate_all +# Whether cleanup-on-abnormal-exit is in force, and why not. A silent failure +# here leaks every child on a crash, so record it and log it. +_win_job_status: "tuple[bool, str]" = (False, "not attempted") + + +def _last_error(ctypes_module) -> int: + # get_last_error is Windows-only; a POSIX probe must not raise here. + getter = getattr(ctypes_module, "get_last_error", None) + try: + return int(getter()) if getter else 0 + except Exception: + return 0 + + +def _record_job_status(ok: bool, detail: str, last_error: int = 0) -> None: + global _win_job_status + if last_error: + detail = f"{detail} (WinError {last_error})" + _win_job_status = (ok, detail) + try: + import logging + + logger = logging.getLogger(__name__) + if ok: + logger.info("Child-process cleanup on abnormal exit: %s", detail) + else: + logger.warning( + "Child-process cleanup on abnormal exit is NOT guaranteed: %s. Children may " + "survive a crash or a force quit; the startup sweep reaps them on the next " + "launch.", + detail, + ) + except Exception: + pass + + +def windows_job_status() -> "tuple[bool, str]": + """(in_force, detail) for the Windows kill-on-close job.""" + return _win_job_status + + def _is_linux() -> bool: return sys.platform.startswith("linux") @@ -63,6 +108,11 @@ def initialize_parent_lifetime() -> None: _initialized = True if _is_windows(): _install_windows_job() + elif _is_linux(): + _record_job_status(True, "PR_SET_PDEATHSIG per child") + else: + # macOS: no pdeathsig, no job object; reap_recorded_children covers it. + _record_job_status(False, "no kernel-level parent-death signal on this platform") def _win_signatures(kernel32) -> None: @@ -132,23 +182,27 @@ class _EXT(ctypes.Structure): job = kernel32.CreateJobObjectW(None, None) if not job: + _record_job_status(False, "CreateJobObjectW failed", _last_error(ctypes)) return info = _EXT() info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE if not kernel32.SetInformationJobObject( job, _JobObjectExtendedLimitInformation, ctypes.byref(info), ctypes.sizeof(info) ): + _record_job_status(False, "SetInformationJobObject failed", _last_error(ctypes)) kernel32.CloseHandle(job) return # AssignProcessToJobObject(parent) makes children inherit the job. May # fail if Unsloth already runs inside an incompatible host job (pre-Win8); # degrade to the cooperative path rather than blocking startup. if not kernel32.AssignProcessToJobObject(job, kernel32.GetCurrentProcess()): + _record_job_status(False, "AssignProcessToJobObject failed", _last_error(ctypes)) kernel32.CloseHandle(job) return _win_job_handle = job # hold the handle so the job is not closed early - except Exception: - pass + _record_job_status(True, "kill-on-close job installed") + except Exception as error: + _record_job_status(False, f"{type(error).__name__}: {error}") # ── Child binding ── @@ -326,16 +380,33 @@ def child_popen_kwargs(preexec_fn: Optional[Callable[[], None]] = None) -> dict: def _pid_identity(pid: int) -> Optional[str]: - # Linux /proc starttime (stat field 22); pins identity so a reused pid is not - # signalled later. None (other platforms / unreadable) disables the check. - if not _is_linux(): - return None - try: - with open(f"/proc/{pid}/stat", encoding = "utf-8") as fh: - stat = fh.read() - return stat[stat.rfind(")") + 2 :].split()[19] # after comm: starttime - except Exception: - return None + # Start time pins identity so a reused pid is never signalled later. None + # (unreadable, or a platform with no cheap source) disables the check. + if _is_linux(): + try: + with open(f"/proc/{pid}/stat", encoding = "utf-8") as fh: + stat = fh.read() + return stat[stat.rfind(")") + 2 :].split()[19] # after comm: starttime + except Exception: + return None + if sys.platform == "darwin": + # No /proc; `ps -o lstart` is enough to spot a recycled pid. + try: + import subprocess + + out = subprocess.run( + ["ps", "-o", "lstart=,comm=", "-p", str(pid)], + capture_output = True, + text = True, + encoding = "utf-8", + errors = "replace", + timeout = 5, + ) + line = (out.stdout or "").strip() + return line or None + except Exception: + return None + return None def forget_pid(pid: Optional[int]) -> None: @@ -343,6 +414,174 @@ def forget_pid(pid: Optional[int]) -> None: signals a recycled pid.""" if pid: _tracked_pids.pop(pid, None) + _write_breadcrumb() + + +# ── Crash-survivable child record ── +# +# macOS has neither PR_SET_PDEATHSIG nor job objects, so a crash leaves every +# sidecar running. Record children as they are adopted; sweep the previous +# run's leftovers at startup. + + +def _breadcrumb_file(): + from pathlib import Path + + override = os.environ.get("UNSLOTH_STUDIO_CHILD_RECORD") + if override: + return Path(override) + try: + from utils.paths.storage_roots import studio_root + + return Path(studio_root()) / "run" / "child_processes.json" + except Exception: + return None + + +def _write_breadcrumb() -> None: + path = _breadcrumb_file() + if path is None: + return + try: + import json + + path.parent.mkdir(parents = True, exist_ok = True) + payload = { + "owner_pid": os.getpid(), + "owner_identity": _pid_identity(os.getpid()), + "children": [ + {"pid": pid, "identity": identity} for pid, identity in _tracked_pids.items() + ], + } + tmp = path.with_suffix(".tmp") + tmp.write_text(json.dumps(payload), encoding = "utf-8") + tmp.replace(path) + except Exception: + pass + + +def clear_breadcrumb() -> None: + """Drop the record after a clean shutdown; everything in it is already gone.""" + path = _breadcrumb_file() + if path is None: + return + try: + path.unlink(missing_ok = True) + except Exception: + pass + + +def _pid_alive(pid: int) -> bool: + if _is_windows(): + # NOT os.kill(pid, 0): that is TerminateProcess here, so the probe + # would kill the process it is asking about. + try: + import ctypes + from ctypes import wintypes + + SYNCHRONIZE = 0x0010_0000 + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + WAIT_TIMEOUT = 0x102 + ERROR_ACCESS_DENIED = 5 + + kernel32 = ctypes.WinDLL("kernel32", use_last_error = True) + kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD] + kernel32.WaitForSingleObject.restype = wintypes.DWORD + kernel32.CloseHandle.argtypes = [wintypes.HANDLE] + + handle = kernel32.OpenProcess( + SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, False, pid + ) + if not handle: + # ACCESS_DENIED means alive but another user's; else it is gone. + return _last_error(ctypes) == ERROR_ACCESS_DENIED + try: + # Signalled means exited; still waiting means running. + return kernel32.WaitForSingleObject(handle, 0) == WAIT_TIMEOUT + finally: + kernel32.CloseHandle(handle) + except Exception: + return False + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +def reap_recorded_children(timeout: float = 5.0) -> "list[int]": + """Kill children recorded by a previous Studio that is no longer running. + + Runs once at startup, before anything new spawns. A recycled pid is never + signalled: the recorded start-time identity has to still match. + """ + path = _breadcrumb_file() + if path is None or not path.is_file(): + return [] + killed: "list[int]" = [] + try: + import json + + record = json.loads(path.read_text(encoding = "utf-8")) + except Exception: + try: + path.unlink(missing_ok = True) + except Exception: + pass + return killed + + owner_pid = record.get("owner_pid") + owner_identity = record.get("owner_identity") + # Identity decides, not the pid: pids recycle, and this process may have + # inherited the pid of the Studio that wrote the record. + owner_matches = owner_identity is None or owner_identity == _pid_identity(owner_pid or -1) + if owner_pid == os.getpid() and owner_matches: + return killed # our own record + if isinstance(owner_pid, int) and owner_matches and _pid_alive(owner_pid): + return killed # that Studio is still running; its children are its own + + for entry in record.get("children") or []: + pid = entry.get("pid") + if not isinstance(pid, int) or not _pid_alive(pid): + continue + identity = entry.get("identity") + current = _pid_identity(pid) + # Definite mismatch only: the macOS probe shells out to `ps`, and a + # transient failure there must not silently disable the sweep. + if identity is not None and current is not None and identity != current: + continue # pid was recycled by an unrelated process + if _is_windows(): + try: + os.kill(pid, signal.SIGTERM) + except OSError: + pass + else: + _posix_terminate(pid, timeout = timeout) + # Counted once signalled: an unwaited child lingers as a zombie, which + # a liveness re-check would read as alive. + killed.append(pid) + + try: + path.unlink(missing_ok = True) + except Exception: + pass + if killed: + try: + import logging + + logging.getLogger(__name__).warning( + "Reaped %d orphaned child process(es) left by a previous Studio: %s", + len(killed), killed, + ) + except Exception: + pass + return killed def adopt_pid(pid: Optional[int]) -> None: @@ -352,6 +591,7 @@ def adopt_pid(pid: Optional[int]) -> None: if not pid: return _tracked_pids[pid] = _pid_identity(pid) + _write_breadcrumb() if _is_windows() and _win_job_handle: try: import ctypes diff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.ts index ec00dbc36d..381ba3528a 100644 --- a/studio/frontend/src/hooks/use-tauri-update.ts +++ b/studio/frontend/src/hooks/use-tauri-update.ts @@ -384,6 +384,9 @@ export function useTauriUpdate(isExternalServer = false) { } finally { // Success, failure and cancel alike: the installer is no longer running. publishShellUpdateActive(false); + // Reaching here means the installer did not replace us, so the + // cleanup the pre-exit hook stood down has to come back. + await invoke("resume_desktop_update_cleanup").catch(() => {}); } // relaunch() re-execs with the original argv, so flag the inherited --hidden as not a login diff --git a/studio/src-tauri/src/desktop_updater.rs b/studio/src-tauri/src/desktop_updater.rs index 344dddc4c2..b2b633a29f 100644 --- a/studio/src-tauri/src/desktop_updater.rs +++ b/studio/src-tauri/src/desktop_updater.rs @@ -13,6 +13,20 @@ pub(crate) struct DesktopUpdateMetadata { raw_json: serde_json::Value, } +/// Re-arm crash cleanup when the installer never took over. +/// +/// `on_before_exit` clears kill-on-close assuming the installer is about to +/// replace this process; a failed or cancelled install leaves the app running +/// with no reaper for its children. +#[tauri::command] +pub(crate) async fn resume_desktop_update_cleanup() -> Result<(), String> { + #[cfg(windows)] + { + crate::windows_job::resume_after_update_installer().map_err(|error| error.to_string())?; + } + Ok(()) +} + #[tauri::command] pub(crate) async fn check_desktop_update( webview: tauri::Webview, diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs index bd8dad5d80..3c97eab046 100644 --- a/studio/src-tauri/src/main.rs +++ b/studio/src-tauri/src/main.rs @@ -1036,6 +1036,7 @@ fn main() { desktop_update_policy::check_desktop_manual_update, desktop_update_policy::desktop_update_policy, desktop_updater::check_desktop_update, + desktop_updater::resume_desktop_update_cleanup, diagnostics::collect_support_diagnostics, native_clipboard::read_native_clipboard_files, native_clipboard::read_native_clipboard_png, diff --git a/studio/src-tauri/src/windows_job.rs b/studio/src-tauri/src/windows_job.rs index cc6ec37e16..65cbe44847 100644 --- a/studio/src-tauri/src/windows_job.rs +++ b/studio/src-tauri/src/windows_job.rs @@ -7,13 +7,18 @@ use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; #[cfg(windows)] use std::sync::OnceLock; #[cfg(windows)] +use windows_sys::Win32::Foundation::CloseHandle; +#[cfg(windows)] use windows_sys::Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, - QueryInformationJobObject, SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicProcessIdList, + JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject, + JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, }; #[cfg(windows)] -use windows_sys::Win32::System::Threading::GetCurrentProcess; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentProcessId, OpenProcess, TerminateProcess, PROCESS_TERMINATE, +}; #[cfg(windows)] static APP_JOB: OnceLock> = OnceLock::new(); @@ -95,21 +100,107 @@ unsafe fn set_kill_on_close(job: &OwnedHandle, enabled: bool) -> std::io::Result Ok(()) } +/// Every process currently assigned to the job, excluding this one. +#[cfg(windows)] +unsafe fn job_process_ids(job: &OwnedHandle) -> std::io::Result> { + // Variable-length list; a generous fixed buffer, and ERROR_MORE_DATA below + // still fills what fits. + const CAPACITY: usize = 512; + #[repr(C)] + struct ProcessIdList { + header: JOBOBJECT_BASIC_PROCESS_ID_LIST, + rest: [usize; CAPACITY], + } + + let mut buffer: ProcessIdList = std::mem::zeroed(); + if QueryInformationJobObject( + job.as_raw_handle(), + JobObjectBasicProcessIdList, + &mut buffer as *mut _ as *mut _, + size_of::() as u32, + std::ptr::null_mut(), + ) == 0 + { + let error = std::io::Error::last_os_error(); + if buffer.header.NumberOfProcessIdsInList == 0 { + return Err(error); + } + } + + let own = GetCurrentProcessId(); + let count = buffer.header.NumberOfProcessIdsInList as usize; + let first = buffer.header.ProcessIdList[0]; + let ids = std::iter::once(first) + .chain(buffer.rest.iter().copied()) + .take(count.min(CAPACITY + 1)) + .map(|id| id as u32) + .filter(|id| *id != 0 && *id != own) + .collect(); + Ok(ids) +} + +/// Terminate every other process in the app job, returning how many. +/// +/// Runs just before `suspend_for_update_installer`: once kill-on-close is +/// cleared nothing reaps the job, so whatever the cooperative stop missed would +/// outlive the app and hold the venv open against the installer. +#[cfg(windows)] +pub fn drain_job_children() -> std::io::Result { + let Some(job) = APP_JOB.get().and_then(Option::as_ref) else { + return Ok(0); + }; + + let ids = unsafe { job_process_ids(job) }?; + let mut terminated = 0; + for id in ids { + unsafe { + let handle = OpenProcess(PROCESS_TERMINATE, 0, id); + if handle.is_null() { + continue; // gone, or not ours to kill + } + if TerminateProcess(handle, 1) != 0 { + terminated += 1; + } + CloseHandle(handle); + } + } + if terminated > 0 { + warn!("Terminated {terminated} leftover child process(es) before suspending job cleanup"); + } + Ok(terminated) +} + /// Keep the updater-launched installer alive after Tauri exits this process. /// -/// The updater calls this from its native pre-exit hook after extraction and -/// immediately before it launches the installer. +/// Called from the updater's pre-exit hook, just before the installer launches. +/// Drains the job first: clearing kill-on-close removes the last backstop, and a +/// child that outlives the app keeps `%STUDIO_HOME%\unsloth_studio` open, which +/// is what makes the next `unsloth studio update` refuse to run. #[cfg(windows)] pub fn suspend_for_update_installer() -> std::io::Result<()> { let Some(job) = APP_JOB.get().and_then(Option::as_ref) else { return Ok(()); }; + drain_job_children()?; unsafe { set_kill_on_close(job, false) }?; info!("Windows job cleanup suspended for updater installer launch"); Ok(()) } +/// Re-arm crash cleanup after a suspension that did not end in an exit (a failed +/// or abandoned install). Without it the app runs on with no reaper at all. +#[cfg(windows)] +pub fn resume_after_update_installer() -> std::io::Result<()> { + let Some(job) = APP_JOB.get().and_then(Option::as_ref) else { + return Ok(()); + }; + + unsafe { set_kill_on_close(job, true) }?; + info!("Windows job cleanup re-armed after the updater did not exit"); + Ok(()) +} + #[cfg(all(test, windows))] mod tests { use super::*; From f7505ee2b37d75ac1babd6ed1c0786ca7b099d85 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 8 Aug 2026 11:54:59 +0000 Subject: [PATCH 2/5] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- .../tests/test_child_lifetime_boundary.py | 17 +++++++++-------- studio/backend/tests/test_orphaned_children.py | 18 +++++++++--------- studio/backend/utils/process_lifetime.py | 13 +++++++------ 3 files changed, 25 insertions(+), 23 deletions(-) diff --git a/studio/backend/tests/test_child_lifetime_boundary.py b/studio/backend/tests/test_child_lifetime_boundary.py index aa252d9c8f..2ab4567cdb 100644 --- a/studio/backend/tests/test_child_lifetime_boundary.py +++ b/studio/backend/tests/test_child_lifetime_boundary.py @@ -23,8 +23,9 @@ def _alive(pid: int) -> bool: if IS_WINDOWS: - out = subprocess.run(["tasklist", "/FI", f"PID eq {pid}", "/NH"], - capture_output=True, text=True).stdout + out = subprocess.run( + ["tasklist", "/FI", f"PID eq {pid}", "/NH"], capture_output = True, text = True + ).stdout return str(pid) in out try: os.kill(pid, 0) @@ -36,7 +37,7 @@ def _alive(pid: int) -> bool: def _kill(pid: int) -> None: try: if IS_WINDOWS: - subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True) + subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output = True) else: os.kill(pid, 9) except Exception: @@ -86,10 +87,10 @@ def _run_case(tmp_path: Path, mode: str) -> bool: # Hard kill, no tree flag: exactly what "End Task" / a crash does. if IS_WINDOWS: - subprocess.run(["taskkill", "/PID", str(parent.pid), "/F"], capture_output=True) + subprocess.run(["taskkill", "/PID", str(parent.pid), "/F"], capture_output = True) else: os.kill(parent.pid, 9) - parent.wait(timeout=30) + parent.wait(timeout = 30) time.sleep(5) survived = _alive(payload_pid) print(f"\n[{sys.platform}] mode={mode}: payload {payload_pid} survived = {survived}") @@ -102,13 +103,13 @@ def _run_case(tmp_path: Path, mode: str) -> bool: _kill(parent.pid) -@pytest.mark.skipif(not IS_WINDOWS, reason="job objects are Windows-only") +@pytest.mark.skipif(not IS_WINDOWS, reason = "job objects are Windows-only") def test_job_object_reaps_the_whole_tree(tmp_path): """With the guarantee in force, even a shell grandchild is reaped.""" assert _run_case(tmp_path, "job") is False -@pytest.mark.skipif(not IS_WINDOWS, reason="job objects are Windows-only") +@pytest.mark.skipif(not IS_WINDOWS, reason = "job objects are Windows-only") def test_without_the_job_the_grandchild_is_orphaned(tmp_path): """This is the state the desktop updater leaves the app in: the job is still there but KILL_ON_JOB_CLOSE has been cleared and nothing restores @@ -116,7 +117,7 @@ def test_without_the_job_the_grandchild_is_orphaned(tmp_path): assert _run_case(tmp_path, "nojob") is True -@pytest.mark.skipif(IS_WINDOWS, reason="POSIX contrast") +@pytest.mark.skipif(IS_WINDOWS, reason = "POSIX contrast") def test_posix_orphan_behaviour(tmp_path): """Linux reaps via PR_SET_PDEATHSIG on the direct child; macOS has no equivalent and relies entirely on the cooperative shutdown path.""" diff --git a/studio/backend/tests/test_orphaned_children.py b/studio/backend/tests/test_orphaned_children.py index dd0f87fde1..34ac9f8080 100644 --- a/studio/backend/tests/test_orphaned_children.py +++ b/studio/backend/tests/test_orphaned_children.py @@ -23,7 +23,8 @@ def _alive(pid: int) -> bool: if IS_WINDOWS: out = subprocess.run( ["tasklist", "/FI", f"PID eq {pid}", "/NH"], - capture_output=True, text=True, + capture_output = True, + text = True, ).stdout return str(pid) in out try: @@ -36,7 +37,7 @@ def _alive(pid: int) -> bool: def _kill(pid: int) -> None: try: if IS_WINDOWS: - subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True) + subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output = True) else: os.kill(pid, 9) except Exception: @@ -73,7 +74,7 @@ def test_tool_kill_takes_the_shell_payload_with_it(tmp_path): try: _kill_process_tree(proc) - proc.wait(timeout=10) + proc.wait(timeout = 10) time.sleep(2.0) survived = _alive(grandchild) print(f"payload pid {grandchild} alive after _kill_process_tree: {survived}") @@ -88,13 +89,13 @@ def test_tool_kill_takes_the_shell_payload_with_it(tmp_path): # --------------------------------------------------------------------------- # 2. One surviving venv process blocks `unsloth studio update` (Windows) # --------------------------------------------------------------------------- -@pytest.mark.skipif(not IS_WINDOWS, reason="the update gate is Windows-only") +@pytest.mark.skipif(not IS_WINDOWS, reason = "the update gate is Windows-only") def test_update_gate_blocks_on_a_single_orphan(tmp_path): from unsloth_cli import _studio_runtime_gate studio_home = tmp_path / "studio_home" venv = studio_home / "unsloth_studio" - subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(venv)], check=True) + subprocess.run([sys.executable, "-m", "venv", "--without-pip", str(venv)], check = True) venv_python = venv / "Scripts" / "python.exe" assert venv_python.is_file() @@ -113,11 +114,10 @@ def test_update_gate_blocks_on_a_single_orphan(tmp_path): _kill(orphan.pid) -@pytest.mark.skipif(IS_WINDOWS, reason="contrast case for POSIX") +@pytest.mark.skipif(IS_WINDOWS, reason = "contrast case for POSIX") def test_update_gate_is_a_noop_on_posix(tmp_path): """On Linux/macOS nothing checks for a running Studio before an update.""" from unsloth_cli import _studio_runtime_gate - _studio_runtime_gate.ensure_managed_environment_is_idle(tmp_path / "anything") @@ -179,7 +179,7 @@ def test_macos_style_orphans_are_recorded_and_reaped(tmp_path, monkeypatch): print(f"\nreaped: {reaped}") assert child.pid in reaped # Reap our own zombie so the liveness check means something. - child.wait(timeout=10) + child.wait(timeout = 10) assert not _alive(child.pid) assert not record.exists(), "the record should be consumed" finally: @@ -200,7 +200,7 @@ def test_liveness_probe_does_not_kill_what_it_probes(): _kill(victim.pid) dead = subprocess.Popen([sys.executable, "-c", "pass"]) - dead.wait(timeout=30) + dead.wait(timeout = 30) assert pl._pid_alive(dead.pid) is False diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py index acc35aec68..8bc44c9dc3 100644 --- a/studio/backend/utils/process_lifetime.py +++ b/studio/backend/utils/process_lifetime.py @@ -57,14 +57,17 @@ def _last_error(ctypes_module) -> int: return 0 -def _record_job_status(ok: bool, detail: str, last_error: int = 0) -> None: +def _record_job_status( + ok: bool, + detail: str, + last_error: int = 0, +) -> None: global _win_job_status if last_error: detail = f"{detail} (WinError {last_error})" _win_job_status = (ok, detail) try: import logging - logger = logging.getLogger(__name__) if ok: logger.info("Child-process cleanup on abnormal exit: %s", detail) @@ -432,7 +435,6 @@ def _breadcrumb_file(): return Path(override) try: from utils.paths.storage_roots import studio_root - return Path(studio_root()) / "run" / "child_processes.json" except Exception: return None @@ -527,7 +529,6 @@ def reap_recorded_children(timeout: float = 5.0) -> "list[int]": killed: "list[int]" = [] try: import json - record = json.loads(path.read_text(encoding = "utf-8")) except Exception: try: @@ -574,10 +575,10 @@ def reap_recorded_children(timeout: float = 5.0) -> "list[int]": if killed: try: import logging - logging.getLogger(__name__).warning( "Reaped %d orphaned child process(es) left by a previous Studio: %s", - len(killed), killed, + len(killed), + killed, ) except Exception: pass From c6634d52d6a3ad80747d1ae614e79b2e14c49bc5 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 8 Aug 2026 12:24:11 +0000 Subject: [PATCH 3/5] Review fixes: console handler must not touch signals, one child record per owner, drop the job drain - the console handler ran _signal_handler on the thread Windows creates for the event, where signal.signal raises, so closing the window did no cleanup at all - bound that work to the ~5s Windows allows before it kills the process - one record file per owner pid: two Studios can share a home, and a single file let the second erase the first's children - add a Windows process identity (creation time) and refuse to signal a pid that cannot be verified - drop the whole-job drain: it would also terminate the WebView2 hosts, and cleanup_child_processes already taskkills the backend tree --- studio/backend/run.py | 39 +++- .../backend/tests/test_orphaned_children.py | 33 ++- studio/backend/utils/process_lifetime.py | 204 +++++++++++------- studio/src-tauri/src/windows_job.rs | 88 +------- 4 files changed, 194 insertions(+), 170 deletions(-) diff --git a/studio/backend/run.py b/studio/backend/run.py index 155f6c0621..cb23f53bf9 100644 --- a/studio/backend/run.py +++ b/studio/backend/run.py @@ -1136,13 +1136,26 @@ def _remove_pid_file(): pass -def _install_windows_console_handler(handler) -> bool: +# Windows terminates the process ~5s after a close event, so leave a margin. +_CONSOLE_SHUTDOWN_BUDGET = 4.5 + + +def _run_console_shutdown(shutdown) -> None: + try: + shutdown() + except Exception as error: + logger.warning("Console-close cleanup failed: %s", error) + + +def _install_windows_console_handler(shutdown) -> bool: """Run the graceful shutdown when the console window is closed. Closing the window raises CTRL_CLOSE_EVENT, which Python never turns into a signal, so neither a signal handler nor atexit runs and cleanup is skipped. - Windows allows a few seconds here, enough to stop the sidecars that would - otherwise keep holding the install. No-op off Windows. + ``shutdown`` takes no arguments and must not touch signal.signal: Windows + runs this on a thread it creates for the event, and Windows kills the + process about five seconds later, so the work is bounded to fit. No-op off + Windows. """ if sys.platform != "win32": return False @@ -1154,12 +1167,15 @@ def _install_windows_console_handler(handler) -> bool: CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT = 2, 5, 6 HANDLER = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD) + import threading + def _on_console_event(event: int) -> bool: if event in (CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT): - try: - handler(signal.SIGTERM, None) - except Exception: - pass + worker = threading.Thread( + target = _run_console_shutdown, args = (shutdown,), daemon = True + ) + worker.start() + worker.join(timeout = _CONSOLE_SHUTDOWN_BUDGET) return True # Ctrl+C / Ctrl+Break already arrive as Python signals; pass them # on rather than shutting down twice. @@ -2549,7 +2565,14 @@ def _signal_handler(signum, frame): if hasattr(signal, "SIGBREAK"): signal.signal(signal.SIGBREAK, _signal_handler) - _install_windows_console_handler(_signal_handler) + # NOT _signal_handler: Windows runs this on a thread it creates, and + # signal.signal() off the main thread raises, which would leave the window + # close doing no cleanup at all. + def _console_shutdown(): + _graceful_shutdown(_server) + _shutdown_event.set() + + _install_windows_console_handler(_console_shutdown) # Keep running until shutdown signal. Event.wait() without a timeout blocks at # the C level on Linux, preventing SIGINT delivery; a short timeout in a loop diff --git a/studio/backend/tests/test_orphaned_children.py b/studio/backend/tests/test_orphaned_children.py index 34ac9f8080..11cf5113f2 100644 --- a/studio/backend/tests/test_orphaned_children.py +++ b/studio/backend/tests/test_orphaned_children.py @@ -156,13 +156,14 @@ def test_macos_style_orphans_are_recorded_and_reaped(tmp_path, monkeypatch): """The on-disk child record is the only reaper macOS has after a crash.""" from utils import process_lifetime as pl - record = tmp_path / "child_processes.json" - monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(record)) + records = tmp_path / "children" + monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(records)) pl._tracked_pids.clear() child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) try: pl.adopt_pid(child.pid) + record = records / f"{os.getpid()}.json" assert record.is_file(), "the child was not recorded" # Pretend a previous Studio wrote this and died. The identity is what @@ -204,12 +205,36 @@ def test_liveness_probe_does_not_kill_what_it_probes(): assert pl._pid_alive(dead.pid) is False +def test_a_second_studio_does_not_erase_the_first_record(tmp_path, monkeypatch): + """Two Studios can share a home; one record per owner keeps both tracked.""" + from utils import process_lifetime as pl + + records = tmp_path / "children" + monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(records)) + pl._tracked_pids.clear() + + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + try: + pl.adopt_pid(child.pid) + # A sibling Studio's record, written under its own pid. + import json + + other = records / "424242.json" + other.write_text(json.dumps({ + "owner_pid": 424242, "owner_identity": "a-studio-that-is-gone", "children": [], + })) + pl.adopt_pid(child.pid) # rewrites ours only + assert other.is_file(), "a sibling's record was erased" + assert (records / f"{os.getpid()}.json").is_file() + finally: + _kill(child.pid) + + def test_a_live_owner_is_never_reaped(tmp_path, monkeypatch): """Two Studios at once must not kill each other's children.""" from utils import process_lifetime as pl - record = tmp_path / "child_processes.json" - monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(record)) + monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(tmp_path / "children")) pl._tracked_pids.clear() child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py index 8bc44c9dc3..60dc235aad 100644 --- a/studio/backend/utils/process_lifetime.py +++ b/studio/backend/utils/process_lifetime.py @@ -57,17 +57,14 @@ def _last_error(ctypes_module) -> int: return 0 -def _record_job_status( - ok: bool, - detail: str, - last_error: int = 0, -) -> None: +def _record_job_status(ok: bool, detail: str, last_error: int = 0) -> None: global _win_job_status if last_error: detail = f"{detail} (WinError {last_error})" _win_job_status = (ok, detail) try: import logging + logger = logging.getLogger(__name__) if ok: logger.info("Child-process cleanup on abnormal exit: %s", detail) @@ -392,6 +389,36 @@ def _pid_identity(pid: int) -> Optional[str]: return stat[stat.rfind(")") + 2 :].split()[19] # after comm: starttime except Exception: return None + if _is_windows(): + # Creation time, so a recycled pid is never mistaken for the child that + # was recorded. Same purpose as starttime on Linux. + try: + import ctypes + from ctypes import wintypes + + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + kernel32 = ctypes.WinDLL("kernel32", use_last_error = True) + kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ + ctypes.POINTER(wintypes.FILETIME) + ] * 4 + kernel32.GetProcessTimes.restype = wintypes.BOOL + handle = kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid) + if not handle: + return None + try: + created = wintypes.FILETIME() + other = [wintypes.FILETIME() for _ in range(3)] + if not kernel32.GetProcessTimes( + handle, ctypes.byref(created), *[ctypes.byref(x) for x in other] + ): + return None + return f"{created.dwHighDateTime}:{created.dwLowDateTime}" + finally: + kernel32.CloseHandle(handle) + except Exception: + return None if sys.platform == "darwin": # No /proc; `ps -o lstart` is enough to spot a recycled pid. try: @@ -427,7 +454,7 @@ def forget_pid(pid: Optional[int]) -> None: # run's leftovers at startup. -def _breadcrumb_file(): +def _breadcrumb_dir(): from pathlib import Path override = os.environ.get("UNSLOTH_STUDIO_CHILD_RECORD") @@ -435,11 +462,19 @@ def _breadcrumb_file(): return Path(override) try: from utils.paths.storage_roots import studio_root - return Path(studio_root()) / "run" / "child_processes.json" + + return Path(studio_root()) / "run" / "children" except Exception: return None +def _breadcrumb_file(): + # One file per owner: two Studios can share a home (different ports), and a + # single shared file would let the second erase the first's children. + directory = _breadcrumb_dir() + return None if directory is None else directory / f"{os.getpid()}.json" + + def _write_breadcrumb() -> None: path = _breadcrumb_file() if path is None: @@ -463,14 +498,14 @@ def _write_breadcrumb() -> None: def clear_breadcrumb() -> None: - """Drop the record after a clean shutdown; everything in it is already gone.""" + """Drop our record after a clean shutdown; everything in it is already gone.""" path = _breadcrumb_file() - if path is None: - return - try: - path.unlink(missing_ok = True) - except Exception: - pass + if path is not None: + _unlink(path) + + +def _identity_or_none(pid) -> "Optional[str]": + return _pid_identity(pid) if isinstance(pid, int) and pid > 0 else None def _pid_alive(pid: int) -> bool: @@ -517,46 +552,101 @@ def _pid_alive(pid: int) -> bool: return True +def adopt_pid(pid: Optional[int]) -> None: + """Track a child (e.g. a multiprocessing worker started after the parent job + was set up) and, on Windows, assign it to the job as belt-and-suspenders. + Tolerates a None or already-exited pid.""" + if not pid: + return + _tracked_pids[pid] = _pid_identity(pid) + _write_breadcrumb() + if _is_windows() and _win_job_handle: + try: + import ctypes + from ctypes import wintypes + + kernel32 = ctypes.WinDLL("kernel32", use_last_error = True) + _win_signatures(kernel32) + kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] + kernel32.OpenProcess.restype = wintypes.HANDLE + PROCESS_SET_QUOTA, PROCESS_TERMINATE = 0x0100, 0x0001 + handle = kernel32.OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, pid) + if handle: + kernel32.AssignProcessToJobObject(_win_job_handle, handle) + kernel32.CloseHandle(handle) + except Exception: + pass + + +def terminate_all(timeout: float = 5.0) -> None: + """Backstop sweep over adopted pids, after per-subsystem cleanup. SIGTERM, + then SIGKILL the survivors after `timeout`. Skips a pid whose identity no + longer matches (recycled). Idempotent and teardown-safe.""" + for pid, identity in list(_tracked_pids.items()): + _tracked_pids.pop(pid, None) + if identity is not None and _pid_identity(pid) != identity: + continue # pid was reused by an unrelated process + try: + if _is_windows(): + os.kill(pid, signal.SIGTERM) + continue + _posix_terminate(pid, timeout) + except Exception: + pass + + def reap_recorded_children(timeout: float = 5.0) -> "list[int]": """Kill children recorded by a previous Studio that is no longer running. - Runs once at startup, before anything new spawns. A recycled pid is never - signalled: the recorded start-time identity has to still match. + Runs once at startup, before anything new spawns. Every record in the + directory is considered, so a Studio that crashed while a sibling was + running is still cleaned up. A child is only signalled when its recorded + start-time identity still matches, so a recycled pid is never touched. """ - path = _breadcrumb_file() - if path is None or not path.is_file(): + directory = _breadcrumb_dir() + if directory is None or not directory.is_dir(): return [] + killed: "list[int]" = [] + for path in sorted(directory.glob("*.json")): + killed.extend(_reap_one_record(path, timeout)) + return killed + + +def _reap_one_record(path, timeout: float) -> "list[int]": + import json + killed: "list[int]" = [] try: - import json record = json.loads(path.read_text(encoding = "utf-8")) except Exception: - try: - path.unlink(missing_ok = True) - except Exception: - pass + _unlink(path) return killed owner_pid = record.get("owner_pid") owner_identity = record.get("owner_identity") # Identity decides, not the pid: pids recycle, and this process may have # inherited the pid of the Studio that wrote the record. - owner_matches = owner_identity is None or owner_identity == _pid_identity(owner_pid or -1) + owner_matches = owner_identity is None or owner_identity == _identity_or_none(owner_pid) if owner_pid == os.getpid() and owner_matches: return killed # our own record if isinstance(owner_pid, int) and owner_matches and _pid_alive(owner_pid): return killed # that Studio is still running; its children are its own + unresolved = False for entry in record.get("children") or []: pid = entry.get("pid") if not isinstance(pid, int) or not _pid_alive(pid): continue identity = entry.get("identity") - current = _pid_identity(pid) - # Definite mismatch only: the macOS probe shells out to `ps`, and a - # transient failure there must not silently disable the sweep. - if identity is not None and current is not None and identity != current: - continue # pid was recycled by an unrelated process + current = _identity_or_none(pid) + if identity is None or current is None: + # Unverifiable: never signal a pid that might now be something else. + # Windows has no identity source here, and the Job Object already + # covers that case. + unresolved = True + continue + if identity != current: + continue # recycled by an unrelated process if _is_windows(): try: os.kill(pid, signal.SIGTERM) @@ -568,64 +658,26 @@ def reap_recorded_children(timeout: float = 5.0) -> "list[int]": # a liveness re-check would read as alive. killed.append(pid) - try: - path.unlink(missing_ok = True) - except Exception: - pass + if not unresolved: + _unlink(path) if killed: try: import logging + logging.getLogger(__name__).warning( "Reaped %d orphaned child process(es) left by a previous Studio: %s", - len(killed), - killed, + len(killed), killed, ) except Exception: pass return killed -def adopt_pid(pid: Optional[int]) -> None: - """Track a child (e.g. a multiprocessing worker started after the parent job - was set up) and, on Windows, assign it to the job as belt-and-suspenders. - Tolerates a None or already-exited pid.""" - if not pid: - return - _tracked_pids[pid] = _pid_identity(pid) - _write_breadcrumb() - if _is_windows() and _win_job_handle: - try: - import ctypes - from ctypes import wintypes - - kernel32 = ctypes.WinDLL("kernel32", use_last_error = True) - _win_signatures(kernel32) - kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD] - kernel32.OpenProcess.restype = wintypes.HANDLE - PROCESS_SET_QUOTA, PROCESS_TERMINATE = 0x0100, 0x0001 - handle = kernel32.OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, pid) - if handle: - kernel32.AssignProcessToJobObject(_win_job_handle, handle) - kernel32.CloseHandle(handle) - except Exception: - pass - - -def terminate_all(timeout: float = 5.0) -> None: - """Backstop sweep over adopted pids, after per-subsystem cleanup. SIGTERM, - then SIGKILL the survivors after `timeout`. Skips a pid whose identity no - longer matches (recycled). Idempotent and teardown-safe.""" - for pid, identity in list(_tracked_pids.items()): - _tracked_pids.pop(pid, None) - if identity is not None and _pid_identity(pid) != identity: - continue # pid was reused by an unrelated process - try: - if _is_windows(): - os.kill(pid, signal.SIGTERM) - continue - _posix_terminate(pid, timeout) - except Exception: - pass +def _unlink(path) -> None: + try: + path.unlink(missing_ok = True) + except Exception: + pass def _posix_terminate(pid: int, timeout: float = 5.0) -> None: diff --git a/studio/src-tauri/src/windows_job.rs b/studio/src-tauri/src/windows_job.rs index 65cbe44847..7c45e76972 100644 --- a/studio/src-tauri/src/windows_job.rs +++ b/studio/src-tauri/src/windows_job.rs @@ -7,18 +7,13 @@ use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; #[cfg(windows)] use std::sync::OnceLock; #[cfg(windows)] -use windows_sys::Win32::Foundation::CloseHandle; -#[cfg(windows)] use windows_sys::Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicProcessIdList, - JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject, - JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, + QueryInformationJobObject, SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, }; #[cfg(windows)] -use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, GetCurrentProcessId, OpenProcess, TerminateProcess, PROCESS_TERMINATE, -}; +use windows_sys::Win32::System::Threading::GetCurrentProcess; #[cfg(windows)] static APP_JOB: OnceLock> = OnceLock::new(); @@ -100,89 +95,18 @@ unsafe fn set_kill_on_close(job: &OwnedHandle, enabled: bool) -> std::io::Result Ok(()) } -/// Every process currently assigned to the job, excluding this one. -#[cfg(windows)] -unsafe fn job_process_ids(job: &OwnedHandle) -> std::io::Result> { - // Variable-length list; a generous fixed buffer, and ERROR_MORE_DATA below - // still fills what fits. - const CAPACITY: usize = 512; - #[repr(C)] - struct ProcessIdList { - header: JOBOBJECT_BASIC_PROCESS_ID_LIST, - rest: [usize; CAPACITY], - } - - let mut buffer: ProcessIdList = std::mem::zeroed(); - if QueryInformationJobObject( - job.as_raw_handle(), - JobObjectBasicProcessIdList, - &mut buffer as *mut _ as *mut _, - size_of::() as u32, - std::ptr::null_mut(), - ) == 0 - { - let error = std::io::Error::last_os_error(); - if buffer.header.NumberOfProcessIdsInList == 0 { - return Err(error); - } - } - - let own = GetCurrentProcessId(); - let count = buffer.header.NumberOfProcessIdsInList as usize; - let first = buffer.header.ProcessIdList[0]; - let ids = std::iter::once(first) - .chain(buffer.rest.iter().copied()) - .take(count.min(CAPACITY + 1)) - .map(|id| id as u32) - .filter(|id| *id != 0 && *id != own) - .collect(); - Ok(ids) -} - -/// Terminate every other process in the app job, returning how many. -/// -/// Runs just before `suspend_for_update_installer`: once kill-on-close is -/// cleared nothing reaps the job, so whatever the cooperative stop missed would -/// outlive the app and hold the venv open against the installer. -#[cfg(windows)] -pub fn drain_job_children() -> std::io::Result { - let Some(job) = APP_JOB.get().and_then(Option::as_ref) else { - return Ok(0); - }; - - let ids = unsafe { job_process_ids(job) }?; - let mut terminated = 0; - for id in ids { - unsafe { - let handle = OpenProcess(PROCESS_TERMINATE, 0, id); - if handle.is_null() { - continue; // gone, or not ours to kill - } - if TerminateProcess(handle, 1) != 0 { - terminated += 1; - } - CloseHandle(handle); - } - } - if terminated > 0 { - warn!("Terminated {terminated} leftover child process(es) before suspending job cleanup"); - } - Ok(terminated) -} - /// Keep the updater-launched installer alive after Tauri exits this process. /// /// Called from the updater's pre-exit hook, just before the installer launches. -/// Drains the job first: clearing kill-on-close removes the last backstop, and a -/// child that outlives the app keeps `%STUDIO_HOME%\unsloth_studio` open, which -/// is what makes the next `unsloth studio update` refuse to run. +/// `cleanup_child_processes` has already reaped the backend tree by then, which +/// is what has to be gone: a child that outlives the app keeps +/// `%STUDIO_HOME%\unsloth_studio` open and the next update refuses to run. #[cfg(windows)] pub fn suspend_for_update_installer() -> std::io::Result<()> { let Some(job) = APP_JOB.get().and_then(Option::as_ref) else { return Ok(()); }; - drain_job_children()?; unsafe { set_kill_on_close(job, false) }?; info!("Windows job cleanup suspended for updater installer launch"); Ok(()) From 67c9c556b889c5f59d06440244867065faaa20f5 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 8 Aug 2026 12:46:07 +0000 Subject: [PATCH 4/5] Harden the child record against a malformed or older file A record that is not an object, or whose children are not dicts, raised out of the startup sweep and would have stopped Studio from starting. Pair the Linux start time with the command name as well, since start time alone has 10ms granularity. --- .../backend/tests/test_orphaned_children.py | 33 +++++++++++++++++++ studio/backend/utils/process_lifetime.py | 13 ++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/studio/backend/tests/test_orphaned_children.py b/studio/backend/tests/test_orphaned_children.py index 11cf5113f2..1d80dcdc41 100644 --- a/studio/backend/tests/test_orphaned_children.py +++ b/studio/backend/tests/test_orphaned_children.py @@ -247,5 +247,38 @@ def test_a_live_owner_is_never_reaped(tmp_path, monkeypatch): _kill(child.pid) +@pytest.mark.parametrize("content", [ + "", "not json", "[]", "null", '{"children": "nope"}', + '{"children": [1, 2]}', '{"children": [{"pid": "x"}]}', +]) +def test_a_malformed_record_never_blocks_startup(tmp_path, monkeypatch, content): + """The sweep runs before the server binds, so it must not raise on a record + written by an older build or truncated by a power cut.""" + from utils import process_lifetime as pl + + directory = tmp_path / "children" + directory.mkdir() + monkeypatch.setenv("UNSLOTH_STUDIO_CHILD_RECORD", str(directory)) + (directory / "700000.json").write_text(content) + assert pl.reap_recorded_children() == [] + + +def test_identity_separates_two_processes_started_together(tmp_path): + """Linux starttime has 10ms granularity, so identity carries the command + name too: a recycled pid has to match both.""" + from utils import process_lifetime as pl + + first = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + second = subprocess.Popen(["sleep", "30"]) if not IS_WINDOWS else None + try: + assert pl._pid_identity(first.pid) == pl._pid_identity(first.pid) + if second is not None: + assert pl._pid_identity(first.pid) != pl._pid_identity(second.pid) + finally: + _kill(first.pid) + if second is not None: + _kill(second.pid) + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-q", "-s"])) diff --git a/studio/backend/utils/process_lifetime.py b/studio/backend/utils/process_lifetime.py index 60dc235aad..a0a10a6b03 100644 --- a/studio/backend/utils/process_lifetime.py +++ b/studio/backend/utils/process_lifetime.py @@ -386,7 +386,10 @@ def _pid_identity(pid: int) -> Optional[str]: try: with open(f"/proc/{pid}/stat", encoding = "utf-8") as fh: stat = fh.read() - return stat[stat.rfind(")") + 2 :].split()[19] # after comm: starttime + comm = stat[stat.find("(") + 1 : stat.rfind(")")] + # starttime has 10ms granularity, so pair it with comm: a recycled + # pid then has to match both. + return f"{stat[stat.rfind(')') + 2 :].split()[19]}:{comm}" except Exception: return None if _is_windows(): @@ -621,6 +624,9 @@ def _reap_one_record(path, timeout: float) -> "list[int]": except Exception: _unlink(path) return killed + if not isinstance(record, dict): + _unlink(path) + return killed owner_pid = record.get("owner_pid") owner_identity = record.get("owner_identity") @@ -633,8 +639,9 @@ def _reap_one_record(path, timeout: float) -> "list[int]": return killed # that Studio is still running; its children are its own unresolved = False - for entry in record.get("children") or []: - pid = entry.get("pid") + children = record.get("children") + for entry in children if isinstance(children, list) else []: + pid = entry.get("pid") if isinstance(entry, dict) else None if not isinstance(pid, int) or not _pid_alive(pid): continue identity = entry.get("identity") From d2b41006adb2de80d9249a712fc5298352c960e6 Mon Sep 17 00:00:00 2001 From: Daniel Han Date: Sat, 8 Aug 2026 12:50:56 +0000 Subject: [PATCH 5/5] Add staging CI workflows for unslothai/unsloth#8170 --- .github/workflows/staging-8170-macos-14.yml | 41 +++++++++++++++++++ .../workflows/staging-8170-ubuntu-latest.yml | 41 +++++++++++++++++++ .../workflows/staging-8170-windows-latest.yml | 41 +++++++++++++++++++ 3 files changed, 123 insertions(+) create mode 100644 .github/workflows/staging-8170-macos-14.yml create mode 100644 .github/workflows/staging-8170-ubuntu-latest.yml create mode 100644 .github/workflows/staging-8170-windows-latest.yml diff --git a/.github/workflows/staging-8170-macos-14.yml b/.github/workflows/staging-8170-macos-14.yml new file mode 100644 index 0000000000..d849964c0e --- /dev/null +++ b/.github/workflows/staging-8170-macos-14.yml @@ -0,0 +1,41 @@ +name: "staging-8170 macos-14" +on: + push: + branches: ["pr-8170-xplat-ci"] + paths: + - 'studio/backend/core/inference/llama_cpp.py' + - 'studio/backend/core/inference/tools.py' + - 'studio/backend/run.py' + - 'studio/backend/tests/test_child_lifetime_boundary.py' + - 'studio/backend/tests/test_orphaned_children.py' + - 'studio/backend/utils/process_lifetime.py' + - 'studio/frontend/src/hooks/use-tauri-update.ts' + - 'studio/src-tauri/src/desktop_updater.rs' + - 'studio/src-tauri/src/main.rs' + - 'studio/src-tauri/src/windows_job.rs' + - '.github/workflows/staging-8170-macos-14.yml' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash +jobs: + test: + runs-on: macos-14 + timeout-minutes: 30 + env: + UNSLOTH_COMPILE_DISABLE: '1' + UNSLOTH_IS_PRESENT: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r studio/backend/requirements/studio.txt pytest pytest-asyncio pytest-timeout python-multipart + - run: rc=0; PYTHONPATH=studio/backend python -m pytest studio/backend/tests/test_child_lifetime_boundary.py studio/backend/tests/test_orphaned_children.py -q --tb=short -k 'not llama_cpp_load_progress_live and not TestGpuAutoSelection and not TestPreSpawnGpuResolution and not TestPerGpuFitGuardAllCounts and not TestTransformersIntrospection and not test_returns_cuda_when_cuda_available and not test_calls_cuda_cache_when_cuda' || rc=$?; if [ "$rc" = "5" ]; then echo "no tests ran (deps absent on this runner)"; rc=0; fi; exit "$rc" diff --git a/.github/workflows/staging-8170-ubuntu-latest.yml b/.github/workflows/staging-8170-ubuntu-latest.yml new file mode 100644 index 0000000000..58083715ab --- /dev/null +++ b/.github/workflows/staging-8170-ubuntu-latest.yml @@ -0,0 +1,41 @@ +name: "staging-8170 ubuntu-latest" +on: + push: + branches: ["pr-8170-xplat-ci"] + paths: + - 'studio/backend/core/inference/llama_cpp.py' + - 'studio/backend/core/inference/tools.py' + - 'studio/backend/run.py' + - 'studio/backend/tests/test_child_lifetime_boundary.py' + - 'studio/backend/tests/test_orphaned_children.py' + - 'studio/backend/utils/process_lifetime.py' + - 'studio/frontend/src/hooks/use-tauri-update.ts' + - 'studio/src-tauri/src/desktop_updater.rs' + - 'studio/src-tauri/src/main.rs' + - 'studio/src-tauri/src/windows_job.rs' + - '.github/workflows/staging-8170-ubuntu-latest.yml' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: + UNSLOTH_COMPILE_DISABLE: '1' + UNSLOTH_IS_PRESENT: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r studio/backend/requirements/studio.txt pytest pytest-asyncio pytest-timeout python-multipart + - run: rc=0; PYTHONPATH=studio/backend python -m pytest studio/backend/tests/test_child_lifetime_boundary.py studio/backend/tests/test_orphaned_children.py -q --tb=short -k 'not llama_cpp_load_progress_live and not TestGpuAutoSelection and not TestPreSpawnGpuResolution and not TestPerGpuFitGuardAllCounts and not TestTransformersIntrospection and not test_returns_cuda_when_cuda_available and not test_calls_cuda_cache_when_cuda' || rc=$?; if [ "$rc" = "5" ]; then echo "no tests ran (deps absent on this runner)"; rc=0; fi; exit "$rc" diff --git a/.github/workflows/staging-8170-windows-latest.yml b/.github/workflows/staging-8170-windows-latest.yml new file mode 100644 index 0000000000..0ecc75c929 --- /dev/null +++ b/.github/workflows/staging-8170-windows-latest.yml @@ -0,0 +1,41 @@ +name: "staging-8170 windows-latest" +on: + push: + branches: ["pr-8170-xplat-ci"] + paths: + - 'studio/backend/core/inference/llama_cpp.py' + - 'studio/backend/core/inference/tools.py' + - 'studio/backend/run.py' + - 'studio/backend/tests/test_child_lifetime_boundary.py' + - 'studio/backend/tests/test_orphaned_children.py' + - 'studio/backend/utils/process_lifetime.py' + - 'studio/frontend/src/hooks/use-tauri-update.ts' + - 'studio/src-tauri/src/desktop_updater.rs' + - 'studio/src-tauri/src/main.rs' + - 'studio/src-tauri/src/windows_job.rs' + - '.github/workflows/staging-8170-windows-latest.yml' + workflow_dispatch: +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +permissions: + contents: read +defaults: + run: + shell: bash +jobs: + test: + runs-on: windows-latest + timeout-minutes: 30 + env: + UNSLOTH_COMPILE_DISABLE: '1' + UNSLOTH_IS_PRESENT: '1' + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r studio/backend/requirements/studio.txt pytest pytest-asyncio pytest-timeout python-multipart + - run: rc=0; PYTHONPATH=studio/backend python -m pytest studio/backend/tests/test_child_lifetime_boundary.py studio/backend/tests/test_orphaned_children.py -q --tb=short -k 'not llama_cpp_load_progress_live and not TestGpuAutoSelection and not TestPreSpawnGpuResolution and not TestPerGpuFitGuardAllCounts and not TestTransformersIntrospection and not test_returns_cuda_when_cuda_available and not test_calls_cuda_cache_when_cuda' || rc=$?; if [ "$rc" = "5" ]; then echo "no tests ran (deps absent on this runner)"; rc=0; fi; exit "$rc"