{
 "board": "lean-factor",
 "instance": "lf-model-v1",
 "mode": "ranked",
 "cpu_seconds": 1800,
 "mem_mb": 16000,
 "model": "QArena.Factor, cost model version 1 (leanfactor/QArenaFactor/Model.lean, frozen)",
 "statement": "theorem QArenaSubmission.result : QArena.Factor.PolyBound QArenaSubmission.algo C a b D, where PolyBound algo C a b D := 0 < D ∧ ∀ N : Nat, 2 ≤ N → ∀ tape : Nat → Bool, (∃ σ, Exec algo (init N tape) σ) ∧ ∀ σ, Exec algo (init N tape) σ → Correct N (σ.reg 1) ∧ σ.cost ^ D ≤ C ^ D * N ^ a * len N ^ b",
 "submission": {
  "artifact": "{\"lean\": \"<the text of one Lean 4 file>\"}",
  "module": "Submission",
  "program": "QArenaSubmission.algo : QArena.Factor.Stmt",
  "theorem": "QArenaSubmission.result",
  "max_source_bytes": 4194304,
  "max_artifact_bytes": 8388608,
  "max_digits": 300,
  "max_program_nodes": 100000
 },
 "axioms": [
  "propext",
  "Classical.choice",
  "Quot.sound"
 ],
 "kernel_roots": [
  "Nat",
  "Nat.add",
  "Nat.sub",
  "Nat.mul",
  "Nat.div",
  "Nat.mod",
  "Nat.gcd",
  "Nat.beq",
  "Nat.ble",
  "Nat.land",
  "Nat.lor",
  "Nat.xor",
  "Nat.shiftLeft",
  "Nat.shiftRight",
  "Nat.pow",
  "String.ofList",
  "Char.ofNat",
  "Bool",
  "List",
  "eagerReduce",
  "String",
  "String.mk",
  "Char",
  "optParam",
  "autoParam",
  "semiOutParam",
  "outParam",
  "Quot",
  "Quot.mk",
  "Quot.lift",
  "Quot.ind"
 ],
 "score": {
  "e": "a/D (exact rational)",
  "k": "b/D (exact rational)",
  "C": "C",
  "order": "e, then k, then C, lower first; equal keys by submission number"
 },
 "pins": {
  "lean": "v4.36.0",
  "lean_commit": "611c117bfaf7",
  "lean_tarball": "lean-4.36.0-linux.tar.zst",
  "lean_tarball_sha256": "2b7ab1ed8b92d2e6abfaf41344823b510064dbc9c0260cac73eb496ab2dea6eb",
  "mathlib": "v4.36.0",
  "mathlib_commit": "fc4f59e577feb1a4956671bc04ac18aaaf8cd842",
  "reference_export_sha256": "0c1f3873764fb31043e8107595c55c4eee8f490858d164e9da26cdb88ab71b01"
 },
 "files": {
  "leanfactor/lean-toolchain": "leanprover/lean4:v4.36.0\n",
  "leanfactor/lakefile.toml": "name = \"qarena_factor\"\nversion = \"1.0.0\"\ndefaultTargets = [\"QArenaFactor\", \"qafactor_check\"]\n\n[[require]]\nname = \"mathlib\"\ngit = \"https://github.com/leanprover-community/mathlib4.git\"\nrev = \"v4.36.0\"\n\n[[lean_lib]]\nname = \"QArenaFactor\"\nmoreLeanArgs = [\"-j4\"]\n\n[[lean_exe]]\nname = \"qafactor_check\"\nroot = \"QArenaFactorCheck\"\nsupportInterpreter = true\nmoreLeanArgs = [\"-j4\"]\n",
  "leanfactor/lake-manifest.json": "{\"version\": \"1.3.0\",\n \"packagesDir\": \".lake/packages\",\n \"packages\":\n [{\"url\": \"https://github.com/leanprover-community/mathlib4.git\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"\",\n   \"rev\": \"fc4f59e577feb1a4956671bc04ac18aaaf8cd842\",\n   \"name\": \"mathlib\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"v4.36.0\",\n   \"inherited\": false,\n   \"configFile\": \"lakefile.lean\"},\n  {\"url\": \"https://github.com/leanprover-community/plausible\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"054b228ce0ac61d767c6e71ba73a24728f191b72\",\n   \"name\": \"plausible\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"main\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"},\n  {\"url\": \"https://github.com/leanprover-community/LeanSearchClient\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"4fb58e749ef3fc0395fe274f6cab70c2ea85f1c9\",\n   \"name\": \"LeanSearchClient\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"main\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"},\n  {\"url\": \"https://github.com/leanprover-community/import-graph\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"8370c640afcd1cc3fb1cb9bf1560cc66eafee5e0\",\n   \"name\": \"importGraph\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"main\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"},\n  {\"url\": \"https://github.com/leanprover-community/ProofWidgets4\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"2f0f3520daeac2d9310ff25b7a877a0e5cdaa203\",\n   \"name\": \"proofwidgets\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"main\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.lean\"},\n  {\"url\": \"https://github.com/leanprover-community/aesop\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"66ff77cf0c4c898799e4b94d14db55f7a02d0c5a\",\n   \"name\": \"aesop\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"master\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"},\n  {\"url\": \"https://github.com/leanprover-community/quote4\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"ff055a2fcc835935e0ae607339b455a5f5896b4b\",\n   \"name\": \"Qq\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"master\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"},\n  {\"url\": \"https://github.com/leanprover-community/batteries\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover-community\",\n   \"rev\": \"b4b25a3886a16daacaf6615c2eea7170a6e8f458\",\n   \"name\": \"batteries\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"main\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"},\n  {\"url\": \"https://github.com/leanprover/lean4-cli\",\n   \"type\": \"git\",\n   \"subDir\": null,\n   \"scope\": \"leanprover\",\n   \"rev\": \"50810f72af7618bee62fe9800dc26e806c188703\",\n   \"name\": \"Cli\",\n   \"manifestFile\": \"lake-manifest.json\",\n   \"inputRev\": \"v4.36.0\",\n   \"inherited\": true,\n   \"configFile\": \"lakefile.toml\"}],\n \"name\": \"qarena_factor\",\n \"lakeDir\": \".lake\",\n \"fixedToolchain\": false}\n",
  "leanfactor/QArenaFactor/Model.lean": "/-\nQArena \"proven factoring complexity\" board: the frozen cost model, version 1.\n\nPinned to Lean v4.36.0 and Mathlib v4.36.0 (commit fc4f59e577feb1a4956671bc04ac18aaaf8cd842).\nOnce the board opens, this file never changes; a change is a new model version with its own\nleaderboard.\n\nWhat a submission proves: `PolyBound algo C a b D`, i.e. the program `algo` (a value of the\nsyntax type `Stmt` below, run by the big-step semantics `Exec`) terminates on every input\n`N ≥ 2`, every run returns a correct answer, and the bit cost of the run satisfies\n`cost ≤ C · N^(a/D) · (len N)^(b/D)`, written without real numbers as\n`cost ^ D ≤ C ^ D * N ^ a * (len N) ^ b`.\n\nWhy the model is airtight against cheap arithmetic: the program is data (an abstract syntax\ntree), so it can only compute through the primitives below, and every primitive is charged at\nleast the bit length of every number it reads or writes, plus the schoolbook product of the\noperand lengths for `mul`, `div` and `mod`. Unit-cost arithmetic on huge numbers (Shamir 1977)\npays for the length of those numbers, and no library function is callable from a program.\n-/\nimport Mathlib.Data.Nat.Prime.Defs\n\nnamespace QArena.Factor\n\n/-- Bit length of a natural number, counting `0` as one bit (`len 0 = len 1 = 1`). -/\ndef len (n : Nat) : Nat := n.log2 + 1\n\n/-- Binary register operations. `sub` truncates at zero; `div` and `mod` follow Lean\n(`a / 0 = 0`, `a % 0 = a`); `shl a b = a * 2 ^ b`, `shr a b = a / 2 ^ b`. -/\ninductive BinOp where\n  | add | sub | mul | div | mod | shl | shr | band | bor | bxor\n  deriving DecidableEq, Repr\n\n/-- The value an operation computes. -/\ndef BinOp.eval : BinOp → Nat → Nat → Nat\n  | .add, a, b => a + b\n  | .sub, a, b => a - b\n  | .mul, a, b => a * b\n  | .div, a, b => a / b\n  | .mod, a, b => a % b\n  | .shl, a, b => a <<< b\n  | .shr, a, b => a >>> b\n  | .band, a, b => a &&& b\n  | .bor, a, b => a ||| b\n  | .bxor, a, b => a ^^^ b\n\n/-- Bit operations charged for one binary operation on values `a`, `b`: one step, the lengths\nof both operands and of the result, and for `mul`, `div`, `mod` the schoolbook term\n`len a * len b`. The result length makes a shift by a huge amount pay for the bits it creates. -/\ndef BinOp.cost (op : BinOp) (a b : Nat) : Nat :=\n  1 + len a + len b + len (op.eval a b) +\n    (match op with\n     | .mul | .div | .mod => len a * len b\n     | _ => 0)\n\n/-- Branch and loop conditions compare two registers. -/\ninductive Cond where\n  | lt (a b : Nat)\n  | eq (a b : Nat)\n  deriving DecidableEq, Repr\n\n/-- Programs. Registers and memory cells hold natural numbers of any size; register indices are\nfixed by the program text, memory addresses are computed values. -/\ninductive Stmt where\n  | skip\n  /-- `reg r := k` -/\n  | const (r k : Nat)\n  /-- `reg r := reg s` -/\n  | copy (r s : Nat)\n  /-- `reg r := op (reg a) (reg b)` -/\n  | bin (op : BinOp) (r a b : Nat)\n  /-- `reg r := mem[reg a]` -/\n  | load (r a : Nat)\n  /-- `mem[reg a] := reg v` -/\n  | store (a v : Nat)\n  /-- `reg r := next bit of the random tape` (0 or 1) -/\n  | coin (r : Nat)\n  | seq (s t : Stmt)\n  | ite (c : Cond) (s t : Stmt)\n  /-- `while c do s` -/\n  | loop (c : Cond) (s : Stmt)\n  deriving DecidableEq, Repr\n\n/-- Number of syntax nodes (used by the verifier to check that a program is a concrete value). -/\ndef Stmt.size : Stmt → Nat\n  | .seq s t => s.size + t.size + 1\n  | .ite _ s t => s.size + t.size + 1\n  | .loop _ s => s.size + 1\n  | _ => 1\n\n/-- Machine state: registers, memory (initially zero everywhere), the random tape with its read\nposition, and the bit operations spent so far. -/\nstructure State where\n  reg : Nat → Nat\n  mem : Nat → Nat\n  tape : Nat → Bool\n  pos : Nat\n  cost : Nat\n\n/-- Set register `r` to `v`. -/\ndef State.write (σ : State) (r v : Nat) : State :=\n  { σ with reg := fun i => if i = r then v else σ.reg i }\n\n/-- Set memory cell `a` to `v`. -/\ndef State.poke (σ : State) (a v : Nat) : State :=\n  { σ with mem := fun i => if i = a then v else σ.mem i }\n\n/-- Charge `c` bit operations. -/\ndef State.tick (σ : State) (c : Nat) : State :=\n  { σ with cost := σ.cost + c }\n\ndef Cond.eval : Cond → State → Bool\n  | .lt a b, σ => decide (σ.reg a < σ.reg b)\n  | .eq a b, σ => decide (σ.reg a = σ.reg b)\n\n/-- A test costs one step plus the lengths of the two values compared. -/\ndef Cond.cost : Cond → State → Nat\n  | .lt a b, σ => 1 + len (σ.reg a) + len (σ.reg b)\n  | .eq a b, σ => 1 + len (σ.reg a) + len (σ.reg b)\n\n/-- Big-step semantics with bit-cost accounting. `Exec s σ σ'` means: run from `σ`, the program\n`s` terminates in `σ'` (whose `cost` field includes everything charged). Only terminating runs\nhave derivations, and the relation is deterministic (`Exec.det`). -/\ninductive Exec : Stmt → State → State → Prop where\n  | skip (σ : State) : Exec .skip σ (σ.tick 1)\n  | const (r k : Nat) (σ : State) :\n      Exec (.const r k) σ ((σ.write r k).tick (1 + len k))\n  | copy (r s : Nat) (σ : State) :\n      Exec (.copy r s) σ ((σ.write r (σ.reg s)).tick (1 + 2 * len (σ.reg s)))\n  | bin (op : BinOp) (r a b : Nat) (σ : State) :\n      Exec (.bin op r a b) σ\n        ((σ.write r (op.eval (σ.reg a) (σ.reg b))).tick (op.cost (σ.reg a) (σ.reg b)))\n  | load (r a : Nat) (σ : State) :\n      Exec (.load r a) σ\n        ((σ.write r (σ.mem (σ.reg a))).tick (1 + len (σ.reg a) + len (σ.mem (σ.reg a))))\n  | store (a v : Nat) (σ : State) :\n      Exec (.store a v) σ ((σ.poke (σ.reg a) (σ.reg v)).tick (1 + len (σ.reg a) + len (σ.reg v)))\n  | coin (r : Nat) (σ : State) :\n      Exec (.coin r) σ\n        ({ σ.write r (if σ.tape σ.pos then 1 else 0) with pos := σ.pos + 1 }.tick 1)\n  | seq {s t : Stmt} {σ σ' σ'' : State} :\n      Exec s σ σ' → Exec t σ' σ'' → Exec (.seq s t) σ σ''\n  | iteT {c : Cond} {s t : Stmt} {σ σ' : State} :\n      c.eval σ = true → Exec s (σ.tick (c.cost σ)) σ' → Exec (.ite c s t) σ σ'\n  | iteF {c : Cond} {s t : Stmt} {σ σ' : State} :\n      c.eval σ = false → Exec t (σ.tick (c.cost σ)) σ' → Exec (.ite c s t) σ σ'\n  | loopT {c : Cond} {s : Stmt} {σ σ' σ'' : State} :\n      c.eval σ = true → Exec s (σ.tick (c.cost σ)) σ' → Exec (.loop c s) σ' σ'' →\n        Exec (.loop c s) σ σ''\n  | loopF {c : Cond} {s : Stmt} {σ : State} :\n      c.eval σ = false → Exec (.loop c s) σ (σ.tick (c.cost σ))\n\n/-- The semantics is deterministic: a program run from a given state (tape included) has at most\none final state. -/\ntheorem Exec.det {s : Stmt} {σ σ₁ σ₂ : State} (h₁ : Exec s σ σ₁) (h₂ : Exec s σ σ₂) :\n    σ₁ = σ₂ := by\n  induction h₁ generalizing σ₂ with\n  | skip => cases h₂; rfl\n  | const => cases h₂; rfl\n  | copy => cases h₂; rfl\n  | bin => cases h₂; rfl\n  | load => cases h₂; rfl\n  | store => cases h₂; rfl\n  | coin => cases h₂; rfl\n  | seq _ _ ih₁ ih₂ =>\n    cases h₂ with\n    | seq h₁' h₂' => cases ih₁ h₁'; exact ih₂ h₂'\n  | iteT hc _ ih =>\n    cases h₂ with\n    | iteT _ h => exact ih h\n    | iteF hc' _ => rw [hc] at hc'; cases hc'\n  | iteF hc _ ih =>\n    cases h₂ with\n    | iteT hc' _ => rw [hc] at hc'; cases hc'\n    | iteF _ h => exact ih h\n  | loopT hc _ _ ih₁ ih₂ =>\n    cases h₂ with\n    | loopT _ h₁' h₂' => cases ih₁ h₁'; exact ih₂ h₂'\n    | loopF hc' => rw [hc] at hc'; cases hc'\n  | loopF hc =>\n    cases h₂ with\n    | loopT hc' _ _ => rw [hc] at hc'; cases hc'\n    | loopF _ => rfl\n\n/-- Initial state on input `N`: register 0 holds `N`, every other register and every memory\ncell holds 0, the tape is read from position 0, nothing has been spent. -/\ndef init (N : Nat) (tape : Nat → Bool) : State where\n  reg := fun i => if i = 0 then N else 0\n  mem := fun _ => 0\n  tape := tape\n  pos := 0\n  cost := 0\n\n/-- What counts as factoring `N ≥ 2`: the output `d` (register 1 at the end) is a divisor of `N`\ngreater than 1, and it equals `N` only when `N` is prime. So a composite `N` gets a nontrivial\nfactor and a prime `N` gets `d = N` (a sign of primality only through the proven theorem). -/\ndef Correct (N d : Nat) : Prop := 1 < d ∧ d ∣ N ∧ (d = N → N.Prime)\n\n/-- The ranked statement (deterministic track, polynomial family): for every `N ≥ 2` and every\nrandom tape, the run terminates, and every run is correct with\n`cost ^ D ≤ C ^ D * N ^ a * (len N) ^ b`, i.e. `cost ≤ C · N^(a/D) · (len N)^(b/D)`.\nEntries rank by `a/D`, then `b/D`, then `C`. Requiring every tape makes a coin-using program\nanswer for its worst tape. -/\ndef PolyBound (algo : Stmt) (C a b D : Nat) : Prop :=\n  0 < D ∧ ∀ N : Nat, 2 ≤ N → ∀ tape : Nat → Bool,\n    (∃ σ, Exec algo (init N tape) σ) ∧\n    ∀ σ, Exec algo (init N tape) σ → Correct N (σ.reg 1) ∧ σ.cost ^ D ≤ C ^ D * N ^ a * len N ^ b\n\n/-- Convenience: by determinism one good run per input and tape is enough. -/\ntheorem PolyBound.intro {algo : Stmt} {C a b D : Nat} (hD : 0 < D)\n    (h : ∀ N : Nat, 2 ≤ N → ∀ tape : Nat → Bool, ∃ σ, Exec algo (init N tape) σ ∧\n      Correct N (σ.reg 1) ∧ σ.cost ^ D ≤ C ^ D * N ^ a * len N ^ b) :\n    PolyBound algo C a b D := by\n  refine ⟨hD, fun N hN tape => ?_⟩\n  obtain ⟨σ, hσ, hc, hb⟩ := h N hN tape\n  exact ⟨⟨σ, hσ⟩, fun σ' hσ' => Exec.det hσ hσ' ▸ ⟨hc, hb⟩⟩\n\nend QArena.Factor\n",
  "leanfactor/QArenaFactorCheck.lean": "/-\nQArena factoring board: statement checker on a text export (second implementation, in Lean).\n\nusage: qafactor_check SUB.ndjson\n\nReads the export with Lean's own export parser (no .olean of the submission is loaded), replays\nevery declaration through the Lean kernel into an empty environment, then checks:\n  * `QArenaSubmission.result` is a theorem of type\n    `QArena.Factor.PolyBound QArenaSubmission.algo C a b D` with natural-number literals, D > 0;\n  * `QArenaSubmission.algo` is a definition of type `QArena.Factor.Stmt`;\n  * every axiom of the export is one of propext, Classical.choice, Quot.sound;\n  * `algo` is a concrete program: kernel weak-head reduction turns it, all the way down, into\n    the `Stmt` and `Cond` constructors, exactly one of the ten nullary `BinOp` constructors for\n    each operation, and numerals (a program chosen with `Classical.choice`, an opaque operation\n    or any other stuck term is rejected), with at most 100,000 statement nodes. The normalized\n    program is printed with its node count.\nThe identity of the frozen declarations with the trusted build is checked by leanfactor_s1.py.\nWritten for QArena run qa_lean_factor_design2; exact operation match, axioms of the whole\nexport, node count and the 300-digit numeral limit added in run qa_lean_factor_build\n(discussion/lean_factor/astra_lean.md section A). Exit code 0 accepted, 1 rejected, 125 a\nresource limit of the kernel (run qa_fix_atk_leanfactor, m2): no verdict, the driver reports\nstatus error.\n-/\nimport Lean\nimport LeanExport.Parse\n\nopen Lean\n\nnamespace QArenaFactorCheck\n\ndef whitelist : List Name := [``propext, ``Classical.choice, ``Quot.sound]\n\ndef jsonStr (s : String) : String := (Json.str s).compress\n\ndef reject (why : String) : IO UInt32 := do\n  IO.println s!\"\\{\\\"status\\\": \\\"rejected\\\", \\\"reason\\\": {jsonStr why}}\"\n  return 1\n\n/-- A resource limit, not a verdict: the reason on stderr and exit 125, which the driver reads as\na limit (status error). -/\ndef limit (why : String) : IO UInt32 := do\n  IO.eprintln s!\"limit: {why}\"\n  return 125\n\n/-- How Lean v4.36.0 ends a kernel message for a resource limit rather than an ill-typed export:\nthe four resource kinds of `Kernel.Exception` (Lean/Message.lean), the kernel's refusals to\nevaluate oversized numerals, which it throws as `other` (src/kernel/type_checker.cpp), and a\nfailed stack-size query (src/runtime/stackinfo.cpp). Replay puts the kernel's message last,\nafter its \"while replaying declaration\" lines. The driver's `KERNEL_LIMITS` is the same list. -/\ndef limitEndings : List String :=\n  [\"(kernel) deterministic timeout\",\n   \"(kernel) excessive memory consumption detected\",\n   \"(kernel) deep recursion detected, use `set_option maxRecDepth <num>` to increase the limit\",\n   \"(kernel) interrupted\",\n   \"increase the LEAN_NAT_MAX_SIZE environment variable to allow it\",\n   \"because its second argument does not fit in a 32-bit unsigned integer\",\n   \"(kernel) failed to retrieve thread stack size\"]\n\ndef isLimit (msg : String) : Bool :=\n  limitEndings.any fun x => msg.trimAsciiEnd.endsWith x\n\n/-- Marks a reduction that stopped at a resource limit, so `run` exits 125 instead of rejecting. -/\ndef limitTag : String := \"limit: \"\n\n/-- C, a, b, D have at most this many decimal digits (a verifier rule, as in leanfactor_s1.py). -/\ndef maxDigits : Nat := 300\n\n/-- A natural-number literal: raw, or `@OfNat.ofNat ℕ n (instOfNatNat n)`. -/\ndef natLit? (e : Expr) : Option Nat :=\n  match e with\n  | .lit (.natVal n) => some n\n  | _ =>\n    if e.isAppOfArity ``OfNat.ofNat 3 then\n      match e.getArg! 0, e.getArg! 1, e.getArg! 2 with\n      | .const ``Nat [], .lit (.natVal n), .app (.const ``instOfNatNat []) (.lit (.natVal m)) =>\n        if n == m && e.getAppFn == .const ``OfNat.ofNat [.zero] then some n else none\n      | _, _, _ => none\n    else none\n\n/-- Every axiom declared in the export (the export is the closure of `result`, `algo` and the\nkernel-evaluated constants, so these are the axioms anything checked here may use). -/\ndef exportAxioms (consts : Std.HashMap Name ConstantInfo) : NameSet :=\n  consts.fold (init := {}) fun s n ci => match ci with\n    | .axiomInfo _ => s.insert n\n    | _ => s\n\n/-- Kernel weak-head normal form in the replayed environment. Both kernels accepted the export, so a\nkernel exception here (deep recursion, a numeral the kernel refuses to evaluate) proves nothing\nabout the program: a resource limit, never a verdict. -/\ndef whnf (env : Environment) (e : Expr) : Except String Expr :=\n  match Kernel.whnf env {} e with\n  | .ok e => .ok e\n  | .error _ => .error (limitTag ++ \"the kernel's reduction of the program stopped at a resource limit\")\n\npartial def evalNat (env : Environment) (e : Expr) : Except String Nat := do\n  let e ← whnf env e\n  match e with\n  | .lit (.natVal n) => return n\n  | .const ``Nat.zero [] => return 0\n  | .app (.const ``Nat.succ []) x => return (← evalNat env x) + 1\n  | _ => throw \"a numeral in the program does not reduce to a literal\"\n\ndef ctorName (env : Environment) (e : Expr) : Except String (Name × Array Expr) := do\n  let e ← whnf env e\n  match e.getAppFn with\n  | .const n _ => return (n, e.getAppArgs)\n  | _ => throw \"the program does not reduce to constructors\"\n\n/-- The ten operations, exactly: a nullary constructor of `BinOp` and nothing else (an opaque\nconstant or any other term in the `BinOp` namespace is not an operation). -/\ndef binOps : List Name :=\n  [`QArena.Factor.BinOp.add, `QArena.Factor.BinOp.sub, `QArena.Factor.BinOp.mul,\n   `QArena.Factor.BinOp.div, `QArena.Factor.BinOp.mod, `QArena.Factor.BinOp.shl,\n   `QArena.Factor.BinOp.shr, `QArena.Factor.BinOp.band, `QArena.Factor.BinOp.bor,\n   `QArena.Factor.BinOp.bxor]\n\ndef evalOp (env : Environment) (e : Expr) : Except String String := do\n  let e ← whnf env e\n  match e with\n  | .const n [] => if binOps.contains n then return n.getString! else throw s!\"not a BinOp constructor: {n}\"\n  | _ => throw \"an operation does not reduce to one of the ten BinOp constructors\"\n\ndef evalCond (env : Environment) (e : Expr) : Except String String := do\n  let (n, args) ← ctorName env e\n  if args.size == 2 && (n == `QArena.Factor.Cond.lt || n == `QArena.Factor.Cond.eq) then\n    return s!\"({n.getString!} {← evalNat env args[0]!} {← evalNat env args[1]!})\"\n  throw s!\"not a Cond constructor: {n}\"\n\n/-- The program as an S-expression; `budget` bounds the number of nodes. -/\npartial def evalStmt (env : Environment) (e : Expr) (budget : IO.Ref Nat) :\n    ExceptT String IO String := do\n  let b ← budget.get\n  if b == 0 then throw \"program larger than the display budget\"\n  budget.set (b - 1)\n  let (n, a) ← ExceptT.mk (pure (ctorName env e))\n  let nat (i : Nat) : ExceptT String IO Nat := ExceptT.mk (pure (evalNat env a[i]!))\n  let S := `QArena.Factor.Stmt\n  if n == S ++ `skip && a.size == 0 then return \"skip\"\n  else if n == S ++ `const && a.size == 2 then return s!\"(const {← nat 0} {← nat 1})\"\n  else if n == S ++ `copy && a.size == 2 then return s!\"(copy {← nat 0} {← nat 1})\"\n  else if n == S ++ `bin && a.size == 4 then\n    let op ← ExceptT.mk (pure (evalOp env a[0]!))\n    return s!\"({op} {← nat 1} {← nat 2} {← nat 3})\"\n  else if n == S ++ `load && a.size == 2 then return s!\"(load {← nat 0} {← nat 1})\"\n  else if n == S ++ `store && a.size == 2 then return s!\"(store {← nat 0} {← nat 1})\"\n  else if n == S ++ `coin && a.size == 1 then return s!\"(coin {← nat 0})\"\n  else if n == S ++ `seq && a.size == 2 then\n    return s!\"(seq {← evalStmt env a[0]! budget} {← evalStmt env a[1]! budget})\"\n  else if n == S ++ `ite && a.size == 3 then\n    let c ← ExceptT.mk (pure (evalCond env a[0]!))\n    return s!\"(ite {c} {← evalStmt env a[1]! budget} {← evalStmt env a[2]! budget})\"\n  else if n == S ++ `loop && a.size == 2 then\n    let c ← ExceptT.mk (pure (evalCond env a[0]!))\n    return s!\"(loop {c} {← evalStmt env a[1]! budget})\"\n  else throw s!\"not a Stmt constructor: {n}\"\n\ndef run (path : String) : IO UInt32 := do\n  let exportEnv ← IO.FS.withFile path .read fun h => LeanExport.parseStream (.ofHandle h)\n  let quotTargets := [``Quot.mk, ``Quot.lift, ``Quot.ind]\n  let constMap := quotTargets.foldl (init := exportEnv.constMap) (·.erase ·)\n  let kenv ← try (← mkEmptyEnvironment).toKernelEnv.replay constMap\n    catch e =>\n      let msg := toString e\n      return ← if isLimit msg then limit msg else reject s!\"kernel rejects the export: {msg.take 200}\"\n  let env := Environment.ofKernelEnv kenv\n  let resultN := `QArenaSubmission.result\n  let algoN := `QArenaSubmission.algo\n  let some (.defnInfo algo) := env.find? algoN\n    | reject \"QArenaSubmission.algo must be a definition\"\n  unless algo.levelParams.isEmpty && algo.type == .const `QArena.Factor.Stmt [] do\n    return ← reject \"QArenaSubmission.algo must have type QArena.Factor.Stmt\"\n  let some (.thmInfo res) := env.find? resultN\n    | reject \"QArenaSubmission.result must be a theorem\"\n  unless res.levelParams.isEmpty do\n    return ← reject \"QArenaSubmission.result must not have universe parameters\"\n  let ty := res.type\n  unless ty.isAppOfArity `QArena.Factor.PolyBound 5 && ty.getAppFn == .const `QArena.Factor.PolyBound [] do\n    return ← reject \"result's type is not QArena.Factor.PolyBound applied to five arguments\"\n  let args := ty.getAppArgs\n  unless args[0]! == .const algoN [] do\n    return ← reject \"result's program argument is not QArenaSubmission.algo\"\n  let some C := natLit? args[1]! | reject \"C is not a numeral\"\n  let some a := natLit? args[2]! | reject \"a is not a numeral\"\n  let some b := natLit? args[3]! | reject \"b is not a numeral\"\n  let some D := natLit? args[4]! | reject \"D is not a numeral\"\n  if D == 0 then return ← reject \"D = 0\"\n  for x in [C, a, b, D] do\n    if (toString x).length > maxDigits then\n      return ← reject s!\"C, a, b, D must have at most {maxDigits} digits each\"\n  let axs := exportAxioms exportEnv.constMap\n  for ax in axs do\n    unless whitelist.contains ax do\n      return ← reject s!\"axiom {ax} is not allowed\"\n  let maxNodes := 100000\n  let budget ← IO.mkRef maxNodes\n  let prog ← match ← (evalStmt env (.const algoN []) budget).run with\n    | .ok s => pure s\n    | .error e => return ← if e.startsWith limitTag then limit e else reject s!\"algo is not a concrete program: {e}\"\n  let nodes := maxNodes - (← budget.get)\n  let axList := (axs.toList.map toString).toArray.qsort (· < ·)\n  IO.println s!\"\\{\\\"status\\\": \\\"accepted\\\", \\\"C\\\": {C}, \\\"a\\\": {a}, \\\"b\\\": {b}, \\\"D\\\": {D}, \\\"axioms\\\": {(toJson axList).compress}, \\\"declarations\\\": {exportEnv.constMap.size}, \\\"nodes\\\": {nodes}, \\\"program\\\": {jsonStr prog}}\"\n  return 0\n\nend QArenaFactorCheck\n\ndef main (args : List String) : IO UInt32 := do\n  match args with\n  | [path] => QArenaFactorCheck.run path\n  | _ => QArenaFactorCheck.reject \"usage: qafactor_check SUB.ndjson\"\n",
  "leanfactor/install_store.sh": "#!/bin/bash\n# Build the read-only Lean store of the lean-factor board's verifier (site/verifiers/leanfactor.py) on a lane machine (on\n# Derecho a compute node, which reaches GitHub: runs/qa_lean_factor_build/derecho/install_store.pbs).\n#\n#   bash site/leanfactor/install_store.sh STORE_DIR\n#\n# STORE_DIR must not exist. The downloads and the Lake project go to STORE_DIR.build (about 13 GB; it may be deleted once the\n# store is built: the store's files are hard links, so they stay). Needs network (GitHub and Mathlib's cache server), curl,\n# git, tar with zstd, sha256sum and python3. Took 2.5 minutes on a 4-core box and 23 in a 4-core Derecho job (Lustre). Mathlib's\n# download cache goes to STORE_DIR.build/mathlib-cache, not to the home folder.\n#\n# Pins: Lean v4.36.0 (Linux x86-64 release tarball, SHA-256 below, commit 611c117bfaf7), Mathlib v4.36.0 (commit\n# fc4f59e577feb1a4956671bc04ac18aaaf8cd842) with every dependency at the commit in lake-manifest.json, and the trusted\n# reference export and the S2 checker, whose SHA-256 the verifier checks again on every run (REF_SHA256 and CHECK_SHA256 in\n# site/verifiers/leanfactor.py; the build is reproducible).\n#\n# The verifier finds the store at $QARENA_LEAN_STORE, else at ~/qarena_lean/store-v1 of the account that runs it (on Derecho,\n# build it under /glade/work and link ~/qarena_lean there). Then run the board's lane test on a compute node:\n# python3 site/tests/lane_leanfactor.py STORE_DIR WORK_DIR. The store also links the bubblewrap found on PATH now (bin/bwrap),\n# since the lane's jobs run with PATH=/usr/bin:/bin and Derecho has bwrap only in its software view.\nset -euo pipefail\nHERE=$(cd \"$(dirname \"$0\")\" && pwd)\nSTORE=${1:?usage: install_store.sh STORE_DIR}\n[ -e \"$STORE\" ] && { echo \"$STORE exists; give a new directory\" >&2; exit 2; }\nTAR=lean-4.36.0-linux.tar.zst\nTAR_SHA=2b7ab1ed8b92d2e6abfaf41344823b510064dbc9c0260cac73eb496ab2dea6eb\nREF_SHA=$(python3 -c 'import re,sys; print(re.search(r\"^REF_SHA256 = \\\"([0-9a-f]{64})\\\"\", open(sys.argv[1]).read(), re.M).group(1))' \\\n          \"$HERE/../verifiers/leanfactor.py\")\nB=\"$STORE.build\"\nmkdir -p \"$B\"\nB=$(cd \"$B\" && pwd)\ncd \"$B\"\nif [ ! -f \"$TAR\" ]; then\n  curl -fsSL -o \"$TAR.part\" \"https://github.com/leanprover/lean4/releases/download/v4.36.0/$TAR\"\n  mv \"$TAR.part\" \"$TAR\"\nfi\necho \"$TAR_SHA  $TAR\" | sha256sum -c -\nif [ ! -d toolchain ]; then\n  [ -e toolchain.part ] && { echo \"$B/toolchain.part is left from a failed run; delete it first\" >&2; exit 2; }\n  mkdir toolchain.part\n  tar --zstd -xf \"$TAR\" -C toolchain.part\n  mv toolchain.part/lean-4.36.0-linux toolchain\n  rmdir toolchain.part\nfi\nexport PATH=\"$B/toolchain/bin:$PATH\"\nexport LEAN_STACK_SIZE_KB=65536          # Lean's default thread stacks do not fit an address-space cap (prlimit --as)\nmkdir -p proj/QArenaFactor\ncp \"$HERE/lean-toolchain\" \"$HERE/lakefile.toml\" \"$HERE/lake-manifest.json\" \"$HERE/QArenaFactorCheck.lean\" proj/\ncp \"$HERE/QArenaFactor/Model.lean\" proj/QArenaFactor/\ncd proj\nexport MATHLIB_CACHE_DIR=\"$B/mathlib-cache\"\nlake exe cache get                      # Mathlib's prebuilt .olean files for the pinned commit\nlake build QArenaFactor.Model qafactor_check\nfor p in .lake/packages/*; do           # every dependency at the manifest's commit\n  n=$(basename \"$p\")\n  want=$(python3 -c 'import json,sys; print([q[\"rev\"] for q in json.load(open(\"lake-manifest.json\"))[\"packages\"] if q[\"name\"] == sys.argv[1]][0])' \"$n\")\n  got=$(git -C \"$p\" rev-parse HEAD)\n  [ \"$want\" = \"$got\" ] || { echo \"package $n is at $got, the manifest pins $want\" >&2; exit 3; }\ndone\nSTAGE=\"$STORE.part\"\n[ -e \"$STAGE\" ] && { echo \"$STAGE is left from a failed run; delete it first\" >&2; exit 2; }\nmkdir -p \"$STAGE/packages\" \"$STAGE/model/QArenaFactor\" \"$STAGE/bin\"\nBW=$(command -v bwrap) || { echo \"bwrap (bubblewrap) is not on PATH; the verifier's sandbox needs it\" >&2; exit 4; }\nBW=$(readlink -f \"$BW\")\n\"$BW\" --unshare-all --unshare-user --ro-bind / / true ||\n  echo \"warning: $BW cannot make a sandbox on this host; the lane test must pass on the lane's compute nodes\" >&2\nln -s \"$BW\" \"$STAGE/bin/bwrap\"\ncp -al \"$B/toolchain\" \"$STAGE/toolchain\"\nfor p in .lake/packages/*; do\n  n=$(basename \"$p\")\n  if [ -d \"$p/.lake/build/lib/lean\" ]; then\n    mkdir -p \"$STAGE/packages/$n/.lake/build/lib\"\n    cp -al \"$p/.lake/build/lib/lean\" \"$STAGE/packages/$n/.lake/build/lib/lean\"\n  fi\ndone\ncp .lake/build/lib/lean/QArenaFactor/Model.olean .lake/build/lib/lean/QArenaFactor/Model.ilean \"$STAGE/model/QArenaFactor/\"\ncp .lake/build/bin/qafactor_check \"$STAGE/bin/\"\nCHECK_SHA=$(python3 -c 'import re,sys; print(re.search(r\"^CHECK_SHA256 = \\\"([0-9a-f]{64})\\\"\", open(sys.argv[1]).read(), re.M).group(1))' \\\n            \"$HERE/../verifiers/leanfactor.py\")\necho \"$CHECK_SHA  $STAGE/bin/qafactor_check\" | sha256sum -c -\nLP=$(ls -d \"$STAGE\"/packages/*/.lake/build/lib/lean | tr '\\n' ':')\"$STAGE/model\"\n# The trusted reference export: the frozen template's closure, the three allowed axioms and the kernel's built-in constants (the\n# toolchain's own list and Bool: KERNEL_ROOTS in site/verifiers/leanfactor.py, which the board's lane test compares with the list).\nROOTS=$(python3 -c 'import re,sys; print(re.search(r\"^KERNEL_ROOTS = \\\"([^\\\"]+)\\\"\", open(sys.argv[1]).read(), re.M).group(1))' \\\n        \"$HERE/../verifiers/leanfactor.py\")\n# shellcheck disable=SC2086\nenv LEAN_PATH=\"$LP\" leanexport QArenaFactor.Model -- QArena.Factor.PolyBound propext Classical.choice Quot.sound $ROOTS \\\n  > \"$STAGE/ref.ndjson\"\necho \"$REF_SHA  $STAGE/ref.ndjson\" | sha256sum -c -\nchmod -R a-w \"$STAGE\"\nchmod u+w \"$STAGE\"\nmv \"$STAGE\" \"$STORE\"\nchmod a-w \"$STORE\"\necho \"store ready: $STORE\"\ndu -sh \"$STORE\" 2>/dev/null | tail -1\n"
 },
 "use": "Write each entry of files to its path (beside a verifiers/ folder holding leanfactor.py), then bash leanfactor/install_store.sh ~/qarena_lean/store-v1 builds the verifier's store; the same Lake project (lake exe cache get, then lake build) is a place to develop a submission against the frozen model.",
 "licence": "Apache-2.0",
 "source": "QArena's own model, checker and scripts (runs qa_lean_factor_design2 and qa_lean_factor_build; review discussion/lean_factor/astra_lean.md); Lean and Mathlib are named by version and commit, not copied"
}
