Files
Pavlo RatushnyiandClaude Sonnet 5.5 c27e26407d STRA-327: laptop run wiring - mandatory run root, STOP/lock checks, launcher, heartbeat reader, tolerant unlock
run_core start now requires --run-root and checks, before any ledger line: STOP file (exit 10),
then a foreign / stale / unreadable lock (exit 4, LOCK_FOREIGN / LOCK_STALE / LOCK_UNREADABLE),
then the run-root guard. The Windows lock path needs a run root named `runs` (exit 3 otherwise)
because watchdog.ps1 and guard.ps1 only look in <artifacts>\locks. unlock exits 0 when the lock
is already gone (guard.ps1 releases it after the cool-down); another run's lock is still exit 4.
heartbeat.json gets a reader: `run_core.py heartbeat` (exit 13 when missing/unreadable/stale) and
`resume` reports a live owner whose heartbeat is stale. New launch_arm.py is the only way to
start an arm: the arm is the child of watchdog.ps1, so no watchdog (script missing, not
startable, or ended without starting the arm) means no arm; the slot is then closed INVALID.
Mock/dry tests only; no PowerShell, no GPU. PowerShell scripts are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 01:10:27 +01:00

171 lines
9.4 KiB
Python

#!/usr/bin/env python3
"""Launcher of one laptop arm under the watchdog (STRA-327): the only way the runner starts an arm on the Windows laptop.
Why it exists: run_core.py (STRA-316) owns the schedule, ledger and lock; scripts/laptop/win/watchdog.ps1 (STRA-291, which adopts the
containment of guard.ps1, STRA-320) owns the GPU safeguards. Nothing tied them together, so an arm could be started without the watchdog.
This launcher never runs the arm itself: the arm is the CHILD of watchdog.ps1 (-ChildCommand), so an arm exists only while a watchdog
process exists, and a watchdog that cannot be started means no arm. Before anything is started it enforces, in this order and before the
first ledger line: the watchdog script exists; no STOP file; no foreign / stale / unreadable lock; the run-root guard (git-ignored, not in a
linked worktree, >= 20 GB free). Then it starts the slot (ledger QUEUED + STARTED), takes the lock for the slot's run id (watchdog.ps1
verifies a lock of its own -RunId and makes no second one), writes heartbeat.json in the run directory (read by `run_core.py heartbeat`
and `resume`) and starts the watchdog.
Stdlib only, Python >= 3.9. Offline. It changes no power, display, lock-screen, sleep, execution-policy or registry setting; the
PowerShell child is started with a per-process `-ExecutionPolicy Bypass` as the watchdog's own usage note says.
launch_arm.py --schedule FILE --slot ID --run-root DIR --timeout-s N [--leaf NAME] [--ledger FILE] [--free-gb N] [--rerun]
[--watchdog PATH] [--powershell EXE] -- <arm exe> [arm arguments...]
Exit codes: run_core.py's table for the refusals (2 wrong slot, 3 usage, 4 lock, 5/6 run root, 7, 8, 9, 10 STOP, 11) and
13 no live watchdog (script missing, could not be started, or it ended without starting the arm; the slot is closed INVALID with
attributed_to WATCHDOG / LOCK / POWER and the lock is released)
otherwise the exit code of watchdog.ps1 (0 the arm exited 0, 1 non-zero, 5/6/7 aborted / timeout / STALL: the lock is KEPT for the
guard and the owner; DONE / INVALID for a run that did start is left to the runner after capture, `run_core.py finish`).
"""
import argparse
import importlib.util
import json
import os
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
DEFAULT_WATCHDOG = os.path.join(REPO, "scripts", "laptop", "win", "watchdog.ps1")
EXIT_NO_WATCHDOG = 13
# watchdog.ps1 exit codes that mean the arm was never started, and the cause the slot is attributed to (validity.INFRA_CAUSES)
NOT_STARTED_CAUSE = {2: "WATCHDOG", 3: "LOCK", 4: "POWER", 8: "WATCHDOG"}
KEEP_LOCK_CODES = (5, 6, 7) # aborted / timeout / STALL: the watchdog and guard decide when the lock goes (STALL keeps it for the owner)
def _load_run_core():
cached = sys.modules.get("_launch_arm_run_core")
if cached is not None:
return cached
spec = importlib.util.spec_from_file_location("_launch_arm_run_core", os.path.join(HERE, "run_core.py"))
module = importlib.util.module_from_spec(spec)
sys.modules["_launch_arm_run_core"] = module
spec.loader.exec_module(module)
return module
def watchdog_command(powershell, script, child, child_args, timeout_s, run_id, leaf, artifacts_root, watchdog_run_root):
"""The argv that starts watchdog.ps1 with the arm as its child (usage note in the header of watchdog.ps1)."""
return [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", script,
"-ChildCommand", child, "-ChildArguments", subprocess.list2cmdline(list(child_args)), "-TimeoutSeconds", repr(float(timeout_s)),
"-RunId", run_id, "-Leaf", leaf, "-ArtifactsRoot", artifacts_root, "-RunRoot", watchdog_run_root]
def _spawn(argv):
return subprocess.Popen(argv, stdin=subprocess.DEVNULL)
def _read_summary(watchdog_run_root):
try:
with open(os.path.join(watchdog_run_root, "watchdog_summary.json"), "r", encoding="utf-8-sig") as fh:
doc = json.load(fh)
return doc if isinstance(doc, dict) else {}
except (OSError, ValueError):
return {}
def launch(schedule, slot, run_root, child_cmd, timeout_s, leaf="STRA-257", ledger=None, mode=None, free_gb=None, rerun=False,
watchdog=None, powershell="powershell", spawn=None, settle_s=2.0, poll_s=1.0, sleep=time.sleep, clock=time.monotonic,
ctx=None, heartbeat_interval=None):
"""Starts one arm under the watchdog. Returns the info dict (with exit_code); raises run_core.RunCoreError for a refusal.
spawn(argv) -> object with poll() and wait() (default subprocess.Popen); sleep / clock are injectable for the tests."""
rc = _load_run_core()
ctx = ctx or rc.Context()
spawn = spawn or _spawn
script = os.path.abspath(watchdog or DEFAULT_WATCHDOG)
if not child_cmd:
raise rc.RunCoreError(rc.EXIT_MALFORMED, "no arm command given after --")
if not os.path.isfile(script): # before anything is written: no watchdog, no run
raise rc.RunCoreError(EXIT_NO_WATCHDOG, "no live watchdog: %s does not exist; no ledger line written, no arm started" % script)
run_root = os.path.abspath(run_root)
ledger = ledger or os.path.join(run_root, "ledger.jsonl")
rc.check_start_preconditions(run_root, slot, None, mode, free_gb, ctx)
info = rc.start_slot(schedule, slot, ledger, rerun, ctx)
run_id, run_dir = info["run_id"], info["run_dir"]
watchdog_run_root = os.path.join(run_dir, "watchdog")
result = {"run_id": run_id, "run_dir": run_dir, "watchdog_run_root": watchdog_run_root, "arm_started": False, "watchdog_exit": None}
beat = None
lock_taken = False
def close_slot(cause, why):
"""The arm never started: close the slot INVALID (kept, never deleted), release the lock we took, refuse with 13."""
if beat is not None:
beat.stop() # before the run directory is renamed
rc.finish_run(ledger, run_id, "INVALID", outcome="CRASH", attributed_to=cause, run_dir=run_dir, ctx=ctx)
if lock_taken:
rc.release_lock(run_root, run_id, None, mode)
raise rc.RunCoreError(EXIT_NO_WATCHDOG, "no live watchdog: %s; the arm was not started, slot %s is INVALID (attributed to %s)" % (
why, run_id, cause), **result)
try:
rc.acquire_lock(run_root, run_id, leaf, None, mode, ctx)
lock_taken = True
kwargs = {} if heartbeat_interval is None else {"interval": heartbeat_interval, "poll_s": min(1.0, heartbeat_interval / 2.0)}
beat = rc.Heartbeat(os.path.join(run_dir, "heartbeat.json"), run_id, **kwargs).start()
argv = watchdog_command(powershell, script, child_cmd[0], child_cmd[1:], timeout_s, run_id, leaf, os.path.dirname(run_root),
watchdog_run_root)
try:
proc = spawn(argv)
except OSError as exc:
close_slot("WATCHDOG", "the watchdog could not be started (%s)" % exc)
t0 = clock()
while clock() - t0 < settle_s and proc.poll() is None: # a watchdog that dies at once never had an arm
sleep(min(poll_s, 0.2))
while proc.poll() is None:
sleep(poll_s)
code = proc.poll()
result["watchdog_exit"] = code
summary = _read_summary(watchdog_run_root)
result["arm_started"] = summary.get("child_pid") is not None
if not result["arm_started"] and code in NOT_STARTED_CAUSE:
close_slot(NOT_STARTED_CAUSE[code], "watchdog.ps1 exited %s before starting the arm (%s)" % (code, summary.get("reason") or "no reason recorded"))
if code not in KEEP_LOCK_CODES:
rc.release_lock(run_root, run_id, None, mode) # tolerant: the watchdog / guard may have released it already
return dict(result, exit_code=code)
finally:
if beat is not None:
beat.stop()
def main(argv=None):
argv = list(sys.argv[1:] if argv is None else argv)
child = []
if "--" in argv:
i = argv.index("--")
argv, child = argv[:i], argv[i + 1:]
rc = _load_run_core()
parser = rc._Parser(prog="launch_arm.py", description=__doc__.split("\n")[0])
parser.add_argument("--schedule", required=True)
parser.add_argument("--slot", required=True)
parser.add_argument("--run-root", required=True)
parser.add_argument("--timeout-s", required=True, type=float)
parser.add_argument("--leaf", default="STRA-257")
parser.add_argument("--ledger")
parser.add_argument("--mode", choices=["file", "mkdir"])
parser.add_argument("--free-gb", type=float, help="override the measured free space (tests only)")
parser.add_argument("--rerun", action="store_true")
parser.add_argument("--watchdog", help="default: scripts/laptop/win/watchdog.ps1 of this tree")
parser.add_argument("--powershell", default="powershell")
args = parser.parse_args(argv)
try:
info = launch(args.schedule, args.slot, args.run_root, child, args.timeout_s, args.leaf, args.ledger, args.mode, args.free_gb,
args.rerun, args.watchdog, args.powershell)
rc._emit(info)
return info["exit_code"] if info["exit_code"] is not None else 8
except rc.RunCoreError as exc:
sys.stderr.write("REFUSED (exit %d): %s\n" % (exc.code, exc))
body = {"refused": str(exc), "exit": exc.code}
body.update(exc.extra)
sys.stdout.write(json.dumps(body, default=str) + "\n")
return exc.code
if __name__ == "__main__":
sys.exit(main())