Datasets:
File size: 7,076 Bytes
987b273 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | #!/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()
|