unsloth/studio/backend/utils/lifespan_shutdown.py
Daniel Han d97777e74a Studio: reliably reap an orphaned llama-server so GPU loads are not stuck on CPU
Once a model overflowed VRAM and Studio later died in a way that bypasses the
graceful path (SIGHUP from a closed terminal, SIGKILL/OOM, or a direct-uvicorn
launch), the llama-server child was orphaned and kept holding GPU memory. GPU
placement is recomputed every load from a live free-VRAM probe, so the leftover
process made every subsequent load (even a tiny model, even after a restart)
spill to system RAM until it was killed by hand.

The main llama-server spawn now records its PID to a pidfile under the active
studio root, removed on _kill_process. The startup reaper kills that exact PID
first (path-independent, so it catches an orphan the install-root match misses),
verifying it is still a llama-server to guard against PID reuse; the pidfile
only ever names a Studio-spawned server, so unrelated user processes (vllm,
games) are never touched. The existing root-gated enumeration stays as a
fallback. A belt-and-suspenders kill is also wired into the FastAPI lifespan
shutdown (before hardware/cache teardown) to cover the direct-uvicorn path that
run.py's signal handler does not.

PR_SET_PDEATHSIG is intentionally not used on the main spawn: llama-server is
launched on a pooled asyncio.to_thread worker, and a thread-scoped death signal
could prematurely kill a healthy server. The reaper runs before any model loads
on the next start, so it fully covers the user-visible problem.

Adds tests for the pidfile reap (kills a recorded live server, skips a reused
non-llama PID, cleans a stale/missing pidfile, clears on kill) and for the
lifespan kill (runs first, errors swallowed).
2026-06-18 07:07:24 +00:00

66 lines
2.5 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Resilient FastAPI lifespan shutdown cleanup.
On an abrupt shutdown (Windows console-close, interpreter teardown racing
uvicorn) the loop's default executor may already be dead, so an unguarded
``asyncio.to_thread`` raise here would abort the nested-lifespan unwind and
surface as "Application shutdown failed". Dependency-injected so it can be
unit-tested without the heavy backend import graph.
"""
import asyncio
import contextvars
import types
from typing import Callable, Optional
import structlog
logger = structlog.get_logger(__name__)
async def run_lifespan_shutdown(
terminate_downloads: Callable[[], None],
clear_compiled_cache: Callable[[], None],
hw_module: types.ModuleType,
kill_llama_server: Optional[Callable[[], None]] = None,
) -> None:
"""Run each shutdown step guarded so one failure can't skip the others; never raise."""
# Kill the llama-server child first, before clearing hardware/cache state, so a
# direct-uvicorn shutdown (which bypasses run.py's signal handler) cannot orphan a
# GPU process. The signal / _graceful_shutdown path already covers SIGTERM/SIGINT.
if kill_llama_server is not None:
try:
kill_llama_server()
except Exception as exc:
logger.warning("kill_llama_server failed at shutdown: %s", exc)
loop = asyncio.get_running_loop()
# Copy context for parity with asyncio.to_thread. Schedule and await
# separately so a dead executor (raises at submit) runs inline, while a
# body exception (raised at await) is logged, not re-run.
ctx = contextvars.copy_context()
try:
future = loop.run_in_executor(None, ctx.run, terminate_downloads)
except RuntimeError:
# Executor gone: run inline on the loop thread.
try:
ctx.run(terminate_downloads)
except Exception as exc:
logger.warning("terminate_downloads (inline) failed at shutdown: %s", exc)
else:
try:
await future
except Exception as exc:
logger.warning("terminate_downloads failed at shutdown: %s", exc)
try:
hw_module.DEVICE = None
except Exception as exc:
logger.warning("clearing hardware DEVICE failed at shutdown: %s", exc)
try:
clear_compiled_cache()
except Exception as exc:
logger.warning("clear_compiled_cache failed at shutdown: %s", exc)