From 8969a5704592ba784e9d96eb622ff3179e6c3a89 Mon Sep 17 00:00:00 2001 From: Semprini Date: Sat, 5 Dec 2026 17:13:10 +1300 Subject: [PATCH] AI: never cut a request off mid-reply; bound the logs and the stop path - service.py: the idle stop's settings write now happens under the same lock claim() holds, so a request arriving between the idle check and the write can no longer have its selection overwritten and its server stopped under it. - service.py: _reconcile no longer stops or replaces a server with a request in flight, however the switch happens (selecting another backend or None, changing Strata's model): the old server finishes its request, and the new one does not start until the GPU's memory is free again. - service.py: an "external" server is only used once a poll has proved the program behind its port answers as that server; a port held by something else now fails the request saying who holds it, instead of forwarding prompts to it. - strata_host.py: the stop watchdog is real -- if server.main never returns within 40 s of the stop request it ends the engine processes and exits, instead of relying on interrupt_main() alone (The Kurgan's 45 s kill stays as the last resort); the never-read stopping event is gone. It rotates its logs at startup: the task log keeps one .prev, the newest seven stdout or stderr files per start are kept. - backends.py: StrataBackend.before_start rotates strata-host.log the way LlamaBackend does for llama-server.log. - tests: five new tests (the two draining guards, external verification, both rotations). README updated to match. VRAM-aware start (the review's "port closed != GPU free, check VRAM before start") stays a capability idea: no setting knows a model's size to check free VRAM against. --- README.md | 22 ++++++++---- kurgan/ai/backends.py | 10 ++++++ kurgan/ai/service.py | 40 +++++++++++++++++----- kurgan/ai/strata_host.py | 48 +++++++++++++++++++++++--- tests/test_ai.py | 74 ++++++++++++++++++++++++++++++++++++++-- 5 files changed, 171 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index ff71d48..78cee54 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ This does the following: `-RetireAIServices` stops and disables the **Strata Local Service** and **Qwen4 Local Service** tasks, so The Kurgan can run whichever server you select. Without that switch, The Kurgan finds those servers already listening on their ports. It shows them as "running outside The Kurgan" -and monitors them, but it never starts a second copy. +and monitors them, but it never starts a second copy. Requests go to one only once it answers +as the expected server; a port held by some other program is reported, not served. `uninstall.ps1` removes the task. `uninstall.ps1 -RestoreAIServices` also re-enables and starts the two LLM service tasks. `-RemovePawnIO` uninstalls PawnIO. @@ -133,6 +134,9 @@ server it is addressed to. If the other server is running, it is stopped first: cutting it off. - Stopping means stopping completely: every process in its job object has ended and its port has closed. Only then does the other server start. +- A server with a request in flight is never stopped or replaced mid-reply, however the switch + happens: the old server finishes its request first, and the new one doesn't start until the + GPU's memory is free again. - A request that has to start its server waits for it. A swap takes a few seconds, plus the model's load time (about 45 s for either model). Give clients a generous timeout. @@ -162,10 +166,12 @@ Strata's optional API-monitor page (`/api-monitor`) uses absolute paths, so it d Both start with no model in memory. The model loads on the first request, or when you press **Load model**. Strata unloads it after 2000 s idle; llama.cpp sleeps after its preset's idle -time. Strata is stopped gracefully through a named event, and gets 45 s to finish. llama.cpp -is ended through its job object. Each server gets the same environment its own service gave it: -Strata runs with `GGML_CUDA_DISABLE_GRAPHS=1`, and llama.cpp runs without it. Both use OpenBLAS's -default threading, not the single-thread pin The Kurgan uses for itself. +time. Strata is stopped gracefully through a named event, and gets 45 s to finish; if the server +somehow never returns from that, it ends its engine processes and exits by itself after 40 s +(The Kurgan's kill stays as the last resort). llama.cpp is ended through its job object. Each +server gets the same environment its own service gave it: Strata runs with +`GGML_CUDA_DISABLE_GRAPHS=1`, and llama.cpp runs without it. Both use OpenBLAS's default +threading, not the single-thread pin The Kurgan uses for itself. Live progress comes from different places: @@ -174,8 +180,10 @@ Live progress comes from different places: Logs: -- `%LOCALAPPDATA%\Kurgan\logs\strata-host.log`, plus Strata's own `D:\AI\Strata\logs\local-service-*.log` -- `%LOCALAPPDATA%\Kurgan\logs\llama-server.log` (the previous run's log is kept as `.prev`) +- `%LOCALAPPDATA%\Kurgan\logs\strata-host.log` and `llama-server.log` (each keeps the previous + run's log as `.prev`) +- Strata's own `D:\AI\Strata\logs\local-service-*.log`: the task log keeps one `.prev`, and the + newest seven stdout/stderr pairs are kept A server that exits on its own is restarted after 5 seconds. After 5 exits within 5 minutes, The Kurgan waits 5 minutes before trying again, and the UI shows why. diff --git a/kurgan/ai/backends.py b/kurgan/ai/backends.py index 834b456..3ac7d67 100644 --- a/kurgan/ai/backends.py +++ b/kurgan/ai/backends.py @@ -202,6 +202,16 @@ class StrataBackend(Backend): finally: _k32.CloseHandle(handle) + def before_start(self) -> None: + # The launcher appends; keep one previous run's log, as LlamaBackend does for its own. + os.makedirs(LOG_DIR, exist_ok=True) + try: + path = os.path.join(LOG_DIR, "strata-host.log") + if os.path.exists(path): + os.replace(path, os.path.join(LOG_DIR, "strata-host.prev.log")) + except OSError as e: + log.warning("Could not rotate strata-host.log: %s", e) + def _url(self, path: str) -> str: return f"http://127.0.0.1:{self.port}{path}" diff --git a/kurgan/ai/service.py b/kurgan/ai/service.py index ef6ad99..b7073a1 100644 --- a/kurgan/ai/service.py +++ b/kurgan/ai/service.py @@ -193,8 +193,12 @@ class AiService: def _wait_ready(self, key: str, slot: Slot, gone=None) -> None: start = time.monotonic() while True: - running = slot.external is not None or (slot.child is not None and not slot.stopping) - if running and port_in_use(slot.backend.port): + 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") @@ -203,6 +207,10 @@ class AiService: 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: @@ -303,11 +311,14 @@ class AiService: return active if time.monotonic() - self.last_used[active] < minutes * 60: return active - try: - self.settings.update("ai", active=None) - except OSError as e: - log.warning("Couldn't save the AI selection: %s", e) - 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 @@ -315,9 +326,15 @@ class AiService: 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: + 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 @@ -327,11 +344,16 @@ class AiService: self.transition = None return slot = self.slots[active] - if slot.child is not None and slot.variant != slot.backend.variant(): + 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 # At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the diff --git a/kurgan/ai/strata_host.py b/kurgan/ai/strata_host.py index ca558cf..46ce4e1 100644 --- a/kurgan/ai/strata_host.py +++ b/kurgan/ai/strata_host.py @@ -5,6 +5,8 @@ imported by it. Does what Strata's local-service-tray.py did, without the tray i the same environment, arguments, logs and single-instance mutex. The Kurgan asks it to stop by setting the named event given in --stop-event; Strata then shuts down cleanly (finishing or cancelling the current request within --shutdown-timeout) and ends its engine processes. +If the server somehow never returns from that, a watchdog ends the process rather than +letting it hang; The Kurgan's own kill (a little later) is the last resort behind that. """ from __future__ import annotations @@ -23,6 +25,8 @@ import sys import threading LOG = logging.getLogger("kurgan-strata") +SHUTDOWN_GRACE = 40 # Strata's --shutdown-timeout is 30 s; The Kurgan kills at 45 s (its stop_timeout) +KEEP_LOG_PAIRS = 7 # stdout/stderr files are written per start; keep the newest few K32 = ctypes.WinDLL("kernel32", use_last_error=True) K32.CreateEventW.argtypes, K32.CreateEventW.restype = [wt.LPVOID, wt.BOOL, wt.BOOL, wt.LPCWSTR], wt.HANDLE K32.CreateMutexW.argtypes, K32.CreateMutexW.restype = [wt.LPVOID, wt.BOOL, wt.LPCWSTR], wt.HANDLE @@ -30,12 +34,43 @@ K32.WaitForSingleObject.argtypes, K32.WaitForSingleObject.restype = [wt.HANDLE, K32.CloseHandle.argtypes = [wt.HANDLE] -def watch_stop(event: int, stopping: threading.Event) -> None: +def watch_stop(event: int, shutdown: threading.Event, cleanup) -> None: while K32.WaitForSingleObject(event, 1000) != 0: pass LOG.info("The Kurgan asked Strata to stop") - stopping.set() - _thread.interrupt_main() + _thread.interrupt_main() # KeyboardInterrupt in the main thread unwinds server.main() + if not shutdown.wait(SHUTDOWN_GRACE): + # The server never returned (stuck in engine code, say): end the children ourselves + # rather than leave The Kurgan to kill the whole job without a clean shutdown. + LOG.error("Strata did not stop within %d s of the request; ending it", SHUTDOWN_GRACE) + try: + cleanup() + except Exception: + LOG.exception("Ending the engine processes failed") + os._exit(1) + + +def rotate_logs(logs: Path) -> None: + """Bound the log directory: one previous task log, and the newest few stdout/stderr pairs.""" + task = logs / "local-service-task.log" + if task.exists(): + try: + task.replace(logs / "local-service-task.prev.log") + except OSError as e: + LOG.warning("Could not rotate the task log: %s", e) + stamps = set() + for path in logs.glob("local-service-std*.log"): + for kind in ("stdout", "stderr"): + prefix = f"local-service-{kind}-" + if path.name.startswith(prefix): + stamps.add(path.name[len(prefix):-len(".log")]) + break + for stamp in sorted(stamps)[:-KEEP_LOG_PAIRS]: + for path in logs.glob(f"local-service-std*-{stamp}.log"): + try: + path.unlink() + except OSError as e: + LOG.warning("Could not delete the old log %s: %s", path.name, e) def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: str) -> int: @@ -58,8 +93,9 @@ def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: st if not stop_event: K32.CloseHandle(mutex) raise ctypes.WinError(ctypes.get_last_error()) - stopping = threading.Event() - threading.Thread(target=watch_stop, args=(stop_event, stopping), name="kurgan-stop", daemon=True).start() + shutdown = threading.Event() + threading.Thread(target=watch_stop, args=(stop_event, shutdown, lifeline.end_children), + name="kurgan-stop", daemon=True).start() try: LOG.info("Starting Strata API for %s at 127.0.0.1:%s (The Kurgan, pid %s)", model_id, port, os.getpid()) os.environ["GGML_CUDA_DISABLE_GRAPHS"] = "1" @@ -71,6 +107,7 @@ def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: st except KeyboardInterrupt: return 0 finally: + shutdown.set() # the process is winding down: the watchdog stands down lifeline.end_children() K32.CloseHandle(stop_event) K32.CloseHandle(mutex) @@ -87,6 +124,7 @@ def main() -> int: args = parser.parse_args() logs = args.root / "logs" logs.mkdir(exist_ok=True) + rotate_logs(logs) stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f") logging.basicConfig(filename=logs / "local-service-task.log", level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") diff --git a/tests/test_ai.py b/tests/test_ai.py index dc6bf6c..a283619 100644 --- a/tests/test_ai.py +++ b/tests/test_ai.py @@ -2,10 +2,11 @@ import os import tempfile import threading import unittest +from pathlib import Path from unittest.mock import patch -from kurgan.ai import launcher -from kurgan.ai.backends import Backend, LlamaLog +from kurgan.ai import launcher, strata_host +from kurgan.ai.backends import Backend, LlamaLog, StrataBackend from kurgan.ai.service import CLIENT_GONE, AiService, RouteError from kurgan.settings import Settings @@ -311,6 +312,75 @@ class AiServiceTest(unittest.TestCase): self.reconcile() self.assertEqual(self.processes()["llama"], "starting") + def test_a_server_with_a_request_in_flight_is_not_stopped_or_replaced(self): + self.service.set_active("strata") + self.reconcile() + self.service.inflight["strata"] = 1 # a reply in progress + self.service.set_active("llama") + self.reconcile() + # Strata finishes its request first; llama must not start onto the GPU's memory. + self.assertEqual(self.events, [("start", "strata")]) + self.assertIn("Waiting for Strata to finish its request", self.service.transition) + self.service.release("strata") + self.reconcile() + self.assertEqual(self.events, [("start", "strata"), ("stop", "strata"), ("start", "llama")]) + + def test_a_model_change_waits_for_the_request_in_flight(self): + self.service.set_active("strata", "iq3") + self.reconcile() + self.service.inflight["strata"] = 1 + self.service.set_active("strata", "q5") + self.reconcile() + self.assertEqual(self.events, [("start", "strata")]) # iq3 keeps serving until the reply ends + self.service.release("strata") + self.reconcile() + self.assertEqual(self.events, [("start", "strata"), ("stop", "strata"), ("start", "strata")]) + + def test_a_port_held_by_a_program_that_is_not_the_server_is_not_used(self): + self.external_ports.add(18082) + self.service.set_active("strata") + self.reconcile() + self.assertEqual(self.service.snapshot()["backends"][0]["process"], "external") + self.service.slots["strata"].reachable = True # a poll succeeded: the program is Strata + self.assertEqual(self.service.claim("strata").key, "strata") + self.service.release("strata") + self.service.slots["strata"].reachable = False # ...and then it stopped answering as one + thread, result = self.claim_in_background("strata") + threading.Event().wait(0.2) + self.clock[0] += 11 + thread.join(5) + self.assertIn("isn't answering as Strata", str(result["error"])) + self.assertEqual(self.service.inflight["strata"], 0) # the failed claim gave its place back + + +class StrataLogRotationTest(unittest.TestCase): + def test_old_strata_logs_are_rotated_and_pruned(self): + with tempfile.TemporaryDirectory() as directory: + logs = Path(directory) + (logs / "local-service-task.log").write_text("last run") + for number in range(9): + stamp = f"2026010{number + 1}-000000-000000" + (logs / f"local-service-stdout-{stamp}.log").write_text("out") + (logs / f"local-service-stderr-{stamp}.log").write_text("err") + strata_host.rotate_logs(logs) + self.assertEqual((logs / "local-service-task.prev.log").read_text(), "last run") + self.assertFalse((logs / "local-service-task.log").exists()) + names = sorted(p.name for p in logs.glob("local-service-std*.log")) + self.assertEqual(len(names), 2 * strata_host.KEEP_LOG_PAIRS) # the newest few pairs + self.assertIn("local-service-stdout-20260109-000000-000000.log", names) + self.assertNotIn("local-service-stdout-20260101-000000-000000.log", names) + + def test_strata_host_log_is_rotated_before_a_start(self): + with tempfile.TemporaryDirectory() as directory: + with patch("kurgan.ai.backends.LOG_DIR", directory): + backend = StrataBackend(Settings(os.path.join(directory, "settings.json"), None)) + with open(os.path.join(directory, "strata-host.log"), "w") as log: + log.write("previous run") + backend.before_start() + self.assertFalse(os.path.exists(os.path.join(directory, "strata-host.log"))) + with open(os.path.join(directory, "strata-host.prev.log")) as log: + self.assertEqual(log.read(), "previous run") + class LauncherTest(unittest.TestCase): def test_child_runs_as_a_normal_user_with_its_output_logged(self):