feat(e2e): validity derivation module, schedule balance check and ledger/manifest cross-check (STRA-312)

Adds scripts/e2e/evidence/validity.py (E2 validity rules, E1 balanced-schedule check, E8
ledger/manifest cross-check; countable is derived, never typed) and test_validity.py.
The STRA-311 golden vectors pass unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-28 20:36:31 +01:00
co-authored by Claude Sonnet 5.5
parent 75254fb593
commit 806774609e
2 changed files with 711 additions and 0 deletions
+278
View File
@@ -0,0 +1,278 @@
"""Tests of validity.py (STRA-312, S0.1c): the acceptance commands AC2-AC7 and AC9 of the leaf on multi-pair fixtures, boundary and
precedence cases, and the in-process functions the runner (STRA-257) and the evaluator (STRA-290) import.
Run: python -m unittest scripts.e2e.evidence.test_validity_golden scripts.e2e.evidence.test_validity -v (from the repository root)
Stdlib only, Python >= 3.9. The golden cases (test_validity_golden.py) are NOT edited here; their fixture builder
golden/gen_validity.py:materialize() is reused so both test files read identical fixture formats.
"""
import copy
import importlib.util
import json
import os
import subprocess
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
GOLDEN = os.path.join(HERE, "golden")
VALIDITY = os.path.join(HERE, "validity.py")
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
V = _load("validity_under_test", VALIDITY)
G = _load("gen_validity_for_test", os.path.join(GOLDEN, "gen_validity.py"))
with open(os.path.join(GOLDEN, "validity_cases.json"), "r", encoding="utf-8") as _fh:
DOC = json.load(_fh)
ARMS = ["ours", "vanilla_default", "vanilla_noskip"]
def pw(mn, mx, mean, lim=150.0):
return {"set": G.power_set(mn, mx, mean, lim)}
def clean(valid=True, reasons=(), event=None):
return {"valid": valid, "reasons": list(reasons), "event": event}
def run_cli(*args):
proc = subprocess.run([sys.executable, VALIDITY] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True, cwd=REPO, timeout=120)
return proc.returncode, proc.stdout, proc.stderr
class Fixture(object):
"""Files for one `pairs` run, built with the golden materialize(). expected: pair number -> clean(...) (types countable)."""
def __init__(self, test, machine, pairs, expected=None, schedule="pairs_n6", ledger_extra=None, drop_ledger=None):
self.machine = machine
self.tmp = tempfile.TemporaryDirectory()
test.addCleanup(self.tmp.cleanup)
case_input = {"machine": machine, "schedule": schedule, "pairs": pairs}
if ledger_extra:
case_input["ledger_extra"] = ledger_extra
if drop_ledger:
case_input["drop_ledger"] = drop_ledger
exp = dict((n, dict(clean(), pair=n, **dict((k, v) for k, v in e.items()))) for n, e in (expected or {}).items())
mat = G.materialize(case_input, DOC["templates"], DOC["schedules"], exp)
self.records = os.path.join(self.tmp.name, "records")
os.makedirs(self.records)
for fname, rec in mat["records"].items():
self.write(os.path.join(self.records, fname), rec)
self.schedule = os.path.join(self.tmp.name, "schedule.json")
self.write(self.schedule, mat["schedule"])
self.ledger = os.path.join(self.tmp.name, "ledger.jsonl")
self.write(self.ledger, "".join(json.dumps(line) + "\n" for line in mat["ledger"]))
@staticmethod
def write(path, obj):
with open(path, "w", encoding="utf-8", newline="\n") as fh:
fh.write(obj if isinstance(obj, str) else json.dumps(obj, indent=2))
def run(self):
rc, out, err = run_cli("pairs", "--records", self.records, "--schedule", self.schedule, "--ledger", self.ledger,
"--machine", self.machine)
return rc, out, err
def by_pair(out):
return dict((p["pair"], p) for p in json.loads(out)["pairs"])
class AcceptanceCommands(unittest.TestCase):
def test_ac2_clean_laptop_run_valid_and_51w_run_invalid(self):
fx = Fixture(self, "laptop", [
{"pair": 1, "arms": dict((a, pw(110.0, 126.6, 118.3)) for a in ARMS)},
{"pair": 2, "arms": {"ours": pw(51.0, 51.0, 51.0)}},
], expected={1: clean(), 2: clean(False, ["POWER"])})
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
got = by_pair(out)
self.assertTrue(got[1]["valid"])
self.assertEqual(got[1]["reasons"], [])
self.assertFalse(got[2]["valid"])
self.assertEqual(got[2]["reasons"], ["POWER"])
self.assertAlmostEqual(json.loads(out)["invalid_rate"], 0.5)
def test_ac3_orphan_run_id_exit_2_and_named(self):
fx = Fixture(self, "server", [{"pair": 1, "arms": {}}], ledger_extra=[
{"pair": 2, "arm": "vanilla_noskip", "state": "QUEUED"}, {"pair": 2, "arm": "vanilla_noskip", "state": "DONE"}])
rc, out, err = fx.run()
self.assertEqual(rc, 2)
self.assertIn("pair-0002.vanilla_noskip", out + err)
def test_ac4_typed_countable_true_derived_false(self):
fx = Fixture(self, "laptop", [
{"pair": 1, "arms": {}},
{"pair": 2, "arms": {"vanilla_noskip": {"set": G.power_set(99.0, 112.0, 105.0, 150.0), "countable": True}}},
], expected={1: clean(), 2: clean(False, ["POWER"])})
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
got = by_pair(out)
self.assertTrue(got[1]["valid"])
self.assertIn("COUNTABLE_MISMATCH", got[2]["reasons"])
self.assertFalse(got[2]["valid"])
def test_ac5_schedule_check_n30_n29_and_missing_permutation(self):
want = {"n30_balanced": True, "n29": False, "n30_group_missing_permutation": False}
for key, balanced in want.items():
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "s.json")
Fixture.write(path, DOC["schedules"][key])
rc, out, err = run_cli("schedule", "--check", path)
self.assertEqual(rc, 0, err)
res = json.loads(out)
self.assertIs(res["balanced"], balanced, key)
self.assertRegex(res["hash"], r"^[0-9a-f]{64}$")
def test_ac6_session_start_attestation_absent(self):
absent = {"present": False, "identifier": None, "time_utc": None}
fx = Fixture(self, "laptop", [
{"pair": 1, "arms": {}},
{"pair": 2, "arms": {"ours": {"set": {"hardware.owner_attestation": absent}}}},
], expected={1: clean(), 2: clean(False, ["ATTESTATION_MISSING"], "OWNER")})
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
got = by_pair(out)
self.assertTrue(got[1]["valid"])
self.assertFalse(got[2]["valid"])
self.assertEqual(got[2]["reasons"], ["ATTESTATION_MISSING"])
self.assertEqual(got[2]["event"], "OWNER")
def test_ac7_foreign_load_6_percent_flagged_4_percent_not(self):
def fl(pct):
return {"vanilla_default": {"set": {"hardware.foreign_load.samples":
[{"process_name": "x", "cpu_percent_of_core": pct, "duration_s": 3.0}]}}}
fx = Fixture(self, "laptop", [{"pair": 1, "arms": fl(6.0)}, {"pair": 2, "arms": fl(4.0)}],
expected={1: clean(False, ["FOREIGN_LOAD"]), 2: clean()})
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
got = by_pair(out)
self.assertFalse(got[1]["valid"])
self.assertEqual(got[1]["reasons"], ["FOREIGN_LOAD"])
self.assertTrue(got[2]["valid"])
def test_ac9_build_id_mismatch_vs_equal(self):
other = "fedcba9876543210fedcba9876543210fedcba98"
fx = Fixture(self, "laptop", [
{"pair": 1, "arms": {"ours": {"set": {"ours_build_id_observed.commit": other}}}},
{"pair": 2, "arms": {}},
], expected={1: clean(False, ["INFRASTRUCTURE"], "RERUN"), 2: clean()})
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
got = by_pair(out)
self.assertFalse(got[1]["valid"])
self.assertEqual(got[1]["reasons"], ["INFRASTRUCTURE"])
self.assertEqual(got[1]["event"], "RERUN")
self.assertTrue(got[2]["valid"])
self.assertIsNone(got[2]["event"])
class Boundaries(unittest.TestCase):
def pair(self, machine, arms, valid=True, reasons=(), event=None):
fx = Fixture(self, machine, [{"pair": 1, "arms": arms}], expected={1: clean(valid, reasons, event)})
rc, out, err = fx.run()
self.assertEqual(rc, 0, err)
return by_pair(out)[1]
def test_server_nonzero_spread_is_power(self):
p = self.pair("server", {"ours": pw(574.0, 575.0, 574.5, 600.0)}, False, ["POWER"])
self.assertEqual(p["reasons"], ["POWER"])
def test_server_floor_does_not_apply(self):
self.assertTrue(self.pair("server", dict((a, pw(50.0, 50.0, 50.0, 600.0)) for a in ARMS))["valid"])
def test_laptop_limit_may_change_inside_the_run(self):
self.assertTrue(self.pair("laptop", dict((a, pw(110.0, 126.6, 118.3)) for a in ARMS))["valid"])
def test_event_precedence_fail_over_owner_over_rerun(self):
absent = {"present": False, "identifier": None, "time_utc": None}
arms = {"ours": {"record": False, "attempts": [{"outcome": "CRASH", "attributed_to": None}]},
"vanilla_default": {"set": {"hardware.owner_attestation": absent}},
"vanilla_noskip": {"record": False, "attempts": [{"outcome": "CRASH", "attributed_to": "LOCK"}]}}
p = self.pair("laptop", arms, False, ["ATTESTATION_MISSING", "INFRASTRUCTURE"], "FAIL")
self.assertEqual(p["event"], "FAIL")
self.assertEqual(sorted(p["reasons"]), ["ATTESTATION_MISSING", "INFRASTRUCTURE"])
def test_attributed_failures_do_not_count_toward_the_vanilla_cap(self):
attempts = [{"outcome": "CRASH", "attributed_to": "LOCK"}, {"outcome": "CRASH", "attributed_to": None},
{"outcome": "CRASH", "attributed_to": None}]
p = self.pair("laptop", {"vanilla_default": {"record": False, "attempts": attempts}}, False, ["INFRASTRUCTURE"], "RERUN")
# two non-attributable failures are within the cap of two; the attributable one is a RERUN of its own
self.assertEqual(p["event"], "RERUN")
def test_unknown_attribution_is_malformed(self):
fx = Fixture(self, "laptop", [{"pair": 1, "arms": {"vanilla_default": {"record": False,
"attempts": [{"outcome": "CRASH", "attributed_to": "SUNSPOTS"}]}}}])
self.assertEqual(fx.run()[0], 3)
def test_incomplete_pair_is_malformed_not_valid(self):
fx = Fixture(self, "laptop", [{"pair": 1, "arms": {"ours": {"record": False}}}])
rc, out, err = fx.run()
self.assertEqual(rc, 3)
self.assertIn("incomplete", err)
def test_usage_error_exits_3_not_2(self):
self.assertEqual(run_cli("pairs", "--machine", "laptop")[0], 3)
self.assertEqual(run_cli("bogus")[0], 3)
def test_out_file_is_written_when_requested(self):
fx = Fixture(self, "server", [{"pair": 1, "arms": {}}])
out_path = os.path.join(fx.tmp.name, "report.json")
rc, out, err = run_cli("pairs", "--records", fx.records, "--schedule", fx.schedule, "--ledger", fx.ledger,
"--machine", "server", "--out", out_path)
self.assertEqual(rc, 0, err)
with open(out_path, "r", encoding="utf-8") as fh:
self.assertEqual(json.load(fh), json.loads(out))
class ImportedFunctions(unittest.TestCase):
"""The runner and the evaluator import these; the CLI is a thin shell around them."""
def test_derive_pairs_in_process(self):
fx = Fixture(self, "laptop", [{"pair": 1, "arms": {}}])
records = V.read_records(fx.records)
last, _ = V.read_ledger(fx.ledger)
with open(fx.schedule, "r", encoding="utf-8") as fh:
sched = json.load(fh)
res = V.derive_pairs(records, sched, last, "laptop")
self.assertEqual(res["pairs"], [{"pair": 1, "valid": True, "reasons": [], "event": None}])
self.assertTrue(res["manifest_ok"])
self.assertEqual(res["invalid_rate"], 0.0)
def test_schedule_balanced_ignores_file_order_of_blocks(self):
sched = copy.deepcopy(DOC["schedules"]["n30_balanced"])
sched["blocks"].reverse()
self.assertTrue(V.schedule_balanced(sched))
def test_schedule_balanced_defensive_on_garbage(self):
for bad in ({}, {"arms": 1}, {"arms": ["a"], "blocks": [], "n_pairs": 0}, {"arms": ["a", "b", "c"], "blocks": [{"x": 1}]}):
self.assertFalse(V.schedule_balanced(bad))
def test_thresholds_are_the_ba_values(self):
self.assertEqual((V.LAPTOP_POWER_FLOOR_W, V.ARM_MEAN_LIMIT_DIFF_MAX_W, V.ARM_SPREAD_MAX_W, V.SERVER_SPREAD_W),
(100.0, 10.0, 20.0, 0.0))
self.assertEqual((V.CONTEXT_TOKENS, V.MAX_PROMPT_TOKENS_MIN, V.VANILLA_RERUN_CAP), (262144, 200000, 2))
for key in ("laptop_power_floor_w", "arm_mean_limit_diff_max_w", "arm_spread_max_w", "server_spread_w", "context_tokens",
"max_prompt_tokens_min", "vanilla_rerun_cap"):
self.assertIn(key, DOC["thresholds"])
self.assertEqual(DOC["thresholds"]["laptop_power_floor_w"], V.LAPTOP_POWER_FLOOR_W)
self.assertEqual(DOC["thresholds"]["arm_mean_limit_diff_max_w"], V.ARM_MEAN_LIMIT_DIFF_MAX_W)
self.assertEqual(DOC["thresholds"]["arm_spread_max_w"], V.ARM_SPREAD_MAX_W)
self.assertEqual(DOC["thresholds"]["server_spread_w"], V.SERVER_SPREAD_W)
self.assertEqual(DOC["thresholds"]["context_tokens"], V.CONTEXT_TOKENS)
self.assertEqual(DOC["thresholds"]["max_prompt_tokens_min"], V.MAX_PROMPT_TOKENS_MIN)
self.assertEqual(DOC["thresholds"]["vanilla_rerun_cap"], V.VANILLA_RERUN_CAP)
if __name__ == "__main__":
unittest.main()
+433
View File
@@ -0,0 +1,433 @@
#!/usr/bin/env python3
"""Validity derivation for END_TO_END evidence series (STRA-312, S0.1c).
The ONE place where the E2 validity rules of STRA-245 (BA round 2, decision D7, comment 3eeb53e1; thresholds first fixed in BA comment
dabfd08e) and the balanced-schedule rule of E1 (D5) are coded. The runner (STRA-257) and the evaluator (STRA-290) import this module;
`countable` is never a typed input: it is DERIVED from the records, and a typed value that disagrees is reported as COUNTABLE_MISMATCH.
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]
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]
stdout: {"balanced": bool, "hash": "<sha256 hex>"}
exit 0 = result produced; 2 = ledger/manifest refusal (the offending run ids are named on stdout and stderr);
3 = malformed input (also an incomplete pair or a command-line usage error).
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).
Precedence when several apply: FAIL > OWNER > RERUN.
Files read
records dir one END_TO_END record (STRA-246 schema v1) per <run_id>.json, run_id = <pair_id>.<arm>
ledger JSONL, append-only, the LAST line of a run_id is its state (QUEUED|STARTED|DONE|INVALID|INTERRUPTED). An INVALID line of a
failed attempt carries outcome (CRASH|TIMEOUT|INTEGRITY_FAILURE) and attributed_to (null or one of INFRA_CAUSES). The
ledger is also the manifest (E8): a DONE run needs a record, a record needs a ledger line, an INVALID run needs no record.
schedule {arms, n_pairs, blocks: [{block, order}], cache_residency_band: {min, max}, foreign_load_threshold:
{cpu_percent_of_core, duration_s}, ...}; the format is fixed by the golden fixtures of STRA-311.
"""
import argparse
import hashlib
import itertools
import json
import os
import sys
# --------------------------------------------------------------------------------------------------------------------------------
# Thresholds. All are BA decisions (not owner numbers): STRA-245 acceptance E1/E2, BA comment 3eeb53e1 (round 2, D5/D7) and BA comment
# dabfd08e. Named so that the item text and the code can be compared line by line.
# --------------------------------------------------------------------------------------------------------------------------------
LAPTOP_POWER_FLOOR_W = 100.0 # E2(1): a sample BELOW 100 W invalidates (laptop only; floor of scripts/laptop/monitor.sh)
ARM_MEAN_LIMIT_DIFF_MAX_W = 10.0 # E2(1): arms' mean limits differing by MORE than 10 W invalidate (laptop)
ARM_SPREAD_MAX_W = 20.0 # E2(1): spread (max - min) within one arm ABOVE 20 W invalidates (laptop)
SERVER_SPREAD_W = 0.0 # E2(1): server limit is the configured value: spread 0 W, equal across the arms
CONTEXT_TOKENS = 262144 # E2(3): 256k class
MAX_PROMPT_TOKENS_MIN = 200000 # E2(3): largest per-turn prompt_tokens >= 200,000
VANILLA_RERUN_CAP = 2 # E2(5): a vanilla failure not attributable is re-run at most twice; the third goes to the owner
# 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")
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
"hardware.cpu_model", "hardware.gpu_name", "hardware.os", "software.driver_version", "software.cuda_version",
"software.leleka_commit", "software.strata_upstream_commit", "model.digest", "configuration.kv", "configuration.slots",
"configuration.batch", "configuration.speculation", "cache.state",
)
EPS_DECIMALS = 9 # differences of decimal inputs are rounded here so 128.01 - 118.0 compares as 10.01, not 10.000000000000005
class Malformed(Exception):
"""Input that cannot be interpreted (exit 3)."""
class Refusal(Exception):
"""Ledger/manifest refusal (exit 2); .names lists the offending run ids."""
def __init__(self, message, names):
Exception.__init__(self, message)
self.names = list(names)
# --------------------------------------------------------------------------------------------------------------------------------
# helpers
# --------------------------------------------------------------------------------------------------------------------------------
def canonical(obj):
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
def schedule_hash(sched):
"""sha256 of the compact sorted-key JSON of the parsed schedule: a function of the content, not of the bytes."""
return hashlib.sha256(canonical(sched).encode("utf-8")).hexdigest()
def get_path(obj, dotted, default=None):
cur = obj
for part in dotted.split("."):
try:
cur = cur[int(part)] if isinstance(cur, list) else cur[part]
except (KeyError, IndexError, TypeError, ValueError):
return default
return cur
def _num(value):
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
return float(value)
def _diff(a, b):
return round(a - b, EPS_DECIMALS)
def _load_json(path, what):
try:
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)
except (OSError, ValueError) as exc:
raise Malformed("%s %s: %s" % (what, path, exc))
# --------------------------------------------------------------------------------------------------------------------------------
# E1: balanced schedule
# --------------------------------------------------------------------------------------------------------------------------------
def schedule_balanced(sched):
"""E1/D5. Three arms: n_pairs a positive multiple of 6, each consecutive group of 6 blocks holds all 6 permutations once.
Two arms: blocks alternate [a, b], [b, a], ... and n_pairs is even. Any other arm count is not balanced."""
if not isinstance(sched, dict):
return False
arms = sched.get("arms")
blocks = sched.get("blocks")
if not isinstance(arms, list) or not isinstance(blocks, list) or len(set(arms)) != len(arms):
return False
try:
numbers = sorted(b["block"] for b in blocks)
orders = [b["order"] for b in blocks]
except (KeyError, TypeError):
return False
if numbers != list(range(1, len(blocks) + 1)) or len(blocks) != sched.get("n_pairs"):
return False
# the blocks are used in block-number order, not in file order
orders = [o for _, o in sorted(zip([b["block"] for b in blocks], orders), key=lambda t: t[0])]
if any(not isinstance(o, list) or sorted(o) != sorted(arms) for o in orders):
return False
if len(arms) == 3:
if not orders or len(orders) % GROUP_SIZE != 0:
return False
every = sorted(list(p) for p in itertools.permutations(arms))
return all(sorted(orders[g * GROUP_SIZE:(g + 1) * GROUP_SIZE]) == every for g in range(len(orders) // GROUP_SIZE))
if len(arms) == 2:
if not orders or len(orders) % 2 != 0:
return False
return all(order == (list(arms) if i % 2 == 0 else list(reversed(arms))) for i, order in enumerate(orders))
return False
# --------------------------------------------------------------------------------------------------------------------------------
# E2: per-pair derivation
# --------------------------------------------------------------------------------------------------------------------------------
def _power_findings(machine, summaries):
"""E2(1). summaries: arm -> power_sample_summary dict or None. Returns True when POWER applies."""
bad = False
means = []
for s in summaries.values():
if not isinstance(s, dict):
return True # no summary: the limit cannot be established
mn, mx, mean, lim = (_num(s.get(k)) for k in ("min_w", "max_w", "mean_w", "power_max_limit_w"))
if None in (mn, mx, mean, lim):
return True
if machine == "laptop" and mn < LAPTOP_POWER_FLOOR_W:
bad = True
if mx > lim:
bad = True # above the card's maximum limit (both machines)
if _diff(mx, mn) > (ARM_SPREAD_MAX_W if machine == "laptop" else SERVER_SPREAD_W):
bad = True
means.append(mean)
if means and _diff(max(means), min(means)) > (ARM_MEAN_LIMIT_DIFF_MAX_W if machine == "laptop" else 0.0):
bad = True
return bad
def _workload_findings(recs):
"""E2(3). True when WORKLOAD applies."""
turn_lists = []
for r in recs.values():
turns = get_path(r, "metrics.turns")
if not isinstance(turns, list) or not turns:
return True
turn_lists.append(turns)
if turn_lists:
if len(set(len(t) for t in turn_lists)) > 1:
return True
for i in range(len(turn_lists[0])):
hashes = set(str(t[i].get("prompt_sha256")) if isinstance(t[i], dict) else None for t in turn_lists)
if len(hashes) > 1 or None in hashes or "None" in hashes:
return True
for r in recs.values():
if get_path(r, "configuration.context_tokens") != CONTEXT_TOKENS:
return True
tokens = [_num(t.get("prompt_tokens")) if isinstance(t, dict) else None for t in get_path(r, "metrics.turns", [])]
if None in tokens or not tokens or max(tokens) < MAX_PROMPT_TOKENS_MIN:
return True
for path in METADATA_PATHS:
value = get_path(r, path)
if value is None or value == "":
return True
return False
def _cache_findings(recs, sched):
"""E2(4). True when CACHE applies: residency before each arm inside the band written in the schedule."""
band = sched.get("cache_residency_band")
if not isinstance(band, dict) or _num(band.get("min")) is None or _num(band.get("max")) is None:
raise Malformed("schedule has no cache_residency_band {min, max}")
for r in recs.values():
value = _num(get_path(r, "cache.page_cache_residency_before.value"))
if value is None or value < band["min"] or value > band["max"]:
return True
return False
def _foreign_load_findings(recs, sched):
"""SC14. True when FOREIGN_LOAD applies; the threshold comes from the schedule file."""
thr = sched.get("foreign_load_threshold")
if not isinstance(thr, dict) or _num(thr.get("cpu_percent_of_core")) is None or _num(thr.get("duration_s")) is None:
raise Malformed("schedule has no foreign_load_threshold {cpu_percent_of_core, duration_s}")
for r in recs.values():
samples = get_path(r, "hardware.foreign_load.samples")
if not isinstance(samples, list):
return True # not recorded: absence of foreign load is not established
for s in samples:
pct, dur = _num(s.get("cpu_percent_of_core")), _num(s.get("duration_s"))
if pct is None or dur is None:
return True
if pct > thr["cpu_percent_of_core"] and dur >= thr["duration_s"]:
return True
return False
def _build_identity_mismatch(recs):
"""E1b (part of E2(5)): an ours record whose observed build id differs from the frozen one."""
ours = recs.get("ours")
if ours is None:
return False
observed, frozen = ours.get("ours_build_id_observed"), ours.get("ours_build_id_frozen")
if not isinstance(observed, dict) or not isinstance(frozen, dict):
return True # the identity cannot be shown to be the frozen one
return observed != frozen
def derive_pair(number, recs, fails, machine, sched, arms):
"""One pair. recs: arm -> record; fails: arm -> [INVALID ledger lines of failed attempts]. Returns the pairs-entry dict."""
reasons, events = set(), []
if _power_findings(machine, dict((a, r.get("power_sample_summary")) for a, r in recs.items())):
reasons.add("POWER")
for r in recs.values(): # E2(2): checked present, not measured
att = get_path(r, "hardware.owner_attestation")
if not isinstance(att, dict) or att.get("present") is not True:
reasons.add("ATTESTATION_MISSING")
events.append("OWNER")
if _workload_findings(recs):
reasons.add("WORKLOAD")
if _cache_findings(recs, sched):
reasons.add("CACHE")
if _build_identity_mismatch(recs):
reasons.add("INFRASTRUCTURE")
events.append("RERUN")
if _foreign_load_findings(recs, sched):
reasons.add("FOREIGN_LOAD")
for arm in arms: # E2(5): failed attempts from the ledger
unattributed = 0
for line in fails.get(arm, []):
cause = line.get("attributed_to")
if cause is not None and cause not in INFRA_CAUSES:
raise Malformed("ledger run %s: attributed_to %r is not one of %s" % (line.get("run_id"), cause, ", ".join(INFRA_CAUSES)))
outcome = line.get("outcome")
if outcome is not None and outcome not in OUTCOMES:
raise Malformed("ledger run %s: outcome %r is not one of %s" % (line.get("run_id"), outcome, ", ".join(OUTCOMES)))
if cause is not None:
reasons.add("INFRASTRUCTURE")
events.append("RERUN")
elif arm == "ours":
events.append("FAIL")
else:
unattributed += 1
events.append("OWNER" if unattributed > VANILLA_RERUN_CAP else "RERUN")
event = max(events, key=lambda e: EVENT_RANK[e]) if events else None
derived = (not reasons) and event is None
for r in recs.values(): # countable is derived; a typed value that disagrees is a finding
if r.get("countable") is not derived:
reasons.add("COUNTABLE_MISMATCH")
return {"pair": number, "valid": (not reasons) and event is None, "reasons": sorted(reasons), "event": event}
# --------------------------------------------------------------------------------------------------------------------------------
# ledger / manifest cross-check (E8) and the pairs command
# --------------------------------------------------------------------------------------------------------------------------------
def read_records(records_dir):
if not os.path.isdir(records_dir):
raise Malformed("records directory %s does not exist" % records_dir)
out = {}
for name in sorted(os.listdir(records_dir)):
if name.endswith(".json"):
rec = _load_json(os.path.join(records_dir, name), "record")
if not isinstance(rec, dict):
raise Malformed("record %s is not a JSON object" % name)
out[name[:-5]] = rec
return out
def read_ledger(path):
"""Returns (last line per run_id, all lines)."""
try:
with open(path, "r", encoding="utf-8") as fh:
text = fh.read()
except OSError as exc:
raise Malformed("ledger %s: %s" % (path, exc))
lines, last = [], {}
for n, raw in enumerate(text.splitlines(), 1):
if not raw.strip():
continue
try:
line = json.loads(raw)
except ValueError as exc:
raise Malformed("ledger %s line %d: %s" % (path, n, exc))
if not isinstance(line, dict) or not isinstance(line.get("run_id"), str) or not isinstance(line.get("state"), str):
raise Malformed("ledger %s line %d: needs string run_id and state" % (path, n))
lines.append(line)
last[line["run_id"]] = line
return last, lines
def _pair_number(line):
block = line.get("block")
if isinstance(block, int) and not isinstance(block, bool):
return block
pair_id = line.get("pair_id")
if isinstance(pair_id, str) and pair_id.rsplit("-", 1)[-1].isdigit():
return int(pair_id.rsplit("-", 1)[-1])
raise Malformed("ledger run %s has neither an integer block nor a pair_id ending in a number" % line["run_id"])
def check_manifest(records, last):
"""E8: every run id whose last state is DONE has a record; every record has a ledger line. Raises Refusal naming the run ids."""
orphans = sorted(rid for rid, line in last.items() if line["state"] == "DONE" and rid not in records)
unlisted = sorted(rid for rid in records if rid not in last)
if orphans or unlisted:
parts = []
if orphans:
parts.append("ledger run(s) DONE without a record and without an invalid listing: " + ", ".join(orphans))
if unlisted:
parts.append("record(s) without a ledger line: " + ", ".join(unlisted))
raise Refusal("; ".join(parts), orphans + unlisted)
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")
arms = list(sched["arms"])
check_manifest(records, last)
by_pair = {}
for rid, line in last.items():
by_pair.setdefault(_pair_number(line), []).append((rid, line))
pairs = []
for number in sorted(by_pair):
recs, fails = {}, {}
for rid, line in by_pair[number]:
arm = line.get("arm")
if arm not in arms:
raise Malformed("ledger run %s: arm %r is not in the schedule arms %s" % (rid, arm, arms))
if rid in records:
recs[arm] = records[rid]
if line["state"] == "INVALID":
fails.setdefault(arm, []).append(line)
for arm in arms:
if arm not in recs and arm not in fails:
raise Malformed("pair %d is incomplete: arm %s has neither a record nor a failed attempt" % (number, arm))
pairs.append(derive_pair(number, recs, fails, machine, sched, arms))
bad = sum(1 for p in pairs if not p["valid"])
return {"pairs": pairs, "manifest_ok": True, "invalid_rate": (float(bad) / len(pairs)) if pairs else 0.0}
# --------------------------------------------------------------------------------------------------------------------------------
# command line
# --------------------------------------------------------------------------------------------------------------------------------
class _Parser(argparse.ArgumentParser):
def error(self, message): # argparse exits 2 by default, which this interface reserves for the manifest refusal
sys.stderr.write("%s: error: %s\n" % (self.prog, message))
raise SystemExit(3)
def _emit(result, out_path):
text = json.dumps(result, indent=2, sort_keys=False) + "\n"
sys.stdout.write(text)
if out_path:
with open(out_path, "w", encoding="utf-8", newline="\n") as fh:
fh.write(text)
def main(argv=None):
parser = _Parser(prog="validity.py", description=__doc__.split("\n")[0])
sub = parser.add_subparsers(dest="command")
sub.required = True
p = sub.add_parser("pairs", help="derive validity of every pair")
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("--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")
s.add_argument("--out", help="also write the JSON result here (run roots outside Git)")
args = parser.parse_args(argv)
try:
if args.command == "schedule":
sched = _load_json(args.check, "schedule")
if not isinstance(sched, dict):
raise Malformed("schedule %s is not a JSON object" % args.check)
_emit({"balanced": schedule_balanced(sched), "hash": schedule_hash(sched)}, args.out)
return 0
sched = _load_json(args.schedule, "schedule")
records = read_records(args.records)
last, _ = read_ledger(args.ledger)
_emit(derive_pairs(records, sched, last, args.machine), args.out)
return 0
except Refusal as exc:
sys.stderr.write("REFUSED (ledger/manifest): %s\n" % exc)
sys.stdout.write(json.dumps({"manifest_ok": False, "run_ids": exc.names}) + "\n")
return 2
except Malformed as exc:
sys.stderr.write("MALFORMED INPUT: %s\n" % exc)
return 3
if __name__ == "__main__":
sys.exit(main())