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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: cut backend start time and stop blocking the event loop (#8498)
Daniel Hand7e88a816d3b
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex f156e6bf533..4df402ed506 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -3251,6 +3251,10 @@ class CountAborted(Exception):__slots__ = ()+# Module level so tests can point the orphan sweep at a fixture tree.+_PROC_ROOT = "/proc"++class LlamaCppBackend:"""Manages a llama-server subprocess for GGUF model inference.@@ -3434,6 +3438,9 @@ class LlamaCppBackend:self._mtp_runtime_fallback_active = Falseself._stdout_lines: list[str] = []self._stdout_thread: Optional[threading.Thread] = None+ # Wakes the health probe on subprocess readiness/exit, so a ready or crashed+ # server is not hidden behind the 500 ms fallback poll.+ self._health_probe_event = threading.Event()# llama-server tee log (see _drain_stdout / _kill_process).self._llama_log_fh = Noneself._llama_log_path: Optional[Path] = None@@ -7005,6 +7012,13 @@ class LlamaCppBackend:line = line.rstrip()if line:self._stdout_lines.append(line)+ # Two forms across llama.cpp builds. Only readiness lines wake the+ # probe: waking on every tensor-load log spins startup.+ line_lower = line.lower()+ if "server is listening" in line_lower or "model loaded" in line_lower:+ health_probe_event = getattr(self, "_health_probe_event", None)+ if health_probe_event is not None:+ health_probe_event.set()logger.debug(f"[llama-server] {line}")fh = getattr(self, "_llama_log_fh", None)if fh is not None:@@ -7018,6 +7032,11 @@ class LlamaCppBackend:# Never let the drain thread die: a full stdout pipe can deadlock# llama-server (Windows). Pipe-closed on exit is the common case.logger.debug("llama-server stdout drain stopped", exc_info = True)+ finally:+ # EOF means the process exited; wake the health loop immediately.+ health_probe_event = getattr(self, "_health_probe_event", None)+ if health_probe_event is not None:+ health_probe_event.set()# GGUF KV type sizes for fast skipping_GGUF_TYPE_SIZE = {@@ -14574,9 +14593,16 @@ class LlamaCppBackend:_find_llama_server_binary() can return, so orphans from anysupported install path are cleaned up.- Uses psutil for cross-platform support (Linux, macOS, Windows);- falls back to pgrep + /proc/<pid>/exe on Linux when psutil is- absent.+ Reads /proc directly on Linux and uses psutil elsewhere (macOS, Windows).+ The pgrep fallback the psutil-less path used to take is gone: /proc is+ what that fallback read anyway, and psutil is a hard dependency, so it+ was unreachable from both directions.++ Candidates are collected first and killed afterwards, so an enumeration+ that fails part way kills nothing rather than some. The parent check+ therefore runs after enumeration rather than during it; a parent that+ exits in between makes the process a genuine orphan, and the start-time+ check below still refuses to signal a PID that has been reused.Returns the count of processes killed; callers arm the VRAM-settlewait on a positive count.@@ -14641,108 +14667,169 @@ class LlamaCppBackend:my_pid = os.getpid()- # -- Enumerate processes -------------------------------------------- # Prefer psutil (cross-platform); fall back to pgrep + /proc on- # Linux when psutil is absent.- try:- import psutil- has_psutil = True- except ImportError:- has_psutil = False+ # -- Enumerate candidate processes ---------------------------------+ # (pid, resolved binary, kill callable) per llama-server-looking process;+ # ownership, orphan and kill handling is shared below so the paths agree.+ candidates = []- if has_psutil:- for proc in psutil.process_iter(["pid", "name", "exe"]):- try:- if proc.info["pid"] == my_pid:- continue+ def _looks_like_server(name):+ return bool(name) and name.lower().startswith("llama-server")- name = proc.info.get("name") or ""- if not name.lower().startswith("llama-server"):- continue+ def _stat_start_time(line):+ right = line.rfind(b")")+ fields = line[right + 2 :].split()+ return fields[19] if len(fields) > 19 else None- exe = proc.info.get("exe")- if not exe:- continue+ def _proc_start_time(proc_dir):+ """Field 22 of /proc/<pid>/stat, in jiffies since boot."""+ try:+ with open(f"{proc_dir}/stat", "rb") as fh:+ line = fh.read()+ except OSError:+ return None+ right = line.rfind(b")")+ if right < 0:+ return None+ # Fields after comm start at field 3, so starttime is index 19.+ fields = line[right + 2 :].split()+ return fields[19] if len(fields) > 19 else None++ def _make_signal_killer(proc_dir, pid, start_time):+ def _kill():+ # psutil.Process.kill() refuses to signal a reused PID, so re-check+ # identity here too: starttime never changes for a process and a reused+ # PID gets a later one, so a mismatch means this is not our process.+ if start_time is None or _proc_start_time(proc_dir) != start_time:+ return False+ try:+ os.kill(pid, signal.SIGKILL)+ except (ProcessLookupError, PermissionError):+ return False+ return True- exe_path = Path(exe).resolve()+ return _kill++ # /proc is Linux only; a missing one falls back to psutil rather than finding+ # nothing. Tests point _PROC_ROOT elsewhere to drive either path.+ proc_root = _PROC_ROOT+ if sys.platform == "linux" and os.path.isdir(proc_root):+ # psutil.process_iter(["pid", "name", "exe"]) reads /proc/<pid>/stat several+ # times per process and resolves exe for every one before the name rejects+ # almost all. This sweep runs on every backend start and every temporary+ # LlamaCppBackend(), so read comm once and resolve exe only on a name match.+ def _proc_exe(proc_dir):+ try:+ target = os.readlink(f"{proc_dir}/exe")+ except OSError:+ return None+ if not target:+ return None+ # The kernel appends " (deleted)" once the binary is replaced or removed,+ # which is what an upgrade's orphan looks like. psutil strips the marker,+ # so strip it here too or that orphan stops being recognised as ours.+ if target.endswith(" (deleted)") and not os.path.exists(target):+ target = target[: -len(" (deleted)")]+ try:+ return Path(target).resolve()+ except OSError:+ return None- # Ownership: exact match OR binary under a known root.- is_ours = exe_path in exact_binaries or any(- exe_path.is_relative_to(root) for root in resolved_roots- )- if not is_ours:+ with os.scandir(proc_root) as entries:+ for entry in entries:+ if not entry.name.isdigit():continue-- # A live parent means a running Unsloth (or the user's- # shell) still owns it -- not an orphan.- if LlamaCppBackend._pid_parent_is_alive(proc.info["pid"]):+ try:+ pid = int(entry.name)+ except ValueError:continue-- proc.kill()- killed += 1- logger.info(- f"Killed orphaned llama-server process (pid={proc.info['pid']})"+ if pid == my_pid:+ continue+ try:+ with open(f"{entry.path}/stat", "rb") as fh:+ stat_line = fh.read()+ except OSError:+ continue # the process exited mid-scan+ left = stat_line.find(b"(")+ right = stat_line.rfind(b")")+ if left < 0 or right <= left:+ continue+ # comm is truncated to 15 bytes, which still leaves the 12-byte+ # "llama-server" prefix intact, so this selects the names psutil does.+ name = stat_line[left + 1 : right].decode("utf-8", "replace")+ if not _looks_like_server(name):+ continue+ exe_path = _proc_exe(entry.path)+ if exe_path is None:+ continue+ candidates.append(+ (+ pid,+ exe_path,+ _make_signal_killer(entry.path, pid, _stat_start_time(stat_line)),+ ))- except (- psutil.NoSuchProcess,- psutil.AccessDenied,- psutil.ZombieProcess,- ):- passelse:- # -- Fallback: pgrep + /proc/<pid>/exe (Linux only) ------------ if sys.platform != "linux":- return killed- result = subprocess.run(- ["pgrep", "-a", "-f", "llama-server"],- capture_output = True,- text = True,- encoding = "utf-8",- errors = "replace",- timeout = 5,- env = child_env_without_native_path_secret(),- )- if result.returncode != 0:- return killed+ try:+ import psutil+ except ImportError:+ psutil = None- 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+ if psutil is not None:- # /proc/<pid>/exe symlinks the real binary, avoiding- # cmdline-parsing ambiguities; 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)+ def _make_psutil_killer(psutil_mod, proc):+ def _kill():+ try:+ proc.kill()+ except (+ psutil_mod.NoSuchProcess,+ psutil_mod.AccessDenied,+ psutil_mod.ZombieProcess,+ ):+ return False+ return True- owned = binary in exact_binaries or any(- binary.is_relative_to(root) for root in resolved_roots- )- if not owned:- continue+ return _kill- if LlamaCppBackend._pid_parent_is_alive(pid):- continue+ for proc in psutil.process_iter(["pid", "name", "exe"]):+ try:+ pid = proc.info["pid"]+ if pid == my_pid:+ continue+ if not _looks_like_server(proc.info.get("name") or ""):+ continue+ exe = proc.info.get("exe")+ if not exe:+ continue+ candidates.append(+ (pid, Path(exe).resolve(), _make_psutil_killer(psutil, proc))+ )+ except (+ psutil.NoSuchProcess,+ psutil.AccessDenied,+ psutil.ZombieProcess,+ ):+ pass+ else:+ # Unreachable while the Linux branch above exists; kept so the+ # psutil-less path stays correct if that changes.+ return killed- try:- os.kill(pid, signal.SIGKILL)- killed += 1- logger.info(f"Killed orphaned llama-server process (pid={pid})")- except ProcessLookupError:- pass- except PermissionError:- pass+ # -- Ownership check, orphan check, kill ---------------------------+ for pid, binary, kill in candidates:+ # Ownership: exact match OR binary under a known root.+ is_ours = binary in exact_binaries or any(+ binary.is_relative_to(root) for root in resolved_roots+ )+ if not is_ours:+ continue++ # A live parent means a running Unsloth (or the user's shell) still owns it.+ if LlamaCppBackend._pid_parent_is_alive(pid):+ continue++ if kill():+ killed += 1+ logger.info(f"Killed orphaned llama-server process (pid={pid})")except Exception:logger.warning("Error during orphan server cleanup", exc_info = True)return killed@@ -15227,8 +15314,14 @@ class LlamaCppBackend:"""Poll llama-server's /health until 200; also detect early exit/crash."""deadline = time.monotonic() + timeouturl = f"{self.base_url}/health"+ health_probe_event = getattr(self, "_health_probe_event", None)+ if health_probe_event is None: # Backward-compatible with lightweight test doubles.+ health_probe_event = self._health_probe_event = threading.Event()while time.monotonic() < deadline:+ # Cleared before probing so output during the request stays latched for+ # the fallback wait below.+ health_probe_event.clear()# Process crashed?if self._process.poll() is not None:# Let the drain thread collect final output.@@ -15266,7 +15359,7 @@ class LlamaCppBackend:):pass- time.sleep(interval)+ health_probe_event.wait(interval)# Leave a marker so _classify_llama_start_failure tells a live but# never-healthy load (too large, or a proxy hijacking the loopbackdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 889be03341a..e321a9d8ebb 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -27,7 +27,7 @@ from fastapi import (from fastapi.encoders import jsonable_encoderfrom fastapi.responses import StreamingResponse, JSONResponse, PlainTextResponse, Responsefrom starlette.requests import ClientDisconnect-from typing import Any, Callable, Collection, List, NamedTuple, Optional, Union+from typing import Any, Callable, Collection, List, NamedTuple, Optional, TYPE_CHECKING, Unionimport jsonimport httpxfrom loggers import get_logger@@ -2320,9 +2320,11 @@ from utils.utils import is_hf_authentication_error, safe_error_detail, log_and_himport ioimport base64-import numpy as npfrom datetime import date as _date+if TYPE_CHECKING:+ import numpy as np+router = APIRouter()# Unsloth-only router (not mounted on /v1 OpenAI-compat).studio_router = APIRouter()@@ -9152,6 +9154,15 @@ async def get_api_monitor_entry(entry_id: str, current_subject: str = Depends(gereturn entry+def _decode_and_resize_image(backend, encoded: str):+ """Decode one request image and run Pillow resampling off the event loop."""+ from PIL import Image+ from io import BytesIO++ image_data = base64.b64decode(encoded)+ return backend.resize_image(Image.open(BytesIO(image_data)))++@router.post("/generate/stream")async def generate_stream(request: GenerateRequest,@@ -9174,10 +9185,6 @@ async def generate_stream(image = Noneif request.image_base64:try:- import base64- from PIL import Image- from io import BytesIO-# Check current model supports visionmodel_info = backend.models.get(backend.active_model_name, {})if not model_info.get("is_vision"):@@ -9186,9 +9193,11 @@ async def generate_stream(detail = "Image provided but current model is text-only. Load a vision model.",)- image_data = base64.b64decode(request.image_base64)- image = Image.open(BytesIO(image_data))- image = backend.resize_image(image)+ image = await asyncio.to_thread(+ _decode_and_resize_image,+ backend,+ request.image_base64,+ )except HTTPException:raise@@ -10350,7 +10359,7 @@ async def transcribe_audio_raw(# =====================================================================-def _decode_audio_base64(b64: str) -> np.ndarray:+def _decode_audio_base64(b64: str) -> "np.ndarray":"""Decode base64 audio (any format) → float32 numpy array at 16kHz."""import torchaudioimport tempfile@@ -10405,13 +10414,14 @@ def _sniff_audio_container(raw: bytes) -> Optional[str]:return None-def _mono_f32_to_wav_bytes(arr: np.ndarray, sample_rate: int) -> bytes:+def _mono_f32_to_wav_bytes(arr: "np.ndarray", sample_rate: int) -> bytes:"""Encode a mono float32 array as 16-bit PCM WAV bytes.Torch-free (numpy + stdlib only) so it works on no-torch GGUF-only installs;the shared audio_codecs helper pulls in torch at import time."""import io+ import numpy as npimport wavearr = np.nan_to_num(np.asarray(arr, dtype = np.float32).flatten(), posinf = 0.0, neginf = 0.0)@@ -10431,8 +10441,10 @@ def _mono_f32_to_wav_bytes(arr: np.ndarray, sample_rate: int) -> bytes:return buf.getvalue()-def _resample_mono_linear(arr: np.ndarray, source_rate: int, target_rate: int) -> np.ndarray:+def _resample_mono_linear(arr: "np.ndarray", source_rate: int, target_rate: int) -> "np.ndarray":"""Small numpy-only resampler for upload size limiting."""+ import numpy as np+if source_rate <= 0 or target_rate <= 0 or source_rate == target_rate:return arrduration = len(arr) / float(source_rate)@@ -10444,7 +10456,9 @@ def _resample_mono_linear(arr: np.ndarray, source_rate: int, target_rate: int) -return np.interp(target_x, source_x, arr).astype(np.float32)-def _fit_transcoded_audio_to_wav_cap(arr: np.ndarray, sample_rate: int) -> tuple[np.ndarray, int]:+def _fit_transcoded_audio_to_wav_cap(+ arr: "np.ndarray", sample_rate: int+) -> "tuple[np.ndarray, int]":"""Downsample only when needed so transcoded WAV stays within the upload cap."""if sample_rate <= 0:raise ValueError("decoded audio has an invalid sample rate")@@ -10464,7 +10478,7 @@ def _fit_transcoded_audio_to_wav_cap(arr: np.ndarray, sample_rate: int) -> tuplereturn fitted, target_rate-def _decode_audio_mono(raw: bytes) -> tuple[np.ndarray, int]:+def _decode_audio_mono(raw: bytes) -> "tuple[np.ndarray, int]":"""Decode audio bytes to (mono float32 array, native sample_rate).soundfile (libsndfile) reads wav/mp3/ogg/flac straight from memory. librosa@@ -12062,7 +12076,7 @@ async def openai_chat_completions(logger.warning("Audio decode failed: %s", e, exc_info = True)raise _reject(400, "Could not decode the provided audio file.")- gguf_messages, _ = _openai_messages_for_gguf_chat(+ gguf_messages, _ = await _openai_messages_for_gguf_chat_async(payload,llama_backend.is_vision,)@@ -13503,10 +13517,6 @@ async def openai_chat_completions(if image_b64:try:- import base64- from PIL import Image- from io import BytesIO-model_info = backend.models.get(backend.active_model_name, {})if not model_info.get("is_vision"):raise HTTPException(@@ -13514,9 +13524,11 @@ async def openai_chat_completions(detail = "Image provided but current model is text-only. Load a vision model.",)- image_data = base64.b64decode(image_b64)- image = Image.open(BytesIO(image_data))- image = backend.resize_image(image)+ image = await asyncio.to_thread(+ _decode_and_resize_image,+ backend,+ image_b64,+ )except HTTPException:raise@@ -16289,7 +16301,7 @@ async def _responses_stream(# Streaming /v1/responses builds the passthrough body directly (bypassing# openai_chat_completions), so apply recommended sampling here too._fill_recommended_sampling_openai(chat_req, getattr(llama_backend, "model_identifier", None))- body = _build_openai_passthrough_body(+ body = await _build_openai_passthrough_body_async(chat_req, backend_ctx = llama_backend.context_length, llama_backend = llama_backend)body["stream_options"] = {"include_usage": True}@@ -18006,7 +18018,17 @@ async def anthropic_messages(# Enforce vision guard + re-encode embedded images to PNG so the Anthropic# endpoint matches /v1/chat/completions.- _has_image = _normalize_anthropic_openai_images(openai_messages, llama_backend.is_vision)+ if _anthropic_request_has_image(payload):+ _has_image = await asyncio.to_thread(+ _normalize_anthropic_openai_images,+ openai_messages,+ llama_backend.is_vision,+ )+ else:+ _has_image = _normalize_anthropic_openai_images(+ openai_messages,+ llama_backend.is_vision,+ )# Fill omitted sampling fields with the per-model recommendation (or an operator# UNSLOTH_SAMPLING_* pin); an explicit client value wins unless the operator pinned it.@@ -20025,6 +20047,12 @@ def _openai_messages_for_gguf_chat(payload, is_vision: bool) -> tuple[list[dict]return messages, has_image+async def _openai_messages_for_gguf_chat_async(payload, is_vision: bool) -> tuple[list[dict], bool]:+ if _request_has_image(payload):+ return await asyncio.to_thread(_openai_messages_for_gguf_chat, payload, is_vision)+ return _openai_messages_for_gguf_chat(payload, is_vision)++def _extract_response_format(payload):"""Return the ``response_format`` field on an incoming ChatCompletionRequest(or None). The model uses ``extra="allow"`` so pydantic stashes unknown@@ -20097,6 +20125,25 @@ def _build_openai_passthrough_body(return body+async def _build_openai_passthrough_body_async(+ payload,+ backend_ctx = None,+ llama_backend = None,+) -> dict:+ if _request_has_image(payload):+ return await asyncio.to_thread(+ _build_openai_passthrough_body,+ payload,+ backend_ctx = backend_ctx,+ llama_backend = llama_backend,+ )+ return _build_openai_passthrough_body(+ payload,+ backend_ctx = backend_ctx,+ llama_backend = llama_backend,+ )++async def _openai_passthrough_stream(request,cancel_event,@@ -20347,7 +20394,7 @@ async def _openai_passthrough_stream_admitted(# Keep tracker cleanup paired if pre-header dispatch is cancelled.try:- body = _build_openai_passthrough_body(+ body = await _build_openai_passthrough_body_async(payload, backend_ctx = llama_backend.context_length, llama_backend = llama_backend)# Text-form tool calls from small models get promoted to structured calls on@@ -21133,7 +21180,7 @@ async def _openai_passthrough_non_streaming_upstream("""target_url = f"{llama_backend.base_url}/v1/chat/completions"upstream_headers = _openai_passthrough_upstream_headers(llama_backend = llama_backend)- body = _build_openai_passthrough_body(+ body = await _build_openai_passthrough_body_async(payload, backend_ctx = llama_backend.context_length, llama_backend = llama_backend)body["stream"] = Falsediff --git a/studio/backend/tests/test_llama_cpp_wait_for_health.py b/studio/backend/tests/test_llama_cpp_wait_for_health.pyindex 423c3dd009e..508d371a555 100644--- a/studio/backend/tests/test_llama_cpp_wait_for_health.py+++ b/studio/backend/tests/test_llama_cpp_wait_for_health.py@@ -12,6 +12,8 @@ subprocess.poll() branch so a crashed llama-server surfaces a structuredfrom __future__ import annotationsimport sys+import threading+import timeimport types as _typesfrom pathlib import Pathfrom unittest import mock@@ -32,10 +34,8 @@ import httpx # noqa: E402from core.inference.llama_cpp import LlamaCppBackend # noqa: E402-# Sibling tests install lightweight httpx stubs via sys.modules.setdefault.-# When collected together, our `httpx` may be such a stub lacking `get`. Add-# the missing attributes so production code finds a working `httpx.get` and-# the standard exception types regardless of collection order.+# Sibling tests install lightweight httpx stubs, so when collected together our `httpx`+# may be a stub lacking `get`. Fill in the gaps so collection order does not matter.if not hasattr(httpx, "get"):httpx.get = None # placeholder; every test below monkeypatches itfor _exc_name in (@@ -138,6 +138,43 @@ class TestWaitForHealthResilience:assert b._wait_for_health(timeout = 5.0, interval = 0.01) is Trueassert calls["n"] >= 3+ def test_stdout_readiness_wakes_probe_before_fallback_interval(self, monkeypatch):+ b = _make_backend()+ b._process.poll.return_value = None+ b._health_probe_event = threading.Event()+ calls = {"n": 0}++ def becomes_healthy(*a, **kw):+ calls["n"] += 1+ if calls["n"] == 1:+ raise httpx.ConnectError("not yet")+ return mock.Mock(status_code = 200)++ monkeypatch.setattr(httpx, "get", becomes_healthy)+ wake = threading.Timer(0.02, b._health_probe_event.set)+ wake.start()+ start = time.monotonic()+ try:+ assert b._wait_for_health(timeout = 1.0, interval = 0.5) is True+ finally:+ wake.cancel()+ assert time.monotonic() - start < 0.25+ assert calls["n"] == 2++ def test_stdout_drain_sets_health_event_on_readiness_line(self):+ b = _make_backend()+ b._health_probe_event = threading.Event()+ b._process.stdout = iter(["main: server is listening on http://127.0.0.1:12345\n"])+ event_seen_while_draining = []+ b._llama_log_fh = mock.Mock()+ b._llama_log_fh.write.side_effect = lambda _line: event_seen_while_draining.append(+ b._health_probe_event.is_set()+ )++ b._drain_stdout()++ assert event_seen_while_draining == [True]+def test_dead_process_before_probe_returns_false(self, monkeypatch):"""poll() != None on entry: _wait_for_health returns Falseimmediately without calling httpx."""diff --git a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.pyindex b28df7ec3fe..6c5d782dce3 100644--- a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py+++ b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py@@ -58,6 +58,7 @@ _httpx_stub.Client = type()sys.modules.setdefault("httpx", _httpx_stub)+from core.inference import llama_cpp as llama_cpp_module # noqa: E402from core.inference.llama_cpp import LlamaCppBackend # noqa: E402@@ -344,6 +345,11 @@ def test_helper_is_static_method_callable_off_class():# ---------------------------------------------------------------------------+# Hiding /proc selects the psutil branch (what macOS and Windows take); the procfs+# branch is covered separately below.+_NO_PROCFS = "/unsloth-test-no-such-proc-root"++def test_kill_orphaned_servers_returns_count():"""The reaper reports how many owned orphans it killed, so __init__ canarm the settle wait. Only Unsloth-owned llama-server procs count."""@@ -373,6 +379,7 @@ def test_kill_orphaned_servers_returns_count():with (patch.dict(sys.modules, {"psutil": fake_psutil}),patch.dict(os.environ, {"LLAMA_SERVER_PATH": fake_path}),+ patch.object(llama_cpp_module, "_PROC_ROOT", _NO_PROCFS),patch.object(LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False)),):n = LlamaCppBackend._kill_orphaned_servers()@@ -385,6 +392,7 @@ def test_kill_orphaned_servers_returns_count():with (patch.dict(sys.modules, {"psutil": fake_psutil}),patch.dict(os.environ, {"LLAMA_SERVER_PATH": fake_path}),+ patch.object(llama_cpp_module, "_PROC_ROOT", _NO_PROCFS),patch.object(LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False)),):assert LlamaCppBackend._kill_orphaned_servers() == 0@@ -420,6 +428,7 @@ def test_kill_orphaned_servers_spares_live_parent():with (patch.dict(sys.modules, {"psutil": fake_psutil}),patch.dict(os.environ, {"LLAMA_SERVER_PATH": fake_path}),+ patch.object(llama_cpp_module, "_PROC_ROOT", _NO_PROCFS),patch.object(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0)),patch.object(LlamaCppBackend,@@ -652,3 +661,205 @@ def test_reap_recorded_pid_no_pidfile(tmp_path):pidfile = tmp_path / "llama-server.pid" # never createdwith patch.object(LlamaCppBackend, "_server_pidfile_path", staticmethod(lambda: pidfile)):assert LlamaCppBackend._reap_recorded_pid() == 0+++def _stat_bytes(+ pid,+ comm,+ start_time = 1000,+):+ """A /proc/<pid>/stat line. starttime is field 22, so the filler matters."""+ filler = " ".join(["0"] * 18) # fields 4..21+ return f"{pid} ({comm}) S {filler} {start_time}".encode("utf-8")+++def _write_fake_procfs(tmp_path, entries):+ """Build a /proc-shaped tree. entries is [(pid, comm, exe_target)]."""+ root = tmp_path / "fake-proc"+ root.mkdir()+ for pid, comm, exe_target in entries:+ d = root / str(pid)+ d.mkdir()+ (d / "stat").write_bytes(_stat_bytes(pid, comm))+ if exe_target is not None:+ (d / "exe").symlink_to(exe_target)+ return root++[email protected](sys.platform != "linux", reason = "the procfs scan only runs on Linux")+def test_kill_orphaned_servers_procfs_matches_psutil_selection(tmp_path):+ """The Linux /proc sweep must select exactly what the psutil sweep selects:+ the Unsloth-owned orphan, never a foreign llama-server or another program."""+ import os++ mypid = os.getpid()+ owned_dir = tmp_path / "unsloth-test-llama"+ owned_dir.mkdir()+ fake_path = owned_dir / "llama-server"+ fake_path.write_text("x")+ foreign = tmp_path / "usr-bin-llama-server"+ foreign.write_text("x")++ root = _write_fake_procfs(+ tmp_path,+ [+ (mypid + 1, "llama-server", str(fake_path)), # owned orphan+ (mypid + 2, "llama-server", str(foreign)), # not ours+ (mypid + 3, "python3", str(fake_path)), # wrong name+ (mypid + 4, "llama-server", None), # exe unreadable+ ],+ )++ killed = []++ def _fake_kill(pid, sig):+ killed.append(pid)++ with (+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": str(fake_path)}),+ patch.object(llama_cpp_module, "_PROC_ROOT", str(root)),+ patch.object(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0)),+ patch.object(LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False)),+ patch.object(os, "kill", _fake_kill),+ ):+ n = LlamaCppBackend._kill_orphaned_servers()++ assert n == 1, "only the Unsloth-owned orphan should be counted"+ assert killed == [mypid + 1]++[email protected](sys.platform != "linux", reason = "the procfs scan only runs on Linux")+def test_kill_orphaned_servers_procfs_spares_live_parent(tmp_path):+ """Same live-parent rule as the psutil sweep: only the true orphan is reaped."""+ import os++ mypid = os.getpid()+ owned_dir = tmp_path / "unsloth-test-llama"+ owned_dir.mkdir()+ fake_path = owned_dir / "llama-server"+ fake_path.write_text("x")++ root = _write_fake_procfs(+ tmp_path,+ [+ (mypid + 1, "llama-server", str(fake_path)), # live parent+ (mypid + 2, "llama-server", str(fake_path)), # true orphan+ ],+ )++ killed = []++ with (+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": str(fake_path)}),+ patch.object(llama_cpp_module, "_PROC_ROOT", str(root)),+ patch.object(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0)),+ patch.object(+ LlamaCppBackend,+ "_pid_parent_is_alive",+ staticmethod(lambda pid: pid == mypid + 1),+ ),+ patch.object(os, "kill", lambda pid, sig: killed.append(pid)),+ ):+ n = LlamaCppBackend._kill_orphaned_servers()++ assert n == 1, "only the true orphan should be reaped"+ assert killed == [mypid + 2], "the live-parent server must be spared"++[email protected](sys.platform != "linux", reason = "the procfs scan only runs on Linux")+def test_kill_orphaned_servers_procfs_handles_a_deleted_binary(tmp_path):+ """An orphan left behind by an upgrade has " (deleted)" appended to its exe+ link. psutil strips that marker, so the procfs sweep must too, or the+ orphan stops being recognised as ours."""+ import os++ mypid = os.getpid()+ owned_dir = tmp_path / "unsloth-test-llama"+ owned_dir.mkdir()+ fake_path = owned_dir / "llama-server"++ root = _write_fake_procfs(+ tmp_path,+ [(mypid + 1, "llama-server", f"{fake_path} (deleted)")],+ )++ killed = []+ with (+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": str(fake_path)}),+ patch.object(llama_cpp_module, "_PROC_ROOT", str(root)),+ patch.object(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0)),+ patch.object(LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False)),+ patch.object(os, "kill", lambda pid, sig: killed.append(pid)),+ ):+ n = LlamaCppBackend._kill_orphaned_servers()++ assert n == 1+ assert killed == [mypid + 1]++[email protected](sys.platform != "linux", reason = "the procfs scan only runs on Linux")+def test_kill_orphaned_servers_procfs_refuses_a_reused_pid(tmp_path):+ """psutil.Process.kill() refuses to signal a PID that has been reused. The+ procfs sweep must do the same, or an orphan that exits between the scan and+ the signal takes an unrelated replacement process with it."""+ import os++ mypid = os.getpid()+ owned_dir = tmp_path / "unsloth-test-llama"+ owned_dir.mkdir()+ fake_path = owned_dir / "llama-server"+ fake_path.write_text("x")++ root = _write_fake_procfs(tmp_path, [(mypid + 1, "llama-server", str(fake_path))])+ stat_file = root / str(mypid + 1) / "stat"++ killed = []++ def _pid_reused_between_scan_and_kill(pid):+ # Runs after the scan and before the kill: stand in a different process+ # on the same PID by giving it a later starttime.+ stat_file.write_bytes(_stat_bytes(pid, "some-daemon", start_time = 9999))+ return False++ with (+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": str(fake_path)}),+ patch.object(llama_cpp_module, "_PROC_ROOT", str(root)),+ patch.object(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0)),+ patch.object(+ LlamaCppBackend,+ "_pid_parent_is_alive",+ staticmethod(_pid_reused_between_scan_and_kill),+ ),+ patch.object(os, "kill", lambda pid, sig: killed.append(pid)),+ ):+ n = LlamaCppBackend._kill_orphaned_servers()++ assert killed == [], "a reused PID must never be signalled"+ assert n == 0++[email protected](sys.platform != "linux", reason = "the procfs scan only runs on Linux")+def test_kill_orphaned_servers_procfs_still_kills_the_same_process(tmp_path):+ """Control for the test above: an unchanged starttime is still reaped, so+ the identity check is not simply refusing everything."""+ import os++ mypid = os.getpid()+ owned_dir = tmp_path / "unsloth-test-llama"+ owned_dir.mkdir()+ fake_path = owned_dir / "llama-server"+ fake_path.write_text("x")++ root = _write_fake_procfs(tmp_path, [(mypid + 1, "llama-server", str(fake_path))])+ killed = []+ with (+ patch.dict(os.environ, {"LLAMA_SERVER_PATH": str(fake_path)}),+ patch.object(llama_cpp_module, "_PROC_ROOT", str(root)),+ patch.object(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0)),+ patch.object(LlamaCppBackend, "_pid_parent_is_alive", staticmethod(lambda pid: False)),+ patch.object(os, "kill", lambda pid, sig: killed.append(pid)),+ ):+ n = LlamaCppBackend._kill_orphaned_servers()++ assert killed == [mypid + 1]+ assert n == 1diff --git a/studio/backend/tests/test_local_llama_cpp_link.py b/studio/backend/tests/test_local_llama_cpp_link.pyindex 79c9977c843..1d69175963d 100644--- a/studio/backend/tests/test_local_llama_cpp_link.py+++ b/studio/backend/tests/test_local_llama_cpp_link.py@@ -13,11 +13,13 @@ These exercise real link behavior rather than grepping the scripts.import osimport subprocess+import sysfrom pathlib import Pathimport pytestfrom utils import llama_cpp_update as u+from core.inference import llama_cpp as llama_cpp_modulefrom core.inference.llama_cpp import LlamaCppBackend@@ -99,7 +101,32 @@ def test_start_update_refuses_local_link(tmp_path: Path, monkeypatch) -> None:assert res["reason"] == "local_link"-def _run_orphan_scan(monkeypatch, studio_root: Path, fake: _FakeProc) -> int:+def _fake_procfs(tmp_path: Path, fake: _FakeProc) -> Path:+ """Build a /proc-shaped tree holding a single llama-server process."""+ root = tmp_path / "fake-proc"+ entry = root / str(fake.info["pid"])+ entry.mkdir(parents = True)+ # comm sits between the first "(" and the last ")"; starttime is field 22.+ filler = " ".join(["0"] * 18) # fields 4..21+ (entry / "stat").write_bytes(+ f"{fake.info['pid']} (llama-server) S {filler} 1000".encode("utf-8")+ )+ (entry / "exe").symlink_to(fake.info["exe"])+ # A non-numeric sibling and a process with a different name must be ignored.+ (root / "self").mkdir()+ other = root / str(fake.info["pid"] + 1)+ other.mkdir()+ (other / "stat").write_bytes(f"1 (python3) S {filler} 1000".encode("utf-8"))+ return root+++def _run_orphan_scan(+ monkeypatch,+ studio_root: Path,+ fake: _FakeProc,+ scan: str = "psutil",+ tmp_path: Path = None,+) -> int:# psutil drives the cross-platform process scan; skip (rather than error) if a# minimal test env lacks it. CI installs it so these tests actually run.psutil = pytest.importorskip("psutil")@@ -110,11 +137,30 @@ def _run_orphan_scan(monkeypatch, studio_root: Path, fake: _FakeProc) -> int:staticmethod(lambda: (studio_root.resolve(), False)),)monkeypatch.setattr(LlamaCppBackend, "_reap_recorded_pid", staticmethod(lambda: 0))- monkeypatch.setattr(psutil, "process_iter", lambda attrs = None: iter([fake]))++ if scan == "procfs":+ # Linux reads /proc directly. Point it at a fixture tree and intercept the+ # signal, since the fixture's pid is not a real process.+ if sys.platform != "linux":+ pytest.skip("the procfs scan only runs on Linux")+ monkeypatch.setattr(llama_cpp_module, "_PROC_ROOT", str(_fake_procfs(tmp_path, fake)))++ def _fake_kill(pid, sig):+ if pid == fake.info["pid"]:+ fake.kill()+ return+ raise ProcessLookupError(pid)++ monkeypatch.setattr(os, "kill", _fake_kill)+ else:+ # No /proc means the psutil branch, which is what macOS and Windows take.+ monkeypatch.setattr(llama_cpp_module, "_PROC_ROOT", str(studio_root / "no-such-proc"))+ monkeypatch.setattr(psutil, "process_iter", lambda attrs = None: iter([fake]))return LlamaCppBackend._kill_orphaned_servers()-def test_orphan_cleanup_spares_local_link_tree(tmp_path: Path, monkeypatch) -> None:[email protected]("scan", ["psutil", "procfs"])+def test_orphan_cleanup_spares_local_link_tree(tmp_path: Path, monkeypatch, scan) -> None:studio_root = tmp_path / "studio-home"studio_root.mkdir()external = tmp_path / "external"@@ -124,14 +170,15 @@ def test_orphan_cleanup_spares_local_link_tree(tmp_path: Path, monkeypatch) -> Nexe_under_link = str((external / _server_subpath()).resolve())fake = _FakeProc(os.getpid() + 777, exe_under_link)- killed = _run_orphan_scan(monkeypatch, studio_root, fake)+ killed = _run_orphan_scan(monkeypatch, studio_root, fake, scan, tmp_path)assert killed == 0assert fake.killed is False-def test_orphan_cleanup_kills_under_real_root(tmp_path: Path, monkeypatch) -> None:- # Control: a real (non-link) managed root still gets its orphan reaped, so- # the spare-the-link test above is meaningful (not a no-op).[email protected]("scan", ["psutil", "procfs"])+def test_orphan_cleanup_kills_under_real_root(tmp_path: Path, monkeypatch, scan) -> None:+ # Control: a real (non-link) managed root still gets its orphan reaped, so the+ # spare-the-link test above is not a no-op.studio_root = tmp_path / "studio-home"bin_dir = studio_root / "llama.cpp" / _server_subpath().parentbin_dir.mkdir(parents = True)@@ -139,6 +186,6 @@ def test_orphan_cleanup_kills_under_real_root(tmp_path: Path, monkeypatch) -> Noexe.write_text("x")fake = _FakeProc(os.getpid() + 888, str(exe.resolve()))- killed = _run_orphan_scan(monkeypatch, studio_root, fake)+ killed = _run_orphan_scan(monkeypatch, studio_root, fake, scan, tmp_path)assert killed == 1assert fake.killed is True