diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fefdffdc4e9fdcee7bff0e654e52e0cef546e79 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 8x + 1\) 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-t0000/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9602e3f4c441252f566bdcc613b41ae07b72980f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/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 = 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/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-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/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6fcd17f1d39a9f81e577cb3dde1b49f7d6288955 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/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 + 1)).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-t0000/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-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/logic-and-sets/logic-and-sets-finset_card-d1-t0009/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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-t0009/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3891888558deb8c0f5cd4f8437b643d67cf2e21 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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 : ℕ => 5 * x + 5)) ×ˢ t).card = s.card * t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4193b50475ae4f78d2665fce1ec4747992175dc --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 5x + 5\) 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-t0009/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e96de74918f6d93acb6dde5bd68a8a1ea254283 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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 : ℕ => 5 * x + 5)) ×ˢ t).card = s.card * t.card := by + have hinj : Function.Injective (fun x : ℕ => 5 * x + 5) := 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-t0009/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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-t0009/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e599ff370e65420cbda3603be78e74cb464f79c1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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 = 9 + +[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-t0009/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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-t0009/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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-t0009/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..43339dc1543ae3eecd4feeda47969956a1834cbe --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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 : ℕ => 5 * x + 5)) ×ˢ 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-t0009/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0009/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-t0036/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/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-t0036/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8eb83a7392bb75158b358741131de55464a61a3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/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 : ℕ => 6 * x + 6)).card = s.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a5e3a056ea9d91e869fb84c7d780b24802257e1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 6x + 6\) 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-t0036/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d324aa6452085901138cfeb04b1be68c3a67083 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A cardinality fact about finite sets. -/ +theorem card_fact (s : Finset ℕ) : + (s.image (fun x : ℕ => 6 * x + 6)).card = s.card := by + have hinj : Function.Injective (fun x : ℕ => 6 * x + 6) := 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-t0036/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/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-t0036/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f67027553247517c3756e053703aa3293cfd6cd8 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/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 = 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/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-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/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-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/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..1c15a1eee979af74342ecd468d6649bb0ab73dbe --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/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 : ℕ => 6 * x + 6)).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-t0036/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-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/logic-and-sets/logic-and-sets-finset_card-d1-t0054/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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-t0054/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..837ac542ff075ac273946cd048675c1bc9d77b73 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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 : ℕ => 9 * x + 0)) ×ˢ t).card = s.card * t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7df8b3b392e5ccbfadd6d4fafab04f0ed4e28b60 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 9x + 0\) 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-t0054/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..40692a92229acff5e82f34e95d496fd48348dc24 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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 : ℕ => 9 * x + 0)) ×ˢ t).card = s.card * t.card := by + have hinj : Function.Injective (fun x : ℕ => 9 * x + 0) := 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-t0054/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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-t0054/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32d24dad99294e91838dc0209cf67ffab0003129 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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 = 54 + +[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-t0054/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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-t0054/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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-t0054/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..572f4a19e571b163133d562dfc92aeab41d7fd37 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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 : ℕ => 9 * x + 0)) ×ˢ 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-t0054/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0054/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-t0063/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/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-t0063/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..284a7f61032c811c8afe0921b682f318369f2df9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/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 + 8)) ×ˢ t).card = s.card * t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c26dda79bc6c592e78b21472fd551dc78cd1f07 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/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 + 8)) ×ˢ t).card = s.card * t.card := by + have hinj : Function.Injective (fun x : ℕ => 2 * x + 8) := 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-t0063/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/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-t0063/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d1-t0063/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-e0012/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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-e0012/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..804929f28a9008b0dceead05d9deca9056b12722 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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 + 8)).card + ((s ∩ t).image (fun x : ℕ => 5 * x + 8)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..72bd1b72fb4e59e1c064a70ef7fb7c7c2190ea64 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 5x + 8\) 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-e0012/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..93266133f58677fa00fee0d78ba5796a5a6402b3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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 : ℕ => 5 * x + 8)).card + ((s ∩ t).image (fun x : ℕ => 5 * x + 8)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 5 * x + 8) := 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-e0012/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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-e0012/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c9a50578e6ab2892216d65c6a0ca8c39a5d28f19 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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 = 10012 + +[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-e0012/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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-e0012/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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-e0012/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e1e60b498e3bdb8728f2c0a37678e66abb8ae559 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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 + 8)).card + ((s ∩ t).image (fun x : ℕ => 5 * x + 8)).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-e0012/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d2-e0012/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-t0006/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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-t0006/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..59f77293ee96436ef8bd227a9f72de92d137f647 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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 : ℕ => 4 * x + 6)).card = s.card + t.card := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/instruction.md b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8785aca42d539958c9c13ad84c94953f578903a0 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/instruction.md @@ -0,0 +1,14 @@ +# Prove a cardinality fact about finite sets + +Prove the following. + +Let \(f(x) = 4x + 6\) 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-t0006/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a66cd90ff9606cb7fd1db49b95132a5389aa0575 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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 : ℕ => 4 * x + 6)).card = s.card + t.card := by + have hinj : Function.Injective (fun x : ℕ => 4 * x + 6) := 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-t0006/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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-t0006/task.toml b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1398fa5c6830134ace14ac2d1bfbe12383bf2ac3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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 = 6 + +[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-t0006/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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-t0006/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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-t0006/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..38eca8d9d2366a0a8d31c8f865d08dededbc05de --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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 : ℕ => 4 * 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-d3-t0006/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-finset_card-d3-t0006/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-t0031/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/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-t0031/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7c457b45b9c480b6632fc66eff562353b7e6d01 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun p q : ℕ × ℕ => p.1 + 6 * q.2 = q.1 + 6 * p.2) := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/instruction.md b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97f5a0ddc386406d657e6ce795c5ffcea63160a4 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/instruction.md @@ -0,0 +1,14 @@ +# Prove properties of a relation + +Prove the following. + +On pairs of natural numbers define \((x_1, y_1) \sim (x_2, y_2) \iff x_1 + 6 y_2 = x_2 + 6 y_1\). Prove that \(\sim\) is an equivalence relation. + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9b5c92e948eb34b3b7fdc0943b5c45486f4b47c --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/solution/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The relation is reflexive, symmetric and transitive. -/ +theorem rel_equiv : + Equivalence (fun p q : ℕ × ℕ => p.1 + 6 * q.2 = q.1 + 6 * p.2) := ⟨fun p => by omega, fun {p q} h => by omega, fun {p q r} h1 h2 => by omega⟩ diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/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-t0031/task.toml b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a30a39ce54284c257a249d2f4f0e8a59d5c5d292 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/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 = 31 + +[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-t0031/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/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-t0031/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/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-t0031/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..440ed3266db5306f420e3ad7f11a09f3b675fa43 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The relation is reflexive, symmetric and transitive. -/\ntheorem rel_equiv :\n Equivalence (fun p q : ℕ × ℕ => p.1 + 6 * q.2 = q.1 + 6 * p.2) := by\n sorry\n", + "targets": [ + { + "name": "rel_equiv", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-relations-d2-t0031/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-t0002/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/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-t0002/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..438069514f4afb4478804e5d5798af8571f99ab1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (T C Y : Set α) : + (T ∩ C)ᶜ = Tᶜ ∪ Cᶜ := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02f5f00e1246793c48b972bd557482f9ff037cd3 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(T, C, Y\) be subsets of a type \(\alpha\). Prove the set identity \[(T \cap C)^{c} = T^{c} \cup C^{c}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3618c895b2001349019041e518f421b7be2ce94f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (T C Y : Set α) : + (T ∩ C)ᶜ = Tᶜ ∪ Cᶜ := 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-t0002/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/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-t0002/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..db2b6b2150b1ff7d9364d8b0c67755b6c3596791 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/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 = 2 + +[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-t0002/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/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-t0002/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/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-t0002/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ef46474e35660cf9a4b8684143141eccd3f30d45 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (T C Y : Set α) :\n (T ∩ C)ᶜ = Tᶜ ∪ Cᶜ := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0002/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-t0056/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/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-t0056/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7930b91b4fe4b2c9829aa81b97dd2c8b60d3885d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (X Y C : Set α) : + X ∩ Cᶜ = X \ C := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..904cef61e89f4a7ebf22ba6f5b9bc35e60b4d8b1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(X, Y, C\) be subsets of a type \(\alpha\). Prove the set identity \[X \cap C^{c} = X \setminus 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-d1-t0056/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..be257302fb6bc2b03db305999531dd4d0db58f8f --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (X Y C : Set α) : + X ∩ Cᶜ = X \ C := 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-t0056/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/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-t0056/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..62de3b26484ff7c9e433bf8bb42ef62e92c7da13 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/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 = 56 + +[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-t0056/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/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-t0056/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/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-t0056/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..11b62975a4ff990a8154cdb4b1b373c22aedd575 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (X Y C : Set α) :\n X ∩ Cᶜ = X \\ C := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d1-t0056/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-t0035/environment/Dockerfile b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/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-t0035/environment/workdir/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b6390ded5519198aaac24b50d4e6637c2c9e4aef --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (C A X : Set α) (h : C ⊆ A) : + ((C ∪ A) ∪ X)ᶜ = ((C ∩ A) ∪ (X ∪ A))ᶜ := by + sorry diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/instruction.md b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f3101580a9efb6df3ca59fdb9f425c543aa64fc --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/instruction.md @@ -0,0 +1,14 @@ +# Prove an identity between sets + +Prove the following. + +Let \(C, A, X\) be subsets of a type \(\alpha\). Assume that \(C \subseteq A\). Prove the set identity \[((C \cup A) \cup X)^{c} = ((C \cap A) \cup (X \cup A))^{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-t0035/solution/Solution.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a8dcc6cb1d93a151cf978e9948f56416f7d0125 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The stated identity between sets. -/ +theorem set_identity {α : Type*} (C A X : Set α) (h : C ⊆ A) : + ((C ∪ A) ∪ X)ᶜ = ((C ∩ A) ∪ (X ∪ A))ᶜ := by + ext x + have hx : x ∈ C → x ∈ A := @h x + simp only [Set.mem_union, Set.mem_inter_iff, Set.mem_diff, Set.mem_compl_iff] + all_goals tauto diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/solution/solve.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/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-t0035/task.toml b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0f3a2a9ba208149b9ef305067f42128e60ad3592 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/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 = 35 + +[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-t0035/tests/Verify.lean b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/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-t0035/tests/grade.py b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/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-t0035/tests/spec.json b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..eafb2086d6a3c4a22ca1652e6e80e7aef02c454d --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The stated identity between sets. -/\ntheorem set_identity {α : Type*} (C A X : Set α) (h : C ⊆ A) :\n ((C ∪ A) ∪ X)ᶜ = ((C ∩ A) ∪ (X ∪ A))ᶜ := by\n sorry\n", + "targets": [ + { + "name": "set_identity", + "weight": 1.0 + } + ] +} diff --git a/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/tests/test.sh b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/logic-and-sets/logic-and-sets-set_identities-d3-t0035/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