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" 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..cb23f53bf9 100644 --- a/studio/backend/run.py +++ b/studio/backend/run.py @@ -1136,6 +1136,73 @@ def _remove_pid_file(): pass +# 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. + ``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 + 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) + + import threading + + def _on_console_event(event: int) -> bool: + if event in (CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, CTRL_SHUTDOWN_EVENT): + 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. + 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 +1256,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 +1917,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 +2565,15 @@ def _signal_handler(signum, frame): if hasattr(signal, "SIGBREAK"): signal.signal(signal.SIGBREAK, _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 # 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..2ab4567cdb --- /dev/null +++ b/studio/backend/tests/test_child_lifetime_boundary.py @@ -0,0 +1,132 @@ +# 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..1d80dcdc41 --- /dev/null +++ b/studio/backend/tests/test_orphaned_children.py @@ -0,0 +1,284 @@ +# 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 + + 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 + # 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_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 + + 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)"]) + 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) + + +@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 6c48e99394..a0a10a6b03 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,66 @@ 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() + 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(): + # 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: + 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 +447,112 @@ 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_dir(): + 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" / "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: + 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 our record after a clean shutdown; everything in it is already gone.""" + path = _breadcrumb_file() + 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: + 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 adopt_pid(pid: Optional[int]) -> None: @@ -352,6 +562,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 @@ -387,6 +598,95 @@ def terminate_all(timeout: float = 5.0) -> None: 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. 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. + """ + 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: + record = json.loads(path.read_text(encoding = "utf-8")) + 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") + # 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 == _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 + 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") + 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) + 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) + + 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, + ) + except Exception: + pass + return killed + + +def _unlink(path) -> None: + try: + path.unlink(missing_ok = True) + except Exception: + pass + + def _posix_terminate(pid: int, timeout: float = 5.0) -> None: # SIGTERM, give the child up to `timeout` to exit, then SIGKILL. Reaping # belongs to the child's owner (or init for orphans). Prefer the group 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..7c45e76972 100644 --- a/studio/src-tauri/src/windows_job.rs +++ b/studio/src-tauri/src/windows_job.rs @@ -97,8 +97,10 @@ unsafe fn set_kill_on_close(job: &OwnedHandle, enabled: bool) -> std::io::Result /// 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. +/// `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 { @@ -110,6 +112,19 @@ pub fn suspend_for_update_installer() -> std::io::Result<()> { 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::*;