From 2e0e2d1ff0db3a6df712722030fb7957625797db Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:05:31 -0800 Subject: [PATCH 01/15] test(lifecycle): reproduce inconsistent root admission and ownership --- tests/unit/test_lifecycle.py | 390 +++++++++++++++++++++++++++++++++++ 1 file changed, 390 insertions(+) diff --git a/tests/unit/test_lifecycle.py b/tests/unit/test_lifecycle.py index fcc4236..d6e218d 100644 --- a/tests/unit/test_lifecycle.py +++ b/tests/unit/test_lifecycle.py @@ -7,17 +7,21 @@ import re import secrets import selectors +import signal +import shutil import socket import stat import subprocess import sys import tempfile import threading +import time import unittest from unittest.mock import patch import urllib.request from omp_strata import common, dflash2, fetch, lifecycle, nvfp4, procs +from scripts.requalify import IDLE_STATES from omp_strata.layout import Layout from omp_strata.profile import ENGINE_ENV_GROUPS, Profile, engine_env_union, load from tests.candidate import PROFILE @@ -353,6 +357,392 @@ def test_status_distinguishes_install_and_exit_states(self): details = {"exit_code": code, "log": "logs/server.log"} if expected == "failed" else {} self.assertEqual({"state": expected, **details, **self.idle_gpu_report()}, result) + def dead_identity(self): + proc, identity = self.sleeper() + proc.kill() + proc.wait(timeout=5) + self.assertIsNone(procs.matches(identity.as_dict())) + return identity.as_dict() + + def test_status_never_reports_an_idle_state_while_a_process_of_the_root_lives(self): + proc, identity = self.sleeper() + live, dead = identity.as_dict(), self.dead_identity() + installed = {"profile_fingerprint": self.layout.profile.fingerprint} + # Each record would have reported the idle state named, before status looked at liveness everywhere. + cases = (("not_installed", None, {"state": "ready", "server": live}, "server", "install record missing"), + ("stopped", installed, {"state": "stopped", "wrapper": dead, "server": dead, "engine": None, + "server_tree": [dead, live]}, "server_tree[1]", "server process gone"), + ("failed", installed, {"state": "exited", "exit_code": 1, "wrapper": dead, "server": dead, + "engine": None, "server_tree": [live]}, + "server_tree[0]", "server process gone")) + for idle, install, record, role, problem in cases: + with self.subTest(idle=idle): + self.layout.install_record.unlink(missing_ok=True) + if install is not None: + common.atomic_write_json(self.layout.install_record, install) + common.atomic_write_json(self.layout.run_record, record) + result = lifecycle.status(self.layout) + self.assertEqual(("degraded", [role]), (result["state"], result.get("live"))) + [text] = result["problems"] + self.assertIn(problem, text) + self.assertIn(f"pid {proc.pid}", text) # Names what is alive ... + self.assertIn("run `stop` for this root", text) # ... and what to do. + self.assertIsNone(proc.poll()) + # Without the live process each record reports its idle state again. + proc.kill() + proc.wait(timeout=5) + for idle, install, record, _, _ in cases: + with self.subTest(idle=idle, process="dead"): + self.layout.install_record.unlink(missing_ok=True) + if install is not None: + common.atomic_write_json(self.layout.install_record, install) + common.atomic_write_json(self.layout.run_record, record) + self.assertEqual(idle, lifecycle.status(self.layout)["state"]) + + def test_status_reports_an_unpublished_child_as_not_idle(self): + dead = self.dead_identity() + for install in (None, {"profile_fingerprint": self.layout.profile.fingerprint}): + with self.subTest(installed=install is not None): + self.layout.install_record.unlink(missing_ok=True) + if install is not None: + common.atomic_write_json(self.layout.install_record, install) + common.atomic_write_json(self.layout.run_record, + {"state": "starting", "wrapper": dead, "unpublished_child": True}) + result = lifecycle.status(self.layout) + self.assertEqual("degraded", result["state"]) + self.assertIn("lifetime is unknown", result["problems"][0]) + with self.assertRaisesRegex(lifecycle.LifecycleError, "unpublished child"): + lifecycle.stop(self.layout, log=self.messages.append) # Reconciliation stays manual. + + def test_stop_ends_the_live_process_of_each_not_idle_case_and_start_follows(self): + installed = {"profile_fingerprint": self.layout.profile.fingerprint} + + def start(): + # The port check comes right after start's liveness check: reaching it means start admitted the root. + with patch.object(lifecycle, "verify_install_fast", return_value={}), \ + patch.object(lifecycle.dflash2, "is_pinned", return_value=False), \ + patch.object(lifecycle, "read_key", return_value=secrets.token_urlsafe(32)), \ + patch.object(lifecycle, "port_in_use", + side_effect=lifecycle.LifecycleError("fixture: liveness check passed")): + lifecycle.start(self.layout, tool_argv=[sys.executable], log=self.messages.append) + + for idle in ("not_installed", "stopped", "failed"): + with self.subTest(idle=idle): + proc, identity = self.sleeper() + reaper = threading.Thread(target=proc.wait, daemon=True) # A real wrapper reaps its child. + reaper.start() + dead = self.dead_identity() + self.layout.install_record.unlink(missing_ok=True) + if idle == "not_installed": + record = {"state": "ready", "server": identity.as_dict()} + else: + common.atomic_write_json(self.layout.install_record, installed) + record = {"state": "stopped" if idle == "stopped" else "exited", "exit_code": 1, + "wrapper": dead, "server": dead, "server_tree": [identity.as_dict()]} + if idle == "stopped": + record.pop("exit_code") + common.atomic_write_json(self.layout.run_record, record) + self.assertEqual("degraded", lifecycle.status(self.layout)["state"]) + if idle != "not_installed": + with self.assertRaisesRegex(lifecycle.LifecycleError, r"already running \(server_tree\[0\]\)"): + start() + result = lifecycle.stop(self.layout, log=self.messages.append) # The operator's way out. + reaper.join(timeout=5) + self.assertFalse(reaper.is_alive()) + self.assertEqual(("stopped", 1), (result["state"], len(result["stopped"]))) + self.assertEqual("not_installed" if idle == "not_installed" else "stopped", + lifecycle.status(self.layout)["state"]) + if idle != "not_installed": # A root without an install record needs `install` before `start`. + with self.assertRaisesRegex(lifecycle.LifecycleError, "liveness check passed"): + start() + + def test_status_and_stop_act_on_one_set_of_live_processes(self): + processes = [self.sleeper() for _ in range(5)] + wrapper, server, engine, tree0, tree1 = (identity.as_dict() for _, identity in processes) + pids = {"wrapper": wrapper["pid"], "server": server["pid"], "engine": engine["pid"], + "server_tree[0]": tree0["pid"], "server_tree[1]": tree1["pid"]} + record = {"state": "ready", "wrapper": wrapper, "server": server, "engine": engine, + "server_tree": [tree0, tree1]} + common.atomic_write_json(self.layout.install_record, {"profile_fingerprint": self.layout.profile.fingerprint}) + for gone in (None, "server"): + with self.subTest(gone=gone): + current = dict(record, **({gone: self.dead_identity()} if gone else {})) + common.atomic_write_json(self.layout.run_record, current) + expected = {role: pid for role, pid in pids.items() if role != gone} + live = lifecycle.running(self.layout) + self.assertEqual(expected, {role: info.pid for role, info in live.items()}) + if gone == "server": # status names the same set without contacting a server. + self.assertEqual(sorted(expected), lifecycle.status(self.layout)["live"]) + terminated = [] + with patch.object(lifecycle.procs, "descendants", return_value=[]), \ + patch.object(lifecycle.procs, "terminate", + side_effect=lambda proc, _timeout: terminated.append(proc.pid) or True): + lifecycle.stop(self.layout, log=self.messages.append) + self.assertEqual(sorted(expected.values()), sorted(terminated)) + self.assertTrue(all(proc.poll() is None for proc, _ in processes)) + + # A detached serve wrapper as `start` dispatches it, with a stub server: the real `serve` path, run late. + LATE_WRAPPER = ( + "import os, sys\n" + "from pathlib import Path\n" + "from omp_strata import lifecycle\n" + "from omp_strata.layout import Layout\n" + "from omp_strata.profile import load\n" + "profile, root, log, launch_id = sys.argv[1:5]\n" + "lifecycle.read_key = lambda layout: 'x' * 32\n" + "lifecycle.server_argv = lambda layout: [sys.executable, '-c', 'import time; time.sleep(60)']\n" + "lifecycle.server_env = lambda layout, key: dict(os.environ)\n" + "sys.exit(lifecycle.serve(Layout(Path(root), load(Path(profile))), log_path=Path(log), launch_id=launch_id))\n") + + def run_late_wrapper(self, launch_id): + """Run the dispatched wrapper now; True when it was admitted and published a server for `launch_id`.""" + self.layout.strata.mkdir(parents=True, exist_ok=True) + def end_server(): # Registered first so that it runs after the wrapper is ended: whatever it published. + server = common.read_json(self.layout.run_record).get("server") + # By creation time: a framework Python re-executes itself after the identity is taken, changing its exe. + live = procs.info(server["pid"]) if server else None + if live is not None and live.created == server["created"]: + os.killpg(server["pid"], signal.SIGKILL) + self.addCleanup(end_server) + wrapper = self.spawn(self.LATE_WRAPPER, self.layout.profile.path, self.layout.root, + self.directory / "late.log", launch_id) + deadline = time.monotonic() + 20 + while time.monotonic() < deadline: + record = common.read_json(self.layout.run_record) + # The wrapper publishes itself (`starting`) before its server; wait for the server or its refusal. + if record.get("server") or record.get("state") not in ("launching", "starting") \ + or wrapper.poll() is not None: + break + time.sleep(0.1) + record = common.read_json(self.layout.run_record) + return bool(record.get("server")) and record.get("launch_id") == launch_id + + def test_a_launch_pending_after_its_start_died_is_not_reported_idle(self): + """`start` records `launching`, dispatches the detached wrapper and is killed before the wrapper publishes + anything. That wrapper is still entitled to start a server in the root, so no reader may call it idle.""" + class Killed(BaseException): # start cleans up after Exception and KeyboardInterrupt; a kill runs nothing + pass + identity = {"profile_fingerprint": self.layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64} + common.atomic_write_json(self.layout.install_record, identity) + with patch.object(lifecycle, "verify_install_fast", return_value=identity), \ + patch.object(lifecycle, "read_key", return_value="x" * 32), \ + patch.object(lifecycle.procs, "memory", return_value={"available": 1 << 40}), \ + patch.object(lifecycle, "_engine_log_path", return_value=self.layout.root.resolve() / "engine.log"), \ + patch.object(lifecycle, "_launch_detached", side_effect=Killed): + with self.assertRaises(Killed): + lifecycle.start(self.layout, tool_argv=[sys.executable], log=self.messages.append) + pending = common.read_json(self.layout.run_record) + self.assertEqual("launching", pending["state"]) + reported = lifecycle.status(self.layout)["state"] + admitted = self.run_late_wrapper(pending["launch_id"]) + self.assertFalse(reported in IDLE_STATES and admitted, + f"status reported {reported!r}; the pending launch's wrapper then started a server") + + def test_status_never_reports_idle_a_root_whose_record_start_and_idle_generation_refuse(self): + common.atomic_write_json(self.layout.install_record, {"profile_fingerprint": self.layout.profile.fingerprint}) + base = {"profile_fingerprint": self.layout.profile.fingerprint, "launch_id": "earlier"} + records = {"launching": dict(base, state="launching"), + "job generation exited": dict(base, state="exited", exit_code=0, tree_token="t"), + "job generation ready, nothing recorded alive": dict(base, state="ready", tree_token="t"), + "job generation stop incomplete": dict(base, state="stop_incomplete", tree_token="t")} + for name, record in records.items(): + with self.subTest(record=name): + common.atomic_write_json(self.layout.run_record, record) + with self.assertRaisesRegex(lifecycle.LifecycleError, "pending launch|unpublished child"): + lifecycle.start(self.layout, tool_argv=[sys.executable], log=self.messages.append) + with self.assertRaisesRegex(lifecycle.LifecycleError, "unproved"): + lifecycle.idle_generation(self.layout) + self.assertNotIn(lifecycle.status(self.layout)["state"], IDLE_STATES) + + def test_status_reports_a_launch_whose_wrapper_published_before_its_child_as_starting(self): + """Between the wrapper's own publication and its child's, the launch is in progress: `stop` refuses it (and in + a real launch the wrapper holds the root lock), so status must not call the server gone and advise `stop`.""" + _, wrapper = self.sleeper() + identity = {"profile_fingerprint": self.layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64} + common.atomic_write_json(self.layout.install_record, identity) + common.atomic_write_json(self.layout.run_record, dict(identity, state="starting", launch_id="in-progress", + wrapper=wrapper.as_dict(), unpublished_child=True)) + with self.assertRaisesRegex(lifecycle.LifecycleError, "unpublished child"): + lifecycle.stop(self.layout, log=self.messages.append) + common.atomic_write_json(self.layout.run_record, dict(identity, state="starting", launch_id="in-progress", + wrapper=wrapper.as_dict(), unpublished_child=True)) + reported = lifecycle.status(self.layout) + self.assertEqual("starting", reported["state"], reported) + + def runtime_engine(self): + """A stand-in engine where engines run: inside the root's runtime (every published engine identity is + `\\runtime\\strata\\engine\\strata.exe`). It is a copy of the running interpreter image (a copied + system binary is not runnable on macOS, and a framework launcher would re-execute from its own path).""" + path = self.layout.strata / "engine" / "strata" + if not path.exists(): + path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(procs.info(os.getpid()).exe, path) + return path + + # A stub stock server: it starts the engine and, on each input line, restarts it as stock Strata does on the + # request after an engine death. + STUB_SERVER = ( + "import subprocess, sys\n" + "def engine():\n" + " return subprocess.Popen([sys.argv[1], '-c', 'import time; time.sleep(120)'])\n" + "current = engine()\n" + "print(current.pid, flush=True)\n" + "for _ in sys.stdin:\n" + " current.kill(); current.wait(); current = engine()\n" + " print(current.pid, flush=True)\n") + + def test_an_unrecorded_engine_that_outlives_its_server_keeps_the_root_from_idle(self): + """The run record names the engine generation seen at readiness only. An engine the server started before + readiness, or restarted after it, can outlive a killed server and wrapper (on POSIX nothing ends a detached + session's members when its leader dies); status must not call that root idle, and stop must end it.""" + common.atomic_write_json(self.layout.install_record, {"profile_fingerprint": self.layout.profile.fingerprint}) + for moment in ("restarted after readiness", "started before readiness"): + with self.subTest(moment=moment): + wrapper_proc, wrapper = self.sleeper() + server_proc = self.spawn(self.STUB_SERVER, self.runtime_engine()) + server = procs.info(server_proc.pid) + first = procs.info(int(self.line(server_proc))) + record = {"profile_fingerprint": self.layout.profile.fingerprint, "launch_id": moment, + "wrapper": wrapper.as_dict(), "server": server.as_dict()} + if moment == "restarted after readiness": + record.update(state="ready", engine=first.as_dict(), server_tree=[first.as_dict()]) + server_proc.stdin.write("restart\n") + server_proc.stdin.flush() + survivor = procs.info(int(self.line(server_proc))) + else: # The server died during startup; its wrapper recorded the exit before dying too. + record.update(state="exited", exit_code=-9) + survivor = first + self.addCleanup(lambda p=survivor: procs.matches(p.as_dict()) and os.kill(p.pid, signal.SIGKILL)) + common.atomic_write_json(self.layout.run_record, record) + for proc in (server_proc, wrapper_proc): + proc.kill() + proc.wait(timeout=5) + self.assertIsNotNone(procs.matches(survivor.as_dict())) + reported = lifecycle.status(self.layout)["state"] + lifecycle.stop(self.layout, log=self.messages.append) + outlived_stop = procs.matches(survivor.as_dict()) is not None + self.assertEqual((False, False), (reported in IDLE_STATES, outlived_stop), + f"status {reported!r} with an unrecorded engine alive; stop left it running") + + # A stand-in for the base interpreter behind the venv redirector: a server-tree member that starts the engine + # and, like the stock server, reaps it when it ends. + STUB_MEMBER = ( + "import subprocess, sys, threading, time\n" + "engine = subprocess.Popen([sys.argv[1], '-c', 'import time; time.sleep(120)']) if sys.argv[1:] else None\n" + "if engine:\n" + " threading.Thread(target=engine.wait, daemon=True).start()\n" + "print(engine.pid if engine else 0, flush=True)\n" + "time.sleep(120)\n") + + def test_stop_ends_a_surviving_tree_member_and_the_engine_running_under_it(self): + """The Windows shape: the recorded server (the venv redirector) and the wrapper are gone, the base + interpreter recorded in the server tree survives, and an engine it restarted runs under it, named nowhere. + Status counts both and is not idle; stop ends both; afterwards the root is idle. Without an engine the + surviving member alone keeps the root from idle and stop ends it.""" + common.atomic_write_json(self.layout.install_record, {"profile_fingerprint": self.layout.profile.fingerprint}) + for with_engine in (True, False): + with self.subTest(with_engine=with_engine): + member_proc = self.spawn(self.STUB_MEMBER, *([self.runtime_engine()] if with_engine else [])) + engine_pid = int(self.line(member_proc)) + member = procs.info(member_proc.pid) + threading.Thread(target=member_proc.wait, daemon=True).start() # Its real parent reaps it. + engine = procs.info(engine_pid) if with_engine else None + if engine is not None: + self.addCleanup(lambda p=engine: procs.matches(p.as_dict()) and os.kill(p.pid, signal.SIGKILL)) + common.atomic_write_json(self.layout.run_record, { + "state": "ready", "profile_fingerprint": self.layout.profile.fingerprint, + "wrapper": self.dead_identity(), "server": self.dead_identity(), "engine": self.dead_identity(), + "server_tree": [member.as_dict()]}) + before = lifecycle.status(self.layout) + counted = [role for role in before.get("live", []) if engine is not None and str(engine.pid) in role] + lifecycle.stop(self.layout, log=self.messages.append) + after = lifecycle.status(self.layout)["state"] + self.assertEqual( + (False, True, False, False, "stopped"), + (before["state"] in IDLE_STATES, "server_tree[0]" in before.get("live", []), + procs.matches(member.as_dict()) is not None, + engine is not None and procs.matches(engine.as_dict()) is not None, after)) + self.assertEqual(with_engine, bool(counted), before) + + def test_status_is_not_idle_and_stop_does_not_finish_while_the_process_table_cannot_be_read(self): + """A process-table read that fails is not an empty table: a recorded server still runs.""" + proc, server = self.sleeper() + identity = {"profile_fingerprint": self.layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64} + common.atomic_write_json(self.layout.install_record, identity) + common.atomic_write_json(self.layout.run_record, dict(identity, state="ready", server=server.as_dict())) + real_run = subprocess.run + def no_ps(argv, *args, **kwargs): + if argv and argv[0] == "ps": + raise subprocess.TimeoutExpired(argv, 10) + return real_run(argv, *args, **kwargs) + with patch.object(procs.subprocess, "run", side_effect=no_ps): + reported = lifecycle.status(self.layout)["state"] + try: + lifecycle.stop(self.layout, log=self.messages.append) + finished = True + except lifecycle.LifecycleError: + finished = False + self.assertEqual((False, False, None, False), + (reported in IDLE_STATES, finished, proc.poll(), + common.read_json(self.layout.run_record)["state"] == "stopped")) + + def test_a_port_held_by_a_process_the_root_does_not_record_keeps_it_from_idle(self): + common.atomic_write_json(self.layout.install_record, {"profile_fingerprint": self.layout.profile.fingerprint}) + server = self.layout.profile.data["server"] + with socket.socket() as listener: + listener.bind((server["listen_host"], server["port"])) + listener.listen() + reported = lifecycle.status(self.layout) + with patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "a" * 64}), \ + patch.object(lifecycle, "read_key", return_value="x" * 32), \ + self.assertRaisesRegex(lifecycle.LifecycleError, str(server["port"])): + lifecycle.start(self.layout, tool_argv=[sys.executable], log=self.messages.append) + self.assertNotIn(reported["state"], IDLE_STATES, reported) + + def test_install_refuses_a_root_that_is_not_quiescent(self): + from omp_strata import cli + _, server = self.sleeper() + identity = {"profile_fingerprint": self.layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64} + common.atomic_write_json(self.layout.install_record, identity) + common.atomic_write_json(self.layout.run_record, dict(identity, state="ready", server=server.as_dict())) + args = cli.build_parser().parse_args(["install", "--profile", str(self.layout.profile.path), + "--root", str(self.layout.root)]) + with patch.object(cli.install_mod, "install", side_effect=AssertionError("installed over a live runtime")), \ + patch.object(cli.nvfp4, "staging_preflight"): + with self.assertRaisesRegex(lifecycle.LifecycleError, "stop"): + cli.cmd_install(args) + + def test_a_late_wrapper_refuses_a_launching_record_that_is_not_its_own(self): + """A launch's record is its own by `launch_id`, a random token `start` writes into `launching` and hands its + wrapper on the command line. Start A dispatches and dies; stop fences; start B records its own launch; A's + wrapper then takes the lock and must refuse B's record. Without the stop, B refuses A's pending launch.""" + class Killed(BaseException): + pass + identity = {"profile_fingerprint": self.layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64} + common.atomic_write_json(self.layout.install_record, identity) + engine_log = self.layout.root.resolve() / "engine.log" + def killed_start(): + with patch.object(lifecycle, "verify_install_fast", return_value=identity), \ + patch.object(lifecycle, "read_key", return_value="x" * 32), \ + patch.object(lifecycle.procs, "memory", return_value={"available": 1 << 40}), \ + patch.object(lifecycle, "_engine_log_path", return_value=engine_log), \ + patch.object(lifecycle, "_launch_detached", side_effect=Killed): + with self.assertRaises(Killed): + lifecycle.start(self.layout, tool_argv=[sys.executable], log=self.messages.append) + return common.read_json(self.layout.run_record)["launch_id"] + first = killed_start() + with patch.object(lifecycle, "verify_install_fast", return_value=identity), \ + self.assertRaisesRegex(lifecycle.LifecycleError, "pending launch"): + lifecycle.start(self.layout, tool_argv=[sys.executable], log=self.messages.append) + self.assertEqual(first, common.read_json(self.layout.run_record)["launch_id"]) + lifecycle.stop(self.layout, log=self.messages.append) + second = killed_start() + before = self.layout.run_record.read_bytes() + self.assertFalse(self.run_late_wrapper(first)) + self.assertEqual((second, "launching"), (common.read_json(self.layout.run_record)["launch_id"], + common.read_json(self.layout.run_record)["state"])) + self.assertEqual(before, self.layout.run_record.read_bytes()) + def test_fetch_checks_remaining_space_before_any_download(self): items = fetch.plan(self.layout, platform="linux-x64") total = sum(item.bytes for item in items) From aef71faff05c5948dfe98c1151437ba7d0800bf9 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:07:45 -0800 Subject: [PATCH 02/15] test(lifecycle): make historical admission vocabulary self-contained --- tests/unit/test_lifecycle.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/test_lifecycle.py b/tests/unit/test_lifecycle.py index d6e218d..a2f0ce0 100644 --- a/tests/unit/test_lifecycle.py +++ b/tests/unit/test_lifecycle.py @@ -21,7 +21,6 @@ import urllib.request from omp_strata import common, dflash2, fetch, lifecycle, nvfp4, procs -from scripts.requalify import IDLE_STATES from omp_strata.layout import Layout from omp_strata.profile import ENGINE_ENV_GROUPS, Profile, engine_env_union, load from tests.candidate import PROFILE @@ -29,6 +28,7 @@ from tests.unit.test_profile import multi_gpu_data, single_gpu_data REPO = Path(__file__).resolve().parents[2] +IDLE_STATES = ("not_installed", "stopped", "failed") def gpu_fact(profile, index, processes=(), used=0): From 0185ca96f014a807b97db5e8e05dcfcc70f6c43c Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:08:37 -0800 Subject: [PATCH 03/15] fix(lifecycle): share one root verdict and process census --- omp_strata/cli.py | 4 + omp_strata/lifecycle.py | 350 ++++++++++++++----- omp_strata/procs.py | 96 +++++- tests/unit/test_experiment_loop.py | 26 +- tests/unit/test_lifecycle.py | 21 +- tests/unit/test_lifecycle_states.py | 513 ++++++++++++++++++++++++++++ 6 files changed, 894 insertions(+), 116 deletions(-) create mode 100644 tests/unit/test_lifecycle_states.py diff --git a/omp_strata/cli.py b/omp_strata/cli.py index 31d5185..ca0a75a 100644 --- a/omp_strata/cli.py +++ b/omp_strata/cli.py @@ -104,6 +104,10 @@ def cmd_install(args: argparse.Namespace) -> int: with lifecycle.FileLock(layout.lock_file): if getattr(args, "idle_generation", None) is not None: lifecycle.idle_generation(layout, expected=args.idle_generation) + root = lifecycle.verdict(layout) + if not root.quiescent: + raise lifecycle.LifecycleError(f"install refused: the root is {root.state} (" + + "; ".join(root.problems) + "); run `stop` for this root first") record = install_mod.install(layout, log=eprint) _print({k: record[k] for k in ("profile_id", "runtime_identity_sha256", "strata_commit", "mtp_tensor_manifest_sha256", "python")}) diff --git a/omp_strata/lifecycle.py b/omp_strata/lifecycle.py index 94c0f39..3aaa341 100644 --- a/omp_strata/lifecycle.py +++ b/omp_strata/lifecycle.py @@ -29,6 +29,7 @@ import time import urllib.error import urllib.request +from dataclasses import dataclass, field from pathlib import Path from typing import Callable from xml.etree import ElementTree @@ -1280,29 +1281,206 @@ def _ps_quote(s: str) -> str: return "'" + s.replace("'", "''") + "'" -# ------------------------------------------------------------------------------------------------ start -def running(layout: Layout) -> dict[str, procs.ProcInfo]: - rec = read_json(layout.run_record) if layout.run_record.exists() else {} - live = {} - for role in ("wrapper", "server", "engine"): - p = procs.matches(rec.get(role)) - if p is not None: - live[role] = p - return live +# ------------------------------------------------------------------------------------------------ verdict +# The one decision of what a root is: the closed table in docs/OPERATIONS.md ("Lifecycle states"). `status` renders +# it, `start` admits only an idle root, `stop` ends exactly its `live` set, `install` and `idle_generation` require it +# quiescent, and the qualification launcher admits only a state in IDLE_STATES. Nothing else decides idleness. +IDLE_STATES = ("not_installed", "stopped", "failed") +ROWS = ("unreadable-record", "unreadable-table", "custody-unknown", "launch-pending", "launch-abandoned", + "wrapper-publishing", "mismatched", "server-live", "orphans", "job-unproved", "port-held", "idle") +CUSTODY_REFUSAL = "unpublished child lifetime is unknown; retain custody for reconciliation" +PENDING_REFUSAL = "pending launch already owns this root; use stop before replacement" + + +@dataclass +class Verdict: + row: str + state: str + problems: list[str] = field(default_factory=list) + # Every process of the root found alive, recorded or not: exactly what `stop` ends. + live: dict[str, procs.ProcInfo] = field(default_factory=dict) + # No process of the root alive, no launch pending, custody known: what `install` and `idle_generation` require. + quiescent: bool = False + refusal: str | None = None # why `start` must not act; None exactly when the root is idle + details: dict = field(default_factory=dict) + run: dict = field(default_factory=dict) + # pid -> the recorded role whose current tree it was found in (server first, then wrapper, then the rest). + under: dict[int, str] = field(default_factory=dict) + + @property + def idle(self) -> bool: + return self.state in IDLE_STATES + + +def process_table() -> dict[int, procs.ProcInfo]: + """The one process-table read a verdict rests on.""" + return procs.table() + + +def recorded_processes(run: dict) -> list[tuple[str, dict | None]]: + """Every process a run record names for its root: the wrapper, server and engine, and each server-tree member + recorded at readiness (on Windows the real interpreter behind the venv redirector, and the engine).""" + return [(role, run.get(role)) for role in ("wrapper", "server", "engine")] + [ + (f"server_tree[{index}]", identity) for index, identity in enumerate(run.get("server_tree") or [])] + + +def runs_from(exe: str, base: Path) -> bool: + """True when the executable lies inside `base`, compared as recorded and as resolved (case-blind on Windows).""" + if not exe: + return False + prefixes = {os.path.normcase(os.path.join(path, "")) for path in (str(base), os.path.realpath(base))} + return any(os.path.normcase(path).startswith(prefix) + for path in (exe, os.path.realpath(exe)) for prefix in prefixes) + + +def _alive(identity: dict | None, table: dict[int, procs.ProcInfo]) -> procs.ProcInfo | None: + proc = table.get(int(identity["pid"])) if identity else None + return proc if proc is not None and procs.same_identity(proc, identity) else None + + +def _descendants(table: dict[int, procs.ProcInfo], + live: dict[str, procs.ProcInfo]) -> tuple[dict[str, procs.ProcInfo], dict[int, str]]: + """The current descendants of the live recorded processes, deepest first, read from the same table, and for each + process reached the role whose tree it lies in (the server's tree first, then the wrapper's, then the rest).""" + children: dict[int, list[procs.ProcInfo]] = {} + for proc in table.values(): + children.setdefault(proc.ppid, []).append(proc) + recorded = {proc.pid for proc in live.values()} + order: list[procs.ProcInfo] = [] + under: dict[int, str] = {} + for role in sorted(live, key=lambda role: {"server": 0, "wrapper": 1}.get(role, 2)): + if live[role].pid in under: + continue + frontier = [live[role]] + while frontier: + parent = frontier.pop(0) + for child in children.get(parent.pid, []): + # Windows keeps a dead parent's PID in its children's records, and PIDs are reused. + if child.pid in under or procs.WINDOWS and int(child.created) < int(parent.created): + continue + under[child.pid] = role + frontier.append(child) + if child.pid not in recorded: + order.append(child) + return {f"descendant[{proc.pid}]": proc for proc in reversed(order)}, under + + +def _unrecorded(layout: Layout, table: dict[int, procs.ProcInfo], known: dict) -> dict[str, procs.ProcInfo]: + """Processes of the root its record does not name: whatever executes a file inside the root's runtime + (`runtime/strata`: the engine, the DSV41 engine, the llama.cpp tools, the venv interpreter). A process running + from elsewhere is not counted; that is the declared residual.""" + pids = {proc.pid for proc in known.values()} | {os.getpid()} + return {f"unrecorded[{proc.pid}]": proc for proc in table.values() + if proc.pid not in pids and runs_from(proc.exe, layout.strata)} + + +def _verifiable(run: dict) -> dict[str, procs.ProcInfo]: + """Recorded processes alive, each checked on its own: what `stop` can still end when the table is unreadable.""" + return {role: proc for role, identity in recorded_processes(run) if (proc := procs.matches(identity)) is not None} + + +def _describe(live: dict[str, procs.ProcInfo]) -> str: + return ", ".join(f"{role} {Path(p.exe).name} pid {p.pid}" for role, p in sorted(live.items())) + + +def verdict(layout: Layout) -> Verdict: + """The root's row in the closed state table, first match wins (docs/OPERATIONS.md, "Lifecycle states").""" + try: + run = read_json(layout.run_record) if layout.run_record.exists() else {} + except (OSError, ValueError): + run = None + if not isinstance(run, dict): + message = "run record unreadable; reconcile this root by hand" + return Verdict("unreadable-record", "degraded", [message], refusal=message) + try: + table = process_table() + except procs.TableUnavailable as exc: + message = f"{exc}; custody unknown, so the root is not reported idle (retry `status`)" + return Verdict("unreadable-table", "degraded", [message], refusal=message, run=run) + live = {role: proc for role, identity in recorded_processes(run) if (proc := _alive(identity, table))} + descendants, under = _descendants(table, live) + known = {**live, **descendants} + owned = {**known, **_unrecorded(layout, table, known)} + found = {"details": {"live": sorted(owned)} if owned else {}, "run": run, "under": under, + "refusal": f"integration-owned processes already running ({', '.join(sorted(owned))}); use status/stop"} + state = run.get("state") + # `stop` ends a process-tree (job) generation only on Windows; elsewhere such a root is reconciled on its host. + stopper = ("reconcile it on its Windows host" if run.get("tree_token") and not WINDOWS + else "run `stop` for this root") + if run.get("unpublished_child"): + if state == "starting" and "wrapper" in live: + return Verdict("wrapper-publishing", "starting", + [f"launch in progress: its wrapper (pid {live['wrapper'].pid}) is publishing its server"], + owned, **{**found, "refusal": CUSTODY_REFUSAL, + "details": {**found["details"], "pending": True}}) + advice = ("run `stop` to end its process-tree job" if WINDOWS and run.get("tree_token") + else "`stop` refuses until the root is reconciled by hand") + return Verdict("custody-unknown", "degraded", + [f"the serve wrapper's child was never recorded and its lifetime is unknown; {advice}"], + owned, **{**found, "refusal": CUSTODY_REFUSAL}) + if state == "launching": + pending = {**found, "refusal": PENDING_REFUSAL, "details": {**found["details"], "pending": True}} + launcher = _alive(run.get("launcher"), table) + if launcher is not None: + return Verdict("launch-pending", "starting", + [f"launch pending: its start command (pid {launcher.pid}) has not handed over to its " + "wrapper"], owned, **pending) + return Verdict("launch-abandoned", "degraded", + ["launch abandoned before its wrapper published: its start command is gone and a dispatched " + f"wrapper may still be waiting for the root lock; {stopper} to fence it"], owned, **pending) + install = read_json(layout.install_record) if layout.install_record.exists() else None + if install is not None and install.get("profile_fingerprint") != layout.profile.fingerprint: + if not owned: + found["refusal"] = "the install was made for a different profile fingerprint; reinstall or switch back" + return Verdict("mismatched", "mismatched", ["install record belongs to another profile fingerprint"], owned, + quiescent=not owned, **found) + if owned: + remain = f"({_describe(owned)}); {stopper}" + if install is None: + return Verdict("orphans", "degraded", [f"install record missing while owned processes remain {remain}"], + owned, **found) + if "server" not in live: + return Verdict("orphans", "degraded", [f"server process gone while other owned processes remain {remain}"], + owned, **found) + if run.get("runtime_identity_sha256") != install.get("runtime_identity_sha256"): + return Verdict("server-live", "mismatched", ["running server was started from another install identity"], + owned, **found) + if state == "starting": + return Verdict("server-live", "starting", [], owned, **found) + if state == "stop_incomplete": + return Verdict("server-live", "degraded", [f"an earlier stop did not end {remain}"], owned, **found) + # `status` decides healthy or degraded from the authenticated checks. + return Verdict("server-live", "healthy", [], owned, **found) + token = run.get("tree_token") + if token and not (state == "stopped" and run.get("tree_verified_empty") == token): + advice = "run `stop` to end and prove its process-tree job" if WINDOWS else "reconcile it on its Windows host" + return Verdict("job-unproved", "degraded", [f"process-tree generation not proved empty; {advice}"], + refusal=CUSTODY_REFUSAL, run=run) + srv = layout.profile.data["server"] + if port_in_use(srv["listen_host"], srv["port"]): + message = (f"{srv['listen_host']}:{srv['port']} is occupied by a process this integration does not own; " + "refusing to start or adopt it") + return Verdict("port-held", "degraded", [message], quiescent=True, refusal=message, run=run) + if install is None: + return Verdict("idle", "not_installed", quiescent=True, run=run) + if state == "exited" and run.get("exit_code") not in (0, None): + return Verdict("idle", "failed", quiescent=True, run=run, + details={"exit_code": run.get("exit_code"), "log": run.get("log")}) + return Verdict("idle", "stopped", quiescent=True, run=run) def idle_generation(layout: Layout, *, expected: str | None = None, timeout: float = 30) -> str: - """Caller holds the installation lock through this check and all admitted effects.""" - current = read_json(layout.run_record) if layout.run_record.exists() else {} - if layout.run_record.exists() and not current: + """Caller holds the installation lock through this check and all admitted effects. The candidate path requires + a quiescent root whose prior generation, if any, is a process-tree job proved empty.""" + root = verdict(layout) + current = root.run + if root.row == "unreadable-record" or layout.run_record.exists() and not current: raise LifecycleError("partial candidate generation record") generation = sha256_bytes(canonical_json(current)) if expected is not None and generation != expected: raise LifecycleError("candidate admission generation changed") - if current and (current.get("state") != "stopped" or current.get("unpublished_child") - or not current.get("tree_token") + if not root.quiescent or current and (current.get("state") != "stopped" or not current.get("tree_token") or current.get("tree_verified_empty") != current["tree_token"] - or running(layout) or ProcessJob.scan(current["tree_token"], set(), {}, timeout=timeout)): raise LifecycleError("prior candidate generation unproved") return generation @@ -1790,11 +1968,9 @@ def start(layout: Layout, *, tool_argv: list[str], log: Log, timeout: int | None with FileLock(layout.lock_file): if expected_idle_generation is not None: idle_generation(layout, expected=expected_idle_generation) - previous = read_json(layout.run_record) if layout.run_record.exists() else {} - if previous.get("unpublished_child") or previous.get("tree_token") and previous.get("state") != "stopped": - raise LifecycleError("unpublished child lifetime is unknown; retain custody for reconciliation") - if previous.get("state") == "launching": - raise LifecycleError("pending launch already owns this root; use stop before replacement") + root = verdict(layout) + if not root.idle: + raise LifecycleError(root.refusal) rec = verify_install_fast(layout) if dflash2.is_pinned(p) and dflash2.tuned_aware(p["strata"]["engine_version"]): try: @@ -1802,12 +1978,6 @@ def start(layout: Layout, *, tool_argv: list[str], log: Log, timeout: int | None except IntegrityError as exc: raise LifecycleError(f"stock DFlash2 folder: {exc}") from exc key = read_key(layout) - live = running(layout) - if live: - raise LifecycleError(f"integration-owned processes already running ({', '.join(live)}); use status/stop") - if port_in_use(srv["listen_host"], srv["port"]): - raise LifecycleError(f"{srv['listen_host']}:{srv['port']} is occupied by a process this integration " - "does not own; refusing to start or adopt it") if experimental: # Physical GPU readiness belongs to the controller's reservation receipt. # Never inspect unrelated GPU processes on this candidate-only path. @@ -1841,10 +2011,13 @@ def start(layout: Layout, *, tool_argv: list[str], log: Log, timeout: int | None "engine_log": engine_log.relative_to(layout.root.resolve()).as_posix(), "engine_log_start_offset": engine_log.stat().st_size if engine_log.exists() else 0} launch_id = secrets.token_hex(16) + # The launcher's own identity lets a later reader tell a pending launch from one whose start was killed. + launcher = procs.info(os.getpid()) atomic_write_json(layout.run_record, { "schema_version": 1, "profile_id": layout.profile.id, "profile_fingerprint": layout.profile.fingerprint, "runtime_identity_sha256": rec["runtime_identity_sha256"], "port": srv["port"], "requested_utc": utc_now(), "state": "launching", "launch_id": launch_id, + **({"launcher": launcher.as_dict()} if launcher is not None else {}), "log": log_path.relative_to(layout.root).as_posix(), **({"experiment_launch_id": os.environ[EXPERIMENT_LAUNCH_ENV]} if os.environ.get(EXPERIMENT_LAUNCH_ENV) else {}), **({"tree_token": os.environ[EXPERIMENT_LAUNCH_ENV]} @@ -1976,25 +2149,13 @@ def processes(run): # ------------------------------------------------------------------------------------------------ status / stop def status(layout: Layout) -> dict: - if not layout.install_record.exists(): - return {"state": "not_installed"} - rec = read_json(layout.install_record) - if rec.get("profile_fingerprint") != layout.profile.fingerprint: - return {"state": "mismatched", "problems": ["install record belongs to another profile fingerprint"]} - run = read_json(layout.run_record) if layout.run_record.exists() else {} - live = running(layout) - if not live: - occupancy = {"cards": card_observations(layout.profile)} if layout.profile.multi_gpu else {} - if run.get("state") == "exited" and run.get("exit_code") not in (0, None): - return {"state": "failed", "exit_code": run.get("exit_code"), "log": run.get("log"), **occupancy} - return {"state": "stopped", **occupancy} - if run.get("runtime_identity_sha256") != rec.get("runtime_identity_sha256"): - return {"state": "mismatched", "problems": ["running server was started from another install identity"]} - if "server" not in live: - return {"state": "degraded", "problems": ["server process gone while other owned processes remain"], - "live": sorted(live)} - if run.get("state") in ("launching", "starting"): - return {"state": "starting", "live": sorted(live)} + root = verdict(layout) + if root.row != "server-live" or root.state != "healthy": + report = {"state": root.state, **({"problems": root.problems} if root.problems else {}), **root.details} + if root.state in ("stopped", "failed") and layout.profile.multi_gpu: + report["cards"] = card_observations(layout.profile) + return report + run, live = root.run, root.live try: key = read_key(layout) except LifecycleError as exc: @@ -2005,6 +2166,9 @@ def status(layout: Layout) -> dict: tree = procs.descendants(server.pid) if run.get("engine") and not any(Path(p.exe).name.lower().startswith("strata") for p in tree): problems.append("no engine process under the server (stock Strata restarts it on the next request)") + stray = {role: p for role, p in live.items() if role.startswith("unrecorded[")} + if stray: + problems.append(f"processes of this root outside its recorded trees ({_describe(stray)}); `stop` ends them") extra = {} if layout.profile.multi_gpu: cards = card_observations(layout.profile, owned_pids={server.pid, *(p.pid for p in tree)}) @@ -2022,12 +2186,37 @@ def status(layout: Layout) -> dict: "started_utc": run.get("ready_utc"), **extra} +def _stop_order(live: dict[str, procs.ProcInfo]) -> list[tuple[str, procs.ProcInfo]]: + """Deepest first: unrecorded processes (descendants already deepest first), then recorded processes other than + the server and the wrapper, then the server, then the wrapper.""" + def rank(role: str) -> int: + if role.startswith(("descendant[", "unrecorded[")): + return 0 + return {"server": 2, "wrapper": 3}.get(role, 1) + return sorted(live.items(), key=lambda item: rank(item[0])) + + +def _stop_label(role: str, proc: procs.ProcInfo, under: dict[int, str]) -> str: + """How `stop` names what it ended: a process in the server's or the wrapper's tree is that root's descendant; + another recorded process, or one in its tree, is an orphan; a process found only by the census is unrecorded.""" + if role in ("server", "wrapper"): + return role + if under.get(proc.pid) in ("server", "wrapper"): + return f"{under[proc.pid]}-descendant" + return "unrecorded" if role.startswith("unrecorded[") else "orphan" + + def stop(layout: Layout, *, log: Log, locked: bool = False, job: ProcessJob | None = None) -> dict: def _stop() -> dict: - if not layout.run_record.exists(): + root = verdict(layout) + existed = layout.run_record.exists() + if not existed and not root.live and root.row != "unreadable-table": extra = {"cards": card_observations(layout.profile), "owned_gpus_released": None} if layout.profile.multi_gpu else {} return {"state": "stopped", "stopped": [], **extra} - run = read_json(layout.run_record) + if root.row == "unreadable-record": + raise LifecycleError(root.problems[0]) + run = root.run + unreadable = root.row == "unreadable-table" tree_stopped = False if (run.get("tree_token") and run.get("state") == "stopped" and run.get("tree_verified_empty") == run["tree_token"]): @@ -2043,9 +2232,7 @@ def _stop() -> dict: # Windows destroys a kill-on-close job after its last handle and # associated processes are gone. ERROR_ACCESS_DENIED is not this # proof. Independently reject marked or recorded survivors. - recorded = [run.get(role) for role in ("wrapper", "server", "engine")] - recorded += run.get("server_tree", []) - if (not WINDOWS or any(procs.matches(identity) for identity in recorded) + if (not WINDOWS or unreadable or root.live or ProcessJob.scan(run["tree_token"], set(), {})): raise LifecycleError("destroyed job still has survivors or unavailable verification") else: @@ -2059,40 +2246,45 @@ def _stop() -> dict: raise tree_stopped = True if run.get("unpublished_child") and not tree_stopped: - raise LifecycleError("unpublished child lifetime is unknown; retain custody for reconciliation") + raise LifecycleError(CUSTODY_REFUSAL) timeout = layout.profile.data["server"]["stop_timeout_s"] stopped, refused = [], [] - # Owned roots are the recorded wrapper and server (identity-verified). Their CURRENT descendants are owned - # too (the real interpreter behind the venv redirector, and any engine the server restarted), so each - # verified root is stopped with its subtree, deepest first; a PID that no longer matches is never touched. - targets: list[tuple[str, procs.ProcInfo]] = [] - for role in ("server", "wrapper"): - root = procs.matches(run.get(role)) - if root is None: - continue - targets += [(f"{role}-descendant", d) for d in procs.descendants(root.pid)] - targets.append((role, root)) - for rec in [run.get("engine"), *run.get("server_tree", [])]: - orphan = procs.matches(rec) - if orphan is not None and all(orphan.pid != t.pid for _, t in targets): - targets.insert(0, ("orphan", orphan)) + # The verdict's live set: every recorded process alive, the current descendants of each (the real interpreter + # behind the venv redirector, any engine a server restarted) and every unrecorded process running the root's + # runtime. With the process table unreadable only recorded identities, each verified on its own, are ended. done: set[int] = set() - for role, proc in targets: - if proc.pid in done: - continue - done.add(proc.pid) - try: - if procs.terminate(proc, timeout): - stopped.append(f"{role}:{Path(proc.exe).name}") - else: - refused.append(f"{role} {Path(proc.exe).name} did not exit within {timeout}s") - except PermissionError as exc: - refused.append(str(exc)) + live, under = (_verifiable(run), {}) if unreadable else (root.live, root.under) + for attempt in range(2): + for role, proc in _stop_order(live): + if proc.pid in done: + continue + done.add(proc.pid) + label = _stop_label(role, proc, under) + try: + if procs.terminate(proc, timeout): + stopped.append(f"{label}:{Path(proc.exe).name}") + else: + refused.append(f"{label} {Path(proc.exe).name} did not exit within {timeout}s") + except PermissionError as exc: + refused.append(str(exc)) + if unreadable or refused: + break + # A server can start an engine while its tree is being ended: what is still alive gets one more pass. + again = verdict(layout) + live = {role: proc for role, proc in again.live.items() if proc.pid not in done} + under = again.under + if not live: + break + if attempt: + refused.append(f"still alive after stop ({_describe(live)})") + if unreadable: + refused.append(root.problems[0]) run.update({"state": "stopped" if not refused else "stop_incomplete", "stopped_utc": utc_now(), "unpublished_child": False}) if tree_stopped and not refused: run["tree_verified_empty"] = run["tree_token"] - atomic_write_json(layout.run_record, run) + if existed: # A root that never had a run record does not get one from stop. + atomic_write_json(layout.run_record, run) srv = layout.profile.data["server"] deadline = time.monotonic() + timeout while port_in_use(srv["listen_host"], srv["port"]) and time.monotonic() < deadline: @@ -2127,5 +2319,5 @@ def tool_argv() -> list[str]: -__all__ = ["FileLock", "InstallError", "LifecycleError", "doctor", "ensure_healthy", "keygen", "read_key", - "serve", "start", "status", "stop", "tool_argv"] +__all__ = ["FileLock", "IDLE_STATES", "InstallError", "LifecycleError", "Verdict", "doctor", "ensure_healthy", "keygen", + "read_key", "serve", "start", "status", "stop", "tool_argv", "verdict"] diff --git a/omp_strata/procs.py b/omp_strata/procs.py index 6b36307..385961e 100644 --- a/omp_strata/procs.py +++ b/omp_strata/procs.py @@ -27,6 +27,10 @@ def as_dict(self) -> dict: return asdict(self) +class TableUnavailable(OSError): + """The process table could not be read as a whole, so no process may be taken to be absent.""" + + if WINDOWS: import ctypes from ctypes import wintypes @@ -71,11 +75,11 @@ def _open(pid: int, access: int): h = _k32.OpenProcess(access, False, pid) return h or None - def _parents() -> dict[int, tuple[int, str]]: + def _snapshot() -> dict[int, tuple[int, str]]: snap = _k32.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) - out: dict[int, tuple[int, str]] = {} if snap in (None, wintypes.HANDLE(-1).value): - return out + raise TableUnavailable(f"process snapshot failed (error {ctypes.get_last_error()})") + out: dict[int, tuple[int, str]] = {} try: entry = PROCESSENTRY32W() entry.dwSize = ctypes.sizeof(PROCESSENTRY32W) @@ -85,6 +89,25 @@ def _parents() -> dict[int, tuple[int, str]]: ok = _k32.Process32NextW(snap, ctypes.byref(entry)) finally: _k32.CloseHandle(snap) + if not out: + raise TableUnavailable("process snapshot listed no process") + return out + + def _parents() -> dict[int, tuple[int, str]]: + try: + return _snapshot() + except TableUnavailable: + return {} + + def table() -> dict[int, ProcInfo]: + """Every process from one Toolhelp snapshot, identified as `info` identifies one. A snapshot that fails or + lists nothing raises TableUnavailable. A process whose creation time or image cannot be read (protected + system processes refuse even limited query access) is left out: this user's processes are readable.""" + out: dict[int, ProcInfo] = {} + for pid, (ppid, _) in _snapshot().items(): + proc = info(pid, ppid=ppid) + if proc is not None and proc.exe: + out[pid] = proc return out def info(pid: int, *, ppid: int | None = None) -> ProcInfo | None: @@ -207,6 +230,16 @@ def _proc_children(pid: int) -> list[int]: kids.append(int(entry)) return kids + def _identity(pid: int, ppid: int, created: str, comm: str) -> ProcInfo: + exe = comm + link = f"/proc/{pid}/exe" + if os.path.exists(link): + try: + exe = os.readlink(link) + except OSError: + pass + return ProcInfo(pid=pid, ppid=ppid, created=created, exe=exe) + def info(pid: int, *, ppid: int | None = None) -> ProcInfo | None: if pid <= 0: return None @@ -219,15 +252,43 @@ def info(pid: int, *, ppid: int | None = None) -> ProcInfo | None: row = _ps(pid) if row is None: return None - ppid, created, comm = row - exe = comm - link = f"/proc/{pid}/exe" - if os.path.exists(link): - try: - exe = os.readlink(link) - except OSError: - pass - return ProcInfo(pid=pid, ppid=ppid, created=created, exe=exe) + return _identity(pid, *row) + + def parse_ps_table(text: str) -> dict[int, ProcInfo]: + """`ps -A -o pid=,ppid=,lstart=,comm=` rows, identified as `info` identifies one process. A row that does + not parse is left out.""" + out: dict[int, ProcInfo] = {} + for line in text.splitlines(): + parts = line.split() + if len(parts) < 8 or not parts[0].isdigit() or not parts[1].isdigit(): + continue + out[int(parts[0])] = _identity(int(parts[0]), int(parts[1]), " ".join(parts[2:7]), " ".join(parts[7:])) + return out + + def _proc_table() -> dict[int, ProcInfo]: + try: + entries = os.listdir("/proc") + except OSError as exc: + raise TableUnavailable(f"process table unreadable: {exc}") from None + out = {int(entry): _identity(int(entry), *row) for entry in entries + if entry.isdigit() and (row := _proc_stat(int(entry))) is not None} + if not out: + raise TableUnavailable("process table listed no process") + return out + + def table() -> dict[int, ProcInfo]: + """Every process from one read. A read that fails, times out or lists nothing raises TableUnavailable.""" + try: + done = subprocess.run(["ps", "-A", "-o", "pid=,ppid=,lstart=,comm="], capture_output=True, text=True, + stdin=subprocess.DEVNULL, timeout=10) + except FileNotFoundError: + return _proc_table() + except (OSError, subprocess.SubprocessError) as exc: + raise TableUnavailable(f"process table unreadable: {exc}") from None + rows = parse_ps_table(done.stdout) if done.returncode == 0 else {} + if not rows: + raise TableUnavailable(f"process table unreadable: ps exited {done.returncode} with no rows") + return rows def children(pid: int) -> list[int]: try: @@ -291,15 +352,18 @@ def process_memory(pid: int) -> dict[str, int]: return out +def same_identity(live: ProcInfo, recorded: dict) -> bool: + """True when a live process is the recorded one: same creation time and executable (case-blind on Windows).""" + same_exe = live.exe.lower() == recorded["exe"].lower() if WINDOWS else live.exe == recorded["exe"] + return live.created == recorded["created"] and same_exe + + def matches(recorded: dict | None) -> ProcInfo | None: """The live process for a recorded identity, or None when it is gone or the PID now belongs to another.""" if not recorded: return None live = info(int(recorded["pid"])) - if live is None: - return None - same_exe = live.exe.lower() == recorded["exe"].lower() if WINDOWS else live.exe == recorded["exe"] - return live if live.created == recorded["created"] and same_exe else None + return live if live is not None and same_identity(live, recorded) else None def descendants(pid: int) -> list[ProcInfo]: diff --git a/tests/unit/test_experiment_loop.py b/tests/unit/test_experiment_loop.py index 0152cde..f966e3d 100644 --- a/tests/unit/test_experiment_loop.py +++ b/tests/unit/test_experiment_loop.py @@ -293,7 +293,7 @@ def test_pending_start_cannot_be_overwritten_by_another_start(self): root = self.root / "pending" root.mkdir() layout = SimpleNamespace(run_record=root / "run.json", lock_file=root / "lock", - profile=SimpleNamespace(data={"server": {}})) + strata=root / "runtime" / "strata", profile=SimpleNamespace(data={"server": {}})) atomic_write_json(layout.run_record, {"state": "launching", "launch_id": "existing"}) before = layout.run_record.read_bytes() with patch.object(lifecycle, "verify_install_fast") as verify, self.assertRaisesRegex( @@ -681,7 +681,7 @@ def command(arm, script, args, timeout, **kwargs): with patch.object(loop.nvfp4, "staging_preflight"), \ patch.object(lifecycle, "keygen", side_effect=effect), \ patch.object(lifecycle, "verify_install_fast", side_effect=effect), \ - patch.object(lifecycle, "running", return_value={}), \ + patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle.ProcessJob, "scan", return_value={}), \ patch.object(lifecycle, "_job_kernel", return_value=KernelStub()): try: @@ -1005,7 +1005,7 @@ def test_experimental_start_skips_gpu_census_but_ordinary_start_keeps_it(self): patch.object(lifecycle, "FileLock", MemoryLock), \ patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "fixture"}), \ patch.object(lifecycle, "read_key", return_value="fixture"), \ - patch.object(lifecycle, "running", return_value={}), \ + patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle, "port_in_use", return_value=False), \ patch.object(lifecycle, "gpu_facts", return_value={}) as census, \ patch.object(lifecycle, "gpu_busy", return_value=None), \ @@ -1056,9 +1056,13 @@ def information(handle, pointer): lifecycle.directory_identity(path) def test_partial_record_never_matches_admitted_empty_digest(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "run.json" - layout = SimpleNamespace(run_record=path) + with tempfile.TemporaryDirectory() as directory, patch.object(lifecycle, "port_in_use", return_value=False): + root = Path(directory) + path = root / "run.json" + # The stand-in carries what the lifecycle's one verdict reads: records, runtime directory, served port. + layout = SimpleNamespace(run_record=path, install_record=root / "install.json", + strata=root / "runtime" / "strata", + profile=SimpleNamespace(data={"server": {"listen_host": "127.0.0.1", "port": 1}})) empty = lifecycle.idle_generation(layout) atomic_write_json(path, {}) with self.assertRaisesRegex(lifecycle.LifecycleError, "partial"): @@ -1094,7 +1098,7 @@ def __init__(self, manifest, bindings, kernel, cut, parent_exits, publication, p root = Path(bindings["candidate_root"]) root.mkdir(parents=True) self.layouts = {"candidate": SimpleNamespace(root=root, state=root, run_record=root / "run.json", lock_file=root / "lock", - install_record=root / "install.json", + install_record=root / "install.json", strata=root / "runtime" / "strata", profile=SimpleNamespace(fingerprint=manifest["candidate"]["profile_fingerprint"], multi_gpu=False, data=manifest["candidate"]["config"] | {"model": manifest["candidate"]["model"]}))} self.owned_runs, self.launch_requests, self.launch_jobs, self.owned_commands = {}, {}, {}, {} @@ -1106,7 +1110,7 @@ def __init__(self, manifest, bindings, kernel, cut, parent_exits, publication, p atomic_write_json(self.layouts["candidate"].run_record, { "state": "launching" if preexisting == "pending" else "ready", "profile_fingerprint": self.layouts["candidate"].profile.fingerprint, - "wrapper": {"pid": 900}, "launch_id": "prior-generation"}) + "wrapper": fixture_process(900).as_dict(), "launch_id": "prior-generation"}) kernel.live[900] = object() # Outside this invocation's job; never adopt/kill it. reservation = FakeAdapter.reservation @@ -1194,7 +1198,9 @@ def model_schedules(): patch.object(lifecycle, "read_key", return_value="fixture"), \ patch.object(lifecycle, "runtime_checks", side_effect=lambda *args, **kwargs: { "ready": 101 in kernel.live}), \ - patch.object(lifecycle, "port_in_use", return_value=False): + patch.object(lifecycle, "port_in_use", return_value=False), \ + patch.object(lifecycle, "process_table", + side_effect=lambda: {pid: fixture_process(pid) for pid in kernel.live}): result_dir = loop.run(manifest, host, bindings=local, evidence_dir=root / str(index) / "evidence", lock_directory=root / str(index) / "locks") result = loop.report(result_dir) @@ -1245,7 +1251,7 @@ def command(arm, script, args, timeout): "--root", str(layout.root)]) cli.cmd_install(parsed) adapter.command = command - with patch.object(lifecycle, "running", return_value={}), \ + with patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle.ProcessJob, "scan", return_value={}), \ patch.object(loop.nvfp4, "staging_preflight"), \ patch.object(install.fetch_mod, "fetch", side_effect=fetch_boundary): diff --git a/tests/unit/test_lifecycle.py b/tests/unit/test_lifecycle.py index a2f0ce0..de3b910 100644 --- a/tests/unit/test_lifecycle.py +++ b/tests/unit/test_lifecycle.py @@ -21,6 +21,7 @@ import urllib.request from omp_strata import common, dflash2, fetch, lifecycle, nvfp4, procs +from omp_strata.lifecycle import IDLE_STATES from omp_strata.layout import Layout from omp_strata.profile import ENGINE_ENV_GROUPS, Profile, engine_env_union, load from tests.candidate import PROFILE @@ -28,7 +29,6 @@ from tests.unit.test_profile import multi_gpu_data, single_gpu_data REPO = Path(__file__).resolve().parents[2] -IDLE_STATES = ("not_installed", "stopped", "failed") def gpu_fact(profile, index, processes=(), used=0): @@ -469,7 +469,7 @@ def test_status_and_stop_act_on_one_set_of_live_processes(self): current = dict(record, **({gone: self.dead_identity()} if gone else {})) common.atomic_write_json(self.layout.run_record, current) expected = {role: pid for role, pid in pids.items() if role != gone} - live = lifecycle.running(self.layout) + live = lifecycle.verdict(self.layout).live self.assertEqual(expected, {role: info.pid for role, info in live.items()}) if gone == "server": # status names the same set without contacting a server. self.assertEqual(sorted(expected), lifecycle.status(self.layout)["live"]) @@ -791,7 +791,7 @@ def launch(*args, **kwargs): with self.subTest(gpu=gpu): with patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "a" * 64}), \ patch.object(lifecycle, "read_key", return_value="x" * 32), \ - patch.object(lifecycle, "running", return_value={}), \ + patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle, "port_in_use", return_value=False), \ patch.object(lifecycle.procs, "memory", return_value={"total": 1 << 40, "available": 1 << 40}), \ patch.object(lifecycle.procs, "matches", side_effect=lambda rec: server if rec == server.as_dict() else None), \ @@ -833,7 +833,7 @@ def launch(*args, **kwargs): with patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "a" * 64}), \ patch.object(lifecycle, "read_key", return_value="x" * 32), \ - patch.object(lifecycle, "running", return_value={}), \ + patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle, "port_in_use", return_value=False), \ patch.object(lifecycle.procs, "memory", return_value={"total": 1 << 40, "available": 1 << 40}), \ patch.object(lifecycle.procs, "matches", side_effect=lambda rec: server if rec == server.as_dict() else None), \ @@ -886,7 +886,7 @@ def launch(*args, **kwargs): self.enterContext(patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "a" * 64})) self.enterContext(patch.object(lifecycle, "read_key", return_value="x" * 32)) - self.enterContext(patch.object(lifecycle, "running", return_value={})) + self.enterContext(patch.object(lifecycle, "process_table", return_value={})) self.enterContext(patch.object(lifecycle, "port_in_use", return_value=False)) self.enterContext(patch.object(lifecycle.procs, "memory", return_value={"available": 1 << 40})) self.enterContext(patch.object(lifecycle.procs, "matches", side_effect=lambda rec: server if rec == server.as_dict() else None)) @@ -1312,7 +1312,7 @@ def launch(argv, **_kwargs): common.atomic_write_json(self.layout.strata_config, {"log": str(self.layout.strata / "engine.log")}) with patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "a" * 64}), \ patch.object(lifecycle, "read_key", return_value="fixture-key"), \ - patch.object(lifecycle, "running", return_value={}), \ + patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle, "port_in_use", return_value=False), \ patch.object(lifecycle, "gpu_busy", return_value=None), \ patch.object(lifecycle.procs, "memory", return_value={"available": 0}), \ @@ -1668,7 +1668,7 @@ def prepare_start(self, foreign=False, engine_prefix="", engine_text=StageOrderT common.atomic_write_json(self.layout.strata_config, cfg) self.enterContext(patch.object(lifecycle, "verify_install_fast", return_value={"runtime_identity_sha256": "a" * 64})) self.enterContext(patch.object(lifecycle, "read_key", return_value="x" * 32)) - self.enterContext(patch.object(lifecycle, "running", return_value={})) + self.enterContext(patch.object(lifecycle, "process_table", return_value={})) self.enterContext(patch.object(lifecycle, "port_in_use", return_value=False)) self.enterContext(patch.object(lifecycle.procs, "memory", return_value={"total": 1 << 40, "available": 1 << 40})) self.enterContext(patch.object(lifecycle.procs, "matches", side_effect=self.matches)) @@ -2119,7 +2119,7 @@ def test_status_respawn_invalidates_capture_without_mutating_record(self): self.assertTrue(lifecycle.capture_startup_gpu_order(self.layout)["complete"]) before = self.layout.run_record.read_bytes() replacement = procs.ProcInfo(102, 100, "replacement-created", "strata.exe") - with patch.object(lifecycle, "running", return_value={"server": self.server}), \ + with patch.object(lifecycle, "process_table", return_value={self.server.pid: self.server}), \ patch.object(lifecycle.procs, "descendants", return_value=[replacement]), \ patch.object(lifecycle, "read_key", return_value="x" * 32), \ patch.object(lifecycle, "runtime_checks", return_value={"ready": True, "problems": []}), \ @@ -2131,7 +2131,7 @@ def test_status_respawn_invalidates_capture_without_mutating_record(self): def test_stopped_status_reports_foreign_occupancy_without_changing_process_state(self): self.record() - with patch.object(lifecycle, "running", return_value={}), \ + with patch.object(lifecycle, "process_table", return_value={}), \ patch.object(lifecycle, "gpu_facts", side_effect=lambda i, **kwargs: self.gpu(i, [{"pid": 999, "type": "C"}])): result = lifecycle.status(self.layout) self.assertEqual("stopped", result["state"]) @@ -2139,8 +2139,7 @@ def test_stopped_status_reports_foreign_occupancy_without_changing_process_state def test_stop_never_owns_foreign_gpu_pid_and_reports_all_card_release(self): self.record() - with patch.object(lifecycle.procs, "matches", side_effect=self.matches), \ - patch.object(lifecycle.procs, "descendants", return_value=[self.engine]), \ + with patch.object(lifecycle, "process_table", return_value={p.pid: p for p in (self.server, self.engine)}), \ patch.object(lifecycle.procs, "terminate", return_value=True) as terminate, \ patch.object(lifecycle, "port_in_use", return_value=False), \ patch.object(lifecycle, "gpu_facts", side_effect=lambda i, **kwargs: self.gpu(i, [{"pid": 999, "type": "C"}])): diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py new file mode 100644 index 0000000..b3283b4 --- /dev/null +++ b/tests/unit/test_lifecycle_states.py @@ -0,0 +1,513 @@ +"""The lifecycle's closed state table, walked (docs/OPERATIONS.md, "Lifecycle states"). + +The walk crosses everything the code can write (install record, run record state and flags) with everything the +process table can show (which recorded processes live, unrecorded processes of the root, a pid reused by a stranger, +a failed read, the port), using a process world kept in memory, and checks that status, start, stop and +idle_generation act on one verdict and that every row of the closed table is reached. +""" +from __future__ import annotations + +import itertools +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from unittest.mock import patch + +from omp_strata import lifecycle, procs +from omp_strata.common import atomic_write_json, read_json +from omp_strata.layout import Layout +from omp_strata.profile import Profile +from tests.candidate import PROFILE +from tests.mock.test_remote_support import free_port +from tests.unit.test_profile import single_gpu_data + +FULL = ("wrapper", "server", "engine", "server_tree") +TOKEN = "a" * 32 +# Rows whose `stop` refuses on this platform: custody unknown, a publishing wrapper, an unreadable record, and (off +# Windows) any process-tree record. An unreadable table ends verified recorded processes, then refuses. +STOP_REFUSES = {"unreadable-record", "custody-unknown", "wrapper-publishing", "unreadable-table"} + + +class Admitted(Exception): + """`start` passed every root check and reached the install check.""" + + +def ident(pid: int, ppid: int, exe: str) -> procs.ProcInfo: + return procs.ProcInfo(pid, ppid, f"created-{pid}", exe) + + +class StateTableWalk(unittest.TestCase): + def setUp(self): + directory = self.enterContext(tempfile.TemporaryDirectory()) + data = single_gpu_data() + data["server"].update(port=free_port(), stop_timeout_s=0) + self.layout = Layout(Path(directory) / "root", Profile(PROFILE, data)) + self.layout.run_record.parent.mkdir(parents=True, exist_ok=True) + engine = str(self.layout.strata / "engine" / "strata") + self.p = {"launcher": ident(10, 1, "/tools/python3"), "wrapper": ident(11, 1, "/tools/python3"), + "server": ident(12, 11, "/tools/python3"), "server_tree": ident(13, 12, "/usr/bin/python3"), + "engine": ident(14, 13, engine)} + self.engine_exe = engine + + def record(self, template): + fingerprint = self.layout.profile.fingerprint + base = {"profile_fingerprint": fingerprint, "runtime_identity_sha256": "a" * 64, "launch_id": "walked"} + full: dict = {role: self.p[role].as_dict() for role in ("wrapper", "server", "engine")} + full["server_tree"] = [self.p["server_tree"].as_dict()] + return { + "absent": (None, ()), + "unreadable": ("{", ()), + "launching": (dict(base, state="launching", launcher=self.p["launcher"].as_dict()), ("launcher",)), + "publishing": (dict(base, state="starting", unpublished_child=True, wrapper=full["wrapper"]), + ("wrapper",)), + "starting": (dict(base, state="starting", wrapper=full["wrapper"], server=full["server"]), + ("wrapper", "server")), + "ready": (dict(base, state="ready", **full), FULL), + "exited-0": (dict(base, state="exited", exit_code=0, **full), FULL), + "exited-1": (dict(base, state="exited", exit_code=1, **full), FULL), + "stopped": (dict(base, state="stopped", **full), FULL), + "stop_incomplete": (dict(base, state="stop_incomplete", **full), FULL), + "job-ready": (dict(base, state="ready", tree_token=TOKEN, **full), FULL), + "job-stopped": (dict(base, state="stopped", tree_token=TOKEN, tree_verified_empty=TOKEN, **full), FULL), + }[template] + + def write(self, path, value): + if value is None: + path.unlink(missing_ok=True) + else: + path.write_text(value if isinstance(value, str) else json.dumps(value), encoding="utf-8") + + @staticmethod + def owners(world, alive_roles, p, runtime_pids): + """Ground truth, independent of the verdict: recorded processes alive, their current descendants, and every + process running the root's runtime. A launcher is not a process of the root; it only makes a launch pending.""" + roots = {p[role].pid for role in alive_roles if role != "launcher"} + found, frontier = set(roots), list(roots) + while frontier: + parent = frontier.pop() + for proc in world.values(): + if proc.ppid == parent and proc.pid not in found: + found.add(proc.pid) + frontier.append(proc.pid) + return found | runtime_pids + + def test_every_combination_lands_in_one_row_and_every_consumer_acts_on_it(self): + world: dict[int, procs.ProcInfo] = {} + readable = {"value": True} + port = {"held": False} + terminated: list[int] = [] + + def table(): + if not readable["value"]: + raise procs.TableUnavailable("fixture process table unreadable") + return dict(world) + + def matches(recorded): + proc = world.get(int(recorded["pid"])) if recorded else None + return proc if proc is not None and procs.same_identity(proc, recorded) else None + + def terminate(proc, timeout): + terminated.append(proc.pid) + world.pop(proc.pid, None) + return True + + def fast_write(path, value): + Path(path).write_text(json.dumps(value), encoding="utf-8") + + def not_installed(_layout): + raise Admitted + + patches = ( + patch.object(lifecycle, "process_table", side_effect=table), + patch.object(lifecycle.procs, "matches", side_effect=matches), + patch.object(lifecycle.procs, "terminate", side_effect=terminate), + patch.object(lifecycle.procs, "descendants", + side_effect=lambda pid: [proc for proc in world.values() if proc.ppid == pid]), + patch.object(lifecycle, "port_in_use", side_effect=lambda *args: port["held"]), + patch.object(lifecycle, "read_key", return_value="x" * 32), + patch.object(lifecycle, "runtime_checks", return_value={"ready": True, "problems": []}), + patch.object(lifecycle, "verify_install_fast", side_effect=not_installed), + patch.object(lifecycle.ProcessJob, "scan", return_value={}), + patch.object(lifecycle, "atomic_write_json", side_effect=fast_write), + ) + for active in patches: + self.enterContext(active) + installs = {"absent": None, "this": {"profile_fingerprint": self.layout.profile.fingerprint, + "runtime_identity_sha256": "a" * 64}, + "other": {"profile_fingerprint": "0" * 64, "runtime_identity_sha256": "a" * 64}, + "stale": {"profile_fingerprint": self.layout.profile.fingerprint, + "runtime_identity_sha256": "b" * 64}} + templates = ("absent", "unreadable", "launching", "publishing", "starting", "ready", "exited-0", "exited-1", + "stopped", "stop_incomplete", "job-ready", "job-stopped") + seen_rows, combinations, started = set(), 0, time.monotonic() + for template in templates: + record, roles = self.record(template) + for alive in itertools.product((False, True), repeat=len(roles)): + alive_roles = {role for role, up in zip(roles, alive) if up} + for install, extra, can_read, held in itertools.product( + installs, ("none", "engine", "helper", "reused"), (True, False), (False, True)): + if not can_read and (extra != "none" or held): + continue # An unread table hides processes and port alike: one case covers it. + if extra == "reused" and "wrapper" in alive_roles: + continue # The wrapper's pid is taken by the wrapper itself. + combinations += 1 + world.clear() + world.update({self.p[role].pid: self.p[role] for role in alive_roles}) + parent = next((self.p[role].pid for role in ("server_tree", "server") if role in alive_roles), 1) + if extra == "engine": # an engine nobody recorded, e.g. restarted by the server tree + world[20] = ident(20, parent, self.engine_exe) + elif extra == "helper": # a helper outside the runtime, under the server if it lives + world[21] = ident(21, self.p["server"].pid if "server" in alive_roles else 1, "/usr/bin/helper") + elif extra == "reused": # a stranger now holding the recorded wrapper's pid + world[11] = procs.ProcInfo(11, 1, "created-other", "/tools/python3") + readable["value"], port["held"] = can_read, held + self.write(self.layout.install_record, installs[install]) + self.write(self.layout.run_record, record) + runtime = {pid for pid, proc in world.items() if proc.exe == self.engine_exe} + truth = self.owners(world, alive_roles, self.p, runtime) + case = (template, sorted(alive_roles), install, extra, can_read, held) + with self.subTest(case=case): + seen_rows.add(self.check(record, truth, readable["value"], held, installs[install], world, + terminated)) + self.combinations, self.seconds = combinations, time.monotonic() - started + print(f"\nstate-table walk: {combinations} combinations in {self.seconds:.1f} s", file=sys.stderr) + self.assertEqual(set(lifecycle.ROWS), seen_rows) # Every row of the closed table is reachable. + + def check(self, record, truth, readable, held, install, world, terminated): + run = record if isinstance(record, dict) else {} + verdict = lifecycle.verdict(self.layout) + # I6: every combination is in exactly one row of the closed table. + self.assertIn(verdict.row, lifecycle.ROWS) + token = run.get("tree_token") + expected_idle = (readable and isinstance(record, (dict, type(None))) and not truth + and run.get("state") != "launching" and not run.get("unpublished_child") + and (not token or (run.get("state") == "stopped" and run.get("tree_verified_empty") == token)) + and not held and (install is None or install["profile_fingerprint"] + == self.layout.profile.fingerprint)) + # I1: idle exactly when no process of the root is alive, no launch is pending, custody is known, the table + # was read and nothing else holds the port. + self.assertEqual(expected_idle, verdict.idle, verdict) + if readable and verdict.row not in ("unreadable-record",): + self.assertEqual(truth, {proc.pid for proc in verdict.live.values()}, verdict) + # I4: the status document carries the verdict, and its state is idle exactly when the verdict is. + reported = lifecycle.status(self.layout) + self.assertEqual(verdict.idle, reported["state"] in lifecycle.IDLE_STATES, reported) + if not (verdict.row == "server-live" and verdict.state == "healthy"): + self.assertEqual(verdict.state, reported["state"]) + # I3: start passes its root checks exactly when the verdict is idle, and refuses with the verdict's reason. + admitted = None + try: + lifecycle.start(self.layout, tool_argv=[sys.executable], log=lambda line: None) + except Admitted: + admitted = True + except lifecycle.LifecycleError as exc: + admitted = False + self.assertEqual(verdict.refusal, str(exc)) + self.assertEqual(verdict.idle, admitted) + try: + lifecycle.idle_generation(self.layout) + accepted = True + except lifecycle.LifecycleError: + accepted = False + self.assertTrue(not accepted or verdict.quiescent, verdict) + self.assertTrue(not accepted or not run or (run.get("tree_verified_empty") == token and token), verdict) + # I2: stop ends exactly the verdict's live set; I5: no status problem advises a stop that refuses. + terminated.clear() + recorded_alive = {proc.pid for role, identity in lifecycle.recorded_processes(run) + if identity and (proc := world.get(int(identity["pid"]))) is not None + and procs.same_identity(proc, identity)} + try: + lifecycle.stop(self.layout, log=lambda line: None) + refused = False + except lifecycle.LifecycleError: + refused = True + advises = any("run `stop`" in problem for problem in verdict.problems) + self.assertFalse(refused and advises, verdict) + if refused: + self.assertTrue(verdict.row in STOP_REFUSES or (token and not lifecycle.WINDOWS), verdict) + if verdict.row == "unreadable-table": + self.assertLessEqual(set(terminated), recorded_alive) + if isinstance(record, dict) and not run.get("unpublished_child") and not token: + self.assertEqual("stop_incomplete", read_json(self.layout.run_record)["state"]) + return verdict.row + self.assertEqual({proc.pid for proc in verdict.live.values()}, set(terminated), verdict) + after = lifecycle.verdict(self.layout) + self.assertEqual({}, after.live, after) + self.assertNotIn(after.row, ("launch-pending", "launch-abandoned"), after) + self.assertTrue(after.idle or after.state == "mismatched" or after.row == "port-held", after) + return verdict.row + + +@unittest.skipIf(procs.WINDOWS, "POSIX ps boundary; native Windows is unexercised") +class ProcessTableTests(unittest.TestCase): + def test_malformed_ps_rows_are_left_out_without_losing_valid_rows(self): + text = ("987654321 1 Fri Nov 13 12:34:56 2026 /fixture/path with spaces/python\n" + "truncated\n" + "not-a-pid 1 Fri Nov 13 12:34:56 2026 /fixture/python\n" + "987654320 not-a-parent Fri Nov 13 12:34:56 2026 /fixture/python\n") + self.assertEqual({987654321: procs.ProcInfo(987654321, 1, "Fri Nov 13 12:34:56 2026", + "/fixture/path with spaces/python")}, procs.parse_ps_table(text)) + + def test_failed_timed_out_or_empty_ps_is_unavailable_not_an_empty_census(self): + cases = (("failed", subprocess.CompletedProcess(["ps"], 1, "", "denied")), + ("timed out", subprocess.TimeoutExpired(["ps"], 10)), + ("empty", subprocess.CompletedProcess(["ps"], 0, "", ""))) + for name, result in cases: + with self.subTest(case=name), patch.object(procs.subprocess, "run") as run: + if isinstance(result, Exception): + run.side_effect = result + else: + run.return_value = result + with self.assertRaises(procs.TableUnavailable): + procs.table() + run.assert_called_once_with(["ps", "-A", "-o", "pid=,ppid=,lstart=,comm="], capture_output=True, + text=True, stdin=subprocess.DEVNULL, timeout=10) + + +def interruption_driver(root, data, point, role): + """Run the real writer in a killable process; only host checks and the stock server are substitutes.""" + layout = Layout(Path(root), Profile(PROFILE, data)) + + def wait_for(name): + deadline = time.monotonic() + 15 + while not (layout.root / name).exists(): + if time.monotonic() >= deadline: + raise RuntimeError(f"interruption driver timed out waiting for {name}") + time.sleep(0.01) + + def hold(): + (layout.root / "held").touch() + wait_for("release") + + real_write, real_info = lifecycle.atomic_write_json, procs.info + + def write(path, value): + state = value.get("state") + if role == "start" and point == 0 and state == "launching": + hold() + real_write(path, value) + if role == "start" and ((point == 1 and state == "launching") or (point == 6 and state == "ready")): + hold() + if role == "serve" and ((point == 3 and value.get("unpublished_child")) + or (point == 5 and value.get("server") and state == "starting") + or (point == 8 and state == "exited")): + hold() + + def info(pid, **kwargs): + result = real_info(pid, **kwargs) + if role == "serve" and pid != os.getpid(): + (layout.root / "server.pid").write_text(str(pid)) + if point == 4: + hold() + return result + + def dispatch(argv, **kwargs): + atomic_write_json(layout.root / "dispatch.json", {"launch_id": argv[-1]}) + wait_for("dispatched") + if point in (2, 3, 4, 5, 8): + (layout.root / "launcher-held").touch() + wait_for("launcher-release") + + def health(*args, **kwargs): + if point == 7: + raise lifecycle.LifecycleError("injected readiness failure") + return {"ready": True, "problems": []} + + real_terminate = procs.terminate + + def terminate(proc, timeout): + if point == 7: + hold() # The real failure cleanup entered stop, before its first process effect. + return real_terminate(proc, timeout) + + with patch.object(lifecycle, "atomic_write_json", side_effect=write), \ + patch.object(procs, "info", side_effect=info), \ + patch.object(lifecycle, "read_key", return_value="x" * 32): + if role == "serve": + if point == 2: + (layout.root / "wrapper-waiting").touch() + wait_for("wrapper-release") + engine = layout.strata / "engine" / "strata" + argv = ["/bin/sh", "-c", '"$1" -c "import time; time.sleep(600)" & echo $! > "$2"; wait', + "stub-server", str(engine), str(layout.root / "engine.pid")] + with patch.object(lifecycle, "server_argv", return_value=argv): + try: + lifecycle.serve(layout, log_path=layout.logs / "server.log", + launch_id=read_json(layout.root / "dispatch.json")["launch_id"]) + except lifecycle.LifecycleError as exc: + (layout.root / "refused").write_text(str(exc)) + raise + else: + with patch.object(lifecycle, "verify_install_fast", return_value=read_json(layout.install_record)), \ + patch.object(lifecycle, "gpu_facts", return_value={}), \ + patch.object(lifecycle, "gpu_busy", return_value=None), \ + patch.object(procs, "memory", return_value={"available": 1 << 40}), \ + patch.object(lifecycle, "_launch_detached", side_effect=dispatch), \ + patch.object(lifecycle, "runtime_checks", side_effect=health), \ + patch.object(procs, "terminate", side_effect=terminate): + lifecycle.start(layout, tool_argv=[sys.executable], log=lambda line: None) + + +@unittest.skipIf(procs.WINDOWS, "POSIX interruption drivers; native Windows is unexercised") +class InterruptionWalk(unittest.TestCase): + def wait_for(self, predicate, detail): + deadline = time.monotonic() + 15 + while not predicate(): + if time.monotonic() >= deadline: + self.fail(f"timed out waiting for {detail}") + time.sleep(0.01) + + def test_every_interruption_preserves_a_nonidle_verdict_until_custody_is_resolved(self): + started = time.monotonic() + for point, expected in enumerate(("idle", "launch-abandoned", "launch-abandoned", "custody-unknown", + "custody-unknown", "server-live", "server-live", "server-live", "orphans")): + with self.subTest(point=f"P{point}"), tempfile.TemporaryDirectory() as directory: + data = single_gpu_data() + data["server"].update(port=free_port(), stop_timeout_s=2) + layout = Layout(Path(directory) / "root", Profile(PROFILE, data)) + layout.strata.mkdir(parents=True) + engine = layout.strata / "engine" / "strata" + engine.parent.mkdir() + shutil.copy(procs.info(os.getpid()).exe, engine) + atomic_write_json(layout.install_record, { + "profile_fingerprint": layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64}) + atomic_write_json(layout.strata_config, {"log": str(layout.root.resolve() / "engine.log")}) + children, identities = [], [] + killed = set() + + def spawn(role): + code = ("import json,sys; from tests.unit.test_lifecycle_states import interruption_driver; " + "interruption_driver(sys.argv[1],json.loads(sys.argv[2]),int(sys.argv[3]),sys.argv[4])") + output = open(layout.root / (role + ".log"), "wb") + try: + child = subprocess.Popen([sys.executable, "-c", code, str(layout.root), json.dumps(data), + str(point), role], stdin=subprocess.DEVNULL, + stdout=output, stderr=subprocess.STDOUT) + finally: + output.close() + children.append(child) + threading.Thread(target=child.wait, daemon=True).start() + return child + + def marker(name): + def ready(): + if (layout.root / name).exists(): + return True + for child in children: + if child not in killed and child.poll() is not None: + logs = "\n".join(path.read_text() for path in layout.root.glob("*.log")) + self.fail(f"P{point} driver exited before {name}:\n{logs}") + return False + self.wait_for(ready, f"P{point} {name}") + + def kill(child): + killed.add(child) + if child.poll() is None: + child.kill() + child.wait(timeout=5) + + def observe(row): + verdict = lifecycle.verdict(layout) + self.assertIn(verdict.row, lifecycle.ROWS) + self.assertEqual(row, verdict.row, verdict) + self.assertEqual(point == 0, verdict.idle, verdict) + if verdict.idle: + self.assertFalse(verdict.live) + self.assertFalse(verdict.details.get("pending")) + return verdict + + try: + launcher = spawn("start") + wrapper = None + if point >= 2: + marker("dispatch.json") + wrapper = spawn("serve") + (layout.root / "dispatched").touch() + if point == 2: + marker("wrapper-waiting") + marker("launcher-held") + observe("launch-pending") + elif point == 8: + marker("launcher-held") + marker("server.pid") + else: + marker("held") + if point in (3, 4): + observe("wrapper-publishing") + if point >= 4: + marker("engine.pid") + for name in ("server", "engine"): + pid = int((layout.root / (name + ".pid")).read_text()) + self.wait_for(lambda: (proc := procs.info(pid)) is not None + and (name != "engine" or proc.exe == str(engine)), f"{name} exec") + identities.append(procs.info(pid)) + if point == 1: + observe("launch-pending") + kill(launcher) + if point in (3, 4, 5): + kill(wrapper) + if point == 8: + os.kill(identities[0].pid, signal.SIGKILL) + marker("held") # serve published the real child exit. + kill(wrapper) + verdict = observe(expected) + print(f"\nP{point}: {verdict.row} ({verdict.state}), idle={verdict.idle}", file=sys.stderr) + if point == 2: + lifecycle.stop(layout, log=lambda line: None) + (layout.root / "wrapper-release").touch() + wrapper.wait(timeout=5) + self.assertNotEqual(0, wrapper.returncode) + self.assertIn("generation changed or stopped", (layout.root / "refused").read_text()) + self.assertEqual("idle", lifecycle.verdict(layout).row) + self.assertFalse((layout.root / "server.pid").exists()) + print("P2 fenced: idle; late wrapper refused without spawning", file=sys.stderr) + elif point in (3, 4): + with self.assertRaisesRegex(lifecycle.LifecycleError, "unpublished child"): + lifecycle.stop(layout, log=lambda line: None) + elif point >= 5: + lifecycle.stop(layout, log=lambda line: None) + self.assertTrue(lifecycle.verdict(layout).idle) + finally: + # Deepest first: the shell reaps its engine, serve reaps the shell, and our waiters reap drivers. + for proc in reversed(identities): + if procs.matches(proc.as_dict()): + self.assertTrue(procs.terminate(proc, 2), f"leftover process {proc}") + for child in reversed(children): + kill(child) + for proc in identities: + self.assertIsNone(procs.matches(proc.as_dict()), f"leftover process {proc}") + print(f"\ninterruption walk: P0-P8 in {time.monotonic() - started:.2f} s", file=sys.stderr) + + +@unittest.skipIf(procs.WINDOWS, "POSIX process fixture; native Windows is unexercised") +class CensusResidualTests(unittest.TestCase): + def test_an_unrecorded_process_outside_the_runtime_is_not_counted_or_stopped(self): + with tempfile.TemporaryDirectory() as directory: + data = single_gpu_data() + data["server"]["port"] = free_port() + layout = Layout(Path(directory), Profile(PROFILE, data)) + child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) + try: + # The child has no recorded ancestor, executes outside the runtime and does not hold its port. + before = lifecycle.verdict(layout) + self.assertEqual("idle", before.row) + self.assertEqual({}, before.live) + self.assertEqual([], lifecycle.stop(layout, log=lambda line: None)["stopped"]) + self.assertIsNone(child.poll()) + self.assertFalse(layout.run_record.exists()) + finally: + child.kill() + child.wait(timeout=5) + self.assertIsNone(procs.info(child.pid)) + + +if __name__ == "__main__": + unittest.main() From 8b75d5c13fc7e13860e7532ebda7eb6f22876db4 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:08:38 -0800 Subject: [PATCH 04/15] test(cli): reject impossible install recovery advice --- tests/unit/test_lifecycle.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tests/unit/test_lifecycle.py b/tests/unit/test_lifecycle.py index de3b910..00363ba 100644 --- a/tests/unit/test_lifecycle.py +++ b/tests/unit/test_lifecycle.py @@ -743,6 +743,29 @@ def killed_start(): common.read_json(self.layout.run_record)["state"])) self.assertEqual(before, self.layout.run_record.read_bytes()) + def test_install_does_not_advise_stop_when_the_verdict_requires_reconciliation_or_a_retry(self): + from omp_strata import cli + args = cli.build_parser().parse_args(["install", "--profile", str(self.layout.profile.path), + "--root", str(self.layout.root)]) + self.layout.run_record.parent.mkdir(parents=True, exist_ok=True) + for case in ("unreadable record", "unreadable table", "unknown custody"): + with self.subTest(case=case): + if case == "unreadable record": + self.layout.run_record.write_text("{") + else: + common.atomic_write_json(self.layout.run_record, + {"state": "starting", "unpublished_child": True} + if case == "unknown custody" else {}) + with patch.object(lifecycle, "process_table", return_value={}, + side_effect=procs.TableUnavailable("unreadable table") + if case == "unreadable table" else None), \ + patch.object(cli.install_mod, "install") as install, \ + patch.object(cli.nvfp4, "staging_preflight"), \ + self.assertRaises(lifecycle.LifecycleError) as raised: + cli.cmd_install(args) + install.assert_not_called() + self.assertNotIn("run `stop`", str(raised.exception)) + def test_fetch_checks_remaining_space_before_any_download(self): items = fetch.plan(self.layout, platform="linux-x64") total = sum(item.bytes for item in items) From 0717e0fe8bf90ce4a838d386629f21cb49157327 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:08:47 -0800 Subject: [PATCH 05/15] fix(cli): preserve the verdict recovery advice during install --- omp_strata/cli.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/omp_strata/cli.py b/omp_strata/cli.py index ca0a75a..0331d9e 100644 --- a/omp_strata/cli.py +++ b/omp_strata/cli.py @@ -106,8 +106,7 @@ def cmd_install(args: argparse.Namespace) -> int: lifecycle.idle_generation(layout, expected=args.idle_generation) root = lifecycle.verdict(layout) if not root.quiescent: - raise lifecycle.LifecycleError(f"install refused: the root is {root.state} (" - + "; ".join(root.problems) + "); run `stop` for this root first") + raise lifecycle.LifecycleError(f"install refused: the root is {root.state}; {root.refusal}") record = install_mod.install(layout, log=eprint) _print({k: record[k] for k in ("profile_id", "runtime_identity_sha256", "strata_commit", "mtp_tensor_manifest_sha256", "python")}) From 56f0db83655cd57a5ff8a43da841e24a33f09d92 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:20:03 -0800 Subject: [PATCH 06/15] fix(lifecycle): preserve the documented port refusal source phrase --- omp_strata/lifecycle.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/omp_strata/lifecycle.py b/omp_strata/lifecycle.py index 3aaa341..1db8e47 100644 --- a/omp_strata/lifecycle.py +++ b/omp_strata/lifecycle.py @@ -1458,8 +1458,8 @@ def verdict(layout: Layout) -> Verdict: refusal=CUSTODY_REFUSAL, run=run) srv = layout.profile.data["server"] if port_in_use(srv["listen_host"], srv["port"]): - message = (f"{srv['listen_host']}:{srv['port']} is occupied by a process this integration does not own; " - "refusing to start or adopt it") + message = (f"{srv['listen_host']}:{srv['port']} is occupied by a process this integration " + "does not own; refusing to start or adopt it") return Verdict("port-held", "degraded", [message], quiescent=True, refusal=message, run=run) if install is None: return Verdict("idle", "not_installed", quiescent=True, run=run) From 19e7e5c10349826380762e6864604e7e906a11c9 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:45:49 -0800 Subject: [PATCH 07/15] test(lifecycle): reproduce PID reuse during stop rechecks --- tests/unit/test_lifecycle_states.py | 75 +++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py index b3283b4..79d935e 100644 --- a/tests/unit/test_lifecycle_states.py +++ b/tests/unit/test_lifecycle_states.py @@ -246,6 +246,81 @@ def check(self, record, truth, readable, held, install, world, terminated): return verdict.row +class StopIdentityWalk(unittest.TestCase): + def setUp(self): + directory = self.enterContext(tempfile.TemporaryDirectory()) + data = single_gpu_data() + data["server"].update(port=free_port(), stop_timeout_s=0) + self.layout = Layout(Path(directory), Profile(PROFILE, data)) + self.install = {"profile_fingerprint": self.layout.profile.fingerprint, + "runtime_identity_sha256": "a" * 64} + atomic_write_json(self.layout.install_record, self.install) + + def walk(self, event, reverse=False, reused_pid=10, generations=1): + """Termination can re-issue an ended PID, not just delete a process from a fixed world.""" + engine = str(self.layout.strata / "engine" / "strata") + original = {10: ident(10, 1, engine), 11: ident(11, 10, engine)} + world = dict(reversed(list(original.items()))) if reverse else dict(original) + ended, snapshots = [], [] + issued = 0 + + def table(): + snapshots.append(dict(world)) + return dict(world) + + def terminate(proc, timeout): + nonlocal issued + self.assertEqual(proc, world.pop(proc.pid), "stop tried to terminate a stale identity") + ended.append(proc) + if not world and event != "none" and issued < generations: + issued += 1 + previous = original[reused_pid] + created = f"{previous.created}-generation-{issued}" if event == "creation" else previous.created + exe = f"{engine}-{issued}" if event == "executable" else engine + world[reused_pid] = procs.ProcInfo(reused_pid, 1, created, exe) + return True + + atomic_write_json(self.layout.run_record, dict(self.install, state="ready")) + with patch.object(lifecycle, "process_table", side_effect=table), \ + patch.object(procs, "terminate", side_effect=terminate), \ + patch.object(lifecycle, "port_in_use", return_value=False): + result, failure = None, None + try: + result = lifecycle.stop(self.layout, log=lambda line: None) + except lifecycle.LifecycleError as exc: + failure = exc + after = lifecycle.verdict(self.layout) + self.assertFalse(result and result["state"] == "stopped" and after.live, + f"stop reported stopped while the verdict still counts {after.live}") + if event != "none": + self.assertNotEqual(original[reused_pid], snapshots[1][reused_pid]) + exhausted = event != "none" and generations == 2 + self.assertEqual(exhausted, failure is not None) + self.assertEqual(exhausted, bool(after.live)) + self.assertEqual("stop_incomplete" if exhausted else "stopped", read_json(self.layout.run_record)["state"]) + self.assertEqual(2 + (event != "none"), len(ended)) + if exhausted: + self.assertIn("still alive after stop", str(failure)) + else: + self.assertTrue(after.idle) + return len(snapshots) + + def test_stop_never_reports_stopped_while_a_reused_pid_is_still_counted(self): + for event in ("creation", "executable"): + with self.subTest(identity_change=event): + self.walk(event) + + def test_stop_identity_walk_reissues_ended_pids_between_passes(self): + started, snapshots, cases = time.monotonic(), 0, 0 + for event, reverse, pid, generations in itertools.product( + ("none", "creation", "executable"), (False, True), (10, 11), (1, 2)): + with self.subTest(event=event, reverse=reverse, pid=pid, generations=generations): + snapshots += self.walk(event, reverse, pid, generations) + cases += 1 + print(f"\nstop identity walk: {cases} schedules, {snapshots} snapshots in " + f"{time.monotonic() - started:.3f} s", file=sys.stderr) + + @unittest.skipIf(procs.WINDOWS, "POSIX ps boundary; native Windows is unexercised") class ProcessTableTests(unittest.TestCase): def test_malformed_ps_rows_are_left_out_without_losing_valid_rows(self): From 999535b39b023d553d4d2da8468f57b7c9cd0b71 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:45:58 -0800 Subject: [PATCH 08/15] fix(lifecycle): remember full process identities across stop passes --- omp_strata/lifecycle.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/omp_strata/lifecycle.py b/omp_strata/lifecycle.py index 1db8e47..204e362 100644 --- a/omp_strata/lifecycle.py +++ b/omp_strata/lifecycle.py @@ -2187,8 +2187,8 @@ def status(layout: Layout) -> dict: def _stop_order(live: dict[str, procs.ProcInfo]) -> list[tuple[str, procs.ProcInfo]]: - """Deepest first: unrecorded processes (descendants already deepest first), then recorded processes other than - the server and the wrapper, then the server, then the wrapper.""" + """Descendants (already deepest first) and census members (in table order), then other recorded processes, + then the server, then the wrapper.""" def rank(role: str) -> int: if role.startswith(("descendant[", "unrecorded[")): return 0 @@ -2252,13 +2252,18 @@ def _stop() -> dict: # The verdict's live set: every recorded process alive, the current descendants of each (the real interpreter # behind the venv redirector, any engine a server restarted) and every unrecorded process running the root's # runtime. With the process table unreadable only recorded identities, each verified on its own, are ended. - done: set[int] = set() + def identity(proc: procs.ProcInfo) -> tuple[int, str, str]: + return proc.pid, proc.created, proc.exe.lower() if procs.WINDOWS else proc.exe + + # A new process can take an ended PID between passes; only the same full identity is already done. + done: set[tuple[int, str, str]] = set() live, under = (_verifiable(run), {}) if unreadable else (root.live, root.under) for attempt in range(2): for role, proc in _stop_order(live): - if proc.pid in done: + key = identity(proc) + if key in done: continue - done.add(proc.pid) + done.add(key) label = _stop_label(role, proc, under) try: if procs.terminate(proc, timeout): @@ -2271,7 +2276,7 @@ def _stop() -> dict: break # A server can start an engine while its tree is being ended: what is still alive gets one more pass. again = verdict(layout) - live = {role: proc for role, proc in again.live.items() if proc.pid not in done} + live = {role: proc for role, proc in again.live.items() if identity(proc) not in done} under = again.under if not live: break @@ -2294,7 +2299,7 @@ def _stop() -> dict: extra = {} if layout.profile.multi_gpu: recorded = {r["pid"] for r in [run.get("engine"), *run.get("server_tree", [])] if r} - cards = card_observations(layout.profile, owned_pids=done | recorded) + cards = card_observations(layout.profile, owned_pids={pid for pid, _, _ in done} | recorded) released = all(card["owned_count"] == 0 for card in cards) extra = {"cards": cards, "owned_gpus_released": released} return {"state": "stopped", "stopped": stopped, **extra} From 0defcd9f46412a221247949cde1ea0379a827d9b Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:57:05 -0800 Subject: [PATCH 09/15] test(procs): reproduce stale parent attribution after PID reuse --- tests/unit/test_lifecycle_states.py | 46 +++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py index 79d935e..897a16b 100644 --- a/tests/unit/test_lifecycle_states.py +++ b/tests/unit/test_lifecycle_states.py @@ -7,6 +7,7 @@ """ from __future__ import annotations +import ast import itertools import json import os @@ -18,6 +19,7 @@ import tempfile import threading import time +from types import SimpleNamespace import unittest from unittest.mock import patch @@ -321,6 +323,50 @@ def test_stop_identity_walk_reissues_ended_pids_between_passes(self): f"{time.monotonic() - started:.3f} s", file=sys.stderr) +class WindowsSnapshotIdentityTests(unittest.TestCase): + def setUp(self): + # Execute the unchanged Windows function body without loading kernel32 on this host. Its snapshot and + # identity-query boundaries are fakes; table's attribution policy is the production code. + source = ast.parse(Path(procs.__file__).read_text()) + branch = next(node for node in source.body + if isinstance(node, ast.If) and isinstance(node.test, ast.Name) and node.test.id == "WINDOWS") + function = next(node for node in branch.body if isinstance(node, ast.FunctionDef) and node.name == "table") + self.namespace = dict(vars(procs)) + exec(compile(ast.Module(body=[function], type_ignores=[]), procs.__file__, "exec"), self.namespace) + self.table = self.namespace["table"] + self.cutoff = 116444736000000000 + 1234567890 + self.events = [] + self.namespace["time"] = SimpleNamespace(time_ns=self.clock) + + def clock(self): + self.events.append("clock") + return 123456789000 + + def snapshot(self): + self.events.append("snapshot") + return {11: (10, "old-child.exe")} + + def queried(self, created): + self.namespace["_snapshot"] = self.snapshot + self.namespace["info"] = lambda pid, *, ppid: procs.ProcInfo(pid, ppid, str(created), "/unrelated/python") + return self.table() + + def test_a_reused_pid_created_after_the_snapshot_is_not_attributed_to_the_old_parent(self): + parent = procs.ProcInfo(10, 1, str(self.cutoff - 10), "/root/server") + table = {10: parent, **self.queried(self.cutoff + 1)} + with patch.object(procs, "WINDOWS", True): + descendants, _ = lifecycle._descendants(table, {"server": parent}) + self.assertNotIn("descendant[11]", descendants, + "a new unrelated process inherited the old snapshot row's parent") + self.assertNotIn(11, table) + self.assertEqual(["clock", "snapshot"], self.events) + + def test_snapshot_creation_boundary_keeps_before_and_equal_but_not_later_identities(self): + for delta in (-1, 0, 1): + with self.subTest(filetime_ticks_from_snapshot=delta): + self.assertEqual(delta <= 0, 11 in self.queried(self.cutoff + delta)) + + @unittest.skipIf(procs.WINDOWS, "POSIX ps boundary; native Windows is unexercised") class ProcessTableTests(unittest.TestCase): def test_malformed_ps_rows_are_left_out_without_losing_valid_rows(self): From 0072d968d5e5841f729e0d66dc5fea57a8bebdb3 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 14:57:15 -0800 Subject: [PATCH 10/15] fix(procs): reject identities created after the Windows snapshot --- omp_strata/procs.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/omp_strata/procs.py b/omp_strata/procs.py index 385961e..14bb502 100644 --- a/omp_strata/procs.py +++ b/omp_strata/procs.py @@ -103,10 +103,13 @@ def table() -> dict[int, ProcInfo]: """Every process from one Toolhelp snapshot, identified as `info` identifies one. A snapshot that fails or lists nothing raises TableUnavailable. A process whose creation time or image cannot be read (protected system processes refuse even limited query access) is left out: this user's processes are readable.""" + # Both are UTC system time: time_ns uses the Unix epoch; GetProcessTimes uses 100 ns since 1601. + # A later-created process may have reused the snapshot's PID and must not inherit its old parent. + snapshot_at = time.time_ns() // 100 + 116444736000000000 out: dict[int, ProcInfo] = {} for pid, (ppid, _) in _snapshot().items(): proc = info(pid, ppid=ppid) - if proc is not None and proc.exe: + if proc is not None and proc.exe and int(proc.created) <= snapshot_at: out[pid] = proc return out From 2eaa217eec9d655c444421d278649169664fb977 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 15:59:13 -0800 Subject: [PATCH 11/15] test(lifecycle): expose evidence and custody admission gaps --- tests/unit/test_lifecycle_states.py | 262 +++++++++++++++++++++++++++- 1 file changed, 261 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py index 897a16b..ed581ca 100644 --- a/tests/unit/test_lifecycle_states.py +++ b/tests/unit/test_lifecycle_states.py @@ -8,6 +8,7 @@ from __future__ import annotations import ast +import contextlib import itertools import json import os @@ -23,7 +24,7 @@ import unittest from unittest.mock import patch -from omp_strata import lifecycle, procs +from omp_strata import cli, lifecycle, nvfp4, procs, remote from omp_strata.common import atomic_write_json, read_json from omp_strata.layout import Layout from omp_strata.profile import Profile @@ -248,6 +249,223 @@ def check(self, record, truth, readable, held, install, world, terminated): return verdict.row +class EvidenceAndCustodyWalk(unittest.TestCase): + """Cross evidence failures, later observations and native custody without native effects.""" + setUp = StateTableWalk.setUp + + def world(self): + self.records, self.processes = {}, {} + self.reads, self.ended = [], [] + self.schedule = (True, True, True) + self.replace = self.held = self.missing_job = False + self.layout.run_record.touch() + self.layout.install_record.touch() + + def load(path): + value = self.records[path] + if isinstance(value, Exception): + raise value + return json.loads(value) + + def save(path, value): + self.records[path] = json.dumps(value) + + def table(): + index = len(self.reads) + readable = self.schedule[min(index, 2)] + if index == 1 and self.replace: + self.processes[20] = procs.ProcInfo(20, 1, "replacement", self.engine_exe) + self.reads.append((readable, dict(self.processes))) + if not readable: + raise procs.TableUnavailable("fixture census unavailable") + return dict(self.processes) + + def terminate(proc, timeout): + self.ended.append(proc.pid) + self.processes.pop(proc.pid, None) + return True + + def job(token, **kwargs): + if self.missing_job: + raise lifecycle.MissingProcessJob("fixture job gone") + return SimpleNamespace(token=token, stop=lambda timeout: None, close=lambda: None) + + for active in ( + patch.object(lifecycle, "read_json", side_effect=load), + patch.object(lifecycle, "atomic_write_json", side_effect=save), + patch.object(lifecycle, "process_table", side_effect=table), + patch.object(procs, "terminate", side_effect=terminate), + patch.object(procs, "matches", side_effect=lambda rec: self.processes.get(rec["pid"]) if rec else None), + patch.object(procs, "descendants", return_value=[]), + patch.object(lifecycle, "port_in_use", side_effect=lambda *args: self.held), + patch.object(remote, "listener_pids", return_value={99}), + patch.object(lifecycle, "read_key", return_value="x" * 32), + patch.object(lifecycle, "runtime_checks", return_value={"problems": []}), + patch.object(lifecycle, "verify_install_fast", side_effect=Admitted), + patch.object(lifecycle, "FileLock", return_value=contextlib.nullcontext())): + self.enterContext(active) + mocked_job = self.enterContext(patch.object(lifecycle, "ProcessJob", side_effect=job)) + mocked_job.scan.return_value = {} + + def configure(self, run_kind="valid", install_kind="valid", token="none", alive=True, held=False): + self.reads.clear() + self.ended.clear() + self.processes.clear() + self.held = held + install = {"profile_fingerprint": self.layout.profile.fingerprint, "runtime_identity_sha256": "a" * 64} + run = dict(install, state="ready", server=self.p["server"].as_dict()) + if token != "none": + run["tree_token"] = TOKEN + if token == "proved": + run.update(state="stopped", tree_verified_empty=TOKEN) + if alive: + self.processes[12] = self.p["server"] + self.processes[20] = ident(20, 1, self.engine_exe) + faults = {"corrupt": "{", "io": PermissionError("fixture record unreadable"), + "null": "null", "list": "[]", "scalar": "42"} + self.records[self.layout.run_record] = faults.get(run_kind, json.dumps(run)) + if install_kind == "other": + install["profile_fingerprint"] = "other" + self.records[self.layout.install_record] = faults.get(install_kind, json.dumps(install)) + return run + + def stop_result(self): + try: + return lifecycle.stop(self.layout, log=lambda line: None), None + except lifecycle.LifecycleError as exc: + return None, exc + + def test_stop_requires_its_last_census_to_be_read_and_empty(self): + self.world() + for schedule in ((False, True, True), (True, False, True), (True, True, False)): + with self.subTest(schedule=schedule), patch.object(lifecycle, "WINDOWS", True): + self.configure(token="unproved") + self.schedule, self.replace = schedule, True + result, failure = self.stop_result() + self.assertIsNone(result) + self.assertIsNotNone(failure) + saved = json.loads(self.records[self.layout.run_record]) + self.assertEqual("stop_incomplete", saved["state"]) + self.assertNotIn("tree_verified_empty", saved) + + def test_missing_windows_job_does_not_hide_census_cleanup(self): + self.world() + self.configure(token="unproved") + self.missing_job = True + with patch.object(lifecycle, "WINDOWS", True): + result, failure = self.stop_result() + self.assertIsNone(failure) + self.assertEqual("stopped", result["state"]) + self.assertEqual({12, 20}, set(self.ended)) + + def test_mismatched_install_never_bypasses_retained_job_proof(self): + self.world() + for token in ("unproved", "proved"): + with self.subTest(token=token): + self.configure(install_kind="other", token=token, alive=False) + self.assertEqual(token == "proved", lifecycle.verdict(self.layout).quiescent) + + def test_relative_executable_never_acquires_ownership_from_cwd(self): + self.world() + self.configure(alive=False) + self.layout.strata.mkdir(parents=True) + self.processes[99] = ident(99, 1, "python") + with contextlib.chdir(self.layout.strata): + root = lifecycle.verdict(self.layout) + result, failure = self.stop_result() + self.assertEqual({}, root.live) + self.assertEqual([], self.ended) + self.assertIsNone(failure) + self.assertEqual("stopped", result["state"]) + + def test_record_faults_block_admission_but_preserve_available_cleanup(self): + self.world() + for which, kind in itertools.product(("run", "install"), ("corrupt", "io", "null", "list", "scalar")): + with self.subTest(record=which, fault=kind): + self.configure(**{which + "_kind": kind}) + root = lifecycle.verdict(self.layout) + self.assertEqual("unreadable-record", root.row) + self.assertFalse(root.quiescent or root.idle) + self.reads.clear() + result, failure = self.stop_result() + self.assertIsNone(result) + self.assertIsNotNone(failure) + self.assertIn(20, self.ended) + if which == "install": + self.assertIn(12, self.ended) + + def test_port_holder_outside_census_blocks_install_and_names_pid(self): + self.world() + self.configure(alive=False, held=True) + self.processes[99] = ident(99, 1, "/base/python") + root = lifecycle.verdict(self.layout) + self.assertEqual({}, root.live) + self.assertFalse(root.quiescent) + self.assertIn("99", root.refusal) + self.assertIn("change the port", root.refusal) + with patch.object(cli, "_layout", return_value=self.layout), patch.object(cli.install_mod, "install") as install: + with self.assertRaises(lifecycle.LifecycleError): + cli.cmd_install(SimpleNamespace(idle_generation=None)) + install.assert_not_called() + + def test_advice_on_both_platforms_including_healthy_stray_status(self): + self.world() + seen = set() + for windows, missing, token, state, unpublished, alive in itertools.product( + (False, True), (False, True), ("none", "unproved", "proved"), + ("launching", "starting", "ready", "stop_incomplete"), (False, True), (False, True)): + with self.subTest(case=(windows, missing, token, state, unpublished, alive)), \ + patch.object(lifecycle, "WINDOWS", windows): + run = self.configure(token=token, alive=alive) + run.update(state=state, unpublished_child=unpublished) + self.records[self.layout.run_record] = json.dumps(run) + self.missing_job = missing + root = lifecycle.verdict(self.layout) + report = lifecycle.status(self.layout) + seen.add(root.row) + texts = [root.refusal or "", *root.problems, *report.get("problems", [])] + advises = any("run `stop`" in text or "use stop" in text or "status/stop" in text + or "`stop` ends" in text for text in texts) + self.reads.clear() + _, failure = self.stop_result() + self.assertFalse(advises and failure, texts) + if state == "ready" and alive and not unpublished: + self.assertTrue(any("outside its recorded trees" in text for text in report["problems"])) + self.assertIn("server-live", seen) + + def test_extended_product_preserves_all_three_properties(self): + self.world() + faults = ("valid", "corrupt", "io", "null", "list", "scalar") + failures, cases, started = [], 0, time.monotonic() + for run_kind, install_kind, token, windows, missing, alive, held, schedule in itertools.product( + faults, (*faults, "other"), ("none", "unproved", "proved"), (False, True), (False, True), + (False, True), (False, True), tuple(itertools.product((False, True), repeat=3))): + cases += 1 + with patch.object(lifecycle, "WINDOWS", windows): + self.configure(run_kind, install_kind, token, alive, held) + self.schedule, self.replace, self.missing_job = schedule, alive, missing + case = (run_kind, install_kind, token, windows, missing, alive, held, schedule) + try: + root = lifecycle.verdict(self.layout) + valid = run_kind == "valid" and install_kind in ("valid", "other") + if root.quiescent and not (valid and schedule[0] and token != "unproved" and not held): + raise AssertionError("quiescent without complete evidence, custody or port proof") + texts = [root.refusal or "", *root.problems] + advises = any("run `stop`" in t or "use stop" in t or "status/stop" in t for t in texts) + self.reads.clear() + result, failure = self.stop_result() + if result and not (self.reads and self.reads[-1] == (True, {})): + raise AssertionError("stopped without a final read empty census") + # Advice uses the same initial evidence; later failures are not the same state. + if advises and failure and all(schedule): + raise AssertionError("advised stop refuses the same state") + except Exception as exc: + if len(failures) < 12: + failures.append((case, type(exc).__name__, str(exc))) + print(f"\nextended evidence walk: {cases} combinations in {time.monotonic() - started:.2f} s", file=sys.stderr) + self.assertEqual([], failures) + + class StopIdentityWalk(unittest.TestCase): def setUp(self): directory = self.enterContext(tempfile.TemporaryDirectory()) @@ -369,6 +587,12 @@ def test_snapshot_creation_boundary_keeps_before_and_equal_but_not_later_identit @unittest.skipIf(procs.WINDOWS, "POSIX ps boundary; native Windows is unexercised") class ProcessTableTests(unittest.TestCase): + def test_same_executable_pid_reuse_inside_one_second_is_distinguished(self): + text = "987654321 1 Fri Nov 13 12:34:56 2026 /fixture/python\n" + first = procs.parse_ps_table(text)[987654321] + replacement = procs.parse_ps_table(text)[987654321] + self.assertFalse(procs.same_identity(replacement, first.as_dict())) + def test_malformed_ps_rows_are_left_out_without_losing_valid_rows(self): text = ("987654321 1 Fri Nov 13 12:34:56 2026 /fixture/path with spaces/python\n" "truncated\n" @@ -393,6 +617,42 @@ def test_failed_timed_out_or_empty_ps_is_unavailable_not_an_empty_census(self): text=True, stdin=subprocess.DEVNULL, timeout=10) +class StagingPreflightReadOnlyTests(unittest.TestCase): + def test_preflight_only_reads_for_absent_unprepared_and_prepared_roots(self): + with tempfile.TemporaryDirectory() as directory: + data = single_gpu_data() + data["model"]["conversion"] = nvfp4.conversion_pin(next(iter(nvfp4.RECIPES.values()))[0]) + layout = Layout(Path(directory) / "root", Profile(PROFILE, data)) + + def snapshot(): + return {str(path.relative_to(layout.root)): path.read_bytes() if path.is_file() else None + for path in layout.root.rglob("*")} if layout.root.exists() else None + + with patch.object(nvfp4.shutil, "disk_usage", return_value=SimpleNamespace(free=10**15)): + for state in ("absent", "unprepared", "prepared"): + with self.subTest(state=state): + if state == "unprepared": + layout.root.mkdir() + (layout.root / "retained").write_bytes(b"unchanged") + elif state == "prepared": + base = nvfp4.prepared_dir(layout) + for name in ("dense.gguf", "ple-nvfp4.gguf", "pack/experts.bin", "pack/dense.bin", + "pack/index.txt", "pack/native_experts.txt", "pack/tokenizer/vocab.json", + "mtp/rt/experts.bin", "mtp/rt/draft_vocab.bin"): + path = base / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"fixture") + atomic_write_json(base / "conversion-receipt.json", { + "input_fingerprint": lifecycle.sha256_bytes(lifecycle.canonical_json(data["model"])), + "recipe_commit": data["model"]["conversion"]["recipe_commit"], + "recipe_sha256": data["model"]["conversion"]["recipe_sha256"], + "weight_manifest_sha256": nvfp4.MANIFEST_SHA256, + "files": nvfp4.output_manifest(layout)}) + before = snapshot() + nvfp4.staging_preflight(layout) + self.assertEqual(before, snapshot()) + + def interruption_driver(root, data, point, role): """Run the real writer in a killable process; only host checks and the stock server are substitutes.""" layout = Layout(Path(root), Profile(PROFILE, data)) From 0ff258a7e15e89b6deb35be63681a2532016f411 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 16:07:45 -0800 Subject: [PATCH 12/15] test(lifecycle): record the declared POSIX one-second identity limit The preceding reproduction expected subsecond distinction from ps lstart. Pin the actual collision as the declared limit; native identity collection stays unchanged. --- tests/unit/test_lifecycle_states.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py index ed581ca..db30962 100644 --- a/tests/unit/test_lifecycle_states.py +++ b/tests/unit/test_lifecycle_states.py @@ -587,11 +587,12 @@ def test_snapshot_creation_boundary_keeps_before_and_equal_but_not_later_identit @unittest.skipIf(procs.WINDOWS, "POSIX ps boundary; native Windows is unexercised") class ProcessTableTests(unittest.TestCase): - def test_same_executable_pid_reuse_inside_one_second_is_distinguished(self): + def test_same_executable_pid_reuse_inside_one_second_is_not_distinguished(self): + # Declared POSIX limit: ps lstart cannot distinguish these two lifetimes. text = "987654321 1 Fri Nov 13 12:34:56 2026 /fixture/python\n" first = procs.parse_ps_table(text)[987654321] replacement = procs.parse_ps_table(text)[987654321] - self.assertFalse(procs.same_identity(replacement, first.as_dict())) + self.assertTrue(procs.same_identity(replacement, first.as_dict())) def test_malformed_ps_rows_are_left_out_without_losing_valid_rows(self): text = ("987654321 1 Fri Nov 13 12:34:56 2026 /fixture/path with spaces/python\n" From 2ac1c65208fbf8f60cc080e57fc4fa247710a11a Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 16:09:42 -0800 Subject: [PATCH 13/15] fix(lifecycle): require readable evidence and empty final custody Guard both records without discarding attributable cleanup. Recheck census success before publishing stopped, resolve retained jobs before quiescence, and block install on any occupied port. Share structural stop admission with recovery advice and reject relative executable attribution. --- omp_strata/lifecycle.py | 142 ++++++++++++++++++---------- tests/unit/test_lifecycle_states.py | 52 +++++++++- 2 files changed, 142 insertions(+), 52 deletions(-) diff --git a/omp_strata/lifecycle.py b/omp_strata/lifecycle.py index 204e362..7e7fe15 100644 --- a/omp_strata/lifecycle.py +++ b/omp_strata/lifecycle.py @@ -1289,7 +1289,7 @@ def _ps_quote(s: str) -> str: ROWS = ("unreadable-record", "unreadable-table", "custody-unknown", "launch-pending", "launch-abandoned", "wrapper-publishing", "mismatched", "server-live", "orphans", "job-unproved", "port-held", "idle") CUSTODY_REFUSAL = "unpublished child lifetime is unknown; retain custody for reconciliation" -PENDING_REFUSAL = "pending launch already owns this root; use stop before replacement" +PENDING_REFUSAL = "pending launch already owns this root" @dataclass @@ -1299,7 +1299,7 @@ class Verdict: problems: list[str] = field(default_factory=list) # Every process of the root found alive, recorded or not: exactly what `stop` ends. live: dict[str, procs.ProcInfo] = field(default_factory=dict) - # No process of the root alive, no launch pending, custody known: what `install` and `idle_generation` require. + # Readable evidence, no process/launch, proved custody and a free port: install and idle_generation admission. quiescent: bool = False refusal: str | None = None # why `start` must not act; None exactly when the root is idle details: dict = field(default_factory=dict) @@ -1326,7 +1326,7 @@ def recorded_processes(run: dict) -> list[tuple[str, dict | None]]: def runs_from(exe: str, base: Path) -> bool: """True when the executable lies inside `base`, compared as recorded and as resolved (case-blind on Windows).""" - if not exe: + if not exe or not os.path.isabs(exe): return False prefixes = {os.path.normcase(os.path.join(path, "")) for path in (str(base), os.path.realpath(base))} return any(os.path.normcase(path).startswith(prefix) @@ -1383,43 +1383,67 @@ def _describe(live: dict[str, procs.ProcInfo]) -> str: return ", ".join(f"{role} {Path(p.exe).name} pid {p.pid}" for role, p in sorted(live.items())) +def _stop_custody_refusal(run: dict) -> str | None: + """Structural stop admission, shared by the action and all recovery advice.""" + if run.get("tree_token") and not WINDOWS: + return "reconcile it on its Windows host" + if run.get("unpublished_child") and not run.get("tree_token"): + return CUSTODY_REFUSAL + return None + + +def _stop_advice(run: dict) -> str: + return _stop_custody_refusal(run) or "run `stop` for this root" + + def verdict(layout: Layout) -> Verdict: """The root's row in the closed state table, first match wins (docs/OPERATIONS.md, "Lifecycle states").""" - try: - run = read_json(layout.run_record) if layout.run_record.exists() else {} - except (OSError, ValueError): - run = None - if not isinstance(run, dict): - message = "run record unreadable; reconcile this root by hand" - return Verdict("unreadable-record", "degraded", [message], refusal=message) + errors = [] + + def record(path: Path, name: str, absent): + try: + value = read_json(path) + except FileNotFoundError: + return absent + except (OSError, ValueError): + value = None + if not isinstance(value, dict): + errors.append(name) + return absent + return value + + run = record(layout.run_record, "run", {}) + install = record(layout.install_record, "install", None) + details = {"unreadable_records": errors} if errors else {} + problems = [f"{name} record unreadable; reconcile this root by hand" for name in errors] try: table = process_table() except procs.TableUnavailable as exc: message = f"{exc}; custody unknown, so the root is not reported idle (retry `status`)" - return Verdict("unreadable-table", "degraded", [message], refusal=message, run=run) + return Verdict("unreadable-table", "degraded", [*problems, message], refusal=message, run=run, details=details) live = {role: proc for role, identity in recorded_processes(run) if (proc := _alive(identity, table))} descendants, under = _descendants(table, live) known = {**live, **descendants} owned = {**known, **_unrecorded(layout, table, known)} - found = {"details": {"live": sorted(owned)} if owned else {}, "run": run, "under": under, - "refusal": f"integration-owned processes already running ({', '.join(sorted(owned))}); use status/stop"} + found = {"details": {**details, **({"live": sorted(owned)} if owned else {})}, "run": run, "under": under, + "refusal": f"integration-owned processes already running ({', '.join(sorted(owned))}); {_stop_advice(run)}"} + if errors: + return Verdict("unreadable-record", "degraded", problems, owned, + **{**found, "refusal": "; ".join(problems)}) state = run.get("state") - # `stop` ends a process-tree (job) generation only on Windows; elsewhere such a root is reconciled on its host. - stopper = ("reconcile it on its Windows host" if run.get("tree_token") and not WINDOWS - else "run `stop` for this root") + stopper = _stop_advice(run) if run.get("unpublished_child"): if state == "starting" and "wrapper" in live: return Verdict("wrapper-publishing", "starting", [f"launch in progress: its wrapper (pid {live['wrapper'].pid}) is publishing its server"], owned, **{**found, "refusal": CUSTODY_REFUSAL, "details": {**found["details"], "pending": True}}) - advice = ("run `stop` to end its process-tree job" if WINDOWS and run.get("tree_token") - else "`stop` refuses until the root is reconciled by hand") return Verdict("custody-unknown", "degraded", - [f"the serve wrapper's child was never recorded and its lifetime is unknown; {advice}"], + [f"the serve wrapper's child was never recorded and its lifetime is unknown; {stopper}"], owned, **{**found, "refusal": CUSTODY_REFUSAL}) if state == "launching": - pending = {**found, "refusal": PENDING_REFUSAL, "details": {**found["details"], "pending": True}} + pending = {**found, "refusal": f"{PENDING_REFUSAL}; {stopper} before replacement", + "details": {**found["details"], "pending": True}} launcher = _alive(run.get("launcher"), table) if launcher is not None: return Verdict("launch-pending", "starting", @@ -1428,7 +1452,26 @@ def verdict(layout: Layout) -> Verdict: return Verdict("launch-abandoned", "degraded", ["launch abandoned before its wrapper published: its start command is gone and a dispatched " f"wrapper may still be waiting for the root lock; {stopper} to fence it"], owned, **pending) - install = read_json(layout.install_record) if layout.install_record.exists() else None + # Custody and the port precede every row that can be quiescent, including a different installed profile. + if not owned: + token = run.get("tree_token") + if token and not (state == "stopped" and run.get("tree_verified_empty") == token): + return Verdict("job-unproved", "degraded", + [f"process-tree generation not proved empty; {stopper}"], + refusal=CUSTODY_REFUSAL, run=run) + srv = layout.profile.data["server"] + if port_in_use(srv["listen_host"], srv["port"]): + # Reuse the platform listener query; import lazily because remote's errors derive from LifecycleError. + from .remote import RemoteError, listener_pids + try: + pids = listener_pids(srv["port"]) + holder = "PID " + ", ".join(map(str, sorted(pids))) if pids else "PID unavailable" + except RemoteError: + holder = "PID unavailable (inspect the listener on this host)" + message = (f"{srv['listen_host']}:{srv['port']} is occupied; ownership unproved, so treating its holder " + "as a process this integration does not own; refusing to start or adopt it. " + f"End the holder ({holder}) or change the port before start or install") + return Verdict("port-held", "degraded", [message], refusal=message, run=run) if install is not None and install.get("profile_fingerprint") != layout.profile.fingerprint: if not owned: found["refusal"] = "the install was made for a different profile fingerprint; reinstall or switch back" @@ -1451,16 +1494,6 @@ def verdict(layout: Layout) -> Verdict: return Verdict("server-live", "degraded", [f"an earlier stop did not end {remain}"], owned, **found) # `status` decides healthy or degraded from the authenticated checks. return Verdict("server-live", "healthy", [], owned, **found) - token = run.get("tree_token") - if token and not (state == "stopped" and run.get("tree_verified_empty") == token): - advice = "run `stop` to end and prove its process-tree job" if WINDOWS else "reconcile it on its Windows host" - return Verdict("job-unproved", "degraded", [f"process-tree generation not proved empty; {advice}"], - refusal=CUSTODY_REFUSAL, run=run) - srv = layout.profile.data["server"] - if port_in_use(srv["listen_host"], srv["port"]): - message = (f"{srv['listen_host']}:{srv['port']} is occupied by a process this integration " - "does not own; refusing to start or adopt it") - return Verdict("port-held", "degraded", [message], quiescent=True, refusal=message, run=run) if install is None: return Verdict("idle", "not_installed", quiescent=True, run=run) if state == "exited" and run.get("exit_code") not in (0, None): @@ -2168,7 +2201,7 @@ def status(layout: Layout) -> dict: problems.append("no engine process under the server (stock Strata restarts it on the next request)") stray = {role: p for role, p in live.items() if role.startswith("unrecorded[")} if stray: - problems.append(f"processes of this root outside its recorded trees ({_describe(stray)}); `stop` ends them") + problems.append(f"processes of this root outside its recorded trees ({_describe(stray)}); {_stop_advice(run)}") extra = {} if layout.profile.multi_gpu: cards = card_observations(layout.profile, owned_pids={server.pid, *(p.pid for p in tree)}) @@ -2210,18 +2243,19 @@ def stop(layout: Layout, *, log: Log, locked: bool = False, job: ProcessJob | No def _stop() -> dict: root = verdict(layout) existed = layout.run_record.exists() - if not existed and not root.live and root.row != "unreadable-table": + evidence_failed = root.row in ("unreadable-record", "unreadable-table") + if not existed and not root.live and not evidence_failed: extra = {"cards": card_observations(layout.profile), "owned_gpus_released": None} if layout.profile.multi_gpu else {} return {"state": "stopped", "stopped": [], **extra} - if root.row == "unreadable-record": - raise LifecycleError(root.problems[0]) run = root.run + writable_run = existed and "run" not in root.details.get("unreadable_records", []) + custody_refusal = _stop_custody_refusal(run) + if custody_refusal: + raise LifecycleError(custody_refusal) unreadable = root.row == "unreadable-table" tree_stopped = False if (run.get("tree_token") and run.get("state") == "stopped" and run.get("tree_verified_empty") == run["tree_token"]): - if not WINDOWS or ProcessJob.scan(run["tree_token"], set(), {}): - raise LifecycleError("stopped process-tree verification unavailable or surviving") tree_stopped = True if run.get("tree_token") and not tree_stopped: run["state"] = "stop_incomplete" # Fence every delayed wrapper before native effects. @@ -2231,10 +2265,8 @@ def _stop() -> dict: except MissingProcessJob: # Windows destroys a kill-on-close job after its last handle and # associated processes are gone. ERROR_ACCESS_DENIED is not this - # proof. Independently reject marked or recorded survivors. - if (not WINDOWS or unreadable or root.live - or ProcessJob.scan(run["tree_token"], set(), {})): - raise LifecycleError("destroyed job still has survivors or unavailable verification") + # proof. End census members below before independently checking for token-marked survivors. + pass else: if owned_job.token != run["tree_token"]: raise LifecycleError("process-tree generation changed") @@ -2245,10 +2277,8 @@ def _stop() -> dict: owned_job.close() raise tree_stopped = True - if run.get("unpublished_child") and not tree_stopped: - raise LifecycleError(CUSTODY_REFUSAL) timeout = layout.profile.data["server"]["stop_timeout_s"] - stopped, refused = [], [] + stopped, refused = [], list(root.problems) if evidence_failed else [] # The verdict's live set: every recorded process alive, the current descendants of each (the real interpreter # behind the venv redirector, any engine a server restarted) and every unrecorded process running the root's # runtime. With the process table unreadable only recorded identities, each verified on its own, are ended. @@ -2272,23 +2302,35 @@ def identity(proc: procs.ProcInfo) -> tuple[int, str, str]: refused.append(f"{label} {Path(proc.exe).name} did not exit within {timeout}s") except PermissionError as exc: refused.append(str(exc)) - if unreadable or refused: + if unreadable: break # A server can start an engine while its tree is being ended: what is still alive gets one more pass. again = verdict(layout) - live = {role: proc for role, proc in again.live.items() if identity(proc) not in done} + if "run" in again.details.get("unreadable_records", []): + writable_run = False + if again.row in ("unreadable-record", "unreadable-table"): + refused.extend(again.problems) + break + live = again.live under = again.under if not live: break - if attempt: + if attempt or all(identity(proc) in done for proc in live.values()): refused.append(f"still alive after stop ({_describe(live)})") - if unreadable: - refused.append(root.problems[0]) + break + if tree_stopped and not refused: + try: + if ProcessJob.scan(run["tree_token"], set(), {}): + refused.append("process-tree survivors remain after census cleanup") + except (LifecycleError, OSError, ValueError, subprocess.SubprocessError) as exc: + refused.append(f"process-tree verification unavailable: {exc}") run.update({"state": "stopped" if not refused else "stop_incomplete", "stopped_utc": utc_now(), "unpublished_child": False}) if tree_stopped and not refused: run["tree_verified_empty"] = run["tree_token"] - if existed: # A root that never had a run record does not get one from stop. + elif refused: + run.pop("tree_verified_empty", None) + if writable_run: # Never invent an absent record or overwrite unreadable evidence. atomic_write_json(layout.run_record, run) srv = layout.profile.data["server"] deadline = time.monotonic() + timeout diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py index db30962..f144e4e 100644 --- a/tests/unit/test_lifecycle_states.py +++ b/tests/unit/test_lifecycle_states.py @@ -135,6 +135,7 @@ def not_installed(_layout): patch.object(lifecycle.procs, "descendants", side_effect=lambda pid: [proc for proc in world.values() if proc.ppid == pid]), patch.object(lifecycle, "port_in_use", side_effect=lambda *args: port["held"]), + patch.object(remote, "listener_pids", return_value={99}), patch.object(lifecycle, "read_key", return_value="x" * 32), patch.object(lifecycle, "runtime_checks", return_value={"ready": True, "problems": []}), patch.object(lifecycle, "verify_install_fast", side_effect=not_installed), @@ -258,10 +259,13 @@ def world(self): self.reads, self.ended = [], [] self.schedule = (True, True, True) self.replace = self.held = self.missing_job = False + self.later_record = None self.layout.run_record.touch() self.layout.install_record.touch() def load(path): + if self.later_record and len(self.reads) == 1 and path == self.later_record[0]: + self.records[path] = self.later_record[1] value = self.records[path] if isinstance(value, Exception): raise value @@ -304,8 +308,8 @@ def job(token, **kwargs): patch.object(lifecycle, "verify_install_fast", side_effect=Admitted), patch.object(lifecycle, "FileLock", return_value=contextlib.nullcontext())): self.enterContext(active) - mocked_job = self.enterContext(patch.object(lifecycle, "ProcessJob", side_effect=job)) - mocked_job.scan.return_value = {} + self.job = self.enterContext(patch.object(lifecycle, "ProcessJob", side_effect=job)) + self.job.scan.return_value = {} def configure(self, run_kind="valid", install_kind="valid", token="none", alive=True, held=False): self.reads.clear() @@ -365,6 +369,18 @@ def test_mismatched_install_never_bypasses_retained_job_proof(self): self.configure(install_kind="other", token=token, alive=False) self.assertEqual(token == "proved", lifecycle.verdict(self.layout).quiescent) + def test_job_scan_proves_empty_after_census_cleanup_not_before(self): + self.world() + self.missing_job = True + self.job.scan.side_effect = lambda *args, **kwargs: dict(self.processes) + for token in ("unproved", "proved"): + with self.subTest(token=token), patch.object(lifecycle, "WINDOWS", True): + self.configure(token=token) + result, failure = self.stop_result() + self.assertIsNone(failure) + self.assertEqual("stopped", result["state"]) + self.assertEqual({12, 20}, set(self.ended)) + def test_relative_executable_never_acquires_ownership_from_cwd(self): self.world() self.configure(alive=False) @@ -408,6 +424,38 @@ def test_port_holder_outside_census_blocks_install_and_names_pid(self): cli.cmd_install(SimpleNamespace(idle_generation=None)) install.assert_not_called() + def test_record_failure_after_cleanup_never_publishes_success_or_overwrites_bad_run(self): + self.world() + for which, value in itertools.product(("run", "install"), ("{", "null", "[]", PermissionError("unreadable"))): + with self.subTest(record=which, value=value): + self.configure() + path = self.layout.run_record if which == "run" else self.layout.install_record + self.later_record = (path, value) + result, failure = self.stop_result() + self.assertIsNone(result) + self.assertIsNotNone(failure) + self.assertEqual({12, 20}, set(self.ended)) + self.assertEqual(value, self.records[path]) + if which == "install": + self.assertEqual("stop_incomplete", json.loads(self.records[self.layout.run_record])["state"]) + + def test_a_still_counted_identity_is_not_an_empty_final_census(self): + self.world() + self.configure() + with patch.object(procs, "terminate", return_value=True): + result, failure = self.stop_result() + self.assertIsNone(result) + self.assertIn("still alive after stop", str(failure)) + + def test_unavailable_listener_pid_is_not_permission_to_install(self): + self.world() + self.configure(alive=False, held=True) + with patch.object(remote, "listener_pids", side_effect=remote.RemoteError("unavailable")): + root = lifecycle.verdict(self.layout) + self.assertFalse(root.quiescent or root.idle) + self.assertIn("PID unavailable", root.refusal) + self.assertIn("change the port", root.refusal) + def test_advice_on_both_platforms_including_healthy_stray_status(self): self.world() seen = set() From 4bd2a22a0c3df4ddc7ee1e76ed0e86604546a982 Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 16:18:54 -0800 Subject: [PATCH 14/15] test(lifecycle): stop fixtures must actually empty their census Two termination doubles returned success while leaving every identity in later snapshots, encoding the false-success defect. Remove ended identities from their modeled census without changing any assertion or real sleeper cleanup. Supply the newly required install-record path in the pending-start fixture. --- tests/unit/test_experiment_loop.py | 2 +- tests/unit/test_lifecycle.py | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/unit/test_experiment_loop.py b/tests/unit/test_experiment_loop.py index f966e3d..1f18a2f 100644 --- a/tests/unit/test_experiment_loop.py +++ b/tests/unit/test_experiment_loop.py @@ -292,7 +292,7 @@ def test_import_has_no_native_or_controller_effects(self): def test_pending_start_cannot_be_overwritten_by_another_start(self): root = self.root / "pending" root.mkdir() - layout = SimpleNamespace(run_record=root / "run.json", lock_file=root / "lock", + layout = SimpleNamespace(run_record=root / "run.json", install_record=root / "install.json", lock_file=root / "lock", strata=root / "runtime" / "strata", profile=SimpleNamespace(data={"server": {}})) atomic_write_json(layout.run_record, {"state": "launching", "launch_id": "existing"}) before = layout.run_record.read_bytes() diff --git a/tests/unit/test_lifecycle.py b/tests/unit/test_lifecycle.py index 00363ba..2648627 100644 --- a/tests/unit/test_lifecycle.py +++ b/tests/unit/test_lifecycle.py @@ -474,7 +474,10 @@ def test_status_and_stop_act_on_one_set_of_live_processes(self): if gone == "server": # status names the same set without contacting a server. self.assertEqual(sorted(expected), lifecycle.status(self.layout)["live"]) terminated = [] - with patch.object(lifecycle.procs, "descendants", return_value=[]), \ + with patch.object(lifecycle, "process_table", + side_effect=lambda: {info.pid: info for info in live.values() + if info.pid not in terminated}), \ + patch.object(lifecycle.procs, "descendants", return_value=[]), \ patch.object(lifecycle.procs, "terminate", side_effect=lambda proc, _timeout: terminated.append(proc.pid) or True): lifecycle.stop(self.layout, log=self.messages.append) @@ -2162,8 +2165,10 @@ def test_stopped_status_reports_foreign_occupancy_without_changing_process_state def test_stop_never_owns_foreign_gpu_pid_and_reports_all_card_release(self): self.record() - with patch.object(lifecycle, "process_table", return_value={p.pid: p for p in (self.server, self.engine)}), \ - patch.object(lifecycle.procs, "terminate", return_value=True) as terminate, \ + world = {p.pid: p for p in (self.server, self.engine)} + with patch.object(lifecycle, "process_table", side_effect=lambda: dict(world)), \ + patch.object(lifecycle.procs, "terminate", + side_effect=lambda proc, timeout: bool(world.pop(proc.pid))) as terminate, \ patch.object(lifecycle, "port_in_use", return_value=False), \ patch.object(lifecycle, "gpu_facts", side_effect=lambda i, **kwargs: self.gpu(i, [{"pid": 999, "type": "C"}])): result = lifecycle.stop(self.layout, log=self.messages.append) From 92d001cb84a2cc4bd80e9530f20d8dc4b301098c Mon Sep 17 00:00:00 2001 From: Sunil Srivatsa Date: Fri, 13 Nov 2026 16:19:44 -0800 Subject: [PATCH 15/15] test(lifecycle): exercise every recovery row on both platform flags --- tests/unit/test_lifecycle_states.py | 47 +++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py index f144e4e..f2c7f3b 100644 --- a/tests/unit/test_lifecycle_states.py +++ b/tests/unit/test_lifecycle_states.py @@ -513,6 +513,52 @@ def test_extended_product_preserves_all_three_properties(self): print(f"\nextended evidence walk: {cases} combinations in {time.monotonic() - started:.2f} s", file=sys.stderr) self.assertEqual([], failures) + def test_advice_table_reaches_every_row_on_both_platform_flags(self): + self.world() + seen = {False: set(), True: set()} + cases = 0 + for windows, missing, row in itertools.product((False, True), (False, True), lifecycle.ROWS): + with self.subTest(windows=windows, missing_job=missing, row=row), \ + patch.object(lifecycle, "WINDOWS", windows): + self.schedule = (row != "unreadable-table",) * 3 + self.missing_job = missing + run = self.configure(run_kind="null" if row == "unreadable-record" else "valid", + install_kind="other" if row == "mismatched" else "valid", + token="unproved" if row == "job-unproved" else "none", + alive=row in ("server-live", "orphans"), held=row == "port-held") + if row in ("launch-pending", "launch-abandoned"): + run["state"] = "launching" + if row == "launch-pending": + run["launcher"] = self.p["launcher"].as_dict() + self.processes[10] = self.p["launcher"] + if row in ("wrapper-publishing", "custody-unknown"): + run.update(state="starting", unpublished_child=True) + if row == "wrapper-publishing": + run["wrapper"] = self.p["wrapper"].as_dict() + self.processes[11] = self.p["wrapper"] + if row == "orphans": + run.pop("server") + if row != "unreadable-record": + self.records[self.layout.run_record] = json.dumps(run) + root = lifecycle.verdict(self.layout) + self.assertEqual(row, root.row) + seen[windows].add(root.row) + texts = [root.refusal or "", *root.problems, *lifecycle.status(self.layout).get("problems", [])] + advises = any("run `stop`" in t or "use stop" in t or "status/stop" in t or "`stop` ends" in t + for t in texts) + if any("reinstall" in t for t in texts): + with patch.object(cli, "_layout", return_value=self.layout), \ + patch.object(cli.install_mod, "install", side_effect=Admitted): + with self.assertRaises(Admitted): + cli.cmd_install(SimpleNamespace(idle_generation=None)) + self.reads.clear() + _, failure = self.stop_result() + self.assertFalse(advises and failure, texts) + cases += 1 + for rows in seen.values(): + self.assertEqual(set(lifecycle.ROWS), rows) + print(f"\nadvice row table: {cases} cases, all rows on both platform flags", file=sys.stderr) + class StopIdentityWalk(unittest.TestCase): def setUp(self): @@ -670,6 +716,7 @@ class StagingPreflightReadOnlyTests(unittest.TestCase): def test_preflight_only_reads_for_absent_unprepared_and_prepared_roots(self): with tempfile.TemporaryDirectory() as directory: data = single_gpu_data() + data["model"]["format"] = nvfp4.FORMAT data["model"]["conversion"] = nvfp4.conversion_pin(next(iter(nvfp4.RECIPES.values()))[0]) layout = Layout(Path(directory) / "root", Profile(PROFILE, data))