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.
This commit is contained in:
paul committed 2026-12-05 17:13:10 +13:00
1 parent 9036c6e734
commit 8969a57045
5 files changed
+171 -23

No files matched your search

+43 -5
View File
@@ -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")