Files
paul 8969a57045 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.
2026-12-05 17:13:10 +13:00

421 lines
19 KiB
Python

import os
import tempfile
import threading
import unittest
from pathlib import Path
from unittest.mock import patch
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
LLAMA_REQUEST = """\
slot launch_slot_: id 0 | task 12 | processing task
slot update_slots: id 0 | task 12 | prompt processing, n_tokens = 2048, progress = 0.5, t = 1.2 s / 1706.7 tokens per second
slot update_slots: id 0 | task 12 | prompt processing, n_tokens = 4096, progress = 1.0, t = 2.4 s / 1706.7 tokens per second
slot process_toke: id 0 | task 12 | n_gen = 100, tg = 95.2 t/s, tg_3s = 97.1 t/s
slot print_timing: id 0 | task 12 | prompt eval time = 2400.00 ms / 4096 tokens ( 0.59 ms per token, 1706.67 tokens per second)
slot print_timing: id 0 | task 12 | eval time = 5000.00 ms / 500 tokens ( 10.00 ms per token, 100.00 tokens per second)
slot release: id 0 | task 12 | stop processing: n_tokens = 5096, truncated = 0
"""
class LlamaLogTest(unittest.TestCase):
def test_request_in_progress_and_finished(self):
parser = LlamaLog()
lines = LLAMA_REQUEST.splitlines()
for line in lines[:2]:
parser.feed(line, now=1000.0)
live, requests, _ = parser.snapshot()
self.assertEqual((live["phase"], live["progress"], live["read"], live["tok_s"]), ("reading", 0.5, 2048, 1706.7))
self.assertEqual(requests, [])
parser.feed(lines[3], now=1003.0)
live, _, _ = parser.snapshot()
self.assertEqual((live["phase"], live["generated"], live["tok_s"]), ("generating", 100, 97.1))
for line in lines[4:]:
parser.feed(line, now=1008.0)
live, requests, averages = parser.snapshot()
self.assertIsNone(live)
self.assertEqual(len(requests), 1)
r = requests[0]
self.assertEqual((r["status"], r["prompt"], r["reused"], r["output"], r["duration"]), ("ok", 4596, 500, 500, 8.0))
self.assertEqual((r["prefill_tps"], r["decode_tps"]), (1706.67, 100.0))
self.assertEqual(averages, {"prefill_tps": 1706.7, "decode_tps": 100.0, "requests": 1})
def test_unrelated_lines_and_lines_before_a_task_are_ignored(self):
parser = LlamaLog()
parser.feed("srv log_server_r: request: GET /models 127.0.0.1 200")
parser.feed("slot update_slots: id 0 | task 3 | n_gen = 5, tg = 1.0 t/s, tg_3s = 1.0 t/s")
self.assertEqual(parser.snapshot(), (None, [], {"prefill_tps": None, "decode_tps": None, "requests": 0}))
class FakeChild:
def __init__(self, argv):
self.argv = argv
self.pid = 4000 + len(argv[0])
self.token = {"integrity": "medium", "elevated": False}
self.code = None
def poll(self):
return self.code
def wait(self, timeout=None):
return self.code
def kill(self):
if self.code is None:
self.code = 1
def close(self):
pass
class FakeBackend(Backend):
stop_timeout = 0.1
def __init__(self, settings, key, port, events):
self.key, self.label, self._port, self.events = key, key.capitalize(), port, events
super().__init__(settings)
@property
def port(self):
return self._port
def variant(self):
return self.settings.get("ai", "strata_model") if self.key == "strata" else None
def model_label(self):
return f"{self.key} model"
def command(self):
return [self.key], ".", None
def request_stop(self, child):
self.events.append(("stop", self.key))
child.code = 0
class AiServiceTest(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
self.addCleanup(self.dir.cleanup)
self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None)
self.events = []
self.children = []
self.service = AiService(self.settings, [FakeBackend(self.settings, "strata", 18082, self.events),
FakeBackend(self.settings, "llama", 18083, self.events)])
self.external_ports = set()
self.clock = [1000.0]
def launch(argv, cwd, log_path):
self.events.append(("start", argv[0]))
self.children.append(FakeChild(argv))
return self.children[-1]
for target, fake in (("kurgan.ai.service.launcher.launch", launch),
("kurgan.ai.service.port_in_use", lambda port: port in self.external_ports),
("kurgan.ai.service.port_owner", lambda port: (1234, "pythonw.exe")),
("kurgan.ai.service.time.monotonic", lambda: self.clock[0])):
patcher = patch(target, side_effect=fake)
patcher.start()
self.addCleanup(patcher.stop)
self.stop = threading.Event()
def reconcile(self):
self.service._reconcile(self.stop)
def processes(self):
return {b["key"]: b["process"] for b in self.service.snapshot()["backends"]}
def test_swapping_stops_the_running_server_before_starting_the_other(self):
self.reconcile()
self.assertEqual(self.events, [])
self.service.set_active("llama")
self.reconcile()
self.service.set_active("strata", "iq3")
self.reconcile()
self.assertEqual(self.events, [("start", "llama"), ("stop", "llama"), ("start", "strata")])
self.assertEqual(self.settings.get("ai", "strata_model"), "iq3")
self.service.set_active("strata", "q5") # another Strata model: restart it
self.reconcile()
self.service.set_active(None)
self.reconcile()
self.assertEqual(self.events[3:], [("stop", "strata"), ("start", "strata"), ("stop", "strata")])
self.assertEqual(self.processes(), {"strata": "stopped", "llama": "stopped"})
def test_unknown_backend_or_variant_is_rejected_and_not_saved(self):
with self.assertRaises(ValueError):
self.service.set_active("ollama")
with self.assertRaises(ValueError):
self.service.set_active("strata", "q8")
self.assertIsNone(self.settings.get("ai", "active"))
def test_crashes_restart_after_a_pause_and_repeated_crashes_hold_off(self):
self.service.set_active("llama")
self.reconcile()
for crash in range(4):
self.children[-1].code = 3
self.reconcile()
self.assertEqual(len(self.children), crash + 1, "no restart during the 5 s pause")
self.assertIn("exited (code 3); restarting", self.service.snapshot()["backends"][1]["error"])
self.clock[0] += 6
self.reconcile()
self.assertEqual(len(self.children), crash + 2)
self.children[-1].code = 3
self.reconcile()
self.clock[0] += 60
self.reconcile()
self.assertEqual(len(self.children), 5)
self.assertIn("keeps exiting", self.service.snapshot()["backends"][1]["error"])
self.clock[0] += 300
self.reconcile()
self.assertEqual(len(self.children), 6)
def test_a_server_started_elsewhere_is_watched_not_duplicated(self):
self.external_ports.add(18082)
self.service.set_active("strata")
self.reconcile()
self.assertEqual(self.events, [])
snap = self.service.snapshot()
self.assertEqual((snap["backends"][0]["process"], snap["backends"][0]["pid"]), ("external", 1234))
self.service.set_active("llama")
self.reconcile()
self.assertEqual(self.events, [("start", "llama")])
self.assertIn("Strata is also running outside The Kurgan", self.service.snapshot()["warning"])
self.service.set_active(None)
self.reconcile()
self.assertIn("Strata is running outside The Kurgan, from its own startup task",
self.service.snapshot()["warning"])
def claim_in_background(self, key):
result = {}
def run():
try:
result["backend"] = self.service.claim(key)
except Exception as e:
result["error"] = e
thread = threading.Thread(target=run, daemon=True)
thread.start()
return thread, result
def serve(self, key, port):
"""Let the supervisor start key's server and have it 'listen'."""
for _ in range(100):
if self.settings.get("ai", "active") == key:
break
threading.Event().wait(0.02)
self.reconcile()
self.external_ports.add(port)
def test_a_request_starts_its_server_once_the_other_is_idle(self):
self.service.set_active("llama")
self.reconcile()
thread, result = self.claim_in_background("strata")
self.serve("strata", 18082)
thread.join(5)
self.assertEqual(result["backend"].key, "strata")
self.assertEqual(self.events, [("start", "llama"), ("stop", "llama"), ("start", "strata")])
self.assertEqual(self.service.inflight["strata"], 1)
self.service.release("strata")
self.assertEqual(self.service.inflight["strata"], 0)
# The selected server's own requests go straight through.
self.assertEqual(self.service.claim("strata").key, "strata")
self.service.release("strata")
def test_a_request_waits_while_the_other_server_is_busy(self):
self.service.set_active("llama")
self.reconcile()
self.external_ports.add(18083)
self.service.claim("llama") # a reply in progress
thread, result = self.claim_in_background("strata")
thread.join(0.3)
self.assertTrue(thread.is_alive())
self.assertEqual(self.settings.get("ai", "active"), "llama")
self.service.release("llama")
self.external_ports.discard(18083)
self.serve("strata", 18082)
thread.join(5)
self.assertEqual(result["backend"].key, "strata")
def test_a_request_gives_up_if_the_other_server_stays_busy(self):
self.service.set_active("llama")
self.reconcile()
self.external_ports.add(18083)
self.service.claim("llama")
thread, result = self.claim_in_background("strata")
thread.join(0.2)
self.clock[0] += AiService.BUSY_WAIT + 1
with self.service._cv:
self.service._cv.notify_all()
thread.join(5)
self.assertIn("still busy", str(result["error"]))
self.assertEqual(self.service.inflight, {"strata": 0, "llama": 1})
def test_a_request_whose_client_hangs_up_never_switches_servers(self):
self.service.set_active("llama")
self.reconcile()
self.external_ports.add(18083)
self.service.claim("llama") # llama busy
hung_up = threading.Event()
result = {}
def run():
try:
self.service.claim("strata", gone=hung_up.is_set)
except RouteError as e:
result["error"] = e
thread = threading.Thread(target=run, daemon=True)
thread.start()
thread.join(0.2)
hung_up.set()
self.service.release("llama") # llama now idle: a live request would switch here
thread.join(5)
self.assertEqual((result["error"].status, str(result["error"])), (CLIENT_GONE, "while waiting for Llama to finish"))
self.assertEqual(self.settings.get("ai", "active"), "llama")
self.assertEqual(self.service.inflight, {"strata": 0, "llama": 0})
# Hanging up while its own server starts also gives the place back.
self.external_ports.clear() # llama's port closes when it stops
self.service.set_active(None)
self.reconcile()
answers = iter([False] + [True] * 10) # still there when it asks for llama; gone while it starts
with self.assertRaises(RouteError) as caught:
self.service.claim("llama", gone=lambda: next(answers))
self.assertEqual((caught.exception.status, str(caught.exception)), (CLIENT_GONE, "while waiting for Llama to start"))
self.assertEqual(self.service.inflight["llama"], 0)
def test_an_unused_server_stops_after_the_idle_time(self):
self.service.set_active("llama")
self.reconcile()
self.assertEqual(self.service.snapshot()["backends"][1]["idle_stop_in"], 40 * 60)
self.clock[0] += 39 * 60
self.reconcile()
self.assertEqual(self.processes()["llama"], "starting")
self.assertEqual(self.service.snapshot()["backends"][1]["idle_stop_in"], 60)
self.service.inflight["llama"] = 1 # a long request keeps it running
self.clock[0] += 5 * 60
self.reconcile()
self.assertEqual(self.processes()["llama"], "starting")
self.service.release("llama")
self.clock[0] += 40 * 60 + 1
self.reconcile()
self.assertEqual(self.processes()["llama"], "stopped")
self.assertIsNone(self.settings.get("ai", "active"))
self.settings.update("ai", idle_stop_minutes=0) # never
self.service.set_active("llama")
self.reconcile()
self.clock[0] += 24 * 3600
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):
with tempfile.TemporaryDirectory() as directory:
log_path = os.path.join(directory, "logs", "child.log")
child = launcher.launch(["cmd.exe", "/d", "/c", "echo hello from the child& exit 7"], directory, log_path)
try:
self.assertEqual(child.wait(10), 7)
self.assertEqual(child.token, {"integrity": "medium", "elevated": False})
finally:
child.close()
with open(log_path, encoding="utf-8", errors="replace") as f:
self.assertIn("hello from the child", f.read())
def test_kill_ends_the_whole_job(self):
with tempfile.TemporaryDirectory() as directory:
child = launcher.launch(["cmd.exe", "/d", "/c", "ping -n 30 127.0.0.1"], directory, None)
try:
self.assertIsNone(child.poll())
child.kill()
self.assertIsNotNone(child.wait(10))
finally:
child.close()
def test_pinned_openblas_setting_is_not_passed_on(self):
with patch.dict(os.environ, {"OPENBLAS_NUM_THREADS": "1", "KURGAN_PINNED_OPENBLAS": "1"}):
env = launcher.child_environment({"EXTRA": "x"})
self.assertNotIn("OPENBLAS_NUM_THREADS", env)
self.assertNotIn("KURGAN_PINNED_OPENBLAS", env)
self.assertEqual(env["EXTRA"], "x")
with patch.dict(os.environ, {"OPENBLAS_NUM_THREADS": "4"}):
os.environ.pop("KURGAN_PINNED_OPENBLAS", None)
self.assertEqual(launcher.child_environment()["OPENBLAS_NUM_THREADS"], "4")
if __name__ == "__main__":
unittest.main()