Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/real-analysis/real-analysis-continuity-d1-e0000/environment/DockerfileAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-e0000/environment/workdir/Solution.leanAdded+6
- tasks/real-analysis/real-analysis-continuity-d1-e0000/instruction.mdAdded+12
- tasks/real-analysis/real-analysis-continuity-d1-e0000/solution/Solution.leanAdded+11
- tasks/real-analysis/real-analysis-continuity-d1-e0000/solution/solve.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-e0000/task.tomlAdded+25
- tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/Verify.leanAdded+135
- tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/grade.pyAdded+127
- tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/spec.jsonAdded+9
- tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/test.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-e0012/environment/DockerfileAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-e0012/environment/workdir/Solution.leanAdded+6
- tasks/real-analysis/real-analysis-continuity-d1-e0012/instruction.mdAdded+12
- tasks/real-analysis/real-analysis-continuity-d1-e0012/solution/Solution.leanAdded+11
- tasks/real-analysis/real-analysis-continuity-d1-e0012/solution/solve.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-e0012/task.tomlAdded+25
- tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/Verify.leanAdded+135
- tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/grade.pyAdded+127
- tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/spec.jsonAdded+9
- tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/test.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0012/environment/DockerfileAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0012/environment/workdir/Solution.leanAdded+6
- tasks/real-analysis/real-analysis-continuity-d1-t0012/instruction.mdAdded+12
- tasks/real-analysis/real-analysis-continuity-d1-t0012/solution/Solution.leanAdded+11
- tasks/real-analysis/real-analysis-continuity-d1-t0012/solution/solve.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0012/task.tomlAdded+25
- tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/Verify.leanAdded+135
- tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/grade.pyAdded+127
- tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/spec.jsonAdded+9
- tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/test.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0024/environment/DockerfileAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0024/environment/workdir/Solution.leanAdded+6
- tasks/real-analysis/real-analysis-continuity-d1-t0024/instruction.mdAdded+12
- tasks/real-analysis/real-analysis-continuity-d1-t0024/solution/Solution.leanAdded+11
- tasks/real-analysis/real-analysis-continuity-d1-t0024/solution/solve.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0024/task.tomlAdded+25
- tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/Verify.leanAdded+135
- tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/grade.pyAdded+127
- tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/spec.jsonAdded+9
- tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/test.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0048/environment/DockerfileAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0048/environment/workdir/Solution.leanAdded+6
- tasks/real-analysis/real-analysis-continuity-d1-t0048/instruction.mdAdded+12
- tasks/real-analysis/real-analysis-continuity-d1-t0048/solution/Solution.leanAdded+11
- tasks/real-analysis/real-analysis-continuity-d1-t0048/solution/solve.shAdded+3
- tasks/real-analysis/real-analysis-continuity-d1-t0048/task.tomlAdded+25
- tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/Verify.leanAdded+135
- tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/grade.pyAdded+127
- tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/spec.jsonAdded+9
- tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/test.shAdded+3
123FROM lean-arenaWORKDIR /appCOPY workdir/ /app/123456import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-4 : ℝ) * x + (3 : ℝ)) - ((-4 : ℝ) * (0 : ℝ) + (3 : ℝ))| < ε := by sorry123456789101112# Prove continuity from the epsilon-delta definition
Prove, from the epsilon-delta definition, that \(f(x) = -4x + 3\) is continuous at \(x_0 = 0\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\).
## What to do
`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof.
- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors.- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.- The reward is 1 if the theorem is proved and 0 otherwise.1234567891011import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-4 : ℝ) * x + (3 : ℝ)) - ((-4 : ℝ) * (0 : ℝ) + (3 : ℝ))| < ε := by intro ε hε refine ⟨ε / (4 : ℝ), by positivity, fun x hx => ?_⟩ have e : ((-4 : ℝ) * x + (3 : ℝ)) - ((-4 : ℝ) * (0 : ℝ) + (3 : ℝ)) = (-4 : ℝ) * (x - (0 : ℝ)) := by ring rw [e, abs_mul, show |(-4 : ℝ)| = (4 : ℝ) by norm_num] rw [lt_div_iff₀ (by norm_num)] at hx linarith123#!/bin/bashset -ecp /solution/Solution.lean /app/Solution.lean12345678910111213141516171819202122232425version = "1.0"
[metadata]author_name = "Renaissance Labs"author_email = "unknown"difficulty = "easy"category = "real-analysis"tags = ["real-analysis", "continuity", "msc-26", "eval", "lean4"]msc = "26"family = "continuity"split = "eval"seed = 10000
[verifier]timeout_sec = 900.0
[agent]timeout_sec = 1800.0
[environment]build_timeout_sec = 1800.0cpus = 2memory_mb = 6144storage_mb = 10240allow_internet = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/-Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
`--free a,b` names definitions the task asks the solver to write: their type must match thereference, their value is the solver's own. `--native` additionally accepts the axioms that`native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only`Lean`, never the submission, so nothing the submission declares (notation, macros, instances)can change how the check itself is read. It reads the reference module's constants from its .olean, imports thesubmission as an environment, and compares kernel terms:
1. every non-target constant the reference module declares (the task's own definitions) must be present in the submission with the same kind, type and value; 2. every target must be present with exactly the reference type; 3. the proof of every target may depend only on the three standard axioms.
It prints one JSON object per target and exits 0. The caller turns that into a reward.-/import Leanopen Lean
def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
/-- All axioms a constant depends on, found by walking every constant it mentions. -/partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do let mut seen : NameSet := {} let mut todo : Array Name := #[root] let mut out : Array Name := #[] while h : todo.size > 0 do let c := todo[todo.size - 1] todo := todo.pop if seen.contains c then continue seen := seen.insert c match env.find? c with | none => out := out.push (`missing ++ c) | some info => let mut es : Array Expr := #[info.type] match info with | .axiomInfo _ => out := out.push c | .defnInfo v => es := es.push v.value | .thmInfo v => es := es.push v.value | .opaqueInfo v => es := es.push v.value | .ctorInfo v => todo := todo.push v.induct | .inductInfo v => for k in v.ctors do todo := todo.push k | .recInfo v => for r in v.rules do es := es.push r.rhs | .quotInfo _ => pure () for e in es do for k in e.getUsedConstants do if !seen.contains k then todo := todo.push k return out
def kindOf : ConstantInfo → String | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
def valueOf : ConstantInfo → Option Expr | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value | _ => none
def sameDecl (a b : ConstantInfo) : Bool := kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
def jstr (s : String) : String := (Json.str s).compress
def isNativeAxiom (n : Name) : Bool := n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || n.components.any (fun c => c == `native_decide)
def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
partial def parseFlags (args : List String) (free : List Name) (native : Bool) : List Name × Bool × List String := match args with | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native | "--native" :: rest => parseFlags rest free true | rest => (free, native, rest)
def main (args : List String) : IO UInt32 := do let (free, native, args) := parseFlags args [] false match args with | refMod :: solMod :: targets => initSearchPath (← findSysroot) let refName := refMod.toName let solName := solMod.toName let targetNames := targets.map String.toName -- The reference is read straight from its .olean: that file holds exactly the constants the -- reference module declares, which is all the comparison needs. Only the submission is imported -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. let (refData, _) ← readModuleData (← findOLean refName) let mut refMap : Std.HashMap Name ConstantInfo := {} for i in [0:refData.constNames.size] do refMap := refMap.insert refData.constNames[i]! refData.constants[i]! let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) -- 1. the task's own definitions are unchanged let mut tampered : Array Name := #[] for c in refData.constNames do if targetNames.contains c then continue let some r := refMap[c]? | continue if free.contains c then match solEnv.find? c with | some s => if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c | none => tampered := tampered.push c continue if isUnder free c then continue match solEnv.find? c with | some s => if !sameDecl r s then tampered := tampered.push c | none => tampered := tampered.push c for t in targetNames do let mut ok := true let mut why := "" match refMap[t]?, solEnv.find? t with | none, _ => ok := false; why := "target missing from reference" | _, none => ok := false; why := "theorem not found in the submission" | some r, some s => if !tampered.isEmpty then ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" else if kindOf s != "theorem" && kindOf s != "def" then ok := false; why := s!"declared as {kindOf s}, not proved" else if r.levelParams != s.levelParams || r.type != s.type then ok := false; why := "the statement differs from the one asked for" else let ax := axiomsOf solEnv t let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) if !bad.isEmpty then ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" return 0 | _ => IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..." return 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#!/usr/bin/env python3"""Grade a Lean submission against a task. Standard library only.
python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
`spec.json` holds the hidden reference file, the target theorem names and their weights (seearena/core.py). The reward is the weighted share of targets that are proved: stated exactly asasked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing asecond kernel check by `leanchecker`. A submission that does not compile scores 0.
The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to thisfile, then /opt/arena/lean."""import argparse, json, os, shutil, subprocess, sys, tempfile, time
HERE = os.path.dirname(os.path.abspath(__file__))TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
def project(): for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) raise SystemExit("Lean project not found; set ARENA_LEAN")
_lp = {}def lean_path(proj): if proj not in _lp: cache = os.path.join(proj, ".lake", "lean_path.txt") if os.path.exists(cache): _lp[proj] = open(cache).read().strip() else: _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() try: open(cache, "w").write(_lp[proj]) except OSError: pass return _lp[proj]
class Slot: """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" def __enter__(self): self.path = None n = int(os.environ.get("ARENA_SLOTS", "0")) if not n: return self d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) while True: for i in range(n): p = os.path.join(d, "slot%d" % i) try: os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self except FileExistsError: try: pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) except (OSError, ValueError): shutil.rmtree(p, ignore_errors=True) # stale time.sleep(1) def __exit__(self, *a): if self.path: shutil.rmtree(self.path, ignore_errors=True)
def run(cmd, proj, extra_path=None, timeout=TIMEOUT): env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") with Slot(): try: r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) return r.returncode, (r.stdout + r.stderr) except subprocess.TimeoutExpired: return 124, "timed out after %d s" % timeout
def compile_lean(proj, src, work): """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages).""" olean = os.path.join(work, src + ".olean") if os.path.exists(olean): os.remove(olean) code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) return code == 0 and os.path.exists(olean), out
def grade(spec, solution_text, keep=None): proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") os.makedirs(work, exist_ok=True) targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} def fail(stage, log): res["stage"] = stage; res["log"] = log[-4000:] res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] return res try: open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) open(os.path.join(work, "Solution.lean"), "w").write(solution_text) ok, out = compile_lean(proj, "Reference", work) if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) ok, out = compile_lean(proj, "Solution", work) if not ok: return fail("the submission does not compile", out) code, out = run(["leanchecker", "Solution"], proj, work) if code != 0: return fail("the submission fails the kernel re-check", out) sub = "Solution"; flags = [] if spec.get("tests"): open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) ok, out = compile_lean(proj, "Tests", work) if not ok: return fail("the hidden tests do not pass", out) code, out = run(["leanchecker", "Tests"], proj, work) if code != 0: return fail("the tests fail the kernel re-check", out) sub = "Tests"; flags = ["--native"] if spec.get("free"): flags += ["--free", ",".join(spec["free"])] verify = os.path.join(HERE, "Verify.lean") if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) got = {} for line in out.splitlines(): if line.startswith("{"): try: j = json.loads(line); got[j["target"]] = j except ValueError: pass if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) res["targets"] = [got[t["name"]] for t in targets] res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) res["stage"] = "graded" return res finally: if not keep: shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) a = ap.parse_args() spec = json.load(open(a.spec, encoding="utf-8")) try: text = open(a.solution, encoding="utf-8").read() except OSError: text = None res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} print(json.dumps(res, indent=1, ensure_ascii=False)) if a.out: os.makedirs(a.out, exist_ok=True) open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)123456789{ "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-4 : ℝ) * x + (3 : ℝ)) - ((-4 : ℝ) * (0 : ℝ) + (3 : ℝ))| < ε := by\n sorry\n", "targets": [ { "name": "continuous_at", "weight": 1.0 } ]}123#!/bin/bashmkdir -p /logs/verifierpython3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt123FROM lean-arenaWORKDIR /appCOPY workdir/ /app/123456import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-3 : ℝ)| < δ → |((-6 : ℝ) * x + (-1 : ℝ)) - ((-6 : ℝ) * (-3 : ℝ) + (-1 : ℝ))| < ε := by sorry123456789101112# Prove continuity from the epsilon-delta definition
Prove, from the epsilon-delta definition, that \(f(x) = -6x - 1\) is continuous at \(x_0 = -3\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\).
## What to do
`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof.
- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors.- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.- The reward is 1 if the theorem is proved and 0 otherwise.1234567891011import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-3 : ℝ)| < δ → |((-6 : ℝ) * x + (-1 : ℝ)) - ((-6 : ℝ) * (-3 : ℝ) + (-1 : ℝ))| < ε := by intro ε hε refine ⟨ε / (6 : ℝ), by positivity, fun x hx => ?_⟩ have e : ((-6 : ℝ) * x + (-1 : ℝ)) - ((-6 : ℝ) * (-3 : ℝ) + (-1 : ℝ)) = (-6 : ℝ) * (x - (-3 : ℝ)) := by ring rw [e, abs_mul, show |(-6 : ℝ)| = (6 : ℝ) by norm_num] rw [lt_div_iff₀ (by norm_num)] at hx linarith123#!/bin/bashset -ecp /solution/Solution.lean /app/Solution.lean12345678910111213141516171819202122232425version = "1.0"
[metadata]author_name = "Renaissance Labs"author_email = "unknown"difficulty = "easy"category = "real-analysis"tags = ["real-analysis", "continuity", "msc-26", "eval", "lean4"]msc = "26"family = "continuity"split = "eval"seed = 10012
[verifier]timeout_sec = 900.0
[agent]timeout_sec = 1800.0
[environment]build_timeout_sec = 1800.0cpus = 2memory_mb = 6144storage_mb = 10240allow_internet = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/-Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
`--free a,b` names definitions the task asks the solver to write: their type must match thereference, their value is the solver's own. `--native` additionally accepts the axioms that`native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only`Lean`, never the submission, so nothing the submission declares (notation, macros, instances)can change how the check itself is read. It reads the reference module's constants from its .olean, imports thesubmission as an environment, and compares kernel terms:
1. every non-target constant the reference module declares (the task's own definitions) must be present in the submission with the same kind, type and value; 2. every target must be present with exactly the reference type; 3. the proof of every target may depend only on the three standard axioms.
It prints one JSON object per target and exits 0. The caller turns that into a reward.-/import Leanopen Lean
def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
/-- All axioms a constant depends on, found by walking every constant it mentions. -/partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do let mut seen : NameSet := {} let mut todo : Array Name := #[root] let mut out : Array Name := #[] while h : todo.size > 0 do let c := todo[todo.size - 1] todo := todo.pop if seen.contains c then continue seen := seen.insert c match env.find? c with | none => out := out.push (`missing ++ c) | some info => let mut es : Array Expr := #[info.type] match info with | .axiomInfo _ => out := out.push c | .defnInfo v => es := es.push v.value | .thmInfo v => es := es.push v.value | .opaqueInfo v => es := es.push v.value | .ctorInfo v => todo := todo.push v.induct | .inductInfo v => for k in v.ctors do todo := todo.push k | .recInfo v => for r in v.rules do es := es.push r.rhs | .quotInfo _ => pure () for e in es do for k in e.getUsedConstants do if !seen.contains k then todo := todo.push k return out
def kindOf : ConstantInfo → String | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
def valueOf : ConstantInfo → Option Expr | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value | _ => none
def sameDecl (a b : ConstantInfo) : Bool := kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
def jstr (s : String) : String := (Json.str s).compress
def isNativeAxiom (n : Name) : Bool := n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || n.components.any (fun c => c == `native_decide)
def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
partial def parseFlags (args : List String) (free : List Name) (native : Bool) : List Name × Bool × List String := match args with | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native | "--native" :: rest => parseFlags rest free true | rest => (free, native, rest)
def main (args : List String) : IO UInt32 := do let (free, native, args) := parseFlags args [] false match args with | refMod :: solMod :: targets => initSearchPath (← findSysroot) let refName := refMod.toName let solName := solMod.toName let targetNames := targets.map String.toName -- The reference is read straight from its .olean: that file holds exactly the constants the -- reference module declares, which is all the comparison needs. Only the submission is imported -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. let (refData, _) ← readModuleData (← findOLean refName) let mut refMap : Std.HashMap Name ConstantInfo := {} for i in [0:refData.constNames.size] do refMap := refMap.insert refData.constNames[i]! refData.constants[i]! let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) -- 1. the task's own definitions are unchanged let mut tampered : Array Name := #[] for c in refData.constNames do if targetNames.contains c then continue let some r := refMap[c]? | continue if free.contains c then match solEnv.find? c with | some s => if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c | none => tampered := tampered.push c continue if isUnder free c then continue match solEnv.find? c with | some s => if !sameDecl r s then tampered := tampered.push c | none => tampered := tampered.push c for t in targetNames do let mut ok := true let mut why := "" match refMap[t]?, solEnv.find? t with | none, _ => ok := false; why := "target missing from reference" | _, none => ok := false; why := "theorem not found in the submission" | some r, some s => if !tampered.isEmpty then ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" else if kindOf s != "theorem" && kindOf s != "def" then ok := false; why := s!"declared as {kindOf s}, not proved" else if r.levelParams != s.levelParams || r.type != s.type then ok := false; why := "the statement differs from the one asked for" else let ax := axiomsOf solEnv t let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) if !bad.isEmpty then ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" return 0 | _ => IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..." return 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#!/usr/bin/env python3"""Grade a Lean submission against a task. Standard library only.
python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
`spec.json` holds the hidden reference file, the target theorem names and their weights (seearena/core.py). The reward is the weighted share of targets that are proved: stated exactly asasked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing asecond kernel check by `leanchecker`. A submission that does not compile scores 0.
The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to thisfile, then /opt/arena/lean."""import argparse, json, os, shutil, subprocess, sys, tempfile, time
HERE = os.path.dirname(os.path.abspath(__file__))TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
def project(): for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) raise SystemExit("Lean project not found; set ARENA_LEAN")
_lp = {}def lean_path(proj): if proj not in _lp: cache = os.path.join(proj, ".lake", "lean_path.txt") if os.path.exists(cache): _lp[proj] = open(cache).read().strip() else: _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() try: open(cache, "w").write(_lp[proj]) except OSError: pass return _lp[proj]
class Slot: """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" def __enter__(self): self.path = None n = int(os.environ.get("ARENA_SLOTS", "0")) if not n: return self d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) while True: for i in range(n): p = os.path.join(d, "slot%d" % i) try: os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self except FileExistsError: try: pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) except (OSError, ValueError): shutil.rmtree(p, ignore_errors=True) # stale time.sleep(1) def __exit__(self, *a): if self.path: shutil.rmtree(self.path, ignore_errors=True)
def run(cmd, proj, extra_path=None, timeout=TIMEOUT): env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") with Slot(): try: r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) return r.returncode, (r.stdout + r.stderr) except subprocess.TimeoutExpired: return 124, "timed out after %d s" % timeout
def compile_lean(proj, src, work): """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages).""" olean = os.path.join(work, src + ".olean") if os.path.exists(olean): os.remove(olean) code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) return code == 0 and os.path.exists(olean), out
def grade(spec, solution_text, keep=None): proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") os.makedirs(work, exist_ok=True) targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} def fail(stage, log): res["stage"] = stage; res["log"] = log[-4000:] res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] return res try: open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) open(os.path.join(work, "Solution.lean"), "w").write(solution_text) ok, out = compile_lean(proj, "Reference", work) if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) ok, out = compile_lean(proj, "Solution", work) if not ok: return fail("the submission does not compile", out) code, out = run(["leanchecker", "Solution"], proj, work) if code != 0: return fail("the submission fails the kernel re-check", out) sub = "Solution"; flags = [] if spec.get("tests"): open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) ok, out = compile_lean(proj, "Tests", work) if not ok: return fail("the hidden tests do not pass", out) code, out = run(["leanchecker", "Tests"], proj, work) if code != 0: return fail("the tests fail the kernel re-check", out) sub = "Tests"; flags = ["--native"] if spec.get("free"): flags += ["--free", ",".join(spec["free"])] verify = os.path.join(HERE, "Verify.lean") if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) got = {} for line in out.splitlines(): if line.startswith("{"): try: j = json.loads(line); got[j["target"]] = j except ValueError: pass if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) res["targets"] = [got[t["name"]] for t in targets] res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) res["stage"] = "graded" return res finally: if not keep: shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) a = ap.parse_args() spec = json.load(open(a.spec, encoding="utf-8")) try: text = open(a.solution, encoding="utf-8").read() except OSError: text = None res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} print(json.dumps(res, indent=1, ensure_ascii=False)) if a.out: os.makedirs(a.out, exist_ok=True) open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)123456789{ "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-3 : ℝ)| < δ → |((-6 : ℝ) * x + (-1 : ℝ)) - ((-6 : ℝ) * (-3 : ℝ) + (-1 : ℝ))| < ε := by\n sorry\n", "targets": [ { "name": "continuous_at", "weight": 1.0 } ]}123#!/bin/bashmkdir -p /logs/verifierpython3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt123FROM lean-arenaWORKDIR /appCOPY workdir/ /app/123456import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-1 : ℝ) * x + (5 : ℝ)) - ((-1 : ℝ) * (0 : ℝ) + (5 : ℝ))| < ε := by sorry123456789101112# Prove continuity from the epsilon-delta definition
Prove, from the epsilon-delta definition, that \(f(x) = -x + 5\) is continuous at \(x_0 = 0\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\).
## What to do
`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof.
- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors.- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.- The reward is 1 if the theorem is proved and 0 otherwise.1234567891011import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-1 : ℝ) * x + (5 : ℝ)) - ((-1 : ℝ) * (0 : ℝ) + (5 : ℝ))| < ε := by intro ε hε refine ⟨ε / (1 : ℝ), by positivity, fun x hx => ?_⟩ have e : ((-1 : ℝ) * x + (5 : ℝ)) - ((-1 : ℝ) * (0 : ℝ) + (5 : ℝ)) = (-1 : ℝ) * (x - (0 : ℝ)) := by ring rw [e, abs_mul, show |(-1 : ℝ)| = (1 : ℝ) by norm_num] rw [lt_div_iff₀ (by norm_num)] at hx linarith123#!/bin/bashset -ecp /solution/Solution.lean /app/Solution.lean12345678910111213141516171819202122232425version = "1.0"
[metadata]author_name = "Renaissance Labs"author_email = "unknown"difficulty = "easy"category = "real-analysis"tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"]msc = "26"family = "continuity"split = "train"seed = 12
[verifier]timeout_sec = 900.0
[agent]timeout_sec = 1800.0
[environment]build_timeout_sec = 1800.0cpus = 2memory_mb = 6144storage_mb = 10240allow_internet = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/-Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
`--free a,b` names definitions the task asks the solver to write: their type must match thereference, their value is the solver's own. `--native` additionally accepts the axioms that`native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only`Lean`, never the submission, so nothing the submission declares (notation, macros, instances)can change how the check itself is read. It reads the reference module's constants from its .olean, imports thesubmission as an environment, and compares kernel terms:
1. every non-target constant the reference module declares (the task's own definitions) must be present in the submission with the same kind, type and value; 2. every target must be present with exactly the reference type; 3. the proof of every target may depend only on the three standard axioms.
It prints one JSON object per target and exits 0. The caller turns that into a reward.-/import Leanopen Lean
def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
/-- All axioms a constant depends on, found by walking every constant it mentions. -/partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do let mut seen : NameSet := {} let mut todo : Array Name := #[root] let mut out : Array Name := #[] while h : todo.size > 0 do let c := todo[todo.size - 1] todo := todo.pop if seen.contains c then continue seen := seen.insert c match env.find? c with | none => out := out.push (`missing ++ c) | some info => let mut es : Array Expr := #[info.type] match info with | .axiomInfo _ => out := out.push c | .defnInfo v => es := es.push v.value | .thmInfo v => es := es.push v.value | .opaqueInfo v => es := es.push v.value | .ctorInfo v => todo := todo.push v.induct | .inductInfo v => for k in v.ctors do todo := todo.push k | .recInfo v => for r in v.rules do es := es.push r.rhs | .quotInfo _ => pure () for e in es do for k in e.getUsedConstants do if !seen.contains k then todo := todo.push k return out
def kindOf : ConstantInfo → String | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
def valueOf : ConstantInfo → Option Expr | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value | _ => none
def sameDecl (a b : ConstantInfo) : Bool := kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
def jstr (s : String) : String := (Json.str s).compress
def isNativeAxiom (n : Name) : Bool := n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || n.components.any (fun c => c == `native_decide)
def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
partial def parseFlags (args : List String) (free : List Name) (native : Bool) : List Name × Bool × List String := match args with | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native | "--native" :: rest => parseFlags rest free true | rest => (free, native, rest)
def main (args : List String) : IO UInt32 := do let (free, native, args) := parseFlags args [] false match args with | refMod :: solMod :: targets => initSearchPath (← findSysroot) let refName := refMod.toName let solName := solMod.toName let targetNames := targets.map String.toName -- The reference is read straight from its .olean: that file holds exactly the constants the -- reference module declares, which is all the comparison needs. Only the submission is imported -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. let (refData, _) ← readModuleData (← findOLean refName) let mut refMap : Std.HashMap Name ConstantInfo := {} for i in [0:refData.constNames.size] do refMap := refMap.insert refData.constNames[i]! refData.constants[i]! let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) -- 1. the task's own definitions are unchanged let mut tampered : Array Name := #[] for c in refData.constNames do if targetNames.contains c then continue let some r := refMap[c]? | continue if free.contains c then match solEnv.find? c with | some s => if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c | none => tampered := tampered.push c continue if isUnder free c then continue match solEnv.find? c with | some s => if !sameDecl r s then tampered := tampered.push c | none => tampered := tampered.push c for t in targetNames do let mut ok := true let mut why := "" match refMap[t]?, solEnv.find? t with | none, _ => ok := false; why := "target missing from reference" | _, none => ok := false; why := "theorem not found in the submission" | some r, some s => if !tampered.isEmpty then ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" else if kindOf s != "theorem" && kindOf s != "def" then ok := false; why := s!"declared as {kindOf s}, not proved" else if r.levelParams != s.levelParams || r.type != s.type then ok := false; why := "the statement differs from the one asked for" else let ax := axiomsOf solEnv t let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) if !bad.isEmpty then ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" return 0 | _ => IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..." return 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#!/usr/bin/env python3"""Grade a Lean submission against a task. Standard library only.
python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
`spec.json` holds the hidden reference file, the target theorem names and their weights (seearena/core.py). The reward is the weighted share of targets that are proved: stated exactly asasked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing asecond kernel check by `leanchecker`. A submission that does not compile scores 0.
The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to thisfile, then /opt/arena/lean."""import argparse, json, os, shutil, subprocess, sys, tempfile, time
HERE = os.path.dirname(os.path.abspath(__file__))TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
def project(): for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) raise SystemExit("Lean project not found; set ARENA_LEAN")
_lp = {}def lean_path(proj): if proj not in _lp: cache = os.path.join(proj, ".lake", "lean_path.txt") if os.path.exists(cache): _lp[proj] = open(cache).read().strip() else: _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() try: open(cache, "w").write(_lp[proj]) except OSError: pass return _lp[proj]
class Slot: """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" def __enter__(self): self.path = None n = int(os.environ.get("ARENA_SLOTS", "0")) if not n: return self d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) while True: for i in range(n): p = os.path.join(d, "slot%d" % i) try: os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self except FileExistsError: try: pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) except (OSError, ValueError): shutil.rmtree(p, ignore_errors=True) # stale time.sleep(1) def __exit__(self, *a): if self.path: shutil.rmtree(self.path, ignore_errors=True)
def run(cmd, proj, extra_path=None, timeout=TIMEOUT): env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") with Slot(): try: r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) return r.returncode, (r.stdout + r.stderr) except subprocess.TimeoutExpired: return 124, "timed out after %d s" % timeout
def compile_lean(proj, src, work): """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages).""" olean = os.path.join(work, src + ".olean") if os.path.exists(olean): os.remove(olean) code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) return code == 0 and os.path.exists(olean), out
def grade(spec, solution_text, keep=None): proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") os.makedirs(work, exist_ok=True) targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} def fail(stage, log): res["stage"] = stage; res["log"] = log[-4000:] res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] return res try: open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) open(os.path.join(work, "Solution.lean"), "w").write(solution_text) ok, out = compile_lean(proj, "Reference", work) if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) ok, out = compile_lean(proj, "Solution", work) if not ok: return fail("the submission does not compile", out) code, out = run(["leanchecker", "Solution"], proj, work) if code != 0: return fail("the submission fails the kernel re-check", out) sub = "Solution"; flags = [] if spec.get("tests"): open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) ok, out = compile_lean(proj, "Tests", work) if not ok: return fail("the hidden tests do not pass", out) code, out = run(["leanchecker", "Tests"], proj, work) if code != 0: return fail("the tests fail the kernel re-check", out) sub = "Tests"; flags = ["--native"] if spec.get("free"): flags += ["--free", ",".join(spec["free"])] verify = os.path.join(HERE, "Verify.lean") if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) got = {} for line in out.splitlines(): if line.startswith("{"): try: j = json.loads(line); got[j["target"]] = j except ValueError: pass if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) res["targets"] = [got[t["name"]] for t in targets] res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) res["stage"] = "graded" return res finally: if not keep: shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) a = ap.parse_args() spec = json.load(open(a.spec, encoding="utf-8")) try: text = open(a.solution, encoding="utf-8").read() except OSError: text = None res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} print(json.dumps(res, indent=1, ensure_ascii=False)) if a.out: os.makedirs(a.out, exist_ok=True) open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)123456789{ "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-1 : ℝ) * x + (5 : ℝ)) - ((-1 : ℝ) * (0 : ℝ) + (5 : ℝ))| < ε := by\n sorry\n", "targets": [ { "name": "continuous_at", "weight": 1.0 } ]}123#!/bin/bashmkdir -p /logs/verifierpython3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt123FROM lean-arenaWORKDIR /appCOPY workdir/ /app/123456import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((7 : ℝ) * x + (-1 : ℝ)) - ((7 : ℝ) * (-4 : ℝ) + (-1 : ℝ))| < ε := by sorry123456789101112# Prove continuity from the epsilon-delta definition
Prove, from the epsilon-delta definition, that \(f(x) = 7x - 1\) is continuous at \(x_0 = -4\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\).
## What to do
`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof.
- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors.- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.- The reward is 1 if the theorem is proved and 0 otherwise.1234567891011import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((7 : ℝ) * x + (-1 : ℝ)) - ((7 : ℝ) * (-4 : ℝ) + (-1 : ℝ))| < ε := by intro ε hε refine ⟨ε / (7 : ℝ), by positivity, fun x hx => ?_⟩ have e : ((7 : ℝ) * x + (-1 : ℝ)) - ((7 : ℝ) * (-4 : ℝ) + (-1 : ℝ)) = (7 : ℝ) * (x - (-4 : ℝ)) := by ring rw [e, abs_mul, show |(7 : ℝ)| = (7 : ℝ) by norm_num] rw [lt_div_iff₀ (by norm_num)] at hx linarith123#!/bin/bashset -ecp /solution/Solution.lean /app/Solution.lean12345678910111213141516171819202122232425version = "1.0"
[metadata]author_name = "Renaissance Labs"author_email = "unknown"difficulty = "easy"category = "real-analysis"tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"]msc = "26"family = "continuity"split = "train"seed = 24
[verifier]timeout_sec = 900.0
[agent]timeout_sec = 1800.0
[environment]build_timeout_sec = 1800.0cpus = 2memory_mb = 6144storage_mb = 10240allow_internet = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/-Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
`--free a,b` names definitions the task asks the solver to write: their type must match thereference, their value is the solver's own. `--native` additionally accepts the axioms that`native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only`Lean`, never the submission, so nothing the submission declares (notation, macros, instances)can change how the check itself is read. It reads the reference module's constants from its .olean, imports thesubmission as an environment, and compares kernel terms:
1. every non-target constant the reference module declares (the task's own definitions) must be present in the submission with the same kind, type and value; 2. every target must be present with exactly the reference type; 3. the proof of every target may depend only on the three standard axioms.
It prints one JSON object per target and exits 0. The caller turns that into a reward.-/import Leanopen Lean
def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
/-- All axioms a constant depends on, found by walking every constant it mentions. -/partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do let mut seen : NameSet := {} let mut todo : Array Name := #[root] let mut out : Array Name := #[] while h : todo.size > 0 do let c := todo[todo.size - 1] todo := todo.pop if seen.contains c then continue seen := seen.insert c match env.find? c with | none => out := out.push (`missing ++ c) | some info => let mut es : Array Expr := #[info.type] match info with | .axiomInfo _ => out := out.push c | .defnInfo v => es := es.push v.value | .thmInfo v => es := es.push v.value | .opaqueInfo v => es := es.push v.value | .ctorInfo v => todo := todo.push v.induct | .inductInfo v => for k in v.ctors do todo := todo.push k | .recInfo v => for r in v.rules do es := es.push r.rhs | .quotInfo _ => pure () for e in es do for k in e.getUsedConstants do if !seen.contains k then todo := todo.push k return out
def kindOf : ConstantInfo → String | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
def valueOf : ConstantInfo → Option Expr | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value | _ => none
def sameDecl (a b : ConstantInfo) : Bool := kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
def jstr (s : String) : String := (Json.str s).compress
def isNativeAxiom (n : Name) : Bool := n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || n.components.any (fun c => c == `native_decide)
def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
partial def parseFlags (args : List String) (free : List Name) (native : Bool) : List Name × Bool × List String := match args with | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native | "--native" :: rest => parseFlags rest free true | rest => (free, native, rest)
def main (args : List String) : IO UInt32 := do let (free, native, args) := parseFlags args [] false match args with | refMod :: solMod :: targets => initSearchPath (← findSysroot) let refName := refMod.toName let solName := solMod.toName let targetNames := targets.map String.toName -- The reference is read straight from its .olean: that file holds exactly the constants the -- reference module declares, which is all the comparison needs. Only the submission is imported -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. let (refData, _) ← readModuleData (← findOLean refName) let mut refMap : Std.HashMap Name ConstantInfo := {} for i in [0:refData.constNames.size] do refMap := refMap.insert refData.constNames[i]! refData.constants[i]! let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) -- 1. the task's own definitions are unchanged let mut tampered : Array Name := #[] for c in refData.constNames do if targetNames.contains c then continue let some r := refMap[c]? | continue if free.contains c then match solEnv.find? c with | some s => if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c | none => tampered := tampered.push c continue if isUnder free c then continue match solEnv.find? c with | some s => if !sameDecl r s then tampered := tampered.push c | none => tampered := tampered.push c for t in targetNames do let mut ok := true let mut why := "" match refMap[t]?, solEnv.find? t with | none, _ => ok := false; why := "target missing from reference" | _, none => ok := false; why := "theorem not found in the submission" | some r, some s => if !tampered.isEmpty then ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" else if kindOf s != "theorem" && kindOf s != "def" then ok := false; why := s!"declared as {kindOf s}, not proved" else if r.levelParams != s.levelParams || r.type != s.type then ok := false; why := "the statement differs from the one asked for" else let ax := axiomsOf solEnv t let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) if !bad.isEmpty then ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" return 0 | _ => IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..." return 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#!/usr/bin/env python3"""Grade a Lean submission against a task. Standard library only.
python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
`spec.json` holds the hidden reference file, the target theorem names and their weights (seearena/core.py). The reward is the weighted share of targets that are proved: stated exactly asasked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing asecond kernel check by `leanchecker`. A submission that does not compile scores 0.
The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to thisfile, then /opt/arena/lean."""import argparse, json, os, shutil, subprocess, sys, tempfile, time
HERE = os.path.dirname(os.path.abspath(__file__))TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
def project(): for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) raise SystemExit("Lean project not found; set ARENA_LEAN")
_lp = {}def lean_path(proj): if proj not in _lp: cache = os.path.join(proj, ".lake", "lean_path.txt") if os.path.exists(cache): _lp[proj] = open(cache).read().strip() else: _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() try: open(cache, "w").write(_lp[proj]) except OSError: pass return _lp[proj]
class Slot: """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" def __enter__(self): self.path = None n = int(os.environ.get("ARENA_SLOTS", "0")) if not n: return self d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) while True: for i in range(n): p = os.path.join(d, "slot%d" % i) try: os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self except FileExistsError: try: pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) except (OSError, ValueError): shutil.rmtree(p, ignore_errors=True) # stale time.sleep(1) def __exit__(self, *a): if self.path: shutil.rmtree(self.path, ignore_errors=True)
def run(cmd, proj, extra_path=None, timeout=TIMEOUT): env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") with Slot(): try: r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) return r.returncode, (r.stdout + r.stderr) except subprocess.TimeoutExpired: return 124, "timed out after %d s" % timeout
def compile_lean(proj, src, work): """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages).""" olean = os.path.join(work, src + ".olean") if os.path.exists(olean): os.remove(olean) code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) return code == 0 and os.path.exists(olean), out
def grade(spec, solution_text, keep=None): proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") os.makedirs(work, exist_ok=True) targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} def fail(stage, log): res["stage"] = stage; res["log"] = log[-4000:] res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] return res try: open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) open(os.path.join(work, "Solution.lean"), "w").write(solution_text) ok, out = compile_lean(proj, "Reference", work) if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) ok, out = compile_lean(proj, "Solution", work) if not ok: return fail("the submission does not compile", out) code, out = run(["leanchecker", "Solution"], proj, work) if code != 0: return fail("the submission fails the kernel re-check", out) sub = "Solution"; flags = [] if spec.get("tests"): open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) ok, out = compile_lean(proj, "Tests", work) if not ok: return fail("the hidden tests do not pass", out) code, out = run(["leanchecker", "Tests"], proj, work) if code != 0: return fail("the tests fail the kernel re-check", out) sub = "Tests"; flags = ["--native"] if spec.get("free"): flags += ["--free", ",".join(spec["free"])] verify = os.path.join(HERE, "Verify.lean") if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) got = {} for line in out.splitlines(): if line.startswith("{"): try: j = json.loads(line); got[j["target"]] = j except ValueError: pass if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) res["targets"] = [got[t["name"]] for t in targets] res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) res["stage"] = "graded" return res finally: if not keep: shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) a = ap.parse_args() spec = json.load(open(a.spec, encoding="utf-8")) try: text = open(a.solution, encoding="utf-8").read() except OSError: text = None res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} print(json.dumps(res, indent=1, ensure_ascii=False)) if a.out: os.makedirs(a.out, exist_ok=True) open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)123456789{ "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((7 : ℝ) * x + (-1 : ℝ)) - ((7 : ℝ) * (-4 : ℝ) + (-1 : ℝ))| < ε := by\n sorry\n", "targets": [ { "name": "continuous_at", "weight": 1.0 } ]}123#!/bin/bashmkdir -p /logs/verifierpython3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt123FROM lean-arenaWORKDIR /appCOPY workdir/ /app/123456import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((4 : ℝ) * x + (3 : ℝ)) - ((4 : ℝ) * (-4 : ℝ) + (3 : ℝ))| < ε := by sorry123456789101112# Prove continuity from the epsilon-delta definition
Prove, from the epsilon-delta definition, that \(f(x) = 4x + 3\) is continuous at \(x_0 = -4\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\).
## What to do
`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof.
- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors.- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.- The reward is 1 if the theorem is proved and 0 otherwise.1234567891011import Mathlib
/-- Epsilon-delta continuity of a linear function at a point. -/theorem continuous_at : ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((4 : ℝ) * x + (3 : ℝ)) - ((4 : ℝ) * (-4 : ℝ) + (3 : ℝ))| < ε := by intro ε hε refine ⟨ε / (4 : ℝ), by positivity, fun x hx => ?_⟩ have e : ((4 : ℝ) * x + (3 : ℝ)) - ((4 : ℝ) * (-4 : ℝ) + (3 : ℝ)) = (4 : ℝ) * (x - (-4 : ℝ)) := by ring rw [e, abs_mul, show |(4 : ℝ)| = (4 : ℝ) by norm_num] rw [lt_div_iff₀ (by norm_num)] at hx linarith123#!/bin/bashset -ecp /solution/Solution.lean /app/Solution.lean12345678910111213141516171819202122232425version = "1.0"
[metadata]author_name = "Renaissance Labs"author_email = "unknown"difficulty = "easy"category = "real-analysis"tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"]msc = "26"family = "continuity"split = "train"seed = 48
[verifier]timeout_sec = 900.0
[agent]timeout_sec = 1800.0
[environment]build_timeout_sec = 1800.0cpus = 2memory_mb = 6144storage_mb = 10240allow_internet = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135/-Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
`--free a,b` names definitions the task asks the solver to write: their type must match thereference, their value is the solver's own. `--native` additionally accepts the axioms that`native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only`Lean`, never the submission, so nothing the submission declares (notation, macros, instances)can change how the check itself is read. It reads the reference module's constants from its .olean, imports thesubmission as an environment, and compares kernel terms:
1. every non-target constant the reference module declares (the task's own definitions) must be present in the submission with the same kind, type and value; 2. every target must be present with exactly the reference type; 3. the proof of every target may depend only on the three standard axioms.
It prints one JSON object per target and exits 0. The caller turns that into a reward.-/import Leanopen Lean
def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
/-- All axioms a constant depends on, found by walking every constant it mentions. -/partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do let mut seen : NameSet := {} let mut todo : Array Name := #[root] let mut out : Array Name := #[] while h : todo.size > 0 do let c := todo[todo.size - 1] todo := todo.pop if seen.contains c then continue seen := seen.insert c match env.find? c with | none => out := out.push (`missing ++ c) | some info => let mut es : Array Expr := #[info.type] match info with | .axiomInfo _ => out := out.push c | .defnInfo v => es := es.push v.value | .thmInfo v => es := es.push v.value | .opaqueInfo v => es := es.push v.value | .ctorInfo v => todo := todo.push v.induct | .inductInfo v => for k in v.ctors do todo := todo.push k | .recInfo v => for r in v.rules do es := es.push r.rhs | .quotInfo _ => pure () for e in es do for k in e.getUsedConstants do if !seen.contains k then todo := todo.push k return out
def kindOf : ConstantInfo → String | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
def valueOf : ConstantInfo → Option Expr | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value | _ => none
def sameDecl (a b : ConstantInfo) : Bool := kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
def jstr (s : String) : String := (Json.str s).compress
def isNativeAxiom (n : Name) : Bool := n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || n.components.any (fun c => c == `native_decide)
def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
partial def parseFlags (args : List String) (free : List Name) (native : Bool) : List Name × Bool × List String := match args with | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native | "--native" :: rest => parseFlags rest free true | rest => (free, native, rest)
def main (args : List String) : IO UInt32 := do let (free, native, args) := parseFlags args [] false match args with | refMod :: solMod :: targets => initSearchPath (← findSysroot) let refName := refMod.toName let solName := solMod.toName let targetNames := targets.map String.toName -- The reference is read straight from its .olean: that file holds exactly the constants the -- reference module declares, which is all the comparison needs. Only the submission is imported -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. let (refData, _) ← readModuleData (← findOLean refName) let mut refMap : Std.HashMap Name ConstantInfo := {} for i in [0:refData.constNames.size] do refMap := refMap.insert refData.constNames[i]! refData.constants[i]! let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) -- 1. the task's own definitions are unchanged let mut tampered : Array Name := #[] for c in refData.constNames do if targetNames.contains c then continue let some r := refMap[c]? | continue if free.contains c then match solEnv.find? c with | some s => if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c | none => tampered := tampered.push c continue if isUnder free c then continue match solEnv.find? c with | some s => if !sameDecl r s then tampered := tampered.push c | none => tampered := tampered.push c for t in targetNames do let mut ok := true let mut why := "" match refMap[t]?, solEnv.find? t with | none, _ => ok := false; why := "target missing from reference" | _, none => ok := false; why := "theorem not found in the submission" | some r, some s => if !tampered.isEmpty then ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" else if kindOf s != "theorem" && kindOf s != "def" then ok := false; why := s!"declared as {kindOf s}, not proved" else if r.levelParams != s.levelParams || r.type != s.type then ok := false; why := "the statement differs from the one asked for" else let ax := axiomsOf solEnv t let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) if !bad.isEmpty then ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" return 0 | _ => IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..." return 2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127#!/usr/bin/env python3"""Grade a Lean submission against a task. Standard library only.
python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
`spec.json` holds the hidden reference file, the target theorem names and their weights (seearena/core.py). The reward is the weighted share of targets that are proved: stated exactly asasked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing asecond kernel check by `leanchecker`. A submission that does not compile scores 0.
The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to thisfile, then /opt/arena/lean."""import argparse, json, os, shutil, subprocess, sys, tempfile, time
HERE = os.path.dirname(os.path.abspath(__file__))TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
def project(): for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) raise SystemExit("Lean project not found; set ARENA_LEAN")
_lp = {}def lean_path(proj): if proj not in _lp: cache = os.path.join(proj, ".lake", "lean_path.txt") if os.path.exists(cache): _lp[proj] = open(cache).read().strip() else: _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() try: open(cache, "w").write(_lp[proj]) except OSError: pass return _lp[proj]
class Slot: """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" def __enter__(self): self.path = None n = int(os.environ.get("ARENA_SLOTS", "0")) if not n: return self d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) while True: for i in range(n): p = os.path.join(d, "slot%d" % i) try: os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self except FileExistsError: try: pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) except (OSError, ValueError): shutil.rmtree(p, ignore_errors=True) # stale time.sleep(1) def __exit__(self, *a): if self.path: shutil.rmtree(self.path, ignore_errors=True)
def run(cmd, proj, extra_path=None, timeout=TIMEOUT): env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") with Slot(): try: r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) return r.returncode, (r.stdout + r.stderr) except subprocess.TimeoutExpired: return 124, "timed out after %d s" % timeout
def compile_lean(proj, src, work): """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages).""" olean = os.path.join(work, src + ".olean") if os.path.exists(olean): os.remove(olean) code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) return code == 0 and os.path.exists(olean), out
def grade(spec, solution_text, keep=None): proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") os.makedirs(work, exist_ok=True) targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} def fail(stage, log): res["stage"] = stage; res["log"] = log[-4000:] res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] return res try: open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) open(os.path.join(work, "Solution.lean"), "w").write(solution_text) ok, out = compile_lean(proj, "Reference", work) if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) ok, out = compile_lean(proj, "Solution", work) if not ok: return fail("the submission does not compile", out) code, out = run(["leanchecker", "Solution"], proj, work) if code != 0: return fail("the submission fails the kernel re-check", out) sub = "Solution"; flags = [] if spec.get("tests"): open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) ok, out = compile_lean(proj, "Tests", work) if not ok: return fail("the hidden tests do not pass", out) code, out = run(["leanchecker", "Tests"], proj, work) if code != 0: return fail("the tests fail the kernel re-check", out) sub = "Tests"; flags = ["--native"] if spec.get("free"): flags += ["--free", ",".join(spec["free"])] verify = os.path.join(HERE, "Verify.lean") if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) got = {} for line in out.splitlines(): if line.startswith("{"): try: j = json.loads(line); got[j["target"]] = j except ValueError: pass if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) res["targets"] = [got[t["name"]] for t in targets] res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) res["stage"] = "graded" return res finally: if not keep: shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) a = ap.parse_args() spec = json.load(open(a.spec, encoding="utf-8")) try: text = open(a.solution, encoding="utf-8").read() except OSError: text = None res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} print(json.dumps(res, indent=1, ensure_ascii=False)) if a.out: os.makedirs(a.out, exist_ok=True) open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)123456789{ "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((4 : ℝ) * x + (3 : ℝ)) - ((4 : ℝ) * (-4 : ℝ) + (3 : ℝ))| < ε := by\n sorry\n", "targets": [ { "name": "continuous_at", "weight": 1.0 } ]}123#!/bin/bashmkdir -p /logs/verifierpython3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txttasks/real-analysis/real-analysis-continuity-d1-e0000/environment/DockerfileAdded+3
tasks/real-analysis/real-analysis-continuity-d1-e0000/environment/workdir/Solution.leanAdded+6
tasks/real-analysis/real-analysis-continuity-d1-e0000/instruction.mdAdded+12
tasks/real-analysis/real-analysis-continuity-d1-e0000/solution/Solution.leanAdded+11
tasks/real-analysis/real-analysis-continuity-d1-e0000/solution/solve.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-e0000/task.tomlAdded+25
tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/Verify.leanAdded+135
tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/grade.pyAdded+127
tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/spec.jsonAdded+9
tasks/real-analysis/real-analysis-continuity-d1-e0000/tests/test.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-e0012/environment/DockerfileAdded+3
tasks/real-analysis/real-analysis-continuity-d1-e0012/environment/workdir/Solution.leanAdded+6
tasks/real-analysis/real-analysis-continuity-d1-e0012/instruction.mdAdded+12
tasks/real-analysis/real-analysis-continuity-d1-e0012/solution/Solution.leanAdded+11
tasks/real-analysis/real-analysis-continuity-d1-e0012/solution/solve.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-e0012/task.tomlAdded+25
tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/Verify.leanAdded+135
tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/grade.pyAdded+127
tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/spec.jsonAdded+9
tasks/real-analysis/real-analysis-continuity-d1-e0012/tests/test.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0012/environment/DockerfileAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0012/environment/workdir/Solution.leanAdded+6
tasks/real-analysis/real-analysis-continuity-d1-t0012/instruction.mdAdded+12
tasks/real-analysis/real-analysis-continuity-d1-t0012/solution/Solution.leanAdded+11
tasks/real-analysis/real-analysis-continuity-d1-t0012/solution/solve.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0012/task.tomlAdded+25
tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/Verify.leanAdded+135
tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/grade.pyAdded+127
tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/spec.jsonAdded+9
tasks/real-analysis/real-analysis-continuity-d1-t0012/tests/test.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0024/environment/DockerfileAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0024/environment/workdir/Solution.leanAdded+6
tasks/real-analysis/real-analysis-continuity-d1-t0024/instruction.mdAdded+12
tasks/real-analysis/real-analysis-continuity-d1-t0024/solution/Solution.leanAdded+11
tasks/real-analysis/real-analysis-continuity-d1-t0024/solution/solve.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0024/task.tomlAdded+25
tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/Verify.leanAdded+135
tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/grade.pyAdded+127
tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/spec.jsonAdded+9
tasks/real-analysis/real-analysis-continuity-d1-t0024/tests/test.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0048/environment/DockerfileAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0048/environment/workdir/Solution.leanAdded+6
tasks/real-analysis/real-analysis-continuity-d1-t0048/instruction.mdAdded+12
tasks/real-analysis/real-analysis-continuity-d1-t0048/solution/Solution.leanAdded+11
tasks/real-analysis/real-analysis-continuity-d1-t0048/solution/solve.shAdded+3
tasks/real-analysis/real-analysis-continuity-d1-t0048/task.tomlAdded+25
tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/Verify.leanAdded+135
tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/grade.pyAdded+127
tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/spec.jsonAdded+9
tasks/real-analysis/real-analysis-continuity-d1-t0048/tests/test.shAdded+3