diff --git a/omp_strata/cli.py b/omp_strata/cli.py index 31d5185..0331d9e 100644 --- a/omp_strata/cli.py +++ b/omp_strata/cli.py @@ -104,6 +104,9 @@ 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}; {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")}) diff --git a/omp_strata/lifecycle.py b/omp_strata/lifecycle.py index 94c0f39..09e4171 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,31 +1281,343 @@ 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; row meanings are below and precedence is in verdict. +# Status renders it, start requires idle, and install/idle_generation require quiescence. +# Recovery advice shares stop's structural gate and names manual cleanup outside its legacy selection. +IDLE_STATES = ("not_installed", "stopped", "failed") +ROWS = ( + "unreadable-record", # Unreadable/ambiguous entry or unusable active recorded role. + "unreadable-table", # Census unavailable or an active recorded identity is cannot-say. + "custody-unknown", # Unpublished child lifetime cannot be reconciled from current evidence. + "launch-pending", # Launching record and positively identified launcher. + "launch-abandoned", # Launching record and launcher absent or counter-proven reused. + "launch-unrecorded", # Launching record has no launcher identity. + "wrapper-publishing", # Starting wrapper is live but child publication is incomplete. + "mismatched", # Installed profile differs; quiescence still requires independent proof. + "server-live", # Identified server; status still performs authenticated health checks. + "orphans", # Owned processes remain without an installed, identified server. + "job-unproved", # Retained process-tree custody lacks stopped/matching empty-tree proof. + "port-held", # Configured port is occupied or its availability cannot be read. + "idle", # Readable evidence, no owned process/pending launch, settled custody and free port. +) +CUSTODY_REFUSAL = "unpublished child lifetime is unknown; retain custody for reconciliation" +PENDING_REFUSAL = "pending launch already owns this root" + + +@dataclass +class Verdict: + row: str + state: str + problems: list[str] = field(default_factory=list) + # Every process of the root found alive, recorded or not. + live: dict[str, procs.ProcInfo] = field(default_factory=dict) + # 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) + 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() -> procs.ProcessTable: + """The one process-table read a verdict rests on.""" + return procs.table() + + +def recorded_processes(run: dict) -> list[tuple[str, object]]: + """Roles actually recorded, including malformed values for the verdict to reject. + + Released _finish_start writes engine=None to mean no recorded engine; no other role has that null meaning. + A record states which roles a run recorded, not which processes exist. Never-recorded processes are found, + if at all, by the runtime-root census. An empty server_tree is a valid collection with no members. + """ + roles = [(role, run[role]) for role in ("wrapper", "server", "engine") + if role in run and not (role == "engine" and run[role] is None)] + tree = run.get("server_tree", []) + if isinstance(tree, list): + roles.extend((f"server_tree[{index}]", identity) for index, identity in enumerate(tree)) + else: + roles.append(("server_tree", tree)) + return roles + + +def runs_from(exe: str, base: Path) -> bool: + """True when the normalized absolute executable or its resolution lies inside the runtime.""" + if not exe or not os.path.isabs(exe): + return False + exe = os.path.normpath(exe) + if os.pardir in Path(exe).parts: + return False + base = os.path.abspath(base) + prefixes = {os.path.normcase(os.path.join(path, "")) for path in (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: object, table: procs.ProcessTable) -> procs.ProcInfo | None: + if not procs.valid_identity(identity) or table.observe(identity) is not procs.Presence.SAME: + return None + return table.identified[identity["pid"]] + + +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, []): + # Creation-order checks belong to the reader; traverse only the edges it vouched for. + if child.pid in under: + 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 _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, live: dict[str, procs.ProcInfo], under: dict[int, str]) -> str: + """Do not promise that the unmigrated stop selects census-only survivors or every table identity.""" + custody = _stop_custody_refusal(run) + if custody: + return custody + manual = {role: proc for role, proc in live.items() + if role.startswith("unrecorded[") + or role.startswith("descendant[") and under.get(proc.pid) not in ("server", "wrapper")} + if not procs.WINDOWS: + for role, identity in recorded_processes(run): + proc = live.get(role) + # Table comparison normalizes deleted images; legacy stop does not. Conservatively inspect either form. + if proc and (proc.exe.endswith(" (deleted)") + or procs.valid_identity(identity) and identity["exe"].endswith(" (deleted)")): + manual[role] = proc + manual.update({name: child for name, child in live.items() if under.get(child.pid) == role}) + manual_advice = (f"inspect and end these processes by hand ({_describe(manual)}); then run `status` for this root" + if manual else None) + if run.get("state") == "launching": + fence = "run `stop` for this root to fence the dispatched wrapper so it cannot start a server" + return f"{fence} (do not rely on it to end the listed processes); {manual_advice}" if manual_advice else fence + return manual_advice or "run `stop` for this root" + + +def _read_record(path: Path) -> object: + """Read verdict evidence without allowing a duplicate role key to erase an earlier identity.""" + def unique_roles(pairs): + record = {} + for key, value in pairs: + if key in ("wrapper", "server", "engine", "launcher", "server_tree") and key in record: + raise ValueError("duplicated process role") + record[key] = value + return record + return json.loads(path.read_text(encoding="utf-8"), object_pairs_hook=unique_roles) + + +def verdict(layout: Layout) -> Verdict: + """The root's row among ROWS, whose meanings are documented at their definition; first match wins.""" + errors = [] + + def record(path: Path, name: str, absent): + try: + if not stat.S_ISREG(path.stat().st_mode): + raise ValueError("record entry is not a regular file") + value = _read_record(path) + except FileNotFoundError: + try: + path.lstat() # A broken link is still evidence, not an absent directory entry. + except FileNotFoundError: + return absent + except OSError: + pass + value = None + 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) + recorded = recorded_processes(run) + try: + table = process_table() + except procs.TableUnavailable as exc: + table, unavailable = None, str(exc) + live, owned, under = {}, {}, {} + else: + live = {role: proc for role, identity in recorded if (proc := _alive(identity, table))} + descendants, under = _descendants(table.identified, live) + known = {**live, **descendants} + owned = {**known, **_unrecorded(layout, table.identified, known)} + # A launcher is launch evidence, not runtime ownership; consult it during launch and before quiescence. + active_launcher = run.get("state") == "launching" or not owned + identities = [*recorded, ("launcher", run["launcher"])] if active_launcher and "launcher" in run else recorded + malformed = [role for role, identity in identities if not procs.valid_identity(identity)] + if malformed and "run" not in errors: + errors.append("run") + details = {"unreadable_records": errors} if errors else {} + if malformed: + details["unreadable_roles"] = malformed + problems = [f"{name} record unreadable; reconcile this root by hand" for name in errors] + if table is None: + message = f"process census unavailable: {unavailable}; custody unknown, so the root is not reported idle (retry `status`)" + return Verdict("unreadable-table", "degraded", [*problems, message], + refusal="; ".join([*problems, message]), run=run, details=details) + stopper = _stop_advice(run, owned, under) + found = {"details": {**details, **({"live": sorted(owned)} if owned else {})}, "run": run, "under": under, + "refusal": f"integration-owned processes already running ({', '.join(sorted(owned))}); {stopper}"} + unknown = [(role, identity["pid"]) for role, identity in identities + if procs.valid_identity(identity) and table.observe(identity) is procs.Presence.UNKNOWN] + if unknown: + names = ", ".join(f"{role} pid {pid}" for role, pid in unknown) + message = (f"cannot prove absence or PID reuse for {names}; custody unknown, so the root is not reported idle. " + "Inspect each PID and reconcile custody by hand; a confirmed-stale run record must be cleared " + f"by hand ({layout.run_record}) before retrying `status`") + return Verdict("unreadable-table", "degraded", [*problems, message], owned, + **{**found, "refusal": "; ".join([*problems, message]), + "details": {**found["details"], "unidentified_records": [role for role, _ in unknown]}}) + if errors: + return Verdict("unreadable-record", "degraded", problems, owned, + **{**found, "refusal": "; ".join(problems)}) + state = run.get("state") + 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}}) + return Verdict("custody-unknown", "degraded", + [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": f"{PENDING_REFUSAL}; {stopper} before replacement", + "details": {**found["details"], "pending": True}} + if "launcher" not in run: + return Verdict("launch-unrecorded", "degraded", + [f"launch pending: its start command identity is not recorded; a dispatched wrapper may " + f"still be waiting for the root lock; {stopper}"], owned, **pending) + launcher = _alive(run["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 " + f"wrapper; {stopper}"], 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}"], owned, **pending) + # 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): + message = f"process-tree generation not proved empty; {stopper}" + return Verdict("job-unproved", "degraded", [message], refusal=message, run=run) + srv = layout.profile.data["server"] + try: + occupied = port_in_use(srv["listen_host"], srv["port"]) + except OSError as exc: + message = (f"configured port {srv['listen_host']}:{srv['port']} unreadable ({exc}); " + "inspect the listener on this host, then retry `status` before start or install") + return Verdict("port-held", "degraded", [message], refusal=message, run=run) + if occupied: + # 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" + 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) + 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: - raise LifecycleError("partial candidate generation record") + """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: + reason = root.refusal or "run record is empty; reconcile this root by hand" + raise LifecycleError(f"partial candidate generation record: {reason}") + if not root.quiescent: + raise LifecycleError(f"prior candidate generation unproved: {root.refusal}") 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 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") + raise LifecycleError("prior candidate generation unproved: process-tree custody is not proved empty; " + "retain custody for reconciliation") return generation @@ -1790,11 +2103,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 +2113,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 +2146,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 +2284,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 +2301,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_advice(run, live, root.under)}") extra = {} if layout.profile.multi_gpu: cards = card_observations(layout.profile, owned_pids={server.pid, *(p.pid for p in tree)}) @@ -2022,12 +2321,19 @@ def status(layout: Layout) -> dict: "started_utc": run.get("ready_utc"), **extra} + + + + def stop(layout: Layout, *, log: Log, locked: bool = False, job: ProcessJob | None = None) -> dict: def _stop() -> dict: if not layout.run_record.exists(): 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) + custody_refusal = _stop_custody_refusal(run) + if custody_refusal: + raise LifecycleError(custody_refusal) tree_stopped = False if (run.get("tree_token") and run.get("state") == "stopped" and run.get("tree_verified_empty") == run["tree_token"]): @@ -2058,8 +2364,6 @@ def _stop() -> dict: owned_job.close() raise tree_stopped = True - if run.get("unpublished_child") and not tree_stopped: - raise LifecycleError("unpublished child lifetime is unknown; retain custody for reconciliation") 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 @@ -2127,5 +2431,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/scripts/experiment_loop.py b/scripts/experiment_loop.py index 0f94d95..75443a9 100755 --- a/scripts/experiment_loop.py +++ b/scripts/experiment_loop.py @@ -666,7 +666,11 @@ def require_idle(self, layout, deadline, *, locked=False): try: return lifecycle.idle_generation(layout, expected=self.admission_generation, timeout=max(0, deadline - time.monotonic())) - except lifecycle.LifecycleError: + except lifecycle.LifecycleError as exc: + private = layout.root / "evidence/experiments" + with self.root_fence(), self.output_fence(private): + with (private / f"{time.time_ns()}.err").open("xb") as diagnostic: + diagnostic.write(f"prior_candidate_generation_unproved: {exc}\n".encode("utf-8", "backslashreplace")) raise ExperimentError("prior_candidate_generation_unproved") from None def reservation(self, *, require_closed_port=False): diff --git a/tests/unit/test_experiment_loop.py b/tests/unit/test_experiment_loop.py index 0152cde..16e1e84 100644 --- a/tests/unit/test_experiment_loop.py +++ b/tests/unit/test_experiment_loop.py @@ -17,6 +17,7 @@ from omp_strata import cli, install, lifecycle from omp_strata.common import atomic_write_json, sha256_file from scripts import experiment_loop as loop +from tests.unit.test_lifecycle_evidence import complete_table from tests.unit.test_process_jobs import KernelStub BASELINE = "win11-rtxpro6000-iq3s-262k-slots4-parking-strata0.2.3-omp18.12.6" @@ -292,8 +293,8 @@ 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", - profile=SimpleNamespace(data={"server": {}})) + 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() with patch.object(lifecycle, "verify_install_fast") as verify, self.assertRaisesRegex( @@ -432,6 +433,35 @@ def native_adapter(self): adapter.check_root(create=True) return adapter + def test_idle_refusal_keeps_private_detail_without_opening_the_public_reason(self): + adapter = self.native_adapter() + layout = adapter.layouts["candidate"] + private = layout.root / "evidence/experiments" + for locked, cause in itertools.product((False, True), ("cannot-say", "survivor", "census")): + with self.subTest(locked=locked, cause=cause): + recorded = fixture_process(101).as_dict() + recorded["created"] = "Fri Nov 13 12:34:56 2026" + atomic_write_json(layout.run_record, {"state": "stopped", "server": recorded}) + rows = {101: lifecycle.procs.ProcInfo(101, 0, "Fri Nov 13 12:34:57 2026", recorded["exe"])} + required = ("server pid 101", "cannot prove", "by hand", str(layout.run_record)) + if cause == "survivor": + rows = {77: lifecycle.procs.ProcInfo(77, 0, "77", str(layout.strata / "orphan"))} + required = ("unrecorded[77]", "pid 77", "inspect", "end", "by hand", "`status`") + elif cause == "census": + required = ("process census unavailable", "fake census fault", "retry `status`") + before = set(private.glob("*.err")) + with patch.object(lifecycle, "process_table", return_value=complete_table(rows), + side_effect=lifecycle.procs.TableUnavailable("fake census fault") if cause == "census" else None), \ + patch.object(lifecycle.ProcessJob, "scan", side_effect=AssertionError("must refuse before scan")), \ + self.assertRaises(loop.ExperimentError) as failure: + adapter.require_idle(layout, time.monotonic() + 10, locked=locked) + self.assertEqual("prior_candidate_generation_unproved", str(failure.exception)) + added = set(private.glob("*.err")) - before + self.assertEqual(1, len(added)) + diagnostic = added.pop().read_text(encoding="utf-8") + for detail in required: + self.assertIn(detail, diagnostic) + def ready_adapter(self): adapter = self.native_adapter() layout = adapter.layouts["candidate"] @@ -681,7 +711,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=complete_table({})), \ patch.object(lifecycle.ProcessJob, "scan", return_value={}), \ patch.object(lifecycle, "_job_kernel", return_value=KernelStub()): try: @@ -1005,7 +1035,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=complete_table({})), \ 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 +1086,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 +1128,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 +1140,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 +1228,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: complete_table({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 +1281,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=complete_table({})), \ 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 fcc4236..f724011 100644 --- a/tests/unit/test_lifecycle.py +++ b/tests/unit/test_lifecycle.py @@ -7,21 +7,26 @@ 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 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 from tests.mock.test_remote_support import free_port +from tests.unit.test_lifecycle_evidence import complete_table from tests.unit.test_profile import multi_gpu_data, single_gpu_data REPO = Path(__file__).resolve().parents[2] @@ -52,6 +57,16 @@ def setUp(self): self.messages = [] self.enterContext(patch.object(lifecycle, "gpu_facts", side_effect=lambda index, **kwargs: gpu_fact(self.layout.profile, index))) + def use_fake_census_reader_identity(self): + """Record the same caller that the fake census identifies; leave other PID lookups unchanged.""" + reader = complete_table().identified[os.getpid()] + native_info = procs.info + + def info(pid, *args, **kwargs): + return reader if pid == reader.pid else native_info(pid, *args, **kwargs) + + self.enterContext(patch.object(procs, "info", side_effect=info)) + def idle_gpu_report(self, *, after_stop=False): if not self.layout.profile.multi_gpu: return {} @@ -353,6 +368,213 @@ 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"]) + + + + + # 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"), "pending launch"), + "job generation exited": (dict(base, state="exited", exit_code=0, tree_token="t"), + "process-tree generation not proved empty"), + "job generation ready, nothing recorded alive": (dict(base, state="ready", tree_token="t"), + "process-tree generation not proved empty"), + "job generation stop incomplete": (dict(base, state="stop_incomplete", tree_token="t"), + "process-tree generation not proved empty")} + for name, (record, reason) in records.items(): + with self.subTest(record=name): + common.atomic_write_json(self.layout.run_record, record) + with self.assertRaisesRegex(lifecycle.LifecycleError, reason): + 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 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") + + + # 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_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_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=complete_table({}), + 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) @@ -384,6 +606,7 @@ class SingleGpuLifecycleTests(LifecycleFixture): def setUp(self): super().setUp() + self.use_fake_census_reader_identity() self.layout = Layout(self.layout.root, Profile(PROFILE, single_gpu_data())) def test_start_keeps_legacy_idle_policy_without_multi_card_ownership_gates(self): @@ -401,7 +624,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=complete_table({})), \ 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), \ @@ -443,7 +666,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=complete_table({})), \ 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), \ @@ -496,7 +719,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=complete_table({}))) 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)) @@ -922,7 +1145,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=complete_table({})), \ 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}), \ @@ -1170,6 +1393,7 @@ def test_contradictory_unknown_and_truncated_output_is_unavailable(self): class MultiGpuLifecycleTests(LifecycleFixture): def setUp(self): super().setUp() + self.use_fake_census_reader_identity() data = multi_gpu_data() data["server"] = self.layout.profile.data["server"] self.layout = Layout(self.layout.root, Profile(self.layout.profile.path, data)) @@ -1278,7 +1502,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=complete_table({}))) 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)) @@ -1729,7 +1953,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=complete_table({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": []}), \ @@ -1741,7 +1965,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=complete_table({})), \ 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"]) diff --git a/tests/unit/test_lifecycle_evidence.py b/tests/unit/test_lifecycle_evidence.py new file mode 100644 index 0000000..06a6347 --- /dev/null +++ b/tests/unit/test_lifecycle_evidence.py @@ -0,0 +1,480 @@ +"""Record entry and attribution boundaries with no host census or process effects.""" +from pathlib import Path +import contextlib +import itertools +import os +import subprocess +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +from omp_strata import cli, lifecycle, procs, remote +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.unit.test_profile import single_gpu_data + + +_native_matches = procs.matches + + +def native_matches(process, recorded): + """Exercise the unchanged individual-reader comparison with only its native lookup substituted.""" + with patch.object(procs, "info", return_value=process): + return _native_matches(recorded) + + +def complete_table(rows=(), *, unidentified=()): + """A reader-contract value: every fake enumerated PID is accounted for, including readable self.""" + import os + identified = dict(rows) + identified.setdefault(os.getpid(), procs.ProcInfo(os.getpid(), 0, "0", "/host-free/reader")) + return procs._checked_table(identified, set(unidentified)) + + +class EvidenceFixture(unittest.TestCase): + def setUp(self): + directory = self.enterContext(tempfile.TemporaryDirectory()) + data = single_gpu_data() + data["server"].update(port=65432, stop_timeout_s=0) + self.layout = Layout(Path(directory), Profile(PROFILE, data)) + self.world, self.ended = {}, [] + self.layout.run_record.parent.mkdir(parents=True, exist_ok=True) + self.install = {"profile_fingerprint": self.layout.profile.fingerprint} + atomic_write_json(self.layout.install_record, self.install) + self.enterContext(patch.object(lifecycle, "process_table", side_effect=lambda: complete_table(self.world))) + self.enterContext(patch.object(lifecycle, "port_in_use", return_value=False)) + + def process(self, pid=20, created="20", owned=True): + return procs.ProcInfo(pid, 1, created, str(self.layout.strata / "engine") if owned else "/foreign/engine") + + def terminate(self, proc, timeout): + current = self.world.get(proc.pid) + if current and native_matches(current, proc.as_dict()) is None: + raise PermissionError("pid now belongs to another process") + self.ended.append(proc) + self.world.pop(proc.pid, None) + return True + + +class RecordEntryTests(EvidenceFixture): + def test_dangling_record_link_is_unreadable_not_absent(self): + for path in (self.layout.run_record, self.layout.install_record): + with self.subTest(record=path.name): + path.unlink(missing_ok=True) + path.symlink_to(path.parent / "missing-record-target") + root = lifecycle.verdict(self.layout) + self.assertEqual("unreadable-record", root.row) + self.assertFalse(root.idle or root.quiescent) + 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() + path.unlink() + + +class AttributionQuestionTests(EvidenceFixture): + def test_parent_segments_cannot_attribute_a_path_outside_runtime(self): + self.world[20] = procs.ProcInfo(20, 1, "old", str(self.layout.strata / ".." / "foreign" / "engine")) + self.assertEqual({}, lifecycle.verdict(self.layout).live) + + def test_listener_command_errors_are_wrapped_and_never_admit(self): + errors = (OSError("denied"), subprocess.TimeoutExpired("lsof", 5), + subprocess.CalledProcessError(1, "lsof"), ValueError("bad owner"), + UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid")) + for error in errors: + with self.subTest(error=type(error).__name__), patch.object(lifecycle, "port_in_use", return_value=True), \ + patch.object(remote.sys, "platform", "darwin"), patch.object(remote.subprocess, "run", side_effect=error): + root = lifecycle.verdict(self.layout) + self.assertEqual("port-held", root.row) + self.assertFalse(root.idle or root.quiescent) + self.assertIn("PID unavailable", root.refusal) + + +class EvidenceEntryWalk(EvidenceFixture): + def test_each_record_entry_kind_is_absent_readable_or_unreadable(self): + import os + kinds = ("absent", "file", "link", "dangling", "directory", "loop", "fifo") + cases = 0 + for path in (self.layout.run_record, self.layout.install_record): + for kind in kinds: + with self.subTest(record=path.name, kind=kind): + path.unlink(missing_ok=True) + target = path.with_name(path.name + ".target") + target.write_text("{}") + if kind == "file": + path.write_text("{}") + elif kind == "link": + path.symlink_to(target) + elif kind == "dangling": + path.symlink_to(path.with_name("absent-target")) + elif kind == "directory": + path.mkdir() + elif kind == "loop": + path.symlink_to(path) + elif kind == "fifo": + if not hasattr(os, "mkfifo"): + continue + os.mkfifo(path) + try: + def load(record): + if kind == "fifo" and record == path: + self.fail("nonregular evidence was opened") + return read_json(record) + with patch.object(lifecycle, "_read_record", side_effect=load): + root = lifecycle.verdict(self.layout) + unreadable = kind not in ("absent", "file", "link") + self.assertEqual(unreadable, root.row == "unreadable-record") + self.assertEqual(not unreadable, root.quiescent) + cases += 1 + finally: + if kind == "directory": + path.rmdir() + else: + path.unlink(missing_ok=True) + self.assertEqual(14 if hasattr(os, "mkfifo") else 12, cases) + + +class SnapshotAncestryTests(EvidenceFixture): + def test_unknown_parent_blocks_ancestry_without_hiding_runtime_identity(self): + from tests.unit.test_process_table import SnapshotSource, windows_reader + cutoff = 116444736000000000 + 1234567890 + reader = windows_reader(SnapshotSource(count=1), cutoff + 1) + reader.__globals__["info"] = lambda pid, *, ppid: procs.ProcInfo( + pid, ppid, str(cutoff + 1), str(self.layout.strata / "engine")) + parent = procs.ProcInfo(1, 0, str(cutoff - 10), "/outside/server") + self.world.update({1: parent, **reader().identified}) + atomic_write_json(self.layout.run_record, dict(self.install, state="ready", server=parent.as_dict())) + with patch.object(procs, "WINDOWS", True): + root = lifecycle.verdict(self.layout) + self.assertEqual(0, self.world[10].ppid) + self.assertNotIn(10, root.under) + self.assertNotIn("descendant[10]", root.live) + self.assertIn("unrecorded[10]", root.live) + self.assertFalse(root.idle or root.quiescent) + + +class UnidentifiedRoleWalk(EvidenceFixture): + def test_every_recorded_role_obeys_the_four_reader_outcomes_in_every_state(self): + import itertools + import time + began = time.monotonic() + cases = 0 + states = (None, "launching", "starting", "ready", "exited", "stopped", "stop_incomplete") + roles = ("wrapper", "server", "engine", "server_tree[0]", "launcher") + for role, state, outcome, mismatch in itertools.product( + roles, states, ("same", "another-process", "not-enumerated", "cannot-say"), (False, True)): + with self.subTest(role=role, state=state, outcome=outcome, mismatched=mismatch): + process = self.process(owned=False) + run = dict(self.install, state=state) + if role == "server_tree[0]": + run["server_tree"] = [process.as_dict()] + else: + run[role] = process.as_dict() + atomic_write_json(self.layout.run_record, run) + atomic_write_json(self.layout.install_record, + dict(self.install, profile_fingerprint="another") if mismatch else self.install) + rows = {process.pid: process} if outcome == "same" else {} + if outcome == "another-process": + rows[process.pid] = self.process(created="21", owned=False) + # Unreadable unrelated system PIDs do not supply ownership evidence for every root. + unknown = {999, process.pid} if outcome == "cannot-say" else {999} + with patch.object(lifecycle, "process_table", return_value=complete_table(rows, unidentified=unknown)): + root = lifecycle.verdict(self.layout) + self.assertEqual(outcome == "cannot-say", root.row == "unreadable-table") + owned = outcome == "same" and role != "launcher" + self.assertEqual({process.pid} if owned else set(), {p.pid for p in root.live.values()}) + self.assertEqual(not owned and state != "launching" and outcome != "cannot-say", root.quiescent) + if outcome == "cannot-say": + self.assertFalse(root.idle) + self.assertEqual([role], root.details["unidentified_records"]) + self.assertEqual("degraded", lifecycle.status(self.layout)["state"]) + with patch.object(lifecycle, "verify_install_fast", side_effect=AssertionError("admitted")): + with self.assertRaises(lifecycle.LifecycleError): + lifecycle.start(self.layout, tool_argv=["fixture"], log=None) + with patch.object(lifecycle.ProcessJob, "scan", side_effect=AssertionError("admitted")): + with self.assertRaises(lifecycle.LifecycleError): + lifecycle.idle_generation(self.layout) + 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() + cases += 1 + self.assertEqual(280, cases) + print(f"recorded-role reader-outcome model: {cases} cases in {time.monotonic() - began:.3f}s") + + +class RecoveryAdviceTests(EvidenceFixture): + def stop_fake(self): + with patch.object(lifecycle, "WINDOWS", False), patch.object(procs, "WINDOWS", False), \ + patch.object(procs, "info", side_effect=lambda pid: self.world.get(pid)), \ + patch.object(procs, "descendants", return_value=[]) as descendants, \ + patch.object(procs, "terminate", side_effect=self.terminate): + result = lifecycle.stop(self.layout, log=None, locked=True) + return result, descendants + + def assert_manual(self, advice, *pids): + for pid in pids: + self.assertIn(f"pid {pid}", advice) + for action in ("inspect", "end", "by hand", "`status`"): + self.assertIn(action, advice) + self.assertNotIn("run `stop`", advice) + + def test_stop_does_not_resolve_an_unrecorded_runtime_survivor(self): + for recorded in (False, True): + with self.subTest(recorded=recorded): + self.world[77] = self.process(pid=77) + self.layout.run_record.unlink(missing_ok=True) + if recorded: + atomic_write_json(self.layout.run_record, {"state": "exited"}) + before = lifecycle.verdict(self.layout) + result, _ = self.stop_fake() + self.assertEqual("stopped", result["state"]) + self.assertEqual([], self.ended) + root = lifecycle.verdict(self.layout) + self.assertEqual("orphans", root.row) + self.assertFalse(root.quiescent) + self.assert_manual(root.refusal, 77) + self.assert_manual(before.refusal, 77) + + def test_engine_and_tree_member_children_are_not_selected_by_legacy_stop(self): + for role in ("engine", "server_tree"): + with self.subTest(role=role): + parent = self.process(owned=False) + child = procs.ProcInfo(77, parent.pid, "77", str(self.layout.strata / "child")) + self.world = {parent.pid: parent, child.pid: child} + run = {"state": "exited", role: [parent.as_dict()] if role == "server_tree" else parent.as_dict()} + atomic_write_json(self.layout.run_record, run) + before = lifecycle.verdict(self.layout) + _, descendants = self.stop_fake() + descendants.assert_not_called() + self.assertEqual({77}, set(self.world)) + self.assert_manual(lifecycle.verdict(self.layout).refusal, 77) + self.assert_manual(before.refusal, 77) + + def test_deleted_image_comparison_does_not_promise_legacy_stop_can_select_the_tree(self): + for role in ("server", "wrapper"): + for deleted_side in ("live", "recorded"): + with self.subTest(role=role, deleted_side=deleted_side), patch.object(procs, "WINDOWS", False): + parent = self.process(owned=False) + recorded = parent.as_dict() + if deleted_side == "live": + parent = procs.ProcInfo(parent.pid, parent.ppid, parent.created, parent.exe + " (deleted)") + else: + recorded["exe"] += " (deleted)" + child = procs.ProcInfo(77, parent.pid, "77", str(self.layout.strata / "child")) + self.world = {parent.pid: parent, child.pid: child} + atomic_write_json(self.layout.run_record, {"state": "exited", role: recorded}) + before = lifecycle.verdict(self.layout) + _, descendants = self.stop_fake() + descendants.assert_not_called() + self.assertEqual({20, 77}, set(self.world)) + self.assert_manual(lifecycle.verdict(self.layout).refusal, 20, 77) + self.assert_manual(before.refusal, 20, 77) + + def test_authenticated_status_does_not_recommend_stop_for_a_stray(self): + server = self.process(owned=False) + self.world = {server.pid: server, 77: self.process(pid=77)} + atomic_write_json(self.layout.run_record, {"state": "ready", "server": server.as_dict()}) + with patch.object(lifecycle, "read_key", return_value="key"), \ + patch.object(lifecycle, "runtime_checks", return_value={"problems": []}), \ + patch.object(procs, "descendants", return_value=[]): + status = lifecycle.status(self.layout) + self.assertEqual("degraded", status["state"]) + self.assert_manual("; ".join(status["problems"]), 77) + + def test_ordinary_recorded_server_retains_effective_stop_advice(self): + server = self.process(owned=False) + self.world[server.pid] = server + atomic_write_json(self.layout.run_record, {"state": "ready", "server": server.as_dict()}) + self.assertIn("run `stop`", lifecycle.verdict(self.layout).refusal) + self.stop_fake() + self.assertTrue(lifecycle.verdict(self.layout).quiescent) + + +class SharedGateExecutionWalk(EvidenceFixture): + def test_stop_executes_the_structural_gate_before_any_effect(self): + token = "a" * 32 + cases = 0 + for windows, has_token, unpublished, state, proof in itertools.product( + (False, True), (False, True), (False, True), ("exited", "stopped"), (False, True)): + with self.subTest(windows=windows, token=has_token, unpublished=unpublished, state=state, proof=proof): + cases += 1 + run = {"state": state, "unpublished_child": unpublished} + if has_token: + run["tree_token"] = token + if proof: + run["tree_verified_empty"] = token + atomic_write_json(self.layout.run_record, run) + refused = has_token and not windows or unpublished and not has_token + with patch.object(lifecycle, "WINDOWS", windows), patch.object(lifecycle, "ProcessJob") as job, \ + patch.object(procs, "info", side_effect=AssertionError("unexpected native lookup")), \ + patch.object(procs, "descendants", side_effect=AssertionError("unexpected native walk")), \ + patch.object(procs, "terminate", side_effect=AssertionError("unexpected native signal")): + job.return_value.token = token + job.scan.return_value = {} + if refused: + with self.assertRaises(lifecycle.LifecycleError) as failure: + lifecycle.stop(self.layout, log=None, locked=True) + expected = "Windows host" if has_token else "unpublished child lifetime is unknown" + self.assertIn(expected, str(failure.exception)) + self.assertEqual(run, read_json(self.layout.run_record)) + job.assert_not_called() + job.scan.assert_not_called() + else: + result = lifecycle.stop(self.layout, log=None, locked=True) + self.assertEqual("stopped", result["state"]) + if has_token and not (state == "stopped" and proof): + job.assert_called_once_with(token, existing=True) + job.return_value.stop.assert_called_once_with(0) + else: + job.assert_not_called() + if has_token and state == "stopped" and proof: + job.scan.assert_called_once_with(token, set(), {}) + else: + job.scan.assert_not_called() + self.assertEqual(32, cases) + + def test_quiescent_candidate_requires_a_fresh_scan_with_and_without_generation_fence(self): + token = "a" * 32 + run = {"state": "stopped", "tree_token": token, "tree_verified_empty": token} + generation = lifecycle.sha256_bytes(lifecycle.canonical_json(run)) + for fenced, outcome in itertools.product((False, True), ("empty", "survivor", "error")): + with self.subTest(fenced=fenced, outcome=outcome), patch.object(lifecycle, "WINDOWS", True): + atomic_write_json(self.layout.run_record, run) + self.assertTrue(lifecycle.verdict(self.layout).quiescent) + with patch.object(lifecycle.ProcessJob, "scan", return_value={} if outcome == "empty" else {77: {}}, + side_effect=lifecycle.LifecycleError("fake scan error") if outcome == "error" else None) as scan: + if outcome == "empty": + self.assertEqual(generation, lifecycle.idle_generation( + self.layout, expected=generation if fenced else None, timeout=2.75)) + else: + with self.assertRaises(lifecycle.LifecycleError) as failure: + lifecycle.idle_generation(self.layout, expected=generation if fenced else None, timeout=2.75) + self.assertIn("fake scan error" if outcome == "error" else "custody is not proved empty", + str(failure.exception)) + scan.assert_called_once_with(token, set(), {}, timeout=2.75) + self.assertEqual(run, read_json(self.layout.run_record)) + + +class LaunchingRecoveryWalk(EvidenceFixture): + stop_fake = RecoveryAdviceTests.stop_fake + assert_manual = RecoveryAdviceTests.assert_manual + FENCE = "run `stop` for this root to fence the dispatched wrapper so it cannot start a server" + MANUAL = ("inspect and end these processes by hand " + "(unrecorded[77] engine pid 77, unrecorded[78] python pid 78); then run `status` for this root") + COMBINED_PREFIX = FENCE + " (do not rely on it to end the listed processes); " + COMBINED = COMBINED_PREFIX + MANUAL + ROWS = ("launch-unrecorded", "launch-pending", "launch-abandoned") + + def launching(self, row, *, survivors=True, token=False): + self.world.clear() + run = {"state": "launching", "launch_id": "old-launch", + "profile_fingerprint": self.layout.profile.fingerprint} + launcher = self.process(owned=False) + if row != "launch-unrecorded": + run["launcher"] = launcher.as_dict() + if row == "launch-pending": + self.world[launcher.pid] = launcher + if token: + run["tree_token"] = "a" * 32 + if survivors: + self.world[77] = self.process(pid=77) + self.world[78] = procs.ProcInfo(78, 1, "78", str(self.layout.strata / "python")) + atomic_write_json(self.layout.run_record, run) + return run + + def test_launch_rows_publish_exact_advice_with_structural_custody_first(self): + for row, survivors, token, windows in itertools.product(self.ROWS, (False, True), (False, True), (False, True)): + with self.subTest(row=row, survivors=survivors, token=token, windows=windows), \ + patch.object(lifecycle, "WINDOWS", windows): + self.launching(row, survivors=survivors, token=token) + expected = "reconcile it on its Windows host" if token and not windows else self.COMBINED if survivors else self.FENCE + root = lifecycle.verdict(self.layout) + self.assertEqual(row, root.row) + self.assertTrue(root.problems[0].endswith("; " + expected), root.problems) + self.assertEqual("pending launch already owns this root; " + expected + " before replacement", root.refusal) + if token and not windows: + self.assertNotIn("`stop`", root.refusal) + self.assertNotIn("by hand", root.refusal) + + def test_stop_fences_late_wrapper_before_manual_survivor_cleanup(self): + for row in self.ROWS: + with self.subTest(row=row): + self.launching(row) + before = lifecycle.verdict(self.layout) + self.stop_fake() + self.assertEqual("stopped", read_json(self.layout.run_record)["state"]) + with patch.dict(os.environ, {lifecycle.TREE_TOKEN_ENV: ""}), \ + patch.object(lifecycle, "FileLock", return_value=contextlib.nullcontext()), \ + patch.object(lifecycle, "read_key", side_effect=AssertionError("must fence before key")) as key, \ + patch.object(procs, "info", side_effect=AssertionError("must fence before identity")) as info, \ + patch.object(lifecycle, "ProcessJob", side_effect=AssertionError("must fence before job")) as job, \ + patch.object(lifecycle.subprocess, "Popen", side_effect=AssertionError("must not start server")) as spawn: + with self.assertRaisesRegex(lifecycle.LifecycleError, "serve generation changed or stopped before launch"): + lifecycle.serve(self.layout, log_path=self.layout.logs / "late-wrapper.log", launch_id="old-launch") + for native in (key, info, job, spawn): + native.assert_not_called() + self.assertTrue({77, 78}.issubset(self.world)) + orphan = lifecycle.verdict(self.layout) + self.assertEqual("orphans", orphan.row) + self.assert_manual(orphan.refusal, 77, 78) + self.assertIn(self.COMBINED, before.refusal) + for pid in (77, 78): + self.world.pop(pid) + empty = lifecycle.verdict(self.layout) + self.assertEqual(("idle", "stopped", True, True), + (empty.row, empty.state, empty.idle, empty.quiescent)) + + def test_manual_cleanup_alone_does_not_fence_a_launch(self): + for row in self.ROWS: + with self.subTest(row=row): + self.launching(row) + for pid in (77, 78): + self.world.pop(pid) + root = lifecycle.verdict(self.layout) + self.assertEqual(row, root.row) + self.assertFalse(root.idle or root.quiescent) + self.assertEqual("launching", read_json(self.layout.run_record)["state"]) + self.assertEqual("pending launch already owns this root; " + self.FENCE + " before replacement", root.refusal) + + def test_unpublished_without_token_precedes_every_launch_row(self): + for row in self.ROWS: + with self.subTest(row=row): + run = self.launching(row) + atomic_write_json(self.layout.run_record, {**run, "unpublished_child": True}) + root = lifecycle.verdict(self.layout) + self.assertEqual("custody-unknown", root.row) + self.assertEqual("unpublished child lifetime is unknown; retain custody for reconciliation", root.refusal) + + def test_waiting_wrapper_is_counted_only_inside_the_ownership_boundary(self): + for inside in (False, True): + with self.subTest(inside=inside): + self.launching("launch-unrecorded", survivors=False) + exe = str(self.layout.strata / "python") if inside else "/outside/python" + self.world[78] = procs.ProcInfo(78, 1, "78", exe) + root = lifecycle.verdict(self.layout) + self.assertEqual({"unrecorded[78]"} if inside else set(), set(root.live)) + + def test_stop_can_end_a_deleted_image_candidate_in_a_mixed_launch_list(self): + run = self.launching("launch-unrecorded", survivors=False) + server = self.process(owned=False) + server = procs.ProcInfo(server.pid, server.ppid, server.created, server.exe + " (deleted)") + self.world = {server.pid: server, 77: self.process(pid=77)} + atomic_write_json(self.layout.run_record, {**run, "server": server.as_dict()}) + expected = (self.COMBINED_PREFIX + "inspect and end these processes by hand " + "(server engine (deleted) pid 20, unrecorded[77] engine pid 77); then run `status` for this root") + with patch.object(procs, "WINDOWS", False): + before = lifecycle.verdict(self.layout) + self.stop_fake() + after = lifecycle.verdict(self.layout) + self.assertEqual({77}, set(self.world)) + self.assertEqual(["20"], [proc.created for proc in self.ended]) + self.assertEqual("orphans", after.row) + self.assertEqual({"unrecorded[77]"}, set(after.live)) + self.assert_manual(after.refusal, 77) + self.assertNotIn("pid 20", after.refusal) + self.assertIn(expected, before.refusal) + self.assertTrue(before.problems[0].endswith("; " + expected), before.problems) diff --git a/tests/unit/test_lifecycle_records.py b/tests/unit/test_lifecycle_records.py new file mode 100644 index 0000000..d83e55a --- /dev/null +++ b/tests/unit/test_lifecycle_records.py @@ -0,0 +1,401 @@ +"""Role-schema, released-writer null and reader-edge contracts; host-free.""" +import contextlib +import itertools +import json +from unittest.mock import patch + +from omp_strata import cli, lifecycle, procs, remote +from omp_strata.common import atomic_write_json +from types import SimpleNamespace +from tests.unit.test_lifecycle_evidence import EvidenceFixture, complete_table, native_matches + + +class RecordedRoleShapeWalk(EvidenceFixture): + def test_present_roles_are_never_silently_absent(self): + states = (None, "launching", "starting", "ready", "exited", "stopped", "stop_incomplete") + forms = ("omitted", "null", "empty", "not-object", "missing-pid", "missing-created", "missing-exe", + "wrong-pid", "wrong-created", "wrong-exe", "duplicate-null-valid", "duplicate-valid-null", "valid") + cases = 0 + identity = self.process(created="20").as_dict() + survivor = self.process(pid=77, created="77") + for role, state, windows, form, remaining in itertools.product( + ("wrapper", "server", "engine", "launcher", "server_tree[0]"), states, (False, True), forms, (False, True)): + with self.subTest(role=role, state=state, windows=windows, form=form, remaining=remaining), \ + patch.object(lifecycle, "WINDOWS", windows), patch.object(procs, "WINDOWS", windows): + cases += 1 + self.world.clear() + if remaining: + self.world[survivor.pid] = survivor + run = {} if state is None else {"state": state} + key = "server_tree" if role == "server_tree[0]" else role + value = dict(identity) + if form == "null": + value = None + elif form == "empty": + value = {} + elif form == "not-object": + value = "not an identity" + elif form.startswith("missing-"): + value.pop(form.removeprefix("missing-")) + elif form.startswith("wrong-"): + field = form.removeprefix("wrong-") + value[field] = "20" if field == "pid" else 101 + if form != "omitted": + run[key] = [value] if key == "server_tree" else value + if form.startswith("duplicate-"): + good = [identity] if key == "server_tree" else identity + run[key] = None if form == "duplicate-null-valid" else good + second = good if form == "duplicate-null-valid" else None + text = json.dumps(run)[:-1] + "," + json.dumps(key) + ":" + json.dumps(second) + "}" + else: + text = json.dumps(run) + self.layout.run_record.write_text(text) + active = role != "launcher" or state == "launching" or not remaining + invalid = (form.startswith("duplicate-") + or active and form not in ("omitted", "valid") and not (role == "engine" and form == "null")) + root = lifecycle.verdict(self.layout) + self.assertEqual(invalid, root.row == "unreadable-record") + self.assertEqual({77} if remaining else set(), {p.pid for p in root.live.values()}) + if invalid: + self.assertFalse(root.idle or root.quiescent) + self.assertIn("run", root.details["unreadable_records"]) + if state == "stopped" and not windows and not remaining: + with self.assertRaises(lifecycle.LifecycleError): + lifecycle.start(self.layout, tool_argv=["fixture"], log=lambda _: None) + 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() + with self.assertRaises(lifecycle.LifecycleError): + lifecycle.idle_generation(self.layout) + else: + self.assertEqual(not remaining and state != "launching", root.quiescent) + self.assertEqual(1820, cases) + + def test_server_tree_collection_requires_a_list_of_identities(self): + for value in (None, {}, "", 0, [None], [{}], []): + with self.subTest(value=value): + atomic_write_json(self.layout.run_record, {"state": "stopped", "server_tree": value}) + root = lifecycle.verdict(self.layout) + self.assertEqual(value != [], root.row == "unreadable-record") + self.assertEqual(value == [], root.quiescent) + + def test_released_engine_null_is_identical_to_an_omitted_role(self): + for state, alive in itertools.product(("starting", "ready", "exited", "stopped", "stop_incomplete"), (False, True)): + with self.subTest(state=state, alive=alive): + server = self.process(created="20") + self.world.clear() + if alive: + self.world[server.pid] = server + run = {"state": state, "server": server.as_dict(), "server_tree": []} + atomic_write_json(self.layout.run_record, run) + before = lifecycle.verdict(self.layout) + atomic_write_json(self.layout.run_record, {**run, "engine": None}) + after = lifecycle.verdict(self.layout) + self.assertEqual((before.row, before.state, before.quiescent, before.live, before.details), + (after.row, after.state, after.quiescent, after.live, after.details)) + + +class LauncherEvidenceTests(EvidenceFixture): + def test_missing_gone_and_unidentified_launcher_have_distinct_reasons(self): + launcher = self.process(created="20", owned=False) + for kind, expected in (("missing", "launch-unrecorded"), ("gone", "launch-abandoned"), + ("unidentified", "unreadable-table")): + with self.subTest(kind=kind): + run = {"state": "launching"} + if kind != "missing": + run["launcher"] = launcher.as_dict() + atomic_write_json(self.layout.run_record, run) + unknown = {launcher.pid} if kind == "unidentified" else set() + with patch.object(lifecycle, "process_table", return_value=complete_table(unidentified=unknown)): + root = lifecycle.verdict(self.layout) + self.assertEqual(expected, root.row) + self.assertFalse(root.idle or root.quiescent) + message = " ".join(root.problems) + if kind == "missing": + self.assertIn("identity is not recorded", message) + if kind != "gone": + self.assertNotIn("is gone", message) + + +class VouchedParentEdgeWalk(EvidenceFixture): + def test_verdict_consumes_only_reader_vouched_edges(self): + cases = 0 + for source, delta, windows in itertools.product(("windows", "procfs", "ps"), (-1, 0, 1), (False, True)): + with self.subTest(source=source, delta=delta, windows=windows), patch.object(procs, "WINDOWS", windows): + cases += 1 + if source == "windows": + stamps = "100", str(100 + delta) + elif source == "procfs": + stamps = "starttime:100", "starttime:" + str(100 + delta) + else: + stamps = "Fri Nov 13 12:34:56 2026", f"Fri Nov 13 12:34:{56 + delta:02d} 2026" + parent = procs.ProcInfo(20, 1, stamps[0], "/outside/python") + child = procs.ProcInfo(21, 20, stamps[1], "/outside/helper") + atomic_write_json(self.layout.run_record, {"server": parent.as_dict()}) + table = complete_table({20: parent, 21: child}) + table = procs._checked_table(table.identified, table.unidentified) + with patch.object(lifecycle, "process_table", return_value=table): + root = lifecycle.verdict(self.layout) + kept = source == "ps" or delta >= 0 + self.assertEqual({20, 21} if kept else {20}, {p.pid for p in root.live.values()}) + self.assertEqual(kept, 21 in root.under) + self.assertEqual(18, cases) + + +class CannotSayConsumerWalk(EvidenceFixture): + def assert_refusals_name(self, evidence, *, pid=None): + root = lifecycle.verdict(self.layout) + self.assertFalse(root.idle or root.quiescent) + report = lifecycle.status(self.layout) + self.assertEqual("degraded", report["state"]) + self.assertIn(evidence, "; ".join(report["problems"])) + if pid is not None: + for required in (f"pid {pid}", "cannot prove", "by hand", str(self.layout.run_record)): + self.assertIn(required, "; ".join(report["problems"])) + with patch.object(lifecycle, "FileLock", side_effect=lambda *args, **kwargs: contextlib.nullcontext()), \ + patch.object(lifecycle, "verify_install_fast", side_effect=AssertionError("start admitted")), \ + patch.object(cli, "_layout", return_value=self.layout), \ + patch.object(cli.install_mod, "install", side_effect=AssertionError("install admitted")), \ + patch.object(lifecycle.ProcessJob, "scan", side_effect=AssertionError("candidate scan admitted")): + callers = { + "start": lambda: lifecycle.start(self.layout, tool_argv=["fixture"], log=lambda _: None), + "install": lambda: cli.cmd_install(SimpleNamespace(idle_generation=None)), + "candidate": lambda: lifecycle.idle_generation(self.layout), + "fenced-candidate": lambda: lifecycle.idle_generation(self.layout, expected="changed"), + } + for name, caller in callers.items(): + with self.subTest(consumer=name), self.assertRaises(lifecycle.LifecycleError) as failure: + caller() + message = str(failure.exception) + self.assertIn(evidence, message) + self.assertRegex(message, r"retry|reconcile|inspect|change the port|retain custody") + if pid is not None: + for required in (f"pid {pid}", "cannot prove", "by hand", str(self.layout.run_record)): + self.assertIn(required, message) + + def test_each_cannot_say_cause_refuses_every_consumer_for_every_recorded_role(self): + states = (None, "launching", "starting", "ready", "exited", "stopped", "stop_incomplete") + causes = ("unidentified", "changed-executable", "calendar", "mixed-clock", "unrecognised", "lossy", + "calendar-executable", "mixed-clock-executable", "unrecognised-executable") + cases = 0 + for role, state, windows, cause in itertools.product( + ("wrapper", "server", "engine", "server_tree[0]", "launcher"), states, (False, True), causes): + with self.subTest(role=role, state=state, windows=windows, cause=cause), \ + patch.object(lifecycle, "WINDOWS", windows), patch.object(procs, "WINDOWS", windows): + process = self.process(created="101", owned=False) + record = process.as_dict() + unknown = {20} if cause == "unidentified" else set() + if cause == "changed-executable": + record["exe"] = "/before/engine" + elif cause.startswith("calendar"): + process = self.process(created="Fri Nov 13 12:34:56 2026", owned=False) + record["created"] = "Fri Nov 13 13:34:56 2026" + elif cause.startswith("mixed-clock"): + record["created"] = "starttime:101" + elif cause.startswith("unrecognised"): + process = self.process(created="sample-a", owned=False) + record["created"] = "sample-b" + elif cause == "lossy": + record.update(created="102", exe="/runtime/\ufffdengine") + if cause.endswith("-executable"): + record["exe"] = "/before/engine" + run = {} if state is None else {"state": state} + run["server_tree" if role == "server_tree[0]" else role] = [record] if role == "server_tree[0]" else record + atomic_write_json(self.layout.run_record, run) + rows = {77: self.process(pid=77, created="200")} + if not unknown: + rows[20] = process + with patch.object(lifecycle, "process_table", return_value=complete_table(rows, unidentified=unknown)): + root = lifecycle.verdict(self.layout) + self.assertEqual({77}, {p.pid for p in root.live.values()}) + if role == "launcher" and state != "launching": + self.assertEqual("orphans", root.row) + self.assertNotIn("unidentified_records", root.details) + self.assert_refusals_name("unrecorded[77]") + else: + self.assertEqual("unreadable-table", root.row) + self.assertEqual([role], root.details["unidentified_records"]) + self.assert_refusals_name(role, pid=20) + cases += 1 + self.assertEqual(630, cases) + + def test_unknown_identity_names_the_pid_and_manual_record_recovery(self): + process = self.process(created="Fri Nov 13 12:34:57 2026", owned=False) + self.world[20] = process + record = dict(process.as_dict(), created="Fri Nov 13 12:34:56 2026") + atomic_write_json(self.layout.run_record, {"state": "stopped", "server": record}) + self.assert_refusals_name("server", pid=20) + + def test_each_unreadable_input_is_named_by_every_consumer(self): + for kind, name in (("run", "run record"), ("install", "install record"), + ("census", "process census"), ("job", "process-tree generation"), + ("unpublished", "child"), ("port", "PID unavailable"), ("probe", "configured port")): + with self.subTest(kind=kind), contextlib.ExitStack() as stack: + run = {"state": "stopped"} + if kind == "job": + run["tree_token"] = "a" * 32 + elif kind == "unpublished": + run["unpublished_child"] = True + atomic_write_json(self.layout.run_record, run) + atomic_write_json(self.layout.install_record, self.install) + if kind in ("run", "install"): + getattr(self.layout, kind + "_record").write_text("{") + elif kind == "census": + stack.enter_context(patch.object(lifecycle, "process_table", side_effect=procs.TableUnavailable())) + elif kind == "probe": + stack.enter_context(patch.object(lifecycle, "port_in_use", side_effect=OSError("descriptor unavailable"))) + elif kind == "port": + stack.enter_context(patch.object(lifecycle, "port_in_use", return_value=True)) + stack.enter_context(patch.object(remote, "listener_pids", side_effect=remote.RemoteError("unreadable"))) + self.assert_refusals_name(name) + + +class NativeComparisonFixtureTests(EvidenceFixture): + def test_start_fixtures_record_the_same_reader_identity_as_their_census(self): + import os + from tests.unit import test_lifecycle as fixtures + + cases = 0 + for case, stamp, exe in itertools.product( + (fixtures.SingleGpuLifecycleTests, fixtures.MultiGpuLifecycleTests), + ("101", "Fri Nov 13 12:34:56 2026"), ("/native/reader", "/host-free/reader")): + cases += 1 + def lookup(pid, *args, **kwargs): + return procs.ProcInfo(pid, 0, stamp, exe) + with self.subTest(fixture=case.__name__, stamp=stamp, exe=exe), \ + patch.object(procs, "info", side_effect=lookup), contextlib.ExitStack() as cleanup: + fixture = case() + cleanup.callback(fixture.doCleanups) + fixture.setUp() + identity = procs.info(os.getpid()) + self.assertIs(procs.Presence.SAME, complete_table().observe(identity.as_dict())) + self.assertEqual(lookup(identity.pid + 1), procs.info(identity.pid + 1)) + self.assertEqual(8, cases) + + def test_fake_native_lookup_retains_the_legacy_comparison(self): + process = self.process(created="101", owned=False) + for windows, created, exe in itertools.product((False, True), ("101", "102"), (process.exe, process.exe.upper())): + with self.subTest(windows=windows, created=created, exe=exe), patch.object(procs, "WINDOWS", windows), \ + patch.object(procs.ProcessTable, "observe", side_effect=AssertionError("not the native comparator")): + record = dict(process.as_dict(), created=created, exe=exe) + expected = process if created == "101" and (windows or exe == process.exe) else None + self.assertIs(expected, native_matches(process, record)) + + +class HostClockAdmissionWalk(EvidenceFixture): + assert_refusals_name = CannotSayConsumerWalk.assert_refusals_name + + def test_pid_reuse_admission_depends_on_the_host_clock_proof(self): + class Admitted(Exception): + pass + + hosts = (("windows", "101", "102"), ("procfs", "starttime:101", "starttime:102"), + ("calendar", "Fri Nov 13 12:34:56 2026", "Fri Nov 13 12:34:57 2026")) + cases = 0 + for (host, before, after), role, changed_executable in itertools.product( + hosts, ("wrapper", "server", "engine", "server_tree[0]", "launcher"), (False, True)): + with self.subTest(host=host, role=role, changed_executable=changed_executable), \ + patch.object(lifecycle, "WINDOWS", host == "windows"), \ + patch.object(procs, "WINDOWS", host == "windows"): + recorded = self.process(created=before, owned=False).as_dict() + current = self.process(created=after, owned=False) + if changed_executable: + current = procs.ProcInfo(current.pid, current.ppid, current.created, "/another/program") + self.world = {20: current} + token = "a" * 32 + run = {"state": "stopped", "tree_token": token, "tree_verified_empty": token} + run["server_tree" if role == "server_tree[0]" else role] = [recorded] if role == "server_tree[0]" else recorded + atomic_write_json(self.layout.run_record, run) + root = lifecycle.verdict(self.layout) + if host == "calendar": + self.assertEqual("unreadable-table", root.row) + self.assert_refusals_name(role, pid=20) + else: + self.assertTrue(root.idle and root.quiescent) + self.assertEqual("stopped", lifecycle.status(self.layout)["state"]) + with patch.object(lifecycle, "FileLock", side_effect=lambda *args, **kwargs: contextlib.nullcontext()), \ + patch.object(lifecycle, "verify_install_fast", side_effect=Admitted), \ + patch.object(cli, "_layout", return_value=self.layout), \ + patch.object(cli.install_mod, "install", side_effect=Admitted), \ + patch.object(lifecycle.ProcessJob, "scan", return_value={}): + with self.assertRaises(Admitted): + lifecycle.start(self.layout, tool_argv=["fixture"], log=lambda _: None) + with self.assertRaises(Admitted): + cli.cmd_install(SimpleNamespace(idle_generation=None)) + generation = lifecycle.idle_generation(self.layout) + self.assertEqual(generation, lifecycle.idle_generation(self.layout, expected=generation)) + cases += 1 + self.assertEqual(30, cases) + + +class LauncherRelevanceWalk(EvidenceFixture): + def launcher(self, outcome): + live = self.process(created="101", owned=False) + recorded = live.as_dict() + if outcome == "other": + recorded["created"] = "100" + elif outcome == "cannot-say": + recorded["created"] = "Fri Nov 13 12:34:56 2026" + live = self.process(created="Fri Nov 13 12:34:57 2026", owned=False) + if outcome != "absent": + self.world[live.pid] = live + return recorded + + def test_serving_server_reaches_authentication_and_clients_despite_inactive_launcher(self): + for outcome in ("same", "other", "absent", "cannot-say", "null", "malformed"): + with self.subTest(outcome=outcome): + self.world.clear() + launcher = self.launcher(outcome) + if outcome in ("null", "malformed"): + launcher = None if outcome == "null" else {} + server = self.process(pid=21, created="21", owned=False) + self.world[server.pid] = server + atomic_write_json(self.layout.run_record, + {"state": "ready", "server": server.as_dict(), "launcher": launcher}) + with patch.object(lifecycle, "read_key", return_value="key"), \ + patch.object(lifecycle, "runtime_checks", return_value={"problems": []}) as checks, \ + patch.object(procs, "descendants", return_value=[]): + self.assertEqual("healthy", lifecycle.status(self.layout)["state"]) + self.assertEqual("key", lifecycle.ensure_healthy(self.layout)) + self.assertEqual(2, checks.call_count) + checks.assert_called_with(self.layout, "key") + self.assertFalse(lifecycle.verdict(self.layout).quiescent) + + def test_launcher_is_active_during_launch_or_before_quiescence(self): + cases = 0 + for state, ownership, outcome in itertools.product( + ("launching", "ready", "stopped"), ("none", "server", "orphan"), + ("same", "other", "absent", "cannot-say")): + with self.subTest(state=state, ownership=ownership, outcome=outcome): + cases += 1 + self.world.clear() + run = {"state": state, "launcher": self.launcher(outcome)} + if ownership != "none": + proc = self.process(pid=77, created="77", owned=ownership == "orphan") + self.world[proc.pid] = proc + if ownership == "server": + run["server"] = proc.as_dict() + atomic_write_json(self.layout.run_record, run) + active = state == "launching" or ownership == "none" + if active and outcome == "cannot-say": + expected = "unreadable-table" + elif state == "launching": + expected = "launch-pending" if outcome == "same" else "launch-abandoned" + else: + expected = {"none": "idle", "server": "server-live", "orphan": "orphans"}[ownership] + root = lifecycle.verdict(self.layout) + self.assertEqual(expected, root.row) + self.assertEqual(expected == "idle", root.idle) + self.assertEqual(expected == "idle", root.quiescent) + self.assertEqual(36, cases) + + def test_stopped_root_retains_uncertain_launcher_until_quiescence_is_proved(self): + atomic_write_json(self.layout.run_record, + {"state": "stopped", "launcher": self.launcher("cannot-say")}) + root = lifecycle.verdict(self.layout) + self.assertEqual("unreadable-table", root.row) + self.assertFalse(root.idle or root.quiescent) + self.assertIn("launcher pid 20", root.refusal) + self.assertIn("by hand", root.refusal) diff --git a/tests/unit/test_lifecycle_states.py b/tests/unit/test_lifecycle_states.py new file mode 100644 index 0000000..1fcb639 --- /dev/null +++ b/tests/unit/test_lifecycle_states.py @@ -0,0 +1,687 @@ +"""The lifecycle's closed state table, defined beside lifecycle.ROWS and walked here. + +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 and +idle_generation act on one verdict and recovery advice passes structural stop admission and that every row of the closed table is reached. +""" +from __future__ import annotations + +import ast +from collections import Counter +import contextlib +import itertools +import json +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import tempfile +import threading +import time +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +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 +from tests.candidate import PROFILE +from tests.mock.test_remote_support import free_port +from tests.unit.test_lifecycle_evidence import complete_table, native_matches +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.""" + + +class VerdictConsumerInventory(unittest.TestCase): + def test_state_table_references_do_not_name_a_missing_document_section(self): + for path in (Path(lifecycle.__file__), Path(__file__)): + with self.subTest(path=path.name): + self.assertNotIn("Lifecycle" + " states", path.read_text()) + + def test_each_closed_row_has_a_reason_at_its_definition(self): + source = Path(lifecycle.__file__).read_text() + definition = next(node for node in ast.parse(source).body if isinstance(node, ast.Assign) + and any(isinstance(target, ast.Name) and target.id == "ROWS" for target in node.targets)) + for row in definition.value.elts: + with self.subTest(row=ast.literal_eval(row)): + self.assertTrue(source.splitlines()[row.lineno - 1].partition("#")[2].strip()) + + @staticmethod + def legacy_reader_uses(): + """Syntactic inventory; reflection, an edited allowlist and a differently + expressed semantic duplicate are outside it. + """ + root = Path(lifecycle.__file__).parent.parent + legacy = {"_open", "_parents", "_ps", "_proc_stat", "_proc_children", "info", "matches", + "children", "descendants", "terminate", "memory", "process_memory", "table"} + uses = Counter() + for directory in ("omp_strata", "scripts"): + for path in (root / directory).rglob("*.py"): + tree = ast.parse(path.read_text()) + relative = path.relative_to(root).as_posix() + bindings = {name: f"procs.{name}" for name in legacy} if relative == "omp_strata/procs.py" else {} + def reader_binding(name): + return name in ("procs", "process_table") or name.startswith("procs.") + def bind(alias, name): + name = name.removeprefix("omp_strata.").removeprefix("lifecycle.") + previous = bindings.get(alias) + if previous is not None and previous != name and (reader_binding(previous) or reader_binding(name)): + raise AssertionError(f"{relative}: conflicting reader binding for {alias}") + bindings[alias] = name + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + bind(alias.asname or alias.name.split(".")[0], alias.name if alias.asname else alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom): + if node.module in ("omp_strata.procs", "procs") and any(a.name == "*" for a in node.names): + raise AssertionError(f"{relative}: reader star imports are not permitted") + for alias in node.names: + bind(alias.asname or alias.name, ".".join(filter(None, (node.module, alias.name)))) + def qualified(node): + if isinstance(node, ast.Name): + return bindings.get(node.id, node.id).removeprefix("omp_strata.").removeprefix("lifecycle.") + if isinstance(node, ast.Attribute): + return f"{qualified(node.value)}.{node.attr}".removeprefix("lifecycle.") + return "" + assignments = [node for node in ast.walk(tree) if isinstance(node, ast.Assign)] + for _ in range(len(assignments) + 1): + changed = False + for node in assignments: + name = qualified(node.value) + for target in node.targets: + if isinstance(target, ast.Name) and reader_binding(name) \ + and bindings.get(target.id) != name: + bind(target.id, name) + changed = True + if not changed: + break + assert not changed, f"ambiguous legacy aliases in {relative}" + for node in assignments: + for target in node.targets: + if isinstance(target, ast.Name) and reader_binding(bindings.get(target.id, "")): + bind(target.id, qualified(node.value)) + parents = {child: node for node in ast.walk(tree) for child in ast.iter_child_nodes(node)} + class Inventory(ast.NodeVisitor): + scope = () + def visit_FunctionDef(self, node): + self.scope += (node.name,) + if node.name == "running": + uses[relative, ".".join(self.scope), "running"] += 1 + self.generic_visit(node) + self.scope = self.scope[:-1] + visit_AsyncFunctionDef = visit_FunctionDef + visit_ClassDef = visit_FunctionDef + def generic_visit(self, node): + name = qualified(node) + reader = name.removeprefix("procs.") if name.startswith("procs.") else None + if name == "process_table": + reader = "process_table" + if name == "running" or name.endswith(".running"): + reader = "running" + if name == "procs" and not isinstance(parents.get(node), ast.Attribute): + reader = "module escape" + if isinstance(node, (ast.Name, ast.Attribute)) and isinstance(node.ctx, ast.Load) \ + and (reader in legacy or reader in ("running", "module escape", "process_table")): + uses[relative, ".".join(self.scope) or "", reader] += 1 + super().generic_visit(node) + Inventory().visit(tree) + return uses + + def test_inventory_rejects_independent_legacy_decisions(self): + source_path = Path(lifecycle.__file__) + original = Path.read_text + shadow = ("def unrelated_record_reader(path):\n" + " from omp_strata.common import read_json as census\n" + " return census(path)\n") + for expression, imports, extra in ( + ("procs.matches(read_json(layout.run_record).get('server'))", "", ""), + ("peek(read_json(layout.run_record).get('server'))", "from omp_strata.procs import matches as peek\n", ""), + ("readers.matches(read_json(layout.run_record).get('server'))", "from omp_strata import procs as readers\n", ""), + ("matches(read_json(layout.run_record).get('server'))", "from omp_strata.procs import *\n", ""), + ("procs.table().identified", "", ""), + ("process_table().identified", "", ""), + ("running(layout)", "", ""), + ("getattr(procs, 'matches')(read_json(layout.run_record).get('server'))", "", ""), + ("census().identified", "from omp_strata.procs import table as census\n", shadow), + ("census().identified", "from omp_strata.lifecycle import process_table as census\n", shadow)): + with self.subTest(expression=expression, imports=imports): + def text(path, *args, **kwargs): + value = original(path, *args, **kwargs) + return value + f"\n{imports}\ndef scratch_fifth_idle(layout):\n return not {expression}\n{extra}" if path == source_path else value + with patch.object(Path, "read_text", autospec=True, side_effect=text), self.assertRaises(AssertionError) as failure: + self.test_the_four_admission_and_status_callers_share_one_verdict() + if extra: + self.assertRegex(str(failure.exception), r"omp_strata/lifecycle\.py.*\bcensus\b") + + def test_the_four_admission_and_status_callers_share_one_verdict(self): + expected = {lifecycle: {"status", "start", "idle_generation"}, cli: {"cmd_install"}} + for module, names in expected.items(): + with self.subTest(module=module.__name__): + tree = ast.parse(Path(module.__file__).read_text()) + callers = {node.name for node in tree.body if isinstance(node, ast.FunctionDef) + and any(isinstance(call, ast.Call) + and (isinstance(call.func, ast.Name) and call.func.id == "verdict" + or isinstance(call.func, ast.Attribute) and call.func.attr == "verdict") + for call in ast.walk(node))} + self.assertEqual(names, callers) + retained = { + "omp_strata/lifecycle.py": { + "process_table": ({"table": 1}, "One accounted census boundary for the verdict; no admission decision."), + "verdict": ({"process_table": 1}, "The sole classifier reads one census for status and admission."), + "serve": ({"info": 4}, "Capture wrapper/server identities at publication, not root admission."), + "start": ({"info": 1, "memory": 1}, "Record launcher identity; RAM gate runs after verdict admission."), + "doctor": ({"matches": 1, "memory": 1}, "Diagnostic port ownership and RAM checks, not idle admission."), + "capture_startup_gpu_order": ({"matches": 4, "descendants": 2}, "Existing live stage-order evidence capture."), + "owned_job_processes": ({"info": 1}, "Identify members of the readiness job snapshot."), + "_finish_start.processes": ({"matches": 1, "descendants": 1}, "Existing post-launch readiness, not admission."), + "status": ({"descendants": 1}, "Engine health only after server-live; never proves idle."), + "stop._stop": ({"matches": 3, "descendants": 1, "terminate": 1}, + "Unmigrated stop target selection and termination, retained until piece 3."), + }, + "omp_strata/procs.py": { + "_proc_children": ({"_proc_stat": 1}, "Legacy procfs child reader."), + "_ps": ({"_proc_stat": 1}, "Legacy fallback when ps is absent."), + "children": ({"_parents": 1, "_proc_children": 1}, "Legacy platform child readers."), + "descendants": ({"children": 1, "info": 2}, "Legacy descendant walk."), + "info": ({"_open": 1, "_parents": 1, "_ps": 1}, "Legacy identity readers."), + "matches": ({"info": 1}, "Legacy individual comparison; verdict does not use it."), + "process_memory": ({"_open": 1}, "Legacy resource observation, not identity comparison."), + "table": ({"info": 1}, "Reader piece uses Windows identity lookup inside accounted snapshot."), + "terminate": ({"_open": 1, "info": 6}, "Legacy termination primitives on both platforms."), + }, + "scripts/gpu_inventory.py": { + "inventory": ({"memory": 1}, "Machine inventory, not root admission."), + }, + "scripts/realhost_gates.py": { + "Sampler._sample_once": ({"memory": 1}, "Existing resource sampling."), + "g10": ({"memory": 1}, "Existing resource gate."), + "g15": ({"terminate": 2}, "Existing realhost engine fault injection, outside this piece."), + "g20": ({"matches": 1}, "Unmigrated cleanup gate; no-match still means no leftover (#94)."), + "kill_tree": ({"descendants": 1, "info": 1, "terminate": 2}, "Existing gate cleanup, outside this piece."), + "server_tree": ({"matches": 1, "descendants": 1}, "Unmigrated gate tree; no-match still means empty (#94)."), + "status_json": ({"running": 3}, "Local HTTP metrics count, not the retired root running() decision."), + "tree_memory": ({"process_memory": 1}, "Existing process resource sampling."), + "watch_tree": ({"descendants": 1}, "Existing gate process-tree sampling."), + }, + } + expected = Counter() + for path, owners in retained.items(): + for owner, (readers, reason) in owners.items(): + self.assertTrue(reason) + expected.update({(path, owner, reader): count for reader, count in readers.items()}) + self.assertEqual(expected, self.legacy_reader_uses()) + + +def ident(pid: int, ppid: int, exe: str) -> procs.ProcInfo: + return procs.ProcInfo(pid, ppid, str(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",)), + "launch-unrecorded": (dict(base, state="launching"), ()), + "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 complete_table(world) + + def matches(recorded): + proc = world.get(int(recorded["pid"])) if recorded else None + return native_matches(proc, recorded) + + 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(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), + 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", "launch-unrecorded", "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, "10011", "/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) + 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.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 + 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, "10020", self.engine_exe) + self.reads.append((readable, dict(self.processes))) + if not readable: + raise procs.TableUnavailable("fixture census unavailable") + return complete_table(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, "_read_record", 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) + 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() + 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 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) + self.assertEqual({}, root.live) + + 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.assertIn("unrecorded[20]", root.live) + + 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_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() + 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 = lifecycle._stop_custody_refusal(root.run) + 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_admission_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) + if advises and lifecycle._stop_custody_refusal(root.run): + raise AssertionError("advised stop fails structural admission") + 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) + + 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", "launch-unrecorded"): + run["state"] = "launching" + if row != "launch-unrecorded": + run["launcher"] = self.p["launcher"].as_dict() + if row == "launch-pending": + 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 = lifecycle._stop_custody_refusal(root.run) + 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 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)) + + 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()) + + +if __name__ == "__main__": + unittest.main()