Files
leleka/scripts/e2e/evidence/golden/gen_validity.py
T
Pavlo RatushnyiandClaude Sonnet 5.5 c2d68f750d STRA-326: cross-check the declared machine against hardware.machine_role / gpu_name
validity.py trusted --machine alone, so laptop records declared "server" skipped the 100 W
power floor and the owner attestation. derive_pairs now refuses (MACHINE_MISMATCH, exit 3,
run ids named) records whose hardware.machine_role differs from the declared machine and a
"server" declaration over a Laptop GPU. A schedule `machine` key pre-registers the machine;
run_core finalize reads it from there (--machine only a fallback) and refuses a conflicting flag.
The golden fixture builder stamps machine_role = machine; golden cases unchanged (0 differences).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-29 01:01:20 +01:00

959 lines
58 KiB
Python

#!/usr/bin/env python3
"""Golden-vector generator and independent re-checker for the validity module (STRA-311, S0.1t).
Role SDET. Stdlib only, Python >= 3.9 (SC15). Offline, no GPU, no machine telemetry: every number in the cases is synthetic.
What it does
* builds scripts/e2e/evidence/golden/validity_cases.json: inputs (END_TO_END records, ledger lines, schedule files),
the expected verdicts, and for every case a `basis` field that writes the arithmetic out;
* re-checks the stored expected values with an ORACLE written here (derive_pairs, schedule_balanced, order_tables),
which shares no code with validity.py (STRA-312, written later by a different role);
* `materialize()` turns a case input into the files that `validity.py pairs|schedule --check` reads; the test file
scripts/e2e/evidence/test_validity_golden.py imports it so the generator and the tests build identical fixtures.
Thresholds are copied from the item STRA-245 acceptance text (E1, E2) and BA round 2 decisions D5, D7 (comment 3eeb53e1);
none is invented. See THRESHOLDS below.
Usage
gen_validity.py --check exit 0 and 'differences: 0' when the stored file equals the regenerated one and the
stored expected values equal the oracle's
gen_validity.py --list one unique case name per line
gen_validity.py --show NAME the expected verdict, e.g. 'valid=false reason=INFRASTRUCTURE event=RERUN'
gen_validity.py --basis NAME the written-out arithmetic of one case
gen_validity.py --check-basis exit 0 when every case has a non-empty basis
gen_validity.py --check-records every record of every expected-valid pair validates against schema.json (needs validate.py)
gen_validity.py --write (re)write validity_cases.json (templates are kept from the stored file; add --from-samples
to take them again from sample_*.json)
"""
import argparse
import copy
import hashlib
import itertools
import json
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
EVID = os.path.dirname(HERE)
CASES_PATH = os.path.join(HERE, "validity_cases.json")
ARMS = ["ours", "vanilla_default", "vanilla_noskip"]
TWO_ARMS = ["ours", "vanilla_default"]
# Thresholds. Source: STRA-245 acceptanceCriteria E1/E2 and the BA comment 3eeb53e1 (D5, D7). BA decisions, not the owner's numbers.
THRESHOLDS = {
"laptop_power_floor_w": 100.0, # E2(1): any sample below 100 W (floor of scripts/laptop/monitor.sh)
"arm_mean_limit_diff_max_w": 10.0, # E2(1): arms' mean limits differ by MORE than 10 W -> invalid
"arm_spread_max_w": 20.0, # E2(1): spread (max - min) within one arm EXCEEDS 20 W -> invalid
"server_spread_w": 0.0, # E2(1): on the server the limit is unchanged (spread 0 W, equal between the arms)
"context_tokens": 262144, # E2(3), common paragraph: 256k class
"max_prompt_tokens_min": 200000, # E2(3): largest per-turn prompt_tokens >= 200,000
"foreign_load_percent_of_core": 5.0, # SC14 / STRA-312 TL proposal: above 5 percent of a core ...
"foreign_load_duration_s": 2.0, # ... for 2 s
"vanilla_rerun_cap": 2, # E2(5): a vanilla crash is re-run twice at most; the third failure goes to the owner
"n_pairs": 30, # E1
"group_size": 6, # D5: 3 arms -> all 6 permutations per group
}
INFRA_CAUSES = ["POWER", "WORKLOAD", "CACHE", "LOCK", "WATCHDOG", "TELEMETRY"] # E2(5): attributable to (1)-(4), lock, watchdog, telemetry
EVENT_RANK = {"RERUN": 1, "OWNER": 2, "FAIL": 3}
FIXTURE_FORMAT = [
"These cases fix a FIXTURE FORMAT for validity.py (STRA-312) because the schedule and ledger files are produced by STRA-316/STRA-257, which do not exist yet. A field name here wins over a guess; if STRA-316 renames a field it amends this file through an SDET-reviewed change.",
"records dir: one END_TO_END record (STRA-246 schema v1) per file, named <run_id>.json; run_id = <pair_id>.<arm> (pair_id = 'pair-NNNN', NNNN = block number, zero padded 4 digits). arm_identity.block is the pair number.",
"ledger (JSONL, one JSON object per line, append-only; the LAST line of a run_id is its state): keys run_id, state (QUEUED|STARTED|DONE|INVALID|INTERRUPTED), pair_id, block, arm, schedule_sha256, utc, pid, boot_time. An INVALID line of a failed attempt adds outcome (CRASH|TIMEOUT|INTEGRITY_FAILURE) and attributed_to (null | POWER|WORKLOAD|CACHE|LOCK|WATCHDOG|TELEMETRY). Failed attempts of one arm slot have run_id <pair_id>.<arm>.a<k> (k = 1, 2, ...). The ledger is also the manifest (E8): every run_id whose last state is DONE must have a record, every record must have a ledger line, an INVALID line is an invalid listing and needs no record.",
"schedule.json: {seed, arms, n_pairs, blocks: [{block, order: [arm, ...]}], context_tokens, cache_residency_band: {min, max}, interim_looks, foreign_load_threshold: {cpu_percent_of_core, duration_s}}. The schedule hash is computed by validity.py; the fixtures write sha256 of the compact sorted-key JSON into the records, validity.py must not depend on that value.",
"pairs output: JSON {pairs: [{pair, valid, reasons, event}], manifest_ok, invalid_rate}; pairs are matched by number, reasons compared as sets; invalid_rate = (pairs with valid=false) / (pairs listed). Exit 0 result produced, 2 ledger/manifest refusal (the offending run_id appears in stdout or stderr), 3 malformed input.",
"event: null for a pair that is invalid by measurement (POWER, WORKLOAD, CACHE, FOREIGN_LOAD, COUNTABLE_MISMATCH); RERUN for an attributable infrastructure failure (reason INFRASTRUCTURE), for the build-id mismatch (reason INFRASTRUCTURE) and for a vanilla crash/timeout not attributable (first and second failure of the slot, reasons empty); OWNER for a missing attestation (reason ATTESTATION_MISSING) and for the third vanilla failure of a slot (reasons empty); FAIL for an ours crash/timeout/integrity failure not attributable (reasons empty, the series stops FAILED). valid=true needs no reason and no event. Precedence if several apply: FAIL > OWNER > RERUN.",
"countable: every fixture record types countable = the pair's expected validity (a countable pair has all arms valid), except in the two COUNTABLE_MISMATCH cases; validity.py derives the value and reports COUNTABLE_MISMATCH (pair valid=false) when a typed value disagrees.",
"power: summaries are in power_sample_summary (min_w, max_w, mean_w, power_max_limit_w); start/end enforced limits are min_w/max_w, power_limit_changed = (start != end); a changed limit is NOT by itself a reason. Floor 100 W applies on the laptop; the maximum-limit check applies on both machines; on the server every arm has spread 0 W and all arms have the same limit.",
"series_eval order tables (kind order_tables, optional until STRA-290 exists): series_eval.py output gains the key order_tables = {by_position: {metric: {arm: {'1'|'2'|'3': mean ln(value)}}}, by_predecessor: {metric: {arm: {predecessor arm | 'none': mean ln(value)}}}} (mean of the natural log of the arm's own metric value grouped by the arm's position / predecessor; this extends INTERFACE v1 of STRA-290).",
]
# ------------------------------------------------------------------------------------------------------------------ helpers
def sha(text):
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def canonical(obj):
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
def set_path(obj, dotted, value):
parts = dotted.split(".")
cur = obj
for part in parts[:-1]:
cur = cur[int(part)] if isinstance(cur, list) else cur[part]
last = parts[-1]
if isinstance(cur, list):
cur[int(last)] = value
else:
cur[last] = value
def unset_path(obj, dotted):
parts = dotted.split(".")
cur = obj
for part in parts[:-1]:
cur = cur[int(part)] if isinstance(cur, list) else cur[part]
del cur[parts[-1]]
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 pair_id(n):
return "pair-%04d" % n
def run_id(n, arm):
return "%s.%s" % (pair_id(n), arm)
def render(obj, ind=0, width=108):
"""Readable JSON: short containers on one line (from depth 3), long ones expanded. Deterministic."""
pad = " " * ind
if isinstance(obj, dict):
if not obj:
return "{}"
flat = json.dumps(obj, ensure_ascii=True)
if ind >= 3 and len(flat) + len(pad) <= width:
return flat
items = [pad + " " + json.dumps(k) + ": " + render(v, ind + 1, width) for k, v in obj.items()]
return "{\n" + ",\n".join(items) + "\n" + pad + "}"
if isinstance(obj, list):
if not obj:
return "[]"
flat = json.dumps(obj, ensure_ascii=True)
if len(flat) + len(pad) <= width:
return flat
items = [pad + " " + render(v, ind + 1, width) for v in obj]
return "[\n" + ",\n".join(items) + "\n" + pad + "]"
return json.dumps(obj, ensure_ascii=True)
# ------------------------------------------------------------------------------------------------------------------ schedules
def lcg_stream(seed):
state = seed % (1 << 64)
while True:
state = (state * 6364136223846793005 + 1442695040888963407) % (1 << 64)
yield state >> 33
def seeded_groups(seed, n_groups, arms=ARMS):
"""n_groups groups, each holding all permutations of the arms once, in an order drawn with an LCG Fisher-Yates (portable)."""
stream = lcg_stream(seed)
perms = [list(p) for p in itertools.permutations(arms)]
blocks = []
for _ in range(n_groups):
group = list(perms)
for i in range(len(group) - 1, 0, -1):
j = next(stream) % (i + 1)
group[i], group[j] = group[j], group[i]
blocks.extend(group)
return blocks
def make_schedule(blocks, arms=ARMS, seed=311, n_pairs=None, looks=None):
n = len(blocks) if n_pairs is None else n_pairs
return {
"seed": seed,
"arms": list(arms),
"n_pairs": n,
"blocks": [{"block": i + 1, "order": list(order)} for i, order in enumerate(blocks)],
"context_tokens": THRESHOLDS["context_tokens"],
"cache_residency_band": {"min": 0.90, "max": 1.00},
"interim_looks": [12, 24] if n == 30 else [],
"foreign_load_threshold": {"cpu_percent_of_core": THRESHOLDS["foreign_load_percent_of_core"],
"duration_s": THRESHOLDS["foreign_load_duration_s"]},
}
def serialise_schedule(sched, variant):
"""Bytes of a schedule file for a variant {indent, reverse_keys}; the test writes these, the oracle hashes their parse."""
def rev(o):
if isinstance(o, dict):
return dict((k, rev(o[k])) for k in reversed(list(o)))
if isinstance(o, list):
return [rev(x) for x in o]
return o
obj = rev(sched) if variant.get("reverse_keys") else sched
return json.dumps(obj, indent=variant.get("indent"), ensure_ascii=True)
def alternating(n, arms=TWO_ARMS):
return [list(arms) if i % 2 == 0 else list(reversed(arms)) for i in range(n)]
def schedule_balanced(sched):
"""ORACLE for `validity.py schedule --check` (E1, D5). Independent of validity.py."""
arms = sched.get("arms")
blocks = [b["order"] for b in sched.get("blocks", [])]
if not isinstance(arms, list) or sorted(b["block"] for b in sched["blocks"]) != list(range(1, len(blocks) + 1)):
return False
if len(blocks) != sched.get("n_pairs"):
return False
if any(sorted(order) != sorted(arms) for order in blocks):
return False
if len(arms) == 3:
if len(blocks) == 0 or len(blocks) % 6 != 0:
return False
all_perms = sorted(list(p) for p in itertools.permutations(arms))
for g in range(len(blocks) // 6):
if sorted(blocks[g * 6:(g + 1) * 6]) != all_perms:
return False
return True
if len(arms) == 2:
if len(blocks) == 0 or len(blocks) % 2 != 0:
return False
return all(order == (list(arms) if i % 2 == 0 else list(reversed(arms))) for i, order in enumerate(blocks))
return False
def schedule_counts(sched):
"""Counts used by the basis text: per-position counts and follow counts over all blocks."""
arms = sched["arms"]
pos = {a: [0] * len(arms) for a in arms}
follow = {a: {b: 0 for b in arms if b != a} for a in arms}
for blk in sched["blocks"]:
order = blk["order"]
for k, a in enumerate(order):
pos[a][k] += 1
if k > 0:
follow[a][order[k - 1]] += 1
return pos, follow
# ------------------------------------------------------------------------------------------------------------------ materialize
def machine_defaults(machine):
if machine == "server":
return {"min": 575.0, "max": 575.0, "mean": 575.0, "limit": 600.0}
return None # laptop: keep the template summary (118.0 / 126.5 / 122.0, max limit 150.0)
def power_set(mn, mx, mean, lim):
return {
"power_sample_summary.min_w": mn,
"power_sample_summary.max_w": mx,
"power_sample_summary.mean_w": mean,
"power_sample_summary.power_max_limit_w": lim,
"power_sample_summary.power_limit_changed": mn != mx,
"hardware.enforced_power_limit_w_start": mn,
"hardware.enforced_power_limit_w_end": mx,
}
def build_record(templates, machine, n, arm, order, sched_hash, spec, valid, reasons):
rec = copy.deepcopy(templates[arm])
pos = order.index(arm) + 1
ident = rec["arm_identity"]
ident["series_id"] = "golden-series"
ident["schedule_sha256"] = sched_hash
ident["block"] = n
ident["position"] = pos
ident["predecessor_arm"] = order[pos - 2] if pos > 1 else "none"
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:
for k, v in power_set(base["min"], base["max"], base["mean"], base["limit"]).items():
set_path(rec, k, v)
for k, v in spec.get("set", {}).items():
set_path(rec, k, v)
for k in spec.get("unset", []):
unset_path(rec, k)
rec["countable"] = spec["countable"] if "countable" in spec else bool(valid)
rec["invalid_reasons"] = sorted(reasons) if not valid else []
return rec
def ledger_line(n, arm, rid, state, sched_hash, **extra):
line = {"run_id": rid, "state": state, "pair_id": pair_id(n), "block": n, "arm": arm, "schedule_sha256": sched_hash,
"utc": "2026-01-01T00:00:00Z", "pid": 4242, "boot_time": "2026-01-01T00:00:00Z"}
line.update(extra)
return line
def materialize(case_input, templates, schedules, expected_pairs=None):
"""Turn a case input (kind pairs) into the in-memory files validity.py reads.
Returns {"records": {file name: record or raw text}, "schedule": dict or raw text, "ledger": [line, ...]}."""
machine = case_input["machine"]
sched = copy.deepcopy(schedules[case_input["schedule"]])
sched_hash = sha(canonical(sched))
expected_pairs = expected_pairs or {}
records, ledger = {}, []
for pair in case_input["pairs"]:
n = pair["pair"]
order = sched["blocks"][n - 1]["order"]
exp = expected_pairs.get(n, {"valid": True, "reasons": [], "event": None})
typed_reasons = [r for r in exp["reasons"] if r != "COUNTABLE_MISMATCH"]
base_valid = (not typed_reasons) and exp.get("event") is None # the value validity.py derives (before COUNTABLE_MISMATCH)
for arm in ARMS:
spec = pair.get("arms", {}).get(arm, {})
rid = run_id(n, arm)
for k, attempt in enumerate(spec.get("attempts", []), 1):
arid = "%s.a%d" % (rid, k)
ledger.append(ledger_line(n, arm, arid, "QUEUED", sched_hash))
ledger.append(ledger_line(n, arm, arid, "STARTED", sched_hash))
ledger.append(ledger_line(n, arm, arid, "INVALID", sched_hash, outcome=attempt["outcome"], attributed_to=attempt["attributed_to"]))
if spec.get("record", True):
records[rid + ".json"] = build_record(templates, machine, n, arm, order, sched_hash, spec, base_valid, typed_reasons)
ledger.append(ledger_line(n, arm, rid, "QUEUED", sched_hash))
ledger.append(ledger_line(n, arm, rid, "STARTED", sched_hash))
ledger.append(ledger_line(n, arm, rid, "DONE", sched_hash))
for extra in case_input.get("ledger_extra", []):
ledger.append(ledger_line(extra["pair"], extra["arm"], run_id(extra["pair"], extra["arm"]), extra["state"], sched_hash))
drop = set(case_input.get("drop_ledger", []))
ledger = [line for line in ledger if line["run_id"] not in drop]
for fname, text in case_input.get("raw_records", {}).items():
records[fname] = text
return {"records": records, "schedule": sched, "ledger": ledger}
# ------------------------------------------------------------------------------------------------------------------ oracle
def derive_pairs(case_input, mat, machine):
"""ORACLE for `validity.py pairs` (E2). Returns the expected result dict. Independent of validity.py."""
if any(isinstance(v, str) for v in mat["records"].values()):
return {"exit": 3}
sched = mat["schedule"]
band = sched["cache_residency_band"]
thr = sched["foreign_load_threshold"]
last = {}
for line in mat["ledger"]:
last[line["run_id"]] = line
rec_ids = {name[:-5]: rec for name, rec in mat["records"].items()}
for rid, line in sorted(last.items()):
if line["state"] == "DONE" and rid not in rec_ids:
return {"exit": 2, "names": [rid]}
for rid in sorted(rec_ids):
if rid not in last:
return {"exit": 2, "names": [rid]}
numbers = sorted(set(l["block"] for l in last.values()))
out = []
for n in numbers:
recs = {a: rec_ids[run_id(n, a)] for a in ARMS if run_id(n, a) in rec_ids}
reasons, events = set(), []
# (1) POWER
sums = {a: r["power_sample_summary"] for a, r in recs.items()}
for a, s in sums.items():
if machine == "laptop" and s["min_w"] < THRESHOLDS["laptop_power_floor_w"]:
reasons.add("POWER")
if s["max_w"] > s["power_max_limit_w"]:
reasons.add("POWER")
limit = THRESHOLDS["arm_spread_max_w"] if machine == "laptop" else THRESHOLDS["server_spread_w"]
if s["max_w"] - s["min_w"] > limit:
reasons.add("POWER")
if sums:
means = [s["mean_w"] for s in sums.values()]
allowed = THRESHOLDS["arm_mean_limit_diff_max_w"] if machine == "laptop" else 0.0
if max(means) - min(means) > allowed:
reasons.add("POWER")
# (2) HOLDS: owner attestation
for r in recs.values():
if not r["hardware"]["owner_attestation"]["present"]:
reasons.add("ATTESTATION_MISSING")
events.append("OWNER")
# (3) WORKLOAD
turns = [r["metrics"]["turns"] for r in recs.values()]
for t in range(5):
if len(set(tt[t]["prompt_sha256"] for tt in turns)) > 1:
reasons.add("WORKLOAD")
for r in recs.values():
if r["configuration"]["context_tokens"] != THRESHOLDS["context_tokens"]:
reasons.add("WORKLOAD")
if max(t["prompt_tokens"] for t in r["metrics"]["turns"]) < THRESHOLDS["max_prompt_tokens_min"]:
reasons.add("WORKLOAD")
for path in ("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"):
if get_path(r, path) is None:
reasons.add("WORKLOAD")
# (4) CACHE
for r in recs.values():
v = r["cache"]["page_cache_residency_before"]["value"]
if v < band["min"] or v > band["max"]:
reasons.add("CACHE")
# BUILD IDENTITY
if "ours" in recs and recs["ours"]["ours_build_id_observed"] != recs["ours"]["ours_build_id_frozen"]:
reasons.add("INFRASTRUCTURE")
events.append("RERUN")
# SC14 foreign load
for r in recs.values():
for s in r["hardware"]["foreign_load"]["samples"]:
if s["cpu_percent_of_core"] > thr["cpu_percent_of_core"] and s["duration_s"] >= thr["duration_s"]:
reasons.add("FOREIGN_LOAD")
# (5) crashes from the ledger
for arm in ARMS:
fails = [l for rid, l in last.items() if l["block"] == n and l["arm"] == arm and l["state"] == "INVALID"]
for l in fails:
if l["attributed_to"] in INFRA_CAUSES:
reasons.add("INFRASTRUCTURE")
events.append("RERUN")
elif arm == "ours":
events.append("FAIL")
else:
events.append("OWNER" if len(fails) > THRESHOLDS["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():
if r["countable"] != derived:
reasons.add("COUNTABLE_MISMATCH")
valid = (not reasons) and event is None
out.append({"pair": n, "valid": valid, "reasons": sorted(reasons), "event": event})
bad = sum(1 for p in out if not p["valid"])
return {"exit": 0, "pairs": out, "manifest_ok": True, "invalid_rate": (float(bad) / len(out)) if out else 0.0}
def order_tables(series):
"""ORACLE for the order tables: mean ln(value) in units of ln 2 as exact Fractions, by arm position and by predecessor."""
from fractions import Fraction
by_pos, by_pred = {}, {}
for p in series["pairs"]:
for arm, vals in p["arms"].items():
k = Fraction(vals["exp2"])
by_pos.setdefault(arm, {}).setdefault(str(p["position"][arm]), []).append(k)
by_pred.setdefault(arm, {}).setdefault(p["predecessor"][arm] or "none", []).append(k)
mean = lambda xs: sum(xs, Fraction(0)) / len(xs)
return ({a: {k: str(mean(v)) for k, v in d.items()} for a, d in by_pos.items()},
{a: {k: str(mean(v)) for k, v in d.items()} for a, d in by_pred.items()})
# ------------------------------------------------------------------------------------------------------------------ cases
def A(outcome, attributed_to=None):
return {"outcome": outcome, "attributed_to": attributed_to}
def X(valid, reasons=(), event=None):
return {"valid": valid, "reasons": sorted(reasons), "event": event}
def pairs_expected(*items):
"""items: (pair number, X(...)). Computes manifest_ok and invalid_rate the way the fixture format defines them."""
pl = [{"pair": n, "valid": x["valid"], "reasons": x["reasons"], "event": x["event"]} for n, x in items]
bad = sum(1 for p in pl if not p["valid"])
return {"exit": 0, "pairs": pl, "manifest_ok": True, "invalid_rate": float(bad) / len(pl)}
def case(name, klass, kind, basis, inp, expected):
return {"name": name, "class": klass, "kind": kind, "basis": basis, "input": inp, "expected": expected}
def one_pair(machine, arms, **extra):
inp = {"machine": machine, "schedule": "pairs_n6", "pairs": [{"pair": 1, "arms": arms}]}
inp.update(extra)
return inp
def pw(mn, mx, mean, lim=150.0):
return {"set": power_set(mn, mx, mean, lim)}
SWAP_BLOCKS = [6, 7]
def build_schedules():
s30 = make_schedule(seeded_groups(311, 5))
scheds = {"pairs_n6": make_schedule(seeded_groups(7, 1), seed=7)}
scheds["n30_balanced"] = s30
blocks29 = [b["order"] for b in s30["blocks"]][:29]
scheds["n29"] = make_schedule(blocks29)
blocks = [b["order"] for b in s30["blocks"]]
missing = [list(b) for b in blocks]
# group 3 (blocks 13..18): replace its last permutation by a copy of its first -> one permutation missing, one doubled
missing[17] = list(missing[12])
scheds["n30_group_missing_permutation"] = make_schedule(missing)
swapped = [list(b) for b in blocks]
j = next(i for i in range(6, 12) if blocks[i] != blocks[5]) # first block of group 2 that differs from block 6
swapped[5], swapped[j] = swapped[j], swapped[5] # traded between group 1 and group 2: globally balanced, per group not
SWAP_BLOCKS[:] = [6, j + 1]
scheds["n30_groups_broken"] = make_schedule(swapped)
scheds["n36_balanced"] = make_schedule(seeded_groups(311, 6))
scheds["two_arms_alternating"] = make_schedule(alternating(30), arms=TWO_ARMS)
scheds["two_arms_blocks_not_alternating"] = make_schedule([list(TWO_ARMS)] * 15 + [list(reversed(TWO_ARMS))] * 15, arms=TWO_ARMS)
# hash cases
changed = copy.deepcopy(s30)
changed["blocks"][0]["order"] = list(reversed(changed["blocks"][0]["order"]))
scheds["n30_first_block_reversed"] = changed
return scheds
def order_series():
"""6 blocks, one group of all permutations; wall_norm = 2^k, k hand-chosen (exponents in units of ln 2)."""
orders = [["ours", "vanilla_default", "vanilla_noskip"], ["ours", "vanilla_noskip", "vanilla_default"],
["vanilla_default", "ours", "vanilla_noskip"], ["vanilla_default", "vanilla_noskip", "ours"],
["vanilla_noskip", "ours", "vanilla_default"], ["vanilla_noskip", "vanilla_default", "ours"]]
k = {"ours": [0, 1, 2, 3, 4, 5], "vanilla_default": [1, 1, 2, 2, 3, 3], "vanilla_noskip": [2, 0, 2, 0, 2, 0]}
pairs = []
for i, order in enumerate(orders):
arms = {}
for a in ARMS:
v = float(2 ** k[a][i])
arms[a] = {"wall_norm": v, "ttft_sum": v, "decode_tps": v, "exp2": k[a][i]}
pairs.append({"pair": i + 1, "valid": True, "reasons": [],
"position": {a: order.index(a) + 1 for a in ARMS},
"predecessor": {a: (order[order.index(a) - 1] if order.index(a) > 0 else None) for a in ARMS},
"arms": arms})
return {"machine": "laptop", "ours_build_id": "golden-build-1", "cache_state": "WARM-OS/EMPTY-ENGINE",
"schedule_hash": "golden-order-tables", "N": 6, "rows_coincide": False, "pairs": pairs}
def build_cases():
S = build_schedules()
cases = []
add = cases.append
# ---- POWER (laptop) ----
add(case("power_sample_below_100w", "POWER", "pairs",
"E2(1) floor 100 W. ours min 99.9 W < 100 -> POWER. Isolated: ours 99.9..112.0 (spread 12.1 <= 20, mean 105.0), the other arms 100.5..112.0 (mean 105.0): mean difference 0.0 <= 10, no sample above the 150.0 W maximum limit.",
one_pair("laptop", {"ours": pw(99.9, 112.0, 105.0), "vanilla_default": pw(100.5, 112.0, 105.0), "vanilla_noskip": pw(100.5, 112.0, 105.0)}),
pairs_expected((1, X(False, ["POWER"])))))
add(case("power_51w_recorded_run", "POWER", "pairs",
"The recorded run of docs/laptop-vs-vanilla.md section 14 (the run with the prefix-checkpoint fix: 'the GPU power limit read 51 W (P3) for the whole run'): ours min = max = mean = 51.0 W. 51.0 < 100 -> POWER (also: mean difference to the 122.0 W arms = 71.0 > 10). The other two arms keep the clean template band 118.0..126.5.",
one_pair("laptop", {"ours": pw(51.0, 51.0, 51.0)}),
pairs_expected((1, X(False, ["POWER"])))))
add(case("power_sample_above_max_limit", "POWER", "pairs",
"E2(1) above the card's max limit. power_max_limit_w = 150.0; ours max sample 150.5 > 150.0 -> POWER. Isolated: ours 140.0..150.5 (spread 10.5 <= 20, mean 145.0), others 140.0..148.0 (mean 144.0): mean difference 1.0 <= 10, all samples >= 100.",
one_pair("laptop", {"ours": pw(140.0, 150.5, 145.0), "vanilla_default": pw(140.0, 148.0, 144.0), "vanilla_noskip": pw(140.0, 148.0, 144.0)}),
pairs_expected((1, X(False, ["POWER"])))))
add(case("power_floor_exactly_100w_valid", "POWER", "pairs",
"The floor is 'below 100 W': a minimum of exactly 100.0 W is valid. ours 100.0..112.0 (spread 12.0, mean 105.0), others 100.5..112.0 (mean 105.0); all <= 150.0; mean difference 0.0.",
one_pair("laptop", {"ours": pw(100.0, 112.0, 105.0), "vanilla_default": pw(100.5, 112.0, 105.0), "vanilla_noskip": pw(100.5, 112.0, 105.0)}),
pairs_expected((1, X(True)))))
for tag, other_mean, valid, arith in (
("10_01w", 128.01, False, "128.01 - 118.0 = 10.01 > 10"),
("9_99w", 127.99, True, "127.99 - 118.0 = 9.99 <= 10"),
("exactly_10w", 128.0, True, "128.0 - 118.0 = 10.0, not MORE than 10")):
add(case("power_means_differ_%s" % tag, "POWER", "pairs",
"E2(1) arms' mean limits. ours and vanilla_noskip 110.0..126.0 mean 118.0; vanilla_default 120.0..130.0 mean %s. %s -> %s. Spreads 16.0 and 10.0 <= 20, samples within 100..150." % (other_mean, arith, "POWER" if not valid else "valid"),
one_pair("laptop", {"ours": pw(110.0, 126.0, 118.0), "vanilla_default": pw(120.0, 130.0, other_mean), "vanilla_noskip": pw(110.0, 126.0, 118.0)}),
pairs_expected((1, X(valid, [] if valid else ["POWER"])))))
add(case("power_spread_20_01w", "POWER", "pairs",
"E2(1) spread within one arm. ours 110.0..130.01: 130.01 - 110.0 = 20.01 > 20 -> POWER. Mean 120.0 vs 122.0 of the others = 2.0 <= 10; samples within 100..150.",
one_pair("laptop", {"ours": pw(110.0, 130.01, 120.0)}),
pairs_expected((1, X(False, ["POWER"])))))
add(case("power_spread_exactly_20w_valid", "POWER", "pairs",
"Spread 'exceeds 20 W': ours 110.0..130.0 = exactly 20.0 is valid. Mean 120.0 vs 122.0 = 2.0 <= 10; samples within 100..150.",
one_pair("laptop", {"ours": pw(110.0, 130.0, 120.0)}),
pairs_expected((1, X(True)))))
add(case("clean_laptop_run", "POWER", "pairs",
"The recorded clean run g2-vanilla-noskip of docs/laptop-vs-vanilla.md section 11: limit 110.0 rising to 126.6 W over the whole run. Spread 126.6 - 110.0 = 16.6 <= 20; floor 110.0 >= 100; max 126.6 <= 150.0; all three arms 110.0..126.6 mean 118.3 so the mean difference is 0.0. The limit changed during the run (start 110.0, end 126.6, power_limit_changed true) and the pair MUST stay valid (SDET remark H, QA-2).",
one_pair("laptop", {a: pw(110.0, 126.6, 118.3) for a in ARMS}),
pairs_expected((1, X(True)))))
# ---- POWER (server) ----
add(case("server_limit_spread_0w_valid", "POWER", "pairs",
"E2(1) server: the enforced limit is the configured value, spread 0 W. All arms 575.0..575.0 mean 575.0, power_max_limit_w 600.0: spread 0.0, means equal, <= max limit.",
one_pair("server", {}),
pairs_expected((1, X(True)))))
add(case("server_limit_spread_1w", "POWER", "pairs",
"E2(1) server: ours 574.0..575.0 (mean 574.5): spread 1.0 != 0 -> POWER; the mean also differs by 0.5 from the other arms.",
one_pair("server", {"ours": pw(574.0, 575.0, 574.5, 600.0)}),
pairs_expected((1, X(False, ["POWER"])))))
add(case("server_limit_differs_between_arms", "POWER", "pairs",
"E2(1) server: 'the limit must be unchanged between the arms'. vanilla_default constant 550.0 (spread 0), the others constant 575.0: mean difference 25.0 != 0 -> POWER. The 10 W tolerance is a laptop rule.",
one_pair("server", {"vanilla_default": pw(550.0, 550.0, 550.0, 600.0)}),
pairs_expected((1, X(False, ["POWER"])))))
# ---- WORKLOAD ----
other = sha("golden-different-prompt")
add(case("prompt_sha256_differs_between_arms", "WORKLOAD", "pairs",
"E2(3)/E7: the prompt sha256 of turn 3 (index 2) of vanilla_noskip is replaced by sha256('golden-different-prompt'); the other two arms keep the template hash -> the three hashes of turn 3 are not equal -> WORKLOAD.",
one_pair("laptop", {"vanilla_noskip": {"set": {"metrics.turns.2.prompt_sha256": other}}}),
pairs_expected((1, X(False, ["WORKLOAD"])))))
for tokens, valid in ((199999, False), (200000, True)):
add(case("max_prompt_tokens_%d" % tokens, "WORKLOAD", "pairs",
"256k class (BA decision, common paragraph): context_tokens 262144 AND largest per-turn prompt_tokens >= 200,000. Turn 5 of every arm set to %d (turns 1-4 are 43000..172500, so the largest is turn 5): %d %s 200000 -> %s." % (tokens, tokens, ">=" if valid else "<", "valid" if valid else "WORKLOAD"),
one_pair("laptop", {a: {"set": {"metrics.turns.4.prompt_tokens": tokens}} for a in ARMS}),
pairs_expected((1, X(valid, [] if valid else ["WORKLOAD"])))))
add(case("context_tokens_131072", "WORKLOAD", "pairs",
"256k class needs context_tokens == 262144. All arms configured with 131072 (charter: half the window) -> WORKLOAD even though the prompts (largest 215000) would pass the token test.",
one_pair("laptop", {a: {"set": {"configuration.context_tokens": 131072}} for a in ARMS}),
pairs_expected((1, X(False, ["WORKLOAD"])))))
add(case("missing_metadata_field", "WORKLOAD", "pairs",
"E2(3): the metadata of the common paragraph is missing. software.driver_version removed from the vanilla_default record -> WORKLOAD (the field list: hardware, driver and CUDA versions, commits, model digest, configuration, cache state, token counts).",
one_pair("laptop", {"vanilla_default": {"unset": ["software.driver_version"]}}),
pairs_expected((1, X(False, ["WORKLOAD"])))))
# ---- CACHE ----
add(case("cache_residency_below_band", "CACHE", "pairs",
"E2(4): the schedule band is 0.90..1.00 of the model file resident. ours page_cache_residency_before = 0.80 < 0.90 -> CACHE; the other arms keep 0.97.",
one_pair("laptop", {"ours": {"set": {"cache.page_cache_residency_before.value": 0.80}}}),
pairs_expected((1, X(False, ["CACHE"])))))
add(case("cache_residency_inside_band", "CACHE", "pairs",
"E2(4): ours 0.91 and vanilla_noskip 0.99 are inside 0.90..1.00 (0.90 <= 0.91, 0.99 <= 1.00) -> valid.",
one_pair("laptop", {"ours": {"set": {"cache.page_cache_residency_before.value": 0.91}}, "vanilla_noskip": {"set": {"cache.page_cache_residency_before.value": 0.99}}}),
pairs_expected((1, X(True)))))
# ---- INFRASTRUCTURE (attributable crash) ----
for cause in ("POWER", "CACHE", "LOCK", "WATCHDOG", "TELEMETRY"):
add(case("infra_crash_attributed_to_%s" % cause.lower(), "INFRASTRUCTURE", "pairs",
"E2(5): the vanilla_default run crashed and the ledger attributes it to %s (one of power/cache/lock/watchdog/telemetry) -> pair invalid, reason INFRASTRUCTURE, event RERUN. The other two arms have clean records." % cause,
one_pair("laptop", {"vanilla_default": {"record": False, "attempts": [A("CRASH", cause)]}}),
pairs_expected((1, X(False, ["INFRASTRUCTURE"], "RERUN")))))
add(case("infra_ours_crash_attributed_to_watchdog", "INFRASTRUCTURE", "pairs",
"E2(5): an OURS crash attributable to the watchdog is infrastructure, not a FAIL event: invalid, INFRASTRUCTURE, RERUN.",
one_pair("laptop", {"ours": {"record": False, "attempts": [A("CRASH", "WATCHDOG")]}}),
pairs_expected((1, X(False, ["INFRASTRUCTURE"], "RERUN")))))
# ---- BUILD IDENTITY ----
other_commit = "fedcba9876543210fedcba9876543210fedcba98"
add(case("build_id_mismatch", "BUILD_IDENTITY", "pairs",
"E1b/E2(5): ours_build_id_observed.commit = %s differs from ours_build_id_frozen.commit = 0123456789abcdef0123456789abcdef01234567 -> invalid, reason INFRASTRUCTURE, event RERUN." % other_commit,
one_pair("laptop", {"ours": {"set": {"ours_build_id_observed.commit": other_commit}}}),
pairs_expected((1, X(False, ["INFRASTRUCTURE"], "RERUN")))))
add(case("build_id_mismatch_cargo_features", "BUILD_IDENTITY", "pairs",
"E1b: the build id is commit + target triple + cargo features + profile hash. Observed cargo_features ['cuda'] differs from frozen ['cuda','native-cpu-expert'] -> INFRASTRUCTURE, RERUN.",
one_pair("laptop", {"ours": {"set": {"ours_build_id_observed.cargo_features": ["cuda"]}}}),
pairs_expected((1, X(False, ["INFRASTRUCTURE"], "RERUN")))))
add(case("build_id_equal_valid", "BUILD_IDENTITY", "pairs",
"Observed and frozen ids both set to commit %s (all other fields equal): identical -> no build-identity finding, valid." % other_commit,
one_pair("laptop", {"ours": {"set": {"ours_build_id_observed.commit": other_commit, "ours_build_id_frozen.commit": other_commit}}}),
pairs_expected((1, X(True)))))
# ---- FAIL event (ours, not attributable) ----
for outcome in ("CRASH", "TIMEOUT", "INTEGRITY_FAILURE"):
add(case("fail_event_ours_%s_unattributed" % outcome.lower(), "FAIL_EVENT", "pairs",
"E2(5): an ours %s that is not attributable to (1)-(5) is NOT a re-run: event FAIL, the series stops FAILED. The pair is not valid; no E2 reason code applies, so reasons is empty." % outcome,
one_pair("laptop", {"ours": {"record": False, "attempts": [A(outcome)]}}),
pairs_expected((1, X(False, [], "FAIL")))))
# ---- vanilla re-run cap ----
add(case("vanilla_crash_unattributed_first", "VANILLA_RERUN_CAP", "pairs",
"E2(5): a vanilla crash not attributable is re-run at most twice. One failed attempt (a1) of the vanilla_default slot -> event RERUN, reasons empty.",
one_pair("laptop", {"vanilla_default": {"record": False, "attempts": [A("CRASH")]}}),
pairs_expected((1, X(False, [], "RERUN")))))
add(case("vanilla_crash_unattributed_second", "VANILLA_RERUN_CAP", "pairs",
"Two failed attempts (a1, a2) of the slot: the second re-run is still allowed (2 <= cap 2) -> RERUN.",
one_pair("laptop", {"vanilla_default": {"record": False, "attempts": [A("CRASH"), A("CRASH")]}}),
pairs_expected((1, X(False, [], "RERUN")))))
add(case("vanilla_crash_unattributed_third_owner", "VANILLA_RERUN_CAP", "pairs",
"Three failed attempts (a1, a2, a3): 3 > cap 2 -> the series stops and the third failure is reported to the owner: event OWNER, reasons empty.",
one_pair("laptop", {"vanilla_default": {"record": False, "attempts": [A("CRASH"), A("TIMEOUT"), A("CRASH")]}}),
pairs_expected((1, X(False, [], "OWNER")))))
add(case("vanilla_timeout_unattributed_first", "VANILLA_RERUN_CAP", "pairs",
"A vanilla TIMEOUT counts like a crash: one failed attempt of vanilla_noskip -> RERUN.",
one_pair("laptop", {"vanilla_noskip": {"record": False, "attempts": [A("TIMEOUT")]}}),
pairs_expected((1, X(False, [], "RERUN")))))
# ---- ledger / manifest cross-check (E8) ----
add(case("ledger_orphan_run_id", "LEDGER", "pairs",
"E8: the ledger has run pair-0002.vanilla_noskip with last state DONE, but there is no record and no INVALID listing -> the series is refused (no pair may be dropped silently): exit 2, the run id is named. Pair 1 is clean.",
{"machine": "server", "schedule": "pairs_n6", "pairs": [{"pair": 1, "arms": {}}],
"ledger_extra": [{"pair": 2, "arm": "vanilla_noskip", "state": "QUEUED"}, {"pair": 2, "arm": "vanilla_noskip", "state": "STARTED"}, {"pair": 2, "arm": "vanilla_noskip", "state": "DONE"}]},
{"exit": 2, "names": ["pair-0002.vanilla_noskip"]}))
add(case("ledger_record_not_in_manifest", "LEDGER", "pairs",
"E8: the record pair-0001.vanilla_noskip.json exists but the ledger (the manifest) has no line for its run id -> exit 2, the run id is named.",
{"machine": "server", "schedule": "pairs_n6", "pairs": [{"pair": 1, "arms": {}}], "drop_ledger": ["pair-0001.vanilla_noskip"]},
{"exit": 2, "names": ["pair-0001.vanilla_noskip"]}))
add(case("ledger_invalid_listing_is_not_an_orphan", "LEDGER", "pairs",
"A run with no record whose last ledger state is INVALID is an invalid listing, not an orphan: exit 0, manifest_ok true. Pair 1 clean (valid); pair 2: the vanilla_noskip attempt crashed, attributed to LOCK -> INFRASTRUCTURE/RERUN. invalid_rate = 1 invalid pair / 2 pairs = 0.5.",
{"machine": "laptop", "schedule": "pairs_n6", "pairs": [{"pair": 1, "arms": {}}, {"pair": 2, "arms": {"vanilla_noskip": {"record": False, "attempts": [A("CRASH", "LOCK")]}}}]},
pairs_expected((1, X(True)), (2, X(False, ["INFRASTRUCTURE"], "RERUN")))))
# ---- typed countable ----
add(case("countable_typed_true_derived_false", "COUNTABLE", "pairs",
"`countable` is derived, never typed: the ours record types countable=true while its power sample (99.9 W < 100) makes the pair invalid (derived false). The disagreement adds COUNTABLE_MISMATCH next to POWER; the pair is rejected. The other arms type false (their own derived value).",
one_pair("laptop", {"ours": {"set": power_set(99.9, 112.0, 105.0, 150.0), "countable": True}, "vanilla_default": pw(100.5, 112.0, 105.0), "vanilla_noskip": pw(100.5, 112.0, 105.0)}),
pairs_expected((1, X(False, ["COUNTABLE_MISMATCH", "POWER"])))))
add(case("countable_typed_false_derived_true", "COUNTABLE", "pairs",
"A clean pair (derived countable true) whose ours record types countable=false: any disagreement between typed and derived value is COUNTABLE_MISMATCH -> rejected, valid=false.",
one_pair("laptop", {"ours": {"countable": False}}),
pairs_expected((1, X(False, ["COUNTABLE_MISMATCH"])))))
# ---- owner attestation ----
absent = {"present": False, "identifier": None, "time_utc": None}
add(case("attestation_missing", "ATTESTATION", "pairs",
"E2(2): the owner's session-start attestation (Turbo, unlocked screen) is absent in the ours record (present false, identifier and time null per RULE_ATTESTATION) -> invalid, reason ATTESTATION_MISSING, event OWNER. It is checked present, not measured.",
one_pair("laptop", {"ours": {"set": {"hardware.owner_attestation": absent}}}),
pairs_expected((1, X(False, ["ATTESTATION_MISSING"], "OWNER")))))
add(case("attestation_present", "ATTESTATION", "pairs",
"Every record carries a present attestation (identifier golden-attestation-1, time 2026-01-01T00:00:00Z) -> no attestation finding, valid.",
one_pair("laptop", {}),
pairs_expected((1, X(True)))))
# ---- foreign load (SC14): threshold in the schedule = 5 percent of a core for 2 s ----
def fl(pct, dur):
return {"set": {"hardware.foreign_load.samples": [{"process_name": "golden-indexer", "cpu_percent_of_core": pct, "duration_s": dur}]}}
add(case("foreign_load_6pct", "FOREIGN_LOAD", "pairs",
"SC14: a non-harness process at 6.0 percent of a core for 3.0 s in vanilla_default: 6.0 > 5.0 and 3.0 >= 2.0 -> invalid, reason FOREIGN_LOAD.",
one_pair("laptop", {"vanilla_default": fl(6.0, 3.0)}),
pairs_expected((1, X(False, ["FOREIGN_LOAD"])))))
add(case("foreign_load_4pct", "FOREIGN_LOAD", "pairs",
"SC14: 4.0 percent of a core for 3.0 s: 4.0 <= 5.0 -> not flagged, valid.",
one_pair("laptop", {"vanilla_default": fl(4.0, 3.0)}),
pairs_expected((1, X(True)))))
add(case("foreign_load_6pct_1s", "FOREIGN_LOAD", "pairs",
"SC14: 6.0 percent but only 1.0 s: 1.0 < 2.0 s -> below the duration threshold, not flagged, valid.",
one_pair("laptop", {"vanilla_default": fl(6.0, 1.0)}),
pairs_expected((1, X(True)))))
# ---- malformed input (exit 3) ----
add(case("record_malformed_json", "MALFORMED", "pairs",
"Interface: exit 3 = malformed input. The record file pair-0001.ours.json contains '{not json' -> exit 3.",
{"machine": "laptop", "schedule": "pairs_n6", "pairs": [{"pair": 1, "arms": {"ours": {"record": False}}}], "raw_records": {"pair-0001.ours.json": "{not json"}},
{"exit": 3}))
# ---- schedule (E1, D5) ----
def sched_case(name, key, balanced, basis, klass="SCHEDULE"):
add(case(name, klass, "schedule", basis, {"schedule": key}, {"exit": 0, "balanced": balanced}))
s30 = S["n30_balanced"]
pos, follow = schedule_counts(s30)
assert all(c == 10 for v in pos.values() for c in v) and all(c == 10 for v in follow.values() for c in v.values())
sched_case("schedule_n30_three_arms_balanced", "n30_balanced", True,
"E1/D5: N = 30, 3 arms -> 30/6 = 5 groups, each of the 6 permutations of (ours, vanilla_default, vanilla_noskip) exactly once, group and in-group order drawn with a seeded stream (seed 311). Counts re-derived: each arm appears 5 groups x 2 permutations = 10 times in each of positions 1, 2, 3, and follows each other arm 5 x 2 = 10 times.")
sched_case("schedule_n29_rejected", "n29", False,
"E1: N = 29 (the first 29 blocks of the N = 30 schedule): 29 is not a multiple of 6, the last group is incomplete (5 of 6 permutations) -> balanced false, exit 0.")
sched_case("schedule_group_missing_permutation", "n30_group_missing_permutation", False,
"N = 30 but group 3 (blocks 13-18) has its last permutation replaced by a copy of its first: one permutation is missing and one appears twice -> balanced false.")
sched_case("schedule_balanced_overall_groups_broken", "n30_groups_broken", False,
"Blocks %d and %d are traded between group 1 and group 2: the multiset of all 30 orders is unchanged (each permutation 5 times, overall position counts still 10) but group 1 now misses a permutation and group 2 doubles one -> the rule is per group of 6 -> balanced false." % tuple(SWAP_BLOCKS))
sched_case("schedule_n36_six_groups_balanced", "n36_balanced", True,
"D2/E1: N is raised in multiples of 6 when the spread says 30 pairs cannot resolve 1 percent: N = 36 = 6 groups of all 6 permutations (same seed stream) -> balanced true.")
sched_case("schedule_two_arms_alternate_ab_ba", "two_arms_alternating", True,
"D5: two arms (rows coincide, A/A cells) alternate AB, BA: blocks 1,3,5,... = [ours, vanilla_default], blocks 2,4,6,... = reversed; N = 30 -> 15 AB + 15 BA, each arm 15 times first -> balanced true.")
sched_case("schedule_two_arms_not_alternating", "two_arms_blocks_not_alternating", False,
"Two arms with 15 x AB followed by 15 x BA: the totals are balanced (15 first each) but the blocks do not alternate AB, BA -> balanced false.")
add(case("schedule_hash_stable_under_reserialisation", "SCHEDULE", "schedule_hash",
"The schedule hash is a function of the content, not of the bytes: the N = 30 schedule written compact with its keys in file order, and written with indent 4 and the keys of every object in reverse order, gives the same hash; the same schedule with block 1 reversed gives a different hash. The test asserts equality / inequality and a 64-hex string, not a particular value.",
{"schedule": "n30_balanced", "variants": [{"indent": None, "reverse_keys": False}, {"indent": 4, "reverse_keys": True}], "other": "n30_first_block_reversed"},
{"exit": 0, "same_across_variants": True, "differs_from_other": True}))
add(case("schedule_malformed_json", "MALFORMED", "schedule_raw",
"Interface: exit 3 = malformed input. The schedule file contains 'not json{' -> `schedule --check` exits 3.",
{"raw": "not json{"},
{"exit": 3}))
# ---- evaluator order tables (E1: mean by position and by predecessor), optional until STRA-290 exists ----
series = order_series()
by_pos, by_pred = order_tables(series)
add(case("order_tables_hand_computed", "ORDER_TABLES", "order_tables",
"E1: the evaluator prints the mean by arm position and by predecessor. One group of the 6 permutations; wall_norm = 2^k with k (blocks 1-6): ours 0,1,2,3,4,5; vanilla_default 1,1,2,2,3,3; vanilla_noskip 2,0,2,0,2,0. ours is at position 1 in blocks 1,2 (k 0,1: mean 1/2), position 2 in blocks 3,5 (k 2,4: 3), position 3 in blocks 4,6 (k 3,5: 4); its predecessor is none in blocks 1,2, vanilla_default in blocks 3,6 (k 2,5: 7/2), vanilla_noskip in blocks 4,5 (k 3,4: 7/2). Means of ln(value) are these exponents times ln 2. The remaining rows are the same arithmetic (see the stored tables).",
{"series": series},
{"unit": "ln2", "by_position": by_pos, "by_predecessor": by_pred}))
return cases, S
# ------------------------------------------------------------------------------------------------------------------ document
def load_templates(from_samples):
if not from_samples and os.path.exists(CASES_PATH):
with open(CASES_PATH, "r", encoding="utf-8") as fh:
return json.load(fh)["templates"]
out = {}
for arm, fname in (("ours", "sample_ours.json"), ("vanilla_default", "sample_vanilla_default.json"), ("vanilla_noskip", "sample_vanilla_noskip.json")):
with open(os.path.join(EVID, fname), "r", encoding="utf-8") as fh:
out[arm] = json.load(fh)
return out
def build_document(templates):
cases, schedules = build_cases()
return {
"format_version": 1,
"leaf": "STRA-311",
"role": "SDET",
"note": "Synthetic fixtures only (no machine telemetry). Generated by golden/gen_validity.py; do not edit by hand. The oracle that re-checks every expected value lives in gen_validity.py and shares no code with validity.py (STRA-312).",
"interface": "validity.py INTERFACE v1 (STRA-312): pairs --records --schedule --ledger --machine laptop|server ; schedule --check <file>",
"fixture_format": FIXTURE_FORMAT,
"thresholds": THRESHOLDS,
"templates": templates,
"schedules": schedules,
"cases": cases,
}
def dump_document(doc):
return render(doc) + "\n"
def case_expected_pairs(c):
return {p["pair"]: p for p in c["expected"].get("pairs", [])}
def recompute(c, doc):
"""Oracle result for one case in the shape of c['expected']."""
kind = c["kind"]
if kind == "pairs":
mat = materialize(c["input"], doc["templates"], doc["schedules"], case_expected_pairs(c))
return derive_pairs(c["input"], mat, c["input"]["machine"])
if kind == "schedule":
return {"exit": 0, "balanced": schedule_balanced(doc["schedules"][c["input"]["schedule"]])}
if kind == "schedule_raw":
try:
json.loads(c["input"]["raw"])
return {"exit": 0}
except ValueError:
return {"exit": 3}
if kind == "schedule_hash":
base = doc["schedules"][c["input"]["schedule"]]
other = doc["schedules"][c["input"]["other"]]
hashes = set(sha(canonical(json.loads(serialise_schedule(base, v)))) for v in c["input"]["variants"])
return {"exit": 0, "same_across_variants": len(hashes) == 1, "differs_from_other": sha(canonical(other)) not in hashes}
if kind == "order_tables":
by_pos, by_pred = order_tables(c["input"]["series"])
return {"unit": "ln2", "by_position": by_pos, "by_predecessor": by_pred}
raise ValueError("unknown kind " + kind)
def verdict_lines(c):
e = c["expected"]
if c["kind"] == "pairs":
if e["exit"] != 0:
return ["exit=%d%s" % (e["exit"], (" run_id=" + ",".join(e["names"])) if e.get("names") else "")]
lines = []
for p in e["pairs"]:
text = "valid=%s" % ("true" if p["valid"] else "false")
if p["reasons"]:
text += " reason=%s" % ",".join(p["reasons"])
if p["event"]:
text += " event=%s" % p["event"]
lines.append(("pair %d: " % p["pair"] if len(e["pairs"]) > 1 else "") + text)
return lines
if c["kind"] == "schedule":
return ["balanced=%s" % ("true" if e["balanced"] else "false")]
if c["kind"] == "schedule_hash":
return ["same_across_variants=%s differs_from_other=%s" % (str(e["same_across_variants"]).lower(), str(e["differs_from_other"]).lower())]
if c["kind"] == "schedule_raw":
return ["exit=%d" % e["exit"]]
return ["order_tables by_position=%s" % json.dumps(e["by_position"], sort_keys=True), "order_tables by_predecessor=%s" % json.dumps(e["by_predecessor"], sort_keys=True)]
def do_check(templates):
doc = build_document(templates)
diffs = 0
names = [c["name"] for c in doc["cases"]]
if len(names) != len(set(names)):
print("DIFF duplicate case names")
diffs += 1
try:
with open(CASES_PATH, "r", encoding="utf-8") as fh:
stored_text = fh.read()
except IOError:
print("DIFF %s does not exist" % CASES_PATH)
return 1
stored = json.loads(stored_text)
if stored_text != dump_document(doc):
print("DIFF stored file text differs from the regenerated document")
diffs += 1
stored_by_name = {c["name"]: c for c in stored["cases"]}
for c in doc["cases"]:
s = stored_by_name.get(c["name"])
if s is None:
print("DIFF case %s missing in the stored file" % c["name"])
diffs += 1
continue
for key in ("class", "kind", "basis", "input", "expected"):
if s.get(key) != c[key]:
print("DIFF case %s field %s differs from the regenerated one" % (c["name"], key))
diffs += 1
oracle = recompute(s, stored)
if not same_result(oracle, s["expected"]):
print("DIFF case %s: stored expected %s != oracle %s" % (c["name"], json.dumps(s["expected"], sort_keys=True), json.dumps(oracle, sort_keys=True)))
diffs += 1
if not s.get("basis"):
print("DIFF case %s has no basis" % c["name"])
diffs += 1
for name in stored_by_name:
if name not in names:
print("DIFF stored case %s is not generated" % name)
diffs += 1
print("cases: %d" % len(doc["cases"]))
print("differences: %d" % diffs)
return 0 if diffs == 0 else 1
def same_result(a, b):
"""Compare an oracle result with a stored expected value (floats with a small tolerance, reasons as sorted lists)."""
if isinstance(a, float) or isinstance(b, float):
return abs(a - b) < 1e-9
if isinstance(a, dict):
return isinstance(b, dict) and sorted(a) == sorted(b) and all(same_result(a[k], b[k]) for k in a)
if isinstance(a, list):
return isinstance(b, list) and len(a) == len(b) and all(same_result(x, y) for x, y in zip(a, b))
return a == b
def do_check_records(templates):
sys.path.insert(0, EVID)
import validate as V # noqa: E402
doc = build_document(templates)
schema = V.load_schema()
checked = bad = 0
for c in doc["cases"]:
if c["kind"] != "pairs" or c["expected"]["exit"] != 0:
continue
exp = case_expected_pairs(c)
mat = materialize(c["input"], doc["templates"], doc["schedules"], exp)
for fname, rec in sorted(mat["records"].items()):
n = int(fname.split(".")[0].split("-")[1])
if not exp[n]["valid"] or isinstance(rec, str):
continue
checked += 1
errors = V.validate_record(rec, schema, None)
if errors:
bad += 1
print("SCHEMA %s %s: %s" % (c["name"], fname, errors[:2]))
print("records of expected-valid pairs validated against schema.json: %d, rejected: %d" % (checked, bad))
return 0 if bad == 0 else 1
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--check", action="store_true")
ap.add_argument("--list", action="store_true")
ap.add_argument("--show", metavar="NAME")
ap.add_argument("--basis", metavar="NAME")
ap.add_argument("--check-basis", action="store_true")
ap.add_argument("--check-records", action="store_true")
ap.add_argument("--write", action="store_true")
ap.add_argument("--from-samples", action="store_true")
args = ap.parse_args(argv)
templates = load_templates(args.from_samples)
if args.write:
doc = build_document(templates)
with open(CASES_PATH, "w", encoding="utf-8", newline="\n") as fh:
fh.write(dump_document(doc))
print("wrote %s (%d cases)" % (CASES_PATH, len(doc["cases"])))
return 0
if args.check:
return do_check(templates)
if args.check_records:
return do_check_records(templates)
doc = build_document(templates)
by_name = {c["name"]: c for c in doc["cases"]}
if args.list:
for c in doc["cases"]:
print(c["name"])
return 0
if args.check_basis:
missing = [c["name"] for c in doc["cases"] if not c["basis"].strip()]
for name in missing:
print("no basis: " + name)
print("cases without basis: %d" % len(missing))
return 0 if not missing else 1
for opt, key in ((args.show, "show"), (args.basis, "basis")):
if opt is not None:
if opt not in by_name:
print("unknown case: %s" % opt, file=sys.stderr)
return 2
if key == "show":
print("\n".join(verdict_lines(by_name[opt])))
else:
print(by_name[opt]["basis"])
return 0
ap.print_help()
return 2
if __name__ == "__main__":
sys.exit(main())