"""AI service: runs one LLM server at a time and swaps between them. The selected server (settings "ai.active") is started as a normal-user child process and restarted if it crashes (5 crashes within 5 minutes pause restarts for 5 minutes). Swapping stops the running server completely first, so the two never share the GPU's memory. Servers are also started on demand: a request through The Kurgan's web server (/strata/..., /llama/...; see kurgan/web/proxy.py) selects its server and waits until it answers. If the other server is busy (a request in flight, a reply being generated or a model loading), the request waits for it to finish rather than cutting it off. A server nobody has used for ai.idle_stop_minutes is stopped. A server already listening on a port that The Kurgan didn't start (for example Strata's or the Qwen4 service's own tray, before they are retired) is shown as "external": it is monitored but never started, stopped or duplicated. """ from __future__ import annotations import collections import ctypes import ctypes.wintypes as wt import logging import os import socket import threading import time from kurgan.ai import launcher from kurgan.ai.backends import Backend, LlamaBackend, StrataBackend from kurgan.ai.config import BACKENDS from kurgan.settings import Settings log = logging.getLogger(__name__) _iphlp = ctypes.WinDLL("iphlpapi") _k32 = ctypes.WinDLL("kernel32", use_last_error=True) _iphlp.GetExtendedTcpTable.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.DWORD), wt.BOOL, wt.ULONG, ctypes.c_int, wt.ULONG] _iphlp.GetExtendedTcpTable.restype = wt.DWORD _k32.OpenProcess.argtypes, _k32.OpenProcess.restype = [wt.DWORD, wt.BOOL, wt.DWORD], wt.HANDLE _k32.QueryFullProcessImageNameW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPWSTR, ctypes.POINTER(wt.DWORD)] _k32.QueryFullProcessImageNameW.restype = wt.BOOL _k32.CloseHandle.argtypes = [wt.HANDLE] def port_in_use(port: int) -> bool: with socket.socket() as probe: probe.settimeout(0.3) return probe.connect_ex(("127.0.0.1", port)) == 0 def port_owner(port: int) -> tuple[int, str] | None: """(pid, executable name) of the process listening on 127.0.0.1:port, if any.""" size = wt.DWORD(0) _iphlp.GetExtendedTcpTable(None, ctypes.byref(size), False, 2, 3, 0) # AF_INET, TCP_TABLE_OWNER_PID_LISTENER buf = ctypes.create_string_buffer(size.value) if _iphlp.GetExtendedTcpTable(buf, ctypes.byref(size), False, 2, 3, 0) != 0: return None count = ctypes.c_uint32.from_buffer(buf).value row = ctypes.c_uint32 * 6 # state, local addr, local port, remote addr, remote port, pid for i in range(count): state, _addr, lport, _raddr, _rport, pid = row.from_buffer(buf, 4 + i * ctypes.sizeof(row)) if ((lport & 0xFF) << 8 | (lport >> 8) & 0xFF) == port: name = "?" handle = _k32.OpenProcess(launcher.PROCESS_QUERY_LIMITED_INFORMATION, False, pid) if handle: try: text, length = ctypes.create_unicode_buffer(1024), wt.DWORD(1024) if _k32.QueryFullProcessImageNameW(handle, 0, text, ctypes.byref(length)): name = os.path.basename(text.value) finally: _k32.CloseHandle(handle) return pid, name return None class Slot: """One backend and the process The Kurgan runs for it.""" def __init__(self, backend: Backend): self.backend = backend self.child: launcher.ChildProcess | None = None self.variant: str | None = None self.started_at: float | None = None self.stopping = False self.external: tuple[int, str] | None = None self.crashes: collections.deque[float] = collections.deque(maxlen=5) self.hold_until = 0.0 self.restarts = 0 self.error: str | None = None self.reachable = False class RouteError(Exception): """A request for a server that can't be served now; status is the HTTP status to answer with.""" def __init__(self, message: str, status: int = 503): super().__init__(message) self.status = status BUSY_STATES = ("loading", "reading", "generating") CLIENT_GONE = 499 # RouteError status: the client hung up while waiting (nginx's "client closed request") class AiService: BUSY_WAIT = 600.0 # how long a request waits for the other server to finish before giving up READY_WAIT = 120.0 # how long it waits for its own server to start answering def __init__(self, settings: Settings, backends: list[Backend] | None = None): self.settings = settings backends = backends or [StrataBackend(settings), LlamaBackend(settings)] self.slots = {b.key: Slot(b) for b in backends} self._wake = threading.Event() self._lock = threading.Lock() self._cv = threading.Condition() # guards inflight/last_used; notified when a request ends self.inflight = {key: 0 for key in self.slots} self.last_used = {key: time.monotonic() for key in self.slots} self.transition: str | None = None self.action: str | None = None # "Loading model..." while a load/unload request runs self.message: str | None = None self._stop: threading.Event | None = None def set_public_url(self, url: str) -> None: """The Kurgan's web server, which the links in the UI point to.""" for slot in self.slots.values(): slot.backend.public = url.rstrip("/") # -- requests from the web UI (any thread) def set_active(self, key: str | None, variant: str | None = None) -> None: if key is not None and key not in self.slots: raise ValueError(f"Unknown AI backend {key!r}") changes: dict = {"active": key} if variant is not None: changes["strata_model"] = variant self.settings.update("ai", **changes) # validates the variant log.info("AI backend selected: %s%s", key or "none", f" ({variant})" if variant else "") if key is not None: with self._cv: self.last_used[key] = time.monotonic() # a full idle period before it can stop self._wake.set() # -- requests through the web server (any thread) def _busy(self, key: str) -> bool: """Serving or about to serve: a request in flight here, or a reply/model load in progress.""" if self.inflight[key]: return True status = self.slots[key].backend.status return bool(status.get("live")) or status["model"]["state"] in BUSY_STATES def claim(self, key: str, gone=None) -> Backend: """Reserve key's server for one request: select it (stopping the other once that is idle) and wait until it answers. Always pair with release(key). gone(), if given, says whether the client has hung up; then the wait ends without switching anything.""" if key not in self.slots: raise RouteError(f"Unknown AI server {key!r}", 404) slot = self.slots[key] deadline = time.monotonic() + self.BUSY_WAIT with self._cv: while True: active = self.settings.get("ai", "active") if active == key or slot.external is not None: break other = self.slots[active] if active else None if gone is not None and gone(): raise RouteError(f"while waiting for {other.backend.label} to finish" if other is not None else f"before {slot.backend.label} was started", CLIENT_GONE) if other is None or other.external is not None or not self._busy(active): try: self.settings.update("ai", active=key) except OSError as e: raise RouteError(f"Couldn't save the AI selection: {e}", 500) from None log.info("%s requested by a client%s", slot.backend.label, f"; stopping {other.backend.label}" if other is not None and other.child else "") self._wake.set() break if time.monotonic() >= deadline: raise RouteError(f"{other.backend.label} is still busy with another request; try again later.") self._cv.wait(1.0) self.inflight[key] += 1 self.last_used[key] = time.monotonic() try: self._wait_ready(key, slot, gone) except BaseException: self.release(key) raise return slot.backend def _wait_ready(self, key: str, slot: Slot, gone=None) -> None: start = time.monotonic() while True: if slot.external is not None: # An open port isn't proof the program behind it is this server: only a poll # that succeeded means it speaks the API the proxy is about to use. if slot.reachable: return elif slot.child is not None and not slot.stopping and port_in_use(slot.backend.port): return if self._stop is not None and self._stop.is_set(): raise RouteError("The Kurgan is shutting down") if gone is not None and gone(): raise RouteError(f"while waiting for {slot.backend.label} to start", CLIENT_GONE) waited = time.monotonic() - start if slot.external is None and self.settings.get("ai", "active") != key and waited > 3: raise RouteError(f"{slot.backend.label} was switched off in The Kurgan") if slot.external is not None and not slot.reachable and waited > 10: pid, name = slot.external raise RouteError(f"port {slot.backend.port} is held by {name} (pid {pid}), " f"which isn't answering as {slot.backend.label}") if slot.child is None and slot.error and waited > 3: raise RouteError(slot.error) if waited >= self.READY_WAIT: raise RouteError(f"{slot.backend.label} didn't start within {self.READY_WAIT:.0f} s") time.sleep(0.25) def release(self, key: str) -> None: with self._cv: self.inflight[key] = max(0, self.inflight[key] - 1) self.last_used[key] = time.monotonic() self._cv.notify_all() def running(self, key: str) -> bool: """The server answers now (started by The Kurgan or not).""" slot = self.slots[key] return slot.reachable and (slot.external is not None or (slot.child is not None and not slot.stopping)) def model_action(self, action: str) -> None: """Load or unload the model of the running server (in the background).""" key = self.settings.get("ai", "active") if key is None or action not in ("load", "unload"): raise ValueError("No AI backend is selected" if key is None else f"Unknown action {action!r}") slot = self.slots[key] if not slot.reachable: raise ValueError(f"{slot.backend.label} isn't running yet") if self.action: raise ValueError(f"Busy: {self.action}") self.action = f"{'Loading' if action == 'load' else 'Unloading'} {slot.backend.label} model" def run(): try: getattr(slot.backend, action)() self.message = None except Exception as e: log.warning("%s failed: %s", self.action, e) self.message = f"{self.action} failed: {e}" finally: self.action = None threading.Thread(target=run, name=f"ai-{action}", daemon=True).start() # -- worker threads def start(self, stop: threading.Event) -> list[threading.Thread]: self._stop = stop threads = [threading.Thread(target=self.run, args=(stop,), name="ai-supervisor", daemon=True), threading.Thread(target=self.monitor, args=(stop,), name="ai-monitor", daemon=True)] llama = self.slots.get("llama") if llama is not None and isinstance(llama.backend, LlamaBackend): threads.append(threading.Thread(target=llama.backend.logparser.follow, args=(llama.backend.current_log, stop), name="llama-log", daemon=True)) for thread in threads: thread.start() return threads def monitor(self, stop: threading.Event) -> None: while not stop.is_set(): for slot in self.slots.values(): running = slot.child is not None or slot.external is not None if not running: slot.reachable = False slot.backend.mark_offline() continue try: slot.backend.poll() slot.reachable = True except (OSError, ValueError, KeyError, StopIteration) as e: slot.reachable = False slot.backend.mark_offline() log.debug("%s poll failed: %s", slot.backend.label, e) stop.wait(1.5) def run(self, stop: threading.Event) -> None: try: while not stop.is_set(): try: self._reconcile(stop) except Exception: log.exception("AI supervisor error") self._wake.wait(1.0) self._wake.clear() finally: for slot in self.slots.values(): if slot.child is not None: self._stop_slot(slot, "The Kurgan is exiting") def _idle_check(self, active: str | None) -> str | None: """Stop the selected server once nobody has used it for ai.idle_stop_minutes.""" minutes = self.settings.get("ai", "idle_stop_minutes") if not active or not minutes: return active slot = self.slots[active] if slot.child is None or slot.stopping: return active with self._cv: if self._busy(active): self.last_used[active] = time.monotonic() return active if time.monotonic() - self.last_used[active] < minutes * 60: return active try: # Under the same lock as claim(): a request arriving between the check and the # write would otherwise have its selection overwritten and its server stopped # under it. self.settings.update("ai", active=None) except OSError as e: log.warning("Couldn't save the AI selection: %s", e) return active log.info("%s unused for %d minutes; stopping it until the next request", slot.backend.label, minutes) return None def _reconcile(self, stop: threading.Event) -> None: active = self._idle_check(self.settings.get("ai", "active")) for slot in self.slots.values(): self._check_exit(slot) with self._cv: # A server with a request in flight finishes it before being stopped or replaced: # clients wait for servers, they are never cut off mid-reply. draining = next((key for key, slot in self.slots.items() if key != active and slot.child is not None and self.inflight[key]), None) busy_here = active is not None and self.inflight[active] > 0 # Stop whatever isn't selected first, so the selected server gets the GPU to itself. for key, slot in self.slots.items(): if slot.child is not None and key != active and key != draining: self._stop_slot(slot, "switching" if active else "none selected") for key, slot in self.slots.items(): slot.external = None if slot.child is None and port_in_use(slot.backend.port): slot.external = port_owner(slot.backend.port) or (0, "unknown program") if active is None or stop.is_set(): self.transition = None return slot = self.slots[active] if slot.child is not None and not busy_here and slot.variant != slot.backend.variant(): self._stop_slot(slot, "changing model") if slot.child is not None or slot.external is not None: self.transition = None return if draining is not None: # The GPU's memory is still held by the server answering its last request; the # selected one must not start onto it. self.transition = f"Waiting for {self.slots[draining].backend.label} to finish its request" return if time.monotonic() < slot.hold_until: return problem = slot.backend.check_files() if problem: slot.error = problem return self._start_slot(slot) def _check_exit(self, slot: Slot) -> None: if slot.child is None or slot.stopping: return code = slot.child.poll() if code is None: return slot.child.close() slot.child = None slot.restarts += 1 slot.crashes.append(time.monotonic()) if len(slot.crashes) == slot.crashes.maxlen and slot.crashes[-1] - slot.crashes[0] < 300: slot.error = f"{slot.backend.label} keeps exiting (code {code}); retrying in 5 minutes. See its log." slot.hold_until = time.monotonic() + 300 slot.crashes.clear() else: slot.error = f"{slot.backend.label} exited (code {code}); restarting." slot.hold_until = time.monotonic() + 5 log.error(slot.error) def _start_slot(self, slot: Slot) -> None: backend = slot.backend self.transition = f"Starting {backend.label}" backend.before_start() argv, cwd, log_path = backend.command() try: slot.child = launcher.launch(argv, cwd, log_path) except OSError as e: slot.error = f"Could not start {backend.label}: {e}" slot.hold_until = time.monotonic() + 30 log.error(slot.error) self.transition = None return if isinstance(backend, LlamaBackend): backend.owned = True with self._cv: self.last_used[backend.key] = time.monotonic() slot.variant = backend.variant() slot.started_at = time.time() slot.error = None self.transition = None def _stop_slot(self, slot: Slot, why: str) -> None: child, backend = slot.child, slot.backend if child is None: return self.transition = f"Stopping {backend.label} ({why})" log.info("Stopping %s (%s)", backend.label, why) slot.stopping = True try: backend.request_stop(child) if child.wait(backend.stop_timeout) is None: log.warning("%s didn't stop within %.0f s; ending it", backend.label, backend.stop_timeout) child.kill() child.wait(10) deadline = time.monotonic() + 10 # the port and VRAM are free once every process in the job is gone while port_in_use(backend.port) and time.monotonic() < deadline: time.sleep(0.25) finally: child.kill() child.close() slot.child = None slot.stopping = False slot.started_at = None slot.reachable = False if isinstance(backend, LlamaBackend): backend.owned = False backend.mark_offline() self.transition = None # -- state for the UI def snapshot(self) -> dict: active = self.settings.get("ai", "active") minutes = self.settings.get("ai", "idle_stop_minutes") now = time.monotonic() with self._cv: inflight = dict(self.inflight) idle_in = {key: max(0, round(minutes * 60 - (now - self.last_used[key]))) for key, slot in self.slots.items() if minutes and key == active and slot.child is not None and not self._busy(key)} backends = [] for key, slot in self.slots.items(): b = slot.backend if slot.child is not None: process = "stopping" if slot.stopping else ("running" if slot.reachable else "starting") elif slot.external is not None: process = "external" else: process = "stopped" backends.append({ "key": key, "label": b.label, "model_label": b.model_label(), "port": b.port, "variants": b.variants(), "variant": b.variant(), "links": b.links(), "process": process, "pid": slot.child.pid if slot.child else (slot.external[0] if slot.external else None), "external_program": slot.external[1] if slot.external else None, "token": slot.child.token if slot.child else None, "uptime": round(time.time() - slot.started_at) if slot.started_at else None, "restarts": slot.restarts, "error": slot.error, "route": f"/{key}/", "inflight": inflight[key], "idle_stop_in": idle_in.get(key), **b.snapshot(), }) others = [s.backend.label for k, s in self.slots.items() if k != active and s.external is not None] warning = None if others: names, one = " and ".join(others), len(others) == 1 warning = (f"{names} {'is' if one else 'are'} also running outside The Kurgan, so they may share " "the GPU's memory." if active else f"{names} {'is' if one else 'are'} running outside The Kurgan, from " f"{'its own startup task' if one else 'their own startup tasks'}. Run setup.ps1 -RetireAIServices " f"to let The Kurgan manage {'it' if one else 'them'}.") return {"active": active, "backends_order": list(BACKENDS), "transition": self.transition, "action": self.action, "message": self.message, "warning": warning, "idle_stop_minutes": minutes, "backends": backends}