Files
leleka/scripts/e2e/evidence/validity.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 806774609e 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>
2026-10-28 20:36:31 +01:00

434 lines
21 KiB
Python

#!/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())