diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8ee3c3909953c6e425fd3f4233ef892f021dcccc --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 8 * x + 1)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..618b3d416b668b1261342720d5cb07be0c2ebdf3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 8 * x + 1)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 8 * x + 1) := by + intro x y h + simp only at h + omega + exact Finset.card_image_of_injective s hinj diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..94b08e969d01d1dfad1864319c31722b5d70ac14 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) (h : Disjoint s t) : + ((s ∪ t).image (fun x : ℕ => 3 * x + 4)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ed5b27a35127610541394f8fcac2c453cf9462d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 3x + 4\) on the natural numbers and let \(s, t\) be disjoint finite sets of natural numbers. Prove that \(|f(s \cup t)| = |s| + |t|\). + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..14e79292a641b1dbd9c341abcb20bf2828dae331 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) (h : Disjoint s t) : + ((s ∪ t).image (fun x : ℕ => 3 * x + 4)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 3 * x + 4) := by + intro x y h + simp only at h + omega + rw [Finset.card_image_of_injective _ hinj, Finset.card_union_of_disjoint h] diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f0821b91470978f546ea6109691a72cd5f2e53bb --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 15 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2344f85b3d40689118582d0836b154c06b26f37b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s t : Finset ℕ) (h : Disjoint s t) :\n ((s ∪ t).image (fun x : ℕ => 3 * x + 4)).card = s.card + t.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..72ae596db11028604a668e45ec97708664f06da2 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Inclusion and exclusion for three finite sets. -/ +theorem incl_excl (s t u : Finset ℕ) : + (s ∪ t ∪ u).card + (s ∩ t).card + (s ∩ u).card + (t ∩ u).card = s.card + t.card + u.card + (s ∩ t ∩ u).card := by + sorry + +/-- The size of a union of three finite sets, in terms of the sizes of the intersections. -/ +theorem card_union_three (s t u : Finset ℕ) : + (s ∪ t ∪ u).card = s.card + t.card + u.card - (s ∩ t).card - (s ∩ u).card - (t ∩ u).card + (s ∩ t ∩ u).card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c42536ca088a12d8686fe239299b3f100eaa97ad --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(s, t, u\) be finite sets of natural numbers. First prove the identity \[|s \cup t \cup u| + |s \cap t| + |s \cap u| + |t \cap u| = |s| + |t| + |u| + |s \cap t \cap u|.\] Then use it to prove the following, where subtraction is truncated subtraction on the natural numbers: \[|s \cup t \cup u| = |s| + |t| + |u| - |s \cap t| - |s \cap u| - |t \cap u| + |s \cap t \cap u|.\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each 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 the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..abaae4ccb8f3e6b7e8429f49e7c1bbe1b0cafa90 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/solution/Solution.lean @@ -0,0 +1,26 @@ +import Mathlib + +/-- Inclusion and exclusion for three finite sets. -/ +theorem incl_excl (s t u : Finset ℕ) : + (s ∪ t ∪ u).card + (s ∩ t).card + (s ∩ u).card + (t ∩ u).card = s.card + t.card + u.card + (s ∩ t ∩ u).card := by + have h1 := Finset.card_union_add_card_inter (s ∪ t) u + have h2 := Finset.card_union_add_card_inter s t + have h3 := Finset.card_union_add_card_inter (s ∩ u) (t ∩ u) + have e1 : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u := Finset.union_inter_distrib_right s t u + have e2 : s ∩ u ∩ (t ∩ u) = s ∩ t ∩ u := by + ext x + simp only [Finset.mem_inter] + tauto + rw [e1] at h1 + rw [e2] at h3 + omega + +/-- The size of a union of three finite sets, in terms of the sizes of the intersections. -/ +theorem card_union_three (s t u : Finset ℕ) : + (s ∪ t ∪ u).card = s.card + t.card + u.card - (s ∩ t).card - (s ∩ u).card - (t ∩ u).card + (s ∩ t ∩ u).card := by + have h := incl_excl s t u + have h7 : (s ∩ t ∩ u).card ≤ (s ∪ t ∪ u).card := + Finset.card_le_card (fun x hx => by + simp only [Finset.mem_inter, Finset.mem_union] at hx ⊢ + tauto) + omega diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5466a96695482922a279509b7d21e8293161f56b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 24 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb007510c9294303098917ed34ec73e9ed8774d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Inclusion and exclusion for three finite sets. -/\ntheorem incl_excl (s t u : Finset ℕ) :\n (s ∪ t ∪ u).card + (s ∩ t).card + (s ∩ u).card + (t ∩ u).card = s.card + t.card + u.card + (s ∩ t ∩ u).card := by\n sorry\n\n/-- The size of a union of three finite sets, in terms of the sizes of the intersections. -/\ntheorem card_union_three (s t u : Finset ℕ) :\n (s ∪ t ∪ u).card = s.card + t.card + u.card - (s ∩ t).card - (s ∩ u).card - (t ∩ u).card + (s ∩ t ∩ u).card := by\n sorry\n", + "targets": [ + { + "name": "incl_excl", + "weight": 1.0 + }, + { + "name": "card_union_three", + "weight": 2.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0024/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..72ae596db11028604a668e45ec97708664f06da2 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Inclusion and exclusion for three finite sets. -/ +theorem incl_excl (s t u : Finset ℕ) : + (s ∪ t ∪ u).card + (s ∩ t).card + (s ∩ u).card + (t ∩ u).card = s.card + t.card + u.card + (s ∩ t ∩ u).card := by + sorry + +/-- The size of a union of three finite sets, in terms of the sizes of the intersections. -/ +theorem card_union_three (s t u : Finset ℕ) : + (s ∪ t ∪ u).card = s.card + t.card + u.card - (s ∩ t).card - (s ∩ u).card - (t ∩ u).card + (s ∩ t ∩ u).card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c42536ca088a12d8686fe239299b3f100eaa97ad --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(s, t, u\) be finite sets of natural numbers. First prove the identity \[|s \cup t \cup u| + |s \cap t| + |s \cap u| + |t \cap u| = |s| + |t| + |u| + |s \cap t \cap u|.\] Then use it to prove the following, where subtraction is truncated subtraction on the natural numbers: \[|s \cup t \cup u| = |s| + |t| + |u| - |s \cap t| - |s \cap u| - |t \cap u| + |s \cap t \cap u|.\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each 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 the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..abaae4ccb8f3e6b7e8429f49e7c1bbe1b0cafa90 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/solution/Solution.lean @@ -0,0 +1,26 @@ +import Mathlib + +/-- Inclusion and exclusion for three finite sets. -/ +theorem incl_excl (s t u : Finset ℕ) : + (s ∪ t ∪ u).card + (s ∩ t).card + (s ∩ u).card + (t ∩ u).card = s.card + t.card + u.card + (s ∩ t ∩ u).card := by + have h1 := Finset.card_union_add_card_inter (s ∪ t) u + have h2 := Finset.card_union_add_card_inter s t + have h3 := Finset.card_union_add_card_inter (s ∩ u) (t ∩ u) + have e1 : (s ∪ t) ∩ u = s ∩ u ∪ t ∩ u := Finset.union_inter_distrib_right s t u + have e2 : s ∩ u ∩ (t ∩ u) = s ∩ t ∩ u := by + ext x + simp only [Finset.mem_inter] + tauto + rw [e1] at h1 + rw [e2] at h3 + omega + +/-- The size of a union of three finite sets, in terms of the sizes of the intersections. -/ +theorem card_union_three (s t u : Finset ℕ) : + (s ∪ t ∪ u).card = s.card + t.card + u.card - (s ∩ t).card - (s ∩ u).card - (t ∩ u).card + (s ∩ t ∩ u).card := by + have h := incl_excl s t u + have h7 : (s ∩ t ∩ u).card ≤ (s ∪ t ∪ u).card := + Finset.card_le_card (fun x hx => by + simp only [Finset.mem_inter, Finset.mem_union] at hx ⊢ + tauto) + omega diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b6c208a32bb59494064e8938d8596739d963cfe4 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 78 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb007510c9294303098917ed34ec73e9ed8774d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Inclusion and exclusion for three finite sets. -/\ntheorem incl_excl (s t u : Finset ℕ) :\n (s ∪ t ∪ u).card + (s ∩ t).card + (s ∩ u).card + (t ∩ u).card = s.card + t.card + u.card + (s ∩ t ∩ u).card := by\n sorry\n\n/-- The size of a union of three finite sets, in terms of the sizes of the intersections. -/\ntheorem card_union_three (s t u : Finset ℕ) :\n (s ∪ t ∪ u).card = s.card + t.card + u.card - (s ∩ t).card - (s ∩ u).card - (t ∩ u).card + (s ∩ t ∩ u).card := by\n sorry\n", + "targets": [ + { + "name": "incl_excl", + "weight": 1.0 + }, + { + "name": "card_union_three", + "weight": 2.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0078/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5da320233f8269337ad7bb96503d031742d7debb --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun p q : ℕ × ℕ => p.1 + 4 * q.2 = q.1 + 4 * p.2) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d54eac7ef56d2756cb88c845c624d2c9debd67c7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On pairs of natural numbers define \((x_1, y_1) \sim (x_2, y_2) \iff x_1 + 4 y_2 = x_2 + 4 y_1\). Prove that \(\sim\) is an equivalence relation. + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a7f4a19512f61b51394b1f0b0b6e80ccdea31b1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/solution/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun p q : ℕ × ℕ => p.1 + 4 * q.2 = q.1 + 4 * p.2) := ⟨fun p => by omega, fun {p q} h => by omega, fun {p q r} h1 h2 => by omega⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..837fdbb125597c6f23a7144c3cdcc5c337997173 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "logic-and-sets" +tags = ["logic-and-sets", "relations", "msc-03", "train", "lean4"] +msc = "03" +family = "relations" +split = "train" +seed = 40 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..25275e77e077e77cdf16520025ae990869ad8107 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv :\n Equivalence (fun p q : ℕ × ℕ => p.1 + 4 * q.2 = q.1 + 4 * p.2) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0040/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7c457b45b9c480b6632fc66eff562353b7e6d01 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun p q : ℕ × ℕ => p.1 + 6 * q.2 = q.1 + 6 * p.2) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97f5a0ddc386406d657e6ce795c5ffcea63160a4 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On pairs of natural numbers define \((x_1, y_1) \sim (x_2, y_2) \iff x_1 + 6 y_2 = x_2 + 6 y_1\). Prove that \(\sim\) is an equivalence relation. + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9b5c92e948eb34b3b7fdc0943b5c45486f4b47c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/solution/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun p q : ℕ × ℕ => p.1 + 6 * q.2 = q.1 + 6 * p.2) := ⟨fun p => by omega, fun {p q} h => by omega, fun {p q r} h1 h2 => by omega⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a2a92f9e563cc6b8cb8c7fef43c21db9dd7e1e29 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "logic-and-sets" +tags = ["logic-and-sets", "relations", "msc-03", "train", "lean4"] +msc = "03" +family = "relations" +split = "train" +seed = 49 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..440ed3266db5306f420e3ad7f11a09f3b675fa43 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv :\n Equivalence (fun p q : ℕ × ℕ => p.1 + 6 * q.2 = q.1 + 6 * p.2) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0049/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..42fe0ac5258db13aa9446b6e9174467e3e58f1d9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => 3 ∣ x ^ 2 - y ^ 2) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9e8a018d0bc6e328c7d0af8c0605cfc2b6572f3b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On the integers define \(x \sim y \iff 3 \mid x^{2} - y^{2}\). Prove that \(\sim\) is an equivalence relation. + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..542b1be2663b362d664efcaf3ea3cba2ef0eb9de --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => 3 ∣ x ^ 2 - y ^ 2) := ⟨fun x => by simp, fun {x y} h => (dvd_sub_comm).mp h, fun {x y z} h1 h2 => by + have h := dvd_add h1 h2 + rwa [sub_add_sub_cancel] at h⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e54f225fb61c6a2d1bbc967435392f1b103825b3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "logic-and-sets" +tags = ["logic-and-sets", "relations", "msc-03", "train", "lean4"] +msc = "03" +family = "relations" +split = "train" +seed = 76 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b49a8a95cff5228705cd4f5345c475689e82f015 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv :\n Equivalence (fun x y : ℤ => 3 ∣ x ^ 2 - y ^ 2) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0076/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9eee95a6d4d0ea9fc91a51779abfd1cc24c05aa6 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/environment/workdir/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (q : ℤ) : + Equivalence (fun x y : ℤ => x ≡ y [ZMOD q]) := by + sorry + +/-- The relation is compatible with addition. -/ +theorem rel_add (q a b c d : ℤ) (h1 : a ≡ b [ZMOD q]) (h2 : c ≡ d [ZMOD q]) : + a + c ≡ b + d [ZMOD q] := by + sorry + +/-- The relation is compatible with taking powers. -/ +theorem rel_pow (q a b : ℤ) (k : ℕ) (h : a ≡ b [ZMOD q]) : + a ^ k ≡ b ^ k [ZMOD q] := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f3d2c172e7f1d2af1fc58656af9f224023744fa --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +For an integer \(q\), define a relation on the integers by \(x \sim y \iff x \equiv y \pmod{q}\). Prove three things: (1) \(\sim\) is an equivalence relation; (2) \(\sim\) is compatible with addition: if \(a \equiv b \pmod{q}\) and \(c \equiv d \pmod{q}\) then \(a+c \equiv b+d \pmod{q}\); (3) \(\sim\) is compatible with powers: if \(a \equiv b \pmod{q}\) then \(a^k \equiv b^k \pmod{q}\) for every natural number \(k\). + +## What to do + +`Solution.lean` in the working directory states 3 theorems in Lean 4 with Mathlib, with `sorry` in place of each 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 the share of the 3 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4cebafb0dba48c20c6d5b4009f9a0e41a195868f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (q : ℤ) : + Equivalence (fun x y : ℤ => x ≡ y [ZMOD q]) := ⟨fun x => Int.ModEq.refl x, fun {x y} h => h.symm, fun {x y z} h1 h2 => h1.trans h2⟩ + +/-- The relation is compatible with addition. -/ +theorem rel_add (q a b c d : ℤ) (h1 : a ≡ b [ZMOD q]) (h2 : c ≡ d [ZMOD q]) : + a + c ≡ b + d [ZMOD q] := h1.add h2 + +/-- The relation is compatible with taking powers. -/ +theorem rel_pow (q a b : ℤ) (k : ℕ) (h : a ≡ b [ZMOD q]) : + a ^ k ≡ b ^ k [ZMOD q] := h.pow k diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..264c52b24522ee270ab16d611dda806715077d44 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "relations", "msc-03", "eval", "lean4"] +msc = "03" +family = "relations" +split = "eval" +seed = 10007 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7152b168e4e3f641a47e615491d3590904d94389 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/spec.json @@ -0,0 +1,17 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv (q : ℤ) :\n Equivalence (fun x y : ℤ => x ≡ y [ZMOD q]) := by\n sorry\n\n/-- The relation is compatible with addition. -/\ntheorem rel_add (q a b c d : ℤ) (h1 : a ≡ b [ZMOD q]) (h2 : c ≡ d [ZMOD q]) :\n a + c ≡ b + d [ZMOD q] := by\n sorry\n\n/-- The relation is compatible with taking powers. -/\ntheorem rel_pow (q a b : ℤ) (k : ℕ) (h : a ≡ b [ZMOD q]) :\n a ^ k ≡ b ^ k [ZMOD q] := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + }, + { + "name": "rel_add", + "weight": 1.0 + }, + { + "name": "rel_pow", + "weight": 2.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6058e39ecc94e4006c5e6b6d8819f7333f403501 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (U S Y : Set α) : + (Y \ U)ᶜ = Yᶜ ∪ U := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8e5de248143be75873efaf6dec6d94660a62be8 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(U, S, Y\) be subsets of a type \(\alpha\). Prove the set identity \[(Y \setminus U)^{c} = Y^{c} \cup U.\] + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4c3e934bc25827d64883284b6d6592f394e87c6a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (U S Y : Set α) : + (Y \ U)ᶜ = Yᶜ ∪ U := by + ext x + simp only [Set.mem_union, Set.mem_inter_iff, Set.mem_diff, Set.mem_compl_iff] + all_goals tauto diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..464e7d59959adee67f4705c1d9a9f51ad6bf6105 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "logic-and-sets" +tags = ["logic-and-sets", "set_identities", "msc-03", "train", "lean4"] +msc = "03" +family = "set_identities" +split = "train" +seed = 74 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e7f12ad758dcb71e55acb98ede53e9f3b1c9802b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (U S Y : Set α) :\n (Y \\ U)ᶜ = Yᶜ ∪ U := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0074/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..639ef21a54147cfd2b3b197681d98fec23291563 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated statement about images and preimages. -/ +theorem image_identity {α β : Type*} (g : α → β) (C : Set α) (hf : Function.Injective g) : + g ⁻¹' (g '' C) = C := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf6897f0e122d6a0e3abc84bae724ed1db7a4af6 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(g : \alpha \to \beta\) be a function that is injective and let \(C\) be subsets of \(\alpha\). Write \(g(X)\) for the image and \(g^{-1}(X)\) for the preimage of a set \(X\). Prove \[g^{-1}(g(C)) = C.\] + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4f76b90a8af091fc064fdf9e154584f05266958 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The stated statement about images and preimages. -/ +theorem image_identity {α β : Type*} (g : α → β) (C : Set α) (hf : Function.Injective g) : + g ⁻¹' (g '' C) = C := by + ext x + constructor + · rintro ⟨y, hy, hxy⟩ + exact (hf hxy) ▸ hy + · intro hx + exact ⟨x, hx, rfl⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7dd69d9fa93c07e70ab7f4a00f51eb9807ca5330 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "logic-and-sets" +tags = ["logic-and-sets", "set_identities", "msc-03", "eval", "lean4"] +msc = "03" +family = "set_identities" +split = "eval" +seed = 10005 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..9b58670f04f0a7064557b76915c9024c755bab8d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated statement about images and preimages. -/\ntheorem image_identity {α β : Type*} (g : α → β) (C : Set α) (hf : Function.Injective g) :\n g ⁻¹' (g '' C) = C := by\n sorry\n", + "targets": [ + { + "name": "image_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9eccce5f098a35e92ec66ea93729e05d60738d56 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z S A : Set α) (h : Z ⊆ S) : + (A ∪ (Z ∪ S))ᶜ = (A ∪ S)ᶜ := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97e37c53838ea321c199b52ade9a3a32003fe8a5 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Z, S, A\) be subsets of a type \(\alpha\). Assume that \(Z \subseteq S\). Prove the set identity \[(A \cup (Z \cup S))^{c} = (A \cup S)^{c}.\] + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..38152cd08c34305ed9ede197a9b9af97f111c27c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z S A : Set α) (h : Z ⊆ S) : + (A ∪ (Z ∪ S))ᶜ = (A ∪ S)ᶜ := by + ext x + have hx : x ∈ Z → x ∈ S := @h x + simp only [Set.mem_union, Set.mem_inter_iff, Set.mem_diff, Set.mem_compl_iff] + all_goals tauto diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d9535bd746a8d38d22c5ea688d91c55cc444852 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "set_identities", "msc-03", "train", "lean4"] +msc = "03" +family = "set_identities" +split = "train" +seed = 17 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7f73cec12366efd9869eea1c7d467f70c2d641b3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Z S A : Set α) (h : Z ⊆ S) :\n (A ∪ (Z ∪ S))ᶜ = (A ∪ S)ᶜ := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..141dbb0241fbd1e42e551c9128a6653713a75120 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Y T A : Set α) (h : T ⊆ Y) : + ((Y \ A) ∩ Y) ∩ T = (Yᶜ ∪ (T \ A)) ∩ T := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9921203bbb920964b00ff9356990cadf67a97713 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Y, T, A\) be subsets of a type \(\alpha\). Assume that \(T \subseteq Y\). Prove the set identity \[((Y \setminus A) \cap Y) \cap T = (Y^{c} \cup (T \setminus A)) \cap T.\] + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c08362f2b14aca844f9f1d24072d87cfb4b0de01 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Y T A : Set α) (h : T ⊆ Y) : + ((Y \ A) ∩ Y) ∩ T = (Yᶜ ∪ (T \ A)) ∩ T := by + ext x + have hx : x ∈ T → x ∈ Y := @h x + simp only [Set.mem_union, Set.mem_inter_iff, Set.mem_diff, Set.mem_compl_iff] + all_goals tauto diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f9e033e11f621e6a1a29c13f6670d96cdc1c69ec --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "set_identities", "msc-03", "train", "lean4"] +msc = "03" +family = "set_identities" +split = "train" +seed = 26 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d03a13fe3ae35f9794c5c651d8b33a1270ed3938 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Y T A : Set α) (h : T ⊆ Y) :\n ((Y \\ A) ∩ Y) ∩ T = (Yᶜ ∪ (T \\ A)) ∩ T := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0026/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7860e576cf0640cfa0cbdafb7b88d6a3b285c244 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z X U : Set α) (h : Z ⊆ X) : + (U \ X)ᶜ ∩ Z = X ∩ (Z ∩ (X ∩ Z)) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..295dc0913977ae30bd99bbcc6cdb88c80401001e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Z, X, U\) be subsets of a type \(\alpha\). Assume that \(Z \subseteq X\). Prove the set identity \[(U \setminus X)^{c} \cap Z = X \cap (Z \cap (X \cap Z)).\] + +## 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. diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..22aa28ff59b5aa7fa151d3e5a1a88a3620449b6f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z X U : Set α) (h : Z ⊆ X) : + (U \ X)ᶜ ∩ Z = X ∩ (Z ∩ (X ∩ Z)) := by + ext x + have hx : x ∈ Z → x ∈ X := @h x + simp only [Set.mem_union, Set.mem_inter_iff, Set.mem_diff, Set.mem_compl_iff] + all_goals tauto diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85612f59083f3353f9e56d82f90b00b6347c006e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "logic-and-sets" +tags = ["logic-and-sets", "set_identities", "msc-03", "train", "lean4"] +msc = "03" +family = "set_identities" +split = "train" +seed = 80 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, 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 the +submission 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 Lean +open 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] ..." + return 2 diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second 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 this +file, 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/.lean to work/.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) diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c548bf77ddfdfa2b620ee956308e04c7474f57c9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Z X U : Set α) (h : Z ⊆ X) :\n (U \\ X)ᶜ ∩ Z = X ∩ (Z ∩ (X ∩ Z)) := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0080/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt