Files
leleka/scripts/e2e/evidence/run_core.py
T
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

956 lines
50 KiB
Python

#!/usr/bin/env python3
"""Run core of the paired-block runner (STRA-316, S0.3a of STRA-245): schedule, ledger, heartbeat, resume, lock, run-root guard.
The first half of the runner. STRA-257 builds the validity, retry and capture integration on top of this module; this module contains
NO validity rule. It imports validity.py (STRA-312) only for the schedule hash, the ledger vocabulary and, in `finalize`, to DERIVE
`countable` / `invalid_reasons` from the records (the seam of the Train A L1 merge: capture.py writes the neutral placeholders false / [],
which validity.py reports as COUNTABLE_MISMATCH until the runner sets them from the derivation).
Stdlib only, Python >= 3.9 (SC15). Offline, no GPU, no network. It never changes a power, display, lock-screen, sleep, execution-policy or
registry setting (SC3), never deletes a run directory (an invalid run is RENAMED and kept, SC11) and never steals a lock (SC13).
CLI v1 (fixed by the leaf)
run_core.py start --schedule FILE --slot ID --run-root DIR [--ledger FILE] [--lock-dir DIR] [--mode file|mkdir] [--free-gb N] [--rerun]
--run-root is MANDATORY (STRA-327): the STOP file, the lock and the run-root guard are checked before any ledger line
run_core.py lock --run-root DIR --run-id ID --leaf NAME [--lock-dir DIR] [--mode file|mkdir]
run_core.py guard --run-root DIR [--free-gb N]
run_core.py resume --ledger FILE [--schedule FILE] [--run-root DIR]
Additions (same exit-code table)
run_core.py finish --ledger FILE --run-id ID --state DONE|INVALID [--outcome O --attributed-to C] [--records DIR] [--run-dir DIR]
run_core.py unlock --run-root DIR --run-id ID [--lock-dir DIR] [--mode file|mkdir]
exit 0 also when no lock exists any more (guard.ps1 releases it after the cool-down); another run's lock is still exit 4
run_core.py heartbeat --run-dir DIR [--max-age S] reader of heartbeat.json: exit 0 fresh, 13 missing / unreadable / stale
run_core.py finalize --records DIR --schedule FILE --ledger FILE [--machine laptop|server]
the machine is read from the pre-registered schedule (`machine` key, hashed with it); --machine is only a fallback for a
schedule without the key and a flag that conflicts with the schedule is refused (exit 3, MACHINE_MISMATCH; STRA-326)
Exit codes
0 ok | 2 not the next scheduled slot (the message names the scheduled slot) | 3 malformed input or command-line usage error
4 lock held (never waits, never steals) | 5 run root not ignored / inside a linked worktree | 6 less than 20 GB free
7 context_tokens below the 256k class (262144) | 8 schedule differs from the one in the ledger (pre-registration violated)
9 a run is still in flight or not yet resumed | 10 STOP file present | 11 run directory already exists | 12 ledger/manifest refusal (finalize)
13 heartbeat missing, unreadable or stale (heartbeat); launch_arm.py also uses 13 for 'no live watchdog'
Files
schedule JSON {seed, arms, n_pairs, blocks: [{block, order: [arm, ...]}], context_tokens, cache_residency_band: {min, max},
interim_looks, foreign_load_threshold: {cpu_percent_of_core, duration_s}}: the format fixed by the golden fixtures of STRA-311
(golden/validity_cases.json, "fixture_format"), CONFIRMED here unchanged. Slots run in schedule order: block 1 first arm of
its order, ... A slot id is the run id of its first attempt, pair-NNNN.<arm> (NNNN = block number, 4 digits).
ledger JSONL, append-only, ONE fsynced line per state change of a run id. Keys: run_id, state (QUEUED|STARTED|DONE|INVALID|
INTERRUPTED), pair_id, block, arm, schedule_sha256, utc, pid, boot_time, attempt; INVALID lines also outcome
(CRASH|TIMEOUT|INTEGRITY_FAILURE) and attributed_to (null | a cause of validity.INFRA_CAUSES). The LAST line of a run id is its
state. A failed attempt that is followed by a re-run is archived as run id <slot>.a<k> (state INVALID), so validity.py
counts every failure exactly once and the plain slot id then carries the successful attempt.
INTERRUPTED convention (STRA-312's validity.py does not read INTERRUPTED): resume appends INTERRUPTED and then, in a second
line, INVALID with outcome CRASH, attributed_to null and interrupted true. An interrupted pair is therefore invalid (SC3) and
read by validity.py as an unattributed failure (ours: FAIL, vanilla: RERUN up to its cap).
run dir <ledger dir>/<pair_id>/<arm>/ ; heartbeat.json (60 s) in it. Invalid run dirs are renamed <arm>.invalid-<UTC>[-n].
lock Windows: <run-root>/../locks/LAPTOP_GPU.lock; the run root MUST be named `runs` (artifacts\\runs -> artifacts\\locks, where
watchdog.ps1 and guard.ps1 look) unless --lock-dir is given, any other name is refused (exit 3, STRA-327); created with CreateFileW CREATE_NEW and share mode 0 (FileShare.None), written, fsynced and
CLOSED at once (watchdog.ps1 and guard.ps1 open it with a shared read to verify the run id). Linux: atomic mkdir of
<run-root>/run.lock with the `owner` file inside. Contents (JSON): leaf, run_id, pid, utc, boot_time, created_by (+ boot_id).
STOP <run-root>/STOP (artifacts\\runs\\STOP of guard.ps1 / STRA-320). start and guard refuse while it exists; resume creates it
(never overwrites) when an interrupted run dates from another boot and --run-root is given. Only the owner's recorded
inspection removes it.
"""
import argparse
import ctypes
import datetime
import importlib.util
import json
import os
import re
import shutil
import subprocess
import sys
import threading
import time
# --------------------------------------------------------------------------------------------------------------------------------
# constants
# --------------------------------------------------------------------------------------------------------------------------------
EXIT_OK = 0
EXIT_WRONG_SLOT = 2
EXIT_MALFORMED = 3
EXIT_LOCK_HELD = 4
EXIT_NOT_IGNORED = 5
EXIT_LOW_DISK = 6
EXIT_CONTEXT_FLOOR = 7
EXIT_SCHEDULE_CHANGED = 8
EXIT_IN_FLIGHT = 9
EXIT_STOP_FILE = 10
EXIT_RUN_DIR_EXISTS = 11
EXIT_LEDGER_REFUSAL = 12
EXIT_HEARTBEAT = 13
CONTEXT_FLOOR_TOKENS = 262144 # 256k class; a schedule below it is refused (the equality is validity.py's rule)
MIN_FREE_GB = 20.0 # SC11, a DEVOPS proposal (comment 7b25fb7b); GB = 2**30 bytes as in `df -B1G`
HEARTBEAT_INTERVAL_S = 60.0 # DEVOPS D-1
HEARTBEAT_POLL_S = 1.0
BOOT_TOLERANCE_S = 60.0 # two boot-time readings closer than this are the same boot
LOCK_FILE_NAME = "LAPTOP_GPU.lock" # watchdog.ps1 / guard.ps1 / STRA-291 name
LOCK_DIR_NAME = "run.lock" # Linux: atomic mkdir directory in the run root, `owner` inside
STOP_FILE_NAME = "STOP" # guard.ps1 / STRA-320 name, at the root of the runs directory
STATES = ("QUEUED", "STARTED", "DONE", "INVALID", "INTERRUPTED")
SCHEDULE_KEYS = ("seed", "arms", "n_pairs", "blocks", "context_tokens", "cache_residency_band", "interim_looks", "foreign_load_threshold")
CREATED_BY = "run_core.py"
STILL_ACTIVE = 259
class RunCoreError(Exception):
"""A refusal; .code is the process exit code."""
def __init__(self, code, message, **extra):
Exception.__init__(self, message)
self.code = code
self.extra = extra
# --------------------------------------------------------------------------------------------------------------------------------
# small helpers
# --------------------------------------------------------------------------------------------------------------------------------
def utc_now():
return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def _load_validity():
"""validity.py (STRA-312) beside this file; loaded lazily so the other commands do not depend on it."""
cached = sys.modules.get("_run_core_validity")
if cached is not None:
return cached
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "validity.py")
if not os.path.isfile(path):
raise RunCoreError(EXIT_MALFORMED, "validity.py not found beside run_core.py: %s" % path)
spec = importlib.util.spec_from_file_location("_run_core_validity", path)
module = importlib.util.module_from_spec(spec)
sys.modules["_run_core_validity"] = module
spec.loader.exec_module(module)
return module
def schedule_sha256(sched):
"""The schedule hash of validity.py (sha256 of the compact sorted-key JSON): ONE definition, imported."""
return _load_validity().schedule_hash(sched)
def _fsync_dir(path):
if os.name == "nt":
return
fd = os.open(path or ".", os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
def _write_atomic(path, text):
tmp = "%s.tmp.%d" % (path, os.getpid())
with open(tmp, "w", encoding="utf-8", newline="\n") as fh:
fh.write(text)
fh.flush()
os.fsync(fh.fileno())
last = None
for _ in range(5):
try:
os.replace(tmp, path)
return
except PermissionError as exc: # a reader holds the file for a moment (Windows)
last = exc
time.sleep(0.05)
raise last
def _read_json(path, what):
try:
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)
except (OSError, ValueError) as exc:
raise RunCoreError(EXIT_MALFORMED, "%s %s: %s" % (what, path, exc))
def pair_id_of(block):
return "pair-%04d" % block
# --------------------------------------------------------------------------------------------------------------------------------
# machine facts: boot time, process liveness
# --------------------------------------------------------------------------------------------------------------------------------
_BOOT_CACHE = {}
def boot_time_iso():
"""Boot time of this machine as an ISO-8601 UTC string, cached per process.
Windows: the same value as `(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o')`, because
watchdog.ps1 and guard.ps1 compare the lock's boot_time with that string (a read-only query). Linux: /proc/stat btime."""
if "v" in _BOOT_CACHE:
return _BOOT_CACHE["v"]
value = None
if os.name == "nt":
command = "(Get-CimInstance -ClassName Win32_OperatingSystem -Property LastBootUpTime).LastBootUpTime.ToUniversalTime().ToString('o')"
try:
out = subprocess.run(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", command], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, universal_newlines=True, timeout=60)
text = out.stdout.strip()
if out.returncode == 0 and re.match(r"^\d{4}-\d\d-\d\dT", text):
value = text
except (OSError, subprocess.SubprocessError):
value = None
if value is None: # fallback: uptime from GetTickCount64 (second resolution; may differ from the CIM string)
try:
k32 = ctypes.WinDLL("kernel32")
k32.GetTickCount64.restype = ctypes.c_uint64
boot = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(milliseconds=int(k32.GetTickCount64()))
value = boot.replace(microsecond=0).strftime("%Y-%m-%dT%H:%M:%S.0000000Z")
except (OSError, AttributeError):
value = None
else:
try:
with open("/proc/stat", "r") as fh:
for raw in fh:
if raw.startswith("btime "):
stamp = datetime.datetime.fromtimestamp(int(raw.split()[1]), datetime.timezone.utc)
value = stamp.strftime("%Y-%m-%dT%H:%M:%S.0000000Z")
break
except (OSError, ValueError):
value = None
_BOOT_CACHE["v"] = value or "unknown"
return _BOOT_CACHE["v"]
def linux_boot_id():
try:
with open("/proc/sys/kernel/random/boot_id", "r") as fh:
return fh.read().strip()
except OSError:
return None
def _parse_instant(text):
if not isinstance(text, str):
return None
m = re.match(r"^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?Z?$", text.strip())
if not m:
return None
y, mo, d, h, mi, s = (int(m.group(i)) for i in range(1, 7))
frac = float("0." + m.group(7)) if m.group(7) else 0.0
return datetime.datetime(y, mo, d, h, mi, s, tzinfo=datetime.timezone.utc).timestamp() + frac
def same_boot(a, b):
"""True when the two boot-time readings are the same boot (within BOOT_TOLERANCE_S); unparsable values compare as text."""
pa, pb = _parse_instant(a), _parse_instant(b)
if pa is None or pb is None:
return a == b
return abs(pa - pb) <= BOOT_TOLERANCE_S
def pid_alive(pid):
"""Whether a process with this PID exists. Never signals the process (os.kill with a signal terminates on Windows)."""
if isinstance(pid, bool) or not isinstance(pid, int) or pid <= 0:
return False
if os.name == "nt":
from ctypes import wintypes
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.OpenProcess.restype = ctypes.c_void_p
k32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
k32.GetExitCodeProcess.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.DWORD)]
k32.GetExitCodeProcess.restype = wintypes.BOOL
k32.CloseHandle.argtypes = [ctypes.c_void_p]
handle = k32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
if not handle:
return ctypes.get_last_error() == 5 # access denied: it exists
try:
code = wintypes.DWORD()
if not k32.GetExitCodeProcess(handle, ctypes.byref(code)):
return True
return code.value == STILL_ACTIVE
finally:
k32.CloseHandle(handle)
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
except PermissionError:
return True
return True
# --------------------------------------------------------------------------------------------------------------------------------
# schedule
# --------------------------------------------------------------------------------------------------------------------------------
def read_schedule(path):
"""Reads the pre-registered schedule. Returns (schedule, sha256). Refuses a malformed one (3) and a context below 256k (7).
Structure only; the balance rule of E1 is validity.schedule_balanced and is the runner's (STRA-257) call."""
sched = _read_json(path, "schedule")
if not isinstance(sched, dict):
raise RunCoreError(EXIT_MALFORMED, "schedule %s is not a JSON object" % path)
missing = [k for k in SCHEDULE_KEYS if k not in sched]
if missing:
raise RunCoreError(EXIT_MALFORMED, "schedule %s lacks: %s" % (path, ", ".join(missing)))
ctx = sched["context_tokens"]
if isinstance(ctx, bool) or not isinstance(ctx, int):
raise RunCoreError(EXIT_MALFORMED, "schedule context_tokens must be an integer, got %r" % (ctx,))
if ctx < CONTEXT_FLOOR_TOKENS:
raise RunCoreError(EXIT_CONTEXT_FLOOR, "context_tokens %d is below the 256k class (%d); a run below it is refused"
% (ctx, CONTEXT_FLOOR_TOKENS))
arms, blocks = sched["arms"], sched["blocks"]
if not isinstance(arms, list) or not arms or len(set(arms)) != len(arms) or not all(isinstance(a, str) and a for a in arms):
raise RunCoreError(EXIT_MALFORMED, "schedule arms must be a non-empty list of distinct names")
if not isinstance(blocks, list) or sched["n_pairs"] != len(blocks):
raise RunCoreError(EXIT_MALFORMED, "schedule n_pairs must equal the number of blocks")
numbers = []
for b in blocks:
if not isinstance(b, dict) or isinstance(b.get("block"), bool) or not isinstance(b.get("block"), int) \
or not isinstance(b.get("order"), list) or sorted(b["order"]) != sorted(arms):
raise RunCoreError(EXIT_MALFORMED, "every block needs an integer block and an order that is a permutation of the arms")
numbers.append(b["block"])
if sorted(numbers) != list(range(1, len(blocks) + 1)):
raise RunCoreError(EXIT_MALFORMED, "block numbers must be 1..n_pairs")
return sched, schedule_sha256(sched)
def schedule_slots(sched):
"""All slots in schedule order: [{run_id, pair_id, block, arm, position}]."""
out = []
for b in sorted(sched["blocks"], key=lambda x: x["block"]):
for pos, arm in enumerate(b["order"], 1):
out.append({"run_id": "%s.%s" % (pair_id_of(b["block"]), arm), "pair_id": pair_id_of(b["block"]), "block": b["block"],
"arm": arm, "position": pos})
return out
# --------------------------------------------------------------------------------------------------------------------------------
# ledger
# --------------------------------------------------------------------------------------------------------------------------------
def read_ledger(path):
"""Returns (all lines, last line per run id). A missing file is an empty ledger."""
lines, last = [], {}
if not os.path.exists(path):
return lines, last
try:
with open(path, "r", encoding="utf-8") as fh:
text = fh.read()
except OSError as exc:
raise RunCoreError(EXIT_MALFORMED, "ledger %s: %s" % (path, exc))
for n, raw in enumerate(text.splitlines(), 1):
if not raw.strip():
continue
try:
line = json.loads(raw)
except ValueError as exc:
raise RunCoreError(EXIT_MALFORMED, "ledger %s line %d is not JSON: %s" % (path, n, exc))
if not isinstance(line, dict) or not isinstance(line.get("run_id"), str) or line.get("state") not in STATES:
raise RunCoreError(EXIT_MALFORMED, "ledger %s line %d needs a string run_id and a state of %s" % (path, n, "|".join(STATES)))
lines.append(line)
last[line["run_id"]] = line
return lines, last
def append_ledger(path, line):
"""Appends ONE JSON line and fsyncs it (and, off Windows, the directory)."""
data = (json.dumps(line, separators=(",", ":")) + "\n").encode("utf-8")
existed = os.path.exists(path)
flags = os.O_WRONLY | os.O_APPEND | os.O_CREAT | getattr(os, "O_BINARY", 0)
fd = os.open(path, flags, 0o644)
try:
os.write(fd, data)
os.fsync(fd)
finally:
os.close(fd)
if not existed:
_fsync_dir(os.path.dirname(os.path.abspath(path)))
class Context(object):
"""Injectable clock, PID, boot time and liveness probe (tests replace them)."""
def __init__(self, now=utc_now, pid=os.getpid, boot=boot_time_iso, alive=pid_alive):
self.now, self.pid, self.boot, self.alive = now, pid, boot, alive
def make_line(ctx, sha, slot_like, run_id, state, **extra):
line = {"run_id": run_id, "state": state, "pair_id": slot_like["pair_id"], "block": slot_like["block"], "arm": slot_like["arm"],
"schedule_sha256": sha, "utc": ctx.now(), "pid": ctx.pid(), "boot_time": ctx.boot()}
line.update(extra)
return line
def check_same_schedule(lines, sha):
for line in lines:
if line.get("schedule_sha256") != sha:
raise RunCoreError(EXIT_SCHEDULE_CHANGED, "the schedule hash %s differs from the one in the ledger (%s on run %s); the "
"schedule is pre-registered and must not change within a series" % (sha, line.get("schedule_sha256"),
line.get("run_id")))
def next_slot(slots, last):
"""The first slot in schedule order that is neither DONE nor INVALID; None when the schedule is complete."""
for slot in slots:
state = last.get(slot["run_id"], {}).get("state")
if state not in ("DONE", "INVALID"):
return slot
return None
def keep_invalid_dir(path, stamp=None):
"""Renames a run directory to <name>.invalid-<UTC>[-n] and returns the new path. Never deletes, never overwrites."""
if not os.path.isdir(path):
return None
stamp = stamp or re.sub(r"[^0-9TZ]", "", utc_now())[:16]
base = "%s.invalid-%s" % (path.rstrip("\\/"), stamp)
target, n = base, 1
while os.path.exists(target):
n += 1
target = "%s-%d" % (base, n)
os.rename(path, target)
return target
def run_dir_for(ledger_path, line):
return os.path.join(os.path.dirname(os.path.abspath(ledger_path)), line["pair_id"], line["arm"])
def _scheduled_message(slot, requested):
if slot is None:
return "slot %s is not the next scheduled slot: the schedule is complete (no slot is left)" % requested
return "slot %s is not the next scheduled slot; the scheduled slot is %s (block %d, position %d)" % (
requested, slot["run_id"], slot["block"], slot["position"])
def start_slot(schedule_path, slot_id, ledger_path, rerun=False, ctx=None):
"""Starts a slot: refuses anything but the next scheduled slot (2), a changed schedule (8) and a run in flight (9), creates the run
directory (11) and appends QUEUED and STARTED. Returns the info dict."""
ctx = ctx or Context()
sched, sha = read_schedule(schedule_path)
slots = schedule_slots(sched)
by_id = dict((s["run_id"], s) for s in slots)
lines, last = read_ledger(ledger_path)
check_same_schedule(lines, sha)
if slot_id not in by_id:
raise RunCoreError(EXIT_WRONG_SLOT, _scheduled_message(next_slot(slots, last), slot_id), scheduled_slot=(next_slot(slots, last) or {}).get("run_id"))
open_runs = sorted(rid for rid, ln in last.items() if ln["state"] in ("QUEUED", "STARTED", "INTERRUPTED"))
if open_runs:
raise RunCoreError(EXIT_IN_FLIGHT, "run(s) %s are still in flight or not settled; run `resume` first" % ", ".join(open_runs),
in_flight=open_runs)
if rerun:
invalid = [s for s in slots if last.get(s["run_id"], {}).get("state") == "INVALID"]
target = invalid[0] if invalid else None
if target is None or target["run_id"] != slot_id:
raise RunCoreError(EXIT_WRONG_SLOT, "slot %s cannot be re-run; the earliest INVALID slot is %s" % (
slot_id, target["run_id"] if target else "none"), scheduled_slot=target["run_id"] if target else None)
else:
target = next_slot(slots, last)
if target is None or target["run_id"] != slot_id:
raise RunCoreError(EXIT_WRONG_SLOT, _scheduled_message(target, slot_id), scheduled_slot=target["run_id"] if target else None)
slot = by_id[slot_id]
run_dir = os.path.join(os.path.dirname(os.path.abspath(ledger_path)), slot["pair_id"], slot["arm"])
attempt = 1
if rerun:
failed = last[slot_id]
archived = sorted(rid for rid in last if rid.startswith(slot_id + ".a"))
attempt = len(archived) + 2
kept = keep_invalid_dir(run_dir)
extra = {"attempt": len(archived) + 1, "archived_from": slot_id}
for key in ("outcome", "attributed_to", "interrupted"):
if key in failed:
extra[key] = failed[key]
append_ledger(ledger_path, make_line(ctx, sha, slot, "%s.a%d" % (slot_id, len(archived) + 1), "INVALID", **extra))
if kept:
sys.stderr.write("kept previous run directory as %s\n" % kept)
elif os.path.exists(run_dir):
raise RunCoreError(EXIT_RUN_DIR_EXISTS, "run directory %s already exists; it is never overwritten or deleted" % run_dir)
os.makedirs(run_dir)
append_ledger(ledger_path, make_line(ctx, sha, slot, slot_id, "QUEUED", attempt=attempt))
append_ledger(ledger_path, make_line(ctx, sha, slot, slot_id, "STARTED", attempt=attempt))
return {"run_id": slot_id, "pair_id": slot["pair_id"], "block": slot["block"], "arm": slot["arm"], "attempt": attempt,
"schedule_sha256": sha, "run_dir": run_dir, "ledger": os.path.abspath(ledger_path)}
def finish_run(ledger_path, run_id, state, outcome=None, attributed_to=None, records_dir=None, run_dir=None, ctx=None):
"""DONE or INVALID for a STARTED run. INVALID renames run_dir (kept, never deleted). DONE with records_dir needs <run_id>.json."""
ctx = ctx or Context()
lines, last = read_ledger(ledger_path)
cur = last.get(run_id)
if cur is None or cur["state"] != "STARTED":
raise RunCoreError(EXIT_MALFORMED, "run %s is not STARTED (state: %s)" % (run_id, cur["state"] if cur else "unknown"))
extra = {"attempt": cur.get("attempt", 1)}
if state == "DONE":
if records_dir is not None and not os.path.isfile(os.path.join(records_dir, run_id + ".json")):
raise RunCoreError(EXIT_MALFORMED, "run %s cannot be DONE: no record %s.json in %s" % (run_id, run_id, records_dir))
elif state == "INVALID":
v = _load_validity()
if outcome not in v.OUTCOMES:
raise RunCoreError(EXIT_MALFORMED, "INVALID needs --outcome of %s" % "|".join(v.OUTCOMES))
if attributed_to is not None and attributed_to not in v.INFRA_CAUSES:
raise RunCoreError(EXIT_MALFORMED, "--attributed-to must be one of %s" % "|".join(v.INFRA_CAUSES))
extra.update({"outcome": outcome, "attributed_to": attributed_to})
else:
raise RunCoreError(EXIT_MALFORMED, "state must be DONE or INVALID")
append_ledger(ledger_path, make_line(ctx, cur["schedule_sha256"], cur, run_id, state, **extra))
kept = keep_invalid_dir(run_dir) if (state == "INVALID" and run_dir) else None
return {"run_id": run_id, "state": state, "kept_run_dir": kept}
# --------------------------------------------------------------------------------------------------------------------------------
# resume
# --------------------------------------------------------------------------------------------------------------------------------
def write_stop_file(path, reason, run_id, ctx):
"""Creates the STOP file exclusively; an existing file is never changed. Returns True when created."""
body = json.dumps({"kind": "STOP", "reason": reason, "run_id": run_id, "utc": ctx.now(), "created_by": CREATED_BY}) + "\n"
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o644)
except FileExistsError:
return False
try:
os.write(fd, body.encode("utf-8"))
os.fsync(fd)
finally:
os.close(fd)
return True
def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None):
"""Settles the runs a dead process left behind and reports where to continue. A run whose last state is QUEUED or STARTED and whose
recorded process is gone (or whose boot time differs) gets INTERRUPTED and then INVALID (outcome CRASH, attributed_to null,
interrupted true) and its run directory is renamed and kept. A live owner is left alone ('in_flight')."""
ctx = ctx or Context()
lines, last = read_ledger(ledger_path)
sha = None
slots = None
if schedule_path:
sched, sha = read_schedule(schedule_path)
check_same_schedule(lines, sha)
slots = schedule_slots(sched)
interrupted, in_flight, stale_heartbeat, reboot, stop = [], [], [], False, None
current_boot = ctx.boot()
for run_id in sorted(last):
cur = last[run_id]
state = cur["state"]
if state not in ("QUEUED", "STARTED", "INTERRUPTED"):
continue
if state != "INTERRUPTED":
same = same_boot(cur.get("boot_time"), current_boot)
alive = same and ctx.alive(cur.get("pid"))
if alive:
in_flight.append(run_id)
beat = read_heartbeat(run_dir_for(ledger_path, cur))
if beat["state"] != "fresh": # STRA-327: the owner's pid is alive but its heartbeat is not: reported, never acted on
stale_heartbeat.append(run_id)
continue
reason = "process %s is gone" % cur.get("pid") if same else "boot time %s differs from the current boot %s" % (cur.get("boot_time"), current_boot)
append_ledger(ledger_path, make_line(ctx, cur["schedule_sha256"], cur, run_id, "INTERRUPTED", attempt=cur.get("attempt", 1),
owner_pid=cur.get("pid"), reason=reason))
if not same:
reboot = True
append_ledger(ledger_path, make_line(ctx, cur["schedule_sha256"], cur, run_id, "INVALID", attempt=cur.get("attempt", 1),
outcome="CRASH", attributed_to=None, interrupted=True))
keep_invalid_dir(run_dir_for(ledger_path, cur))
interrupted.append(run_id)
if reboot and run_root:
os.makedirs(run_root, exist_ok=True)
stop_path = os.path.join(run_root, STOP_FILE_NAME)
write_stop_file(stop_path, "an interrupted run dates from another boot: %s" % ", ".join(interrupted), interrupted[0], ctx)
stop = stop_path
if slots is not None:
_, last = read_ledger(ledger_path)
nxt = next_slot(slots, last) if slots is not None else None
return {"interrupted": interrupted, "in_flight": in_flight, "stale_heartbeat": stale_heartbeat, "reboot_detected": reboot, "stop_file": stop,
"next_slot": nxt["run_id"] if nxt else None, "schedule_complete": (slots is not None and nxt is None)}
# --------------------------------------------------------------------------------------------------------------------------------
# heartbeat
# --------------------------------------------------------------------------------------------------------------------------------
class Heartbeat(object):
"""heartbeat.json of a detached run, rewritten at least every `interval` seconds (60, DEVOPS D-1). `clock` is injectable: tests drive
poll() with a fake clock; start() runs poll() on a daemon thread every `poll_s` seconds."""
def __init__(self, path, run_id, interval=HEARTBEAT_INTERVAL_S, poll_s=HEARTBEAT_POLL_S, clock=time.monotonic, now=utc_now,
pid=os.getpid):
self.path, self.run_id, self.interval, self.poll_s = path, run_id, float(interval), float(poll_s)
self.clock, self.now, self.pid = clock, now, pid
self.seq = 0
self.last = None
self._stop = threading.Event()
self._thread = None
def beat(self):
self.seq += 1
self.last = self.clock()
_write_atomic(self.path, json.dumps({"run_id": self.run_id, "pid": self.pid(), "utc": self.now(), "seq": self.seq,
"interval_s": self.interval}) + "\n")
def poll(self):
"""Writes when the next poll would already be too late. Returns True when it wrote."""
if self.last is None or (self.clock() - self.last) >= self.interval - self.poll_s:
self.beat()
return True
return False
def start(self):
self.poll()
def loop():
while not self._stop.wait(self.poll_s):
self.poll()
self._thread = threading.Thread(target=loop, name="run_core-heartbeat", daemon=True)
self._thread.start()
return self
def stop(self):
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=5)
# --------------------------------------------------------------------------------------------------------------------------------
# lock (SC13)
# --------------------------------------------------------------------------------------------------------------------------------
def lock_location(run_root, lock_dir=None, mode=None):
"""Returns (mode, directory, lock path, owner-file path). mode: file (Windows) or mkdir (Linux)."""
mode = mode or ("file" if os.name == "nt" else "mkdir")
if mode not in ("file", "mkdir"):
raise RunCoreError(EXIT_MALFORMED, "lock mode must be file or mkdir")
root = os.path.abspath(run_root)
if mode == "file":
if lock_dir:
directory = os.path.abspath(lock_dir)
elif os.path.basename(root).lower() == "runs":
directory = os.path.join(os.path.dirname(root), "locks")
else: # STRA-327: watchdog.ps1 / guard.ps1 only look in <artifacts>\\locks; a lock elsewhere would be invisible to them
raise RunCoreError(EXIT_MALFORMED, "run root %s is not named `runs`: the lock would not be at <artifacts>\\locks where "
"watchdog.ps1 and guard.ps1 look; name the run root `runs` or pass --lock-dir" % root)
path = os.path.join(directory, LOCK_FILE_NAME)
return mode, directory, path, path
path = os.path.abspath(lock_dir) if lock_dir else os.path.join(root, LOCK_DIR_NAME)
return mode, os.path.dirname(path), path, os.path.join(path, "owner")
def _create_exclusive_file(path, data):
"""CREATE_NEW with share mode 0 (FileShare.None) on Windows, O_EXCL elsewhere. The handle is closed before returning."""
if os.name == "nt":
import msvcrt
from ctypes import wintypes
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateFileW.restype = ctypes.c_void_p
k32.CreateFileW.argtypes = [wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD,
ctypes.c_void_p]
handle = k32.CreateFileW(path, 0x40000000, 0, None, 1, 0x80, None) # GENERIC_WRITE, share none, CREATE_NEW, NORMAL
invalid = (1 << (8 * ctypes.sizeof(ctypes.c_void_p))) - 1
if handle is None or handle == invalid:
err = ctypes.get_last_error()
if err in (80, 32) or (err == 5 and os.path.exists(path)): # FILE_EXISTS, SHARING_VIOLATION, delete pending
raise FileExistsError(path)
raise OSError(err, "CreateFileW failed for %s" % path)
fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY)
else:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
try:
os.write(fd, data)
os.fsync(fd)
finally:
os.close(fd)
def _read_holder(path):
try:
with open(path, "r", encoding="utf-8") as fh:
holder = json.load(fh)
return holder if isinstance(holder, dict) else None
except (OSError, ValueError):
return None
def _holder_text(holder, path, alive):
if holder is None:
return "the lock at %s exists and cannot be read; never stolen, needs inspection" % path
text = "the lock at %s is held by run %s (leaf %s, pid %s, since %s)" % (path, holder.get("run_id"), holder.get("leaf"), holder.get("pid"),
holder.get("utc"))
if alive is False:
text += "; its process is gone: never taken over automatically, needs inspection (SC3)"
return text + "; this command never waits"
def acquire_lock(run_root, run_id, leaf, lock_dir=None, mode=None, ctx=None):
"""Takes the in-run lock or raises RunCoreError(4) at once. Returns the lock info."""
ctx = ctx or Context()
mode, directory, path, owner = lock_location(run_root, lock_dir, mode)
content = {"leaf": leaf, "run_id": run_id, "pid": ctx.pid(), "utc": ctx.now(), "boot_time": ctx.boot(), "created_by": CREATED_BY}
if mode == "mkdir":
content["boot_id"] = linux_boot_id()
data = (json.dumps(content, indent=2) + "\n").encode("utf-8")
os.makedirs(directory, exist_ok=True)
if os.name == "nt":
attrs = getattr(os.lstat(directory), "st_file_attributes", 0)
if attrs & 0x400: # FILE_ATTRIBUTE_REPARSE_POINT
raise RunCoreError(EXIT_LOCK_HELD, "lock directory %s is a reparse point; refused" % directory)
try:
if mode == "file":
_create_exclusive_file(path, data)
else:
os.mkdir(path) # atomic
try:
_create_exclusive_file(owner, data)
except BaseException:
if not os.path.exists(owner):
os.rmdir(path) # our own, still empty directory
raise
except FileExistsError:
holder = _read_holder(owner)
alive = ctx.alive(holder.get("pid")) if holder is not None and holder.get("pid") is not None else None
raise RunCoreError(EXIT_LOCK_HELD, _holder_text(holder, path, alive), holder=holder, lock=path)
return {"lock": owner, "mode": mode, "content": content}
def release_lock(run_root, run_id, lock_dir=None, mode=None):
"""Releases the lock of THIS run id only; any other lock is refused (4)."""
mode, directory, path, owner = lock_location(run_root, lock_dir, mode)
if not os.path.exists(path): # STRA-327: guard.ps1 releases the lock itself after the cool-down; nothing left to release is success
return {"released": None, "already_released": True, "lock": owner}
holder = _read_holder(owner)
if holder is None or holder.get("run_id") != run_id:
raise RunCoreError(EXIT_LOCK_HELD, "the lock at %s is not held by run %s; not released" % (path, run_id), holder=holder)
os.remove(owner)
if mode == "mkdir":
os.rmdir(path)
return {"released": owner}
# --------------------------------------------------------------------------------------------------------------------------------
# start preconditions (STRA-327): STOP file and lock are checked before a slot is started, not only by the PowerShell side
# --------------------------------------------------------------------------------------------------------------------------------
def check_stop(run_root):
"""Refuses (10) while <run-root>/STOP exists. Cheap and first: it needs no git and no disk probe."""
stop = os.path.join(os.path.abspath(run_root), STOP_FILE_NAME)
if os.path.exists(stop):
raise RunCoreError(EXIT_STOP_FILE, "STOP file present at %s; only the owner's recorded inspection clears it (SC3)" % stop)
def check_lock(run_root, slot_id, lock_dir=None, mode=None, ctx=None):
"""Refuses (4) with a named reason when a lock is in the way of starting `slot_id`: LOCK_UNREADABLE, LOCK_FOREIGN (another run id) or
LOCK_STALE (this slot's lock, but its process is gone or it dates from another boot). No lock, or this slot's live lock (taken by
its own runner), passes. Never removes or takes over anything."""
ctx = ctx or Context()
mode, directory, path, owner = lock_location(run_root, lock_dir, mode)
if not os.path.exists(path):
return {"lock": None}
holder = _read_holder(owner)
if holder is None:
raise RunCoreError(EXIT_LOCK_HELD, "LOCK_UNREADABLE: " + _holder_text(None, path, None), holder=None, lock=path, reason="LOCK_UNREADABLE")
if holder.get("run_id") != slot_id:
raise RunCoreError(EXIT_LOCK_HELD, "LOCK_FOREIGN: " + _holder_text(holder, path, None), holder=holder, lock=path, reason="LOCK_FOREIGN")
alive = same_boot(holder.get("boot_time"), ctx.boot()) and holder.get("pid") is not None and ctx.alive(holder.get("pid"))
if not alive:
raise RunCoreError(EXIT_LOCK_HELD, "LOCK_STALE: " + _holder_text(holder, path, False), holder=holder, lock=path, reason="LOCK_STALE")
return {"lock": path, "holder": holder}
def check_start_preconditions(run_root, slot_id, lock_dir=None, mode=None, free_gb=None, ctx=None):
"""STOP file, then lock, then the run-root guard (git-ignored, outside a linked worktree, >= 20 GB free, STOP again)."""
check_stop(run_root)
check_lock(run_root, slot_id, lock_dir, mode, ctx)
return guard_run_root(run_root, free_gb)
# --------------------------------------------------------------------------------------------------------------------------------
# heartbeat reader (STRA-327)
# --------------------------------------------------------------------------------------------------------------------------------
def read_heartbeat(run_dir, max_age_s=None, now=None):
"""Reads <run_dir>/heartbeat.json. Returns {"state": fresh|stale|missing|unreadable, "age_s": float|None, "heartbeat": doc|None}.
Stale means older than max_age_s (default: three times the interval the writer recorded, 180 s for the 60 s default)."""
path = os.path.join(run_dir, "heartbeat.json")
if not os.path.isfile(path):
return {"state": "missing", "age_s": None, "heartbeat": None, "path": path}
doc = _read_holder(path)
if doc is None or _parse_instant(doc.get("utc")) is None:
return {"state": "unreadable", "age_s": None, "heartbeat": doc, "path": path}
when = _parse_instant(doc["utc"])
current = _parse_instant(now) if now else time.time()
age = current - when
limit = float(max_age_s) if max_age_s is not None else 3.0 * float(doc.get("interval_s") or HEARTBEAT_INTERVAL_S)
return {"state": "fresh" if age <= limit else "stale", "age_s": round(age, 3), "heartbeat": doc, "path": path, "max_age_s": limit}
# --------------------------------------------------------------------------------------------------------------------------------
# run-root guard (SC11)
# --------------------------------------------------------------------------------------------------------------------------------
def _nearest_existing(path):
cur = os.path.abspath(path)
while not os.path.isdir(cur):
parent = os.path.dirname(cur)
if parent == cur:
break
cur = parent
return cur
def _git(cwd, *args):
try:
out = subprocess.run(["git", "-C", cwd] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True,
timeout=60)
return out.returncode, out.stdout.strip(), out.stderr.strip()
except (OSError, subprocess.SubprocessError) as exc:
return 127, "", str(exc)
def free_gb_of(path):
return shutil.disk_usage(_nearest_existing(path)).free / float(2 ** 30)
def guard_run_root(run_root, free_gb=None, free_fn=None):
"""SC11: the run root must be matched by `git check-ignore -v`, must not sit inside a linked worktree (.git\\wt\\<leaf>: worktree
cleanup deletes ignored files), needs >= 20 GB free (free_gb overrides the measurement, for tests only) and must hold no STOP file."""
root = os.path.abspath(run_root)
anchor = _nearest_existing(root)
probe = root.replace("\\", "/").rstrip("/") + "/"
code, out, err = _git(anchor, "check-ignore", "-v", "--", probe)
if code != 0 or not out:
raise RunCoreError(EXIT_NOT_IGNORED, "run root not ignored: `git check-ignore -v` does not match %s%s" % (
root, "" if code == 1 else " (git: %s)" % (err or "exit %d" % code)))
code, gdir, _ = _git(anchor, "rev-parse", "--absolute-git-dir")
code2, common, _ = _git(anchor, "rev-parse", "--path-format=absolute", "--git-common-dir")
if code == 0 and code2 == 0 and os.path.normcase(os.path.realpath(gdir)) != os.path.normcase(os.path.realpath(common)):
raise RunCoreError(EXIT_NOT_IGNORED, "run root not ignored where it survives: %s is inside a linked worktree (%s); `worktree.sh clean` "
"deletes ignored files there. Use artifacts\\runs of the MAIN checkout" % (root, gdir))
free = float(free_gb) if free_gb is not None else (free_fn or free_gb_of)(root)
if free < MIN_FREE_GB:
raise RunCoreError(EXIT_LOW_DISK, "less than 20 GB free on the run volume (%.1f GB free)" % free)
stop = os.path.join(root, STOP_FILE_NAME)
if os.path.exists(stop):
raise RunCoreError(EXIT_STOP_FILE, "STOP file present at %s; only the owner's recorded inspection clears it (SC3)" % stop)
return {"run_root": root, "ignored_by": out, "free_gb": round(free, 1)}
# --------------------------------------------------------------------------------------------------------------------------------
# seam: countable / invalid_reasons from the validity derivation
# --------------------------------------------------------------------------------------------------------------------------------
def finalize_records(records_dir, schedule_path, ledger_path, machine):
"""Sets `countable` and `invalid_reasons` of every record from validity.derive_pairs (the rules stay in validity.py). A typed value
is never trusted: capture.py writes false / [] and the derivation replaces them. Returns a summary."""
v = _load_validity()
sched = _read_json(schedule_path, "schedule")
try:
records = v.read_records(records_dir)
last, _ = v.read_ledger(ledger_path)
result = v.derive_pairs(records, sched, last, machine)
except v.Refusal as exc:
raise RunCoreError(EXIT_LEDGER_REFUSAL, "ledger/manifest refusal: %s" % exc, run_ids=exc.names)
except v.Malformed as exc:
raise RunCoreError(EXIT_MALFORMED, "malformed input: %s" % exc)
by_number = dict((p["pair"], p) for p in result["pairs"])
updated = []
for run_id, rec in sorted(records.items()):
pair = by_number.get(last[run_id].get("block")) if run_id in last else None
if pair is None:
continue
reasons = [r for r in pair["reasons"] if r != "COUNTABLE_MISMATCH"]
derived = (not reasons) and pair["event"] is None
if rec.get("countable") is not derived or rec.get("invalid_reasons") != reasons:
rec["countable"], rec["invalid_reasons"] = derived, reasons
_write_atomic(os.path.join(records_dir, run_id + ".json"), json.dumps(rec, indent=2, ensure_ascii=False) + "\n")
updated.append(run_id)
after = v.derive_pairs(v.read_records(records_dir), sched, last, machine)
mismatches = sorted(p["pair"] for p in after["pairs"] if "COUNTABLE_MISMATCH" in p["reasons"])
return {"pairs": len(result["pairs"]), "updated": updated, "countable_mismatch_after": mismatches,
"valid_pairs": sum(1 for p in after["pairs"] if p["valid"])}
# --------------------------------------------------------------------------------------------------------------------------------
# command line
# --------------------------------------------------------------------------------------------------------------------------------
class _Parser(argparse.ArgumentParser):
def error(self, message): # argparse exits 2 by default; 2 is reserved here for "not the next scheduled slot"
sys.stderr.write("%s: error: %s\n" % (self.prog, message))
raise SystemExit(EXIT_MALFORMED)
def _default_ledger(args):
if args.ledger:
return args.ledger
if getattr(args, "run_root", None):
return os.path.join(args.run_root, "ledger.jsonl")
return os.path.join(os.path.dirname(os.path.abspath(args.schedule)), "ledger.jsonl")
def _emit(obj):
sys.stdout.write(json.dumps(obj, indent=2) + "\n")
def main(argv=None, ctx=None):
parser = _Parser(prog="run_core.py", description=__doc__.split("\n")[0])
sub = parser.add_subparsers(dest="command")
sub.required = True
p = sub.add_parser("start", help="start the next scheduled slot")
p.add_argument("--schedule", required=True)
p.add_argument("--slot", required=True)
p.add_argument("--ledger")
p.add_argument("--run-root", required=True, help="mandatory: STOP file, lock and run-root guard are checked before the slot starts")
p.add_argument("--lock-dir")
p.add_argument("--mode", choices=["file", "mkdir"])
p.add_argument("--free-gb", type=float, help="override the measured free space (tests only)")
p.add_argument("--rerun", action="store_true", help="re-run the earliest INVALID slot (the retry policy is STRA-257's)")
p = sub.add_parser("finish", help="DONE or INVALID for a STARTED run")
p.add_argument("--ledger", required=True)
p.add_argument("--run-id", required=True)
p.add_argument("--state", required=True, choices=["DONE", "INVALID"])
p.add_argument("--outcome")
p.add_argument("--attributed-to")
p.add_argument("--records")
p.add_argument("--run-dir")
p = sub.add_parser("resume", help="settle runs a dead process left behind and print the next slot")
p.add_argument("--ledger", required=True)
p.add_argument("--schedule")
p.add_argument("--run-root")
for name in ("lock", "unlock"):
p = sub.add_parser(name, help="take / release the in-run lock")
p.add_argument("--run-root", required=True)
p.add_argument("--run-id", required=True)
if name == "lock":
p.add_argument("--leaf", required=True)
p.add_argument("--lock-dir")
p.add_argument("--mode", choices=["file", "mkdir"])
p = sub.add_parser("heartbeat", help="read heartbeat.json of a run directory (exit 13 when missing, unreadable or stale)")
p.add_argument("--run-dir", required=True)
p.add_argument("--max-age", type=float, help="seconds; default three times the interval the writer recorded")
p = sub.add_parser("guard", help="run-root guard")
p.add_argument("--run-root", required=True)
p.add_argument("--free-gb", type=float, help="override the measured free space (tests only)")
p = sub.add_parser("finalize", help="set countable / invalid_reasons of the records from validity.py")
p.add_argument("--records", required=True)
p.add_argument("--schedule", required=True)
p.add_argument("--ledger", required=True)
p.add_argument("--machine", choices=["laptop", "server"], help="only for a schedule without a `machine` key; must agree with it otherwise")
args = parser.parse_args(argv)
try:
if args.command == "start":
check_start_preconditions(args.run_root, args.slot, args.lock_dir, args.mode, args.free_gb, ctx)
_emit(start_slot(args.schedule, args.slot, _default_ledger(args), args.rerun, ctx))
elif args.command == "finish":
_emit(finish_run(args.ledger, args.run_id, args.state, args.outcome, args.attributed_to, args.records, args.run_dir, ctx))
elif args.command == "resume":
_emit(resume_ledger(args.ledger, args.schedule, args.run_root, ctx))
elif args.command == "lock":
_emit(acquire_lock(args.run_root, args.run_id, args.leaf, args.lock_dir, args.mode, ctx))
elif args.command == "unlock":
_emit(release_lock(args.run_root, args.run_id, args.lock_dir, args.mode))
elif args.command == "guard":
_emit(guard_run_root(args.run_root, args.free_gb))
elif args.command == "heartbeat":
info = read_heartbeat(args.run_dir, args.max_age)
_emit(info)
if info["state"] != "fresh":
raise RunCoreError(EXIT_HEARTBEAT, "heartbeat of %s is %s" % (args.run_dir, info["state"]), **info)
elif args.command == "finalize":
_emit(finalize_records(args.records, args.schedule, args.ledger, args.machine))
return EXIT_OK
except 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) + "\n")
return exc.code
if __name__ == "__main__":
sys.exit(main())