Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Fix orphan server cleanup killing user's own llama-server (#4622)

Daniel Han1fb9fe330416
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 2b4ed3b2e6d..3f9bc0421ef 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -1367,27 +1367,33 @@ class LlamaCppBackend:
"""Kill orphaned llama-server processes started by studio.
Only kills processes whose resolved binary lives under a known
- Unsloth install directory to avoid terminating unrelated
- llama-server instances on the machine.
+ Studio install directory (or matches an exact env-var override)
+ to avoid terminating unrelated llama-server instances.
+
+ Mirrors every location that _find_llama_server_binary() can
+ return from so that orphans from any supported install path
+ are still cleaned up.
Uses psutil for cross-platform support (Linux, macOS, Windows).
+ Falls back to pgrep + /proc/<pid>/exe on Linux when psutil is
+ not installed.
"""
import os
+ import signal
+ import sys
try:
- import psutil
- except ImportError:
- return
-
- try:
- # Build the same set of directories that _find_llama_server_binary
- # searches, so we only kill servers we could have started.
+ # -- Build the ownership allowlist --------------------------------
+ # Two kinds of matches:
+ # exact_binaries -- env var overrides (exact path match only)
+ # install_roots -- directory trees that are Studio-owned
+ # (binary must be *under* one of these)
install_roots: list[Path] = []
- # ~/.unsloth/llama.cpp (primary install location)
+ # Primary install dir (setup.sh / prebuilt installer)
install_roots.append(Path.home() / ".unsloth" / "llama.cpp")
- # Legacy: in-tree build
+ # Legacy in-tree build dirs (older setup.sh versions)
project_root = Path(__file__).resolve().parents[4]
install_roots.append(project_root / "llama.cpp")
@@ -1418,40 +1424,103 @@ class LlamaCppBackend:
my_pid = os.getpid()
- for proc in psutil.process_iter(["pid", "name", "exe"]):
- try:
- if proc.info["pid"] == my_pid:
- continue
+ # -- Enumerate processes -------------------------------------------
+ # Prefer psutil (cross-platform). Fall back to pgrep + /proc on
+ # Linux when psutil is not installed.
+ try:
+ import psutil
- name = proc.info.get("name") or ""
- if not name.lower().startswith("llama-server"):
- continue
+ has_psutil = True
+ except ImportError:
+ has_psutil = False
- exe = proc.info.get("exe")
- if not exe:
- continue
+ if has_psutil:
+ for proc in psutil.process_iter(["pid", "name", "exe"]):
+ try:
+ if proc.info["pid"] == my_pid:
+ continue
- exe_path = Path(exe).resolve()
+ name = proc.info.get("name") or ""
+ if not name.lower().startswith("llama-server"):
+ continue
- # Check if this binary is one we manage
- is_ours = exe_path in exact_binaries or any(
- exe_path.is_relative_to(root) for root in resolved_roots
- )
- if not is_ours:
+ exe = proc.info.get("exe")
+ if not exe:
+ continue
+
+ exe_path = Path(exe).resolve()
+
+ # Check ownership: exact binary match OR binary is
+ # under a known install root (proper ancestry, not
+ # substring).
+ is_ours = exe_path in exact_binaries or any(
+ exe_path.is_relative_to(root) for root in resolved_roots
+ )
+ if not is_ours:
+ continue
+
+ proc.kill()
+ logger.info(
+ f"Killed orphaned llama-server process "
+ f"(pid={proc.info['pid']})"
+ )
+ except (
+ psutil.NoSuchProcess,
+ psutil.AccessDenied,
+ psutil.ZombieProcess,
+ ):
+ pass
+ else:
+ # -- Fallback: pgrep + /proc/<pid>/exe (Linux only) -----------
+ if sys.platform != "linux":
+ return
+ result = subprocess.run(
+ ["pgrep", "-a", "-f", "llama-server"],
+ capture_output = True,
+ text = True,
+ timeout = 5,
+ )
+ if result.returncode != 0:
+ return
+
+ for line in result.stdout.strip().splitlines():
+ parts = line.strip().split(None, 1)
+ if len(parts) < 2:
+ continue
+ pid = int(parts[0])
+ if pid == my_pid:
continue
- proc.kill()
- logger.info(
- f"Killed orphaned llama-server process (pid={proc.info['pid']})"
+ # Resolve the actual executable. /proc/<pid>/exe is a
+ # symlink to the real binary and avoids all cmdline-
+ # parsing ambiguities (spaces in paths, argv rewriting).
+ # Fall back to the first cmdline token when /proc is
+ # unavailable.
+ proc_exe = Path(f"/proc/{pid}/exe")
+ try:
+ binary = proc_exe.resolve(strict = True)
+ except (OSError, ValueError):
+ cmdline = parts[1]
+ token = cmdline.split()[0] if cmdline.strip() else ""
+ if not token:
+ continue
+ binary = Path(token).resolve(strict = False)
+
+ owned = binary in exact_binaries or any(
+ binary.is_relative_to(root) for root in resolved_roots
)
- except (
- psutil.NoSuchProcess,
- psutil.AccessDenied,
- psutil.ZombieProcess,
- ):
- pass
+ if not owned:
+ continue
+
+ try:
+ os.kill(pid, signal.SIGKILL)
+ logger.info(f"Killed orphaned llama-server process (pid={pid})")
+ except ProcessLookupError:
+ pass
+ except PermissionError:
+ pass
except Exception:
- pass
+ logger.warning("Error during orphan server cleanup", exc_info = True)
def _cleanup(self):
"""atexit handler to ensure llama-server is terminated."""