#!/usr/bin/env python3 """Verify a Lean submission against an approved target. Usage: lean_verify.py --route ROUTE --approved APPROVED --project PROJECT \ --work WORK [--metrics PATH] [--timeout SECONDS] ROUTE is a folder with target.json and Solution.lean. APPROVED is the approved checkout (it contains targets/registry.json). PROJECT is the pinned Li-Liu formalization/ (it contains ConditionalGoldbach/). The verifier copies the approved Challenge to ConditionalGoldbach/UserChallenge.lean, the route's Solution.lean to ConditionalGoldbach/UserSolution.lean, builds both, runs `lake comparator`, and parses `#print axioms`. This script is the orchestrator; the Lean build and comparator need the pinned image. It is not run by the Python certificate check. """ from __future__ import annotations import argparse import json import re import shutil import subprocess import sys from pathlib import Path ALLOWED_AXIOMS = {"propext", "Classical.choice", "Quot.sound"} # Checked after comments are stripped. The axiom audit is the authority; this # scan gives a clearer error and catches escapes the audit might not name. FORBIDDEN = [ (r"\bsorry\b", "sorry"), (r"\bsorryAx\b", "sorryAx"), (r"\badmit\b", "admit"), (r"(?m)^\s*axiom\b", "an axiom declaration"), (r"\bunsafe\b", "unsafe"), (r"\bnative_decide\b", "native_decide"), (r"\bimplemented_by\b", "implemented_by"), (r"\bextern\b", "extern"), (r"(?m)^\s*opaque\b", "opaque"), (r"import\s+ConditionalGoldbach\.UserChallenge", "importing UserChallenge"), ] class Wrong(Exception): pass def strip_comments(text: str) -> str: """Remove -- line comments and (nested) /- -/ block comments.""" out: list[str] = [] i = 0 depth = 0 n = len(text) while i < n: if depth == 0 and text.startswith("--", i): j = text.find("\n", i) if j < 0: break out.append("\n") i = j + 1 continue if text.startswith("/-", i): depth += 1 i += 2 continue if depth and text.startswith("-/", i): depth -= 1 i += 2 continue if depth == 0: out.append(text[i]) i += 1 return "".join(out) def scan_solution(path: Path) -> None: if not path.is_file(): raise Wrong(f"{path}: missing Solution.lean") try: text = path.read_text(encoding="utf-8") except OSError as e: raise Wrong(f"{path}: cannot read: {e}") from None code = strip_comments(text) for pattern, what in FORBIDDEN: m = re.search(pattern, code) if m: line = code[: m.start()].count("\n") + 1 raise Wrong(f"Solution.lean line {line}: {what} is not allowed") def run(cmd: list[str], cwd: Path, timeout: int) -> str: try: p = subprocess.run( cmd, cwd=str(cwd), text=True, capture_output=True, timeout=timeout, ) except FileNotFoundError: raise Wrong(f"cannot run {cmd[0]}: not on PATH") from None except subprocess.TimeoutExpired: raise Wrong(f"timed out after {timeout}s: {' '.join(cmd)}") from None out = (p.stdout or "") + (p.stderr or "") if p.returncode != 0: tail = "\n".join(out.strip().splitlines()[-15:]) raise Wrong(f"command failed (exit {p.returncode}): {' '.join(cmd)}\n{tail}") return out def axioms_of(theorem: str, output: str) -> list[str]: m = re.search(r"depends on axioms:\s*\[(.*?)\]", output, re.S) if m: names = [x.strip().strip("`'\"") for x in m.group(1).split(",")] return [x for x in names if x] if "does not depend on any axioms" in output: return [] raise Wrong(f"could not read #print axioms output for {theorem}:\n{output.strip()[-1500:]}") def main(argv: list[str]) -> int: ap = argparse.ArgumentParser() ap.add_argument("--route", required=True) ap.add_argument("--approved", required=True) ap.add_argument("--project", required=True) ap.add_argument("--work", required=True) ap.add_argument("--metrics", default=None) ap.add_argument("--timeout", type=int, default=1800) a = ap.parse_args(argv[1:]) route = Path(a.route).resolve() approved = Path(a.approved).resolve() project = Path(a.project).resolve() work = Path(a.work).resolve() metrics = Path(a.metrics).resolve() if a.metrics else None try: registry = json.loads((approved / "targets" / "registry.json").read_text(encoding="utf-8")) target_id = json.loads((route / "target.json").read_text(encoding="utf-8")).get("target") if not isinstance(target_id, str) or target_id not in registry.get("targets", {}): raise Wrong(f"target.json names {target_id!r}, which is not in targets/registry.json") entry = registry["targets"][target_id] challenge = approved / "targets" / entry["challenge"] comparator = approved / "targets" / entry["comparator"] theorem = entry["theorem"] if not challenge.is_file(): raise Wrong(f"approved challenge missing: {challenge}") if not comparator.is_file(): raise Wrong(f"approved comparator missing: {comparator}") if not (project / "ConditionalGoldbach").is_dir(): raise Wrong(f"{project}: not the Li-Liu formalization (no ConditionalGoldbach/)") scan_solution(route / "Solution.lean") work.mkdir(parents=True, exist_ok=True) target_dir = project / "ConditionalGoldbach" user_challenge = target_dir / "UserChallenge.lean" user_solution = target_dir / "UserSolution.lean" shutil.copyfile(challenge, user_challenge) shutil.copyfile(route / "Solution.lean", user_solution) local_comparator = work / "comparator.json" shutil.copyfile(comparator, local_comparator) run(["lake", "build", "ConditionalGoldbach.UserChallenge"], project, a.timeout) run(["lake", "build", "ConditionalGoldbach.UserSolution"], project, a.timeout) run(["lake", "comparator", "--config", str(local_comparator)], project, a.timeout) axioms_file = work / "Axioms.lean" axioms_file.write_text( f"import ConditionalGoldbach.UserSolution\n\n#print axioms {theorem}\n", encoding="utf-8", ) out = run(["lake", "env", "lean", str(axioms_file)], project, a.timeout) axioms = axioms_of(theorem, out) extra = [x for x in axioms if x not in ALLOWED_AXIOMS] if extra: raise Wrong(f"{theorem} depends on axioms outside the permitted set: {extra}") if metrics: metrics.parent.mkdir(parents=True, exist_ok=True) metrics.write_text( json.dumps({"score": 1, "subtasks": {target_id: 1}}) + "\n", encoding="utf-8", ) print(f"{target_id}: proved") return 0 except Wrong as e: print(str(e), file=sys.stderr) return 1 except (OSError, json.JSONDecodeError) as e: print(f"lean_verify: {e}", file=sys.stderr) return 1 finally: for p in ( project / "ConditionalGoldbach" / "UserChallenge.lean", project / "ConditionalGoldbach" / "UserSolution.lean", ): try: p.unlink() except OSError: pass shutil.rmtree(work, ignore_errors=True) if __name__ == "__main__": raise SystemExit(main(sys.argv))