"""Offline module witness atlas from the pinned review TSVs; standard library only.""" import argparse import csv import hashlib import json from collections import Counter from pathlib import Path SOURCE_COMMIT = "3456e5e75cf8d4cd558955a5c7638fba2d68f464" DECLARATION_SHA256 = "1f16d6cbf7cd650c7edccd08f95967ce92cd7e36ec68cfdd081621aec126c5e9" MODULE_SHA256 = "f9db49e0d1b7bc8262ecb7f77b18f378db687e9ed87356c42010f560dac265dc" USED_MODULES = 6523 HEADLINE_COUNT = 17 DECLARATION_COUNT = 250319 USED_DECLARATIONS = 100168 MAX_TSV_BYTES = 64 * 1024 * 1024 ROOT = Path(__file__).resolve().parent SOURCE_URL = f"https://raw.githubusercontent.com/yang-mills-group/OpenAI-YM-20261028/{SOURCE_COMMIT}/verification/" def need(ok, message): if not ok: raise ValueError(message) def obj(path): return json.loads(path.read_text(encoding="utf-8")) def digest(path): need(path.is_file(), f"{path.name}: missing or not a regular file") need(path.stat().st_size <= MAX_TSV_BYTES, f"{path.name}: exceeds 64 MiB") with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def tsv(path, fields): need(path.stat().st_size <= MAX_TSV_BYTES, "TSV exceeds 64 MiB") with path.open(encoding="utf-8", newline="") as stream: reader = csv.DictReader(stream, delimiter="\t") need(reader.fieldnames == fields, f"{path.name}: unexpected TSV columns") rows = list(reader) need(rows and all(None not in r and all(v is not None for v in r.values()) for r in rows), "invalid TSV rows") return rows def extract(declarations, modules): rows = tsv(declarations, ["module", "declaration", "status", "headline_witness", "immediate_user", "source_line"]) summary = tsv(modules, ["module", "declarations", "used", "outside"]) names, counts, used, headlines = {}, {}, Counter(), [] for r in rows: n, m, s = r["declaration"], r["module"], r["status"] need(n and m and n not in names and s in {"headline", "used", "outside"}, "duplicate/invalid declaration") need(not r["source_line"] or r["source_line"].isdigit(), f"{n}: invalid source line") names[n] = r counts.setdefault(m, Counter())[s] += 1 if s != "outside": used[m] += 1 if s == "headline": headlines.append(n) seen = set() for r in summary: m = r["module"] need(m and m not in seen, "module summary missing/duplicate module") seen.add(m) c = counts.get(m, Counter()) need([int(r[k]) for k in ("declarations", "used", "outside")] == [sum(c.values()), c["used"] + c["headline"], c["outside"]], f"{m}: module totals disagree") need(set(counts) <= seen, "module summary incomplete") deps = {m: set() for m in used} for n, r in names.items(): if r["status"] == "outside": continue need(r["headline_witness"] in headlines, f"{n}: invalid headline witness") user = r["immediate_user"] if user: need(user in names and names[user]["status"] != "outside", f"{n}: invalid immediate user") dependent = names[user]["module"] if dependent != r["module"]: deps[dependent].add(r["module"]) graph = [{"name": m, "used": used[m], "total": sum(counts[m].values()), "dependencies": sorted(deps[m])} for m in sorted(used)] return names, sorted(headlines), graph def write_json(path, value): path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", newline="\n") def build(declarations, modules, output): need(digest(declarations) == DECLARATION_SHA256, "declaration TSV sha256 mismatch (use byte-exact LF export)") need(digest(modules) == MODULE_SHA256, "module TSV sha256 mismatch (use byte-exact LF export)") names, headlines, graph = extract(declarations, modules) need(len(names) == DECLARATION_COUNT and sum(m["used"] for m in graph) == USED_DECLARATIONS, "declaration count mismatch") need(len(graph) == USED_MODULES and len(headlines) == HEADLINE_COUNT, "module/headline count mismatch") output.mkdir(parents=True, exist_ok=True) sources = {key: {"path": str(path.resolve()), "url": SOURCE_URL + path.name, "sha256": digest(path)} for key, path in [("declarations", declarations), ("modules", modules)]} # Use canonical names in URLs even if a local download was renamed. sources["declarations"]["url"] = SOURCE_URL + "declaration-usage.tsv" sources["modules"]["url"] = SOURCE_URL + "module-usage.tsv" write_json(output / "atlas.json", {"schema": 1, "source_commit": SOURCE_COMMIT, "sources": sources, "headlines": headlines, "modules": graph, "edge_semantics": "immediate_user witness; dependent -> dependency; not exhaustive"}) dot = ["digraph witness {", ' graph [label="Module dependency witnesses (not exhaustive)"];'] for m in graph: dot.append(f' {json.dumps(m["name"])};') dot.extend(f' {json.dumps(m["name"])} -> {json.dumps(d)};' for d in m["dependencies"]) (output / "atlas.dot").write_text("\n".join(dot) + "\n", encoding="utf-8", newline="\n") print(f"atlas: {len(graph)} modules, {len(headlines)} headlines, sha256 ok") def main(): p = argparse.ArgumentParser(description=__doc__) p.add_argument("--declarations", required=True, type=Path) p.add_argument("--modules", required=True, type=Path) p.add_argument("--output", required=True, type=Path) a = p.parse_args() build(a.declarations, a.modules, a.output) if __name__ == "__main__": try: main() except (ValueError, OSError, KeyError, TypeError, UnicodeError) as error: print(f"Invalid atlas: {error}") raise SystemExit(1)