#!/usr/bin/env python3 """The `build` check: the pushed commit compiles, uses no `sorry`, its theorems depend only on the permitted axioms, and Comparator accepts it against the approved challenge. Usage: build.py [] (BUILD_REPLAY=1: with Comparator even where build.json has "replay": "round", see below) This is leanprover-community/riemann-hypothesis's `build.yml` ("lake build", the merge queue's required check), made a check of this site, plus the Comparator run its README asks for. It runs in the project's Lean image (`docker/`), with no network, on the site's runner, as root in the runner's container. The commit's Lean is code the check runs: an `#eval`, an `initialize` or an elaborator in it runs while Lean compiles the file or imports it, and can print anything, including Comparator's success lines, or rewrite `lake` itself. So nothing the commit's build prints is trusted, and none of its code runs as root: 1. the approved version (the checkout this script is in, PROOF_APPROVED to override) is compiled as root, from the image's `.lake`, and each Comparator configuration's challenge module is exported (`export_command`) before anything of the commit runs. Its definitions, not the commit's, are what the statements mean; 2. the commit's tree is copied to a folder of its own and given the image's `.lake` (the dependencies, read-only, and the build of the approved main, made when the image was built): Lake then rebuilds only what the commit changed. As `nobody`, it runs `lake build`, and `lake build` of every library the approved lakefile.toml declares (the default targets are a key a pull request may change), which must end without error and with no module reporting a declaration that uses `sorry` except the challenge's own files (`frozen` in build.json: they state the theorems with `sorry` on purpose); then it exports each configuration's solution module, and the theorems of build.json; 3. every process of `nobody` is killed; then, as `nobody`, Comparator judges each export pair: the statements and the definitions they use as approved, no axiom beyond the permitted ones (a `sorry` is the axiom `sorryAx`), and a replay through Lean's kernel (and nanoda, where the configuration asks). The theorems of build.json are judged the same way against their own export: axioms and kernel. The judge reads text exports only and never loads an `.olean` of the commit, so what it prints is the verdict; 4. the commit's `lean-toolchain` must be the image's: a bump needs a new image (docker/README.md). Two Comparators are served (`comparator_kind` in build.json). "lake", the default: the toolchain's own (Lean 4.35 and later), `lake comparator --challenge-from-export … --solution-from-export … --inadvisably-no-sandbox`. "standalone": leanprover/comparator as a binary, for the toolchains before it, which builds and exports by itself through `landrun` and has no way to be handed exports. It is given one: COMPARATOR_LANDRUN names a stand-in this script writes, which does nothing for `lake build`, prints step 1's or step 2's export for `lean4export `, and starts an external kernel (nanoda_bin) as it is; Comparator's own comparison, axiom walk and kernels then run as upstream wrote them. Neither Comparator's own sandbox is what holds the commit here. bwrap cannot start in the runner's container (no user namespaces). landrun can (Landlock, measured on the production host 12-02), but upstream's guarantee needs three things the check does not have: nothing of the commit compiled before Comparator runs, a user who is not root, and no AF_UNIX (kernels before 7.1). Step 2, as `nobody`, stands in for both. Where the build is kept. With `"in_place": true` and an image whose `.lake/build` belongs to `nobody`, both sides use that folder itself: root first, for the approved challenge, then the commit, which may write anything there; nothing is read from it as approved after that, and the container is thrown away with what it wrote. A job then costs the disk of what it recompiled. Without it the build is copied for each side, as before (a 600 MB build: fine; 40 GB: not). When Comparator runs. A replay sends the whole proof through a kernel on one core: minutes for a small library, hours for a large one. With `"replay": "round"` in build.json a push gets step 2's build and `sorry` scan only, and the last line says so: that is the commit's own Lean reporting on itself, a filter and not a verdict. The replay (all four steps) is then run once per maintainer round, on main or on a batch of pull requests, with BUILD_REPLAY=1; its result is filed as a report. Without the key every push is replayed. The `sorry` scan of step 2 reads the commit's own build log, which the commit's code can write to: it catches an honest `sorry` anywhere in the library, and a hidden one cannot reach a judged theorem, since step 3 reads the axioms from the exports. Run as another user than root (tests, a machine of one's own) it does the same steps without switching to `nobody`. Each step's wall time is printed as it ends (`-- … s`). Its last line says what held, or the first thing that did not. Exit 0 passes, 1 fails. """ from __future__ import annotations import json import os import re import shlex import shutil import subprocess import sys import tempfile import time import tomllib from pathlib import Path SORRY = re.compile(r"declaration uses ['`]sorry['`]") # where a warning comes from: "warning: Challenge.lean:2:8: declaration uses `sorry`" (a path, possibly ./ or absolute) WHERE = re.compile(r"(?:^|\s)(?:\./)?([^\s:]+\.lean):\d+:\d+:") NOBODY = 65534 # nobody:nogroup in Ubuntu # What is exported with the theorems, as `lake comparator` asks when it exports by itself (Lean 4.35.0, # src/lake/Lake/CLI/Check.lean: builtinTargets, primitiveTargets): the kernel's built-in constants, Quot when Quot.sound # is permitted, then the configuration's theorems, axioms and definitions. PRIMITIVES = [ "Nat.add", "Nat.sub", "Nat.mul", "Nat.pow", "Nat.gcd", "Nat.div", "Nat.mod", "Nat.beq", "Nat.ble", "Nat.land", "Nat.lor", "Nat.xor", "Nat.shiftLeft", "Nat.shiftRight", "String.ofList", "Char.ofNat", "List", "eagerReduce", "Nat", "String", "String.mk", "Char", "optParam", "autoParam", "semiOutParam", "outParam", ] QUOT = ["Quot", "Quot.mk", "Quot.lift", "Quot.ind"] NO_SANDBOX = "WARNING: Sandbox disabled, this run is not trustworthy." class Wrong(Exception): pass ROOT = os.geteuid() == 0 def toolchain_bin(cwd: Path) -> str: """The toolchain's own bin folder (elan puts only lean, lake and leanchecker on PATH; Comparator looks nanoda_bin up on PATH), or nothing where elan is not there.""" try: return str(Path(subprocess.run(["elan", "which", "lean"], cwd=cwd, capture_output=True, text=True, timeout=60, check=True).stdout.strip()).parent) except (OSError, subprocess.SubprocessError): return "" BIN = "" # set in main: the toolchain's bin folder, first on every PATH below def env_for(home: Path) -> dict[str, str]: """What a process of the commit or the judge sees: the image's PATH and elan, a HOME of its own, and git told that the image's repositories, which root owns, are safe to read (Lake asks git about each package).""" keep = {k: v for k, v in os.environ.items() if k in ("PATH", "ELAN_HOME", "LANG", "LC_ALL", "LEAN_NUM_THREADS")} if BIN: keep["PATH"] = f"{BIN}:{keep.get('PATH', '/usr/bin:/bin')}" return {**keep, "HOME": str(home), "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "safe.directory", "GIT_CONFIG_VALUE_0": "*"} def run(cmd: list[str], cwd: Path, timeout: int, log: Path | None = None, *, nobody: bool = False, env: dict[str, str] | None = None, out=None) -> str: """Run a command, keep what it printed in `log`, and fail with its last lines if it fails. With `out`, its standard output goes to that file instead. With `nobody` (and as root), it runs as nobody, with no supplementary group.""" print(f"$ {' '.join(cmd)}", flush=True) who = {"user": NOBODY, "group": NOBODY, "extra_groups": []} if nobody and ROOT else {} began = time.monotonic() try: p = subprocess.run(cmd, cwd=cwd, stdout=out or subprocess.PIPE, stderr=subprocess.STDOUT if out is None else subprocess.PIPE, text=True, timeout=timeout, env=env, **who) except subprocess.TimeoutExpired: raise Wrong(f"{' '.join(cmd)} took longer than {timeout} s") said = (p.stdout if out is None else p.stderr) or "" if log: log.write_text(said, encoding="utf-8") tail = "\n".join(said.replace(NO_SANDBOX, "").strip().splitlines()[-25:]) if tail: print(tail, flush=True) print(f"-- {time.monotonic() - began:.0f} s", flush=True) if p.returncode != 0: # with the first error it gave (Lean's, or Comparator's verdict), so the last line says why why = next((line.strip() for line in said.splitlines() if re.match(r"(error|uncaught exception)\b", line.strip()) and line.strip() != "error: build failed"), "") raise Wrong(f"{' '.join(cmd)} ended with exit {p.returncode}" + (f": {why[:300]}" if why else "")) return said def kill_nobody() -> None: """End every process of nobody at once: kill -1 from nobody reaches exactly those, itself included.""" if ROOT: subprocess.run(["bash", "-c", "kill -KILL -1"], user=NOBODY, group=NOBODY, extra_groups=[], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def give_lake(base: Path, project: Path, in_place: bool = False) -> None: """The image's .lake for a project: its packages shared and read-only (a symbolic link), the rest a copy; in place, the build is shared too, and whoever builds in the project writes into the image's own folder.""" (project / ".lake").mkdir() for entry in (base / ".lake").iterdir(): if entry.name == "packages" or (in_place and entry.name == "build"): (project / ".lake" / entry.name).symlink_to(entry) elif entry.is_dir(): shutil.copytree(entry, project / ".lake" / entry.name, symlinks=True) else: shutil.copy2(entry, project / ".lake" / entry.name) def chown_nobody(folder: Path) -> None: """Give a folder and what is in it to nobody. What is nobody's already is left alone: in a folder of the image itself, a chown copies the file into the container.""" if ROOT: for here, dirs, files in os.walk(folder): for path in [Path(here)] + [Path(here) / name for name in files + [d for d in dirs if (Path(here) / d).is_symlink()]]: if os.lstat(path).st_uid != NOBODY: os.lchown(path, NOBODY, NOBODY) def targets(config: dict) -> list[str]: axioms = config["permitted_axioms"] return (QUOT if "Quot.sound" in axioms else []) + config.get("theorem_names", []) + axioms + PRIMITIVES \ + config.get("definition_names", []) EXPORT = ["lake", "env", "leanexport"] # build.json's export_command, set in main def export(module: str, names: list[str], dest: Path, cwd: Path, timeout: int, nobody: bool, env: dict[str, str]) -> None: with dest.open("w") as f: run([*EXPORT, module, "--", *names], cwd, timeout, nobody=nobody, env=env, out=f) print(f"-- {dest.name}: {dest.stat().st_size / 1e6:.0f} MB", flush=True) def judge_command(spec: dict, config: Path, challenge: Path, solution: Path, modules: tuple[str, str], folder: Path) -> tuple[list[str], dict[str, str]]: """How Comparator is started on two exports, and what is added to its environment.""" if spec.get("comparator_kind", "lake") != "standalone": return spec["comparator_command"] + [str(config), "--challenge-from-export", str(challenge), "--solution-from-export", str(solution), "--inadvisably-no-sandbox"], {} # the standalone Comparator starts everything through landrun: this stands in for it (the module docstring says why) for module in modules: if not re.fullmatch(r"[\w.'«»]+", module): raise Wrong(f"{module!r} is not a module name") stand_in = folder / f"{config.stem}-landrun" serve = "".join(f" {shlex.quote('lean4export ' + m)}) exec cat {shlex.quote(str(e))} ;;\n" for m, e in dict(zip(modules, (challenge, solution))).items()) stand_in.write_text('#!/bin/sh\n# in landrun\'s place: the builds are done, and the exports made\n' 'while [ $# -gt 0 ] && [ "$1" != -- ]; do shift; done\n[ $# -gt 1 ] || exit 2\nshift\n' f'case "$1 $2" in\n "lake build") exit 0 ;;\n{serve} lake\\ *|lean4export\\ *) echo "not served: $*" >&2; exit 2 ;;\nesac\nexec "$@"\n') stand_in.chmod(0o755) (folder / ".lake").mkdir(exist_ok=True) # Comparator makes it in its folder otherwise, which nobody cannot return spec["comparator_command"] + [str(config)], {"COMPARATOR_LANDRUN": str(stand_in)} def imports_of(path: Path) -> list[str]: """The modules a file's header imports.""" found = [] for line in path.read_text(encoding="utf-8").splitlines(): m = re.match(r"\s*(?:public\s+)?import\s+(.+)", line) if m: found += m.group(1).split() elif line.strip() and not line.lstrip().startswith(("--", "/-", "module", "prelude")): break return found def main(argv: list[str]) -> int: if len(argv) < 2: print(__doc__.strip().splitlines()[2]) return 2 tree = Path(argv[1]).resolve() spec = json.loads((Path(argv[2]) if len(argv) > 2 else Path(__file__).with_name("build.json")).read_text(encoding="utf-8")) approved = Path(os.environ.get("PROOF_APPROVED") or Path(__file__).resolve().parents[1]) base = Path(os.environ.get("PROOF_BASE", "/opt/proof")) timeout = int(spec.get("timeout", 6 * 3600)) logs = Path(os.environ.get("BUILD_LOGS", ".")).resolve() logs.mkdir(parents=True, exist_ok=True) work = Path(tempfile.mkdtemp(prefix="build-")) os.chmod(work, 0o711) # nobody passes through to its own folders, and reads nothing else here try: if not (tree / "lakefile.toml").is_file(): print("Nothing to check yet: the commit has no lakefile.toml.") return 0 if not (base / ".lake").is_dir(): raise Wrong(f"{base}/.lake is not there: this check runs in the project's Lean image (docker/README.md)") # 4. the image's toolchain (read, not run) want = (tree / "lean-toolchain").read_text(encoding="utf-8").strip() have = (base / "lean-toolchain").read_text(encoding="utf-8").strip() if want != have: raise Wrong(f"the commit asks for {want}; the image has {have}: a toolchain bump needs a new image (docker/README.md)") global BIN, EXPORT BIN = toolchain_bin(base) # Lake starts a `lean` for every core it sees, and the runner's --cpus is a share of time, not a count of # cores: on a 128-core host a job of 4 CPUs would start 128 (lean-poincare, 12-02) if os.environ.get("SLURM_CPUS_PER_TASK"): os.environ.setdefault("LEAN_NUM_THREADS", os.environ["SLURM_CPUS_PER_TASK"]) EXPORT = spec.get("export_command", EXPORT) configs = [(name, json.loads((approved / name).read_text(encoding="utf-8"))) for name in spec.get("comparator", [])] theorems = spec.get("theorems", []) if spec.get("axioms_file") else [] # a push of a project that replays once a round gets the build and its own account of the axioms, no judge replay = spec.get("replay", "push") != "round" or os.environ.get("BUILD_REPLAY") == "1" in_place = bool(spec.get("in_place")) built = base / ".lake" / "build" if in_place and ROOT and os.stat(built).st_uid != NOBODY: raise Wrong(f"{built} is not nobody's: build.json's in_place needs an image made for it (docker/README.md)") judge = work / "judge" judge.mkdir() # 1. the approved challenges, as root, before anything of the commit runs if configs and replay: mine = work / "approved" # (not the commit's tree, nor the job's logs: on the runner both sit in the approved checkout, /work) shutil.copytree(approved, mine, symlinks=True, ignore=lambda d, names: [n for n in names if n in (".git", ".lake") or (Path(d) / n).resolve() in (tree, logs)]) give_lake(base, mine, in_place) for i, (name, config) in enumerate(configs): run(["lake", "build", config["challenge_module"]], mine, timeout, logs / f"challenge-{i}.log") export(config["challenge_module"], targets(config), judge / f"challenge-{i}.export", mine, timeout, False, None) if in_place: chown_nobody(built) # what root compiled there, the commit's Lake may have to write again # 2. the commit, as nobody, in a folder of its own. In place, the image's build is from here on the commit's: # nothing below reads it as approved proof, home, solve = work / "proof", work / "home", work / "solve" shutil.copytree(tree, proof, symlinks=True, ignore=shutil.ignore_patterns(".git", ".lake")) give_lake(base, proof, in_place) for folder in (home, solve): folder.mkdir() for folder in (proof, home, solve): chown_nobody(folder) env = env_for(home) try: out = run(["lake", "build"], proof, timeout, logs / "build.log", nobody=True, env=env) # and every library the approved lakefile declares, whatever the commit's defaultTargets say (a key a pull # request may change): a proof in a library left out of the default build was never compiled, and passed # (12-01, Goldbach: Open/.lean, its library without globs) approved_lakefile = approved / "lakefile.toml" libs = [lib["name"] for lib in tomllib.loads(approved_lakefile.read_text(encoding="utf-8")).get("lean_lib", [])] if approved_lakefile.exists() else [] if libs: out += "\n" + run(["lake", "build", *libs], proof, timeout, logs / "build-libs.log", nobody=True, env=env) frozen = tuple(spec.get("frozen", [])) def allowed(line: str) -> bool: m = WHERE.search(line) if not m: return False path = os.path.normpath(m.group(1)) # a library with srcDir "src" names src/../Challenge.lean path = path[len(str(proof)) + 1:] if path.startswith(str(proof) + "/") else path return path in frozen sorries = [line for line in out.splitlines() if SORRY.search(line) and not allowed(line)] if sorries: print("\n".join(sorries[:20])) raise Wrong(f"the build reports {len(sorries)} declaration(s) that use sorry") reported = 0 if not replay: # what the commit's own Lean says its theorems rest on: a filter (the commit's code runs in that Lean), # which the round's replay does not rely on names = [t for _, config in configs for t in config.get("theorem_names", [])] + theorems modules = [config["solution_module"] for _, config in configs] + (imports_of(approved / spec["axioms_file"]) if theorems else []) (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)) chown_nobody(solve) out = run(["lake", "env", "lean", str(solve / "ShoalAxioms.lean")], proof, timeout, logs / "axioms.log", nobody=True, env=env) if names else "" for t in names: found = re.findall(rf"'{re.escape(t)}' (does not depend on any axioms|depends on axioms: \[([^\]]*)\])", out) extra = sorted({a for _, listed in found for a in listed.replace(",", " ").split()} - set(spec["permitted_axioms"])) if extra: raise Wrong(f"{t} depends on {', '.join(extra)}: only {', '.join(spec['permitted_axioms'])} are permitted") if not found: raise Wrong(f"Lean did not say which axioms {t} depends on") reported, configs, theorems = len(names), [], [] for i, (name, config) in enumerate(configs): export(config["solution_module"], targets(config), solve / f"solution-{i}.export", proof, timeout, True, env) if theorems: # the theorems, in scope through the approved axioms file's imports, compiled as a module of their own (solve / "ShoalTheorems.lean").write_text("".join(f"import {m}\n" for m in imports_of(approved / spec["axioms_file"]))) chown_nobody(solve) run(["lake", "env", "lean", "-R", str(solve), "-o", str(solve / "ShoalTheorems.olean"), str(solve / "ShoalTheorems.lean")], proof, timeout, logs / "theorems.log", nobody=True, env=env) config = {"permitted_axioms": spec["permitted_axioms"], "theorem_names": theorems} export("ShoalTheorems", targets(config), solve / "theorems.export", proof, timeout, True, {**env, "LEAN_PATH": str(solve)}) finally: kill_nobody() # 3. the judge, as nobody, on the exports alone for i, (name, config) in enumerate(configs): # the configuration as parsed, where nobody can read it: the runner's job folder is closed to others (12-01) mine_config = judge / f"{i}-{Path(name).name}" mine_config.write_text(json.dumps(config)) cmd, more = judge_command(spec, mine_config, judge / f"challenge-{i}.export", solve / f"solution-{i}.export", (config["challenge_module"], config["solution_module"]), judge) out = run(cmd, judge, timeout, logs / f"comparator-{i}.log", nobody=True, env={**env_for(judge), **more}) missing = [s for s in spec["comparator_success"] if s not in out] if missing: raise Wrong(f"Comparator on {name} did not say: {missing[0]}") if theorems: # Comparator with the theorems' export as both sides: the statements trivially agree, so what it judges is # the axioms and the kernel's replay gen = judge / "theorems.json" gen.write_text(json.dumps({"challenge_module": "ShoalTheorems", "solution_module": "ShoalTheorems", "theorem_names": theorems, "permitted_axioms": spec["permitted_axioms"]})) cmd, more = judge_command(spec, gen, solve / "theorems.export", solve / "theorems.export", ("ShoalTheorems", "ShoalTheorems"), judge) out = run(cmd, judge, timeout, logs / "axioms.log", nobody=True, env={**env_for(judge), **more}) if "Your solution is okay!" not in out: raise Wrong("Comparator did not accept the theorems' axioms") said = ["lake build passes with no sorry"] if reported: said.append(f"{reported} theorem(s) report {', '.join(spec['permitted_axioms'])} only") if not replay: said.append("not replayed: Comparator judges this project once per maintainer round") if theorems: said.append(f"{len(theorems)} theorem(s) on {', '.join(spec['permitted_axioms'])} only") if configs: said.append(f"Comparator accepts {', '.join(name for name, _ in configs)}") print("ok: " + "; ".join(said)) return 0 except Wrong as e: print(f"FAILED: {e}") return 1 except (OSError, ValueError, KeyError) as e: print(f"FAILED: {e}") return 1 finally: kill_nobody() shutil.rmtree(work, ignore_errors=True) if __name__ == "__main__": sys.exit(main(sys.argv))