From 48e6d64c4f3d386423b1ca9a8eb85cab9d79f304 Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Thu, 15 Oct 2026 15:58:04 +0200 Subject: [PATCH] serve, control: a server's engine ends with it however it ends, leftovers are found by PID, start time and command line, runtime stop/cleanup recover a lost owner lifeline.popen ties every engine, image encoder, MCP server and sd-cli to the server that started them (kill-on-close job on Windows, PR_SET_PDEATHSIG from one anchor thread on Linux, a pipe watcher elsewhere). Engines and encoders get their own process group so Ctrl+C, a closing terminal and a console Break reach the server only, which stops the engine the clean way (STOP, QUIT, wait 20 s, terminate 5 s, kill). SIGHUP, SIGBREAK and the Windows console close/logoff/shutdown events take Ctrl+C's path; the handlers are installed before the model loads and the browser launch no longer holds the main thread (#1872). The owner guard escalates SIGTERM to SIGKILL after a grace period. strata_control/procs.py records every launch and finds leftovers; the next engine start, runtime start, runtime stop and the new runtime cleanup end them after re-checking identity. runtime start --die-with-pid for app-owned instances. tests/terminal/lifecycle_matrix.py is the close-path matrix. --- serve/images.py | 12 +- serve/lifeline.py | 316 ++++++++++++ serve/mcp.py | 9 +- serve/owner_guard.py | 21 +- serve/server.py | 68 ++- serve/test_lifecycle.py | 2 +- serve/test_lifeline.py | 138 +++++ serve/test_server.py | 10 +- serve/test_vision_busy.py | 2 +- strata_cli/cli.py | 31 +- strata_control/management.py | 6 +- strata_control/procs.py | 370 ++++++++++++++ strata_control/runtime.py | 80 ++- tests/terminal/lifecycle_matrix.py | 652 ++++++++++++++++++++++++ tests/terminal/test_lifecycle_matrix.py | 36 ++ tests/terminal/test_procs.py | 141 +++++ 16 files changed, 1836 insertions(+), 58 deletions(-) create mode 100644 serve/lifeline.py create mode 100644 serve/test_lifeline.py create mode 100644 strata_control/procs.py create mode 100644 tests/terminal/lifecycle_matrix.py create mode 100644 tests/terminal/test_lifecycle_matrix.py create mode 100644 tests/terminal/test_procs.py diff --git a/serve/images.py b/serve/images.py index f322a571..9a7260e3 100644 --- a/serve/images.py +++ b/serve/images.py @@ -230,16 +230,12 @@ class ImageGen: with self.lock: with open(logf, "w", encoding="utf-8", errors="replace") as lf: try: - proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - stdin=subprocess.DEVNULL, env=image_env(self.cfg), - cwd=str(work), text=True, errors="replace", bufsize=1) + from serve import lifeline + proc = lifeline.popen(cmd, "image", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + stdin=subprocess.DEVNULL, env=image_env(self.cfg), + cwd=str(work), text=True, errors="replace", bufsize=1) except OSError as e: raise ImageJobFailed(f"sd-cli did not start ({cmd[0]}): {e}") from e - try: - from serve.winjob import contain - contain(proc) # ends with the server (Windows) - except Exception: - pass why = None def pump(): diff --git a/serve/lifeline.py b/serve/lifeline.py new file mode 100644 index 00000000..c33ced63 --- /dev/null +++ b/serve/lifeline.py @@ -0,0 +1,316 @@ +"""serve/lifeline.py - a process Strata starts ends when the process that started it ends, however that ends. + +The graceful path is the server's own (QUIT to the engine, drain, exit). This module is the guarantee behind it +for the cases where nothing gets to run: kill -9, a crash, the console window closed, logoff, power-off. + +* Windows: the child joins a kill-on-close job object whose only handle is ours (serve/winjob.py). +* Linux: ``PR_SET_PDEATHSIG`` = SIGKILL, set in the child before it execs. The kernel ties the signal to the + THREAD that forked the child, not to the process, so every start goes through one long-lived "anchor" thread; + a request thread that starts an engine and then finishes would otherwise take the engine with it. +* macOS (no such call): a small watcher process holds a pipe to us. When we die the pipe closes, the watcher + sees EOF and ends the child, after checking it is still the same process (PID, start time). A child that + ended on its own, or was ended by us, is released first, so the watcher never signals a reused PID. + +``popen`` is ``subprocess.Popen`` plus the guarantee. ``release`` is called once the child has been reaped. +""" +from __future__ import annotations + +import atexit +import concurrent.futures +import os +import queue +import signal +import subprocess +import sys +import threading +import time + +from serve import winjob +from strata_control import procs + +_REAL_POPEN = subprocess.Popen # tests replace subprocess.Popen; isinstance needs the class +LINUX = sys.platform.startswith("linux") +MODE = (os.environ.get("STRATA_LIFELINE") or "").strip().lower() # "watcher" forces the portable path (tests) + +_libc = None +if LINUX: + try: + import ctypes + _libc = ctypes.CDLL(None, use_errno=True) + _libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong) + except (OSError, AttributeError): + _libc = None + +PR_SET_PDEATHSIG = 1 + + +class _Anchor: + """One thread that lives as long as the process and performs every Popen, so PDEATHSIG's "parent" is it.""" + + def __init__(self) -> None: + self._jobs: queue.Queue = queue.Queue() + self._thread = threading.Thread(target=self._run, name="strata-lifeline-anchor", daemon=True) + self._thread.start() + + def _run(self) -> None: + while True: + fn, future = self._jobs.get() + try: + future.set_result(fn()) + except BaseException as exc: # noqa: BLE001 - handed to the caller + future.set_exception(exc) + + def call(self, fn): + if threading.current_thread() is self._thread: + return fn() + future: concurrent.futures.Future = concurrent.futures.Future() + self._jobs.put((fn, future)) + return future.result() + + +_anchor: _Anchor | None = None +_anchor_lock = threading.Lock() + + +def _the_anchor() -> _Anchor: + global _anchor + with _anchor_lock: + if _anchor is None: + _anchor = _Anchor() + return _anchor + + +def _die_with_parent(parent: int, then=None): + """The preexec function of a child: SIGKILL when the starting thread ends; and if it ended already, now.""" + def run() -> None: + _libc.prctl(PR_SET_PDEATHSIG, int(signal.SIGKILL), 0, 0, 0) + if os.getppid() != parent: # the parent died between fork and prctl + os.kill(os.getpid(), signal.SIGKILL) + if then is not None: + then() + return run + + +# ---------------------------------------------------------------------------------------- the portable watcher + +_WATCHER = r''' +import os, signal, subprocess, sys, time +pid, token = int(sys.argv[1]), sys.argv[2] +for s in (signal.SIGINT, signal.SIGHUP, signal.SIGTERM): + signal.signal(s, signal.SIG_IGN) # it ends with its pipe, not with the terminal +def start_of(p): + try: + out = subprocess.run(["ps", "-o", "lstart=,stat=", "-p", str(p)], capture_output=True, text=True, timeout=5).stdout.strip() + except Exception: + return None + return None if not out or out.endswith("Z") else "s:" + out +os.set_blocking(0, True) +data = b"" +while True: + chunk = os.read(0, 16) + if not chunk: + break + data += chunk + if b"x" in data: # released: the child is gone or was ended on purpose + sys.exit(0) +if token and start_of(pid) == token: + try: + os.kill(pid, signal.SIGTERM) + except OSError: + sys.exit(0) + for _ in range(40): + time.sleep(0.25) + if start_of(pid) != token: + sys.exit(0) + if start_of(pid) == token: + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass +''' + +_watchers: dict[int, subprocess.Popen] = {} +_watchers_lock = threading.Lock() + + +def _start_token(pid: int) -> str: + try: + out = subprocess.run(["ps", "-o", "lstart=,stat=", "-p", str(pid)], capture_output=True, text=True, + timeout=5).stdout.strip() + except (OSError, subprocess.SubprocessError): + return "" + return "" if not out or out.endswith("Z") else "s:" + out + + +def _watch(child: subprocess.Popen) -> None: + try: + watcher = subprocess.Popen([sys.executable, "-S", "-c", _WATCHER, str(child.pid), _start_token(child.pid)], + stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + close_fds=True, start_new_session=True) + except OSError: + return + with _watchers_lock: + _watchers[child.pid] = watcher + + +def release(child: subprocess.Popen | None) -> None: + """The child has been reaped (or ended on purpose): stop watching it. Harmless where nothing is watching.""" + if child is None: + return + with _watchers_lock: + watcher = _watchers.pop(child.pid, None) + if watcher is None: + return + try: + watcher.stdin.write(b"x") + watcher.stdin.close() + except (OSError, ValueError): + pass + try: + watcher.wait(timeout=5) + except subprocess.TimeoutExpired: + watcher.kill() + + +# ---------------------------------------------------------------------------------------------------- popen + +def mechanism() -> str: + """Which guarantee a start gets on this platform: job, pdeathsig, watcher.""" + if os.name == "nt": + return "job" + if LINUX and _libc is not None and MODE != "watcher": + return "pdeathsig" + return "watcher" + + +_children: set = set() +_children_lock = threading.Lock() + + +def end_children(grace: float = 3.0) -> None: + """Whatever this process started and has not ended yet: terminate, then kill. Runs at interpreter exit, so an + exception or a signal that unwinds main() before its own cleanup still leaves nothing behind (the engine and + the others have already been closed on every normal path, so this finds nothing then).""" + with _children_lock: + alive = [c for c in _children if c.poll() is None] + for child in alive: + try: + child.terminate() + except OSError: + pass + deadline = time.monotonic() + grace + for child in alive: + try: + child.wait(timeout=max(0.0, deadline - time.monotonic())) + except (subprocess.TimeoutExpired, OSError): + try: + child.kill() + except OSError: + pass + + +atexit.register(end_children) + + +def _after_exit(child: subprocess.Popen, token: str | None) -> None: + child.wait() + with _children_lock: + _children.discard(child) + release(child) + if token is not None: + procs.drop_record(child.pid, token) + + +ISOLATED_ROLES = ("engine", "vision") # speak a stdin protocol with us: the server alone decides when they stop + + +def _own_group(then=None): + def run() -> None: + os.setpgid(0, 0) + if then is not None: + then() + return run + + +def popen(args, role: str = "engine", **kw) -> subprocess.Popen: + """``subprocess.Popen(args, **kw)`` for a process that must not outlive us. + + An engine or image encoder is also taken out of the terminal's reach (its own process group on POSIX, a new + process group on Windows): Ctrl+C, a closing terminal or a console Break go to the server only, which then ends + the engine the clean way (STOP, QUIT, wait) instead of the engine dying under a request that could have been + finished or cancelled. What ties the engine's life to ours is the guarantee below, not the shared terminal. + + It also leaves a record (strata_control/procs.py) so that, if everything here dies anyway, the next start can + find this process by PID, start time and command line and end it.""" + how = mechanism() + isolate = role in ISOLATED_ROLES + if isolate and os.name == "nt": + kw["creationflags"] = kw.get("creationflags", 0) | subprocess.CREATE_NEW_PROCESS_GROUP + if isolate and os.name != "nt" and "start_new_session" not in kw: + kw["preexec_fn"] = _own_group(kw.pop("preexec_fn", None)) + if how == "pdeathsig": + parent, then = os.getpid(), kw.pop("preexec_fn", None) + kw["preexec_fn"] = _die_with_parent(parent, then) + child = _the_anchor().call(lambda: subprocess.Popen(args, **kw)) + else: + child = subprocess.Popen(args, **kw) + if how == "job": + winjob.contain(child) + else: + _watch(child) + if isinstance(child, _REAL_POPEN): + with _children_lock: + _children.add(child) + try: + token = procs.write_record(child.pid, role, profile=os.environ.get("STRATA_RUNTIME_PROFILE") or None) + threading.Thread(target=_after_exit, args=(child, token), name="strata-lifeline-reaper", daemon=True).start() + except Exception: # noqa: BLE001 - a record is a safety net, never a reason to fail a start + pass + return child + + +# ------------------------------------------------------------------------------------------- stop signals + +_console_handler = None # the ctypes callback must stay referenced for the life of the process + + +def install_stop_handlers(request_stop, finished: threading.Event | None = None) -> None: + """Make every ordinary way a server is asked to end take the clean path (`request_stop(reason)`). + + * POSIX: SIGTERM (docker stop, systemd, `kill`), SIGHUP (the terminal closed, the ssh connection dropped). + SIGINT keeps Python's own handler (Ctrl+C, and a second Ctrl+C to stop waiting). + * Windows: SIGBREAK, and the console's close, logoff and shutdown events. Those arrive on a thread of their own and + the system ends the process a few seconds after the handler returns, so the handler waits for `finished` (up to + 4.5 s) and then returns; whatever is still running is ended by the job object. + Must be called from the main thread.""" + def in_main(reason: str): + def handler(signum, frame): + request_stop(reason) + return handler + for name, reason in (("SIGTERM", "sigterm"), ("SIGHUP", "sighup"), ("SIGBREAK", "sigbreak")): + sig = getattr(signal, name, None) + if sig is None: + continue + try: + signal.signal(sig, in_main(reason)) + except (ValueError, OSError): # not the main thread + pass + if os.name != "nt": + return + import ctypes + from ctypes import wintypes + events = {2: "console-close", 5: "logoff", 6: "shutdown"} + prototype = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD) + + def on_console_event(event: int) -> bool: + reason = events.get(event) + if reason is None: + return False # Ctrl+C and Ctrl+Break: Python's own handling + request_stop(reason) + if finished is not None: + finished.wait(4.5) + return True + + global _console_handler + _console_handler = prototype(on_console_event) + ctypes.windll.kernel32.SetConsoleCtrlHandler(_console_handler, True) diff --git a/serve/mcp.py b/serve/mcp.py index 4586e2c1..116251af 100644 --- a/serve/mcp.py +++ b/serve/mcp.py @@ -31,7 +31,7 @@ import time import urllib.error import urllib.request -from serve.winjob import contain +from serve import lifeline PROTOCOL = "2025-06-18" # the MCP revision Strata asks for; the server's answer is used as given DEFAULTS = {"timeout_s": 60.0, "max_result_chars": 20000, "max_rounds": 8, "start_timeout_s": 120.0} @@ -102,12 +102,11 @@ class StdioTransport: else: extra["start_new_session"] = True # its own process group, so close() ends its children too try: - self.proc = subprocess.Popen([exe, *[str(a) for a in self.cfg.get("args") or []]], stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cfg.get("cwd") or None, - env=env, **extra) + self.proc = lifeline.popen([exe, *[str(a) for a in self.cfg.get("args") or []]], "mcp", stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cfg.get("cwd") or None, + env=env, **extra) except OSError as e: raise McpError(f"could not start {command!r}: {e}") from None - contain(self.proc) # ends with the server, however it ends (Windows) self._err_reader = threading.Thread(target=self._read_stderr, daemon=True) self._err_reader.start() threading.Thread(target=self._read, daemon=True).start() diff --git a/serve/owner_guard.py b/serve/owner_guard.py index 1b4efe51..2d2046b9 100644 --- a/serve/owner_guard.py +++ b/serve/owner_guard.py @@ -18,6 +18,7 @@ import os import signal import stat import threading +import time def _stop_gracefully() -> None: @@ -25,7 +26,7 @@ def _stop_gracefully() -> None: _thread.interrupt_main() -def start(fd: int, on_loss=None) -> None: +def start(fd: int, on_loss=None, grace: float = 60.0) -> None: if os.name == "nt": if fd < 0 or not stat.S_ISFIFO(os.fstat(fd).st_mode): raise ValueError("--owner-fd must be an inherited pipe") @@ -49,13 +50,21 @@ def start(fd: int, on_loss=None) -> None: try: while os.read(fd, 1): pass - # This is an emergency path. Signal the whole dedicated group so - # an engine already spawned during model loading cannot be orphaned. - os.killpg(os.getpgrp(), signal.SIGTERM) except OSError: - # A broken guard must never authorize another process to manage us. - os.killpg(os.getpgrp(), signal.SIGTERM) + pass # a broken guard must never authorize another process to manage us finally: os.close(fd) + # This is an emergency path. Signal the whole dedicated group so an engine already spawned during model + # loading cannot be orphaned. SIGTERM is the clean stop (the server drains and closes its engine); if the + # group is still there after `grace` seconds, SIGKILL ends whatever is left. + pgid = os.getpgrp() + try: + os.killpg(pgid, signal.SIGTERM) + deadline = time.monotonic() + grace + while time.monotonic() < deadline: + time.sleep(0.5) + os.killpg(pgid, signal.SIGKILL) + except OSError: + pass threading.Thread(target=watch, name="strata-owner-guard", daemon=True).start() diff --git a/serve/server.py b/serve/server.py index 9c58465e..642497ed 100644 --- a/serve/server.py +++ b/serve/server.py @@ -67,7 +67,7 @@ from serve import ready as ready_file # noqa: E402 from serve import owner_guard # noqa: E402 from serve import launch_identity # noqa: E402 from serve import logit_bias as bias_api # noqa: E402 -from serve.winjob import contain # noqa: E402 +from serve import lifeline # noqa: E402 from serve.structured import StructuredOutputError, prepare_format, validated_json # noqa: E402 from serve import responses as responses_api # noqa: E402 from serve.responses import ResponsesError, error_body as responses_error_body # noqa: E402 @@ -77,12 +77,12 @@ IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" -def popen(what: str, args: list, **kw): +def popen(what: str, args: list, role: str = "engine", **kw): """#735: subprocess.Popen, but Windows' refusal to start a program (WinError 4551, or 1260 when a policy blocks it: Smart App Control on a clean Windows 11 blocks an exe that is not signed) is said in words instead of a bare OSError.""" try: - return subprocess.Popen(args, **kw) + return lifeline.popen(args, role, **kw) # a child that cannot outlive this server (serve/lifeline.py) except OSError as e: if getattr(e, "winerror", None) in (4551, 1260): raise OSError(f"Windows blocked {what} ({args[0]}): Smart App Control, or an application-control policy, does " @@ -92,6 +92,21 @@ def popen(what: str, args: list, **kw): raise +def end_leftover_engines(exe: str) -> None: + """Before an engine starts: end the ones a lost server left running (strata_control/procs.py). Only a process + this install recorded whose starter is gone, or an orphan of exactly this executable running --serve, and only + after its PID, start time and command line are checked again at the moment of the signal. Never raises.""" + if os.environ.get("STRATA_KEEP_LEFTOVERS") == "1": + return + try: + from strata_control import procs + say = lambda text: print(text, flush=True) # noqa: E731 + procs.end_leftovers(say=say) + procs.end_orphans(exe, say=say) + except Exception as e: # noqa: BLE001 - a failed check must not stop a start + print(f"[strata] could not check for engines left by an earlier run: {type(e).__name__}", flush=True) + + def listen_problem(host: str, port: int, e: OSError) -> str: """#769: why the server cannot listen. Only an address that is taken says "already in use"; anything else (a port Windows keeps reserved, an address this PC does not have, no permission) says what the OS said.""" @@ -943,10 +958,10 @@ class StrataEngine: pin = {} if cpus and hasattr(os, "sched_setaffinity"): # replicas: this engine's own physical cores (serve/replicas.py) pin["preexec_fn"] = lambda: os.sched_setaffinity(0, cpus) + end_leftover_engines(exe) # one an earlier run lost still holds the GPU and the memory spawned_at = time.monotonic() self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, **pin) - contain(self.proc) # ends with the server, however it ends (Windows) # the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream # stays for _pump (one reader at a time) ready_q: queue.Queue = queue.Queue() @@ -2343,13 +2358,15 @@ class StrataEngine: try: if self.proc.poll() is None: try: - self.proc.stdin.write("QUIT\n") + # STOP first: a request still running ends at its next step instead of being waited for (the + # engine reads stdin on its own thread; QUIT behind a long answer would sit in its queue) + self.proc.stdin.write("STOP\nQUIT\n") self.proc.stdin.flush() self.proc.stdin.close() # Windows' detached stdin reader must see EOF before shutdown self.proc.wait(timeout=20) except (OSError, ValueError, subprocess.TimeoutExpired): self.proc.terminate() - self.proc.wait(timeout=20) + self.proc.wait(timeout=5) except subprocess.TimeoutExpired: self.proc.kill() try: @@ -2465,10 +2482,9 @@ class Vision: def _start(self): args, log, env = self.spawn # cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line) - self.proc = popen("the image encoder", args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, + self.proc = popen("the image encoder", args, role="vision", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env, cwd=self.dir) - contain(self.proc) try: line = self._readline(VISION_READY_S, "the vision encoder did not start") except RuntimeError as e: # silent for VISION_READY_S: it was ended, and it is not left half-started @@ -7364,9 +7380,24 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in "[{\"gpus\": [0, 1]}, {\"gpus\": [2, 3]}])") launch_args = list(sys.argv[1:] if argv is None else argv) a = ap.parse_args(launch_args) + # Every ordinary way of being asked to stop takes Ctrl+C's path (QUIT to the engine, then exit): SIGTERM (#96 docker + # stop; systemd), SIGHUP (the terminal closed, ssh dropped), and on Windows Ctrl+Break and the console's close, + # logoff and shutdown events. They are installed before anything slow starts, so one that arrives while the model + # loads is not the default "die at once". SIGINT keeps Python's own handler (a second Ctrl+C stops waiting). + termination = "sigint" + finished = threading.Event() # set when the clean stop is over (a Windows console handler waits for it) + + def request_stop(reason: str): + nonlocal termination + termination = reason + if threading.current_thread() is threading.main_thread(): + raise KeyboardInterrupt + import _thread + _thread.interrupt_main() + lifeline.install_stop_handlers(request_stop, finished) if a.owner_fd is not None: try: - owner_guard.start(a.owner_fd) + owner_guard.start(a.owner_fd, grace=(a.shutdown_timeout or 0) + 40) except (OSError, ValueError) as exc: ap.error(str(exc)) if a.shutdown_timeout is not None and not 0 <= a.shutdown_timeout <= 300: @@ -7742,20 +7773,10 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in " (and set this network to Private in Windows' network settings)", flush=True) if a.open and cfg.get("open_browser") is not False: # #609: the config's "open_browser": false wins (an older import webbrowser # run-.bat still passes --open) - webbrowser.open(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{bound_port}/") - # #96: docker stop sends SIGTERM, which Python ignores by default, so the container's PID 1 would be killed after - # the grace period with the engine still running. SIGTERM takes Ctrl+C's path below (QUIT to the engine). - # SIGINT keeps Python's own handler, so Ctrl+C and a second Ctrl+C work as before. - termination = "sigint" - - def on_sigterm(signum, frame): - nonlocal termination - termination = "sigterm" - raise KeyboardInterrupt - try: - signal.signal(signal.SIGTERM, on_sigterm) - except (ValueError, OSError, AttributeError): # not the main thread - pass + # on its own thread: webbrowser.open waits for the browser launcher, which on Linux can run for as long as + # the browser does, and the main thread must be free to take Ctrl+C and SIGTERM (#1872) + threading.Thread(target=webbrowser.open, daemon=True, name="strata-open-browser", + args=(f"http://{'127.0.0.1' if a.host in ('0.0.0.0', '') else a.host}:{bound_port}/",)).start() if ready_path is not None or event_sink is not None: ready_host = f"[{here}]" if ":" in here and not here.startswith("[") else here record = {"schema_version": 1, "instance_id": svc.instance_id, "pid": os.getpid(), @@ -7816,6 +7837,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in finally: if ready_path is not None: ready_file.remove_if_owned(ready_path, svc.instance_id) + finished.set() if interrupted: print("[strata] stopped", flush=True) exit_code = (8 if not drained else diff --git a/serve/test_lifecycle.py b/serve/test_lifecycle.py index 84847b59..3aaae11f 100644 --- a/serve/test_lifecycle.py +++ b/serve/test_lifecycle.py @@ -74,7 +74,7 @@ class Lifecycle(unittest.TestCase): self.assertEqual(engine.last, {}) if running: proc.terminate.assert_called_once() - proc.wait.assert_called_once_with(timeout=20) + proc.wait.assert_called_once_with(timeout=5) else: proc.terminate.assert_not_called() proc.wait.assert_not_called() diff --git a/serve/test_lifeline.py b/serve/test_lifeline.py new file mode 100644 index 00000000..b85fc659 --- /dev/null +++ b/serve/test_lifeline.py @@ -0,0 +1,138 @@ +"""serve/lifeline.py: a process Strata starts ends when the process that started it ends, however that ends. + + python -m unittest serve.test_lifeline + +Each case runs a small "server" process (a fresh interpreter) that starts a sleeping child through +`lifeline.popen`, then ends that server the hard way (kill -9 / TerminateProcess), and checks that the child +is gone. The mechanism under test is Windows' job object, Linux's PR_SET_PDEATHSIG, or the portable watcher +(forced with STRATA_LIFELINE=watcher so it is proven on every POSIX box, not only on macOS). +""" +import json +import os +import signal +import subprocess +import sys +import tempfile +import textwrap +import time +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +POSIX = os.name == "posix" + +SERVER = textwrap.dedent(""" + import os, sys, time, threading, subprocess + sys.path.insert(0, {root!r}) + from serve import lifeline + mode = sys.argv[1] + sleeper = [sys.executable, "-c", "import time; time.sleep(600)"] + out = {{"mechanism": lifeline.mechanism()}} + if mode == "thread": # started on a request thread that ends at once + box = [] + t = threading.Thread(target=lambda: box.append(lifeline.popen(sleeper, "engine"))) + t.start(); t.join() + child = box[0] + else: + child = lifeline.popen(sleeper, "engine") + out["child"] = child.pid + out["server"] = os.getpid() + print(__import__("json").dumps(out), flush=True) + if mode == "exit": # ends normally, the child still running + sys.exit(0) + time.sleep(600) +""") + + +def alive(pid: int) -> bool: + from strata_control import procs + return procs.start_token(pid) is not None + + +class Lifeline(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="strata-lifeline-") + self.addCleanup(self.temp.cleanup) + self.env = {**os.environ, "LOCALAPPDATA": self.temp.name, "XDG_STATE_HOME": self.temp.name, + "PYTHONPATH": str(ROOT)} + self.script = Path(self.temp.name) / "server.py" + self.script.write_text(SERVER.format(root=str(ROOT)), encoding="utf-8") + self.spawned = [] + self.addCleanup(self._reap) + + def _reap(self): + for pid in self.spawned: + if alive(pid): + try: + os.kill(pid, signal.SIGTERM) + except OSError: + pass + + def launch(self, mode, **env): + proc = subprocess.Popen([sys.executable, str(self.script), mode], stdout=subprocess.PIPE, text=True, + env={**self.env, **env}) + info = json.loads(proc.stdout.readline()) + self.spawned.append(info["child"]) + self.addCleanup(lambda: proc.poll() is None and proc.kill()) + return proc, info + + def wait_gone(self, pid, seconds=15): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if not alive(pid): + return True + time.sleep(0.1) + return not alive(pid) + + def hard_kill(self, proc): + if POSIX: + os.kill(proc.pid, signal.SIGKILL) + else: + proc.kill() + proc.wait(timeout=10) + + def _killed_parent_takes_the_child(self, **env): + proc, info = self.launch("sleep", **env) + self.assertTrue(alive(info["child"])) + self.hard_kill(proc) + self.assertTrue(self.wait_gone(info["child"]), f"the child outlived a killed server ({info['mechanism']})") + return info["mechanism"] + + def test_a_child_ends_when_its_server_is_killed(self): + self.assertIn(self._killed_parent_takes_the_child(), ("job", "pdeathsig", "watcher")) + + @unittest.skipUnless(POSIX, "the portable watcher is the POSIX path") + def test_the_portable_watcher_ends_the_child_when_the_server_is_killed(self): + self.assertEqual(self._killed_parent_takes_the_child(STRATA_LIFELINE="watcher"), "watcher") + + @unittest.skipUnless(sys.platform.startswith("linux"), "PR_SET_PDEATHSIG is Linux") + def test_a_child_started_on_a_request_thread_outlives_that_thread_but_not_the_server(self): + proc, info = self.launch("thread") + self.assertEqual(info["mechanism"], "pdeathsig") + time.sleep(1.0) + self.assertTrue(alive(info["child"]), "the request thread ended and took the child with it") + self.hard_kill(proc) + self.assertTrue(self.wait_gone(info["child"])) + + def test_a_server_that_exits_normally_leaves_nothing_behind(self): + proc, info = self.launch("exit") + proc.wait(timeout=15) + self.assertTrue(self.wait_gone(info["child"]), "end_children at exit must stop what is still running") + + def test_the_child_is_recorded_while_it_runs_and_forgotten_after(self): + from strata_control import procs + proc, info = self.launch("sleep") + base = Path(self.temp.name) / "Strata" / "procs" if not POSIX else Path(self.temp.name) / "strata" / "procs" + record = base / f"{info['child']}.json" + deadline = time.monotonic() + 5 + while not record.exists() and time.monotonic() < deadline: + time.sleep(0.05) + data = json.loads(record.read_text(encoding="utf-8")) + self.assertEqual((data["pid"], data["role"], data["parent"]["pid"]), (info["child"], "engine", info["server"])) + self.assertEqual(data["token"], procs.start_token(info["child"])) + self.hard_kill(proc) + self.assertTrue(self.wait_gone(info["child"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/test_server.py b/serve/test_server.py index 0e566ef5..d3b82ff0 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -5284,7 +5284,7 @@ class VisionArgs(unittest.TestCase): seen.append(args) return Proc() - with mock.patch.object(server.subprocess, "Popen", popen), mock.patch.object(server, "contain"): + with mock.patch.object(server.subprocess, "Popen", popen): server.Vision({"exe": "strata-vision", "mmproj": "m.gguf", "model": "t.gguf", **cfg}) return seen[0] @@ -5400,7 +5400,7 @@ class LazyVision(unittest.TestCase): started.append(p) return p - with mock.patch.object(server, "popen", popen), mock.patch.object(server, "contain"): + with mock.patch.object(server, "popen", popen): v = server.Vision({"exe": "strata-vision", "mmproj": "m.gguf", "model": "t.gguf"}, lazy=True) self.addCleanup(lambda: shutil.rmtree(v.dir, ignore_errors=True)) return v, started, popen @@ -5413,7 +5413,7 @@ class LazyVision(unittest.TestCase): def test_restart_starts_it_and_close_ends_it(self): import serve.server as server v, started, popen = self.make() - with mock.patch.object(server, "popen", popen), mock.patch.object(server, "contain"): + with mock.patch.object(server, "popen", popen): v.restart() self.assertTrue(v.alive()) self.assertEqual(len(started), 1) @@ -5435,7 +5435,7 @@ class LazyVision(unittest.TestCase): return 0 started.append(P) return P() - with mock.patch.object(server, "popen", popen), mock.patch.object(server, "contain"): + with mock.patch.object(server, "popen", popen): with self.assertRaises(RuntimeError): v.restart() self.assertTrue(started[-1].killed) @@ -5643,7 +5643,7 @@ class UntimedReads(unittest.TestCase): v.spawn = (["strata-vision"], None, None) v.dir = Path(tempfile.mkdtemp(prefix="strata-vision-test-")) try: - with mock.patch.object(server, "popen", lambda *a, **k: proc), mock.patch.object(server, "contain"), mock.patch.object(server, "VISION_READY_S", 0.3): + with mock.patch.object(server, "popen", lambda *a, **k: proc), mock.patch.object(server, "VISION_READY_S", 0.3): with self.assertRaises(RuntimeError) as cm: v._start() self.assertIn("did not start", str(cm.exception)) diff --git a/serve/test_vision_busy.py b/serve/test_vision_busy.py index 899a3445..9e719526 100644 --- a/serve/test_vision_busy.py +++ b/serve/test_vision_busy.py @@ -42,7 +42,7 @@ class Busy(unittest.TestCase): v = server.Vision.__new__(server.Vision) v.spawn = (["strata-vision"], None, None) v.dir = Path(tempfile.gettempdir()) - with mock.patch.object(server, "popen", lambda *a, **k: proc), mock.patch.object(server, "contain"): + with mock.patch.object(server, "popen", lambda *a, **k: proc): with self.assertRaises(RuntimeError) as cm: v._start() self.assertIn("Exclusive_Process", str(cm.exception)) diff --git a/strata_cli/cli.py b/strata_cli/cli.py index 550ea823..81476f0c 100644 --- a/strata_cli/cli.py +++ b/strata_cli/cli.py @@ -178,10 +178,18 @@ def parser() -> argparse.ArgumentParser: help="update an existing install (what UPDATE.bat / update.sh run) instead of setting one up") install.add_argument("setup_args", nargs=argparse.REMAINDER, help="options passed to setup.py, e.g. --family qwen --model Q2_0 --yes") - runtime = sp.add_parser("runtime", help="manage an owned local Strata server instance") + runtime = sp.add_parser( + "runtime", help="manage an owned local Strata server instance", + description="`runtime start` starts a background service: the engine keeps serving after this terminal " + "closes and until `runtime stop` (or the process named by --die-with-pid ends). " + "`strata serve` is the foreground form: it ends with this terminal.") runtime_sp = runtime.add_subparsers(dest="runtime_command", required=True) - runtime_start = runtime_sp.add_parser("start", help="start a saved profile under the local owner host") + runtime_start = runtime_sp.add_parser( + "start", help="start a saved profile as a background service under the local owner host (it keeps " + "serving after this terminal closes; stop it with `runtime stop`)") runtime_start.add_argument("--profile", required=True) + runtime_start.add_argument("--die-with-pid", type=int, metavar="PID", + help="stop the instance (drained) when this process ends; for an app that owns it") runtime_start.add_argument("--plan", action="store_true") runtime_start.add_argument("--wait", type=float, default=300) runtime_start.add_argument("--shutdown-timeout", type=float, default=30) @@ -206,6 +214,11 @@ def parser() -> argparse.ArgumentParser: runtime_stop.add_argument("--if-owner-id", help="require the owner ID from --plan") runtime_stop.add_argument("--if-instance-id", help="require the instance ID from --plan") runtime_stop.add_argument("--output", choices=("human", "json"), default="human") + runtime_cleanup = runtime_sp.add_parser( + "cleanup", help="end servers and engines Strata started whose owner is gone (each is checked by PID, " + "start time and command line first; a running instance is never touched)") + runtime_cleanup.add_argument("--profile", help="only this profile's leftovers") + runtime_cleanup.add_argument("--output", choices=("human", "json"), default="human") runtime_restart = runtime_sp.add_parser("restart", help="drain and rerun an owned saved profile") runtime_restart.add_argument("--profile", required=True) runtime_restart.add_argument("--plan", action="store_true", help="compare current and saved launch without draining") @@ -448,7 +461,7 @@ def parser() -> argparse.ArgumentParser: for one_shot in (profile_create, profile_list, profile_show, profile_validate, profile_set, profile_source, profile_edit, profile_history, profile_rollback, doctor, components_verify, models_list, models_inspect, models_import, calibrate, - runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_restart, + runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_cleanup, runtime_restart, *ops_items, bench_run, bench_report, bench_compare, code_sessions): one_shot.add_argument("--json", action="store_true", help="alias for --output json") one_shot.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS, @@ -1020,8 +1033,20 @@ def _bench(a: argparse.Namespace) -> int: def _runtime(a: argparse.Namespace) -> int: from strata_control import management machine = a.output == "json" + if a.runtime_command == "cleanup": + from strata_control import runtime + result = runtime.cleanup(a.profile) + if machine: + print(json.dumps({"schema_version": 1, **result}, ensure_ascii=False, allow_nan=False)) + else: + print(f"ended {len(result['ended'])} leftover process(es)" + + (f"; {len(result['stuck'])} would not end" if result["stuck"] else "") + + (f"; {len(result['unverifiable'])} could not be identified here and were left alone" + if result["unverifiable"] else "")) + return 0 if result["ok"] else result["exit_code"] result = management.runtime_action( a.runtime_command, a.profile, plan=getattr(a, "plan", False), + die_with_pid=getattr(a, "die_with_pid", None), wait=getattr(a, "wait", 300), shutdown_timeout=getattr(a, "shutdown_timeout", 30), startup_wait=getattr(a, "startup_wait", 300), load=getattr(a, "load", False), diff --git a/strata_control/management.py b/strata_control/management.py index 56c6a22d..c1af6252 100644 --- a/strata_control/management.py +++ b/strata_control/management.py @@ -193,7 +193,8 @@ def runtime_action(action: str, profile: str, *, plan: bool = False, if_instance_id: str | None = None, allow_source_switch: bool = False, allow_source_migration: bool = False, - if_source_sha256: str | None = None) -> dict: + if_source_sha256: str | None = None, + die_with_pid: int | None = None) -> dict: """Execute one validated owner operation and return its CLI/host result.""" runtime._name(profile) if type(plan) is not bool: @@ -225,7 +226,8 @@ def runtime_action(action: str, profile: str, *, plan: bool = False, "expected_source_sha256": if_source_sha256}, lambda: runtime.start(profile, wait=wait, shutdown_timeout=shutdown_timeout, expected_profile_revision=if_profile_revision, - expected_source_sha256=if_source_sha256)) + expected_source_sha256=if_source_sha256, + die_with_pid=die_with_pid)) elif action == "status": if plan: raise ProfileError("status has no plan") diff --git a/strata_control/procs.py b/strata_control/procs.py new file mode 100644 index 00000000..8084b8d0 --- /dev/null +++ b/strata_control/procs.py @@ -0,0 +1,370 @@ +"""Which processes Strata started, and how to tell one of them from a stranger. + +Every engine, image encoder and server that Strata starts leaves a small private record: its PID, the time it +started, its command line, and the same two things for the process that started it. When that parent is gone and +the child is still running, the child is a leftover. A leftover is ended only when ALL of these still hold at the +moment of the signal: + +* the process at that PID started at the recorded time (a later process that reused the number does not match); +* its command line is the recorded one (PID reuse plus the same start time is not possible, but this is also what + makes an unrelated program impossible to hit by a corrupted record); +* the recorded parent is not running as that same process. + +A PID that is only a number is never signalled. If the identity of a process cannot be read (no command line on +this platform and no psutil), it is left alone and reported. + +Also here: the one-time check for engines left by earlier Strata versions, which wrote no record: an orphan of +exactly the engine executable that is about to be started, running ``--serve`` with no live parent. +""" + +from __future__ import annotations + +import json +import os +import signal +import subprocess +import sys +import time +from dataclasses import dataclass +from pathlib import Path + +from strata_control import paths + +WINDOWS = os.name == "nt" +SCHEMA = 1 +INIT_NAMES = {"systemd", "init", "launchd", "upstart"} # parents that adopt orphans + +try: # psutil ships in every Strata runtime (requirements.txt, the Control lock files) + import psutil +except ImportError: # pragma: no cover - the Linux /proc fallback below still identifies processes + psutil = None + + +# ---------------------------------------------------------------------------------------------- identity + +def start_token(pid: int) -> str | None: + """A string that is the same for the lifetime of one process and different for a later process with the same + PID. None when there is no such process or its start cannot be read.""" + if type(pid) is not int or pid <= 0: + return None + if sys.platform.startswith("linux"): + try: + raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace") + fields = raw[raw.rindex(")") + 2:].split() + if fields[0] == "Z": # a zombie has exited; only its parent has not collected it + return None + return "l:" + fields[19] # starttime, clock ticks since boot (field 22) + except (OSError, ValueError, IndexError): + return None + if WINDOWS: + from strata_control import winproc + started = winproc.process_started(pid) + return None if started is None else f"w:{started}" + if psutil is not None: + try: + p = psutil.Process(pid) + if p.status() == psutil.STATUS_ZOMBIE: + return None + return f"p:{p.create_time():.3f}" + except (psutil.Error, OSError): + return None + try: + out = subprocess.run(["ps", "-o", "lstart=,stat=", "-p", str(pid)], capture_output=True, text=True, + timeout=5).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + return None if not out or out.endswith("Z") else "s:" + out + + +def command_line(pid: int) -> list[str] | None: + """The process's argv, or None when it cannot be read (then it is never treated as a match).""" + if sys.platform.startswith("linux"): + try: + raw = Path(f"/proc/{pid}/cmdline").read_bytes() + return [part.decode("utf-8", "replace") for part in raw.split(b"\0") if part] or None + except OSError: + return None + if psutil is not None: + try: + return list(psutil.Process(pid).cmdline()) or None + except (psutil.Error, OSError): + return None + if not WINDOWS: + try: + out = subprocess.run(["ps", "-o", "command=", "-p", str(pid)], capture_output=True, text=True, + timeout=5).stdout.strip() + except (OSError, subprocess.SubprocessError): + return None + return out.split() or None + return None + + +def parent_of(pid: int) -> int | None: + if sys.platform.startswith("linux"): + try: + raw = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace") + return int(raw[raw.rindex(")") + 2:].split()[1]) + except (OSError, ValueError, IndexError): + return None + if psutil is not None: + try: + return psutil.Process(pid).ppid() + except (psutil.Error, OSError): + return None + return None + + +def exe_path(pid: int) -> str | None: + if sys.platform.startswith("linux"): + try: + return os.readlink(f"/proc/{pid}/exe") + except OSError: + return None + if psutil is not None: + try: + return psutil.Process(pid).exe() or None + except (psutil.Error, OSError): + return None + return None + + +def same_file(a: str | None, b: str | None) -> bool: + if not a or not b: + return False + try: + return os.path.samefile(a, b) + except OSError: + return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b)) + + +@dataclass(frozen=True) +class Ident: + pid: int + token: str + cmd: tuple[str, ...] + + +def identify(pid: int) -> Ident | None: + """The live process at `pid`, with the facts a record is later compared with.""" + token = start_token(pid) + cmd = command_line(pid) + if token is None or not cmd: + return None + return Ident(pid, token, tuple(cmd)) + + +def is_same(pid: int, token: str, cmd: list[str] | tuple[str, ...] | None) -> bool: + """True only when the process now at `pid` started at `token` and runs exactly `cmd`.""" + if start_token(pid) != token: + return False + now = command_line(pid) + return bool(now) and list(now) == list(cmd or []) + + +# ---------------------------------------------------------------------------------------------- records + +def procs_dir(create: bool = True) -> Path: + """The owner-private folder of launch records (beside runtime/, under the per-user state).""" + base = paths.state_base() / "procs" + if create and not base.exists(): + base.mkdir(parents=True, mode=0o700, exist_ok=True) + if WINDOWS: + from strata_control import private_files + private_files.restrict_to_current_user(base, directory=True) + return base + + +def write_record(pid: int, role: str, *, profile: str | None = None, cmd: list[str] | None = None, + parent_pid: int | None = None) -> str | None: + """Record that this process started `pid`; returns the process's start token (None: nothing was written). + Best effort: a record that cannot be written never stops a launch.""" + try: + token = start_token(pid) + command = list(cmd) if cmd else command_line(pid) + parent_pid = os.getpid() if parent_pid is None else parent_pid + parent_token = start_token(parent_pid) + if token is None or not command or parent_token is None: + return None + record = {"schema": SCHEMA, "pid": pid, "token": token, "cmd": command, "role": role, + "profile": profile, "parent": {"pid": parent_pid, "token": parent_token}, + "written_at": time.time()} + path = procs_dir() / f"{pid}.json" + tmp = path.with_suffix(f".{os.getpid()}.tmp") + tmp.write_text(json.dumps(record), encoding="utf-8") + os.replace(tmp, path) + return token + except (OSError, ValueError): + return None + + +def drop_record(pid: int, token: str | None = None) -> None: + """Delete the record of `pid`; with `token`, only if it is the record of that process (not of a later one).""" + path = procs_dir(create=False) / f"{pid}.json" + try: + if token is not None: + record = _load(path) + if record is None or record["token"] != token: + return + path.unlink(missing_ok=True) + except OSError: + pass + + +def _load(path: Path) -> dict | None: + try: + if path.stat().st_size > 16 * 1024: + return None + record = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + ok = (isinstance(record, dict) and record.get("schema") == SCHEMA and type(record.get("pid")) is int and + isinstance(record.get("token"), str) and isinstance(record.get("cmd"), list) and + all(isinstance(part, str) for part in record["cmd"]) and isinstance(record.get("parent"), dict) and + type(record["parent"].get("pid")) is int and isinstance(record["parent"].get("token"), str)) + return record if ok else None + + +def records(profile: str | None = None) -> list[dict]: + base = procs_dir(create=False) + if not base.is_dir(): + return [] + found = [] + for path in sorted(base.glob("*.json")): + record = _load(path) + if record is None: + continue + if profile is None or record.get("profile") == profile: + found.append(record) + return found + + +# ---------------------------------------------------------------------------------------------- leftovers + +def leftovers(profile: str | None = None, *, forget_stale: bool = True) -> tuple[list[dict], list[dict]]: + """(to_end, unverifiable). `to_end`: recorded processes that still run as exactly what was recorded whose + parent is no longer that process. Records of processes that have gone, or whose PID now belongs to something + else, are deleted (when `forget_stale`); the stranger is not touched. `unverifiable`: still running but their + command line cannot be read here, so they are reported and left alone.""" + to_end, unverifiable = [], [] + for record in records(profile): + pid = record["pid"] + token = start_token(pid) + if token is None or token != record["token"]: + if forget_stale: + drop_record(pid) + continue + parent = record["parent"] + if start_token(parent["pid"]) == parent["token"]: + continue # its starter is still there: not a leftover + if is_same(pid, record["token"], record["cmd"]): + to_end.append(record) + elif command_line(pid) is None: + unverifiable.append(record) + elif forget_stale: + drop_record(pid) # same start time, different command line: not ours + return to_end, unverifiable + + +def _signal_verified(record: dict, sig: int) -> bool: + """Signal the recorded process, but only if it is still the recorded process at this instant.""" + if not is_same(record["pid"], record["token"], record["cmd"]): + return False + try: + os.kill(record["pid"], sig) + except (ProcessLookupError, PermissionError): + return False + return True + + +def end_one(record: dict, *, grace: float = 8.0) -> str: + """End one verified leftover: a polite signal where the OS has one, then a kill after `grace` seconds. + Returns 'gone' (already not running), 'ended' or 'stuck'.""" + pid = record["pid"] + if not is_same(pid, record["token"], record["cmd"]): + drop_record(pid) + return "gone" + if not WINDOWS: + _signal_verified(record, signal.SIGTERM) + deadline = time.monotonic() + grace + while time.monotonic() < deadline and is_same(pid, record["token"], record["cmd"]): + time.sleep(0.1) + if is_same(pid, record["token"], record["cmd"]): + _signal_verified(record, signal.SIGKILL) + else: + if is_same(pid, record["token"], record["cmd"]): + subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True) # one PID, verified just above + deadline = time.monotonic() + 10 + while time.monotonic() < deadline and is_same(pid, record["token"], record["cmd"]): + time.sleep(0.1) + if is_same(pid, record["token"], record["cmd"]): + return "stuck" + drop_record(pid) + return "ended" + + +def end_leftovers(profile: str | None = None, *, grace: float = 8.0, say=None) -> dict: + """End every verified leftover (children first: a record whose parent is itself a leftover goes last).""" + to_end, unverifiable = leftovers(profile) + children_first = sorted(to_end, key=lambda r: r["written_at"], reverse=True) + result = {"ended": [], "gone": [], "stuck": [], "unverifiable": [ + {"pid": r["pid"], "role": r.get("role")} for r in unverifiable]} + for record in children_first: + outcome = end_one(record, grace=grace) + result[outcome].append({"pid": record["pid"], "role": record.get("role"), "profile": record.get("profile")}) + if say is not None and outcome != "gone": + say(f"[strata] leftover {record.get('role', 'process')} {record['pid']} {outcome}") + return result + + +# ---------------------------------------------------------------------------- engines older versions left + +def orphans_of(engine_exe: str) -> list[Ident]: + """Processes that are exactly this engine executable, running ``--serve``, whose parent no longer exists. + + Earlier Strata versions wrote no record. Such an engine is not a service anybody started on purpose: the + server that owned it is gone, and it holds the GPU. Only the executable that is about to be started is + matched, never another installation's, and a process whose parent is alive is never an orphan.""" + if psutil is None or not engine_exe: + return [] + mine = {os.getpid()} + try: + mine.update(q.pid for q in psutil.Process().parents()) + except psutil.Error: + pass + found = [] + for p in psutil.process_iter(["pid", "ppid", "cmdline", "create_time"]): + try: + cmd = p.info.get("cmdline") or [] + if "--serve" not in cmd or p.pid in mine: + continue + if not same_file(p.exe(), engine_exe): + continue + parent = p.info.get("ppid") + if parent in mine: + continue # started by this server (or by one above it: a container's pid 1) + if parent and parent != 1: + try: + q = psutil.Process(parent) + adopted = q.name().lower() in INIT_NAMES # an init that adopts orphans did not start it + if not adopted and q.create_time() <= p.info["create_time"] + 1.0 and q.status() != psutil.STATUS_ZOMBIE: + continue # a live parent started it: not an orphan + except psutil.NoSuchProcess: + pass + ident = identify(p.pid) + if ident is not None: + found.append(ident) + except (psutil.Error, OSError): + continue + return found + + +def end_orphans(engine_exe: str, *, grace: float = 8.0, say=None) -> list[dict]: + """End the orphans of `engine_exe` (see `orphans_of`), re-verified one by one.""" + ended = [] + for ident in orphans_of(engine_exe): + record = {"pid": ident.pid, "token": ident.token, "cmd": list(ident.cmd), "role": "engine", "written_at": 0} + outcome = end_one(record, grace=grace) + ended.append({"pid": ident.pid, "outcome": outcome}) + if say is not None and outcome != "gone": + say(f"[strata] an engine left behind by an earlier run (pid {ident.pid}) {outcome}") + return ended diff --git a/strata_control/runtime.py b/strata_control/runtime.py index d054d652..54aad483 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -37,7 +37,7 @@ try: except ImportError: # Windows has no qualified owner transport yet. fcntl = None -from strata_control import owner_transport, paths, private_files, profiles, readiness, winproc +from strata_control import owner_transport, paths, private_files, procs, profiles, readiness, winproc from serve import launch_identity from strata_control.profiles import ProfileError @@ -392,8 +392,20 @@ def _check_start_candidate(name: str, expected_profile_revision: str | None, def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, expected_profile_revision: str | None = None, - expected_source_sha256: str | None = None) -> dict: + expected_source_sha256: str | None = None, + die_with_pid: int | None = None) -> dict: + """Start the saved profile under a new owner host. + + The owner host is a background service: it is not tied to the terminal or the process that ran this command and + keeps serving after they end. It stops on `runtime stop`, when its server ends, or - only if `die_with_pid` + names a process - when that process is gone (the desktop app uses this for the engines it starts).""" name = _name(name) + die_with = None + if die_with_pid is not None: + token = procs.start_token(die_with_pid) if type(die_with_pid) is int else None + if token is None: + raise ProfileError("the process to follow with --die-with-pid is not running") + die_with = (die_with_pid, token) if not 0 <= wait <= 600 or not 0 <= shutdown_timeout <= 300: raise ProfileError("start wait must be 0..600 and shutdown timeout 0..300 seconds") if expected_profile_revision is not None and (not isinstance(expected_profile_revision, str) or @@ -411,6 +423,7 @@ def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, with profiles._lock(lock_name): if expected_profile_revision is not None or expected_source_sha256 is not None: _check_start_candidate(name, expected_profile_revision, expected_source_sha256) + procs.end_leftovers(profile=name) # a server or engine a lost owner left behind (verified one by one) if _read_state(name) is not None: _recover_stale(name, wait=wait) descriptor = os.open(log_path, flags, 0o600) @@ -422,6 +435,8 @@ def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30, command += ["--expected-profile-revision", expected_profile_revision] if expected_source_sha256 is not None: command += ["--expected-source-sha256", expected_source_sha256] + if die_with is not None: + command += ["--die-with-pid", str(die_with[0]), "--die-with-token", die_with[1]] detach = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW} if WINDOWS else {"start_new_session": True}) proc = subprocess.Popen(command, @@ -474,6 +489,9 @@ def stop(name: str, *, timeout: float = 330, raise ProfileError("expected instance ID must be 32 lowercase hex characters") params = {"expected_owner_id": expected_owner_id, "expected_instance_id": expected_instance_id} + lost = _stop_lost(name) + if lost is not None: + return lost result = _rpc(name, "stop", timeout=timeout, params=params) if not result["ok"]: return result @@ -486,6 +504,50 @@ def stop(name: str, *, timeout: float = 330, return result +def _stop_lost(name: str) -> dict | None: + """`stop` when there is no live owner host: the host was killed or crashed, so nobody can be asked to stop the + server it started. End what it left behind - the recorded server and engine, each re-checked by PID, start time + and command line - and clear the private state. None when an owner is running (the normal stop applies).""" + try: + state = _read_state(name) + except ProfileError: + state = None + if state is not None: + try: + if _host_lease_active(name): + return None + except FileNotFoundError: + state = None + outcome = procs.end_leftovers(profile=name) + recovered = False + if state is not None: + recovered = _recover_stale(name, wait=20) + if state is None and not any(outcome[key] for key in ("ended", "stuck", "unverifiable")): + return None # nothing recorded: the normal "not managed or is stopped" + stuck = bool(outcome["stuck"] or outcome["unverifiable"]) + return {"ok": not stuck, "profile": name, "state": "failed" if stuck else "stopped", "recovered": recovered, + "ended": outcome["ended"], "leftover_unverified": outcome["unverifiable"], + "exit_code": 6 if stuck else 0, + **({"error": "leftover_process_not_ended"} if stuck else {})} + + +def cleanup(profile: str | None = None) -> dict: + """End the servers and engines Strata started whose owner is gone (`strata runtime cleanup`). Owned instances + that are running are not touched, and neither is any process that is not exactly what Strata recorded.""" + if profile is not None: + profile = _name(profile) + outcome = procs.end_leftovers(profile=profile) + if profile is not None: + try: + if _read_state(profile) is not None and not _host_lease_active(profile): + outcome["recovered"] = _recover_stale(profile, wait=20) + except (ProfileError, FileNotFoundError): + pass + stuck = bool(outcome["stuck"] or outcome["unverifiable"]) + return {"ok": not stuck, "state": "cleaned" if not stuck else "failed", **outcome, + "exit_code": 6 if stuck else 0} + + def verify(name: str, *, timeout: float = 300, load: bool = False, expected_owner_id: str | None = None, expected_instance_id: str | None = None) -> dict: @@ -545,8 +607,10 @@ def plan_restart(name: str, *, allow_source_switch: bool = False, class Host: def __init__(self, name: str, shutdown_timeout: float, startup_wait: float = 300, expected_profile_revision: str | None = None, - expected_source_sha256: str | None = None): + expected_source_sha256: str | None = None, + die_with: tuple[int, str] | None = None): self.name = _name(name) + self.die_with = die_with # (pid, start token): stop the server when that process is gone self.shutdown_timeout = shutdown_timeout self.expected_profile_revision = expected_profile_revision self.expected_source_sha256 = expected_source_sha256 @@ -653,6 +717,7 @@ class Host: child_env = os.environ.copy() child_env["STRATA_OWNER_ATTEST_KEY"] = attestation_key.hex() child_env["STRATA_NO_ACQUIRE"] = "1" # a managed server never installs or downloads (acquisition.py) + child_env["STRATA_RUNTIME_PROFILE"] = self.name # the records of its engine say which profile they belong to try: with os.fdopen(descriptor, "ab") as stream: if WINDOWS: @@ -679,6 +744,7 @@ class Host: self.owner_write = self.child.stdin else: self.owner_write_fd = writer + procs.write_record(self.child.pid, "server", profile=self.name) try: self._mark_child("owned", pid=self.child.pid, ready=ready) except BaseException: @@ -1066,6 +1132,9 @@ class Host: except (ProfileError, OSError) as exc: self.last_error = str(exc) if isinstance(exc, ProfileError) else type(exc).__name__ while self.running: + if self.die_with is not None and procs.start_token(self.die_with[0]) != self.die_with[1]: + self.running = False # the process this instance lives for is gone: stop (drained) and leave + break if self.probe_result is not None and "error" in self.probe_result and \ self.child is not None and self.child.poll() is None: self._stop_child() @@ -1137,6 +1206,8 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument("--startup-wait", type=float, default=300) parser.add_argument("--expected-profile-revision") parser.add_argument("--expected-source-sha256") + parser.add_argument("--die-with-pid", type=int) + parser.add_argument("--die-with-token") args = parser.parse_args(argv) if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= 600: parser.error("shutdown timeout must be 0..300") @@ -1145,8 +1216,9 @@ def main(argv: list[str] | None = None) -> int: if args.expected_source_sha256 is not None and not re.fullmatch(r"[0-9a-f]{64}", args.expected_source_sha256): parser.error("expected source digest must be 64 lowercase hex characters") try: + die_with = (args.die_with_pid, args.die_with_token) if args.die_with_pid and args.die_with_token else None return Host(args.host, args.shutdown_timeout, args.startup_wait, - args.expected_profile_revision, args.expected_source_sha256).serve() + args.expected_profile_revision, args.expected_source_sha256, die_with).serve() except (ProfileError, OSError) as exc: print(f"[strata runtime] host failed: {type(exc).__name__}: {exc}", file=sys.stderr) return 6 diff --git a/tests/terminal/lifecycle_matrix.py b/tests/terminal/lifecycle_matrix.py new file mode 100644 index 00000000..747cf7e0 --- /dev/null +++ b/tests/terminal/lifecycle_matrix.py @@ -0,0 +1,652 @@ +"""The close-path matrix: every way a Strata server or app can end, and what must be true afterwards. + +After each case: no process of the tree that was running is left, the port is free, and the runtime's lease can be +taken again (nothing holds it). With a real engine, `--vram` also checks that the GPU's memory came back. + +Run it directly (the pytest wrapper test_lifecycle_matrix.py runs the fake-engine cases on every platform): + + python tests/terminal/lifecycle_matrix.py --scenarios all --report matrix.json + python tests/terminal/lifecycle_matrix.py --engine real --config /data/run.json --vram --scenarios serve-sigterm + +The engine is a small script behind the same manifest-declared entry point a real engine package has, unless +`--engine real` names a run config. It never loads a model. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import signal +import socket +import subprocess +import sys +import tempfile +import time +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) + +import psutil # noqa: E402 + +from strata_control import components, engine_component as ec, procs, profiles, runtime # noqa: E402 + +WINDOWS = os.name == "nt" +LINUX = sys.platform.startswith("linux") + +# Control words (STOP) are taken on a thread of their own, as the real engine does; everything else in order. +FAKE_ENGINE = r''' +import os, sys, threading, time +from pathlib import Path +mark = Path(os.environ["FAKE_ENGINE_MARK"]) +(mark / "engine.pid").write_text(str(os.getpid())) +stop = threading.Event() +inbox = [] +cv = threading.Condition() +def note(name): (mark / name).write_text(str(time.time())) +def reader(): + for raw in sys.stdin: + word = raw.split()[0] if raw.split() else "" + if word == "STOP": + stop.set(); note("stop"); continue + with cv: + inbox.append(raw); cv.notify() + with cv: + inbox.append(None); cv.notify() +threading.Thread(target=reader, daemon=True).start() +print("READY 4096 stop", flush=True) +while True: + with cv: + while not inbox: cv.wait() + line = inbox.pop(0) + if line is None: # the server closed our stdin + note("eof"); sys.exit(0) + word = line.split()[0] if line.split() else "" + if word == "QUIT": + note("quit"); sys.exit(0) + if word in ("GEN", "BGEN"): + slow = int(os.environ.get("FAKE_ENGINE_SLOW_STEPS", "0")) + slot = int(line.split()[1]) if word == "BGEN" else None + steps = slow if (slow and not os.environ.get("FAKE_ENGINE_FAST_FIRST")) else 1 + stop.clear() + note("busy") + for _ in range(steps): + print("T 97", flush=True) + if stop.wait(0.2): + break + print("DONE 1 1 1.0 1.0 length 0 0 0", flush=True) + if slot is not None: print(f"BADM {slot} 0", flush=True) +''' + + +if WINDOWS: # a parent that ignores Ctrl+C hands that to its children; the matrix must start servers that do not + import ctypes + ctypes.windll.kernel32.SetConsoleCtrlHandler(None, False) + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def port_open(port: int) -> bool: + with socket.socket() as s: + s.settimeout(0.5) + return s.connect_ex(("127.0.0.1", port)) == 0 + + +def install_fake_engine(components_dir: Path) -> Path: + folder = components_dir / "engine" / f"0.1.45-{components.host_platform()}-cuda" + folder.mkdir(parents=True) + (folder / "engine_main.py").write_text(FAKE_ENGINE, encoding="utf-8") + if WINDOWS: + entry = "engine.cmd" + (folder / entry).write_bytes(f'@echo off\r\n"{sys.executable}" "%~dp0engine_main.py" %*\r\n'.encode()) + else: + entry = "engine" + (folder / entry).write_text(f'#!/bin/sh\nexec "{sys.executable}" "$(dirname "$0")/engine_main.py" "$@"\n') + (folder / entry).chmod(0o755) + files = [{"path": name, "sha256": hashlib.sha256((folder / name).read_bytes()).hexdigest(), + "bytes": (folder / name).stat().st_size} for name in (entry, "engine_main.py")] + (folder / ec.MANIFEST).write_text(json.dumps({ + "schema_version": 1, "id": "strata-engine", "version": "0.1.45", "platform": components.host_platform(), + "backend": "cuda", "entrypoint": entry, "files": files}), encoding="utf-8") + return folder + + +def vram_used_mib() -> int | None: + try: + out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used", "--format=csv,noheader,nounits"], + capture_output=True, text=True, timeout=20).stdout.split() + return sum(int(v) for v in out) + except (OSError, ValueError, subprocess.SubprocessError): + return None + + +class Rig: + """A throwaway Strata home: state, runtime, profile and (fake or real) engine config.""" + + def __init__(self, root: Path, *, real_config: Path | None = None, slow_steps: int = 0): + self.root = root + self.real = real_config is not None + self.port = free_port() + self.components = root / "components" + self.components.mkdir() + self.mark = root / "mark" + self.mark.mkdir() + self.state = root / "state" + self.state.mkdir() + self.env = {**os.environ, "STRATA_PROFILE_DIR": str(root / "profiles"), "STRATA_RUNTIME_DIR": str(root / "runtime"), + "STRATA_COMPONENTS_DIR": str(self.components), "STRATA_ENGINE_BACKEND": "cuda", + "STRATA_NO_ACQUIRE": "1", "FAKE_ENGINE_MARK": str(self.mark), "LOCALAPPDATA": str(self.state), + "XDG_STATE_HOME": str(self.state), "PYTHONPATH": str(ROOT), "PYTHONUNBUFFERED": "1", + "FAKE_ENGINE_SLOW_STEPS": str(slow_steps)} + self.env.pop("STRATA_API_KEY", None) + for key in ("STRATA_PROFILE_DIR", "STRATA_RUNTIME_DIR", "LOCALAPPDATA", "XDG_STATE_HOME", "STRATA_COMPONENTS_DIR", + "STRATA_NO_ACQUIRE", "STRATA_ENGINE_BACKEND", "FAKE_ENGINE_MARK", "FAKE_ENGINE_SLOW_STEPS"): + os.environ[key] = self.env[key] # this process reads the same folders (profiles, runtime) + if real_config is not None: + cfg = json.loads(real_config.read_text(encoding="utf-8")) + cfg.update({"host": "127.0.0.1", "port": self.port}) + self.config = root / "run.json" + self.config.write_text(json.dumps(cfg), encoding="utf-8") + else: + install_fake_engine(self.components) + from tools.strata_tokenizer import BYTE_TO_UNICODE + tokenizer = root / "tokenizer" + tokenizer.mkdir() + tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + ["ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"] + (tokenizer / "vocab.json").write_text(json.dumps({token: i for i, token in enumerate(tokens)})) + (tokenizer / "merges.txt").write_text("a b") + (tokenizer / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3])) + self.config = root / "run.json" + self.config.write_text(json.dumps({"exe": "component:strata-engine", "backend": "cuda", + "tokenizer": str(tokenizer), "args": [], "cwd": str(root), + "model_name": "fake", "host": "127.0.0.1", "port": self.port}), + encoding="utf-8") + profiles.create("app", str(self.config)) + + # ------------------------------------------------------------------------------------- starting + def serve_argv(self) -> list[str]: + return [sys.executable, str(ROOT / "strata.py"), "serve", "--profile", "app", "--port", str(self.port), + "--host", "127.0.0.1", "--shutdown-timeout", "5"] + + def wait_ready(self, proc=None, seconds=240) -> None: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if proc is not None and proc.poll() is not None: + raise RuntimeError(f"the server exited with {proc.returncode} before it was ready") + if port_open(self.port): + try: + urllib.request.urlopen(f"http://127.0.0.1:{self.port}/health", timeout=3).read() + return + except OSError: + pass + time.sleep(0.25) + raise RuntimeError("the server was not ready in time") + + def tree(self, pid: int) -> list[procs.Ident]: + """The process and everything below it, with the facts that tell them from a later process.""" + found = [] + try: + family = [psutil.Process(pid), *psutil.Process(pid).children(recursive=True)] + except psutil.Error: + return found + for p in family: + token = procs.start_token(p.pid) + if token: + found.append(procs.Ident(p.pid, token, tuple(procs.command_line(p.pid) or []))) + return found + + def engine_idents(self) -> list[procs.Ident]: + """Every live process that is this run's engine (found by its recorded launch, not by a name).""" + return [procs.Ident(r["pid"], r["token"], tuple(r["cmd"])) for r in procs.records() + if r.get("role") in ("engine", "server") and procs.start_token(r["pid"]) == r["token"]] + + # ------------------------------------------------------------------------------------- checking + def survivors(self, idents) -> list[str]: + return [f"{i.pid} {' '.join(i.cmd)[:90]}" for i in idents if procs.start_token(i.pid) == i.token] + + def wait_gone(self, idents, seconds=45) -> list[str]: + deadline = time.monotonic() + seconds + left = self.survivors(idents) + while left and time.monotonic() < deadline: + time.sleep(0.25) + left = self.survivors(idents) + return left + + def lease_free(self) -> bool: + try: + fd = runtime.acquire_activity_lease(shared=False) + except Exception: # noqa: BLE001 + return False + runtime._unlock_file(fd) + os.close(fd) + return True + + def marks(self) -> list[str]: + return sorted(p.name for p in self.mark.iterdir()) + + def clear_marks(self) -> None: + for p in self.mark.iterdir(): + p.unlink() + + +# ------------------------------------------------------------------------------------------- actions + +def spawn_serve(rig: Rig, *, new_console: bool = False, session: bool = True) -> subprocess.Popen: + log = open(rig.root / "serve.log", "ab") + kw: dict = {} + if WINDOWS: + kw["creationflags"] = subprocess.CREATE_NEW_CONSOLE if new_console else subprocess.CREATE_NEW_PROCESS_GROUP + if new_console: + info = subprocess.STARTUPINFO() + info.dwFlags |= subprocess.STARTF_USESHOWWINDOW + info.wShowWindow = 7 # minimized, not activated + kw["startupinfo"] = info + elif session: + kw["start_new_session"] = True # its own process group, like a job in a shell + proc = subprocess.Popen(rig.serve_argv(), cwd=ROOT, env=rig.env, stdin=subprocess.DEVNULL, stdout=log, + stderr=subprocess.STDOUT, **kw) + log.close() + return proc + + +def windows_console_event(pid: int, kind: str) -> None: + """Ctrl+C ('ctrl-c') or the window's close box ('close') on the console `pid` is attached to.""" + code = ( + "import ctypes, sys, time\n" + "k = ctypes.windll.kernel32\n" + "k.FreeConsole()\n" + f"assert k.AttachConsole({pid}), 'AttachConsole failed'\n" + "if sys.argv[1] == 'ctrl-c':\n" + " k.SetConsoleCtrlHandler(None, 1)\n" + " k.GenerateConsoleCtrlEvent(0, 0)\n" + " time.sleep(1.5)\n" + "else:\n" + " hwnd = k.GetConsoleWindow()\n" + " assert hwnd, 'no console window'\n" + " ctypes.windll.user32.PostMessageW(hwnd, 0x0010, 0, 0)\n" + " time.sleep(1.0)\n" + ) + # for "close" the helper is attached to the console that is closing, so the system ends it too: that exit is expected + done = subprocess.run([sys.executable, "-c", code, kind], creationflags=subprocess.DETACHED_PROCESS, timeout=30) + if kind == "ctrl-c" and done.returncode != 0: + raise RuntimeError(f"could not send Ctrl+C (helper exit {done.returncode})") + + +def kill_hard(pid: int) -> None: + if WINDOWS: + subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True) # this one process, not its tree + else: + os.kill(pid, signal.SIGKILL) + + +def pty_close(rig: Rig): + """A terminal: the server runs as the session leader of a pseudo-terminal; closing the master is the window closing.""" + import pty + pid, master = pty.fork() + if pid == 0: + os.chdir(ROOT) + os.execve(sys.executable, rig.serve_argv(), rig.env) + return pid, master + + +# ------------------------------------------------------------------------------------------ scenarios + +class Result(dict): + pass + + +def finish(rig: Rig, name: str, idents, *, expect_graceful: bool | None, note: str = "", vram_before=None, + vram: bool = False, wait: float = 45, stopped_text: str | None = None) -> Result: + left = rig.wait_gone(idents, wait) + problems = [] + if left: + problems.append(f"processes left: {left}") + deadline = time.monotonic() + 10 # a closing process's sockets go a moment after it + while port_open(rig.port) and time.monotonic() < deadline: + time.sleep(0.2) + if port_open(rig.port): + problems.append("port still open") + if not rig.lease_free(): + problems.append("lease still held") + marks = rig.marks() + if expect_graceful is True and not ({"quit", "eof"} & set(marks)): + problems.append(f"engine was not asked to quit (marks {marks})") + if expect_graceful is True and rig.real is False and "quit" not in marks and "eof" not in marks: + problems.append("no graceful stop seen") + if vram and vram_before is not None: + deadline = time.monotonic() + 30 + used = vram_used_mib() + while used is not None and used > vram_before + 300 and time.monotonic() < deadline: + time.sleep(1) + used = vram_used_mib() + if used is not None and used > vram_before + 300: + problems.append(f"VRAM not freed: {used} MiB used, {vram_before} before") + note += f" vram {vram_before}->{used} MiB" + return Result(name=name, ok=not problems, problems=problems, graceful=("quit" in marks or "eof" in marks), + marks=marks, note=note.strip(), stopped=stopped_text) + + +def serve_case(rig: Rig, name: str, action, *, graceful: bool | None, vram: bool = False, + new_console: bool = False, wait: float = 45) -> Result: + rig.clear_marks() + before = vram_used_mib() if vram else None + proc = spawn_serve(rig, new_console=new_console) + try: + rig.wait_ready(proc) + idents = rig.tree(proc.pid) + idents += [i for i in rig.engine_idents() if i.pid not in {x.pid for x in idents}] + if not any("engine" in " ".join(i.cmd) or "--serve" in " ".join(i.cmd) for i in idents): + raise RuntimeError(f"no engine in the tree: {[' '.join(i.cmd)[:60] for i in idents]}") + t0 = time.monotonic() + action(rig, proc) + out = finish(rig, name, idents, expect_graceful=graceful, vram_before=before, vram=vram, wait=wait) + out["seconds"] = round(time.monotonic() - t0, 1) + text = (rig.root / "serve.log").read_text(errors="replace") if (rig.root / "serve.log").exists() else "" + out["stopped"] = "[strata] stopped" in text + return out + finally: + if proc.poll() is None: + proc.kill() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + pass + for i in rig.tree(proc.pid): + if procs.start_token(i.pid) == i.token: + try: + psutil.Process(i.pid).kill() + except psutil.Error: + pass + (rig.root / "serve.log").write_bytes(b"") + + +def sigint_group(rig, proc): # Ctrl+C in a terminal: SIGINT to the whole foreground group + os.killpg(proc.pid, signal.SIGINT) + + +def sigterm(rig, proc): + os.kill(proc.pid, signal.SIGTERM) + + +def sighup(rig, proc): # what ssh dropping the connection does to the shell's job + os.killpg(proc.pid, signal.SIGHUP) + + +def kill9_parent(rig, proc): + kill_hard(proc.pid) + + +def win_ctrl_break(rig, proc): + os.kill(proc.pid, signal.CTRL_BREAK_EVENT) + + +def win_ctrl_c(rig, proc): + windows_console_event(proc.pid, "ctrl-c") + + +def win_console_close(rig, proc): + windows_console_event(proc.pid, "close") + + +def busy_sigterm(rig, proc): + """A request is running when the stop arrives: it must be cancelled, not waited for.""" + import threading + started = threading.Event() + + def ask(): + try: + body = json.dumps({"model": "fake", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 200, + "stream": True}).encode() + req = urllib.request.Request(f"http://127.0.0.1:{rig.port}/v1/chat/completions", data=body, + headers={"content-type": "application/json"}) + started.set() + urllib.request.urlopen(req, timeout=60).read() + except OSError: + pass + threading.Thread(target=ask, daemon=True).start() + started.wait(5) + deadline = time.monotonic() + 10 + while "busy" not in rig.marks() and time.monotonic() < deadline: + time.sleep(0.1) + (sigterm if not WINDOWS else win_ctrl_break)(rig, proc) + + +def pty_close_case(rig: Rig, name: str = "serve-terminal-closed", *, vram: bool = False) -> Result: + rig.clear_marks() + before = vram_used_mib() if vram else None + pid, master = pty_close(rig) + try: + class _P: # just enough of Popen for wait_ready + def poll(self_inner): + done, _ = os.waitpid(pid, os.WNOHANG) + return 0 if done else None + rig.wait_ready(_P()) + idents = rig.tree(pid) + idents += [i for i in rig.engine_idents() if i.pid not in {x.pid for x in idents}] + t0 = time.monotonic() + os.close(master) # the window is closed + out = finish(rig, name, idents, expect_graceful=True, vram_before=before, vram=vram) + out["seconds"] = round(time.monotonic() - t0, 1) + return out + finally: + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + try: + os.waitpid(pid, 0) + except OSError: + pass + + +# --- the detached service (`strata runtime start`) ------------------------------------------------ + +def runtime_start(rig: Rig, die_with: int | None = None) -> dict: + argv = [sys.executable, str(ROOT / "strata.py"), "runtime", "start", "--profile", "app", "--wait", "240", + "--shutdown-timeout", "5", "--output", "json"] + if die_with: + argv += ["--die-with-pid", str(die_with)] + out = subprocess.run(argv, cwd=ROOT, env=rig.env, capture_output=True, text=True, timeout=300) + try: + return json.loads(out.stdout) + except ValueError: + raise RuntimeError(f"runtime start gave {out.returncode}: {out.stdout[-300:]} {out.stderr[-300:]}") from None + + +def runtime_stop(rig: Rig) -> dict: + out = subprocess.run([sys.executable, str(ROOT / "strata.py"), "runtime", "stop", "--profile", "app", "--wait", "60", + "--output", "json"], cwd=ROOT, env=rig.env, capture_output=True, text=True, timeout=120) + try: + return json.loads(out.stdout) + except ValueError: + return {"ok": False, "raw": out.stdout[-300:] + out.stderr[-300:]} + + +def owner_pid(rig: Rig) -> int: + return runtime._read_state("app")["host_pid"] + + +def sleeper_process() -> subprocess.Popen: + return subprocess.Popen([sys.executable, "-c", "import time; time.sleep(600)"], + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + + +def runtime_case(rig: Rig, name: str, what: str, *, vram: bool = False) -> Result: + rig.clear_marks() + before = vram_used_mib() if vram else None + holder = sleeper_process() if what == "die-with" else None + try: + started = runtime_start(rig, die_with=holder.pid if holder else None) + if started.get("state") != "ready": + raise RuntimeError(f"not ready: {started}") + owner = owner_pid(rig) + idents = rig.tree(owner) + t0 = time.monotonic() + graceful = True + note = "" + if what == "stop": + res = runtime_stop(rig) + note = f"stop -> {res.get('state')}" + elif what == "terminal-gone": + # the command that started it is long gone; the service must still be serving + time.sleep(1.5) + note = "still serving: " + str(port_open(rig.port)) + if not port_open(rig.port): + raise RuntimeError("the background service died with its terminal") + res = runtime_stop(rig) + elif what == "owner-killed": + kill_hard(owner) + graceful = None + elif what == "server-killed": + server = next(i for i in idents if "serve.server" in " ".join(i.cmd)) + kill_hard(server.pid) + graceful = None + note = "server killed, owner left alive" + idents = [i for i in idents if "strata_control.runtime" not in " ".join(i.cmd) and "conhost" not in " ".join(i.cmd)] + elif what == "die-with": + holder.kill(); holder.wait(timeout=10) + if what == "server-killed": + # the server and engine are gone; the owner host stays to report the failure until it is told to stop + out = finish(rig, name, idents, expect_graceful=graceful, vram_before=before, vram=vram, note=note, wait=60) + out["problems"] = [p for p in out["problems"] if p != "lease still held"] + res = runtime_stop(rig) + out["stop_after"] = res.get("state") + left = rig.wait_gone(rig.tree(owner) or [], 30) + if left or not rig.lease_free(): + out["problems"].append(f"after runtime stop: {left} lease_free={rig.lease_free()}") + out["ok"] = not out["problems"] + return out + out = finish(rig, name, idents, expect_graceful=graceful, vram_before=before, vram=vram, note=note, wait=60) + out["seconds"] = round(time.monotonic() - t0, 1) + if what == "owner-killed": + res = runtime_stop(rig) # the next stop clears the private state of a lost owner + out["stop_after"] = res.get("state") + if runtime._read_state("app") is not None: + out["problems"].append("state file left after stop"); out["ok"] = False + return out + finally: + if holder and holder.poll() is None: + holder.kill() + try: + if runtime._read_state("app") is not None: + runtime_stop(rig) + except Exception: # noqa: BLE001 + pass + for i in rig.engine_idents(): + try: + psutil.Process(i.pid).kill() + except psutil.Error: + pass + + +def monitor_quit_case(rig: Rig) -> Result: + """The Textual monitor starts no engine: quitting it, or killing it, leaves a service started elsewhere alone and + leaves no process of its own.""" + rig.clear_marks() + started = runtime_start(rig) + if started.get("state") != "ready": + raise RuntimeError(f"not ready: {started}") + owner = owner_pid(rig) + service = rig.tree(owner) + monitor = subprocess.Popen([sys.executable, str(ROOT / "strata.py"), "monitor", "--url", + f"http://127.0.0.1:{rig.port}"], cwd=ROOT, env=rig.env, stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0)) + time.sleep(3) + mine = rig.tree(monitor.pid) + problems = [] + kill_hard(monitor.pid) + monitor.wait(timeout=15) + if rig.survivors(mine): + problems.append("monitor processes left") + if not port_open(rig.port) or rig.survivors(service) != [f"{i.pid} {' '.join(i.cmd)[:90]}" for i in service + if procs.start_token(i.pid) == i.token]: + problems.append("killing the monitor disturbed the service") + runtime_stop(rig) + left = rig.wait_gone(service, 45) + if left: + problems.append(f"service left after stop: {left}") + return Result(name="monitor-killed-leaves-service-alone", ok=not problems, problems=problems, marks=rig.marks(), note="") + + +SCENARIOS = { + # foreground `strata serve` + "serve-ctrl-c": lambda rig, v: serve_case(rig, "serve-ctrl-c", win_ctrl_c if WINDOWS else sigint_group, + graceful=True, vram=v, new_console=WINDOWS), + "serve-sigterm": lambda rig, v: serve_case(rig, "serve-sigterm", sigterm, graceful=True, vram=v), + "serve-sighup": lambda rig, v: serve_case(rig, "serve-sighup", sighup, graceful=True, vram=v), + "serve-ctrl-break": lambda rig, v: serve_case(rig, "serve-ctrl-break", win_ctrl_break, graceful=True, vram=v), + "serve-console-close": lambda rig, v: serve_case(rig, "serve-console-close", win_console_close, graceful=None, + vram=v, new_console=True), + "serve-kill-parent": lambda rig, v: serve_case(rig, "serve-kill-parent", kill9_parent, graceful=None, vram=v), + "serve-busy-stop": lambda rig, v: serve_case(rig, "serve-busy-stop", busy_sigterm, graceful=True, vram=v), + "serve-terminal-closed": lambda rig, v: pty_close_case(rig, vram=v), + # `strata runtime start` (a background service by design) + "runtime-stop": lambda rig, v: runtime_case(rig, "runtime-stop", "stop", vram=v), + "runtime-survives-terminal": lambda rig, v: runtime_case(rig, "runtime-survives-terminal", "terminal-gone", vram=v), + "runtime-owner-killed": lambda rig, v: runtime_case(rig, "runtime-owner-killed", "owner-killed", vram=v), + "runtime-server-killed": lambda rig, v: runtime_case(rig, "runtime-server-killed", "server-killed", vram=v), + "runtime-die-with": lambda rig, v: runtime_case(rig, "runtime-die-with", "die-with", vram=v), + # the TUI + "monitor-killed": lambda rig, v: monitor_quit_case(rig), +} +POSIX_ONLY = {"serve-sigterm", "serve-sighup", "serve-terminal-closed"} +WINDOWS_ONLY = {"serve-ctrl-break", "serve-console-close"} + + +def applicable(name: str) -> bool: + if WINDOWS: + return name not in POSIX_ONLY + return name not in WINDOWS_ONLY + + +def run(names: list[str], *, real_config: Path | None = None, vram: bool = False, slow_steps: int = 600) -> list[Result]: + results = [] + for name in names: + saved = dict(os.environ) # a Rig points this process at its own folders; give them back + with tempfile.TemporaryDirectory(prefix="strata-matrix-") as tmp: + rig = Rig(Path(tmp), real_config=real_config, slow_steps=slow_steps if name == "serve-busy-stop" else 0) + try: + result = SCENARIOS[name](rig, vram) + except Exception as exc: # noqa: BLE001 + result = Result(name=name, ok=False, problems=[f"{type(exc).__name__}: {exc}"], marks=[]) + results.append(result) + print(("PASS " if result["ok"] else "FAIL ") + name, result.get("seconds", ""), result.get("problems") or "", + result.get("note", ""), flush=True) + try: + runtime_stop(rig) + except Exception: # noqa: BLE001 + pass + for ident in rig.engine_idents(): + try: + psutil.Process(ident.pid).kill() + except psutil.Error: + pass + os.environ.clear() + os.environ.update(saved) + return results + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--scenarios", default="all") + ap.add_argument("--config", help="a real engine's run config (then no fake engine is used)") + ap.add_argument("--vram", action="store_true", help="check nvidia-smi memory returns") + ap.add_argument("--report") + a = ap.parse_args(argv) + names = [n for n in SCENARIOS if applicable(n)] if a.scenarios == "all" else a.scenarios.split(",") + results = run(names, real_config=Path(a.config) if a.config else None, vram=a.vram) + if a.report: + Path(a.report).write_text(json.dumps({"platform": sys.platform, "engine": "real" if a.config else "fake", + "results": results}, indent=1), encoding="utf-8") + return 0 if all(r["ok"] for r in results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/terminal/test_lifecycle_matrix.py b/tests/terminal/test_lifecycle_matrix.py new file mode 100644 index 00000000..fdf0fedc --- /dev/null +++ b/tests/terminal/test_lifecycle_matrix.py @@ -0,0 +1,36 @@ +"""Closing always ends the engine: the close-path matrix (tests/terminal/lifecycle_matrix.py) with the fake engine. + +Each case starts `strata serve` or `strata runtime start` with an engine package whose entry point is a script, +ends it one way, and asserts that no process of the tree is left, the port is free and the runtime lease can be taken. +The cases that need a real console window on Windows run when STRATA_MATRIX_CONSOLE=1 (they open a minimised +console); everything else runs everywhere the platform has the mechanism. +""" +import os +import unittest + +from tests.terminal import lifecycle_matrix as matrix + +CONSOLE = {"serve-ctrl-c", "serve-console-close"} + + +@unittest.skipUnless(os.name in ("posix", "nt"), "no qualified owner transport on this platform") +class LifecycleMatrix(unittest.TestCase): + pass + + +def make(name): + def test(self): + if matrix.WINDOWS and name in CONSOLE and not os.environ.get("STRATA_MATRIX_CONSOLE"): + self.skipTest("needs a console window; set STRATA_MATRIX_CONSOLE=1") + result = matrix.run([name])[0] + self.assertTrue(result["ok"], result.get("problems")) + return test + + +for _name in matrix.SCENARIOS: + if matrix.applicable(_name): + setattr(LifecycleMatrix, "test_" + _name.replace("-", "_"), make(_name)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_procs.py b/tests/terminal/test_procs.py new file mode 100644 index 00000000..f5458c09 --- /dev/null +++ b/tests/terminal/test_procs.py @@ -0,0 +1,141 @@ +"""Leftover detection: a process is ended only when it is exactly what Strata recorded and its starter is gone.""" + +import json +import os +import subprocess +import sys +import tempfile +import time +import unittest +from pathlib import Path +from unittest import mock + +from strata_control import procs + +SLEEP = [sys.executable, "-c", "import time; time.sleep(120)"] +NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0) + + +class Procs(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="strata-procs-") + self.addCleanup(self.temp.cleanup) + patcher = mock.patch.dict(os.environ, {"LOCALAPPDATA": self.temp.name, "XDG_STATE_HOME": self.temp.name}) + patcher.start() + self.addCleanup(patcher.stop) + self.started = [] + self.addCleanup(self._kill_all) + + def _kill_all(self): + for proc in self.started: + if proc.poll() is None: + proc.kill() + proc.wait(timeout=10) + + def sleeper(self): + proc = subprocess.Popen(SLEEP, creationflags=NO_WINDOW) + self.started.append(proc) + deadline = time.monotonic() + 10 + while procs.identify(proc.pid) is None and time.monotonic() < deadline: + time.sleep(0.05) + return proc + + def recorded_pair(self): + """(starter, child, record): a recorded child of a starter that is then ended.""" + starter, child = self.sleeper(), self.sleeper() + self.assertIsNotNone(procs.write_record(child.pid, "engine", profile="app-1", parent_pid=starter.pid)) + return starter, child + + def gone(self, proc, seconds=15): + try: + proc.wait(timeout=seconds) + return True + except subprocess.TimeoutExpired: + return False + + def test_a_child_whose_starter_is_gone_is_a_leftover_and_is_ended(self): + starter, child = self.recorded_pair() + self.assertEqual(procs.leftovers()[0], [], "its starter is alive: not a leftover") + starter.kill(); starter.wait(timeout=10) + found, unverifiable = procs.leftovers() + self.assertEqual([r["pid"] for r in found], [child.pid]) + self.assertEqual(unverifiable, []) + result = procs.end_leftovers(grace=2) + self.assertEqual([r["pid"] for r in result["ended"]], [child.pid]) + self.assertTrue(self.gone(child)) + self.assertEqual(procs.records(), [], "the record goes with the process") + + def test_a_child_with_a_live_starter_is_never_touched(self): + starter, child = self.recorded_pair() + result = procs.end_leftovers(grace=1) + self.assertEqual((result["ended"], result["stuck"]), ([], [])) + self.assertIsNone(child.poll()) + + def test_a_reused_pid_is_not_the_recorded_process(self): + starter, child = self.recorded_pair() + path = procs.procs_dir() / f"{child.pid}.json" + record = json.loads(path.read_text(encoding="utf-8")) + record["token"] = "x:not-this-process" # what a later process with the same number looks like + path.write_text(json.dumps(record), encoding="utf-8") + starter.kill(); starter.wait(timeout=10) + result = procs.end_leftovers(grace=1) + self.assertEqual((result["ended"], result["stuck"]), ([], [])) + self.assertIsNone(child.poll(), "a stranger with the recorded PID must be left alone") + self.assertEqual(procs.records(), [], "the stale record is dropped") + + def test_the_same_start_time_with_another_command_line_is_not_ended(self): + starter, child = self.recorded_pair() + path = procs.procs_dir() / f"{child.pid}.json" + record = json.loads(path.read_text(encoding="utf-8")) + record["cmd"] = [sys.executable, "-c", "something else"] + path.write_text(json.dumps(record), encoding="utf-8") + starter.kill(); starter.wait(timeout=10) + result = procs.end_leftovers(grace=1) + self.assertEqual((result["ended"], result["stuck"]), ([], [])) + self.assertIsNone(child.poll()) + + def test_a_profile_filter_only_ends_that_profiles_leftovers(self): + starter, child = self.recorded_pair() + other_starter, other = self.sleeper(), self.sleeper() + procs.write_record(other.pid, "engine", profile="app-2", parent_pid=other_starter.pid) + starter.kill(); other_starter.kill() + starter.wait(timeout=10); other_starter.wait(timeout=10) + result = procs.end_leftovers(profile="app-1", grace=2) + self.assertEqual([r["pid"] for r in result["ended"]], [child.pid]) + self.assertIsNone(other.poll(), "another profile's leftover is not part of this stop") + + def test_garbage_in_the_records_folder_is_ignored(self): + base = procs.procs_dir() + (base / "1.json").write_text("{not json", encoding="utf-8") + (base / "2.json").write_text(json.dumps({"schema": 1, "pid": "no"}), encoding="utf-8") + (base / "3.json").write_text("x" * 40000, encoding="utf-8") + self.assertEqual(procs.records(), []) + self.assertEqual(procs.end_leftovers()["ended"], []) + + def test_an_engine_orphan_of_this_executable_is_found_and_a_live_one_is_not(self): + # an "engine": this interpreter running --serve; its starter is gone after the middle process exits + code = ("import subprocess,sys; p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(120)','--serve']," + "creationflags=%d); print(p.pid, flush=True)" % NO_WINDOW) + middle = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=30) + orphan_pid = int(middle.stdout.split()[0]) + self.addCleanup(lambda: procs.start_token(orphan_pid) and os.kill(orphan_pid, 9)) + deadline = time.monotonic() + 10 + while procs.identify(orphan_pid) is None and time.monotonic() < deadline: + time.sleep(0.05) + live = subprocess.Popen([*SLEEP, "--serve"], creationflags=NO_WINDOW) + self.started.append(live) + deadline = time.monotonic() + 10 + while procs.identify(live.pid) is None and time.monotonic() < deadline: + time.sleep(0.05) + found = [i.pid for i in procs.orphans_of(sys.executable)] + self.assertIn(orphan_pid, found) + self.assertNotIn(live.pid, found, "this test process started it: a live parent") + self.assertEqual(procs.orphans_of(str(Path(sys.executable).with_name("not-the-engine"))), []) + ended = procs.end_orphans(sys.executable, grace=2) + self.assertIn(orphan_pid, [e["pid"] for e in ended]) + self.assertIsNone(live.poll()) + self.assertIsNone(procs.start_token(orphan_pid)) + + +if __name__ == "__main__": + unittest.main()