Files
leleka/scripts/e2e/evidence/test_run_core.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 37438d8025 feat(e2e): run core with schedule, fsynced ledger, heartbeat, resume, lock and run-root guard (STRA-316)
New scripts/e2e/evidence/run_core.py and test_run_core.py (stdlib, Python 3.9, no GPU).
Pre-registered schedule reader with hash in every ledger line, next-slot refusal,
append-only fsynced JSONL ledger, resume marking INTERRUPTED, 60 s heartbeat,
exclusive lock (CreateNew/FileShare.None on Windows, mkdir on Linux), run-root
guard (git check-ignore, linked-worktree refusal, 20 GB, STOP file), 256k floor,
and finalize to set countable/invalid_reasons from validity.py.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-28 21:50:11 +01:00

679 lines
34 KiB
Python

"""Tests of run_core.py (STRA-316, S0.3a): schedule, fsynced ledger, heartbeat, resume, exclusive lock, run-root guard.
Run: python -m unittest discover -s scripts/e2e/evidence -p "test_run_core.py" -v (from the repository root)
python -m unittest scripts.e2e.evidence.test_run_core.TestResume -v
Stdlib only, Python >= 3.9. No GPU, no ssh, no network. Scratch directories live under <repo>/artifacts/test-run-core (ignored by Git),
so nothing is written outside the repository; every one is removed again after its test.
"""
import importlib.util
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import tempfile
import time
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
RUN_CORE = os.path.join(HERE, "run_core.py")
VALIDITY = os.path.join(HERE, "validity.py")
GOLDEN = os.path.join(HERE, "golden")
SCRATCH = os.path.join(REPO, "artifacts", "test-run-core")
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
RC = _load("run_core_under_test", RUN_CORE)
V = _load("validity_for_run_core_test", VALIDITY)
G = _load("gen_validity_for_run_core_test", os.path.join(GOLDEN, "gen_validity.py"))
with open(os.path.join(GOLDEN, "validity_cases.json"), "r", encoding="utf-8") as _fh:
DOC = json.load(_fh)
BOOT = "2026-10-01T00:00:00.0000000Z"
OTHER_BOOT = "2026-10-20T00:00:00.0000000Z"
def _force_remove(func, path, _exc): # read-only files inside .git directories
os.chmod(path, stat.S_IWRITE)
func(path)
class Base(unittest.TestCase):
def tmpdir(self):
os.makedirs(SCRATCH, exist_ok=True)
path = tempfile.mkdtemp(prefix="t", dir=SCRATCH)
self.addCleanup(shutil.rmtree, path, False, _force_remove)
return path
def schedule_file(self, directory, context_tokens=None, name="schedule.json"):
sched = json.loads(json.dumps(DOC["schedules"]["pairs_n6"]))
if context_tokens is not None:
sched["context_tokens"] = context_tokens
path = os.path.join(directory, name)
with open(path, "w", encoding="utf-8", newline="\n") as fh:
json.dump(sched, fh, indent=2)
return path
def ctx(self, pid=4242, boot=BOOT, alive=None, clock=None):
ticks = clock if clock is not None else iter(range(10 ** 6))
return RC.Context(now=lambda: "2026-10-28T10:00:%02d.000000Z" % (next(ticks) % 60), pid=lambda: pid, boot=lambda: boot,
alive=alive or (lambda p: False))
def cli(self, *args):
proc = subprocess.run([sys.executable, RUN_CORE] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True, cwd=REPO, timeout=120)
return proc.returncode, proc.stdout, proc.stderr
@staticmethod
def ledger_lines(path):
with open(path, "r", encoding="utf-8") as fh:
return [json.loads(raw) for raw in fh.read().splitlines() if raw.strip()]
def git_repo(self, ignore=None):
repo = self.tmpdir()
subprocess.run(["git", "init", "-q", repo], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if ignore:
with open(os.path.join(repo, ".gitignore"), "w", encoding="utf-8", newline="\n") as fh:
fh.write(ignore + "\n")
return repo
class TestScheduleHash(Base):
def test_every_ledger_line_carries_the_schedule_hash_of_validity_py(self):
d = self.tmpdir()
sched = self.schedule_file(d)
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.ours")
self.assertEqual(rc, 0, err)
info = json.loads(out)
proc = subprocess.run([sys.executable, VALIDITY, "schedule", "--check", sched], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True)
want = json.loads(proc.stdout)["hash"]
lines = self.ledger_lines(os.path.join(d, "ledger.jsonl"))
self.assertEqual([l["state"] for l in lines], ["QUEUED", "STARTED"])
for line in lines:
self.assertEqual(line["schedule_sha256"], want)
self.assertEqual(info["schedule_sha256"], want)
def test_every_line_of_a_longer_series_carries_it_and_the_required_keys(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
ctx = self.ctx()
for slot in ("pair-0001.ours", "pair-0001.vanilla_default"):
RC.start_slot(sched, slot, ledger, ctx=ctx)
RC.finish_run(ledger, slot, "DONE", ctx=ctx)
lines = self.ledger_lines(ledger)
self.assertEqual(len(lines), 6)
hashes = set(l["schedule_sha256"] for l in lines)
self.assertEqual(len(hashes), 1)
for line in lines:
for key in ("run_id", "state", "pair_id", "block", "arm", "schedule_sha256", "utc", "pid", "boot_time"):
self.assertIn(key, line)
# the acceptance one-liner
code = "import json;[json.loads(l)['run_id'] and json.loads(l)['state'] for l in open(%r)]" % ledger
self.assertEqual(subprocess.run([sys.executable, "-c", code]).returncode, 0)
def test_a_changed_schedule_is_refused_exit_8(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=self.ctx())
RC.finish_run(ledger, "pair-0001.ours", "DONE", ctx=self.ctx())
other = self.schedule_file(d, name="other.json")
with open(other, "r+", encoding="utf-8") as fh:
doc = json.load(fh)
doc["seed"] = 8
fh.seek(0)
fh.truncate()
json.dump(doc, fh)
rc, out, err = self.cli("start", "--schedule", other, "--slot", "pair-0001.vanilla_default", "--ledger", ledger)
self.assertEqual(rc, RC.EXIT_SCHEDULE_CHANGED, err)
self.assertIn("pre-registered", err)
class TestContextFloor(Base):
def test_schedule_below_256k_is_refused_with_exit_7(self):
d = self.tmpdir()
sched = self.schedule_file(d, context_tokens=131072)
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.ours")
self.assertEqual(rc, RC.EXIT_CONTEXT_FLOOR, err)
self.assertNotEqual(rc, 0)
self.assertIn("256k", err)
self.assertFalse(os.path.exists(os.path.join(d, "ledger.jsonl")))
self.assertFalse(os.path.exists(os.path.join(d, "pair-0001")))
def test_262144_is_accepted_and_one_below_is_not(self):
d = self.tmpdir()
self.assertEqual(RC.read_schedule(self.schedule_file(d, 262144))[0]["context_tokens"], 262144)
with self.assertRaises(RC.RunCoreError) as cm:
RC.read_schedule(self.schedule_file(d, 262143, "below.json"))
self.assertEqual(cm.exception.code, RC.EXIT_CONTEXT_FLOOR)
class TestStartSlot(Base):
def test_wrong_slot_exit_2_names_the_scheduled_slot(self):
d = self.tmpdir()
sched = self.schedule_file(d)
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0002.ours")
self.assertEqual(rc, 2)
self.assertIn("pair-0001.ours", err)
self.assertIn("block 1, position 1", err)
self.assertEqual(json.loads(out.strip().splitlines()[-1])["scheduled_slot"], "pair-0001.ours")
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.vanilla_default")
self.assertEqual(rc, 2)
self.assertIn("pair-0001.ours", err)
self.assertFalse(os.path.exists(os.path.join(d, "ledger.jsonl")), "a refused start writes nothing")
def test_slots_run_in_schedule_order_and_one_at_a_time(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
ctx = self.ctx()
order = [s["run_id"] for s in RC.schedule_slots(RC.read_schedule(sched)[0])]
self.assertEqual(order[:3], ["pair-0001.ours", "pair-0001.vanilla_default", "pair-0001.vanilla_noskip"])
self.assertEqual(order[3], "pair-0002.vanilla_default")
RC.start_slot(sched, order[0], ledger, ctx=ctx)
with self.assertRaises(RC.RunCoreError) as cm: # still STARTED
RC.start_slot(sched, order[1], ledger, ctx=ctx)
self.assertEqual(cm.exception.code, RC.EXIT_IN_FLIGHT)
RC.finish_run(ledger, order[0], "DONE", ctx=ctx)
with self.assertRaises(RC.RunCoreError) as cm: # not the next slot
RC.start_slot(sched, order[2], ledger, ctx=ctx)
self.assertEqual(cm.exception.code, RC.EXIT_WRONG_SLOT)
self.assertEqual(cm.exception.extra["scheduled_slot"], order[1])
self.assertEqual(RC.start_slot(sched, order[1], ledger, ctx=ctx)["run_id"], order[1])
def test_a_complete_schedule_has_no_next_slot(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
ctx = self.ctx()
for s in RC.schedule_slots(RC.read_schedule(sched)[0]):
RC.start_slot(sched, s["run_id"], ledger, ctx=ctx)
RC.finish_run(ledger, s["run_id"], "DONE", ctx=ctx)
with self.assertRaises(RC.RunCoreError) as cm:
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=ctx)
self.assertEqual(cm.exception.code, RC.EXIT_WRONG_SLOT)
self.assertIn("complete", str(cm.exception))
def test_an_existing_run_directory_is_never_overwritten(self):
d = self.tmpdir()
sched = self.schedule_file(d)
os.makedirs(os.path.join(d, "pair-0001", "ours"))
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.ours")
self.assertEqual(rc, RC.EXIT_RUN_DIR_EXISTS, err)
self.assertTrue(os.path.isdir(os.path.join(d, "pair-0001", "ours")))
class TestResume(Base):
def test_killed_run_is_interrupted_and_the_restart_resumes_at_the_next_slot(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
child_code = (
"import sys, time\nsys.path.insert(0, %r)\nimport run_core as rc\n"
"rc.start_slot(%r, 'pair-0001.ours', %r)\nprint('READY', flush=True)\ntime.sleep(120)\n" % (HERE, sched, ledger))
child = subprocess.Popen([sys.executable, "-c", child_code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
try:
self.assertEqual(child.stdout.readline().strip(), "READY", "child did not start")
lines = self.ledger_lines(ledger)
self.assertEqual(lines[-1]["state"], "STARTED")
self.assertEqual(lines[-1]["pid"], child.pid)
child.kill() # mid-run
child.wait(timeout=30)
finally:
if child.poll() is None:
child.kill()
child.stdout.close()
child.stderr.close()
# a restart while the dead run is unsettled is refused
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.vanilla_default", "--ledger", ledger)
self.assertEqual(rc, RC.EXIT_IN_FLIGHT, err)
rc, out, err = self.cli("resume", "--ledger", ledger, "--schedule", sched)
self.assertEqual(rc, 0, err)
res = json.loads(out)
self.assertEqual(res["interrupted"], ["pair-0001.ours"])
self.assertEqual(res["next_slot"], "pair-0001.vanilla_default")
lines = self.ledger_lines(ledger)
states = [(l["run_id"], l["state"]) for l in lines]
self.assertIn(("pair-0001.ours", "INTERRUPTED"), states)
self.assertEqual(lines[-1]["state"], "INVALID") # an interrupted pair is invalid (SC3)
self.assertEqual(lines[-1]["outcome"], "CRASH")
self.assertIsNone(lines[-1]["attributed_to"])
self.assertTrue(lines[-1]["interrupted"])
for line in lines: # every line parses and carries the keys of the acceptance one-liner
self.assertTrue(line["run_id"] and line["state"])
code = "import json;[json.loads(l)['run_id'] and json.loads(l)['state'] for l in open(%r)]" % ledger
self.assertEqual(subprocess.run([sys.executable, "-c", code]).returncode, 0)
# the interrupted run directory is kept (renamed), and the restart continues at the next slot
self.assertFalse(os.path.exists(os.path.join(d, "pair-0001", "ours")))
kept = [n for n in os.listdir(os.path.join(d, "pair-0001")) if n.startswith("ours.invalid-")]
self.assertEqual(len(kept), 1)
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.vanilla_default", "--ledger", ledger)
self.assertEqual(rc, 0, err)
self.assertEqual(json.loads(out)["run_id"], "pair-0001.vanilla_default")
# validity.py reads the ledger without complaint
last, _ = V.read_ledger(ledger)
self.assertEqual(last["pair-0001.ours"]["state"], "INVALID")
def test_resume_is_idempotent(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=self.ctx(pid=111))
first = RC.resume_ledger(ledger, sched, ctx=self.ctx(pid=222))
count = len(self.ledger_lines(ledger))
second = RC.resume_ledger(ledger, sched, ctx=self.ctx(pid=222))
self.assertEqual(first["interrupted"], ["pair-0001.ours"])
self.assertEqual(second["interrupted"], [])
self.assertEqual(len(self.ledger_lines(ledger)), count)
def test_a_live_owner_is_left_alone(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=self.ctx(pid=111))
res = RC.resume_ledger(ledger, sched, ctx=self.ctx(pid=222, alive=lambda p: p == 111))
self.assertEqual(res["in_flight"], ["pair-0001.ours"])
self.assertEqual(res["interrupted"], [])
self.assertEqual(self.ledger_lines(ledger)[-1]["state"], "STARTED")
def test_run_from_another_boot_is_interrupted_and_writes_the_stop_file_once(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
runs = os.path.join(d, "runs")
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=self.ctx(pid=111, boot=BOOT))
res = RC.resume_ledger(ledger, sched, run_root=runs, ctx=self.ctx(pid=222, boot=OTHER_BOOT, alive=lambda p: True))
self.assertTrue(res["reboot_detected"]) # the PID may even exist again: another boot is decisive
self.assertEqual(res["interrupted"], ["pair-0001.ours"])
stop = os.path.join(runs, "STOP")
self.assertEqual(res["stop_file"], stop)
with open(stop, "r", encoding="utf-8") as fh:
first = fh.read()
self.assertEqual(json.loads(first)["kind"], "STOP")
self.assertFalse(RC.write_stop_file(stop, "again", "x", self.ctx()), "an existing STOP file is never changed")
with open(stop, "r", encoding="utf-8") as fh:
self.assertEqual(fh.read(), first)
def test_rerun_archives_the_failure_as_an_attempt_and_validity_counts_it_once(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
ctx = self.ctx()
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=ctx)
RC.finish_run(ledger, "pair-0001.ours", "INVALID", outcome="CRASH", attributed_to="LOCK", run_dir=os.path.join(d, "pair-0001", "ours"),
ctx=ctx)
info = RC.start_slot(sched, "pair-0001.ours", ledger, rerun=True, ctx=ctx)
self.assertEqual(info["attempt"], 2)
RC.finish_run(ledger, "pair-0001.ours", "DONE", ctx=ctx)
last, lines = V.read_ledger(ledger)
self.assertEqual(last["pair-0001.ours"]["state"], "DONE")
self.assertEqual(last["pair-0001.ours.a1"]["state"], "INVALID")
self.assertEqual(last["pair-0001.ours.a1"]["attributed_to"], "LOCK")
with self.assertRaises(RC.RunCoreError): # only the earliest INVALID slot can be re-run
RC.start_slot(sched, "pair-0001.ours", ledger, rerun=True, ctx=ctx)
class TestHeartbeat(Base):
def test_rewritten_at_least_every_60_s_with_a_fake_clock(self):
d = self.tmpdir()
path = os.path.join(d, "heartbeat.json")
now = [1000.0]
hb = RC.Heartbeat(path, "pair-0001.ours", clock=lambda: now[0])
writes = []
for _ in range(0, 301):
if hb.poll():
writes.append(now[0])
with open(path, "r", encoding="utf-8") as fh:
self.assertEqual(json.load(fh)["seq"], len(writes))
now[0] += 1.0
gaps = [b - a for a, b in zip(writes, writes[1:])]
self.assertTrue(gaps)
self.assertLessEqual(max(gaps), 60.0)
self.assertGreaterEqual(len(writes), 5)
# a clock that jumps (a long stall) still triggers a write at the very next poll
now[0] += 500.0
self.assertTrue(hb.poll())
def test_content_and_thread_mode(self):
d = self.tmpdir()
path = os.path.join(d, "heartbeat.json")
hb = RC.Heartbeat(path, "pair-0001.ours", interval=0.3, poll_s=0.05).start()
try:
time.sleep(1.0)
finally:
hb.stop()
with open(path, "r", encoding="utf-8") as fh:
doc = json.load(fh)
self.assertEqual(doc["run_id"], "pair-0001.ours")
self.assertEqual(doc["pid"], os.getpid())
self.assertGreaterEqual(doc["seq"], 3)
class TestInvalidKept(Base):
def test_invalid_run_directory_is_renamed_and_kept(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
info = json.loads(self.cli("start", "--schedule", sched, "--slot", "pair-0001.ours")[1])
marker = os.path.join(info["run_dir"], "samples.tsv")
with open(marker, "w", encoding="utf-8") as fh:
fh.write("raw power series\n")
rc, out, err = self.cli("finish", "--ledger", ledger, "--run-id", "pair-0001.ours", "--state", "INVALID", "--outcome", "TIMEOUT",
"--run-dir", info["run_dir"])
self.assertEqual(rc, 0, err)
kept = json.loads(out)["kept_run_dir"]
self.assertFalse(os.path.exists(info["run_dir"]))
self.assertTrue(os.path.isdir(kept))
self.assertIn(".invalid-", os.path.basename(kept))
with open(os.path.join(kept, "samples.tsv"), "r", encoding="utf-8") as fh:
self.assertEqual(fh.read(), "raw power series\n") # content untouched
last = self.ledger_lines(ledger)[-1]
self.assertEqual((last["state"], last["outcome"], last["attributed_to"]), ("INVALID", "TIMEOUT", None))
def test_two_invalid_renames_never_collide(self):
d = self.tmpdir()
first, second = os.path.join(d, "ours"), os.path.join(d, "ours")
os.makedirs(first)
a = RC.keep_invalid_dir(first, stamp="20261028T1000")
os.makedirs(second)
b = RC.keep_invalid_dir(second, stamp="20261028T1000")
self.assertNotEqual(a, b)
self.assertTrue(os.path.isdir(a) and os.path.isdir(b))
self.assertIsNone(RC.keep_invalid_dir(os.path.join(d, "absent")))
def test_done_without_a_record_and_unknown_outcome_are_refused(self):
d = self.tmpdir()
sched = self.schedule_file(d)
ledger = os.path.join(d, "ledger.jsonl")
RC.start_slot(sched, "pair-0001.ours", ledger, ctx=self.ctx())
os.makedirs(os.path.join(d, "records"))
with self.assertRaises(RC.RunCoreError):
RC.finish_run(ledger, "pair-0001.ours", "DONE", records_dir=os.path.join(d, "records"))
with self.assertRaises(RC.RunCoreError):
RC.finish_run(ledger, "pair-0001.ours", "INVALID", outcome="WHATEVER")
with self.assertRaises(RC.RunCoreError):
RC.finish_run(ledger, "pair-0001.ours", "INVALID", outcome="CRASH", attributed_to="MOON")
class TestLock(Base):
def _lock_args(self, root, run_id="R1", leaf="S0.3a", *extra):
return ("lock", "--run-root", root, "--run-id", run_id, "--leaf", leaf) + extra
def test_second_lock_exits_4_at_once_and_names_the_holder(self):
d = self.tmpdir()
root = os.path.join(d, "runs")
rc, out, err = self.cli(*self._lock_args(root))
self.assertEqual(rc, 0, err)
t0 = time.time()
rc, out, err = self.cli(*self._lock_args(root, "R2", "other"))
self.assertEqual(rc, RC.EXIT_LOCK_HELD)
self.assertLess(time.time() - t0, 20, "must not wait")
self.assertIn("R1", err)
self.assertIn("never waits", err)
def test_dead_pid_lock_is_not_stolen_and_not_removed(self):
for mode in ("file", "mkdir"):
d = self.tmpdir()
root = os.path.join(d, "runs")
_, _, path, owner = RC.lock_location(root, mode=mode)
os.makedirs(os.path.dirname(owner), exist_ok=True)
dead = subprocess.Popen([sys.executable, "-c", "pass"])
dead.wait(timeout=30)
holder = {"leaf": "STRA-254", "run_id": "OLD", "pid": dead.pid, "utc": "2026-10-28T00:00:00Z", "boot_time": BOOT, "created_by": "x"}
with open(owner, "w", encoding="utf-8") as fh:
json.dump(holder, fh)
before = os.stat(owner)
rc, out, err = self.cli(*self._lock_args(root, "NEW", "leaf", "--mode", mode))
self.assertEqual(rc, 4, mode + err)
self.assertIn("gone", err)
self.assertIn("inspection", err)
self.assertTrue(os.path.exists(owner), mode)
with open(owner, "r", encoding="utf-8") as fh:
self.assertEqual(json.load(fh), holder)
self.assertEqual(os.stat(owner).st_size, before.st_size)
rc, out, err = self.cli("unlock", "--run-root", root, "--run-id", "NEW", "--mode", mode)
self.assertEqual(rc, 4, "another run's lock is never released")
self.assertTrue(os.path.exists(owner))
def test_unreadable_lock_is_refused_not_stolen(self):
d = self.tmpdir()
root = os.path.join(d, "runs")
_, _, path, owner = RC.lock_location(root, mode="file")
os.makedirs(os.path.dirname(owner))
with open(owner, "w") as fh:
fh.write("not json")
rc, out, err = self.cli(*self._lock_args(root, "R", "l", "--mode", "file"))
self.assertEqual(rc, 4)
self.assertIn("needs inspection", err)
self.assertTrue(os.path.exists(owner))
def test_ac8_lock_file_records_run_id_leaf_pid_utc_and_boot_time(self):
for mode in ("file", "mkdir"):
d = self.tmpdir()
root = os.path.join(d, "runs")
rc, out, err = self.cli(*self._lock_args(root, "R1", "S0.3a", "--mode", mode))
self.assertEqual(rc, 0, err)
lock_file = json.loads(out)["lock"]
if mode == "file":
self.assertEqual(os.path.normcase(lock_file), os.path.normcase(os.path.join(d, "locks", "LAPTOP_GPU.lock")))
else:
self.assertEqual(os.path.normcase(lock_file), os.path.normcase(os.path.join(root, "run.lock", "owner")))
check = "import sys,pathlib;t=pathlib.Path(sys.argv[1]).read_text();print('R1' in t and 'S0.3a' in t)"
proc = subprocess.run([sys.executable, "-c", check, lock_file], stdout=subprocess.PIPE, universal_newlines=True)
self.assertEqual(proc.stdout.strip(), "True")
with open(lock_file, "r", encoding="utf-8") as fh:
doc = json.load(fh)
self.assertEqual((doc["run_id"], doc["leaf"]), ("R1", "S0.3a"))
self.assertIsInstance(doc["pid"], int)
self.assertRegex(doc["utc"], r"^\d{4}-\d\d-\d\dT")
self.assertRegex(doc["boot_time"], r"^\d{4}-\d\d-\d\dT")
self.assertEqual(doc["created_by"], "run_core.py")
rc, out, err = self.cli("unlock", "--run-root", root, "--run-id", "R1", "--mode", mode)
self.assertEqual(rc, 0, err)
self.assertFalse(os.path.exists(lock_file))
rc, out, err = self.cli(*self._lock_args(root, "R3", "x", "--mode", mode))
self.assertEqual(rc, 0, "released lock can be taken again: " + err)
def test_lock_can_be_read_by_another_process_right_after_creation(self):
# watchdog.ps1 / guard.ps1 open the lock with a shared read to verify the run id: the creating handle must be closed
d = self.tmpdir()
root = os.path.join(d, "runs")
info = RC.acquire_lock(root, "R9", "leaf", ctx=self.ctx())
with open(info["lock"], "r", encoding="utf-8") as fh:
self.assertEqual(json.load(fh)["run_id"], "R9")
def test_only_one_of_many_concurrent_lockers_wins(self):
d = self.tmpdir()
root = os.path.join(d, "runs")
procs = [subprocess.Popen([sys.executable, RUN_CORE] + list(self._lock_args(root, "R%d" % i, "l")), stdout=subprocess.PIPE,
stderr=subprocess.PIPE) for i in range(6)]
codes = []
for p in procs:
p.communicate(timeout=120)
codes.append(p.returncode)
self.assertEqual(sorted(codes), [0, 4, 4, 4, 4, 4])
class TestGuard(Base):
def test_unignored_run_root_exit_5(self):
repo = self.git_repo()
rc, out, err = self.cli("guard", "--run-root", os.path.join(repo, "artifacts", "runs"))
self.assertEqual(rc, RC.EXIT_NOT_IGNORED)
self.assertIn("run root not ignored", err)
def test_free_space_19_gb_exit_6_and_20_gb_ok(self):
repo = self.git_repo("artifacts/")
root = os.path.join(repo, "artifacts", "runs")
rc, out, err = self.cli("guard", "--run-root", root, "--free-gb", "19")
self.assertEqual(rc, RC.EXIT_LOW_DISK, err)
self.assertIn("less than 20 GB free", err)
rc, out, err = self.cli("guard", "--run-root", root, "--free-gb", "20")
self.assertEqual(rc, 0, err)
self.assertIn("artifacts", json.loads(out)["ignored_by"])
rc, out, err = self.cli("guard", "--run-root", root) # measured: this volume has far more than 20 GB or the test is moot
self.assertIn(rc, (0, RC.EXIT_LOW_DISK))
def test_injected_free_space_provider(self):
repo = self.git_repo("artifacts/")
root = os.path.join(repo, "artifacts", "runs")
with self.assertRaises(RC.RunCoreError) as cm:
RC.guard_run_root(root, free_fn=lambda p: 19.0)
self.assertEqual(cm.exception.code, RC.EXIT_LOW_DISK)
self.assertEqual(RC.guard_run_root(root, free_fn=lambda p: 223.0)["free_gb"], 223.0)
def test_stop_file_blocks_guard_and_start(self):
repo = self.git_repo("artifacts/")
root = os.path.join(repo, "artifacts", "runs")
os.makedirs(root)
with open(os.path.join(root, "STOP"), "w") as fh:
fh.write("{}")
rc, out, err = self.cli("guard", "--run-root", root, "--free-gb", "50")
self.assertEqual(rc, RC.EXIT_STOP_FILE, err)
d = self.tmpdir()
sched = self.schedule_file(d)
rc, out, err = self.cli("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--free-gb", "50")
self.assertEqual(rc, RC.EXIT_STOP_FILE, err)
self.assertFalse(os.path.exists(os.path.join(root, "ledger.jsonl")))
def test_run_root_inside_a_linked_worktree_is_refused(self):
repo = self.git_repo("artifacts/")
env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid", GIT_COMMITTER_NAME="t",
GIT_COMMITTER_EMAIL="t@example.invalid")
with open(os.path.join(repo, "f.txt"), "w") as fh:
fh.write("x")
subprocess.run(["git", "-C", repo, "add", "-A"], check=True, env=env, stdout=subprocess.PIPE)
subprocess.run(["git", "-C", repo, "commit", "-q", "-m", "c"], check=True, env=env, stdout=subprocess.PIPE)
wt = os.path.join(self.tmpdir(), "wt")
subprocess.run(["git", "-C", repo, "worktree", "add", "-q", "-b", "side", wt], check=True, env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
rc, out, err = self.cli("guard", "--run-root", os.path.join(wt, "artifacts", "runs"), "--free-gb", "50")
self.assertEqual(rc, RC.EXIT_NOT_IGNORED, err)
self.assertIn("linked worktree", err)
rc, out, err = self.cli("guard", "--run-root", os.path.join(repo, "artifacts", "runs"), "--free-gb", "50")
self.assertEqual(rc, 0, err) # the main checkout is fine
class TestFinalize(Base):
"""The seam of the L1 merge: capture.py writes countable=false / invalid_reasons=[]; the runner sets them from validity.py."""
def _fixture(self, pairs, expected, machine="laptop"):
d = self.tmpdir()
case_input = {"machine": machine, "schedule": "pairs_n6", "pairs": pairs}
mat = G.materialize(case_input, DOC["templates"], DOC["schedules"], expected)
records = os.path.join(d, "records")
os.makedirs(records)
for name, rec in mat["records"].items():
rec["countable"] = False # what capture.py writes
rec["invalid_reasons"] = []
with open(os.path.join(records, name), "w", encoding="utf-8", newline="\n") as fh:
json.dump(rec, fh, indent=2)
sched = os.path.join(d, "schedule.json")
with open(sched, "w", encoding="utf-8", newline="\n") as fh:
json.dump(mat["schedule"], fh)
ledger = os.path.join(d, "ledger.jsonl")
with open(ledger, "w", encoding="utf-8", newline="\n") as fh:
fh.write("".join(json.dumps(line) + "\n" for line in mat["ledger"]))
return records, sched, ledger
def _validity(self, records, sched, ledger, machine="laptop"):
proc = subprocess.run([sys.executable, VALIDITY, "pairs", "--records", records, "--schedule", sched, "--ledger", ledger,
"--machine", machine], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
self.assertEqual(proc.returncode, 0, proc.stderr)
return dict((p["pair"], p) for p in json.loads(proc.stdout)["pairs"])
def test_placeholders_give_countable_mismatch_until_finalize_sets_them(self):
bad = G.power_set(51.0, 51.0, 51.0, 150.0)
records, sched, ledger = self._fixture(
[{"pair": 1, "arms": {}}, {"pair": 2, "arms": {"ours": {"set": bad}}}],
{1: {"pair": 1, "valid": True, "reasons": [], "event": None}, 2: {"pair": 2, "valid": False, "reasons": ["POWER"], "event": None}})
before = self._validity(records, sched, ledger)
self.assertIn("COUNTABLE_MISMATCH", before[1]["reasons"])
rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "laptop")
self.assertEqual(rc, 0, err)
res = json.loads(out)
self.assertEqual(res["countable_mismatch_after"], [])
self.assertEqual(res["valid_pairs"], 1)
after = self._validity(records, sched, ledger)
self.assertTrue(after[1]["valid"])
self.assertEqual(after[1]["reasons"], [])
self.assertFalse(after[2]["valid"])
self.assertEqual(after[2]["reasons"], ["POWER"])
with open(os.path.join(records, "pair-0001.ours.json"), "r", encoding="utf-8") as fh:
ok = json.load(fh)
with open(os.path.join(records, "pair-0002.ours.json"), "r", encoding="utf-8") as fh:
invalid = json.load(fh)
self.assertIs(ok["countable"], True)
self.assertEqual(ok["invalid_reasons"], [])
self.assertIs(invalid["countable"], False)
self.assertEqual(invalid["invalid_reasons"], ["POWER"])
again = json.loads(self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "laptop")[1])
self.assertEqual(again["updated"], [], "idempotent")
def test_ledger_manifest_refusal_is_exit_12(self):
records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}})
os.remove(os.path.join(records, "pair-0001.ours.json"))
rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "laptop")
self.assertEqual(rc, RC.EXIT_LEDGER_REFUSAL)
self.assertIn("pair-0001.ours", out + err)
class TestMachineFacts(Base):
def test_pid_alive_and_dead(self):
self.assertTrue(RC.pid_alive(os.getpid()))
dead = subprocess.Popen([sys.executable, "-c", "pass"])
dead.wait(timeout=30)
self.assertFalse(RC.pid_alive(dead.pid))
self.assertFalse(RC.pid_alive(None))
self.assertFalse(RC.pid_alive(0))
def test_boot_time_is_an_instant_and_same_boot_has_a_tolerance(self):
value = RC.boot_time_iso()
self.assertIsNotNone(RC._parse_instant(value), value)
self.assertTrue(RC.same_boot(value, value))
self.assertTrue(RC.same_boot("2026-10-01T00:00:00.0000000Z", "2026-10-01T00:00:30.5000000Z"))
self.assertFalse(RC.same_boot("2026-10-01T00:00:00.0000000Z", "2026-10-01T00:05:00.0000000Z"))
self.assertTrue(RC.same_boot("unknown", "unknown"))
def test_ledger_append_is_one_fsynced_json_line_per_state_change(self):
d = self.tmpdir()
path = os.path.join(d, "ledger.jsonl")
calls = []
real = os.fsync
os.fsync = lambda fd: (calls.append(fd), real(fd))[1]
try:
for state in ("QUEUED", "STARTED", "DONE"):
RC.append_ledger(path, {"run_id": "r", "state": state})
finally:
os.fsync = real
self.assertEqual(len(calls), 3)
with open(path, "rb") as fh:
raw = fh.read()
self.assertEqual(raw.count(b"\n"), 3)
self.assertNotIn(b"\r", raw)
class TestNoForbiddenCalls(unittest.TestCase):
def test_no_power_policy_or_delete_call_in_run_core(self):
with open(RUN_CORE, "r", encoding="utf-8") as fh:
text = fh.read()
pattern = re.compile(r"powercfg|Set-ExecutionPolicy|setacvalueindex|rm -rf|shutil\.rmtree")
self.assertEqual([m.group(0) for m in pattern.finditer(text)], [])
for word in ("rmtree", "os.removedirs", "winreg", "SetThreadExecutionState", "rundll32", "shutdown"):
self.assertNotIn(word, text)
if __name__ == "__main__":
unittest.main()