Spaces:
Paused

assistant / backend /local_server.py
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
7.08 kB
"""
local_server.py β€” Shared primitives for managing external server subprocesses
(llama-server, whisper-server).
Both native backends launch an OpenAI-compatible HTTP server binary as a
subprocess and manage it with the same mechanical moves: probe a free port,
poll the health endpoint until the server answers, terminate cleanly on
stop/restart (kill after a grace period), read the real console tail when a
launch fails, and never leave an orphaned process behind (atexit hook).
This module centralizes those mechanical parts so the two backends can't
drift apart (e.g. one getting a port-probe bug the other doesn't). Each
backend keeps only what is genuinely specific to it: the command line to
launch, the health check, and the config dict that must match for reuse.
"""
import os
import socket
import subprocess
import sys
import time
from typing import Optional
# Windows flag to suppress creating a console window for spawned subprocesses
CREATE_NO_WINDOW: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) if sys.platform == "win32" else 0
# How many extra ports to probe past the preferred one before giving up.
_DEFAULT_PROBE_RANGE = 100
# TCP-connect health cache: (host, port) -> True once a server has been
# seen healthy there. Avoids re-probing a known-good port on every turn.
_TCP_HEALTH_CACHE: dict = {}
def port_is_free(host: str, port: int) -> bool:
"""True when nothing is listening on (host, port) right now.
Uses a bind test (the accurate "can I listen here?" check) rather than a
plain connect-refused test, so TIME_WAIT sockets don't false-negative.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind((host, port))
return True
except OSError:
return False
def find_free_port(host: str, preferred: int, max_probe: int = _DEFAULT_PROBE_RANGE) -> int:
"""First free port at or after `preferred` (probing up to `max_probe`
ports), else `preferred` itself β€” the launch will fail loudly if the
port really is taken."""
port = preferred
for _ in range(max_probe):
if port_is_free(host, port):
return port
port += 1
return preferred
def tcp_health_ok(host: str, port: int, timeout: float = 2.0) -> bool:
"""Best-effort TCP connect check (some servers expose no /health route).
Results are cached per (host, port): once a port has answered, later
checks short-circuit instead of re-probing on every chat turn.
"""
key = (host, port)
if _TCP_HEALTH_CACHE.get(key):
return True
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(timeout)
try:
s.connect((host, port))
_TCP_HEALTH_CACHE[key] = True
return True
except (OSError, ConnectionRefusedError):
_TCP_HEALTH_CACHE.pop(key, None)
return False
def clear_health_cache() -> None:
"""Forget every cached healthy port (call after stopping a server)."""
_TCP_HEALTH_CACHE.clear()
def kill_stray_app_servers(name_tokens: tuple, exe_path: str,
dir_signatures: tuple,
exclude_pid=None) -> int:
"""Kill server processes the app itself launched that are no longer
managed by the current process, and return how many were killed.
A previous app instance can leave its llama-server / whisper-server
subprocess behind (crash, kill -9, taskkill of the parent, the MSIX
update flow, …). That orphan keeps its GGUF model resident in VRAM and
occupies its port, but THIS process never spawned it β€” so the normal
stop-by-handle path (stop_subprocess on the managed Popen) can't see it.
That's the "Free All VRAM still shows ~X% occupied after a restart"
leak. This sweep finds such orphans by the app's OWN launch signature
and terminates them:
- the process name contains one of `name_tokens` (e.g. 'llama-server'),
AND
- its executable path equals `exe_path` (the exact binary this app is
configured to launch), OR its command line references a model file
under one of `dir_signatures` (the app's model directories β€” the
orphan keeps the app's own configured model dir in its `-m` arg).
Both signatures are specific to this app: a llama-server/whisper-server
the user runs manually for other purposes (a different binary, a model
outside the app's folders) is never touched. `exclude_pid` protects the
currently-managed child(ren) β€” a single pid, or a tuple of pids (the
chat AND embedding slots can both be alive; a slot's stop sweep must
never reap its sibling). Never raises β€” inaccessible or vanished
processes are skipped.
"""
killed = 0
try:
import psutil
except Exception:
return killed
if isinstance(exclude_pid, int):
excluded_pids = {exclude_pid}
else:
excluded_pids = {p for p in (exclude_pid or ()) if p}
norm = os.path.normcase
exe_norm = norm(exe_path or "")
sigs = [norm(s) for s in (dir_signatures or ()) if s]
for proc in psutil.process_iter(["pid", "name", "exe", "cmdline"]):
try:
info = proc.info
name = (info.get("name") or "").lower()
if not any(tok.lower() in name for tok in name_tokens):
continue
pid = info.get("pid")
if pid in excluded_pids:
continue
exe = norm(info.get("exe") or "")
if exe_norm and exe == exe_norm:
pass # the exact binary this app launches
elif sigs:
cmd = norm(" ".join(str(c) for c in (info.get("cmdline") or [])))
if not any(s in cmd for s in sigs):
continue
else:
continue
proc.kill()
killed += 1
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
except Exception:
continue
return killed
def stop_subprocess(proc: Optional[subprocess.Popen], tag: str = "") -> None:
"""Terminate a managed subprocess, escalating to kill after 10s.
Never raises β€” callers treat stop as best-effort cleanup (the app must
always launch and degrade gracefully, per AGENTS.md).
"""
if proc is None:
return
try:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
except Exception:
pass
def collect_process_tail(proc: Optional[subprocess.Popen], max_lines: int = 30) -> str:
"""Last `max_lines` of a process's captured stdout ('' on failure).
Used to surface the real console error when a server exits immediately
instead of a bare "connection refused" a moment later.
"""
if proc is None or proc.stdout is None:
return ""
try:
return "".join(proc.stdout.readlines()[-max_lines:])
except Exception:
return ""