Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions .github/workflows/staging-8170-macos-14.yml
Original file line number Diff line number Diff line change
@@ -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"
41 changes: 41 additions & 0 deletions .github/workflows/staging-8170-ubuntu-latest.yml
Original file line number Diff line number Diff line change
@@ -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"
41 changes: 41 additions & 0 deletions .github/workflows/staging-8170-windows-latest.yml
Original file line number Diff line number Diff line change
@@ -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"
17 changes: 17 additions & 0 deletions studio/backend/core/inference/llama_cpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
50 changes: 45 additions & 5 deletions studio/backend/core/inference/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -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)
Expand Down
90 changes: 88 additions & 2 deletions studio/backend/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines +1182 to +1183

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return false for Ctrl events without deleting constants

On Windows, Ctrl+C and Ctrl+Break take this non-close branch, but del CTRL_C_EVENT, CTRL_BREAK_EVENT makes both names local to the callback and raises UnboundLocalError before return False. Because this runs through a ctypes console-control callback, the exception is reported/ignored at the callback boundary instead of intentionally passing the event onward to Python's signal handler, making Ctrl-event handling unreliable.

Useful? React with 👍 / 👎.


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.

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Record tool subprocesses for the macOS startup sweep

When Studio is killed on macOS during a Python or shell tool call, the child continues running because _python_exec and _shell_exec spawn at tools.py:10332 and tools.py:10457 without calling adopt_pid. Consequently this sweep has no record of those processes and cannot reap them on the next launch; a sleeping or file-holding tool payload can therefore survive indefinitely despite the new abnormal-exit cleanup.

Useful? React with 👍 / 👎.

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).
Expand Down Expand Up @@ -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.
Expand Down
Loading
Loading