Merge claude/fix-batch-326-329 into speed-train

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-29 08:26:40 +01:00
co-authored by Claude Sonnet 5.5
23 changed files with 1692 additions and 37 deletions
+2 -1
View File
@@ -22,7 +22,8 @@ How the pieces are obtained
by SUBPROCESS and its `--csv` output is parsed (STRA-251 round-5 re-cut). The two logs are staged under their fixed names
(strata-next.log, inference.log) in a private temporary directory, with CRLF folded to LF (raw bytes are never stored; comparisons are on
the normalised text), because the script reads a RUN directory.
--meta (written by the runner, STRA-257): arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine and
--meta (written by the runner, STRA-257): arm, series_id, block, pair_id, position, predecessor, schedule_hash, h0_id, machine (a real series writes laptop|server: validity.py requires
hardware.machine_role == the declared machine, STRA-326) and
ours_build_id (an object commit / target_triple / cargo_features / profile_value_sha256 = the FROZEN build id, STRA-304/322). Optional:
owner_attestation {present, identifier, time_utc}, foreign_load {samples}, synthetic, long_session_argv, source_snapshot_sha256.
--replay-output: the run JSON of replay_session.py (STRA-308); status must be "ok".
@@ -262,6 +262,7 @@ def build_record(templates, machine, n, arm, order, sched_hash, spec, valid, rea
ident["pair_id"] = pair_id(n)
rec["synthetic"] = True
rec["thresholds_source"] = "S3.7"
rec["hardware"]["machine_role"] = machine # STRA-326: validity.py cross-checks the declared machine against the record
rec["hardware"]["owner_attestation"] = {"present": True, "identifier": "golden-attestation-1", "time_utc": "2026-01-01T00:00:00Z"}
base = machine_defaults(machine)
if base is not None:
+170
View File
@@ -0,0 +1,170 @@
#!/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())
+93 -12
View File
@@ -10,20 +10,26 @@ Stdlib only, Python >= 3.9 (SC15). Offline, no GPU, no network. It never changes
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 [--ledger FILE] [--run-root DIR] [--free-gb N] [--rerun]
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]
run_core.py finalize --records DIR --schedule FILE --ledger FILE --machine laptop|server
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},
@@ -39,8 +45,8 @@ Files
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 when the run root is named `runs` (artifacts\\runs -> artifacts\\locks), else
<run-root>/locks/LAPTOP_GPU.lock; created with CreateFileW CREATE_NEW and share mode 0 (FileShare.None), written, fsynced and
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
@@ -75,6 +81,7 @@ 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`
@@ -514,7 +521,7 @@ def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None):
sched, sha = read_schedule(schedule_path)
check_same_schedule(lines, sha)
slots = schedule_slots(sched)
interrupted, in_flight, reboot, stop = [], [], False, None
interrupted, in_flight, stale_heartbeat, reboot, stop = [], [], [], False, None
current_boot = ctx.boot()
for run_id in sorted(last):
cur = last[run_id]
@@ -526,6 +533,9 @@ def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None):
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),
@@ -544,7 +554,7 @@ def resume_ledger(ledger_path, schedule_path=None, run_root=None, ctx=None):
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, "reboot_detected": reboot, "stop_file": stop,
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)}
@@ -603,8 +613,13 @@ def lock_location(run_root, lock_dir=None, mode=None):
raise RunCoreError(EXIT_MALFORMED, "lock mode must be file or mkdir")
root = os.path.abspath(run_root)
if mode == "file":
directory = os.path.abspath(lock_dir) if lock_dir else (
os.path.join(os.path.dirname(root), "locks") if os.path.basename(root).lower() == "runs" else os.path.join(root, "locks"))
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)
@@ -690,6 +705,8 @@ def acquire_lock(run_root, run_id, leaf, lock_dir=None, mode=None, ctx=None):
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)
@@ -699,6 +716,61 @@ def release_lock(run_root, run_id, lock_dir=None, mode=None):
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)
# --------------------------------------------------------------------------------------------------------------------------------
@@ -812,7 +884,9 @@ def main(argv=None, ctx=None):
p.add_argument("--schedule", required=True)
p.add_argument("--slot", required=True)
p.add_argument("--ledger")
p.add_argument("--run-root", help="when given the run-root guard runs first")
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")
@@ -835,6 +909,9 @@ def main(argv=None, ctx=None):
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)")
@@ -842,12 +919,11 @@ def main(argv=None, ctx=None):
p.add_argument("--records", required=True)
p.add_argument("--schedule", required=True)
p.add_argument("--ledger", required=True)
p.add_argument("--machine", required=True, choices=["laptop", "server"])
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":
if args.run_root:
guard_run_root(args.run_root, args.free_gb)
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))
@@ -859,6 +935,11 @@ def main(argv=None, ctx=None):
_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
+5 -2
View File
@@ -23,8 +23,11 @@ DEFINITIONS (the golden vectors of STRA-310 fix what the BA text leaves open; se
l_i ln(V_i / O_i) for wall_norm and ttft_sum (lower is better), ln(O_i / V_i) for decode_tps (higher is better); positive = ours better.
Only valid pairs, ordered by pair number; the first N valid pairs form the series (later pairs are outside the schedule, E6).
r1 lag-1 autocorrelation sum_{i<n}(l_i - m)(l_{i+1} - m) / sum_i (l_i - m)^2 (0 when the spread is 0).
n_eff n (1 - r1) / (1 + r1) when r1 > 0, else n. dof = max(1, floor(n_eff - 1)) when r1 > 0, else n - 1.
CI mean +- t(1 - alpha/2, dof) * sd / sqrt(n_eff); alpha = 0.05 for the verdicts, 0.0221 for the interim SLOWER test.
n_eff n (1 - r1) / (1 + r1) when r1 > 0, else n. dof = max(1, floor(n_eff - 1)) when r1 > 0, else n - 1: the floor of n_eff - 1 is
taken first and the result is never below 1 (n_eff < 2 gives dof 1, not 0).
se the standard error of the mean is sd / sqrt(n_eff) (sd / sqrt(n) when r1 <= 0, where n_eff = n), NOT sd / sqrt(n): the lag-1
correction acts on the standard error and on the degrees of freedom together (E3; STRA-329 wording fix).
CI mean +- t(1 - alpha/2, dof) * se; alpha = 0.05 for the verdicts, 0.0221 for the interim SLOWER test.
mde 2.8 * sd / sqrt(n) (log-ratio units, charter 4.3 / E1).
EPS 1e-12: a bound within EPS of a threshold counts as ON it (so an sd = 0 CI exactly on 0 or on ln 0.99 is well defined).
strict (wall_norm) PASS lo > 0; SLOWER hi < 0; TIE CI contains 0 and lies in [ln 0.99, ln 1.01]; else INCONCLUSIVE.
+174
View File
@@ -0,0 +1,174 @@
"""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()
+197
View File
@@ -69,7 +69,18 @@ class Base(unittest.TestCase):
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 start_root(self):
"""A git-ignored run root named `runs` in a throw-away repository (`start` needs --run-root since STRA-327)."""
if getattr(self, "_start_repo", None) is None:
self._start_repo = self.git_repo("artifacts/")
return os.path.join(self._start_repo, "artifacts", "runs")
def cli(self, *args):
args = list(args)
if args and args[0] == "start" and "--run-root" not in args: # the pre-STRA-327 tests of the slot logic: supply a valid root
if "--ledger" not in args: # they expect the ledger next to the schedule file
args += ["--ledger", os.path.join(os.path.dirname(os.path.abspath(args[args.index("--schedule") + 1])), "ledger.jsonl")]
args += ["--run-root", self.start_root(), "--free-gb", "50"]
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
@@ -629,6 +640,192 @@ class TestFinalize(Base):
self.assertIn("pair-0001.ours", out + err)
def _with_schedule_machine(self, sched, machine):
with open(sched, "r", encoding="utf-8") as fh:
doc = json.load(fh)
doc["machine"] = machine
with open(sched, "w", encoding="utf-8", newline="\n") as fh:
json.dump(doc, fh)
def test_finalize_takes_the_machine_from_the_schedule(self): # STRA-326 AC4
records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}})
self._with_schedule_machine(sched, "laptop")
rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger)
self.assertEqual(rc, 0, err)
self.assertEqual(json.loads(out)["valid_pairs"], 1)
def test_finalize_refuses_a_flag_that_conflicts_with_the_schedule(self): # STRA-326 AC4
records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}})
self._with_schedule_machine(sched, "laptop")
rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "server")
self.assertEqual(rc, RC.EXIT_MALFORMED)
self.assertIn("MACHINE_MISMATCH", out + err)
def test_finalize_refuses_laptop_records_declared_server(self): # STRA-326 AC1 through the runner
records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}})
rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger, "--machine", "server")
self.assertEqual(rc, RC.EXIT_MALFORMED)
self.assertIn("MACHINE_MISMATCH", out + err)
def test_finalize_without_any_machine_is_refused(self):
records, sched, ledger = self._fixture([{"pair": 1, "arms": {}}], {1: {"pair": 1, "valid": True, "reasons": [], "event": None}})
rc, out, err = self.cli("finalize", "--records", records, "--schedule", sched, "--ledger", ledger)
self.assertEqual(rc, RC.EXIT_MALFORMED)
class TestStartWiring(Base):
"""STRA-327: the preconditions the PowerShell side enforces are enforced by the runner before a slot starts (no GPU, no PowerShell)."""
def raw(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
def runs_root(self):
d = self.tmpdir()
root = os.path.join(d, "artifacts", "runs")
os.makedirs(root)
return d, root
def put_lock(self, root, holder, mode="file"):
_, _, path, owner = RC.lock_location(root, mode=mode)
os.makedirs(os.path.dirname(owner), exist_ok=True)
with open(owner, "w", encoding="utf-8") as fh:
fh.write(holder if isinstance(holder, str) else json.dumps(holder))
return owner
def dead_pid(self):
dead = subprocess.Popen([sys.executable, "-c", "pass"])
dead.wait(timeout=30)
return dead.pid
def test_ac1_start_without_run_root_fails(self):
d = self.tmpdir()
sched = self.schedule_file(d)
rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours")
self.assertEqual(rc, RC.EXIT_MALFORMED)
self.assertIn("--run-root", err)
self.assertFalse(os.path.exists(os.path.join(d, "ledger.jsonl")))
def test_ac1_stop_file_refuses_start_with_exit_10_and_writes_nothing(self):
d, root = self.runs_root() # not even a git repository: the STOP check comes first and needs none
with open(os.path.join(root, "STOP"), "w") as fh:
fh.write("{}")
sched = self.schedule_file(d)
rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--free-gb", "50")
self.assertEqual(rc, RC.EXIT_STOP_FILE, err)
self.assertIn("STOP file present", err)
self.assertFalse(os.path.exists(os.path.join(root, "ledger.jsonl")))
def test_ac2_foreign_lock_refuses_start_with_a_named_reason(self):
d, root = self.runs_root()
owner = self.put_lock(root, {"leaf": "other", "run_id": "pair-0009.ours", "pid": os.getpid(), "utc": "2026-10-28T00:00:00Z",
"boot_time": BOOT, "created_by": "x"})
sched = self.schedule_file(d)
rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--mode", "file")
self.assertEqual(rc, RC.EXIT_LOCK_HELD, err)
self.assertIn("LOCK_FOREIGN", err)
self.assertIn("pair-0009.ours", err)
self.assertTrue(os.path.exists(owner), "never removed")
self.assertFalse(os.path.exists(os.path.join(root, "ledger.jsonl")))
def test_ac2_stale_and_unreadable_locks_refuse_start(self):
d, root = self.runs_root()
sched = self.schedule_file(d)
owner = self.put_lock(root, {"leaf": "l", "run_id": "pair-0001.ours", "pid": self.dead_pid(), "utc": "2026-10-28T00:00:00Z",
"boot_time": RC.boot_time_iso(), "created_by": "x"})
rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--mode", "file")
self.assertEqual((rc, "LOCK_STALE" in err), (RC.EXIT_LOCK_HELD, True), err)
with open(owner, "w") as fh:
fh.write("not json")
rc, out, err = self.raw("start", "--schedule", sched, "--slot", "pair-0001.ours", "--run-root", root, "--mode", "file")
self.assertEqual((rc, "LOCK_UNREADABLE" in err), (RC.EXIT_LOCK_HELD, True), err)
self.assertTrue(os.path.exists(owner))
def test_the_own_live_lock_of_the_slot_passes_the_check(self):
d, root = self.runs_root()
self.put_lock(root, {"leaf": "l", "run_id": "pair-0001.ours", "pid": 4242, "utc": "2026-10-28T00:00:00Z", "boot_time": BOOT,
"created_by": "x"})
ctx = self.ctx(boot=BOOT, alive=lambda p: p == 4242)
self.assertEqual(RC.check_lock(root, "pair-0001.ours", mode="file", ctx=ctx)["holder"]["pid"], 4242)
with self.assertRaises(RC.RunCoreError) as cm:
RC.check_lock(root, "pair-0001.ours", mode="file", ctx=self.ctx(boot=OTHER_BOOT, alive=lambda p: True))
self.assertEqual(cm.exception.extra["reason"], "LOCK_STALE")
with self.assertRaises(RC.RunCoreError) as cm:
RC.check_lock(root, "pair-0002.ours", mode="file", ctx=ctx)
self.assertEqual(cm.exception.extra["reason"], "LOCK_FOREIGN")
def test_no_lock_and_clean_root_start_succeeds(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)
def test_run_root_must_be_named_runs_for_the_windows_lock(self):
d = self.tmpdir()
with self.assertRaises(RC.RunCoreError) as cm:
RC.lock_location(os.path.join(d, "series1"), mode="file")
self.assertEqual(cm.exception.code, RC.EXIT_MALFORMED)
self.assertIn("runs", str(cm.exception))
rc, out, err = self.raw("lock", "--run-root", os.path.join(d, "series1"), "--run-id", "R", "--leaf", "l", "--mode", "file")
self.assertEqual(rc, RC.EXIT_MALFORMED, err)
self.assertFalse(os.path.exists(os.path.join(d, "series1", "locks")), "no lock where the watchdog cannot see it")
explicit = os.path.join(d, "mylocks") # an explicit lock directory is still allowed
self.assertEqual(RC.lock_location(os.path.join(d, "series1"), lock_dir=explicit, mode="file")[1], os.path.abspath(explicit))
self.assertEqual(RC.lock_location(os.path.join(d, "runs"), mode="file")[1], os.path.join(d, "locks"))
def test_ac5_unlock_after_the_guard_removed_the_lock_exits_0(self):
d, root = self.runs_root()
for mode in ("file", "mkdir"):
rc, out, err = self.raw("lock", "--run-root", root, "--run-id", "R1", "--leaf", "l", "--mode", mode)
self.assertEqual(rc, 0, err)
owner = json.loads(out)["lock"]
os.remove(owner) # what guard.ps1 does after the cool-down
if mode == "mkdir":
os.rmdir(os.path.dirname(owner))
rc, out, err = self.raw("unlock", "--run-root", root, "--run-id", "R1", "--mode", mode)
self.assertEqual(rc, 0, mode + err)
self.assertTrue(json.loads(out)["already_released"])
# the exemption is for a missing lock only: a lock of another run is still refused
self.raw("lock", "--run-root", root, "--run-id", "R2", "--leaf", "l", "--mode", "file")
rc, out, err = self.raw("unlock", "--run-root", root, "--run-id", "R1", "--mode", "file")
self.assertEqual(rc, RC.EXIT_LOCK_HELD)
def test_ac4_heartbeat_reader(self):
d = self.tmpdir()
self.assertEqual(RC.read_heartbeat(d)["state"], "missing")
hb = RC.Heartbeat(os.path.join(d, "heartbeat.json"), "pair-0001.ours", now=lambda: "2026-10-28T10:00:00.000000Z")
hb.beat()
self.assertEqual(RC.read_heartbeat(d, now="2026-10-28T10:01:30.000000Z")["state"], "fresh")
info = RC.read_heartbeat(d, now="2026-10-28T10:05:00.000000Z")
self.assertEqual((info["state"], info["age_s"]), ("stale", 300.0))
self.assertEqual(RC.read_heartbeat(d, max_age_s=400, now="2026-10-28T10:05:00.000000Z")["state"], "fresh")
with open(os.path.join(d, "heartbeat.json"), "w") as fh:
fh.write("{broken")
self.assertEqual(RC.read_heartbeat(d)["state"], "unreadable")
def test_ac4_heartbeat_cli_exit_codes(self):
d = self.tmpdir()
rc, out, err = self.raw("heartbeat", "--run-dir", d)
self.assertEqual(rc, RC.EXIT_HEARTBEAT, err)
RC.Heartbeat(os.path.join(d, "heartbeat.json"), "pair-0001.ours").beat() # real clock: written just now
rc, out, err = self.raw("heartbeat", "--run-dir", d)
self.assertEqual(rc, 0, err)
self.assertEqual(json.loads(out)["state"], "fresh")
def test_ac4_resume_reports_a_live_owner_with_a_stale_heartbeat(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=4242))
live = self.ctx(pid=4242, alive=lambda p: p == 4242)
res = RC.resume_ledger(ledger, sched, ctx=live)
self.assertEqual(res["in_flight"], ["pair-0001.ours"])
self.assertEqual(res["stale_heartbeat"], ["pair-0001.ours"], "no heartbeat.json at all")
RC.Heartbeat(os.path.join(d, "pair-0001", "ours", "heartbeat.json"), "pair-0001.ours").beat()
self.assertEqual(RC.resume_ledger(ledger, sched, ctx=live)["stale_heartbeat"], [])
class TestMachineFacts(Base):
def test_pid_alive_and_dead(self):
self.assertTrue(RC.pid_alive(os.getpid()))
+69
View File
@@ -302,5 +302,74 @@ class ImportedFunctions(unittest.TestCase):
self.assertEqual(DOC["thresholds"]["vanilla_rerun_cap"], V.VANILLA_RERUN_CAP)
LAPTOP_GPU = "NVIDIA GeForce RTX 5090 Laptop GPU"
class MachineCrossCheck(unittest.TestCase):
"""STRA-326: the declared machine must match what the records say; the flag alone never selects the rule set."""
BELOW_FLOOR = pw(51.0, 51.0, 51.0) # a laptop sample below the 100 W floor
def test_laptop_records_declared_server_fail_with_a_named_error(self): # AC1
fx = Fixture(self, "laptop", [{"pair": 1, "arms": {"ours": self.BELOW_FLOOR}}])
fx.machine = "server"
rc, out, err = fx.run()
self.assertEqual(rc, 3, err)
self.assertIn("MACHINE_MISMATCH", err)
self.assertIn("pair-0001.ours", err)
def test_laptop_gpu_name_under_a_server_declaration_fails(self): # AC1, the second half of the item
fx = Fixture(self, "server", [{"pair": 1, "arms": {"ours": {"set": {"hardware.gpu_name": LAPTOP_GPU}}}}])
rc, out, err = fx.run()
self.assertEqual(rc, 3, err)
self.assertIn("MACHINE_MISMATCH", err)
self.assertIn("Laptop GPU", err)
def test_server_records_declared_laptop_fail(self): # AC2
fx = Fixture(self, "server", [{"pair": 1, "arms": {}}])
fx.machine = "laptop"
rc, out, err = fx.run()
self.assertEqual(rc, 3, err)
self.assertIn("MACHINE_MISMATCH", err)
def test_missing_machine_role_is_refused(self):
fx = Fixture(self, "laptop", [{"pair": 1, "arms": {"ours": {"unset": ["hardware.machine_role"]}}}])
self.assertEqual(fx.run()[0], 3)
def test_matching_declarations_behave_as_before(self): # AC3 (the golden vectors are the bulk of it)
for machine in ("laptop", "server"):
fx = Fixture(self, machine, [{"pair": 1, "arms": {}}])
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
self.assertTrue(by_pair(out)[1]["valid"])
def test_in_process_error_is_a_malformed_subclass(self):
self.assertTrue(issubclass(V.MachineMismatch, V.Malformed))
def test_schedule_machine_is_used_and_a_conflicting_flag_is_refused(self): # AC4 (validity side)
sched = {"arms": ["ours"], "machine": "laptop"}
self.assertEqual(V.resolve_machine(sched, None), "laptop")
self.assertEqual(V.resolve_machine(sched, "laptop"), "laptop")
with self.assertRaises(V.MachineMismatch):
V.resolve_machine(sched, "server")
self.assertEqual(V.resolve_machine({"arms": []}, "server"), "server") # a schedule without the key falls back to the flag
with self.assertRaises(V.Malformed):
V.resolve_machine({"arms": []}, None)
with self.assertRaises(V.Malformed):
V.resolve_machine({"machine": "desktop"}, None)
def test_cli_machine_flag_is_optional_when_the_schedule_has_it(self):
fx = Fixture(self, "laptop", [{"pair": 1, "arms": {}}])
with open(fx.schedule, "r", encoding="utf-8") as fh:
sched = json.load(fh)
sched["machine"] = "laptop"
fx.write(fx.schedule, sched)
rc, out, err = run_cli("pairs", "--records", fx.records, "--schedule", fx.schedule, "--ledger", fx.ledger)
self.assertEqual(rc, 0, err)
rc, out, err = run_cli("pairs", "--records", fx.records, "--schedule", fx.schedule, "--ledger", fx.ledger, "--machine", "server")
self.assertEqual(rc, 3, err)
self.assertIn("MACHINE_MISMATCH", err)
if __name__ == "__main__":
unittest.main()
+51 -4
View File
@@ -8,7 +8,7 @@ dabfd08e) and the balanced-schedule rule of E1 (D5) are coded. The runner (STRA-
Stdlib only, Python >= 3.9 (SC15). Offline, no GPU, no network. Writes nothing unless --out is given.
INTERFACE v1
validity.py pairs --records <dir> --schedule <schedule.json> --ledger <ledger.jsonl> --machine laptop|server [--out FILE]
validity.py pairs --records <dir> --schedule <schedule.json> --ledger <ledger.jsonl> [--machine laptop|server] [--out FILE]
stdout: {"pairs": [{"pair": i, "valid": bool, "reasons": [...], "event": null|"FAIL"|"RERUN"|"OWNER"}], "manifest_ok": bool,
"invalid_rate": x}
validity.py schedule --check <schedule.json> [--out FILE]
@@ -19,6 +19,12 @@ INTERFACE v1
Machine: the `--machine` argument (the same one that selects the E2(1) laptop/server power rules) also selects the E2(2) rule: the owner
attestation is required on laptop pairs only (ATTESTATION_MISSING / OWNER); a server pair needs none and a present one is ignored.
The declaration is cross-checked (STRA-326): every record's hardware.machine_role must equal the declared machine, and a `server`
declaration is refused for a record whose hardware.gpu_name names a Laptop GPU. The runner writes machine_role = laptop|server into
--meta (capture.py). A mismatch is MALFORMED INPUT (exit 3, MACHINE_MISMATCH naming the run ids): the power floor and the attestation
rule are never skipped by typing the wrong flag. A schedule that carries a `machine` key pre-registers the machine (it is part of the
schedule hash); a conflicting --machine is refused (resolve_machine).
Reason codes: POWER, WORKLOAD, CACHE, INFRASTRUCTURE, ATTESTATION_MISSING, FOREIGN_LOAD, COUNTABLE_MISMATCH.
Events: RERUN (attributable infrastructure failure, build-id mismatch, vanilla failure not attributable up to the cap), OWNER (missing
attestation, third non-attributable vanilla failure of a slot), FAIL (ours failure not attributable; the series stops FAILED).
@@ -53,6 +59,7 @@ VANILLA_RERUN_CAP = 2 # E2(5): a vanilla failure not attributable
# SC14: the foreign-load threshold itself is read from the schedule file (TL proposal: 5 percent of a core for 2 s; BA to confirm).
INFRA_CAUSES = ("POWER", "WORKLOAD", "CACHE", "LOCK", "WATCHDOG", "TELEMETRY") # E2(5): causes a failed attempt can be attributed to
OUTCOMES = ("CRASH", "TIMEOUT", "INTEGRITY_FAILURE")
MACHINES = ("laptop", "server")
EVENT_RANK = {"RERUN": 1, "OWNER": 2, "FAIL": 3}
GROUP_SIZE = 6 # D5: three arms -> all 6 permutations per group of 6 pairs
METADATA_PATHS = ( # E2(3): the metadata of the common paragraph must be complete
@@ -67,6 +74,10 @@ class Malformed(Exception):
"""Input that cannot be interpreted (exit 3)."""
class MachineMismatch(Malformed):
"""The machine the series declares (--machine, schedule `machine`) disagrees with what a record says it was captured on (exit 3)."""
class Refusal(Exception):
"""Ledger/manifest refusal (exit 2); .names lists the offending run ids."""
@@ -350,15 +361,51 @@ def check_manifest(records, last):
raise Refusal("; ".join(parts), orphans + unlisted)
def resolve_machine(sched, flag):
"""The machine a series is judged as. A schedule `machine` key (pre-registered, hashed with the schedule) wins; a --machine flag that
disagrees with it is refused (MachineMismatch). A schedule without the key falls back to the flag (the golden schedules have none);
the per-record cross-check in check_machine() still applies. Returns "laptop" or "server"."""
declared = sched.get("machine") if isinstance(sched, dict) else None
if declared is not None and declared not in MACHINES:
raise Malformed("schedule machine %r is not one of %s" % (declared, ", ".join(MACHINES)))
if flag is not None and flag not in MACHINES:
raise Malformed("machine must be laptop or server")
if declared is not None and flag is not None and declared != flag:
raise MachineMismatch("MACHINE_MISMATCH: the schedule pre-registers machine %r but %r was given on the command line" % (declared, flag))
machine = declared if declared is not None else flag
if machine is None:
raise Malformed("no machine: the schedule has no `machine` key and no --machine was given")
return machine
def check_machine(records, machine):
"""STRA-326: the declared machine must match what the records say they were captured on. Raises MachineMismatch naming run ids."""
wrong, laptop_gpu = [], []
for rid in sorted(records):
role = get_path(records[rid], "hardware.machine_role")
if role != machine:
wrong.append("%s (hardware.machine_role=%r)" % (rid, role))
gpu = get_path(records[rid], "hardware.gpu_name")
if machine == "server" and isinstance(gpu, str) and "laptop" in gpu.lower():
laptop_gpu.append("%s (hardware.gpu_name=%r)" % (rid, gpu))
if wrong or laptop_gpu:
parts = []
if wrong:
parts.append("record(s) whose hardware.machine_role is not %r: %s" % (machine, ", ".join(wrong)))
if laptop_gpu:
parts.append("record(s) of a Laptop GPU under a `server` declaration: %s" % ", ".join(laptop_gpu))
raise MachineMismatch("MACHINE_MISMATCH: declared machine %r; %s" % (machine, "; ".join(parts)))
def derive_pairs(records, sched, last, machine):
"""The pairs command as a function. records: run_id -> record; last: run_id -> last ledger line. Returns the result dict;
raises Refusal (exit 2) or Malformed (exit 3)."""
if machine not in ("laptop", "server"):
raise Malformed("machine must be laptop or server")
if not isinstance(sched, dict) or not isinstance(sched.get("arms"), list):
raise Malformed("schedule has no arms list")
machine = resolve_machine(sched, machine)
arms = list(sched["arms"])
check_manifest(records, last)
check_machine(records, machine)
by_pair = {}
for rid, line in last.items():
by_pair.setdefault(_pair_number(line), []).append((rid, line))
@@ -406,7 +453,7 @@ def main(argv=None):
p.add_argument("--records", required=True)
p.add_argument("--schedule", required=True)
p.add_argument("--ledger", required=True)
p.add_argument("--machine", required=True, choices=["laptop", "server"])
p.add_argument("--machine", choices=list(MACHINES), help="required unless the schedule carries a `machine` key; must agree with it")
p.add_argument("--out", help="also write the JSON result here (run roots outside Git)")
s = sub.add_parser("schedule", help="schedule checks")
s.add_argument("--check", required=True, metavar="SCHEDULE_JSON")
+445
View File
@@ -0,0 +1,445 @@
#!/usr/bin/env python3
"""Paired equivalence check of the prefix-cache `reply` tail (STRA-328): reply-checkpoint restore vs a cold prefill of the same tokens.
OFFLINE TEST DRIVER, stdlib only, Python >= 3.9; never part of serving. It launches no engine and touches no GPU by itself: the operator runs two
`leleka-serve` instances on the 5090 (not at the same time as other GPU jobs) and this script talks to both over /v1/responses.
THE QUESTION. With `--prefix-cache-tail reply` the next turn of an agent session resumes from a checkpoint taken after the committed reply, so the
cells past the prompt were written by the DECODE kernels, not by prefill (docs/prefix-cache.md, "Request-end checkpoints"). A cold prefill of the
very same tokens writes them with the prefill kernels. The two states are not bit-identical by construction; the existing evidence (job 9d4,
flips 1.45 % vs a chunk-cut control 1.45 %) shows only that `reply` sits at the noise floor and could not score `reply` itself (a replay's greedy
replies diverge from the recorded ones). This script scores it live: the SAME input goes to both arms at every request of a multi-turn agent
session, the history being built from the reply-arm's own output (so the reply arm resumes from its own reply checkpoint, as in production).
ARMS (identical in everything except the cache; the operator starts them, this script only checks what it can see)
cold `--prefix-cache-mib 0` (no prefix cache, every request prefilled from token 0) [or a fresh process per request: see --cold-note]
reply `--prefix-cache-mib <N or auto> --prefix-cache-tail reply`
Same model digest, context, KV type, speculation settings, seed policy and `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0` (docs/prefix-cache.md: the
static tier, so the expert placement does not move between arms). Greedy: every request carries temperature 0.
PER REQUEST (one pair = the same body to both arms; request order inside a pair is reply first, then cold, so the reply arm's cache state is the
production one)
1. outputs: the output items (message text, function_call name and arguments string, reasoning text) must be IDENTICAL, string for string.
2. tool-call integrity, checked on EACH arm separately: every function_call has a declared name, a non-empty call_id, `arguments` that parses as a
JSON object and satisfies the tool's schema (types of the properties, required keys), the streamed argument deltas concatenate to the `done`
arguments and to the item's, and the stream ends with response.completed (a cut-off or failed stream is an integrity failure).
3. restore evidence: the reply arm reports `usage.input_tokens_details.cached_tokens`; a request after the first counts as RESTORED when
cached_tokens >= --min-cached-fraction of its input_tokens (default 0.5); the cold arm must report ~0. Without restores the run proves nothing.
4. control (--control): the cold request is sent TWICE; if the two cold outputs differ, greedy decoding is not run-to-run deterministic on this
setup and no difference between the arms can be attributed to the restore (INCONCLUSIVE_NONDETERMINISTIC).
VERDICT (pure function `judge()`, unit-tested in test_prefix_tail_equivalence.py)
PASS every pair identical, no integrity failure on either arm, restores observed on >= --min-restore-fraction of the
requests after the first, control (when used) deterministic.
FAIL_OUTPUT_DIFFERS some pair differs (the first differing request, item and character are recorded).
FAIL_TOOL_CALL_INTEGRITY a function_call (or a stream) of either arm is malformed; arm and request recorded. Reported before OUTPUT_DIFFERS.
INCONCLUSIVE_NO_RESTORE the reply arm restored on too few requests (check the server flags / cache budget); the outputs are not evidence.
INCONCLUSIVE_NONDETERMINISTIC the control found cold != cold.
INCONCLUSIVE_COLD_ARM_WARM the cold arm itself served cached tokens (it is not cold: start it with `--prefix-cache-mib 0`).
ERROR transport or protocol failure.
Exit code: 0 PASS, 1 FAIL_*, 2 INCONCLUSIVE_*, 3 usage, 4 ERROR.
The numeric complement (AC1: q_pair / class gate numbers) is separate and uses the logs of the same two arms: see
scripts/e2e/prefix_tail_equivalence_plan.md, section "Numeric gate".
TWO PHASES. A 5090 cannot hold two serve instances, so the normal run is sequential: `record` against the reply arm (phase 1), then restart the
server WITHOUT the prefix cache and `replay` the recorded requests unchanged against it (phase 2). `run` does both at once when two servers fit.
COMMANDS (server; nothing else on the GPU)
1. reply arm up (`--prefix-cache-mib <N|auto> --prefix-cache-tail reply`):
python3 scripts/e2e/prefix_tail_equivalence.py record --reply-url http://127.0.0.1:8081 --model <model id> --key-file <key file> \\
--context-file <text of ~60-70k tokens> --turns 12 --record-out <run root outside Git>/tail-record.json
2. stop it; start the cold arm with the same flags except `--prefix-cache-mib 0`:
python3 scripts/e2e/prefix_tail_equivalence.py replay --cold-url http://127.0.0.1:8081 --record <run root>/tail-record.json --control \\
--key-file <key file> --out <run root>/tail-equivalence.json
(both arms at once: `run --cold-url U1 --reply-url U2 --model M ... --control --out F`)
The result file holds prompts' hashes and the reply text: keep it outside Git. The API key is never written to any output.
"""
import argparse
import hashlib
import json
import os
import sys
import time
import urllib.error
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
EXIT = {"PASS": 0, "FAIL_OUTPUT_DIFFERS": 1, "FAIL_TOOL_CALL_INTEGRITY": 1, "INCONCLUSIVE_NO_RESTORE": 2, "INCONCLUSIVE_NONDETERMINISTIC": 2,
"INCONCLUSIVE_COLD_ARM_WARM": 2, "ERROR": 4}
MAX_TOOL_ROUNDS = 4
DEFAULT_TURNS = [
"Use the shell tool to list the files in the current directory (run `ls -la`).",
"Use the read_file tool to read the file src/main.rs, lines 1 to 40, then summarise it in two sentences.",
"Use the update_plan tool to record a three step plan: inspect the code (completed), fix the bug (in_progress), run the tests (pending).",
"Now say in one sentence what you would do next. Do not call a tool.",
]
def sha256_text(text):
return hashlib.sha256(text.encode("utf8")).hexdigest()
# ---- schema check (small subset of JSON Schema: type, properties, required, items) -------------------------------------------------------------
def _type_ok(t, v):
return {"object": isinstance(v, dict), "array": isinstance(v, list), "string": isinstance(v, str), "boolean": isinstance(v, bool),
"integer": isinstance(v, int) and not isinstance(v, bool),
"number": isinstance(v, (int, float)) and not isinstance(v, bool), "null": v is None}.get(t, True)
def schema_errors(schema, v, path="$"):
errs = []
t = schema.get("type")
if t and not _type_ok(t, v):
return ["%s: expected %s" % (path, t)]
if isinstance(v, dict):
for k in schema.get("required", []):
if k not in v:
errs.append("%s: missing required key %s" % (path, k))
for k, sub in (schema.get("properties") or {}).items():
if k in v:
errs.extend(schema_errors(sub, v[k], path + "." + k))
if schema.get("additionalProperties") is False:
errs.extend("%s: unexpected key %s" % (path, k) for k in v if k not in (schema.get("properties") or {}))
if isinstance(v, list) and isinstance(schema.get("items"), dict):
for i, x in enumerate(v):
errs.extend(schema_errors(schema["items"], x, "%s[%d]" % (path, i)))
return errs
# ---- one streamed request ----------------------------------------------------------------------------------------------------------------------
def stream_request(base, key, body, timeout=3600):
"""Returns {items, usage, status, terminal, deltas_ok, error}. items: the output items as the server finished them."""
headers = {"Content-Type": "application/json"}
if key:
headers["Authorization"] = "Bearer " + key
req = urllib.request.Request(base.rstrip("/") + "/v1/responses", json.dumps(body).encode(), headers)
out = {"items": [], "usage": {}, "status": None, "terminal": None, "arg_deltas": {}, "arg_done": {}, "error": None}
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
for raw in r:
line = raw.decode("utf8", "replace").strip()
if not line.startswith("data:"):
continue
try:
d = json.loads(line[5:])
except ValueError:
continue
ty = d.get("type", "")
if ty == "response.output_item.done":
out["items"].append((d.get("output_index"), d.get("item") or {}))
elif ty == "response.function_call_arguments.delta":
out["arg_deltas"].setdefault(d.get("output_index"), []).append(d.get("delta", ""))
elif ty == "response.function_call_arguments.done":
out["arg_done"][d.get("output_index")] = d.get("arguments")
elif ty in ("response.completed", "response.incomplete", "response.failed"):
resp = d.get("response") or {}
out["terminal"], out["status"], out["usage"] = ty, resp.get("status"), resp.get("usage") or {}
if not out["items"] and isinstance(resp.get("output"), list):
out["items"] = list(enumerate(resp["output"]))
except (urllib.error.URLError, OSError, ValueError) as exc:
out["error"] = "%s: %s" % (type(exc).__name__, exc)
out["items"] = [item for _, item in sorted(out["items"], key=lambda p: (p[0] is None, p[0]))]
return out
def normalise(items):
"""The comparable form of an arm's output: type + the text-bearing fields only (ids and timestamps differ by construction)."""
norm = []
for it in items:
ty = it.get("type")
if ty == "function_call":
norm.append({"type": ty, "name": it.get("name"), "arguments": it.get("arguments")})
elif ty == "message":
norm.append({"type": ty, "text": "".join(c.get("text", "") for c in it.get("content", []) if isinstance(c, dict))})
elif ty == "reasoning":
norm.append({"type": ty, "text": "".join(c.get("text", "") for c in (it.get("content") or []) if isinstance(c, dict))})
else:
norm.append({"type": ty})
return norm
def first_difference(a, b):
"""(item index, 'type'|'field'|'char', detail) of the first difference between two normalised outputs, or None."""
for i in range(max(len(a), len(b))):
if i >= len(a) or i >= len(b):
return {"item": i, "what": "item count", "a": len(a), "b": len(b)}
if a[i] == b[i]:
continue
for field in sorted(set(a[i]) | set(b[i])):
x, y = a[i].get(field), b[i].get(field)
if x != y:
at = next((j for j in range(min(len(x or ""), len(y or ""))) if (x or "")[j] != (y or "")[j]), min(len(x or ""), len(y or ""))) \
if isinstance(x, str) and isinstance(y, str) else None
return {"item": i, "what": field, "char": at}
return None
def integrity_errors(res, tools):
"""Tool-call and stream integrity of ONE arm's response. Returns a list of strings (empty = intact)."""
errs = []
if res["error"]:
return ["transport: " + res["error"]]
if res["terminal"] != "response.completed":
errs.append("stream ended with %s (status %s), not response.completed" % (res["terminal"], res["status"]))
by = dict((t["name"], t) for t in tools if isinstance(t, dict) and t.get("name"))
for k, it in enumerate(res["items"]):
if it.get("type") != "function_call":
continue
name = it.get("name")
if name not in by:
errs.append("item %d: call to undeclared tool %r" % (k, name))
if not it.get("call_id"):
errs.append("item %d: no call_id" % k)
try:
args = json.loads(it.get("arguments", ""))
except ValueError as exc:
errs.append("item %d: arguments do not parse as JSON (%s): %.120r" % (k, exc, it.get("arguments", "")))
continue
if not isinstance(args, dict):
errs.append("item %d: arguments are not a JSON object" % k)
elif name in by:
errs.extend("item %d: %s" % (k, e) for e in schema_errors(by[name].get("parameters", {}), args))
deltas = "".join(res["arg_deltas"].get(k, []))
done = res["arg_done"].get(k)
if done is not None and done != it.get("arguments"):
errs.append("item %d: arguments.done differs from the item's arguments" % k)
if deltas and deltas != it.get("arguments"):
errs.append("item %d: streamed argument deltas differ from the item's arguments" % k)
return errs
# ---- the verdict, a pure function of the pair records ------------------------------------------------------------------------------------------
def judge(pairs, min_restore_fraction=0.8, control=False):
"""pairs: list of dicts {index, equal, diff, restored (None for the first request), integrity: {reply: [...], cold: [...]}, control_equal (or None),
error (or None)}. Returns {verdict, reasons, restored, restore_candidates}."""
reasons = []
if not pairs:
return {"verdict": "ERROR", "reasons": ["no request was completed"], "restored": 0, "restore_candidates": 0}
errors = [p for p in pairs if p.get("error")]
if errors:
return {"verdict": "ERROR", "reasons": ["request %s: %s" % (p["index"], p["error"]) for p in errors], "restored": 0, "restore_candidates": 0}
cands = [p for p in pairs if p.get("restored") is not None]
restored = sum(1 for p in cands if p["restored"])
broken = [(p["index"], arm, e) for p in pairs for arm in ("reply", "cold") for e in p["integrity"].get(arm, [])]
if broken:
return {"verdict": "FAIL_TOOL_CALL_INTEGRITY", "reasons": ["request %s, %s arm: %s" % b for b in broken[:10]], "restored": restored,
"restore_candidates": len(cands)}
warm = [p["index"] for p in pairs if p.get("cold_warm")]
if warm:
return {"verdict": "INCONCLUSIVE_COLD_ARM_WARM", "reasons": ["the cold arm reported cached tokens at request(s) %s" % warm], "restored": restored,
"restore_candidates": len(cands)}
if control and any(p.get("control_equal") is False for p in pairs):
bad = [p["index"] for p in pairs if p.get("control_equal") is False]
return {"verdict": "INCONCLUSIVE_NONDETERMINISTIC", "reasons": ["two cold runs of the same request differ at request(s) %s" % bad],
"restored": restored, "restore_candidates": len(cands)}
differ = [p for p in pairs if not p["equal"]]
if differ:
return {"verdict": "FAIL_OUTPUT_DIFFERS", "reasons": ["request %d: %s" % (p["index"], json.dumps(p["diff"])) for p in differ[:10]],
"restored": restored, "restore_candidates": len(cands)}
if not cands or restored < min_restore_fraction * len(cands):
return {"verdict": "INCONCLUSIVE_NO_RESTORE", "reasons": ["the reply arm restored %d of %d requests after the first (need %.0f %%)" % (
restored, len(cands), 100 * min_restore_fraction)], "restored": restored, "restore_candidates": len(cands)}
return {"verdict": "PASS", "reasons": reasons, "restored": restored, "restore_candidates": len(cands)}
# ---- the session --------------------------------------------------------------------------------------------------------------------------------
def message(role, text):
return {"type": "message", "role": role, "content": [{"type": "input_text" if role != "assistant" else "output_text", "text": text}]}
def load_scenario(args):
import e2e_client as ec # stdlib-only sibling: TOOLS and the canned tool results of the wire-behaviour scenarios
tools = ec.TOOLS
results = dict(ec.TOOL_RESULTS)
turns = list(DEFAULT_TURNS)
if args.scenario:
with open(args.scenario, "r", encoding="utf-8") as fh:
doc = json.load(fh)
tools, results, turns = doc.get("tools", tools), doc.get("tool_results", results), doc.get("user_turns", turns)
context = []
for path in args.context_file or []:
with open(path, "r", encoding="utf-8", errors="replace") as fh:
context.append(message("user", fh.read()))
return tools, results, turns, context
def request_body(args, tools, history):
body = {"model": args.model, "input": history, "tools": tools, "tool_choice": "auto", "parallel_tool_calls": False, "store": False,
"stream": True, "temperature": 0, "max_output_tokens": args.max_output}
if args.instructions:
body["instructions"] = args.instructions
return body
def res_to_json(res):
return {"items": res["items"], "usage": res["usage"], "status": res["status"], "terminal": res["terminal"], "error": res["error"],
"arg_deltas": dict((str(k), v) for k, v in res["arg_deltas"].items()), "arg_done": dict((str(k), v) for k, v in res["arg_done"].items())}
def res_from_json(doc):
return {"items": doc["items"], "usage": doc["usage"], "status": doc["status"], "terminal": doc["terminal"], "error": doc["error"],
"arg_deltas": dict((int(k), v) for k, v in doc["arg_deltas"].items()), "arg_done": dict((int(k), v) for k, v in doc["arg_done"].items())}
def read_key(args):
if getattr(args, "key_file", None):
with open(args.key_file, "r", encoding="utf-8") as fh:
return fh.read().strip()
return None
def drive_reply(args, send=stream_request):
"""Phase 1: the agent session against the REPLY arm only. The history is always built from that arm's own output, as an agent's next request would
be, so every request after the first can resume from the arm's reply checkpoint. Returns {tools, records}; a record holds the exact request body
and the arm's response, which phase 2 sends unchanged to the cold arm."""
key = read_key(args)
tools, results, turns, history = load_scenario(args)
records = []
for turn_no, user_text in enumerate(turns[:args.turns], 1):
history.append(message("user", user_text))
for _round in range(MAX_TOOL_ROUNDS):
body = request_body(args, tools, history)
reply = send(args.reply_url, key, body)
records.append({"index": len(records) + 1, "turn": turn_no, "body": json.loads(json.dumps(body)), "reply": res_to_json(reply)}) # a copy: history grows
if reply["error"]:
return {"tools": tools, "records": records}
calls = [it for it in reply["items"] if it.get("type") == "function_call"]
for it in reply["items"]:
if it.get("type") == "message":
history.append(message("assistant", "".join(c.get("text", "") for c in it.get("content", []) if isinstance(c, dict))))
elif it.get("type") == "function_call":
history.append({"type": "function_call", "call_id": it.get("call_id"), "name": it.get("name"), "arguments": it.get("arguments")})
if not calls:
break
for it in calls:
history.append({"type": "function_call_output", "call_id": it.get("call_id"), "output": results.get(it.get("name"), "ok")})
return {"tools": tools, "records": records}
def score(args, recorded, send=stream_request):
"""Phase 2: the recorded bodies, unchanged, to the COLD arm (twice with --control); compare, check integrity, judge."""
key = read_key(args)
tools = recorded["tools"]
t0 = time.monotonic()
pairs = []
for rc in recorded["records"]:
reply = res_from_json(rc["reply"])
body = rc["body"]
index = rc["index"]
rec = {"index": index, "turn": rc["turn"], "prompt_items": len(body["input"]), "prompt_sha256": sha256_text(json.dumps(body["input"], sort_keys=True)),
"error": None}
if reply["error"]:
rec["error"] = "reply arm: %s" % reply["error"]
pairs.append(rec)
break
cold = send(args.cold_url, key, body)
cold2 = send(args.cold_url, key, body) if args.control else None
if cold["error"]:
rec["error"] = "cold arm: %s" % cold["error"]
a, b = normalise(reply["items"]), normalise(cold["items"])
rec["equal"] = a == b
rec["diff"] = None if rec["equal"] else first_difference(a, b)
rec["integrity"] = {"reply": integrity_errors(reply, tools), "cold": integrity_errors(cold, tools)}
rec["control_equal"] = None if cold2 is None else (normalise(cold2["items"]) == b)
ru, cu = reply["usage"], cold["usage"]
cached = lambda u: (u.get("input_tokens_details") or {}).get("cached_tokens") # noqa: E731
rec["usage"] = {"reply": {"input": ru.get("input_tokens"), "cached": cached(ru), "output": ru.get("output_tokens")},
"cold": {"input": cu.get("input_tokens"), "cached": cached(cu), "output": cu.get("output_tokens")}}
rec["restored"] = None
rec["cold_warm"] = bool(cu.get("input_tokens") and (cached(cu) or 0) >= args.min_cached_fraction * cu.get("input_tokens"))
if index > 1:
inp, cch = ru.get("input_tokens"), cached(ru)
rec["restored"] = bool(inp and cch is not None and cch >= args.min_cached_fraction * inp)
pairs.append(rec)
if rec["error"]:
break
j = judge(pairs, args.min_restore_fraction, args.control)
return {"schema": "prefix-tail-equivalence-v1", "verdict": j["verdict"], "reasons": j["reasons"], "restored": j["restored"],
"restore_candidates": j["restore_candidates"], "requests": len(pairs), "control": bool(args.control),
"min_cached_fraction": args.min_cached_fraction, "min_restore_fraction": args.min_restore_fraction, "elapsed_s": round(time.monotonic() - t0, 1),
"tools": [t.get("name") for t in tools], "pairs": pairs}
def run_session(args, send=stream_request):
"""Both phases in one process (both arms up at the same time: needs room for two servers)."""
return score(args, drive_reply(args, send), send)
def write_json(path, doc):
with open(path, "w", encoding="utf-8", newline="\n") as fh:
fh.write(json.dumps(doc, indent=2) + "\n")
class _Parser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write("%s: error: %s\n" % (self.prog, message))
raise SystemExit(3)
def add_session_options(p):
p.add_argument("--model", required=True)
p.add_argument("--key-file")
p.add_argument("--scenario", help="JSON {tools, tool_results, user_turns}; default: the tools and canned results of e2e_client.py")
p.add_argument("--context-file", action="append", help="text prepended as a user message (repeatable); use ~60-70k tokens for the production regime")
p.add_argument("--instructions")
p.add_argument("--turns", type=int, default=len(DEFAULT_TURNS))
p.add_argument("--max-output", type=int, default=512)
def add_score_options(p):
p.add_argument("--control", action="store_true", help="send every cold request twice (determinism control)")
p.add_argument("--min-cached-fraction", type=float, default=0.5)
p.add_argument("--min-restore-fraction", type=float, default=0.8)
def report(result, out):
write_json(out, result)
sys.stdout.write("%s: %d requests, restored %d of %d, %s\n" % (result["verdict"], result["requests"], result["restored"], result["restore_candidates"],
"; ".join(result["reasons"][:3])))
return EXIT[result["verdict"]]
def main(argv=None):
parser = _Parser(prog="prefix_tail_equivalence.py", description=__doc__.split("\n")[0])
sub = parser.add_subparsers(dest="command")
sub.required = True
p = sub.add_parser("run", help="both arms up at once: record against the reply arm, replay against the cold arm, judge")
p.add_argument("--cold-url", required=True)
p.add_argument("--reply-url", required=True)
p.add_argument("--out", required=True, help="result JSON (run roots outside Git)")
add_session_options(p)
add_score_options(p)
p = sub.add_parser("record", help="phase 1, reply arm only: drive the session and write the exact requests and the arm's answers")
p.add_argument("--reply-url", required=True)
p.add_argument("--record-out", required=True, help="recording JSON (holds prompts and replies: outside Git)")
add_session_options(p)
p = sub.add_parser("replay", help="phase 2, cold arm only (restart the server without the cache first): send the recorded requests, judge")
p.add_argument("--cold-url", required=True)
p.add_argument("--record", required=True)
p.add_argument("--key-file")
p.add_argument("--out", required=True)
add_score_options(p)
args = parser.parse_args(argv)
try:
if args.command == "run":
return report(run_session(args), args.out)
if args.command == "record":
recorded = drive_reply(args)
write_json(args.record_out, recorded)
bad = [r["index"] for r in recorded["records"] if r["reply"]["error"]]
sys.stdout.write("recorded %d requests%s\n" % (len(recorded["records"]), (", transport error at %s" % bad) if bad else ""))
return EXIT["ERROR"] if bad else 0
with open(args.record, "r", encoding="utf-8") as fh:
recorded = json.load(fh)
return report(score(args, recorded), args.out)
except (OSError, ValueError, ImportError) as exc:
sys.stderr.write("ERROR: %s\n" % exc)
return EXIT["ERROR"]
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,70 @@
# Test plan: prefix-cache `reply` tail, restore vs cold prefill (STRA-328)
Status: plan and tool ready; **not run** (needs the 5090, which was not available to this work). Nothing here changes a default.
`rtx5090-32g` still ships `memory.prefix_cache_tail = reply`; the verdict of this plan decides whether that stays (AGENTS.md: a lossy default needs
its quality gate).
## What is being tested
After a request the `reply` tail stores a checkpoint at the end of prompt + committed reply
(`crates/leleka-runtime/src/qwen_forward/original_serve_prefix.rs`, around lines 511-526). The cells past the prompt were written by the decode
kernels. The next agent turn resumes from there; a cold prefill of the same tokens would write them with the prefill kernels. The states are not
bit-identical by construction, so the question is whether the continuation is the same and whether tool calls stay intact.
Existing evidence (`docs/prefix-cache.md`, job 9d4/9d5, `scripts/quality/q_tail_gate.py`): d_top1 p99 0.401 and flips 1.45 % for `reply` against 0.394 and
1.45 % for a chunk-cut control, teacher-forced on 40 requests. That shows the noise floor only. A replay cannot score `reply` itself (an arm's own greedy
replies diverge from the recorded ones, so the next recorded prompt no longer extends them) and no tool-call integrity check was recorded.
## Design
Paired, live, greedy, same tokens: `scripts/e2e/prefix_tail_equivalence.py`.
1. **Record (reply arm).** A multi-turn agent session (shell / read_file / update_plan tools with canned tool results, a 60-70k-token context file)
is driven against the reply arm. The history of every request is built from that arm's own output, so each request after the first resumes
from its own reply checkpoint, as in production. The exact request bodies and the arm's answers are written to a recording.
2. **Replay (cold arm).** The server is restarted with `--prefix-cache-mib 0` (everything else identical) and the recorded bodies are sent unchanged:
a cold prefill of identical tokens. With `--control` every cold request is sent twice to establish that greedy decoding is run-to-run
deterministic on this setup; without that control a difference cannot be blamed on the restore.
3. **Judge** (`judge()`): per request, output items identical string for string (message text, function_call name and arguments, reasoning text);
tool-call integrity on each arm (declared name, call_id, arguments parse as a JSON object and satisfy the tool schema, streamed argument deltas ==
done == item, stream ends with `response.completed`); restore evidence (`usage.input_tokens_details.cached_tokens` of the reply arm >= 50 % of the
input on at least 80 % of the requests after the first; the cold arm must report none).
Verdicts and exit codes: `PASS` 0; `FAIL_OUTPUT_DIFFERS`, `FAIL_TOOL_CALL_INTEGRITY` 1; `INCONCLUSIVE_NO_RESTORE`, `INCONCLUSIVE_NONDETERMINISTIC`,
`INCONCLUSIVE_COLD_ARM_WARM` 2; usage 3; `ERROR` 4. An inconclusive run is not evidence for the default.
## Preconditions on the server
* The 5090 free of other jobs (one serve instance at a time; the two phases are sequential for that reason). Memory headroom first (`mem_ok`-style
check): the server hung on 2026-10-29 around 23:25Z under memory pressure.
* Same binary, model digest, context, KV type, speculation settings; `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0` (static tier) in both phases.
* Outputs in a run root outside Git (they hold prompts and replies). Record the hardware, software, model digest, flags, token counts and cached
tokens as the charter requires (the result JSON carries per-request input / cached / output tokens).
## Commands
```
python3 scripts/e2e/prefix_tail_equivalence.py record --reply-url http://127.0.0.1:8081 --model <model id> --key-file <key file> \
--context-file <60-70k-token text> --turns 12 --record-out <run root>/tail-record.json
# stop the server; start it again with the same flags but --prefix-cache-mib 0
python3 scripts/e2e/prefix_tail_equivalence.py replay --cold-url http://127.0.0.1:8081 --record <run root>/tail-record.json --control \
--key-file <key file> --out <run root>/tail-equivalence.json
```
Run it on at least three independent sessions (different context files / task scripts) before reading anything into a PASS; one session is one sample.
## Numeric gate (acceptance item AC1, q_pair / class numbers)
`scripts/quality/q_pair.py LOG_A LOG_B [--control LOG_A2]` compares the top-16 log-probability rows of two port smoke logs of the SAME teacher-forced
corpus bit for bit; `scripts/quality/q_tail_gate.py REPLAY_LOG CAPTURE_DIR [--control LOG2]` applies the rule p99, max and flip rate each <= 1.25 x the
chunk-cut control. Both need teacher-forced logs, and the recording above is not in the capture format `q_tail_gate.py` reads. Open decision for the
owner / TL: either convert the recorded session to a capture directory (the reply arm's tokens as the forced path) or take captures from live
sessions of job 9e3. Until then this plan gives the greedy-identity and tool-call evidence, not the numeric class.
## Decision rule
* `PASS` on all sessions and the numeric gate within the control: keep `reply` as the default; add the evidence (verdict JSONs, command lines,
hardware / software / digest) to `docs/prefix-cache.md`.
* Any `FAIL_*`: make `prompt` (or `off`) the profile default and mark `reply` as an explicitly experimental mode. That is a separate change that
needs the owner.
* `INCONCLUSIVE_*`: fix the setup and re-run; the default stays as it is, flagged as unproven.
+205
View File
@@ -0,0 +1,205 @@
"""Tests of prefix_tail_equivalence.py (STRA-328): the verdict logic on in-process fake servers. No engine, no GPU, no network beyond 127.0.0.1.
Run: python -m unittest test_prefix_tail_equivalence -v (from scripts/e2e)
"""
import argparse
import hashlib
import http.server
import json
import os
import sys
import tempfile
import threading
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import prefix_tail_equivalence as PT # noqa: E402
class Arm(http.server.BaseHTTPRequestHandler):
"""A fake /v1/responses server. cfg: arm ('reply'|'cold') and mode (see the tests); state in server.calls."""
def log_message(self, *a):
pass
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
srv = self.server
srv.calls += 1
items_in = body["input"]
digest = hashlib.sha256(json.dumps(items_in, sort_keys=True).encode()).hexdigest()[:8]
last = items_in[-1]
out = []
text = None
if last.get("type") == "function_call_output":
text = "done %d" % len(items_in)
elif "Use the" not in json.dumps(last):
text = "answer %s" % digest
if text is not None:
if srv.mode == "diverge" and srv.arm == "reply" and len(items_in) >= 6:
text += " (decode-state drift)"
if srv.mode == "nondet" and srv.arm == "cold":
text += " #%d" % srv.calls
out.append({"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": text}]})
else:
args = '{"command": ["ls", "-la"]}'
if srv.mode == "bad_args" and srv.arm == "reply":
args = '{"command": ["ls", "-la"'
if srv.mode == "bad_tool" and srv.arm == "reply":
out_name = "rm_rf"
else:
out_name = "shell"
out.append({"type": "function_call", "call_id": "call_" + digest, "name": out_name, "arguments": args})
n_in = 100 * len(items_in)
cached = 0
if srv.arm == "reply" and srv.mode != "no_cache" and len(items_in) > 2:
cached = n_in - 50
if srv.arm == "cold" and srv.mode == "warm_cold" and len(items_in) > 2:
cached = n_in - 50
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.end_headers()
for k, it in enumerate(out):
if it["type"] == "function_call":
a = it["arguments"]
for part in (a[:5], a[5:]):
self.wfile.write(("data: " + json.dumps({"type": "response.function_call_arguments.delta", "output_index": k, "delta": part}) + "\n\n").encode())
self.wfile.write(("data: " + json.dumps({"type": "response.function_call_arguments.done", "output_index": k, "arguments": a}) + "\n\n").encode())
self.wfile.write(("data: " + json.dumps({"type": "response.output_item.done", "output_index": k, "item": it}) + "\n\n").encode())
done = {"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": n_in, "output_tokens": 7,
"input_tokens_details": {"cached_tokens": cached}}}}
if srv.mode == "cut" and srv.arm == "reply":
done = None # the stream just ends
if done:
self.wfile.write(("data: " + json.dumps(done) + "\n\n").encode())
def start(arm, mode):
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Arm)
srv.arm, srv.mode, srv.calls = arm, mode, 0
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
class Session(unittest.TestCase):
def run_pair(self, reply_mode="ok", cold_mode="ok", control=False, turns=4):
reply, cold = start("reply", reply_mode), start("cold", cold_mode)
for srv in (reply, cold):
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
args = argparse.Namespace(cold_url="http://127.0.0.1:%d" % cold.server_address[1], reply_url="http://127.0.0.1:%d" % reply.server_address[1],
model="m", key_file=None, scenario=None, context_file=None, instructions=None, turns=turns, max_output=64,
control=control, min_cached_fraction=0.5, min_restore_fraction=0.8)
return PT.run_session(args)
def test_identical_arms_with_restores_pass(self):
res = self.run_pair(control=True)
self.assertEqual(res["verdict"], "PASS", res["reasons"])
self.assertGreaterEqual(res["requests"], 5, "tool rounds are requests too")
self.assertEqual(res["restored"], res["restore_candidates"])
self.assertTrue(any(p["integrity"]["reply"] == [] for p in res["pairs"]))
def test_a_drifting_reply_arm_fails_with_the_first_difference(self):
res = self.run_pair("diverge")
self.assertEqual(res["verdict"], "FAIL_OUTPUT_DIFFERS")
self.assertIn("char", res["reasons"][0])
def test_malformed_tool_arguments_on_the_reply_arm_fail_integrity(self):
res = self.run_pair("bad_args")
self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY")
self.assertIn("reply arm", res["reasons"][0])
self.assertIn("JSON", res["reasons"][0])
def test_an_undeclared_tool_name_fails_integrity(self):
res = self.run_pair("bad_tool")
self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY")
self.assertIn("undeclared tool", res["reasons"][0])
def test_a_cut_off_stream_fails_integrity(self):
res = self.run_pair("cut")
self.assertEqual(res["verdict"], "FAIL_TOOL_CALL_INTEGRITY")
self.assertIn("response.completed", res["reasons"][0])
def test_no_restore_means_no_evidence(self):
res = self.run_pair("no_cache")
self.assertEqual(res["verdict"], "INCONCLUSIVE_NO_RESTORE")
def test_a_warm_cold_arm_is_not_a_cold_arm(self):
res = self.run_pair(cold_mode="warm_cold")
self.assertEqual(res["verdict"], "INCONCLUSIVE_COLD_ARM_WARM")
def test_nondeterministic_cold_runs_are_inconclusive(self):
res = self.run_pair(cold_mode="nondet", control=True)
self.assertEqual(res["verdict"], "INCONCLUSIVE_NONDETERMINISTIC")
def test_transport_error_is_an_error(self):
args = argparse.Namespace(cold_url="http://127.0.0.1:9", reply_url="http://127.0.0.1:9", model="m", key_file=None, scenario=None,
context_file=None, instructions=None, turns=1, max_output=8, control=False, min_cached_fraction=0.5,
min_restore_fraction=0.8)
self.assertEqual(PT.run_session(args)["verdict"], "ERROR")
def test_cli_exit_codes_and_no_key_in_the_output(self):
reply, cold = start("reply", "diverge"), start("cold", "ok")
for srv in (reply, cold):
self.addCleanup(srv.server_close)
self.addCleanup(srv.shutdown)
with tempfile.TemporaryDirectory() as tmp:
keyf = os.path.join(tmp, "key")
with open(keyf, "w") as fh:
fh.write("sk-secret-test-key")
out = os.path.join(tmp, "res.json")
rc = PT.main(["run", "--cold-url", "http://127.0.0.1:%d" % cold.server_address[1], "--reply-url", "http://127.0.0.1:%d" % reply.server_address[1],
"--model", "m", "--key-file", keyf, "--out", out, "--turns", "4"])
self.assertEqual(rc, 1)
with open(out, "r", encoding="utf-8") as fh:
text = fh.read()
self.assertNotIn("sk-secret-test-key", text)
self.assertEqual(json.loads(text)["verdict"], "FAIL_OUTPUT_DIFFERS")
def test_two_phases_record_then_replay_on_a_restarted_server(self):
"""The production workflow: the reply arm is recorded, stopped, and the recorded bodies are replayed on a cold server."""
for reply_mode, want_rc, want in (("ok", 0, "PASS"), ("diverge", 1, "FAIL_OUTPUT_DIFFERS"), ("bad_args", 1, "FAIL_TOOL_CALL_INTEGRITY")):
reply = start("reply", reply_mode)
with tempfile.TemporaryDirectory() as tmp:
rec = os.path.join(tmp, "record.json")
rc = PT.main(["record", "--reply-url", "http://127.0.0.1:%d" % reply.server_address[1], "--model", "m", "--turns", "4", "--record-out", rec])
reply.shutdown()
reply.server_close()
self.assertEqual(rc, 0, reply_mode)
cold = start("cold", "ok") # a new process on another port, without the cache
out = os.path.join(tmp, "res.json")
rc = PT.main(["replay", "--cold-url", "http://127.0.0.1:%d" % cold.server_address[1], "--record", rec, "--control", "--out", out])
cold.shutdown()
cold.server_close()
self.assertEqual((rc, json.load(open(out, "r", encoding="utf-8"))["verdict"]), (want_rc, want), reply_mode)
def test_usage_error_exits_3(self):
with self.assertRaises(SystemExit) as cm:
PT.main(["run", "--model", "m"])
self.assertEqual(cm.exception.code, 3)
class Pure(unittest.TestCase):
def test_schema_errors(self):
schema = {"type": "object", "properties": {"command": {"type": "array", "items": {"type": "string"}}, "timeout_ms": {"type": "integer"}},
"required": ["command"], "additionalProperties": False}
self.assertEqual(PT.schema_errors(schema, {"command": ["ls"]}), [])
self.assertTrue(PT.schema_errors(schema, {}))
self.assertTrue(PT.schema_errors(schema, {"command": [1]}))
self.assertTrue(PT.schema_errors(schema, {"command": ["a"], "extra": 1}))
self.assertTrue(PT.schema_errors(schema, {"command": ["a"], "timeout_ms": True}))
def test_first_difference_names_item_and_char(self):
a = [{"type": "message", "text": "abcdef"}]
b = [{"type": "message", "text": "abcxef"}]
self.assertEqual(PT.first_difference(a, b), {"item": 0, "what": "text", "char": 3})
self.assertIsNone(PT.first_difference(a, a))
self.assertEqual(PT.first_difference(a, a + a)["what"], "item count")
def test_judge_empty_is_error(self):
self.assertEqual(PT.judge([])["verdict"], "ERROR")
if __name__ == "__main__":
unittest.main()