diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/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-e0018/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..34e04d6965248e3f3c69ec3cccbf40b2f536b27e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s.image (fun x : ℕ => 2 * x + 6)) ×ˢ t).card = s.card * t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fae7acd33cfd06c9f2697a80744764ae7d8591cd --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 2x + 6\) on the natural numbers and let \(s, t\) be finite sets of natural numbers. Prove that the product \(f(s) \times t\) has \(|s| \cdot |t|\) elements. + +## 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-d1-e0018/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..90a52a2f66f4bace0b02900760e78fa7ca55f225 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s.image (fun x : ℕ => 2 * x + 6)) ×ˢ t).card = s.card * t.card := by + have hinj : Function.Injective (fun x : ℕ => 2 * x + 6) := by + intro x y h + simp only at h + omega + rw [Finset.card_product, Finset.card_image_of_injective s hinj] diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/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-e0018/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e84034e9fd193bdf5a3ed04dc460eace341221fa --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/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", "finset_card", "msc-03", "eval", "lean4"] +msc = "03" +family = "finset_card" +split = "eval" +seed = 10018 + +[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-d1-e0018/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/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-d1-e0018/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/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-d1-e0018/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..21f442a9b6ed9c8d5bda006af0ad7aaa69426a7c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s t : Finset ℕ) :\n ((s.image (fun x : ℕ => 2 * x + 6)) ×ˢ t).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-d1-e0018/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-e0018/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-d1-t0018/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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-t0018/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d9fa426e3e96e652320987722af7887f00b0c5f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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 : ℕ => 5 * x + 2)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f61c6d474b182f4b6b3f1795366639f898908a87 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 5x + 2\) on the natural numbers and let \(s\) be a finite set of natural numbers. Prove that the image \(f(s)\) has the same number of elements as \(s\). + +## 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-d1-t0018/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ade31a4aa5e1787739bf24ebd5df244dfc7988ec --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 5 * x + 2)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 5 * x + 2) := 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-t0018/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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-t0018/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7aa4c2744141781d61911409a54ddddcddb2a1c5 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 18 + +[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-d1-t0018/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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-d1-t0018/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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-d1-t0018/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ea162eab086ce173e37aedeb2a370c9d9a457e6a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s : Finset ℕ) :\n (s.image (fun x : ℕ => 5 * x + 2)).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0018/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-d1-t0027/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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-t0027/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..62f4b09b2fc59a1c1f5b8c37ae0cab47d0c310ab --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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 + 9)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30d6873166ad19dc7e872375cd8dde9e8de9b189 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 8x + 9\) on the natural numbers and let \(s\) be a finite set of natural numbers. Prove that the image \(f(s)\) has the same number of elements as \(s\). + +## 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-d1-t0027/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..735287f6b2730f04b44fed3035c3863c13739c3f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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 + 9)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 8 * x + 9) := 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-t0027/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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-t0027/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e68e2aac952a2847351b659ef1b215b33525663 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 27 + +[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-d1-t0027/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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-d1-t0027/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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-d1-t0027/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c394694f419e7b2f9919f68459679e5aecc7ed9c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s : Finset ℕ) :\n (s.image (fun x : ℕ => 8 * x + 9)).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0027/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-d1-t0045/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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-t0045/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4abdd71109ce6678419f70ec7f358a269e8b880e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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 : ℕ => 7 * x + 8)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c8889bf67ae78acd5db2494c385cc9e18c39ba --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 7x + 8\) on the natural numbers and let \(s\) be a finite set of natural numbers. Prove that the image \(f(s)\) has the same number of elements as \(s\). + +## 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-d1-t0045/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb5899d32bd923a4c13b4b104b420600300bc76b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 7 * x + 8)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 7 * x + 8) := 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-t0045/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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-t0045/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..821e1a78bde2cfe92a5d41d849efc0488920d067 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 45 + +[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-d1-t0045/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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-d1-t0045/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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-d1-t0045/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..92213975de4a5fa9894196602f103c352fb7ee09 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s : Finset ℕ) :\n (s.image (fun x : ℕ => 7 * x + 8)).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0045/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-d1-t0072/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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-t0072/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..02633e87158520eb25613a046c9b1f4293fad50d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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 : ℕ => 3 * x + 0)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3cac00557368c530f09898cfd7da2c5eb609a144 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 3x + 0\) on the natural numbers and let \(s\) be a finite set of natural numbers. Prove that the image \(f(s)\) has the same number of elements as \(s\). + +## 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-d1-t0072/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..323c206ac4cf8c7f8f350fa54e9daef415f6c1ad --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 3 * x + 0)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 3 * x + 0) := 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-t0072/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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-t0072/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f92164dda5af688f206a7633908628efbbf41ac1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 72 + +[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-d1-t0072/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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-d1-t0072/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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-d1-t0072/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c39a100b959efd35f1d52557c2c845033c511594 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s : Finset ℕ) :\n (s.image (fun x : ℕ => 3 * x + 0)).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0072/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-d1-t0081/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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-t0081/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7bdf3bc85e17fac0194a6590d666911644fb3071 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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 : ℕ => 2 * x + 7)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e23c1c9b181fa607de97e07182623b4e57858d6e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 2x + 7\) on the natural numbers and let \(s\) be a finite set of natural numbers. Prove that the image \(f(s)\) has the same number of elements as \(s\). + +## 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-d1-t0081/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e490af4848eebb26d8d74b7afa1cb4abe25f38e4 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 2 * x + 7)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 2 * x + 7) := 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-t0081/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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-t0081/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8e03168d1b9806271567445dac0b6e454eeb50c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 81 + +[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-d1-t0081/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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-d1-t0081/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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-d1-t0081/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..857634e09858f92bc51290ce8ce0c3d1f6ef5679 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s : Finset ℕ) :\n (s.image (fun x : ℕ => 2 * x + 7)).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0081/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-d2-e0003/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/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-d2-e0003/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0267b4f3167fb63275cef444193245dc8ebaa20 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s \ t).image (fun x : ℕ => 5 * x + 3)).card + (s ∩ t).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2673e66e29ea8ec5591a2bbdf839d90dc699fd6d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 5x + 3\) on the natural numbers and let \(s, t\) be finite sets of natural numbers. Prove that \[|f(s \setminus t)| + |s \cap t| = |s|.\] + +## 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-d2-e0003/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8775cd3e1051256669caf036851c91cb2d478efc --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s \ t).image (fun x : ℕ => 5 * x + 3)).card + (s ∩ t).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 5 * x + 3) := by + intro x y h + simp only at h + omega + rw [Finset.card_image_of_injective _ hinj] + have h := Finset.card_sdiff_add_card_inter s t + omega diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/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-d2-e0003/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cda3027901cc98ca68ee619a1a34341aaec915f1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/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", "finset_card", "msc-03", "eval", "lean4"] +msc = "03" +family = "finset_card" +split = "eval" +seed = 10003 + +[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-d2-e0003/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/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-d2-e0003/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/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-d2-e0003/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8093c071be1f4ff46c69d0185c06d8e0c26945ea --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s t : Finset ℕ) :\n ((s \\ t).image (fun x : ℕ => 5 * x + 3)).card + (s ∩ t).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0003/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-d2-t0003/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/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-d2-t0003/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..94b2cf6054c3a2e83e8b5a6fe43fff5bc896ece5 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s ∪ t).image (fun x : ℕ => 2 * x + 6)).card + ((s ∩ t).image (fun x : ℕ => 2 * x + 6)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e187f201026d007896fce3b72d6493c0954a3406 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 2x + 6\) on the natural numbers and let \(s, t\) be finite sets of natural numbers. Prove that \[|f(s \cup t)| + |f(s \cap 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-d2-t0003/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..84cc6b5a1ab0a4b468c21ab973f0d94ea1611503 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s ∪ t).image (fun x : ℕ => 2 * x + 6)).card + ((s ∩ t).image (fun x : ℕ => 2 * x + 6)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 2 * x + 6) := by + intro x y h + simp only at h + omega + rw [Finset.image_union, Finset.image_inter _ _ hinj, Finset.card_union_add_card_inter, + Finset.card_image_of_injective s hinj, Finset.card_image_of_injective t hinj] diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/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-d2-t0003/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b7a724b4533260f02d659508fb7e8606bfb24993 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 3 + +[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-d2-t0003/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/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-d2-t0003/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/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-d2-t0003/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7cc8096c243a956c7711256cd0de04304c361157 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s t : Finset ℕ) :\n ((s ∪ t).image (fun x : ℕ => 2 * x + 6)).card + ((s ∩ t).image (fun x : ℕ => 2 * x + 6)).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-d2-t0003/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0003/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-d2-t0057/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/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-d2-t0057/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec15eed3ba25a6203e850b2797c6e6232e67f494 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s ∪ t).image (fun x : ℕ => 8 * x + 4)).card + ((s ∩ t).image (fun x : ℕ => 8 * x + 4)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..253dbd7d568f94fc4409b05804042cf9286195bd --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 8x + 4\) on the natural numbers and let \(s, t\) be finite sets of natural numbers. Prove that \[|f(s \cup t)| + |f(s \cap 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-d2-t0057/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c998d5afefba713c1183e1b7fa6e3640bd2d4d7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s ∪ t).image (fun x : ℕ => 8 * x + 4)).card + ((s ∩ t).image (fun x : ℕ => 8 * x + 4)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 8 * x + 4) := by + intro x y h + simp only at h + omega + rw [Finset.image_union, Finset.image_inter _ _ hinj, Finset.card_union_add_card_inter, + Finset.card_image_of_injective s hinj, Finset.card_image_of_injective t hinj] diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/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-d2-t0057/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a473c121dbc806b0be34a16a7c8cf07aed30e961 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 57 + +[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-d2-t0057/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/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-d2-t0057/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/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-d2-t0057/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..f2c1322e7815a43bef4f04cce7fa2a348bcc9b47 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s t : Finset ℕ) :\n ((s ∪ t).image (fun x : ℕ => 8 * x + 4)).card + ((s ∩ t).image (fun x : ℕ => 8 * 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-d2-t0057/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0057/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-d2-t0066/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/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-d2-t0066/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b843d8c67f3b201e30b9016098bcc390b58bf61d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s \ t).image (fun x : ℕ => 6 * x + 8)).card + (s ∩ t).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2fdff183951cb5a6fddc1f6432b4dc1b852bbea1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 6x + 8\) on the natural numbers and let \(s, t\) be finite sets of natural numbers. Prove that \[|f(s \setminus t)| + |s \cap t| = |s|.\] + +## 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-d2-t0066/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a7be59aef72d88244dc37b2b2cb3e125a61d526e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s t : Finset ℕ) : + ((s \ t).image (fun x : ℕ => 6 * x + 8)).card + (s ∩ t).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 6 * x + 8) := by + intro x y h + simp only at h + omega + rw [Finset.card_image_of_injective _ hinj] + have h := Finset.card_sdiff_add_card_inter s t + omega diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/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-d2-t0066/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..08c9e39d5764303d6df06a925c030bbce574899e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/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", "finset_card", "msc-03", "train", "lean4"] +msc = "03" +family = "finset_card" +split = "train" +seed = 66 + +[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-d2-t0066/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/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-d2-t0066/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/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-d2-t0066/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..bbc2558340aaea1c6e4922c3e6b41146479c9300 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A cardinality fact about finite sets. -/\ntheorem card_fact (s t : Finset ℕ) :\n ((s \\ t).image (fun x : ℕ => 6 * x + 8)).card + (s ∩ t).card = s.card := by\n sorry\n", + "targets": [ + { + "name": "card_fact", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-t0066/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-t0033/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..72ae596db11028604a668e45ec97708664f06da2 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c42536ca088a12d8686fe239299b3f100eaa97ad --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..abaae4ccb8f3e6b7e8429f49e7c1bbe1b0cafa90 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..333dee1c2d616331d487696ecea098ae4e90315c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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 = 33 + +[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-t0033/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb007510c9294303098917ed34ec73e9ed8774d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0033/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0033/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-t0042/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..72ae596db11028604a668e45ec97708664f06da2 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c42536ca088a12d8686fe239299b3f100eaa97ad --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..abaae4ccb8f3e6b7e8429f49e7c1bbe1b0cafa90 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..040a5470e83d5b83903d061d0912b7450712115b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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 = 42 + +[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-t0042/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cdb007510c9294303098917ed34ec73e9ed8774d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0042/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0042/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-t0051/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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-t0051/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee31079662ee774f10c2e04d00a3bab1bc272b9e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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 : ℕ => 5 * x + 2)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..64eae68b172675a0466e197ff1d41dd23839eea5 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 5x + 2\) 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-t0051/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe28c0497d40b92bfa8bba7d0d7eeaa521903be1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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 : ℕ => 5 * x + 2)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 5 * x + 2) := 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-t0051/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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-t0051/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d3a18ab65460792a25c3087554f4e80fd1352e01 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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 = 51 + +[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-t0051/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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-t0051/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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-t0051/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4e7fae77a52b34c3694b9fef057803237a7a9387 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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 : ℕ => 5 * x + 2)).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-t0051/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0051/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-t0060/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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-t0060/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..62d207dc20de112e079510c6abd19e0cba888f49 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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 : ℕ => 8 * x + 7)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2c4ed2ef16d8fee8fe13391a8f7d778ebe037e9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 8x + 7\) 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-t0060/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..379d3167f959015e3972122a4e20eab724347335 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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 : ℕ => 8 * x + 7)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 8 * x + 7) := 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-t0060/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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-t0060/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..efd685ab87b5e1ec0adfe7339578604a0387999f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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 = 60 + +[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-t0060/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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-t0060/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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-t0060/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..163a915565873c63f066701100a7db305666bd6f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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 : ℕ => 8 * x + 7)).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-t0060/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0060/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-t0069/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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-t0069/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee83211fbd4b51e61f5851a29c9635bf39e3558b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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 : ℕ => 9 * x + 7)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13ad5af6a9b9af8f9a61ad57892044403d7d03be --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 9x + 7\) 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-t0069/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cf426ea8dd9b7e9ee53b0fc81e375471ce70da28 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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 : ℕ => 9 * x + 7)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 9 * x + 7) := 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-t0069/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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-t0069/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..294b46a4b529b30ee08bda6913607efde1f32d6b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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 = 69 + +[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-t0069/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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-t0069/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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-t0069/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d89cb7affa0e5ce4877316c194be525644d25030 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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 : ℕ => 9 * x + 7)).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-t0069/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0069/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-d1-e0010/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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-d1-e0010/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ace61006026438bb8f9a00bd7889547e628362d5 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => 7 ∣ x - y) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b146ef64cc59b56e3916c763196626860248b0b8 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On the integers define \(x \sim y \iff 7 \mid x - y\). 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-d1-e0010/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9e0e2b31b33375f4e92f19d593681fc935d6ff3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/solution/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => 7 ∣ x - y) := ⟨fun x => by omega, fun {x y} h => by omega, fun {x y z} h1 h2 => by omega⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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-d1-e0010/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bce076856e4e56aca1afe9d6a662e1bc7cf57fa3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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", "relations", "msc-03", "eval", "lean4"] +msc = "03" +family = "relations" +split = "eval" +seed = 10010 + +[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-d1-e0010/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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-d1-e0010/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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-d1-e0010/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..f7717430700c0a6f5ab5960a95671939d72f8c17 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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 : ℤ => 7 ∣ x - y) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0010/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-d1-e0019/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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-d1-e0019/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7be33c13dd9bd4399a717401655bebc41edb0aab --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => x % 9 = y % 9) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79a9693339b364dc7c2d4b963c9ffa49d6ab2dcf --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On the integers define \(x \sim y \iff x \bmod 9 = y \bmod 9\). 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-d1-e0019/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..204432a06d088d97ef5dc7f476d7ddc510acd679 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/solution/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => x % 9 = y % 9) := ⟨fun x => by omega, fun {x y} h => by omega, fun {x y z} h1 h2 => by omega⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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-d1-e0019/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7069b15a9ed8674b871876b79ac600e55ce87220 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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", "relations", "msc-03", "eval", "lean4"] +msc = "03" +family = "relations" +split = "eval" +seed = 10019 + +[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-d1-e0019/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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-d1-e0019/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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-d1-e0019/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b3d60e2fc9d735d14e4c8b5a5714d03ad82df79b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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 : ℤ => x % 9 = y % 9) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d1-e0019/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-t0058/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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-t0058/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f7c396be65c9eedea5a0ab7faf265ead1fa56959 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => 5 ∣ x ^ 3 - y ^ 3) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2801afef57ba26f047e38cf263f7af00911a8f45 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On the integers define \(x \sim y \iff 5 \mid x^{3} - y^{3}\). 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-t0058/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..da1b41d971d4e976c7f63af40b4d0a3512c64251 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun x y : ℤ => 5 ∣ x ^ 3 - y ^ 3) := ⟨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-t0058/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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-t0058/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..28b84815c079d3135fa83f690d817020f51cf4fd --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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 = 58 + +[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-t0058/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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-t0058/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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-t0058/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..77dff80f6df571c87a5238b3a88e9921eeefdf06 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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 : ℤ => 5 ∣ x ^ 3 - y ^ 3) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0058/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-t0067/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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-t0067/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..89c92aca00e1a7d278e8917744a5b5604d657e57 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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 + 3 * q.2 = q.1 + 3 * p.2) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1309013027b386179c40f5f3f8068808860a9c2d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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 + 3 y_2 = x_2 + 3 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-t0067/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9aadaffb8046eb6cc36ed0916421d5b332a2654c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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 + 3 * q.2 = q.1 + 3 * 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-t0067/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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-t0067/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cbb6fd874227761e6a200cba35048a18f13e005e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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 = 67 + +[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-t0067/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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-t0067/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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-t0067/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..de6bf365d885c13166316913caea5892d1186756 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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 + 3 * q.2 = q.1 + 3 * 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-t0067/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0067/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-e0016/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/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-e0016/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c48c949fa4a2baeebf37a8be7935ed18d67ce93a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/environment/workdir/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (m : ℤ) : + Equivalence (fun x y : ℤ => m ∣ x - y) := by + sorry + +/-- The relation is compatible with addition. -/ +theorem rel_add (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ (a + c) - (b + d) := by + sorry + +/-- The relation is compatible with multiplication. -/ +theorem rel_mul (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ a * c - b * d := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c54ab3e5eb133658d4563c7cf6e3e448338cf7ed --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +For an integer \(m\), define a relation on the integers by \(x \sim y \iff m \mid x - y\). Prove three things: (1) \(\sim\) is an equivalence relation; (2) \(\sim\) is compatible with addition: if \(m \mid a - b\) and \(m \mid c - d\) then \(m \mid (a+c) - (b+d)\); (3) \(\sim\) is compatible with multiplication: if \(m \mid a - b\) and \(m \mid c - d\) then \(m \mid ac - bd\). + +## 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-e0016/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cafb4f154080ecf6240ebe2122b86a93d291b3bf --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/solution/Solution.lean @@ -0,0 +1,22 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (m : ℤ) : + Equivalence (fun x y : ℤ => m ∣ x - y) := ⟨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⟩ + +/-- The relation is compatible with addition. -/ +theorem rel_add (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ (a + c) - (b + d) := by + have h := dvd_add h1 h2 + have e : (a + c) - (b + d) = (a - b) + (c - d) := by ring + rw [e] + exact h + +/-- The relation is compatible with multiplication. -/ +theorem rel_mul (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ a * c - b * d := by + have e : a * c - b * d = a * (c - d) + (a - b) * d := by ring + rw [e] + exact dvd_add (dvd_mul_of_dvd_right h2 a) (dvd_mul_of_dvd_left h1 d) diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/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-e0016/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7a4600f4fe0f91a1cacc5957e7a19e4c0913606d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/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 = 10016 + +[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-e0016/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/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-e0016/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/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-e0016/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d93575ed7699fcd49bef5229f1046f133873814c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/tests/spec.json @@ -0,0 +1,17 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv (m : ℤ) :\n Equivalence (fun x y : ℤ => m ∣ x - y) := by\n sorry\n\n/-- The relation is compatible with addition. -/\ntheorem rel_add (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) :\n m ∣ (a + c) - (b + d) := by\n sorry\n\n/-- The relation is compatible with multiplication. -/\ntheorem rel_mul (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) :\n m ∣ a * c - b * d := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + }, + { + "name": "rel_add", + "weight": 1.0 + }, + { + "name": "rel_mul", + "weight": 2.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-e0016/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-t0034/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/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-t0034/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c48c949fa4a2baeebf37a8be7935ed18d67ce93a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/environment/workdir/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (m : ℤ) : + Equivalence (fun x y : ℤ => m ∣ x - y) := by + sorry + +/-- The relation is compatible with addition. -/ +theorem rel_add (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ (a + c) - (b + d) := by + sorry + +/-- The relation is compatible with multiplication. -/ +theorem rel_mul (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ a * c - b * d := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c54ab3e5eb133658d4563c7cf6e3e448338cf7ed --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +For an integer \(m\), define a relation on the integers by \(x \sim y \iff m \mid x - y\). Prove three things: (1) \(\sim\) is an equivalence relation; (2) \(\sim\) is compatible with addition: if \(m \mid a - b\) and \(m \mid c - d\) then \(m \mid (a+c) - (b+d)\); (3) \(\sim\) is compatible with multiplication: if \(m \mid a - b\) and \(m \mid c - d\) then \(m \mid ac - bd\). + +## 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-t0034/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cafb4f154080ecf6240ebe2122b86a93d291b3bf --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/solution/Solution.lean @@ -0,0 +1,22 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (m : ℤ) : + Equivalence (fun x y : ℤ => m ∣ x - y) := ⟨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⟩ + +/-- The relation is compatible with addition. -/ +theorem rel_add (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ (a + c) - (b + d) := by + have h := dvd_add h1 h2 + have e : (a + c) - (b + d) = (a - b) + (c - d) := by ring + rw [e] + exact h + +/-- The relation is compatible with multiplication. -/ +theorem rel_mul (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) : + m ∣ a * c - b * d := by + have e : a * c - b * d = a * (c - d) + (a - b) * d := by ring + rw [e] + exact dvd_add (dvd_mul_of_dvd_right h2 a) (dvd_mul_of_dvd_left h1 d) diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/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-t0034/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e3b7e85c39bc6f48cb4d1fd2b278dcf4e8a65855 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/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", "train", "lean4"] +msc = "03" +family = "relations" +split = "train" +seed = 34 + +[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-t0034/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/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-t0034/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/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-t0034/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d93575ed7699fcd49bef5229f1046f133873814c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/tests/spec.json @@ -0,0 +1,17 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv (m : ℤ) :\n Equivalence (fun x y : ℤ => m ∣ x - y) := by\n sorry\n\n/-- The relation is compatible with addition. -/\ntheorem rel_add (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) :\n m ∣ (a + c) - (b + d) := by\n sorry\n\n/-- The relation is compatible with multiplication. -/\ntheorem rel_mul (m a b c d : ℤ) (h1 : m ∣ a - b) (h2 : m ∣ c - d) :\n m ∣ a * c - b * d := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + }, + { + "name": "rel_add", + "weight": 1.0 + }, + { + "name": "rel_mul", + "weight": 2.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0034/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-t0061/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/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-t0061/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f70283883605a08efc2765bda6bb6c2fc9df405 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/environment/workdir/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (n : ℤ) : + Equivalence (fun x y : ℤ => x ≡ y [ZMOD n]) := by + sorry + +/-- The relation is compatible with addition. -/ +theorem rel_add (n a b c d : ℤ) (h1 : a ≡ b [ZMOD n]) (h2 : c ≡ d [ZMOD n]) : + a + c ≡ b + d [ZMOD n] := by + sorry + +/-- The relation is compatible with multiplication. -/ +theorem rel_mul (n a b c d : ℤ) (h1 : a ≡ b [ZMOD n]) (h2 : c ≡ d [ZMOD n]) : + a * c ≡ b * d [ZMOD n] := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78bd4952b24bd68fec75d95160739936ac7d7c7b --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +For an integer \(n\), define a relation on the integers by \(x \sim y \iff x \equiv y \pmod{n}\). Prove three things: (1) \(\sim\) is an equivalence relation; (2) \(\sim\) is compatible with addition: if \(a \equiv b \pmod{n}\) and \(c \equiv d \pmod{n}\) then \(a+c \equiv b+d \pmod{n}\); (3) \(\sim\) is compatible with multiplication: if \(a \equiv b \pmod{n}\) and \(c \equiv d \pmod{n}\) then \(ac \equiv bd \pmod{n}\). + +## 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-t0061/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ded2b5f8536595e0cac978b1797977e0bbe93f9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv (n : ℤ) : + Equivalence (fun x y : ℤ => x ≡ y [ZMOD n]) := ⟨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 (n a b c d : ℤ) (h1 : a ≡ b [ZMOD n]) (h2 : c ≡ d [ZMOD n]) : + a + c ≡ b + d [ZMOD n] := h1.add h2 + +/-- The relation is compatible with multiplication. -/ +theorem rel_mul (n a b c d : ℤ) (h1 : a ≡ b [ZMOD n]) (h2 : c ≡ d [ZMOD n]) : + a * c ≡ b * d [ZMOD n] := h1.mul h2 diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/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-t0061/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..27ce8572b65a1b4e5d12105e8352f9c1acaf04bb --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/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", "train", "lean4"] +msc = "03" +family = "relations" +split = "train" +seed = 61 + +[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-t0061/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/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-t0061/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/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-t0061/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6abe7aeb6399d1c89c2434f9ebf823af6f999b48 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/tests/spec.json @@ -0,0 +1,17 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv (n : ℤ) :\n Equivalence (fun x y : ℤ => x ≡ y [ZMOD n]) := by\n sorry\n\n/-- The relation is compatible with addition. -/\ntheorem rel_add (n a b c d : ℤ) (h1 : a ≡ b [ZMOD n]) (h2 : c ≡ d [ZMOD n]) :\n a + c ≡ b + d [ZMOD n] := by\n sorry\n\n/-- The relation is compatible with multiplication. -/\ntheorem rel_mul (n a b c d : ℤ) (h1 : a ≡ b [ZMOD n]) (h2 : c ≡ d [ZMOD n]) :\n a * c ≡ b * d [ZMOD n] := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + }, + { + "name": "rel_add", + "weight": 1.0 + }, + { + "name": "rel_mul", + "weight": 2.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d3-t0061/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-t0038/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/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-t0038/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..57818ae582a7747c421883f1569c22b1323299fc --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Y B X : Set α) : + X \ (Y ∩ B) = (X \ Y) ∪ (X \ B) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03a761c637b97e1b0da76879f9faeb1c2eda2c47 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Y, B, X\) be subsets of a type \(\alpha\). Prove the set identity \[X \setminus (Y \cap B) = (X \setminus Y) \cup (X \setminus B).\] + +## 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-t0038/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffda3908a9ac79236cb9cf9e380b7be108065ac3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Y B X : Set α) : + X \ (Y ∩ B) = (X \ Y) ∪ (X \ B) := 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-t0038/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/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-t0038/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf6978fbfc158eddc9195695141408ea6f402a33 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/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 = 38 + +[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-t0038/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/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-t0038/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/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-t0038/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b6b6c6d0d5828cb638540ab090f61d44f0920e31 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Y B X : Set α) :\n X \\ (Y ∩ B) = (X \\ Y) ∪ (X \\ B) := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0038/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-t0047/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/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-t0047/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ae9700ade59c052b9370c3b551c1d79e61dd56f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (X C Y : Set α) : + C \ (Y ∪ X) = (C \ Y) ∩ (C \ X) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4e9977911c2a2701d858774369bc4095b6785279 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(X, C, Y\) be subsets of a type \(\alpha\). Prove the set identity \[C \setminus (Y \cup X) = (C \setminus Y) \cap (C \setminus X).\] + +## 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-t0047/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7582856777639715ccbe8c357a6442cad29a9a5e --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (X C Y : Set α) : + C \ (Y ∪ X) = (C \ Y) ∩ (C \ X) := 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-t0047/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/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-t0047/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9aae8834f6908ca28614e19bdf952c51e428d021 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/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 = 47 + +[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-t0047/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/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-t0047/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/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-t0047/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..459096aeac02562d1a7b62972b6ba91d82e4e3c1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (X C Y : Set α) :\n C \\ (Y ∪ X) = (C \\ Y) ∩ (C \\ X) := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0047/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-t0065/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/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-t0065/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..49ca7d898e823b27a4120a9e8e7e2bcfa3c1bdf3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z A U : Set α) : + (U \ A) ∪ (U ∩ Z) = U \ (A \ Z) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..133e99391aff6e0ed0062f2f0b9db85d6ec19065 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Z, A, U\) be subsets of a type \(\alpha\). Prove the set identity \[(U \setminus A) \cup (U \cap Z) = U \setminus (A \setminus 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-d1-t0065/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..df673808b4d9689972bcaf90d3009370751e6785 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z A U : Set α) : + (U \ A) ∪ (U ∩ Z) = U \ (A \ Z) := 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-t0065/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/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-t0065/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff039cb7f644c3d336dbdb2ce6fbd46a10bd506c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/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 = 65 + +[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-t0065/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/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-t0065/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/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-t0065/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ad0e1fdd9d43ca35a39b5175b6e105cb2119dc5d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Z A U : Set α) :\n (U \\ A) ∪ (U ∩ Z) = U \\ (A \\ Z) := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0065/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-t0083/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/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-t0083/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3cf1736961bba7abd0f19f369ebe58d8524ec658 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z B C : Set α) : + (B ∪ Z) \ (B ∩ Z) = (B \ Z) ∪ (Z \ B) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aab429672026f54783308be3fd9559735d7d962c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Z, B, C\) be subsets of a type \(\alpha\). Prove the set identity \[(B \cup Z) \setminus (B \cap Z) = (B \setminus Z) \cup (Z \setminus B).\] + +## 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-t0083/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d99af2c96bbba1eda471c29e29ed1f9e61c2d200 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Z B C : Set α) : + (B ∪ Z) \ (B ∩ Z) = (B \ Z) ∪ (Z \ B) := 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-t0083/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/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-t0083/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..daaa52a5d6cfbc75af65d148e40f2079b4f84e17 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/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 = 83 + +[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-t0083/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/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-t0083/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/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-t0083/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e2a77f3efa76275558698bb9473ba6802b0147c2 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Z B C : Set α) :\n (B ∪ Z) \\ (B ∩ Z) = (B \\ Z) ∪ (Z \\ B) := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0083/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-e0023/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/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-e0023/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f96cdb941011d68b62bbeb9744a5df7e9f336e2a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated statement about images and preimages. -/ +theorem image_identity {α β : Type*} (h : α → β) (B : Set α) (hf : Function.Injective h) : + h ⁻¹' (h '' B) = B := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1cc1b29fa4a2b3dad1ab75938e1971398449f63 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(h : \alpha \to \beta\) be a function that is injective and let \(B\) be subsets of \(\alpha\). Write \(h(X)\) for the image and \(h^{-1}(X)\) for the preimage of a set \(X\). Prove \[h^{-1}(h(B)) = B.\] + +## 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-e0023/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a29bf465a104b0a41bab61b4005054b578af392 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The stated statement about images and preimages. -/ +theorem image_identity {α β : Type*} (h : α → β) (B : Set α) (hf : Function.Injective h) : + h ⁻¹' (h '' B) = B := 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-e0023/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/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-e0023/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..59130e90c55cb298f62b7fd3707501553e5c0f04 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/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 = 10023 + +[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-e0023/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/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-e0023/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/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-e0023/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..560afe92539b1c4fb652635f97e3901be264ceda --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated statement about images and preimages. -/\ntheorem image_identity {α β : Type*} (h : α → β) (B : Set α) (hf : Function.Injective h) :\n h ⁻¹' (h '' B) = B := by\n sorry\n", + "targets": [ + { + "name": "image_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d2-e0023/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-t0008/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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-t0008/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..edd26c18ace44e169978024a93a1801a5da0353f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated statement about images and preimages. -/ +theorem image_identity {α β : Type*} (g : α → β) (A C : Set α) (hf : Function.Injective g) : + g '' (A \ C) = g '' A \ g '' C := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..658c411138ffb011664f8e6bc865c9856cbd02c4 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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 \(A, C\) be subsets of \(\alpha\). Write \(g(X)\) for the image and \(g^{-1}(X)\) for the preimage of a set \(X\). Prove \[g(A \setminus C) = g(A) \setminus g(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-t0008/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a2a2624ed926aae956dc661bcc7adfdb814ef41 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The stated statement about images and preimages. -/ +theorem image_identity {α β : Type*} (g : α → β) (A C : Set α) (hf : Function.Injective g) : + g '' (A \ C) = g '' A \ g '' C := by + ext y + constructor + · rintro ⟨x, ⟨ha, hb⟩, rfl⟩ + exact ⟨⟨x, ha, rfl⟩, fun ⟨x', hb', hx⟩ => hb ((hf hx) ▸ hb')⟩ + · rintro ⟨⟨x, ha, rfl⟩, hy⟩ + exact ⟨x, ⟨ha, fun hb => hy ⟨x, hb, rfl⟩⟩, rfl⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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-t0008/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..56b00ecbaf694324d5a5f8c77a1d588026d93173 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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 = 8 + +[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-t0008/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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-t0008/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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-t0008/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..15295431a393a0b6e071116c118087200ad5ab67 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated statement about images and preimages. -/\ntheorem image_identity {α β : Type*} (g : α → β) (A C : Set α) (hf : Function.Injective g) :\n g '' (A \\ C) = g '' A \\ g '' C := by\n sorry\n", + "targets": [ + { + "name": "image_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0008/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-t0071/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/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-t0071/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2082f40edb339d2aadaaa4b83432b33e2440d105 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Y B T : Set α) (h : T ∩ Y = ∅) : + Y \ (Yᶜ ∩ B) = Y ∩ Tᶜ := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5a5d2ce6db34249a6f61fbbb1ddf1396e7a1528 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(Y, B, T\) be subsets of a type \(\alpha\). Assume that \(T \cap Y = \emptyset\). Prove the set identity \[Y \setminus (Y^{c} \cap B) = Y \cap T^{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-t0071/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc2ec4469dde522dff9b9ec3b06b0322476de599 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (Y B T : Set α) (h : T ∩ Y = ∅) : + Y \ (Yᶜ ∩ B) = Y ∩ Tᶜ := by + ext x + have hx : x ∈ T → x ∈ Y → False := fun ha hb => by + have hm : x ∈ T ∩ Y := ⟨ha, hb⟩ + simp [h] at hm + 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-t0071/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/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-t0071/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..873a78bd01ff96f89dccf7fc4404ca7be0026df9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/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 = 71 + +[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-t0071/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/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-t0071/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/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-t0071/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2d39c2584fbe893d0b5f9950128d25c47d0b2397 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (Y B T : Set α) (h : T ∩ Y = ∅) :\n Y \\ (Yᶜ ∩ B) = Y ∩ 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-t0071/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0071/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/real-analysis/real-analysis-continuity-d1-t0000/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0000/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..16f50d8825d783d709544c4cbedd8a4b63cdbbcb --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a linear function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-2 : ℝ)| < δ → |((7 : ℝ) * x + (-5 : ℝ)) - ((7 : ℝ) * (-2 : ℝ) + (-5 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0000/instruction.md b/tasks/real-analysis/real-analysis-continuity-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcc5959e0a8551ffc4fee6d041ffa0e4dcf29a7c --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = 7x - 5\) is continuous at \(x_0 = -2\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0000/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8e52e459261fa0f54b0dbfde3778a0ef8321e89a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Epsilon-delta continuity of a linear function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-2 : ℝ)| < δ → |((7 : ℝ) * x + (-5 : ℝ)) - ((7 : ℝ) * (-2 : ℝ) + (-5 : ℝ))| < ε := by + intro ε hε + refine ⟨ε / (7 : ℝ), by positivity, fun x hx => ?_⟩ + have e : ((7 : ℝ) * x + (-5 : ℝ)) - ((7 : ℝ) * (-2 : ℝ) + (-5 : ℝ)) = (7 : ℝ) * (x - (-2 : ℝ)) := by ring + rw [e, abs_mul, show |(7 : ℝ)| = (7 : ℝ) by norm_num] + rw [lt_div_iff₀ (by norm_num)] at hx + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0000/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0000/task.toml b/tasks/real-analysis/real-analysis-continuity-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4327a01e2ae14ac84555d7c5f4ceba9f96d24786 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 0 + +[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/real-analysis/real-analysis-continuity-d1-t0000/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/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/real-analysis/real-analysis-continuity-d1-t0000/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d1-t0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-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/real-analysis/real-analysis-continuity-d1-t0000/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d1-t0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..34492b20c62a948e2c66faa49df4ea4c717f6fdd --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-2 : ℝ)| < δ → |((7 : ℝ) * x + (-5 : ℝ)) - ((7 : ℝ) * (-2 : ℝ) + (-5 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0000/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0000/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/real-analysis/real-analysis-continuity-d1-t0036/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0036/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0036/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f576d865e373d95e4d554ec0c6a2c308724d6a5 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a linear function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (3 : ℝ)| < δ → |((-5 : ℝ) * x + (-2 : ℝ)) - ((-5 : ℝ) * (3 : ℝ) + (-2 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0036/instruction.md b/tasks/real-analysis/real-analysis-continuity-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb36d9928a3ba1c308487329410fd019bfdf879a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = -5x - 2\) is continuous at \(x_0 = 3\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0036/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0036/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c31b891f17460c6962bc4dc0c2abd351430f20c --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Epsilon-delta continuity of a linear function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (3 : ℝ)| < δ → |((-5 : ℝ) * x + (-2 : ℝ)) - ((-5 : ℝ) * (3 : ℝ) + (-2 : ℝ))| < ε := by + intro ε hε + refine ⟨ε / (5 : ℝ), by positivity, fun x hx => ?_⟩ + have e : ((-5 : ℝ) * x + (-2 : ℝ)) - ((-5 : ℝ) * (3 : ℝ) + (-2 : ℝ)) = (-5 : ℝ) * (x - (3 : ℝ)) := by ring + rw [e, abs_mul, show |(-5 : ℝ)| = (5 : ℝ) by norm_num] + rw [lt_div_iff₀ (by norm_num)] at hx + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0036/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0036/task.toml b/tasks/real-analysis/real-analysis-continuity-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8fdc837e2d6fb2fbf35ec2e2f783fa6ea1075e4 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 36 + +[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/real-analysis/real-analysis-continuity-d1-t0036/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0036/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/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/real-analysis/real-analysis-continuity-d1-t0036/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d1-t0036/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/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/real-analysis/real-analysis-continuity-d1-t0036/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d1-t0036/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3938327572952f8b4282454ae5ac42fd81fa9534 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (3 : ℝ)| < δ → |((-5 : ℝ) * x + (-2 : ℝ)) - ((-5 : ℝ) * (3 : ℝ) + (-2 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0036/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0036/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/real-analysis/real-analysis-continuity-d3-t0008/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0008/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cdb423900213652858ca084088b449e8807e5473 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (1 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (1 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0008/instruction.md b/tasks/real-analysis/real-analysis-continuity-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a16c52c32cd3c972f8ed3d34f4e7f598f8276637 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = \dfrac{3}{x}\) is continuous at \(x_0 = 1\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Here \(x\) ranges over all real numbers (in Lean, division by 0 gives 0, which does not matter for small \(\delta\)). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0008/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff80a95ced861fbcd689bb0a3079a02a0f3c6611 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/solution/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (1 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (1 : ℝ)| < ε := by + intro ε hε + refine ⟨min ((1 : ℝ) / 2) (ε * (1 : ℝ) ^ 2 / (2 * (3 : ℝ))), lt_min (by norm_num) (by positivity), fun x hx => ?_⟩ + have h1 : |x - (1 : ℝ)| < (1 : ℝ) / 2 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (1 : ℝ)| < ε * (1 : ℝ) ^ 2 / (2 * (3 : ℝ)) := lt_of_lt_of_le hx (min_le_right _ _) + have hx0 : (1 : ℝ) / 2 < x := by + have := (abs_lt.mp h1).1 + linarith + have hxpos : (0 : ℝ) < x := by linarith + have e : (3 : ℝ) / x - (3 : ℝ) / (1 : ℝ) = (3 : ℝ) * ((1 : ℝ) - x) / (x * (1 : ℝ)) := by + field_simp + have h3 : (3 : ℝ) * |x - (1 : ℝ)| < ε * (1 : ℝ) ^ 2 / 2 := by + rw [lt_div_iff₀ (by norm_num)] at h2 ⊢ + nlinarith [abs_nonneg (x - (1 : ℝ))] + have h4 : ε * (1 : ℝ) ^ 2 / 2 < ε * (x * (1 : ℝ)) := by nlinarith [mul_pos hε (sub_pos.mpr hx0), mul_pos hε hxpos] + rw [e, abs_div, abs_mul, abs_of_pos (by positivity : (0 : ℝ) < x * (1 : ℝ)), abs_sub_comm, show |(3 : ℝ)| = (3 : ℝ) by norm_num, div_lt_iff₀ (by positivity)] + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0008/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0008/task.toml b/tasks/real-analysis/real-analysis-continuity-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..142ef0b62d0c6a392fc453c6e740df2399c86d4b --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 8 + +[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/real-analysis/real-analysis-continuity-d3-t0008/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/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/real-analysis/real-analysis-continuity-d3-t0008/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d3-t0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/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/real-analysis/real-analysis-continuity-d3-t0008/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d3-t0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ffa883d41b8435ea1806e9029ab135b059aa4cb3 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of the reciprocal function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (1 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (1 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0008/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0008/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/real-analysis/real-analysis-limit_sequence-d1-t0013/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad1cc4e9c8c8e0819003f1ff8a473c7f7802782f --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(4 : ℝ) / ((n : ℝ) + (2 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7c57dd30c16b8ab0bbfc6a7e69bf7705c7cc287 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that the sequence \(u_n = \dfrac{4}{n + 2}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## 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/real-analysis/real-analysis-limit_sequence-d1-t0013/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b2421b0aae4ee28f320d37d9bd8490bd87f8cf8 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(4 : ℝ) / ((n : ℝ) + (2 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(4 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (4 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (4 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hpos : (0 : ℝ) < (n : ℝ) + (2 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (2 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..44a2bca142012ce81c43bbad70fcbdb1b4d45edc --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 13 + +[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/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/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/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/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/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..22b9afd2dde8d71a9ae547a97ec8a9648808c0d9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(4 : ℝ) / ((n : ℝ) + (2 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0013/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/real-analysis/real-analysis-limit_sequence-d1-t0025/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7d6410300d676db3da23695897ffab189702865 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(6 : ℝ) / ((n : ℝ) + (4 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15067ce1292b5543445992c6eb6bb2a3d7159a83 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that the sequence \(u_n = \dfrac{6}{n + 4}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## 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/real-analysis/real-analysis-limit_sequence-d1-t0025/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fcc0296c5e58a34e900907ec8e3f89e593ad9eb0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(6 : ℝ) / ((n : ℝ) + (4 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(6 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (6 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (6 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hpos : (0 : ℝ) < (n : ℝ) + (4 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (4 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..74df99a065d8cbc6bbbc1115aaa8af853d4a3b22 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 25 + +[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/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/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/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/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/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..075f69013016eb3cd6de2a1a24d044d4afb63f93 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(6 : ℝ) / ((n : ℝ) + (4 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0025/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/real-analysis/real-analysis-limit_sequence-d1-t0049/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..875cd58e3af637d1e2aae60a21ddfbe1cf560760 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(3 : ℝ) / ((n : ℝ) + (6 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..734524a5b3e1386429bac551fe6048cc5282771f --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that the sequence \(u_n = \dfrac{3}{n + 6}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## 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/real-analysis/real-analysis-limit_sequence-d1-t0049/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d91a8205b8eed246c7cafcbe62c9aaa5237f3776 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(3 : ℝ) / ((n : ℝ) + (6 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(3 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (3 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (3 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hpos : (0 : ℝ) < (n : ℝ) + (6 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (6 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f17964559789781ec6993e0876c1a165f0c23d46 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +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/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-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/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-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/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2e29796b4bc2237cf4f2a0a0a7336627ffd63980 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(3 : ℝ) / ((n : ℝ) + (6 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-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/real-analysis/real-analysis-sequence_bounds-d1-e0002/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..14db7333a3818225da750e43929c7ba1abdd32d5 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/environment/workdir/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (8 / 3 : ℝ) + | (n + 1) => a n / 2 + (4 / 3 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (8 / 3 : ℝ) := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..159d8af1c1d450a2900c9f796cec6f150631e94a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{8}{3}\) and \(a_{n+1} = \frac{a_n}{2} + \frac{4}{3}\). Prove that \(0 \le a_n \le \frac{8}{3}\) for every \(n\). + +## 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/real-analysis/real-analysis-sequence_bounds-d1-e0002/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec816a8683c0a41145539eea4e7aa6af50273ce9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (8 / 3 : ℝ) + | (n + 1) => a n / 2 + (4 / 3 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (8 / 3 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ffc0c3443d04515c35094f1d47569803279e00a8 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "eval", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "eval" +seed = 10002 + +[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/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/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/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/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/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ce95fb230fbe21483e13a97e4e007c5e4775d4ff --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (8 / 3 : ℝ)\n | (n + 1) => a n / 2 + (4 / 3 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (8 / 3 : ℝ) := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0002/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/real-analysis/real-analysis-sequence_bounds-d2-t0018/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e15af0f1ef65533182551b1a373ad42599f26d0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (3 / 2 : ℝ) + | (n + 1) => a n / 2 + (3 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (6 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8377a5e2486b5dc25558d9ad540137d6a9e46c19 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{3}{2}\) and \(a_{n+1} = \frac{a_n}{2} + 3\). Prove that \(0 \le a_n \le 6\) for every \(n\), and then that the sequence is monotone (non-decreasing). + +## 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/real-analysis/real-analysis-sequence_bounds-d2-t0018/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..46e5df27f1c0e3219235472f54b96eb89db97a52 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/solution/Solution.lean @@ -0,0 +1,25 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (3 / 2 : ℝ) + | (n + 1) => a n / 2 + (3 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (6 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + have h := (a_bounds n).2 + simp only [a] + linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..177b6f6449a8c30710ff5e5f28ce09ee7678b14a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 18 + +[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/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/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/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/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/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..255fa7c1663b67fb9d11dee2938a9624f52332bb --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (3 / 2 : ℝ)\n | (n + 1) => a n / 2 + (3 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (6 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0018/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/real-analysis/real-analysis-sequence_bounds-d2-t0042/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1e420ea6786a6b373ecdca0ee515b19c015eba4 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (2 : ℝ) + | (n + 1) => a n / 2 + (1 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cde9865c3fa81a6b60a219b893151471f9471aec --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = 2\) and \(a_{n+1} = \frac{a_n}{2} + 1\). Prove that \(0 \le a_n \le 2\) for every \(n\), and then that the sequence is monotone (non-decreasing). + +## 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/real-analysis/real-analysis-sequence_bounds-d2-t0042/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2045939151a481de59d48d7a8e21aaaac772da4d --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/solution/Solution.lean @@ -0,0 +1,25 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (2 : ℝ) + | (n + 1) => a n / 2 + (1 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + have h := (a_bounds n).2 + simp only [a] + linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f58801b58152f4731a64d7b818fb67e113ac2026 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 42 + +[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/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/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/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/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/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b582ba28d468bddc083240477e335ad5240e1f58 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (2 : ℝ)\n | (n + 1) => a n / 2 + (1 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0042/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/real-analysis/real-analysis-uniform_bounds-d2-t0067/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5662114f29a9dd07c6df9ea23f040bd1ac37f307 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on partial geometric sums that does not depend on n or x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (3 / 4 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (3 / 4 : ℝ)) := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d05d21e339cce2c2d2e0c1974c7dc5c8a0c373e --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that for every natural number \(n\) and every real \(x\) with \(0 \le x \le \frac{3}{4}\), \[\sum_{i=0}^{n-1} x^{i} \le \frac{1}{1 - \frac{3}{4}}.\] The sum is empty when \(n = 0\). + +## 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/real-analysis/real-analysis-uniform_bounds-d2-t0067/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..064fc5ea1537a357ffacbc79df757def373a558e --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/solution/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +/-- A bound on partial geometric sums that does not depend on n or x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (3 / 4 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (3 / 4 : ℝ)) := by + intro n x hx + have hq : ((3 / 4 : ℝ) : ℝ) ≠ 1 := by norm_num + have h1 : ∑ i ∈ Finset.range n, x ^ i ≤ ∑ i ∈ Finset.range n, ((3 / 4 : ℝ) : ℝ) ^ i := + Finset.sum_le_sum fun i _ => pow_le_pow_left₀ hx.1 hx.2 i + have h2 : ∑ i ∈ Finset.range n, ((3 / 4 : ℝ) : ℝ) ^ i = (1 - (3 / 4 : ℝ) ^ n) / (1 - (3 / 4 : ℝ)) := by + rw [geom_sum_eq hq n, ← neg_sub, ← neg_sub 1, neg_div_neg_eq] + have h3 : (1 - (3 / 4 : ℝ) ^ n) / (1 - (3 / 4 : ℝ)) ≤ 1 / (1 - (3 / 4 : ℝ)) := by + have : (0 : ℝ) < (3 / 4 : ℝ) ^ n := by positivity + apply div_le_div_of_nonneg_right (by linarith) (by norm_num) + linarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..567b85845be455486bca53d1f809721ab007f037 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 67 + +[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/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/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/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/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/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c9eef93cfd78373cc3e523170b82441f09eff34e --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on partial geometric sums that does not depend on n or x. -/\ntheorem uniform_bound :\n ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (3 / 4 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (3 / 4 : ℝ)) := by\n sorry\n", + "targets": [ + { + "name": "uniform_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0067/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/real-analysis/real-analysis-uniform_bounds-d3-e0011/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a25950e4ebdf24935762a5d729ce34e58f88c99a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (1 / 4 : ℝ) → |5 * x ^ n| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9410411caf2bb123dea32bededc2b692c3617ffd --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that \(c\,x^n\) with \(c = 5\) tends to \(0\) uniformly on \([-\frac{1}{4}, \frac{1}{4}]\): for every \(\varepsilon > 0\) there is \(N\) such that \(|5\,x^n| < \varepsilon\) for all \(n \ge N\) and all real \(x\) with \(|x| \le \frac{1}{4}\). + +## 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/real-analysis/real-analysis-uniform_bounds-d3-e0011/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..035f5f7fa25f7933400ce7d11d225f05109cfe29 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (1 / 4 : ℝ) → |5 * x ^ n| < ε := by + intro ε hε + obtain ⟨N, hN⟩ := exists_pow_lt_of_lt_one (div_pos hε (by norm_num : (0 : ℝ) < (5 : ℝ))) (by norm_num : ((1 / 4 : ℝ) : ℝ) < 1) + refine ⟨N, fun n hn x hx => ?_⟩ + rw [abs_mul, abs_pow, show |((5 : ℝ))| = (5 : ℝ) by norm_num] + have h1 : |x| ^ n ≤ ((1 / 4 : ℝ) : ℝ) ^ n := pow_le_pow_left₀ (abs_nonneg x) hx n + have h2 : ((1 / 4 : ℝ) : ℝ) ^ n ≤ ((1 / 4 : ℝ) : ℝ) ^ N := pow_le_pow_of_le_one (by norm_num) (by norm_num) hn + have h3 : ((1 / 4 : ℝ) : ℝ) ^ N < ε / (5 : ℝ) := hN + rw [lt_div_iff₀ (by norm_num)] at h3 + nlinarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..62929ccaaa385a906dabfba7c1567a53a364247e --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "eval", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "eval" +seed = 10011 + +[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/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/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/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/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/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3e17a6dd78e6c26ba09eed676e4ced095cb7c8db --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Uniform convergence of a geometric sequence on an interval. -/\ntheorem uniform_convergence :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (1 / 4 : ℝ) → |5 * x ^ n| < ε := by\n sorry\n", + "targets": [ + { + "name": "uniform_convergence", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-e0011/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