"""Validate local release hashes, schemas and cross-study relationships offline.""" from __future__ import annotations import argparse from collections import Counter import gzip import hashlib import json from pathlib import Path def jsonl(path: Path): opener = gzip.open if path.suffix == ".gz" else open with opener(path, "rt", encoding="utf-8") as handle: for line in handle: if line.strip(): yield json.loads(line) def sha(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): h.update(block) return h.hexdigest() def validate(root: Path) -> dict: manifest = json.loads((root / "release_manifest.json").read_text()) files = {row["path"]: row for row in manifest["files"]} if len(files) != len(manifest["files"]): raise ValueError("Duplicate file entries") for name, row in files.items(): path = root / name if not path.resolve().is_relative_to(root.resolve()): raise ValueError("Manifest path escapes dataset root") if path.stat().st_size != row["bytes"] or sha(path) != row["sha256"]: raise ValueError(f"File checksum mismatch: {name}") croissant = json.loads((root / "croissant.json").read_text()) for obj in croissant["distribution"]: source = obj["contentUrl"] if files[source]["sha256"] != obj["sha256"]: raise ValueError(f"Croissant checksum mismatch: {source}") frontier = [row for p in sorted((root / "transcripts").glob("*.jsonl")) for row in jsonl(p)] ids = [f"{r['scenario']}|{r['cell']}|{r['run']}" for r in frontier] if len(ids) != 945 or len(set(ids)) != 945: raise ValueError("Frontier count or ID mismatch") rounds = [r for battle in frontier for r in battle["battle_log"]] if len(rounds) != 13189 or not all(isinstance(r["defender_output"], str) for r in rounds): raise ValueError("Frontier response count/type mismatch") studies = {} for study, count in [("provenance", 540), ("history", 72), ("defender_state", 216), ("precision_added", 405)]: rows = list(jsonl(root / "studies" / study / "records.jsonl.gz")) if len(rows) != count or len({r["id"] for r in rows}) != count: raise ValueError(f"Study count/ID mismatch: {study}") if not all(isinstance(r["record"]["battle_log"], list) for r in rows): raise ValueError(f"Missing study battle logs: {study}") studies[study] = rows membership = json.loads((root / "studies/precision_n60/membership.json").read_text()) shared = {r["id"] for r in studies["provenance"] if r["arm"] == "A" and r["scenario"] in {"memleak", "paperaccept", "meetingnotes"}} if len(shared) != 135 or shared != set(membership["shared_record_ids"]): raise ValueError("Incorrect precision/provenance overlap") if set(membership["added_record_ids"]) != {r["id"] for r in studies["precision_added"]}: raise ValueError("Incorrect precision additions") trials = json.loads((root / "studies/replay/trials.json").read_text()) if len(trials) != 558 or len({(r["attack"], r["target"], r["repeat"]) for r in trials}) != 558: raise ValueError("Replay trial count/ID mismatch") sources = list(jsonl(root / "studies/replay/inputs.jsonl.gz")) if len(sources) != 62 or {r["id"] for r in sources} != {r["attack"] for r in trials}: raise ValueError("Replay source membership mismatch") for row in sources: if row["input_sha256"] != [hashlib.sha256(x.encode()).hexdigest() for x in row["inputs"]]: raise ValueError("Replay input hash mismatch") sequence = json.dumps(row["inputs"], ensure_ascii=False, separators=(",", ":")).encode() if row["sequence_sha256"] != hashlib.sha256(sequence).hexdigest(): raise ValueError("Replay sequence hash mismatch") events = list(jsonl(root / "studies/competition_utility/events.jsonl.gz")) topics = list(jsonl(root / "studies/competition_utility/topics.jsonl.gz")) attempts = list(jsonl(root / "studies/competition_utility/attempts.jsonl.gz")) if (len(events), len(topics), len(attempts)) != (3083, 9171, 10151): raise ValueError("Utility record count mismatch") event_ids = {r["record_id"] for r in events} topic_ids = {(r["record_id"], r["topic_index"]) for r in topics} if len(event_ids) != len(events) or len(topic_ids) != len(topics): raise ValueError("Duplicate utility IDs") if not all(r["record_id"] in event_ids for r in topics) or not all((r["record_id"], r["topic_index"]) in topic_ids for r in attempts): raise ValueError("Broken utility foreign keys") valid_names = {"Baseline"} | {f"T{i:02d}" for i in range(1, 22)} compute_counts = {} log_metadata = json.loads((root / "studies/compute/log_metadata.json").read_text())["source_files"] for name, expected in [("log_rows", 2610), ("pilot_log_rows", 272)]: rows = list(jsonl(root / "studies/compute" / (name + ".jsonl.gz"))) if len(rows) != expected or any(r["src"] not in log_metadata or r["secs"] < 0 for r in rows): raise ValueError("Compute log inventory mismatch") compute_counts[name] = len(rows) counts = {} for name, expected in [("battles", 18422), ("public_iteration_battles", 93291)]: count, snapshots = 0, set() for row in jsonl(root / "competition_traces" / (name + ".jsonl.gz")): if row["attacker"] not in valid_names or row["defender"] not in valid_names: raise ValueError("Unexpected competition identity label") if not isinstance(row["battle_log"], list): raise ValueError("Competition battle_log must be a list") count += 1 snapshots.add(row["snapshot"]) if count != expected: raise ValueError("Competition record count mismatch") counts[name] = {"records": count, "snapshots": len(snapshots)} return {"checked_files": len(files), "frontier_battles": len(frontier), "frontier_responses": len(rounds), "followups": {name: len(rows) for name, rows in studies.items()}, "shared_precision_ids": len(shared), "replay_sources": len(sources), "replay_trials": len(trials), "utility_events": len(events), "utility_topics": len(topics), "utility_attempts": len(attempts), "compute_log_rows": compute_counts, "competition": counts} def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--data", type=Path, default=Path(__file__).resolve().parent) args = parser.parse_args() print(json.dumps(validate(args.data.resolve()), indent=2)) if __name__ == "__main__": main()