"""Tests of launch_arm.py (STRA-327): no arm without a live watchdog, STOP / lock / run-root checks before every arm. Run: python -m unittest test_launch_arm -v (from scripts/e2e/evidence, or scripts.e2e.evidence.test_launch_arm from the repository root) Mock only: the watchdog is a fake process object, no PowerShell, no nvidia-smi, no GPU. Stdlib only, Python >= 3.9. """ import importlib.util import itertools import json import os import sys import unittest HERE = os.path.dirname(os.path.abspath(__file__)) def _load(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module _RUN_CORE_TESTS = _load("test_run_core_for_launch", os.path.join(HERE, "test_run_core.py")) Base = _RUN_CORE_TESTS.Base BOOT = _RUN_CORE_TESTS.BOOT LA = _load("launch_arm_under_test", os.path.join(HERE, "launch_arm.py")) RC = LA._load_run_core() # the module launch_arm raises its errors from (a second copy of run_core would be a different class) SLOT = "pair-0001.ours" class FakeWatchdog(object): """A watchdog process that is alive for `polls` polls and then exits with `code`. When `starts_arm`, it records the arm the way watchdog.ps1 does (child_pid in watchdog_summary.json). `arms` collects the arms that were started.""" def __init__(self, argv, code, polls, starts_arm, arms, reason=""): self.argv, self.code, self.polls, self.n = argv, code, polls, 0 root = argv[argv.index("-RunRoot") + 1] os.makedirs(root, exist_ok=True) summary = {"outcome": "COMPLETED" if starts_arm else "REFUSED", "reason": reason, "child_pid": 1234 if starts_arm else None} with open(os.path.join(root, "watchdog_summary.json"), "w", encoding="utf-8") as fh: json.dump(summary, fh) if starts_arm: arms.append(argv[argv.index("-ChildCommand") + 1]) def poll(self): self.n += 1 return None if self.n <= self.polls else self.code class TestLaunchArm(Base): def setUp(self): self.repo = self.git_repo("artifacts/") self.root = os.path.join(self.repo, "artifacts", "runs") os.makedirs(self.root) self.d = self.tmpdir() self.sched = self.schedule_file(self.d) self.ledger = os.path.join(self.root, "ledger.jsonl") self.arms, self.spawned = [], [] ticks = itertools.count() self.clock = lambda: float(next(ticks)) self.watchdog_script = os.path.join(self.d, "watchdog.ps1") with open(self.watchdog_script, "w") as fh: fh.write("# stand-in: never executed") def spawner(self, code=0, polls=3, starts_arm=True, reason="", raises=None): def spawn(argv): self.spawned.append(argv) if raises: raise raises return FakeWatchdog(argv, code, polls, starts_arm, self.arms, reason) return spawn def launch(self, spawn, **kwargs): args = dict(watchdog=self.watchdog_script, spawn=spawn, sleep=lambda s: None, clock=self.clock, settle_s=2.0, mode="file", free_gb=50.0, ctx=self.ctx(boot=BOOT), heartbeat_interval=60.0) args.update(kwargs) return LA.launch(self.sched, SLOT, self.root, ["arm.exe", "--serve", "x y"], 1800, **args) def states(self): return [(ln["run_id"], ln["state"], ln.get("attributed_to")) for ln in self.ledger_lines(self.ledger)] def lock_path(self): return RC.lock_location(self.root, mode="file")[3] def test_ac3_no_arm_starts_when_the_watchdog_cannot_be_started(self): with self.assertRaises(RC.RunCoreError) as cm: self.launch(self.spawner(raises=OSError("powershell not found"))) self.assertEqual(cm.exception.code, LA.EXIT_NO_WATCHDOG) self.assertIn("no live watchdog", str(cm.exception)) self.assertEqual(self.arms, [], "no arm started") self.assertEqual(self.states()[-1], (SLOT, "INVALID", "WATCHDOG")) self.assertFalse(os.path.exists(self.lock_path()), "the lock the launcher took is released") def test_ac3_a_missing_watchdog_script_refuses_before_anything_is_written(self): with self.assertRaises(RC.RunCoreError) as cm: self.launch(self.spawner(), watchdog=os.path.join(self.d, "nope.ps1")) self.assertEqual(cm.exception.code, LA.EXIT_NO_WATCHDOG) self.assertEqual(self.spawned, []) self.assertFalse(os.path.exists(self.ledger), "no ledger line") self.assertFalse(os.path.exists(self.lock_path())) def test_ac3_a_watchdog_that_refuses_at_once_never_had_an_arm(self): for code, cause in ((4, "POWER"), (3, "LOCK"), (2, "WATCHDOG"), (8, "WATCHDOG")): self.tearDown_state() with self.assertRaises(RC.RunCoreError) as cm: self.launch(self.spawner(code=code, polls=0, starts_arm=False, reason="preflight refused")) self.assertEqual(cm.exception.code, LA.EXIT_NO_WATCHDOG, code) self.assertEqual(self.arms, []) self.assertEqual(self.states()[-1], (SLOT, "INVALID", cause), code) def tearDown_state(self): # a fresh run root for the next iteration of a loop self.root = os.path.join(self.repo, "artifacts", "runs") for name in os.listdir(self.root): path = os.path.join(self.root, name) if os.path.isfile(path): os.remove(path) else: os.rename(path, path + ".old%d" % len(os.listdir(self.root))) self.ledger = os.path.join(self.root, "ledger.jsonl") lock_dir = os.path.dirname(self.lock_path()) if os.path.isdir(lock_dir): for name in os.listdir(lock_dir): os.remove(os.path.join(lock_dir, name)) def test_stop_file_foreign_lock_and_stale_lock_start_no_watchdog(self): stop = os.path.join(self.root, "STOP") with open(stop, "w") as fh: fh.write("{}") with self.assertRaises(RC.RunCoreError) as cm: self.launch(self.spawner()) self.assertEqual(cm.exception.code, RC.EXIT_STOP_FILE) os.remove(stop) lock = self.lock_path() os.makedirs(os.path.dirname(lock), exist_ok=True) with open(lock, "w") as fh: json.dump({"leaf": "x", "run_id": "pair-0009.ours", "pid": 1, "utc": "2026-10-28T00:00:00Z", "boot_time": BOOT}, fh) with self.assertRaises(RC.RunCoreError) as cm: self.launch(self.spawner()) self.assertEqual((cm.exception.code, cm.exception.extra["reason"]), (RC.EXIT_LOCK_HELD, "LOCK_FOREIGN")) self.assertEqual(self.spawned, [], "the watchdog (and so the arm) is never started") self.assertFalse(os.path.exists(self.ledger)) def test_happy_path_the_arm_is_the_watchdogs_child_and_the_heartbeat_is_written(self): info = self.launch(self.spawner(code=0, polls=5)) self.assertEqual((info["exit_code"], info["arm_started"]), (0, True)) argv = self.spawned[0] self.assertEqual(argv[argv.index("-ChildCommand") + 1], "arm.exe") self.assertEqual(argv[argv.index("-ChildArguments") + 1], '--serve "x y"') self.assertEqual(argv[argv.index("-RunId") + 1], SLOT) self.assertEqual(argv[argv.index("-ArtifactsRoot") + 1], os.path.dirname(os.path.abspath(self.root))) self.assertEqual(argv[argv.index("-TimeoutSeconds") + 1], "1800.0") self.assertEqual(self.arms, ["arm.exe"]) self.assertEqual([s[:2] for s in self.states()], [(SLOT, "QUEUED"), (SLOT, "STARTED")], "DONE / INVALID of a started run is the runner's") self.assertEqual(RC.read_heartbeat(info["run_dir"])["heartbeat"]["run_id"], SLOT) self.assertFalse(os.path.exists(self.lock_path()), "lock released after a normal finish") def test_a_stall_or_abort_keeps_the_lock(self): info = self.launch(self.spawner(code=7, polls=2, starts_arm=True)) self.assertEqual(info["exit_code"], 7) self.assertTrue(os.path.exists(self.lock_path()), "STALL keeps the lock for the guard and the owner") def test_no_arm_command_is_refused(self): with self.assertRaises(RC.RunCoreError) as cm: LA.launch(self.sched, SLOT, self.root, [], 60, watchdog=self.watchdog_script, spawn=self.spawner(), free_gb=50.0) self.assertEqual(cm.exception.code, RC.EXIT_MALFORMED) def test_command_line_without_an_arm_is_a_usage_error(self): rc = LA.main(["--schedule", self.sched, "--slot", SLOT, "--run-root", self.root, "--timeout-s", "60"]) self.assertEqual(rc, RC.EXIT_MALFORMED) if __name__ == "__main__": unittest.main()