"""Recheck all published tuples and derive the finite observed search summary.""" import argparse from collections import Counter import hashlib import importlib.util import json from pathlib import Path ROOT = Path(__file__).resolve().parent MASK64 = (1 << 64)-1 def module(name, path): spec = importlib.util.spec_from_file_location(name, path) result = importlib.util.module_from_spec(spec) spec.loader.exec_module(result) return result def initial_rng(seed): value = 88172645463325252 ^ ((seed*0x9E3779B97F4A7C15) & MASK64) for _ in range(20): value ^= (value << 13) & MASK64 value ^= value >> 7 value ^= (value << 17) & MASK64 return str(value) def summarize(data, verify, reference): plan = data["preregistration"] arms = [] for seed in plan["seeds"]: for target in plan["targets"]: arms.append({ "seed": seed, "target": target, "effective_minimum_cover_length": 6*((target-5)//6)+5, "slices": 0, "started_restarts": 0, "node_limited_restarts": 0, "cpu_interrupted_restarts": 0, "exhausted_restarts": 0, "nodes_including_blocked_entry": 0, "timed_search_cpu_seconds": 0, "search_worker_wall_seconds": 0, "tuples": 0, "best_count": None, "rng": initial_rng(seed), }) unique = {} arm_keys = [set() for _ in arms] raw_histogram = Counter() best = None seen_labels = set() for chunk in data["chunks"]: if chunk["id"] in seen_labels: raise ValueError("Repeated chunk identity") seen_labels.add(chunk["id"]) index = chunk["arm"] arm = arms[index] if (chunk["seed"], chunk["target"]) != (arm["seed"], arm["target"]): raise ValueError("Chunk assigned to the wrong preregistered arm") expected_label = f"arm-{index:02d}-restart-{arm['started_restarts']:04d}" if chunk["id"] != expected_label: raise ValueError("Missing or reordered arm restart") starts = [json.loads(line[8:]) for line in chunk["stderr"].splitlines() if line.startswith("RESTART ")] states = [json.loads(line[6:]) for line in chunk["stderr"].splitlines() if line.startswith("STATE ")] if len(states) != 1 or not starts: raise ValueError("Missing restart/state record") state = states[0] if len(starts) != state["started_restarts"]: raise ValueError("Restart count differs from state") if not 0 < len(starts) <= plan["restarts_per_slice"]: raise ValueError("Restart slice budget exceeded") if arm["started_restarts"]+len(starts) > plan["restarts_per_arm"]: raise ValueError("Arm restart budget exceeded") nodes = 0 counts = Counter() for i, restart in enumerate(starts, 1): if restart["index"] != i or restart["start_state"] != arm["rng"]: raise ValueError("Broken random-state continuity") if not 0 < restart["nodes"] <= plan["nodecap"]+1: raise ValueError("Invalid node count") reason = restart["reason"] if reason == "node_limit": if restart["nodes"] != plan["nodecap"]+1: raise ValueError("Node-limited restart has the wrong count") arm["node_limited_restarts"] += 1 elif reason == "cpu_limit": if i != len(starts) or restart["nodes"] > plan["nodecap"]: raise ValueError("Invalid CPU-interrupted restart") arm["cpu_interrupted_restarts"] += 1 elif reason == "exhausted": arm["exhausted_restarts"] += 1 else: raise ValueError("Unknown restart termination reason") nodes += restart["nodes"] counts[i] = restart["tuples"] arm["rng"] = restart["end_state"] if (state["rng"] != arm["rng"] or state["nodes"] != nodes or state["tuples"] != sum(counts.values()) or state["cpu_interrupted"] != (starts[-1]["reason"] == "cpu_limit")): raise ValueError("Restart records disagree with aggregate state") actual_counts = Counter() for line in chunk["stdout"].splitlines(): if not line.strip(): continue row = verify(line, reference) if row["cover_length"] < arm["effective_minimum_cover_length"]: raise ValueError("Tuple below its effective target") if row["published_gap_control_exceeded"]: raise ValueError("Tuple conflicts with the published 1530 gap control") actual_counts[int(line.split()[-1])] += 1 key = row["key"] coordinates = (row["cover_length"], row["gap_length"], row["count"]) if key in unique and unique[key] != coordinates: raise ValueError("One phase vector has conflicting decoded data") unique[key] = coordinates arm_keys[index].add(key) raw_histogram[coordinates] += 1 arm["tuples"] += 1 if arm["best_count"] is None or row["count"] > arm["best_count"]: arm["best_count"] = row["count"] if best is None or row["count"] > best["count"]: best = dict(row, arm=index, chunk=chunk["id"]) if actual_counts != +counts: raise ValueError("Raw tuple counts disagree with restart logs") if hashlib.sha256(chunk["stdout"].encode()).hexdigest() != chunk["stdout_sha256"]: raise ValueError("Raw output digest mismatch") arm["slices"] += 1 arm["started_restarts"] += len(starts) arm["nodes_including_blocked_entry"] += nodes arm["timed_search_cpu_seconds"] += state["search_cpu_seconds"] arm["search_worker_wall_seconds"] += chunk["wall_seconds"] for index, arm in enumerate(arms): arm["distinct_tuples"] = len(arm_keys[index]) unique_histogram = Counter(unique.values()) rows = [ {"cover_length": key[0], "gap_length": key[1], "interior_count": key[2], "raw": raw_histogram[key], "distinct": unique_histogram[key]} for key in sorted(raw_histogram) ] return { "schema_version": 1, "stop_reason": data["stop_reason"], "all_emitted_tuples_directly_verified": True, "legacy_decoder_agrees": True, "raw_tuples": sum(arm["tuples"] for arm in arms), "distinct_tuples": len(unique), "checked_slices": len(data["chunks"]), "started_restarts": sum(arm["started_restarts"] for arm in arms), "node_limited_restarts": sum(arm["node_limited_restarts"] for arm in arms), "cpu_interrupted_restarts": sum(arm["cpu_interrupted_restarts"] for arm in arms), "exhausted_restarts": sum(arm["exhausted_restarts"] for arm in arms), "nodes_including_blocked_entry": sum(arm["nodes_including_blocked_entry"] for arm in arms), "timed_search_cpu_seconds": sum(arm["timed_search_cpu_seconds"] for arm in arms), "search_worker_wall_seconds": sum(arm["search_worker_wall_seconds"] for arm in arms), "best": best, "arms": arms, "histogram": rows, "scope": "A bounded biased sample, not an exhaustive gap census or a universal upper bound.", } if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("observations", type=Path) parser.add_argument("--expected", type=Path) parser.add_argument("--legacy", type=Path, default=ROOT/"cert2624.py") args = parser.parse_args() data = json.loads(args.observations.read_text()) plan = data["preregistration"] checker = ROOT/"inspect-tuples.py" if hashlib.sha256(checker.read_bytes()).hexdigest() != plan["checker_sha256"]: raise ValueError("Independent tuple checker changed") if hashlib.sha256(args.legacy.read_bytes()).hexdigest() != plan["legacy_decoder_sha256"]: raise ValueError("Legacy decoder changed") result = summarize(data, module("tuple_checker", checker).verify, module("legacy_decoder", args.legacy).certificate) if args.expected: if result != json.loads(args.expected.read_text()): raise ValueError("Published summary differs from independently recomputed data") print(json.dumps({"all_tuples_and_summary_agree": True, "raw_tuples": result["raw_tuples"], "distinct_tuples": result["distinct_tuples"], "best_count": result["best"]["count"] if result["best"] else None}, sort_keys=True)) else: print(json.dumps(result, sort_keys=True))