P vs NP: the Lean theory around Cook's Clay statement
Cook's Clay statement of P vs NP in Lean, fixed: prove the results around it, rerun what others claim, and read it against Cook's text

| 1 | #!/usr/bin/env python3 |
| 2 | """The `build` check: the pushed commit compiles, uses no `sorry`, its theorems depend only on the permitted axioms, |
| 3 | and Comparator accepts it against the approved challenge. |
| 4 | |
| 5 | Usage: build.py <commit's tree> [<build.json>] (BUILD_REPLAY=1: with Comparator even where build.json has |
| 6 | "replay": "round", see below) |
| 7 | |
| 8 | This is leanprover-community/riemann-hypothesis's `build.yml` ("lake build", the merge queue's required check), made a |
| 9 | check of this site, plus the Comparator run its README asks for. It runs in the project's Lean image (`docker/`), with |
| 10 | no network, on the site's runner, as root in the runner's container. |
| 11 | |
| 12 | The commit's Lean is code the check runs: an `#eval`, an `initialize` or an elaborator in it runs while Lean compiles |
| 13 | the file or imports it, and can print anything, including Comparator's success lines, or rewrite `lake` itself. So |
| 14 | nothing the commit's build prints is trusted, and none of its code runs as root: |
| 15 | |
| 16 | 1. the approved version (the checkout this script is in, PROOF_APPROVED to override) is compiled as root, from the |
| 17 | image's `.lake`, and each Comparator configuration's challenge module is exported (`export_command`) before |
| 18 | anything of the commit runs. Its definitions, not the commit's, are what the statements mean; |
| 19 | 2. the commit's tree is copied to a folder of its own and given the image's `.lake` (the dependencies, read-only, and |
| 20 | the build of the approved main, made when the image was built): Lake then rebuilds only what the commit changed. |
| 21 | As `nobody`, it runs `lake build`, and `lake build` of every library the approved lakefile.toml declares (the |
| 22 | default targets are a key a pull request may change), which must end without error and with no module reporting a |
| 23 | declaration that uses `sorry` except the challenge's own files (`frozen` in build.json: they state the theorems |
| 24 | with `sorry` on purpose); then it exports each configuration's solution module, and the theorems of build.json; |
| 25 | 3. every process of `nobody` is killed; then, as `nobody`, Comparator judges each export pair: the statements and the |
| 26 | definitions they use as approved, no axiom beyond the permitted ones (a `sorry` is the axiom `sorryAx`), and a |
| 27 | replay through Lean's kernel (and nanoda, where the configuration asks). The theorems of build.json are judged the |
| 28 | same way against their own export: axioms and kernel. The judge reads text exports only and never loads an `.olean` |
| 29 | of the commit, so what it prints is the verdict; |
| 30 | 4. the commit's `lean-toolchain` must be the image's: a bump needs a new image (docker/README.md). |
| 31 | |
| 32 | Two Comparators are served (`comparator_kind` in build.json). "lake", the default: the toolchain's own (Lean 4.35 and |
| 33 | later), `lake comparator --challenge-from-export … --solution-from-export … --inadvisably-no-sandbox`. "standalone": |
| 34 | leanprover/comparator as a binary, for the toolchains before it, which builds and exports by itself through `landrun` |
| 35 | and has no way to be handed exports. It is given one: COMPARATOR_LANDRUN names a stand-in this script writes, which |
| 36 | does nothing for `lake build`, prints step 1's or step 2's export for `lean4export <module>`, and starts an external |
| 37 | kernel (nanoda_bin) as it is; Comparator's own comparison, axiom walk and kernels then run as upstream wrote them. |
| 38 | Neither Comparator's own sandbox is what holds the commit here. bwrap cannot start in the runner's container (no user |
| 39 | namespaces). landrun can (Landlock, measured on the production host 12-02), but upstream's guarantee needs three things |
| 40 | the check does not have: nothing of the commit compiled before Comparator runs, a user who is not root, and no |
| 41 | AF_UNIX (kernels before 7.1). Step 2, as `nobody`, stands in for both. |
| 42 | |
| 43 | Where the build is kept. With `"in_place": true` and an image whose `.lake/build` belongs to `nobody`, both sides use |
| 44 | that folder itself: root first, for the approved challenge, then the commit, which may write anything there; nothing |
| 45 | is read from it as approved after that, and the container is thrown away with what it wrote. A job then costs the |
| 46 | disk of what it recompiled. Without it the build is copied for each side, as before (a 600 MB build: fine; 40 GB: |
| 47 | not). |
| 48 | |
| 49 | When Comparator runs. A replay sends the whole proof through a kernel on one core: minutes for a small library, hours |
| 50 | for a large one. With `"replay": "round"` in build.json a push gets step 2's build and `sorry` scan only, and the last |
| 51 | line says so: that is the commit's own Lean reporting on itself, a filter and not a verdict. The replay (all four |
| 52 | steps) is then run once per maintainer round, on main or on a batch of pull requests, with BUILD_REPLAY=1; its result |
| 53 | is filed as a report. Without the key every push is replayed. |
| 54 | |
| 55 | The `sorry` scan of step 2 reads the commit's own build log, which the commit's code can write to: it catches an |
| 56 | honest `sorry` anywhere in the library, and a hidden one cannot reach a judged theorem, since step 3 reads the axioms |
| 57 | from the exports. Run as another user than root (tests, a machine of one's own) it does the same steps without |
| 58 | switching to `nobody`. |
| 59 | |
| 60 | Each step's wall time is printed as it ends (`-- … s`). Its last line says what held, or the first thing that did |
| 61 | not. Exit 0 passes, 1 fails. |
| 62 | """ |
| 63 | |
| 64 | from __future__ import annotations |
| 65 | |
| 66 | import json |
| 67 | import os |
| 68 | import re |
| 69 | import shlex |
| 70 | import shutil |
| 71 | import subprocess |
| 72 | import sys |
| 73 | import tempfile |
| 74 | import time |
| 75 | import tomllib |
| 76 | from pathlib import Path |
| 77 | |
| 78 | SORRY = re.compile(r"declaration uses ['`]sorry['`]") |
| 79 | # where a warning comes from: "warning: Challenge.lean:2:8: declaration uses `sorry`" (a path, possibly ./ or absolute) |
| 80 | WHERE = re.compile(r"(?:^|\s)(?:\./)?([^\s:]+\.lean):\d+:\d+:") |
| 81 | NOBODY = 65534 # nobody:nogroup in Ubuntu |
| 82 | # What is exported with the theorems, as `lake comparator` asks when it exports by itself (Lean 4.35.0, |
| 83 | # src/lake/Lake/CLI/Check.lean: builtinTargets, primitiveTargets): the kernel's built-in constants, Quot when Quot.sound |
| 84 | # is permitted, then the configuration's theorems, axioms and definitions. |
| 85 | PRIMITIVES = [ |
| 86 | "Nat.add", "Nat.sub", "Nat.mul", "Nat.pow", "Nat.gcd", "Nat.div", "Nat.mod", "Nat.beq", "Nat.ble", "Nat.land", |
| 87 | "Nat.lor", "Nat.xor", "Nat.shiftLeft", "Nat.shiftRight", "String.ofList", "Char.ofNat", "List", "eagerReduce", |
| 88 | "Nat", "String", "String.mk", "Char", "optParam", "autoParam", "semiOutParam", "outParam", |
| 89 | ] |
| 90 | QUOT = ["Quot", "Quot.mk", "Quot.lift", "Quot.ind"] |
| 91 | NO_SANDBOX = "WARNING: Sandbox disabled, this run is not trustworthy." |
| 92 | |
| 93 | |
| 94 | class Wrong(Exception): |
| 95 | pass |
| 96 | |
| 97 | |
| 98 | ROOT = os.geteuid() == 0 |
| 99 | |
| 100 | |
| 101 | def toolchain_bin(cwd: Path) -> str: |
| 102 | """The toolchain's own bin folder (elan puts only lean, lake and leanchecker on PATH; Comparator looks nanoda_bin |
| 103 | up on PATH), or nothing where elan is not there.""" |
| 104 | try: |
| 105 | return str(Path(subprocess.run(["elan", "which", "lean"], cwd=cwd, capture_output=True, text=True, timeout=60, |
| 106 | check=True).stdout.strip()).parent) |
| 107 | except (OSError, subprocess.SubprocessError): |
| 108 | return "" |
| 109 | |
| 110 | |
| 111 | BIN = "" # set in main: the toolchain's bin folder, first on every PATH below |
| 112 | |
| 113 | |
| 114 | def env_for(home: Path) -> dict[str, str]: |
| 115 | """What a process of the commit or the judge sees: the image's PATH and elan, a HOME of its own, and git told |
| 116 | that the image's repositories, which root owns, are safe to read (Lake asks git about each package).""" |
| 117 | keep = {k: v for k, v in os.environ.items() if k in ("PATH", "ELAN_HOME", "LANG", "LC_ALL", "LEAN_NUM_THREADS")} |
| 118 | if BIN: |
| 119 | keep["PATH"] = f"{BIN}:{keep.get('PATH', '/usr/bin:/bin')}" |
| 120 | return {**keep, "HOME": str(home), "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "safe.directory", |
| 121 | "GIT_CONFIG_VALUE_0": "*"} |
| 122 | |
| 123 | |
| 124 | def run(cmd: list[str], cwd: Path, timeout: int, log: Path | None = None, *, nobody: bool = False, |
| 125 | env: dict[str, str] | None = None, out=None) -> str: |
| 126 | """Run a command, keep what it printed in `log`, and fail with its last lines if it fails. With `out`, its standard |
| 127 | output goes to that file instead. With `nobody` (and as root), it runs as nobody, with no supplementary group.""" |
| 128 | print(f"$ {' '.join(cmd)}", flush=True) |
| 129 | who = {"user": NOBODY, "group": NOBODY, "extra_groups": []} if nobody and ROOT else {} |
| 130 | began = time.monotonic() |
| 131 | try: |
| 132 | p = subprocess.run(cmd, cwd=cwd, stdout=out or subprocess.PIPE, stderr=subprocess.STDOUT if out is None else subprocess.PIPE, |
| 133 | text=True, timeout=timeout, env=env, **who) |
| 134 | except subprocess.TimeoutExpired: |
| 135 | raise Wrong(f"{' '.join(cmd)} took longer than {timeout} s") |
| 136 | said = (p.stdout if out is None else p.stderr) or "" |
| 137 | if log: |
| 138 | log.write_text(said, encoding="utf-8") |
| 139 | tail = "\n".join(said.replace(NO_SANDBOX, "").strip().splitlines()[-25:]) |
| 140 | if tail: |
| 141 | print(tail, flush=True) |
| 142 | print(f"-- {time.monotonic() - began:.0f} s", flush=True) |
| 143 | if p.returncode != 0: |
| 144 | # with the first error it gave (Lean's, or Comparator's verdict), so the last line says why |
| 145 | why = next((line.strip() for line in said.splitlines() if re.match(r"(error|uncaught exception)\b", line.strip()) |
| 146 | and line.strip() != "error: build failed"), "") |
| 147 | raise Wrong(f"{' '.join(cmd)} ended with exit {p.returncode}" + (f": {why[:300]}" if why else "")) |
| 148 | return said |
| 149 | |
| 150 | |
| 151 | def kill_nobody() -> None: |
| 152 | """End every process of nobody at once: kill -1 from nobody reaches exactly those, itself included.""" |
| 153 | if ROOT: |
| 154 | subprocess.run(["bash", "-c", "kill -KILL -1"], user=NOBODY, group=NOBODY, extra_groups=[], |
| 155 | stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) |
| 156 | |
| 157 | |
| 158 | def give_lake(base: Path, project: Path, in_place: bool = False) -> None: |
| 159 | """The image's .lake for a project: its packages shared and read-only (a symbolic link), the rest a copy; in place, |
| 160 | the build is shared too, and whoever builds in the project writes into the image's own folder.""" |
| 161 | (project / ".lake").mkdir() |
| 162 | for entry in (base / ".lake").iterdir(): |
| 163 | if entry.name == "packages" or (in_place and entry.name == "build"): |
| 164 | (project / ".lake" / entry.name).symlink_to(entry) |
| 165 | elif entry.is_dir(): |
| 166 | shutil.copytree(entry, project / ".lake" / entry.name, symlinks=True) |
| 167 | else: |
| 168 | shutil.copy2(entry, project / ".lake" / entry.name) |
| 169 | |
| 170 | |
| 171 | def chown_nobody(folder: Path) -> None: |
| 172 | """Give a folder and what is in it to nobody. What is nobody's already is left alone: in a folder of the image |
| 173 | itself, a chown copies the file into the container.""" |
| 174 | if ROOT: |
| 175 | for here, dirs, files in os.walk(folder): |
| 176 | for path in [Path(here)] + [Path(here) / name for name in files + [d for d in dirs if (Path(here) / d).is_symlink()]]: |
| 177 | if os.lstat(path).st_uid != NOBODY: |
| 178 | os.lchown(path, NOBODY, NOBODY) |
| 179 | |
| 180 | |
| 181 | def targets(config: dict) -> list[str]: |
| 182 | axioms = config["permitted_axioms"] |
| 183 | return (QUOT if "Quot.sound" in axioms else []) + config.get("theorem_names", []) + axioms + PRIMITIVES \ |
| 184 | + config.get("definition_names", []) |
| 185 | |
| 186 | |
| 187 | EXPORT = ["lake", "env", "leanexport"] # build.json's export_command, set in main |
| 188 | |
| 189 | |
| 190 | def export(module: str, names: list[str], dest: Path, cwd: Path, timeout: int, nobody: bool, env: dict[str, str]) -> None: |
| 191 | with dest.open("w") as f: |
| 192 | run([*EXPORT, module, "--", *names], cwd, timeout, nobody=nobody, env=env, out=f) |
| 193 | print(f"-- {dest.name}: {dest.stat().st_size / 1e6:.0f} MB", flush=True) |
| 194 | |
| 195 | |
| 196 | def judge_command(spec: dict, config: Path, challenge: Path, solution: Path, modules: tuple[str, str], folder: Path) -> tuple[list[str], dict[str, str]]: |
| 197 | """How Comparator is started on two exports, and what is added to its environment.""" |
| 198 | if spec.get("comparator_kind", "lake") != "standalone": |
| 199 | return spec["comparator_command"] + [str(config), "--challenge-from-export", str(challenge), "--solution-from-export", str(solution), |
| 200 | "--inadvisably-no-sandbox"], {} |
| 201 | # the standalone Comparator starts everything through landrun: this stands in for it (the module docstring says why) |
| 202 | for module in modules: |
| 203 | if not re.fullmatch(r"[\w.'«»]+", module): |
| 204 | raise Wrong(f"{module!r} is not a module name") |
| 205 | stand_in = folder / f"{config.stem}-landrun" |
| 206 | serve = "".join(f" {shlex.quote('lean4export ' + m)}) exec cat {shlex.quote(str(e))} ;;\n" for m, e in dict(zip(modules, (challenge, solution))).items()) |
| 207 | stand_in.write_text('#!/bin/sh\n# in landrun\'s place: the builds are done, and the exports made\n' |
| 208 | 'while [ $# -gt 0 ] && [ "$1" != -- ]; do shift; done\n[ $# -gt 1 ] || exit 2\nshift\n' |
| 209 | f'case "$1 $2" in\n "lake build") exit 0 ;;\n{serve} lake\\ *|lean4export\\ *) echo "not served: $*" >&2; exit 2 ;;\nesac\nexec "$@"\n') |
| 210 | stand_in.chmod(0o755) |
| 211 | (folder / ".lake").mkdir(exist_ok=True) # Comparator makes it in its folder otherwise, which nobody cannot |
| 212 | return spec["comparator_command"] + [str(config)], {"COMPARATOR_LANDRUN": str(stand_in)} |
| 213 | |
| 214 | |
| 215 | def imports_of(path: Path) -> list[str]: |
| 216 | """The modules a file's header imports.""" |
| 217 | found = [] |
| 218 | for line in path.read_text(encoding="utf-8").splitlines(): |
| 219 | m = re.match(r"\s*(?:public\s+)?import\s+(.+)", line) |
| 220 | if m: |
| 221 | found += m.group(1).split() |
| 222 | elif line.strip() and not line.lstrip().startswith(("--", "/-", "module", "prelude")): |
| 223 | break |
| 224 | return found |
| 225 | |
| 226 | |
| 227 | def main(argv: list[str]) -> int: |
| 228 | if len(argv) < 2: |
| 229 | print(__doc__.strip().splitlines()[2]) |
| 230 | return 2 |
| 231 | tree = Path(argv[1]).resolve() |
| 232 | spec = json.loads((Path(argv[2]) if len(argv) > 2 else Path(__file__).with_name("build.json")).read_text(encoding="utf-8")) |
| 233 | approved = Path(os.environ.get("PROOF_APPROVED") or Path(__file__).resolve().parents[1]) |
| 234 | base = Path(os.environ.get("PROOF_BASE", "/opt/proof")) |
| 235 | timeout = int(spec.get("timeout", 6 * 3600)) |
| 236 | logs = Path(os.environ.get("BUILD_LOGS", ".")).resolve() |
| 237 | logs.mkdir(parents=True, exist_ok=True) |
| 238 | work = Path(tempfile.mkdtemp(prefix="build-")) |
| 239 | os.chmod(work, 0o711) # nobody passes through to its own folders, and reads nothing else here |
| 240 | try: |
| 241 | if not (tree / "lakefile.toml").is_file(): |
| 242 | print("Nothing to check yet: the commit has no lakefile.toml.") |
| 243 | return 0 |
| 244 | if not (base / ".lake").is_dir(): |
| 245 | raise Wrong(f"{base}/.lake is not there: this check runs in the project's Lean image (docker/README.md)") |
| 246 | # 4. the image's toolchain (read, not run) |
| 247 | want = (tree / "lean-toolchain").read_text(encoding="utf-8").strip() |
| 248 | have = (base / "lean-toolchain").read_text(encoding="utf-8").strip() |
| 249 | if want != have: |
| 250 | raise Wrong(f"the commit asks for {want}; the image has {have}: a toolchain bump needs a new image (docker/README.md)") |
| 251 | global BIN, EXPORT |
| 252 | BIN = toolchain_bin(base) |
| 253 | # Lake starts a `lean` for every core it sees, and the runner's --cpus is a share of time, not a count of |
| 254 | # cores: on a 128-core host a job of 4 CPUs would start 128 (lean-poincare, 12-02) |
| 255 | if os.environ.get("SLURM_CPUS_PER_TASK"): |
| 256 | os.environ.setdefault("LEAN_NUM_THREADS", os.environ["SLURM_CPUS_PER_TASK"]) |
| 257 | EXPORT = spec.get("export_command", EXPORT) |
| 258 | configs = [(name, json.loads((approved / name).read_text(encoding="utf-8"))) for name in spec.get("comparator", [])] |
| 259 | theorems = spec.get("theorems", []) if spec.get("axioms_file") else [] |
| 260 | # a push of a project that replays once a round gets the build and its own account of the axioms, no judge |
| 261 | replay = spec.get("replay", "push") != "round" or os.environ.get("BUILD_REPLAY") == "1" |
| 262 | in_place = bool(spec.get("in_place")) |
| 263 | built = base / ".lake" / "build" |
| 264 | if in_place and ROOT and os.stat(built).st_uid != NOBODY: |
| 265 | raise Wrong(f"{built} is not nobody's: build.json's in_place needs an image made for it (docker/README.md)") |
| 266 | judge = work / "judge" |
| 267 | judge.mkdir() |
| 268 | # 1. the approved challenges, as root, before anything of the commit runs |
| 269 | if configs and replay: |
| 270 | mine = work / "approved" |
| 271 | # (not the commit's tree, nor the job's logs: on the runner both sit in the approved checkout, /work) |
| 272 | shutil.copytree(approved, mine, symlinks=True, ignore=lambda d, names: [n for n in names if n in (".git", ".lake") |
| 273 | or (Path(d) / n).resolve() in (tree, logs)]) |
| 274 | give_lake(base, mine, in_place) |
| 275 | for i, (name, config) in enumerate(configs): |
| 276 | run(["lake", "build", config["challenge_module"]], mine, timeout, logs / f"challenge-{i}.log") |
| 277 | export(config["challenge_module"], targets(config), judge / f"challenge-{i}.export", mine, timeout, False, None) |
| 278 | if in_place: |
| 279 | chown_nobody(built) # what root compiled there, the commit's Lake may have to write again |
| 280 | # 2. the commit, as nobody, in a folder of its own. In place, the image's build is from here on the commit's: |
| 281 | # nothing below reads it as approved |
| 282 | proof, home, solve = work / "proof", work / "home", work / "solve" |
| 283 | shutil.copytree(tree, proof, symlinks=True, ignore=shutil.ignore_patterns(".git", ".lake")) |
| 284 | give_lake(base, proof, in_place) |
| 285 | for folder in (home, solve): |
| 286 | folder.mkdir() |
| 287 | for folder in (proof, home, solve): |
| 288 | chown_nobody(folder) |
| 289 | env = env_for(home) |
| 290 | try: |
| 291 | out = run(["lake", "build"], proof, timeout, logs / "build.log", nobody=True, env=env) |
| 292 | # and every library the approved lakefile declares, whatever the commit's defaultTargets say (a key a pull |
| 293 | # request may change): a proof in a library left out of the default build was never compiled, and passed |
| 294 | # (12-01, Goldbach: Open/<Name>.lean, its library without globs) |
| 295 | approved_lakefile = approved / "lakefile.toml" |
| 296 | libs = [lib["name"] for lib in tomllib.loads(approved_lakefile.read_text(encoding="utf-8")).get("lean_lib", [])] if approved_lakefile.exists() else [] |
| 297 | if libs: |
| 298 | out += "\n" + run(["lake", "build", *libs], proof, timeout, logs / "build-libs.log", nobody=True, env=env) |
| 299 | frozen = tuple(spec.get("frozen", [])) |
| 300 | |
| 301 | def allowed(line: str) -> bool: |
| 302 | m = WHERE.search(line) |
| 303 | if not m: |
| 304 | return False |
| 305 | path = os.path.normpath(m.group(1)) # a library with srcDir "src" names src/../Challenge.lean |
| 306 | path = path[len(str(proof)) + 1:] if path.startswith(str(proof) + "/") else path |
| 307 | return path in frozen |
| 308 | sorries = [line for line in out.splitlines() if SORRY.search(line) and not allowed(line)] |
| 309 | if sorries: |
| 310 | print("\n".join(sorries[:20])) |
| 311 | raise Wrong(f"the build reports {len(sorries)} declaration(s) that use sorry") |
| 312 | reported = 0 |
| 313 | if not replay: |
| 314 | # what the commit's own Lean says its theorems rest on: a filter (the commit's code runs in that Lean), |
| 315 | # which the round's replay does not rely on |
| 316 | names = [t for _, config in configs for t in config.get("theorem_names", [])] + theorems |
| 317 | modules = [config["solution_module"] for _, config in configs] + (imports_of(approved / spec["axioms_file"]) if theorems else []) |
| 318 | (solve / "ShoalAxioms.lean").write_text("".join(f"import {m}\n" for m in dict.fromkeys(modules)) + "".join(f"#print axioms {t}\n" for t in names)) |
| 319 | chown_nobody(solve) |
| 320 | out = run(["lake", "env", "lean", str(solve / "ShoalAxioms.lean")], proof, timeout, logs / "axioms.log", nobody=True, env=env) if names else "" |
| 321 | for t in names: |
| 322 | found = re.findall(rf"'{re.escape(t)}' (does not depend on any axioms|depends on axioms: \[([^\]]*)\])", out) |
| 323 | extra = sorted({a for _, listed in found for a in listed.replace(",", " ").split()} - set(spec["permitted_axioms"])) |
| 324 | if extra: |
| 325 | raise Wrong(f"{t} depends on {', '.join(extra)}: only {', '.join(spec['permitted_axioms'])} are permitted") |
| 326 | if not found: |
| 327 | raise Wrong(f"Lean did not say which axioms {t} depends on") |
| 328 | reported, configs, theorems = len(names), [], [] |
| 329 | for i, (name, config) in enumerate(configs): |
| 330 | export(config["solution_module"], targets(config), solve / f"solution-{i}.export", proof, timeout, True, env) |
| 331 | if theorems: |
| 332 | # the theorems, in scope through the approved axioms file's imports, compiled as a module of their own |
| 333 | (solve / "ShoalTheorems.lean").write_text("".join(f"import {m}\n" for m in imports_of(approved / spec["axioms_file"]))) |
| 334 | chown_nobody(solve) |
| 335 | run(["lake", "env", "lean", "-R", str(solve), "-o", str(solve / "ShoalTheorems.olean"), str(solve / "ShoalTheorems.lean")], |
| 336 | proof, timeout, logs / "theorems.log", nobody=True, env=env) |
| 337 | config = {"permitted_axioms": spec["permitted_axioms"], "theorem_names": theorems} |
| 338 | export("ShoalTheorems", targets(config), solve / "theorems.export", proof, timeout, True, |
| 339 | {**env, "LEAN_PATH": str(solve)}) |
| 340 | finally: |
| 341 | kill_nobody() |
| 342 | # 3. the judge, as nobody, on the exports alone |
| 343 | for i, (name, config) in enumerate(configs): |
| 344 | # the configuration as parsed, where nobody can read it: the runner's job folder is closed to others (12-01) |
| 345 | mine_config = judge / f"{i}-{Path(name).name}" |
| 346 | mine_config.write_text(json.dumps(config)) |
| 347 | cmd, more = judge_command(spec, mine_config, judge / f"challenge-{i}.export", solve / f"solution-{i}.export", |
| 348 | (config["challenge_module"], config["solution_module"]), judge) |
| 349 | out = run(cmd, judge, timeout, logs / f"comparator-{i}.log", nobody=True, env={**env_for(judge), **more}) |
| 350 | missing = [s for s in spec["comparator_success"] if s not in out] |
| 351 | if missing: |
| 352 | raise Wrong(f"Comparator on {name} did not say: {missing[0]}") |
| 353 | if theorems: |
| 354 | # Comparator with the theorems' export as both sides: the statements trivially agree, so what it judges is |
| 355 | # the axioms and the kernel's replay |
| 356 | gen = judge / "theorems.json" |
| 357 | gen.write_text(json.dumps({"challenge_module": "ShoalTheorems", "solution_module": "ShoalTheorems", "theorem_names": theorems, |
| 358 | "permitted_axioms": spec["permitted_axioms"]})) |
| 359 | cmd, more = judge_command(spec, gen, solve / "theorems.export", solve / "theorems.export", ("ShoalTheorems", "ShoalTheorems"), judge) |
| 360 | out = run(cmd, judge, timeout, logs / "axioms.log", nobody=True, env={**env_for(judge), **more}) |
| 361 | if "Your solution is okay!" not in out: |
| 362 | raise Wrong("Comparator did not accept the theorems' axioms") |
| 363 | said = ["lake build passes with no sorry"] |
| 364 | if reported: |
| 365 | said.append(f"{reported} theorem(s) report {', '.join(spec['permitted_axioms'])} only") |
| 366 | if not replay: |
| 367 | said.append("not replayed: Comparator judges this project once per maintainer round") |
| 368 | if theorems: |
| 369 | said.append(f"{len(theorems)} theorem(s) on {', '.join(spec['permitted_axioms'])} only") |
| 370 | if configs: |
| 371 | said.append(f"Comparator accepts {', '.join(name for name, _ in configs)}") |
| 372 | print("ok: " + "; ".join(said)) |
| 373 | return 0 |
| 374 | except Wrong as e: |
| 375 | print(f"FAILED: {e}") |
| 376 | return 1 |
| 377 | except (OSError, ValueError, KeyError) as e: |
| 378 | print(f"FAILED: {e}") |
| 379 | return 1 |
| 380 | finally: |
| 381 | kill_nobody() |
| 382 | shutil.rmtree(work, ignore_errors=True) |
| 383 | |
| 384 | |
| 385 | if __name__ == "__main__": |
| 386 | sys.exit(main(sys.argv)) |