File size: 10,684 Bytes
25693a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
178
179
180
181
182
183
184
185
186
187
188
189
190
"""Export the pinned Yang miniF2F source and its recorded AXLE checks.

Uses only the Python standard library. Run --help for required input paths.
No network calls, Lean execution, source edits, or publishing are performed.
"""
import argparse
import hashlib
import io
import json
from pathlib import Path
import re
import subprocess
import tarfile

UPSTREAM = "https://github.com/yangky11/miniF2F-lean4"
COMMIT = "5746b7d6c47855ce1294bed87329618ff7f1bc31"
CONFIG = "lean-4.36.0"
TOOLCHAIN = "leanprover/lean4:v4.36.0"
MATHLIB = "fc4f59e577feb1a4956671bc04ac18aaaf8cd842"
SPLITS = {"Test": "test", "Valid": "validation"}


def sha256(data):
    return hashlib.sha256(data).hexdigest()


def parse_source(path, raw):
    """Accept this pinned snapshot's single-theorem format; fail on ambiguity."""
    text = raw.decode("utf-8")
    matches = list(re.finditer(r"^theorem ([A-Za-z0-9_]+)\b", text, re.MULTILINE))
    if len(matches) != 1:
        raise ValueError(f"Expected one theorem: {path}")
    match = matches[0]
    name = match.group(1)
    if name != Path(path).stem:
        raise ValueError(f"Theorem name differs from filename: {path}")
    header, statement = text[:match.start()], text[match.start():]
    expected_header = "import Mathlib\n\nset_option maxHeartbeats 0\n\nopen BigOperators Real Nat Topology Rat\n\n"
    if header != expected_header:
        raise ValueError(f"Unrecognized source header: {path}")
    if len(re.findall(r"\bsorry\b", statement)) != 1 or not re.search(r":= by sorry\s*\Z", statement):
        raise ValueError(f"Expected one terminal proof placeholder: {path}")
    if (header + statement).encode("utf-8") != raw:
        raise ValueError(f"Source round trip failed: {path}")
    return {"id": name, "header": header, "formal_statement": statement,
            "source_file": path, "source_sha256": sha256(raw)}


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes((json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))


def export(source, axle, output):
    head = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
    if head != COMMIT:
        raise ValueError(f"Expected source commit {COMMIT}; got {head}")
    archive = subprocess.check_output(["git", "-c", "core.autocrlf=false", "-C", str(source), "archive", COMMIT, "MiniF2F", "LICENSE"])
    with tarfile.open(fileobj=io.BytesIO(archive)) as tar:
        originals = {m.name: tar.extractfile(m).read() for m in tar.getmembers() if m.isfile()}
    metadata = json.loads((axle / "metadata.json").read_text(encoding="utf-8"))
    controls = json.loads((axle / "controls.json").read_text(encoding="utf-8"))
    checks = [json.loads(line) for line in (axle / "statements.jsonl").read_text(encoding="utf-8").splitlines()]
    by_path = {r["path"]: r for r in checks}
    if len(checks) != 488 or len(by_path) != 488:
        raise ValueError("AXLE report must cover 488 unique files")
    if metadata["source_commit"] != COMMIT or metadata["toolchain"] != TOOLCHAIN:
        raise ValueError("AXLE report source/toolchain mismatch")
    required_options = {"environment": CONFIG, "ignore_imports": False, "mathlib_options": False,
                        "run_env_linters": False, "timeout_seconds": 120,
                        "global_options": {"maxRecDepth": 65536}}
    if metadata["options"] != required_options:
        raise ValueError("AXLE report options mismatch")
    expected_controls = {"valid_proof": True, "invalid_proof": False, "statement_with_sorry": True}
    if {c["name"]: c["response"]["okay"] for c in controls} != expected_controls:
        raise ValueError("AXLE controls did not pass")
    for control in controls:
        if bool(control["response"]["lean_messages"]["errors"]) == expected_controls[control["name"]]:
            raise ValueError("AXLE control error messages disagree")
    if not any("4.36.0" in s for s in controls[0]["response"]["lean_messages"]["infos"]):
        raise ValueError("AXLE control did not confirm Lean 4.36.0")

    rows = {split: [] for split in SPLITS.values()}
    validation_rows = []
    for path, raw in sorted(originals.items()):
        parts = Path(path).parts
        if len(parts) != 3 or parts[1] not in SPLITS or not path.endswith(".lean"):
            continue
        working = (source / path).read_bytes()
        if working.replace(b"\r\n", b"\n") != raw:
            raise ValueError(f"Theorem source changed from upstream: {path}")
        record = parse_source(path, raw)
        check = by_path[path]
        response = check["response"]
        # The saved run used a Windows checkout. Accept its recorded raw hash
        # only if it matches either canonical LF or equivalent CRLF source.
        if check["sha256"] not in {sha256(raw), sha256(raw.replace(b"\n", b"\r\n"))}:
            raise ValueError(f"AXLE checked different source bytes: {path}")
        if check["status"] != "compiled" or response["okay"] is not True:
            raise ValueError(f"AXLE compilation failed: {path}")
        if response["lean_messages"]["errors"] or response["tool_messages"]["errors"]:
            raise ValueError(f"AXLE reported errors: {path}")
        if response["info"]["environment"] != CONFIG:
            raise ValueError(f"AXLE used a different environment: {path}")
        # AXLE may add a final newline; all actual source text must be preserved.
        if response["content"].replace("\r\n", "\n").rstrip("\n") != raw.decode("utf-8").rstrip("\n"):
            raise ValueError(f"AXLE processed different content: {path}")
        rows[SPLITS[parts[1]]].append(record)
        validation_rows.append({"id": record["id"], "split": SPLITS[parts[1]],
                                "source_sha256": record["source_sha256"], "compiles": True,
                                "request_id": response["info"]["request_id"]})
    if any(len(items) != 244 for items in rows.values()):
        raise ValueError("Expected 244 examples in each original split")
    if len({r["id"] for items in rows.values() for r in items}) != 488:
        raise ValueError("Duplicate theorem identifiers")
    output.mkdir(parents=True, exist_ok=True)
    (output / "LICENSE").write_bytes(originals["LICENSE"])
    artifacts = {}
    for split, items in rows.items():
        relative = f"data/{CONFIG}/{split}.jsonl"
        path = output / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        data = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in items).encode("utf-8")
        path.write_bytes(data)
        artifacts[relative] = sha256(data)
    for filename in ("lean-toolchain", "lakefile.lean", "lake-manifest.json"):
        data = (source / filename).read_bytes().replace(b"\r\n", b"\n")
        if filename == "lean-toolchain" and data.decode().strip() != TOOLCHAIN:
            raise ValueError("Local toolchain mismatch")
        if filename == "lake-manifest.json":
            manifest = json.loads(data)
            recorded_manifest = dict(metadata["manifest"])
            # The initial Windows checker decoded this display name using
            # cp1252. Repair only that exact known encoding discrepancy; all
            # dependency pins and other manifest fields must still match.
            if recorded_manifest.get("name") == manifest["name"].encode("utf-8").decode("cp1252"):
                recorded_manifest["name"] = manifest["name"]
            if manifest != recorded_manifest:
                raise ValueError("Local manifest differs from recorded intended manifest")
            if next(p for p in manifest["packages"] if p["name"] == "mathlib")["rev"] != MATHLIB:
                raise ValueError("Unexpected Mathlib revision")
        relative = f"environment/{CONFIG}/{filename}"
        path = output / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(data)
        artifacts[relative] = sha256(data)
    write_json(output / "manifest.json", {
        "schema_version": 1, "config": CONFIG,
        "upstream": {"repository": UPSTREAM, "commit": COMMIT},
        "source_sha256_definition": "SHA-256 of the original UTF-8 Git blob, with LF line endings",
        "source_statements_modified": False,
        "split_mapping": {"Test": "test", "Valid": "validation"},
        "split_counts": {split: len(items) for split, items in rows.items()},
        "default_evaluation_split": "test",
        "lean_toolchain": TOOLCHAIN, "mathlib_commit": MATHLIB,
        "required_lean_options": {"maxRecDepth": 65536},
        "proof_placeholder": "Exactly one terminal := by sorry; this is an incomplete proof stub",
        "adaptation": "Theorem files are unchanged. Bundled project configuration upgrades Lean/Mathlib from v4.24.0 to v4.36.0; no separate port commit is claimed.",
        "exporter": {"path": "scripts/export.py", "sha256": sha256(Path(__file__).read_bytes())},
        "artifact_sha256": artifacts,
    })
    write_json(output / "validation" / f"{CONFIG}.json", {
        "scope": "Compilation of statements with existing sorry stubs; not proof verification",
        "service": "AXLE", "client_version": metadata["client_version"],
        "run_started_at": metadata["started_at"], "options": metadata["options"],
        "remote_environment": metadata["remote_environment"],
        "controls": controls,
        "total": len(validation_rows), "compiled": len(validation_rows),
        "limitation": "AXLE does not expose its Mathlib commit. This does not certify a local build of the bundled dependency lockfile.",
        "statements": validation_rows,
    })
    # These reports contain public benchmark code and service responses, not
    # credentials or machine paths. Keep them to make the export reproducible.
    inputs = output / "validation" / "axle-input"
    write_json(inputs / "metadata.json", metadata)
    write_json(inputs / "controls.json", controls)
    (inputs / "statements.jsonl").write_bytes(
        "".join(json.dumps(r, ensure_ascii=False) + "\n" for r in sorted(checks, key=lambda r: r["path"])).encode("utf-8")
    )
    print(json.dumps({"counts": {s: len(r) for s, r in rows.items()}, "artifacts": artifacts}, indent=2))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--source", required=True, type=Path)
    parser.add_argument("--axle-results", required=True, type=Path)
    parser.add_argument("--output", type=Path, default=Path(__file__).resolve().parents[1])
    args = parser.parse_args()
    export(args.source.resolve(), args.axle_results.resolve(), args.output.resolve())