#!/usr/bin/env python3 """Read the evidence index or reproduce selected claims from local release files.""" import argparse from collections import defaultdict import json from pathlib import Path import statistics import subprocess import sys ROOT = Path(__file__).resolve().parents[1] def read_json(relative_path): return json.loads((ROOT / relative_path).read_text(encoding="utf-8")) def scored_latencies(): rows_by_run = defaultdict(list) with (ROOT / "data/input_events_paced.jsonl").open(encoding="utf-8") as events: for line in events: event = json.loads(line) if event["scored"]: rows_by_run[event["run_key"]].append(event["latency_us"]) return rows_by_run def p95_ms(values): # Nearest rank, using integer arithmetic for ceil(95 * count / 100). return sorted(values)[(95 * len(values) + 99) // 100 - 1] / 1000 def paired_timings(): manifest = read_json("DATA_MANIFEST.json") scored = scored_latencies() panels = defaultdict(dict) with (ROOT / "data/runs.jsonl").open(encoding="utf-8") as runs: for line in runs: run = json.loads(line) if run["paced"]: observations = scored[run["run_key"]] summary = { "run_key": run["run_key"], "scored_events": len(observations), "mean_ms": statistics.mean(observations) / 1000, "p95_ms": p95_ms(observations), } pair = (run["sweep"], run["matched_pair"]) panels[pair][run["condition"]] = summary by_sweep = defaultdict(list) for (sweep, pair), conditions in sorted(panels.items()): baseline = conditions["baseline"] hook = conditions["hook"] by_sweep[sweep].append({ "matched_pair": pair, "baseline": baseline, "hook": hook, "mean_reduction_ms": baseline["mean_ms"] - hook["mean_ms"], "p95_change_ms": round(hook["p95_ms"] - baseline["p95_ms"], 9), }) summaries = {} for sweep, pairs in by_sweep.items(): no_hook = statistics.mean(pair["baseline"]["mean_ms"] for pair in pairs) with_hook = statistics.mean(pair["hook"]["mean_ms"] for pair in pairs) count = sum(pair[mode]["scored_events"] for pair in pairs for mode in ("baseline", "hook")) summaries[sweep] = { "baseline_equal_run_mean_ms": no_hook, "hook_equal_run_mean_ms": with_hook, "equal_run_mean_reduction_ms": no_hook - with_hook, "scored_events": count, "matched_pairs": pairs, } return {"endpoint": manifest["primary_endpoint"], "scope": manifest["scope"], "sweeps": summaries, "total_scored_events": sum(len(values) for values in scored.values())} def tail_regression(): timings = paired_timings() pair = next(item for item in timings["sweeps"]["initial"]["matched_pairs"] if item["matched_pair"] == 3) return {"sweep": "initial", "endpoint": timings["endpoint"], **pair} def run_reference(path, *args): result = subprocess.run( [sys.executable, "-B", str(ROOT / path), *(str(arg) for arg in args)], cwd=ROOT, check=True, capture_output=True, encoding="utf-8", ) return json.loads(result.stdout) def pulse_order(): return { "unit": "ms", "period": 10, "pulse_width": 9, "denominator": "all uniformly timed start phases in the eight-frame cycle", "alternating": run_reference("src/phase_schedule.py", 10, 9, 0, 4, 0, 4, 0, 4, 0, 4), "one_late_block": run_reference("src/phase_schedule.py", 10, 9, 0, 0, 0, 0, 4, 4, 4, 4), } def pulse_deadline(): return run_reference("src/coverage.py", "results/grace_example.json", "--width", 2, "--spectrum") REPLAYS = { "timing-paired": paired_timings, "tail-regression": tail_regression, "pulse-order": pulse_order, "pulse-deadline": pulse_deadline, } def check(index, claims): def need(condition, message): if not condition: raise ValueError(message) need(len(claims) == len(index["claims"]), "Duplicate evidence ID") need({key for key, value in claims.items() if value["replay"]} == set(REPLAYS), "Evidence index and replay commands disagree") paths = {index["dataset_manifest"]} paths.update(source["file"] for item in claims.values() for source in item["sources"]) for path in paths: file = (ROOT / path).resolve() need(file.is_relative_to(ROOT) and file.is_file(), f"Invalid evidence file: {path}") timing = paired_timings() manifest = read_json(index["dataset_manifest"]) need(timing["total_scored_events"] == 7781, "Scored event count mismatch") need(set(timing["sweeps"]) == set(manifest["sweeps"]), "Unexpected sweep") for name, result in timing["sweeps"].items(): expected = manifest["sweeps"][name]["equal_run_mean_difference_ms"] need(len(result["matched_pairs"]) == 4, f"Missing pair in {name}") need(abs(result["equal_run_mean_reduction_ms"] - expected) < 1e-10, f"Mean difference mismatch in {name}") tail = tail_regression() need(tail["baseline"]["p95_ms"] == 30.932 and tail["hook"]["p95_ms"] == 31.101, "Tail comparison mismatch") ordering = pulse_order() example = read_json("results/sequence_checks.json")["example"] need(ordering["alternating"] == example["alternating"] and ordering["one_late_block"] == example["clustered"], "Pulse schedule mismatch") need(pulse_deadline() == read_json("results/certificate_example.json"), "Pulse witness mismatch") return {"status": "passed", "claims": len(claims), "source_paths": len(paths), "replays_checked": len(REPLAYS), "scored_paced_events": timing["total_scored_events"]} def main(): index = read_json("agent/evidence.json") claims = {claim["id"]: claim for claim in index["claims"]} parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest="command", required=True) commands.add_parser("list", help="List evidence IDs, kinds and available replays") commands.add_parser("show", help="Show one claim and its source locations").add_argument( "claim", choices=claims) commands.add_parser("replay", help="Recompute a claim from the provided data or reference code").add_argument( "claim", choices=REPLAYS) commands.add_parser("check", help="Check evidence paths and all numerical replays") args = parser.parse_args() if args.command == "list": output = [{key: item[key] for key in ("id", "kind", "replay")} for item in claims.values()] elif args.command == "show": output = claims[args.claim] elif args.command == "replay": output = REPLAYS[args.claim]() else: output = check(index, claims) print(json.dumps(output, indent=2, allow_nan=False)) if __name__ == "__main__": main()