From 7ad87bdfb358253a731f6730d62b0acdcdbf84d8 Mon Sep 17 00:00:00 2001 From: Arthur Paulino Date: Thu, 26 Nov 2026 18:11:38 +0000 Subject: [PATCH] feat!: redesign LSpec v3 as a Bool-based, parallel-first, formally verified test framework MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Full breaking redesign of LSpec (v3.0.0) addressing import-time execution overhead and parallel test scalability observed in large consumers such as Ix, backed by a zero-sorry Lean formalization of the test runner enforced in CI: 1. **Zero import-time overhead & lazy test execution** - Replace Prop/Testable/Decidable assertions with Bool- and AssertM-based expectations (expect, shouldBe, shouldNotBe, shouldSatisfy, shouldBeLt/Le/Gt/Ge, shouldContain, shouldThrow, shouldReturn, expectSome/Ok/Err, pending/xit) with compile-time source locations via a meta-only pos% macro (zero runtime Lean compiler dependency). - Define AssertM as a nominal single-field structure (erased to IO (Except AssertStop α) at runtime) so do-notation cleanly lifts polymorphic IO actions such as IO.ofExcept and scoped resource getters. - Defer every leaf test (it, itBool, prop, propWith) under a Unit thunk inside SpecM (StateT (Array TestTree) BaseIO) and declare DSL macros using non-reserved symbols (&"...") so downstream identifiers like prop/it are never shadowed; regular `def mySuite : Spec := do ...` functions work for both top-level and parameterized suites with zero import-time test execution (and test libraries with heavy closed pure expressions can set `-Dcompiler.extract_closed=false` to prevent closed-term hoisting). - Drop #lspec, SlimCheck, and the plausible dependency so LSpec has zero external dependencies. 2. **Bounded-thread parallel execution with controlled memory usage** - Introduce a nest-core-inspired TestTree IR, IsTest typeclass, pluggable TestProcessor pipeline (Processors.list, Processors.console), and Hspec-style SpecM DSL (describe, context, it, prop, parallel, sequential, withTag/withTags, withOptions, withResource/beforeAll, beforeEach/afterEach/aroundEach). - Compile filtered trees into a shared pure ExecPlan IR consumed by both sequential and parallel execution paths, using ExecutionMode.combine so nested parallel scopes inside sequential remain strictly sequential. - Implement a fixed-size WorkerPool (Std.Mutex + Std.Condvar + Std.Queue) parameterized by RunConfig.threads / CLI -j N / --threads N so CI jobs can bound concurrent memory usage while maximizing wall-clock speed. - Drop completed test closures immediately upon completion, isolate per-test stdout/stderr via IO.FS.withIsolatedStreams, catch uncaught IO.Error per test, skip acquiring filtered-out resources, and avoid acquiring withResource after --fail-fast triggers. 3. **Deterministic, thread-safe Bool property testing** - Add pure SplitMix64 Gen/Rng, fuel-bounded Shrinkable, Sampleable, FormatValue, arbitrary-arity PropTestable, precondition guards (==>), and forAll/forAllShrink/forAllNamed. - Derive deterministic per-test seeds from (masterSeed, testPath) and always report seeds so failures are 100% reproducible across sequential and parallel runs. 4. **Formally verified runner (`LSpecProofs`, zero `sorry`, zero consumer overhead)** - Convert all pure runner functions in LSpec.Runner (TestFilter.matchesTest, filterTree, listTests, ReportTree.leaves/leafCount/failures/summarize, compilePlan, computeWorkerCount) from partial to total with kernel-checked termination proofs. - Provide an opt-in LSpecProofs library (excluded from defaultTargets so downstream consumers incur zero build or runtime overhead) proving: - **Filtering & resource pruning (`LSpecProofs.Filter`)**: direct proofs on the executable runner that filtering is sound and complete with respect to listTests, idempotent, obeys exclusion precedence, and prunes empty scopes so filtered-out withResource blocks never survive to execute. - **Reporting & deterministic planning (`LSpecProofs.Report`)**: direct proofs of exact pass/fail/skip accounting (total = leafCount, failed = failures.size, allPassed ↔ failures.isEmpty), permutation invariance of summary counts across arbitrary parallel completion orders, compilePlan equivalence with listTests, mode-independent deterministic per-test seed assignment, fail-fast skip accounting, and worker pool size bounds. - **Parallel scheduler & resource safety (`LSpecProofs.Concurrency`)**: small-step operational semantics of the bounded WorkerPool and ExecPlan scheduler proving bounded concurrency (activeWorkers ≤ cap on every reachable trace), sequential exclusion and strict left-to-right ordering, withResource acquire/release bracket safety (no child executes before acquire; no release before all children finish; exact-once release on completion), deadlock freedom (including arbitrarily nested resources at cap = 1) and termination with an exact step bound, and sequential–parallel confluence (every parallel execution produces the identical ReportTree and RunSummary as sequential execution). - **Compile-time axiom gate (`LSpecProofs.Axioms`)**: #guard_msgs in #print axioms checks on all 31 headline theorems compiled with -DwarningAsError=true, ensuring only Lean's standard axioms (propext, Quot.sound, Classical.choice) are used—never sorryAx or custom axioms. 5. **CI, tests, examples, and documentation** - Remove all legacy v2 modules (LSpec/LSpec.lean, LSpec/Instances.lean, LSpec/Plausible.lean, LSpec/SlimCheck/, Examples/Testing.lean). - Place internal self-tests under LSpecTests/ (LSpecTests/Main.lean, LSpecTests/ImportCheck.lean) so LSpec's build directory never collides with downstream consumers' Tests.* modules on LEAN_PATH, and update Examples/Examples.lean and README.md. - Enforce LSpecProofs in both CI jobs (.github/workflows/ci.yml Lean job via lake build LSpecProofs --wfail and Nix job via checks.proofs in flake.nix). - Verified with lake build --wfail, lake build LSpecProofs --wfail, lake test (35/35), lake exe tests -j 4 (35/35), Examples/Examples.lean, nix flake check (checks.tests & checks.proofs), and end-to-end migration of Ix (55/55 primary suites passing; --list 18.89s -> 6.93s; full suite 380.82s -> 157.43s at -j 4, 116.30s at -j 8, 101.22s at -j 16). --- .github/workflows/ci.yml | 6 + Examples/Examples.lean | 282 ++--- Examples/Testing.lean | 209 ---- LSpec.lean | 13 +- LSpec/Assert.lean | 349 ++++++ LSpec/Cli.lean | 247 ++++ LSpec/Core.lean | 269 +++++ LSpec/Instances.lean | 91 -- LSpec/LSpec.lean | 610 ---------- LSpec/Plausible.lean | 170 --- LSpec/Processors.lean | 183 +++ LSpec/Property/Check.lean | 260 ++++ LSpec/Property/Gen.lean | 227 ++++ LSpec/Property/Sampleable.lean | 236 ++++ LSpec/Runner.lean | 731 +++++++++++ LSpec/SlimCheck.lean | 4 - LSpec/SlimCheck/Checkable.lean | 514 -------- LSpec/SlimCheck/Control/DefaultRange.lean | 64 - LSpec/SlimCheck/Control/Random.lean | 139 --- LSpec/SlimCheck/Gen.lean | 124 -- LSpec/SlimCheck/Sampleable.lean | 232 ---- LSpec/Spec.lean | 228 ++++ LSpecProofs.lean | 20 + LSpecProofs/Axioms.lean | 168 +++ LSpecProofs/Concurrency.lean | 1332 +++++++++++++++++++++ LSpecProofs/Filter.lean | 499 ++++++++ LSpecProofs/Report.lean | 407 +++++++ LSpecTests/ImportCheck.lean | 42 + LSpecTests/Main.lean | 457 +++++++ README.md | 301 +++-- Tests/Main.lean | 258 ---- flake.nix | 13 +- lake-manifest.json | 12 +- lakefile.toml | 17 +- 34 files changed, 5911 insertions(+), 2803 deletions(-) delete mode 100644 Examples/Testing.lean create mode 100644 LSpec/Assert.lean create mode 100644 LSpec/Cli.lean create mode 100644 LSpec/Core.lean delete mode 100644 LSpec/Instances.lean delete mode 100644 LSpec/LSpec.lean delete mode 100644 LSpec/Plausible.lean create mode 100644 LSpec/Processors.lean create mode 100644 LSpec/Property/Check.lean create mode 100644 LSpec/Property/Gen.lean create mode 100644 LSpec/Property/Sampleable.lean create mode 100644 LSpec/Runner.lean delete mode 100644 LSpec/SlimCheck.lean delete mode 100644 LSpec/SlimCheck/Checkable.lean delete mode 100644 LSpec/SlimCheck/Control/DefaultRange.lean delete mode 100644 LSpec/SlimCheck/Control/Random.lean delete mode 100644 LSpec/SlimCheck/Gen.lean delete mode 100644 LSpec/SlimCheck/Sampleable.lean create mode 100644 LSpec/Spec.lean create mode 100644 LSpecProofs.lean create mode 100644 LSpecProofs/Axioms.lean create mode 100644 LSpecProofs/Concurrency.lean create mode 100644 LSpecProofs/Filter.lean create mode 100644 LSpecProofs/Report.lean create mode 100644 LSpecTests/ImportCheck.lean create mode 100644 LSpecTests/Main.lean delete mode 100644 Tests/Main.lean diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d81576..46b110b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,6 +24,12 @@ jobs: - uses: leanprover/lean-action@50fcf42d2e460296f1a34b402e990d1b24f8b596 # v1.6.0 with: build-args: "--wfail" + - name: Verify formal proofs + run: lake build LSpecProofs --wfail + - name: Run parallel test suite + run: lake exe tests -j 4 + - name: Typecheck examples + run: lake env lean Examples/Examples.lean # Builds the library and runs the test suite via Nix flake checks nix-test: diff --git a/Examples/Examples.lean b/Examples/Examples.lean index 83dbc6d..3e4f31b 100644 --- a/Examples/Examples.lean +++ b/Examples/Examples.lean @@ -1,219 +1,83 @@ import LSpec -/-! -# LSpec Examples - -This file provides comprehensive examples of using LSpec for testing in Lean 4. - -## Quick Reference - -| Function | Use Case | Output | -|----------|----------|--------| -| `test` | Unit tests | `✓ ∃: name` | -| `check` | Property tests (simple) | `✓ ∃: name` | -| `check'` | Property tests (with syntax) | `✓ ∃₁₀₀: "name" (property)` | -| `checkIO` | Runtime property tests | Same as check | -| `checkIO'` | Runtime tests (with syntax) | Same as check' | --/ - -section LSpec - -open LSpec - -/-! ## Basic Usage - -The simplest way to run tests is with the `#lspec` command. --/ - -#lspec test "Nat equality" (4 ≠ 5) --- ✓ ∃: Nat equality - -/-! -Tests can be composed into sequences using `$` or `++`. -The output shows `✓ ∃:` for each passing unit test. --/ - -#lspec test "bool equality" (42 == 42) $ - test "list length" ([42].length = 2) $ -- This fails - test "list nonempty" ¬ [42].isEmpty --- ✓ ∃: bool equality --- × ∃: list length --- Expected to be equal: '1' and '2' --- ✓ ∃: list nonempty - -/-! -## Bounded Universal Quantification +open LSpec LSpec.Prop -Tests like `∀ n, n < 10 → P n` are automatically iterated. --/ - -#lspec test "all lt" $ ∀ n, n < 10 → n - 5 < 5 --- ✓ ∃: all lt - -/-! -## IO-based Tests - -For runtime tests, use `lspecIO` with a HashMap of test suites. --/ - -def fourIO : IO Nat := return 4 -def fiveIO : IO Nat := return 5 - -def main := do - let four ← fourIO - let five ← fiveIO - lspecIO (.ofList [("IO tests", [ - test "fourIO equals 4" (four = 4) $ - test "fiveIO equals 5" (five = 5)])]) [] - -#eval main --- IO tests --- ✓ ∃: fourIO equals 4 --- ✓ ∃: fiveIO equals 5 --- 0 - -end LSpec - -section SlimCheck /-! -## Property-Based Testing with SlimCheck - -SlimCheck generates random test cases to verify properties. -The output shows how many samples were tested. - -### Basic Property Tests - -Use `check` for simple output or `check'` to see the property syntax. --/ - -open LSpec SlimCheck - --- Nat has a SampleableExt instance for random generation -example : SampleableExt Nat := by infer_instance - -/-! -### Using `check'` (Recommended) - -The `check'` macro captures the property syntax for display: -- Success shows: `✓ ∃₁₀₀: "name" (∀ n m : Nat, n + m = m + n)` -- Failure shows: `× ∃²/₁₀₀: "name" (property)` with counterexample +# LSpec Examples -The superscript indicates which sample failed, subscript shows total samples. +Demonstrates: +- Hspec-style `describe` / `context` / `it` / `itBool` / `xit` +- Bool-based expectations (`shouldBe`, `shouldContainSubstr`, `expect`) +- Bool-based property testing (`prop`, `==>`, `forAll`, custom `Sampleable`/`Shrinkable`) +- Scoped resources (`withResource`), tags (`withTag`), and `sequential` execution +- Bounded-thread CLI runner (`lspecMain`) -/ -#lspec check' "add_comm" (∀ n m : Nat, n + m = m + n) --- ✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) +/-! ## Custom type with `Sampleable` & `Shrinkable` -/ -#lspec check' "mul_comm_wrong" (∀ n m : Nat, n * m = m * m) --- × ∃⁶/₁₀₀: "mul_comm_wrong" (∀ n m : Nat, n * m = m * m) --- =================== --- Found problems! --- n := 1 --- m := 2 --- issue: 2 = 4 does not hold --- (2 shrinks) --- ------------------- - -/-! -### Custom Types with SlimCheck - -To use SlimCheck with custom types, define `Shrinkable` and `SampleableExt` instances. --/ - -structure Pairs where +structure Pair where left : Nat right : Nat -deriving Repr - -private def mkPairs (as : List α) (bs : List β) : List (α × β) := - let mkPairsAux (a : α) (bs : List β) : List (α × β) := bs.map fun b => (a, b) - as.foldl (fun abs a => mkPairsAux a bs ++ abs) [] - --- Shrinkable instance for reducing counterexamples -open Shrinkable in -instance : Shrinkable Pairs where - shrink := fun p => - let shrinkl := shrink p.left - let shrinkr := shrink p.right - mkPairs shrinkl shrinkr |>.map fun (a, b) => ⟨a, b⟩ - --- SampleableExt instance for random generation -open SampleableExt - -def pairsGen : Gen Pairs := return ⟨← Gen.chooseAny Nat, ← Gen.chooseAny Nat⟩ - -instance : SampleableExt Pairs := mkSelfContained pairsGen - --- Now we can test properties over Pairs -#lspec check' "left + 2 ≤ right" (∀ pair : Pairs, pair.left + 2 ≤ pair.right) --- × ∃¹/₁₀₀: "left + 2 ≤ right" (∀ pair : Pairs, pair.left + 2 ≤ pair.right) --- =================== --- Found problems! --- pair := { left := 0, right := 1 } --- issue: 2 ≤ 1 does not hold --- ... - --- This passes (but note: ⟨0, 0⟩ would fail, showing shrink limitations) -#lspec check' "left + right > right" (∀ pair : Pairs, pair.left + pair.right > pair.right) --- ✓ ∃₁₀₀: "left + right > right" (∀ pair : Pairs, pair.left + pair.right > pair.right) - -/-! -### Weighted Random Generation with Gen.frequency - -`Gen.frequency` creates weighted random generators for more realistic test data. --/ - -inductive Command where - | noop - | read - | write - | delete -deriving Repr, DecidableEq - -/-- -Weighted command generator: -- noop: 10%, read: 50%, write: 30%, delete: 10% --/ -def commandGen : Gen Command := - Gen.frequency #[ - (1, pure Command.noop), - (5, pure Command.read), - (3, pure Command.write), - (1, pure Command.delete) - ] (pure Command.noop) - -instance : Shrinkable Command where - shrink := fun _ => [] - -instance : SampleableExt Command := mkSelfContained commandGen - -#lspec check' "commands are valid" (∀ cmd : Command, - cmd = Command.noop ∨ cmd = Command.read ∨ cmd = Command.write ∨ cmd = Command.delete) --- ✓ ∃₁₀₀: "commands are valid" (∀ cmd : Command, ...) - -/-! -### Biased Number Generation - -Generate numbers with custom distributions. --/ - -def biasedSmallGen : Gen Nat := - Gen.frequency #[ - (5, Gen.choose Nat 0 10), -- 50%: small (0-10) - (3, Gen.choose Nat 11 100), -- 30%: medium (11-100) - (2, Gen.choose Nat 101 1000) -- 20%: larger (101-1000) - ] (pure 0) - -structure BiasedNat where - val : Nat -deriving Repr - -instance : Shrinkable BiasedNat where - shrink := fun n => (Shrinkable.shrink n.val).map BiasedNat.mk - -instance : SampleableExt BiasedNat := mkSelfContained (BiasedNat.mk <$> biasedSmallGen) - -#lspec check' "biased numbers bounded" (∀ n : BiasedNat, n.val ≤ 1000) --- ✓ ∃₁₀₀: "biased numbers bounded" (∀ n : BiasedNat, n.val ≤ 1000) - -end SlimCheck + deriving BEq, Repr + +instance : Shrinkable Pair where + shrink p := + (Shrinkable.shrink p.left).map (fun l => { p with left := l }) ++ + (Shrinkable.shrink p.right).map (fun r => { p with right := r }) + +instance : Sampleable Pair where + sample := return { left := ← Gen.chooseNat 0 (← Gen.getSize), + right := ← Gen.chooseNat 0 (← Gen.getSize) } + +/-! ## Defining Suites -/ + +def mathSuite : Spec := do + describe "Math" do + context "addition" do + it "adds two numbers" do + shouldBe (2 + 2) 4 + shouldBe (0 + 5) 5 + + itBool "is associative on small values" ((1 + 2) + 3 == 1 + (2 + 3)) + + prop "is commutative" fun (a b : Nat) => + a + b == b + a + + prop "with precondition guard" fun (a b : Nat) => + (Nat.ble b a) ==> (a - b + b == a) + + context "custom Pair generator" do + prop "sum is at least each component" fun (p : Pair) => + Nat.ble p.left (p.left + p.right) && Nat.ble p.right (p.left + p.right) + + prop "with explicit weighted generator" <| + let biasedGen : Gen Nat := + Gen.frequency #[ + (5, Gen.chooseNat 0 10), + (3, Gen.chooseNat 11 100), + (2, Gen.chooseNat 101 1000) + ] (pure 0) + forAll biasedGen fun n => Nat.ble n 1000 + +def resourceExample : Spec := do + describe "Resources & Execution Modes" do + let tempResource : ResourceSpec String := { + description := "shared greeting" + acquire := pure "hello from fixture" + release := fun _ => pure () + } + withResource tempResource fun getGreeting => do + it "reads shared resource" do + let msg ← getGreeting + shouldContainSubstr msg "fixture" + + sequential do + it "runs first" do expect true + it "runs second" do expect true + + withTag "slow" do + xit "pending integration check" do + pendingWith "not yet implemented" + +def main (args : List String) : IO UInt32 := + lspecMain (do mathSuite; resourceExample) args { threads := 4 } diff --git a/Examples/Testing.lean b/Examples/Testing.lean deleted file mode 100644 index 96bec33..0000000 --- a/Examples/Testing.lean +++ /dev/null @@ -1,209 +0,0 @@ -import LSpec - -/-! -# LSpec Testing Examples - -This file demonstrates the various testing capabilities of LSpec, -including unit tests, property-based tests, and output formatting. - -## Output Format - -LSpec uses logical quantifier notation to clearly indicate the verification level: - -- `✓ ∃:` - Unit test passed (verified a single specific case) -- `✓ ∀:` - Property test with formal proof (universal quantification proven) -- `✓ ∃ₙ:` - Property test passed n samples without formal proof -- `× ∃ⁿ/ₘ:` - Property test failed on sample n of m total - -The `check'` and `checkIO'` macros capture the property syntax for display, -producing richer output like: `✓ ∃₁₀₀: "name" (∀ n m : Nat, n + m = m + n)` --/ - -open LSpec - -/-! ## Unit Tests - -Unit tests verify specific decidable propositions. They use `∃:` notation -because we're verifying the existence of a specific case that holds. --/ - -#lspec - test "Nat equality" (4 = 5) $ -- This will fail - test "Nat inequality" (4 ≠ 5) $ -- ✓ ∃: Nat inequality - test "bool equality" (42 == 42) $ -- ✓ ∃: bool equality - test "list length" ([42].length = 1) $ - test "list nonempty" ¬ [42].isEmpty - -/-! ## Test Groups - -Tests can be organized into groups using `group`, `describe`, or `context`. -These are aliases that help document intent: -- `describe`: for describing a component being tested -- `context`: for describing circumstances under which tests run -- `group`: general-purpose grouping --/ - -def tGroup : TestSeq := group "test group test" $ - test "Nat inequality" (4 ≠ 5) $ - test "Nat inequality" (3 ≠ 5) $ - test "Nat equality" (42 == 42) - -#lspec (tGroup ++ tGroup ++ test "Nat equality" (42 = 42)) - -#lspec ( - test "Nat equality" (42 = 42) $ - group "manual group" ( - test "Nat equality inside group" (4 = 4)) $ - tGroup - ) - -/-! ## Describe/Context Style (Hspec-inspired) - -Using `describe` for component-level and `context` for circumstance-level -organization creates readable, hierarchical test output. --/ -section describe_context_tests - -def parserTests : TestSeq := - describe "Parser" $ - context "when parsing numbers" $ - test "parses single digits" (true) $ - test "parses multi-digit numbers" (true) $ - context "when parsing strings" $ - test "handles empty strings" (true) $ - test "handles quoted strings" (true) - -#lspec parserTests --- Parser: --- when parsing numbers: --- ✓ ∃: parses single digits --- ✓ ∃: parses multi-digit numbers --- when parsing strings: --- ✓ ∃: handles empty strings --- ✓ ∃: handles quoted strings - -def mathTests : TestSeq := - describe "Math operations" $ - describe "Addition" $ - test "0 + n = n" (0 + 5 = 5) $ - test "commutativity" (3 + 4 = 4 + 3) $ - describe "Multiplication" $ - test "0 * n = 0" (0 * 5 = 0) $ - test "1 * n = n" (1 * 5 = 5) - -#lspec mathTests - -def mixedGrouping : TestSeq := - describe "List operations" $ - context "with empty list" $ - test "length is 0" (([] : List Nat).length = 0) $ - test "isEmpty is true" (([] : List Nat).isEmpty) $ - group "non-empty list tests" $ - test "length is positive" ([1,2,3].length > 0) - -#lspec mixedGrouping - -end describe_context_tests - -/-! ## Basic Test Definitions -/ - -def test1 : TestSeq := - test "Nat equality" (4 = 4) $ - test "Nat inequality" (4 ≠ 5) $ - test "bool equality" (42 == 42) $ - test "list length" ([42].length = 1) $ - test "list nonempty" ¬ [42].isEmpty - -#lspec test1 - --- Running tests via lspecIO for runtime execution -#eval lspecIO (.ofList [("test1", [test1])]) [] - -def test2 := test "true" true - -#lspec test2 -#lspec test "true" <| true - -#lspec - test "a" (4 = 4) $ - test "b" (4 ≠ 5) - -#lspec - test "array eq" <| #[1,2,3] = (List.range 3).toArray --- × ∃: array eq --- Expected to be equal: '#[1, 2, 3]' and '#[0, 1, 2]' - -/-! ## IO-based Tests - -For tests that require IO operations (file reading, network, etc.), -use `lspecIO` with a HashMap of test suites. --/ - -def fourIO : IO Nat := return 4 -def fiveIO : IO Nat := return 5 - -def main := do - let four ← fourIO - let five ← fiveIO - lspecIO (.ofList [("IO tests", [ - tGroup ++ ( - test "fourIO equals 4" (four = 4) $ - test "fiveIO equals 5" (five = 5))])]) [] - -#eval main - -/-! ## Bounded Universal Quantification - -LSpec supports bounded quantification with automatic iteration. --/ - -#lspec test "all lt" $ ∀ n, n < 10 → n - 5 < 5 --- ✓ ∃: all lt - -#lspec test "all lt" $ ∀ n, n < 15 → n - 10 = 0 --- × ∃: all lt --- Fails on input 11. Expected to be equal: '1' and '0' - -/-! ## Property-Based Testing with SlimCheck - -Property tests use random sampling to verify properties over many inputs. - -### Using `check'` (with syntax capture) - -The `check'` macro captures the property syntax for display: -- Success: `✓ ∃₁₀₀: "name" (∀ n m : Nat, n + m = m + n)` -- Failure: `× ∃²/₁₀₀: "name" (∀ n m : Nat, n + m = m + m)` - -The subscript shows samples tested, superscript shows which sample failed. --/ - -section slimcheck_tests - --- Property test with syntax capture - shows the property in output -#lspec check' "add_comm" (∀ n m : Nat, n + m = m + n) --- ✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) - --- Test that fails - shows which sample failed (superscript) out of total (subscript) -#lspec check' "add_fails" (∀ n m : Nat, n + m = m + m) --- × ∃²/₁₀₀: "add_fails" (∀ n m : Nat, n + m = m + m) --- =================== --- Found problems! --- n := 1 --- m := 0 --- ... - --- Chaining property tests -def slimTests : TestSeq := - let t1 : TestSeq := check' "mul_comm" (∀ n m : Nat, n * m = m * n) - let t2 : TestSeq := check' "add_zero" (∀ n : Nat, n + 0 = n) - t1 ++ t2 - -#lspec slimTests --- ✓ ∃₁₀₀: "mul_comm" (∀ n m : Nat, n * m = m * n) --- ✓ ∃₁₀₀: "add_zero" (∀ n : Nat, n + 0 = n) - --- Standard check (without syntax capture) - simpler output -#lspec check "standard_check" (∀ n m : Nat, n + m = m + n) --- ✓ ∃: standard_check - -end slimcheck_tests diff --git a/LSpec.lean b/LSpec.lean index 17a90f8..75fffab 100644 --- a/LSpec.lean +++ b/LSpec.lean @@ -1,5 +1,10 @@ module -public import LSpec.LSpec -public import LSpec.Instances -public import LSpec.SlimCheck -public import LSpec.Plausible +public import LSpec.Core +public import LSpec.Assert +public import LSpec.Property.Gen +public import LSpec.Property.Sampleable +public import LSpec.Property.Check +public import LSpec.Spec +public import LSpec.Runner +public import LSpec.Processors +public import LSpec.Cli diff --git a/LSpec/Assert.lean b/LSpec/Assert.lean new file mode 100644 index 0000000..beee75e --- /dev/null +++ b/LSpec/Assert.lean @@ -0,0 +1,349 @@ +module +public import LSpec.Core +public meta import Lean.Elab.Term + +/-! +# Bool-based Assertions & Expectations (`AssertM`) + +Combines `nest-unit` (source-location tracking via `pos%` and `ExceptT` +assertions) with `Hspec` expectations (`shouldBe`, `shouldNotBe`, +`shouldSatisfy`, `shouldThrow`, `pending`) and `LSpec` unpacking helpers +(`expectSome`, `expectOk`, `expectErr`). + +All assertions are `Bool`-based (no `Prop`/`Decidable` overhead), and `pos%` +imports `Lean.Elab.Term` only at `meta` stage so runtime test binaries have +zero dependency on the `Lean` compiler library. +-/ + +namespace LSpec +public section + +open Lean Elab Term in +/-- Compile-time macro expanding to the current `LSpec.SourcePos` literal. -/ +elab "pos%" : term => do + let file ← getFileName + let fileMap ← getFileMap + let pos := match (← getRef).getPos? with + | some p => fileMap.toPosition p + | none => { line := 0, column := 0 } + let stx ← `(LSpec.SourcePos.mk $(quote file) $(quote pos.line) $(quote pos.column)) + elabTerm stx (some (mkConst ``LSpec.SourcePos)) + +/-- Details of a failed assertion. -/ +structure AssertionError where + message : String + details : String := "" + pos : Option SourcePos := none + deriving BEq, Repr + +/-- Early termination of an `AssertM` test body: either failure or pending/skipped. -/ +inductive AssertStop where + | failed (err : AssertionError) + | skipped (reason : Option String := none) + deriving BEq, Repr + +/-- Monad for unit tests with assertions and IO effects. + Defined as a nominal single-field `structure` (erased to `IO (Except AssertStop α)` + at runtime) so `do`-notation never unfolds `AssertM α` to `IO (Except AssertStop α)` + and always inserts `MonadLift IO AssertM` cleanly for polymorphic `IO` actions such + as `IO.ofExcept` or `withResource` getters. -/ +structure AssertM (α : Type) where + /-- Execute an `AssertM` action in `IO`. -/ + run : IO (Except AssertStop α) + +namespace AssertM + +instance : Monad AssertM where + pure a := ⟨pure (.ok a)⟩ + bind m f := ⟨do + match ← m.run with + | .ok a => (f a).run + | .error e => pure (.error e)⟩ + +instance : MonadExceptOf AssertStop AssertM where + throw e := ⟨pure (.error e)⟩ + tryCatch m h := ⟨do + match ← m.run with + | .ok a => pure (.ok a) + | .error e => (h e).run⟩ + +instance : MonadLift IO AssertM where + monadLift m := ⟨.ok <$> m⟩ + +instance : MonadLift BaseIO AssertM where + monadLift m := ⟨.ok <$> m⟩ + +instance : MonadFinally AssertM where + tryFinally' x h := ⟨do + let r ← tryFinally' x.run fun res => do + let a? := match res with + | some (.ok a) => some a + | _ => none + (h a?).run + match r with + | (.ok a, .ok b) => pure (.ok (a, b)) + | (.error e, _) => pure (.error e) + | (_, .error e) => pure (.error e)⟩ + +end AssertM + +/-- Type alias for a unit test action. -/ +abbrev UnitTest := AssertM Unit + +instance : IsTest UnitTest where + run _ action := do + match ← action.run with + | .ok () => return .pass + | .error (.skipped reason) => return .skip reason + | .error (.failed err) => + let loc := match err.pos with + | some p => s!"at {p}" + | none => "" + let details := + if loc.isEmpty then err.details + else if err.details.isEmpty then loc + else s!"{loc}\n{err.details}" + return .fail err.message details (.assertion err.pos) + +/-- Deferred pure `Bool` test (`Unit → Bool`). Eager `Bool` is intentionally not +an `IsTest` instance so pure test expressions are never evaluated eagerly. -/ +instance : IsTest (Unit → Bool) where + run _ f := do + let ok ← IO.lazyPure f + if ok then return .pass + else return .fail "assertion failed" "evaluated to false" (.assertion none) + +/-- Deferred `IO Bool` test. -/ +instance : IsTest (IO Bool) where + run _ action := do + if ← action then return .pass + else return .fail "assertion failed" "evaluated to false" (.assertion none) + +/-! ## Core Assertion Primitives -/ + +/-- Unconditionally fail the current test with a message and optional details. -/ +def fail (message : String) (details : String := "") + (pos : SourcePos := by exact pos%) : AssertM α := + throw (.failed { message, details, pos := some pos }) + +/-- Mark the current test as pending / skipped. -/ +def pending (reason : Option String := none) : AssertM α := + throw (.skipped reason) + +/-- Mark the current test as pending / skipped with an explanation. -/ +def pendingWith (reason : String) : AssertM α := + throw (.skipped (some reason)) + +/-- Assert that a `Bool` condition is `true`. + (Named `expect` / `assertTrue` because `assert` is a reserved `do`-block keyword in Lean 4.) -/ +def expect (cond : Bool) (message : String := "expected true, got false") + (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless cond do + throw (.failed { message, pos := some pos }) + +/-- Alias for `expect`. -/ +abbrev assertTrue (cond : Bool) (message : String := "expected true, got false") + (pos : SourcePos := by exact pos%) : AssertM Unit := + expect cond message pos + +/-- Assert that a `Bool` condition is `false`. -/ +def expectFalse (cond : Bool) (message : String := "expected false, got true") + (pos : SourcePos := by exact pos%) : AssertM Unit := do + if cond then + throw (.failed { message, pos := some pos }) + +/-- Alias for `expectFalse`. -/ +abbrev assertFalse (cond : Bool) (message : String := "expected false, got true") + (pos : SourcePos := by exact pos%) : AssertM Unit := + expectFalse cond message pos + +/-- Assert that every boolean in an `Array Bool` is `true`, reporting the first failing index. -/ +def expectAll (conds : Array Bool) (message : String := "assertion failed") + (pos : SourcePos := by exact pos%) : AssertM Unit := do + for h : i in [:conds.size] do + unless conds[i] do + throw (.failed { + message := s!"{message} (at index {i})" + pos := some pos + }) + +/-- Alias for `expectAll`. -/ +abbrev assertAll (conds : Array Bool) (message : String := "assertion failed") + (pos : SourcePos := by exact pos%) : AssertM Unit := + expectAll conds message pos + +/-! ## Hspec-style Expectations -/ + +/-- Assert that `actual == expected` using `BEq`. -/ +def shouldBe [BEq α] [Repr α] (actual expected : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless actual == expected do + throw (.failed { + message := "values not equal" + details := s!"expected: {reprStr expected}\n but got: {reprStr actual}" + pos := some pos + }) + +/-- Assert that `actual != unexpected` using `BEq`. -/ +def shouldNotBe [BEq α] [Repr α] (actual unexpected : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + if actual == unexpected then + throw (.failed { + message := "values unexpectedly equal" + details := s!"did not expect: {reprStr unexpected}" + pos := some pos + }) + +/-- Assert that `actual` satisfies a boolean predicate `pred`. -/ +def shouldSatisfy [Repr α] (actual : α) (pred : α → Bool) + (label : String := "predicate") (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless pred actual do + throw (.failed { + message := s!"value failed to satisfy {label}" + details := s!"value: {reprStr actual}" + pos := some pos + }) + +/-- Assert that `actual < bound` using `Ord`. -/ +def shouldBeLt [Ord α] [Repr α] (actual bound : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless compare actual bound == .lt do + throw (.failed { + message := "expected strictly less than" + details := s!"got: {reprStr actual}\nnot < {reprStr bound}" + pos := some pos + }) + +/-- Assert that `actual ≤ bound` using `Ord`. -/ +def shouldBeLe [Ord α] [Repr α] (actual bound : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + let cmp := compare actual bound + unless cmp == .lt || cmp == .eq do + throw (.failed { + message := "expected less than or equal" + details := s!"got: {reprStr actual}\nnot ≤ {reprStr bound}" + pos := some pos + }) + +/-- Assert that `actual > bound` using `Ord`. -/ +def shouldBeGt [Ord α] [Repr α] (actual bound : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless compare actual bound == .gt do + throw (.failed { + message := "expected strictly greater than" + details := s!"got: {reprStr actual}\nnot > {reprStr bound}" + pos := some pos + }) + +/-- Assert that `actual ≥ bound` using `Ord`. -/ +def shouldBeGe [Ord α] [Repr α] (actual bound : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + let cmp := compare actual bound + unless cmp == .gt || cmp == .eq do + throw (.failed { + message := "expected greater than or equal" + details := s!"got: {reprStr actual}\nnot ≥ {reprStr bound}" + pos := some pos + }) + +/-- Assert that a string contains `substr`. -/ +def shouldContainSubstr (haystack substr : String) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless (haystack.splitOn substr).length > 1 || substr.isEmpty do + throw (.failed { + message := s!"expected string to contain {reprStr substr}" + details := s!"actual: {reprStr haystack}" + pos := some pos + }) + +/-- Assert that a list contains `elem`. -/ +def shouldContain [BEq α] [Repr α] (xs : List α) (elem : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + unless xs.contains elem do + throw (.failed { + message := s!"expected list to contain {reprStr elem}" + details := s!"list: {reprStr xs}" + pos := some pos + }) + +/-- Assert that an `IO` action returns a value equal to `expected`. -/ +def shouldReturn [BEq α] [Repr α] (action : IO α) (expected : α) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + let actual ← action + shouldBe actual expected pos + +/-- Assert that an `IO` action throws an `IO.Error`, optionally matching a substring. -/ +def shouldThrow (action : IO α) (expectedSubstr : Option String := none) + (pos : SourcePos := by exact pos%) : AssertM Unit := do + let threw : Option String ← liftM (m := IO) do + try + let _ ← action + pure none + catch e => + pure (some e.toString) + match threw with + | none => + throw (.failed { + message := "expected IO action to throw an exception, but it succeeded" + pos := some pos + }) + | some msg => + if let some sub := expectedSubstr then + unless (msg.splitOn sub).length > 1 || sub.isEmpty do + throw (.failed { + message := s!"exception message did not contain {reprStr sub}" + details := s!"got exception: {msg}" + pos := some pos + }) + +/-! ## Option & Except Unpacking Combinators -/ + +/-- Unwrap `Option.some a`, failing the test on `none`. -/ +def expectSome (opt : Option α) (message : String := "expected 'some _', got 'none'") + (pos : SourcePos := by exact pos%) : AssertM α := + match opt with + | some a => pure a + | none => throw (.failed { message, pos := some pos }) + +/-- Assert that an `Option` is `none`. -/ +def expectNone [Repr α] (opt : Option α) (pos : SourcePos := by exact pos%) : AssertM Unit := + match opt with + | none => pure () + | some a => throw (.failed { + message := "expected 'none'" + details := s!"got: some ({reprStr a})" + pos := some pos + }) + +/-- Unwrap `Except.ok a`, failing the test with the stringified error on `Except.error e`. -/ +def expectOk [ToString ε] (res : Except ε α) (pos : SourcePos := by exact pos%) : AssertM α := + match res with + | .ok a => pure a + | .error e => throw (.failed { + message := "expected 'Except.ok _', got 'Except.error'" + details := s!"error: {e}" + pos := some pos + }) + +/-- Unwrap `Except.ok a`, formatting errors with `Repr`. -/ +def expectOkRepr [Repr ε] (res : Except ε α) (pos : SourcePos := by exact pos%) : AssertM α := + match res with + | .ok a => pure a + | .error e => throw (.failed { + message := "expected 'Except.ok _', got 'Except.error'" + details := s!"error: {reprStr e}" + pos := some pos + }) + +/-- Unwrap `Except.error e`, failing the test on `Except.ok a`. -/ +def expectErr [Repr α] (res : Except ε α) (pos : SourcePos := by exact pos%) : AssertM ε := + match res with + | .error e => pure e + | .ok a => throw (.failed { + message := "expected 'Except.error _', got 'Except.ok'" + details := s!"got: ok ({reprStr a})" + pos := some pos + }) + +end +end LSpec diff --git a/LSpec/Cli.lean b/LSpec/Cli.lean new file mode 100644 index 0000000..dde6bf5 --- /dev/null +++ b/LSpec/Cli.lean @@ -0,0 +1,247 @@ +module +public import LSpec.Core +public import LSpec.Spec +public import LSpec.Runner +public import LSpec.Processors + +/-! +# CLI Argument Parsing & Main Entry Points (`LSpec.Cli`) + +Provides `lspecMain`, `defaultMain`, `defaultMainTree`, `defaultMainWithProcessors`, +and `runSpec` with full command-line support for: +- `-j N` / `--threads N` / `--threads=N` (bounded parallel worker pool) +- `--sequential` (alias for `--threads 1`) +- `--list` (list matching tests without executing or acquiring resources) +- `` / `--filter ` (substring filter, repeatable) +- `--exact ` (exact path match, repeatable) +- `--exclude ` / `--exclude=a,b` (exclude matching paths) +- `--tag ` / `--exclude-tag ` (tag filtering) +- `--seed ` (deterministic property-test master seed) +- `--num-tests ` / `--max-size ` (global property-test overrides) +- `--fail-fast` (stop after first failure) +- `--color` / `--no-color` (respects `NO_COLOR`) +- `-v` / `--verbose` (show details & captured output on passing tests) +- `-h` / `--help` +-/ + +namespace LSpec +public section + +/-- Parsed CLI options. -/ +structure CliOptions where + threads : Option Nat := none + sequential : Bool := false + listOnly : Bool := false + includes : Array String := #[] + exact : Array String := #[] + excludes : Array String := #[] + includeTags : Array String := #[] + excludeTags : Array String := #[] + seed : Option UInt64 := none + numTests : Option Nat := none + maxSize : Option Nat := none + failFast : Bool := false + color : Option Bool := none + verbose : Bool := false + showHelp : Bool := false + deriving BEq, Repr + +private def parseNatArg (flag val : String) : Except String Nat := + match val.toNat? with + | some n => .ok n + | none => .error s!"expected natural number for {flag}, got '{val}'" + +private def parseUInt64Arg (flag val : String) : Except String UInt64 := + match val.toNat? with + | some n => .ok n.toUInt64 + | none => .error s!"expected unsigned integer for {flag}, got '{val}'" + +private def splitPrefix? (arg pfx : String) : Option String := + if arg.startsWith pfx then some ((arg.drop pfx.length).toString) else none + +/-- Parse CLI arguments into `CliOptions`. -/ +def parseCliArgs (args : List String) : Except String CliOptions := + go args {} +where + go : List String → CliOptions → Except String CliOptions + | [], o => .ok o + | "-h" :: rest, o | "--help" :: rest, o => + go rest { o with showHelp := true } + | "--list" :: rest, o => + go rest { o with listOnly := true } + | "--sequential" :: rest, o => + go rest { o with sequential := true, threads := some 1 } + | "--fail-fast" :: rest, o => + go rest { o with failFast := true } + | "--color" :: rest, o => + go rest { o with color := some true } + | "--no-color" :: rest, o => + go rest { o with color := some false } + | "-v" :: rest, o | "--verbose" :: rest, o => + go rest { o with verbose := true } + | "-j" :: val :: rest, o | "--threads" :: val :: rest, o => do + let n ← parseNatArg "--threads" val + if n == 0 then throw "--threads must be at least 1" + go rest { o with threads := some n } + | "--filter" :: pat :: rest, o => + go rest { o with includes := o.includes.push pat } + | "--exact" :: pat :: rest, o => + go rest { o with exact := o.exact.push pat } + | "--exclude" :: pat :: rest, o => + go rest { o with excludes := o.excludes.push pat } + | "--tag" :: tag :: rest, o => + go rest { o with includeTags := o.includeTags.push tag } + | "--exclude-tag" :: tag :: rest, o => + go rest { o with excludeTags := o.excludeTags.push tag } + | "--seed" :: val :: rest, o => do + let s ← parseUInt64Arg "--seed" val + go rest { o with seed := some s } + | "--num-tests" :: val :: rest, o => do + let n ← parseNatArg "--num-tests" val + go rest { o with numTests := some n } + | "--max-size" :: val :: rest, o => do + let n ← parseNatArg "--max-size" val + go rest { o with maxSize := some n } + | arg :: rest, o => + if rest.isEmpty && + ["-j", "--threads", "--filter", "--exact", "--exclude", "--tag", + "--exclude-tag", "--seed", "--num-tests", "--max-size"].contains arg then + .error s!"missing value for '{arg}' (use --help for usage)" + else if let some val := splitPrefix? arg "--threads=" then do + let n ← parseNatArg "--threads" val + if n == 0 then throw "--threads must be at least 1" + go rest { o with threads := some n } + else if let some val := splitPrefix? arg "-j" then do + let n ← parseNatArg "-j" val + if n == 0 then throw "-j must be at least 1" + go rest { o with threads := some n } + else if let some val := splitPrefix? arg "--filter=" then + go rest { o with includes := o.includes.push val } + else if let some val := splitPrefix? arg "--exact=" then + go rest { o with exact := o.exact.push val } + else if let some val := splitPrefix? arg "--exclude=" then + let xs := (val.splitOn ",").filter (!·.isEmpty) + go rest { o with excludes := o.excludes ++ xs.toArray } + else if let some val := splitPrefix? arg "--tag=" then + let xs := (val.splitOn ",").filter (!·.isEmpty) + go rest { o with includeTags := o.includeTags ++ xs.toArray } + else if let some val := splitPrefix? arg "--exclude-tag=" then + let xs := (val.splitOn ",").filter (!·.isEmpty) + go rest { o with excludeTags := o.excludeTags ++ xs.toArray } + else if let some val := splitPrefix? arg "--seed=" then do + let s ← parseUInt64Arg "--seed" val + go rest { o with seed := some s } + else if let some val := splitPrefix? arg "--num-tests=" then do + let n ← parseNatArg "--num-tests" val + go rest { o with numTests := some n } + else if let some val := splitPrefix? arg "--max-size=" then do + let n ← parseNatArg "--max-size" val + go rest { o with maxSize := some n } + else if arg.startsWith "-" then + .error s!"unknown option '{arg}' (use --help for usage)" + else + go rest { o with includes := o.includes.push arg } + +def cliHelpText : String := + String.intercalate "\n" [ + "LSpec test runner options:", + " -j, --threads Run up to N tests concurrently (default: 1)", + " --sequential Run all tests sequentially (alias for --threads 1)", + " --list List matching test paths and exit without running", + " Run only tests whose path contains ", + " --filter Same as positional (repeatable)", + " --exact Run only tests matching exactly (repeatable)", + " --exclude Exclude tests whose path contains ", + " --tag Run only tests carrying (repeatable)", + " --exclude-tag Skip tests carrying (repeatable)", + " --seed Master seed for deterministic property tests", + " --num-tests Override property-test sample count", + " --max-size Override property-test maximum generator size", + " --fail-fast Stop starting new tests after the first failure", + " --color / --no-color Force or disable ANSI color output", + " -v, --verbose Show extra details and captured output on passes", + " -h, --help Show this help message" + ] + +/-- Convert `CliOptions` + defaults into `TestOptions` for `TestProcessor`s. -/ +def CliOptions.toTestOptions (cli : CliOptions) (defaults : RunConfig := {}) + (noColorEnv : Bool := false) : TestOptions := Id.run do + let mut opts := defaults.options + let threads := cli.threads.getD defaults.threads + opts := opts.setNat "runner.threads" (max 1 threads) + opts := opts.setBool "runner.sequential" (cli.sequential || defaults.defaultMode == .sequential) + opts := opts.setBool "runner.list" cli.listOnly + opts := opts.setBool "runner.failFast" (cli.failFast || defaults.failFast) + opts := opts.setBool "runner.isolateStreams" defaults.isolateStreams + let useColor := match cli.color with + | some c => c + | none => !noColorEnv + opts := opts.setBool "console.color" useColor + opts := opts.setBool "console.verbose" cli.verbose + if let some s := cli.seed.orElse (fun () => defaults.seed) then + opts := opts.setUInt64 "runner.seed" s + if let some n := cli.numTests then + opts := opts.setNat "prop.numTests" n + if let some sz := cli.maxSize then + opts := opts.setNat "prop.maxSize" sz + let enc (xs : Array String) : String := "\x00".intercalate xs.toList + let incs := defaults.filter.includes ++ cli.includes + let exts := defaults.filter.exact ++ cli.exact + let excs := defaults.filter.excludes ++ cli.excludes + let itags := defaults.filter.includeTags ++ cli.includeTags + let etags := defaults.filter.excludeTags ++ cli.excludeTags + unless incs.isEmpty do opts := opts.setString "filter.includes" (enc incs) + unless exts.isEmpty do opts := opts.setString "filter.exact" (enc exts) + unless excs.isEmpty do opts := opts.setString "filter.excludes" (enc excs) + unless itags.isEmpty do opts := opts.setString "filter.includeTags" (enc itags) + unless etags.isEmpty do opts := opts.setString "filter.excludeTags" (enc etags) + return opts + +/-- Execute a `TestTree` using a custom list of `TestProcessor`s and CLI arguments. -/ +def defaultMainWithProcessors (procs : List TestProcessor) (tree : TestTree) + (args : List String) (defaults : RunConfig := {}) : IO UInt32 := do + let cli ← match parseCliArgs args with + | .ok c => pure c + | .error msg => + IO.eprintln s!"error: {msg}" + return 2 + if cli.showHelp then + IO.println cliHelpText + return 0 + let noColorEnv := (← IO.getEnv "NO_COLOR").isSome + let opts := cli.toTestOptions defaults noColorEnv + match TestProcessor.runFirst? procs opts tree with + | none => + IO.eprintln "error: no test processor matched the given options" + return 2 + | some act => act + +/-- Execute a `TestTree` with the default processors (`list`, `console`). -/ +def defaultMainTree (tree : TestTree) (args : List String) + (defaults : RunConfig := {}) : IO UInt32 := + defaultMainWithProcessors Processors.defaultProcessors tree args defaults + +/-- Execute a `Spec` with CLI argument parsing and the default processors. + This is the primary entry point for test executables: + ```lean + def main (args : List String) : IO UInt32 := + LSpec.lspecMain mySuite args + ``` -/ +def lspecMain (spec : Spec) (args : List String) + (defaults : RunConfig := {}) : IO UInt32 := do + let tree ← spec.toTestTree "" + defaultMainTree tree args defaults + +/-- Alias for `lspecMain` matching `nest-core`'s naming. -/ +def defaultMain (spec : Spec) (args : List String := []) + (defaults : RunConfig := {}) : IO UInt32 := + lspecMain spec args defaults + +/-- Programmatically run a `Spec` with an explicit `RunConfig` (no CLI parsing, + no stdout printing), returning `(ReportTree, RunSummary)`. -/ +def runSpec (spec : Spec) (cfg : RunConfig := {}) : IO (ReportTree × RunSummary) := do + let tree ← spec.toTestTree "" + runTree tree cfg + +end +end LSpec diff --git a/LSpec/Core.lean b/LSpec/Core.lean new file mode 100644 index 0000000..3713e59 --- /dev/null +++ b/LSpec/Core.lean @@ -0,0 +1,269 @@ +module +public import Std.Data.HashMap + +/-! +# LSpec Core + +Core test tree IR, outcomes, options, and processor abstractions. +Inspired by `nest-core` (`TestTree`, `IsTest`, `TestProcessor`) and `Hspec` +(`parallel`/`sequential` execution modes, tags, scoped resources). + +This module has no runtime dependency on the `Lean` compiler library so test +binaries stay lightweight and fast to compile and import. +-/ + +namespace LSpec +public section + +/-- Source location captured at compile time for assertion failure reporting. -/ +structure SourcePos where + file : String + line : Nat + col : Nat + deriving BEq, Repr, Inhabited + +instance : ToString SourcePos where + toString p := s!"{p.file}:{p.line}:{p.col}" + +/-- Dynamically-typed option value stored in `TestOptions`. -/ +inductive OptionValue where + | bool (val : Bool) + | nat (val : Nat) + | uint64 (val : UInt64) + | string (val : String) + deriving BEq, Repr + +/-- Key-value options passed through the `TestTree` and to `TestProcessor`s. -/ +structure TestOptions where + entries : Std.HashMap String OptionValue := {} + +namespace TestOptions + +def empty : TestOptions := {} + +def setBool (o : TestOptions) (key : String) (v : Bool) : TestOptions := + { entries := o.entries.insert key (.bool v) } + +def setNat (o : TestOptions) (key : String) (v : Nat) : TestOptions := + { entries := o.entries.insert key (.nat v) } + +def setUInt64 (o : TestOptions) (key : String) (v : UInt64) : TestOptions := + { entries := o.entries.insert key (.uint64 v) } + +def setString (o : TestOptions) (key : String) (v : String) : TestOptions := + { entries := o.entries.insert key (.string v) } + +def getBool? (o : TestOptions) (key : String) : Option Bool := + match o.entries[key]? with + | some (.bool v) => some v + | _ => none + +def getBool (o : TestOptions) (key : String) (default : Bool := false) : Bool := + (o.getBool? key).getD default + +def getNat? (o : TestOptions) (key : String) : Option Nat := + match o.entries[key]? with + | some (.nat v) => some v + | _ => none + +def getNat (o : TestOptions) (key : String) (default : Nat := 0) : Nat := + (o.getNat? key).getD default + +def getUInt64? (o : TestOptions) (key : String) : Option UInt64 := + match o.entries[key]? with + | some (.uint64 v) => some v + | some (.nat v) => some v.toUInt64 + | _ => none + +def getUInt64 (o : TestOptions) (key : String) (default : UInt64 := 0) : UInt64 := + (o.getUInt64? key).getD default + +def getString? (o : TestOptions) (key : String) : Option String := + match o.entries[key]? with + | some (.string v) => some v + | _ => none + +def getString (o : TestOptions) (key : String) (default : String := "") : String := + (o.getString? key).getD default + +def contains (o : TestOptions) (key : String) : Bool := + o.entries.contains key + +/-- Merge two option maps, with `override` taking precedence over `base`. -/ +def merge (base override : TestOptions) : TestOptions := + override.entries.fold (init := base) fun acc k v => + { entries := acc.entries.insert k v } + +end TestOptions + +/-- Execution concurrency mode for a subtree of tests. -/ +inductive ExecutionMode where + /-- Tests in this subtree may run concurrently up to the configured thread limit. -/ + | parallel + /-- Tests in this subtree run one at a time in declaration order. -/ + | sequential + deriving BEq, Repr, Inhabited + +/-- Combine an enclosing execution mode with an inner `.withMode` modifier. + Once inside a `.sequential` scope, nested `.parallel` stays `.sequential` + so sequential ordering invariants cannot be violated by inner subtrees. -/ +@[expose] def ExecutionMode.combine (outer inner : ExecutionMode) : ExecutionMode := + match outer with + | .sequential => .sequential + | .parallel => inner + +/-- Why a test failed. -/ +inductive FailureReason where + /-- A unit test assertion or boolean expectation failed. -/ + | assertion (pos : Option SourcePos := none) + /-- A property test found a counterexample. -/ + | property (seed : UInt64) (numTests : Nat) (numShrinks : Nat) + /-- A property test discarded too many generated inputs. -/ + | gaveUp (seed : UInt64) (discarded : Nat) (passed : Nat) + /-- An uncaught `IO.Error` was thrown while running the test. -/ + | exception (error : String) + deriving BEq, Repr + +/-- The outcome of running a single test. -/ +inductive Outcome where + | passed + | skipped (reason : Option String := none) + | failed (reason : FailureReason) + deriving BEq, Repr, Inhabited + +/-- Full result returned by executing a single test. -/ +structure TestResult where + outcome : Outcome + summary : String := "" + details : String := "" + deriving BEq, Repr, Inhabited + +namespace TestResult + +@[expose] def pass (summary : String := "") (details : String := "") : TestResult := + { outcome := .passed, summary, details } + +@[expose] def skip (reason : Option String := none) : TestResult := + { outcome := .skipped reason, summary := reason.getD "pending" } + +@[expose] def fail (summary : String) (details : String := "") + (reason : FailureReason := .assertion none) : TestResult := + { outcome := .failed reason, summary, details } + +@[expose] def isPassed (r : TestResult) : Bool := + match r.outcome with + | .passed => true + | _ => false + +@[expose] def isSkipped (r : TestResult) : Bool := + match r.outcome with + | .skipped _ => true + | _ => false + +@[expose] def isFailed (r : TestResult) : Bool := + match r.outcome with + | .failed _ => true + | _ => false + +end TestResult + +/-- Runtime context passed to every test execution. -/ +structure TestContext where + options : TestOptions := {} + /-- Full hierarchical path of enclosing group names and the leaf test name. -/ + path : Array String := #[] + /-- Deterministic per-test seed derived from the runner's master seed and `path`. -/ + seed : UInt64 := 0 + +namespace TestContext + +/-- Dot-free slash-separated display path (e.g. `"Math/Addition/commutativity"`). -/ +def pathString (ctx : TestContext) : String := + "/".intercalate ctx.path.toList + +end TestContext + +/-- Core extensibility class describing any type that can be executed as a test. -/ +class IsTest (t : Type) where + run : TestContext → t → IO TestResult + +/-- Specification for a shared resource acquired once for a subtree and released +after all tests in that subtree finish. -/ +structure ResourceSpec (α : Type) where + description : String + acquire : IO α + release : α → IO Unit := fun _ => pure () + +/-- The core `TestTree` intermediate representation (living in `Type 0`). + +Every leaf test is deferred as a closure `TestContext → IO TestResult`, so +building or inspecting a `TestTree` (e.g. for `--list` or filtering) never +executes test code or acquires resources. -/ +inductive TestTree : Type where + /-- A single deferred test leaf. -/ + | leaf (name : String) (tags : Array String) (exec : TestContext → IO TestResult) + /-- A named group of child test trees. -/ + | group (name : String) (children : Array TestTree) + /-- Override the concurrency mode (`parallel` or `sequential`) for a subtree. -/ + | withMode (mode : ExecutionMode) (child : TestTree) + /-- Attach tags to every test in a subtree. -/ + | withTags (tags : Array String) (child : TestTree) + /-- Transform `TestOptions` for a subtree. -/ + | withOptions (f : TestOptions → TestOptions) (child : TestTree) + /-- Wrap every leaf execution in a subtree (used for `beforeEach`/`afterEach`/`aroundEach`). -/ + | aroundEach (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) (child : TestTree) + /-- Acquire a shared resource before running `child`, and run the returned + release action in a `finally` block once `child` completes. -/ + | withResource (description : String) (acquire : IO (IO Unit)) (child : TestTree) + +instance : Inhabited TestTree := ⟨.group "" #[]⟩ + +namespace TestTree + +/-- Build a single leaf node from any `IsTest` instance. -/ +def single [inst : IsTest t] (name : String) (test : t) (tags : Array String := #[]) : TestTree := + .leaf name tags (fun ctx => inst.run ctx test) + +/-- Combine multiple trees under a named group. -/ +def ofArray (name : String) (children : Array TestTree) : TestTree := + .group name children + +/-- Combine multiple trees under a named group. -/ +def ofList (name : String) (children : List TestTree) : TestTree := + .group name children.toArray + +end TestTree + +/-- A pluggable processor that consumes a `TestTree` and `TestOptions` +(e.g. running tests in parallel, listing test paths, formatting reports). -/ +structure TestProcessor where + name : String + shouldRun : TestOptions → Bool + exec : TestOptions → TestTree → IO UInt32 + +namespace TestProcessor + +/-- Run the first processor whose `shouldRun` predicate matches `opts`. -/ +def runFirst? (procs : List TestProcessor) (opts : TestOptions) (tree : TestTree) : + Option (IO UInt32) := + match procs.find? (·.shouldRun opts) with + | some p => some (p.exec opts tree) + | none => none + +end TestProcessor + +/-- Mix a `UInt64` using SplitMix64 finalizer for deterministic per-test seed derivation. -/ +@[expose] def mixSeed (x : UInt64) : UInt64 := + let z := (x + 0x9E3779B97F4A7C15) + let z := (z ^^^ (z >>> 30)) * 0xBF58476D1CE4E5B9 + let z := (z ^^^ (z >>> 27)) * 0x94D049BB133111EB + z ^^^ (z >>> 31) + +/-- Derive a deterministic per-test seed from a master seed and the test path. -/ +@[expose] def deriveTestSeed (masterSeed : UInt64) (path : Array String) : UInt64 := + let h := path.foldl (init := masterSeed) fun acc seg => + mixSeed (acc ^^^ seg.hash) + mixSeed h + +end +end LSpec diff --git a/LSpec/Instances.lean b/LSpec/Instances.lean deleted file mode 100644 index 96cc0bf..0000000 --- a/LSpec/Instances.lean +++ /dev/null @@ -1,91 +0,0 @@ -module -public import LSpec.LSpec - -/-! -# Testable Instances - -This module provides `Testable` instances for common types, enabling -LSpec to test equality, inequality, and bounded quantification directly. - -## Provided Instances - -- `Testable (x = y)` for `DecidableEq` types -- `Testable (x == y)` for `BEq` types -- `Testable (x ≠ y)` for `DecidableEq` types -- `Testable (x != y)` for `BEq` types -- `Testable (∀ n, n < b → p n)` for bounded natural number quantification --/ - -namespace LSpec -public section - -/-- Testable instance for decidable equality. -/ -instance (priority := 50) (x y : α) [DecidableEq α] [Repr α] : Testable (x = y) := - if h : x = y then - .isTrue h - else - .isFalse h 0 0 $ s!"Expected to be equal: '{repr x}' and '{repr y}'" - -/-- Testable instance for boolean equality. -/ -instance (priority := 50) (x y : α) [BEq α] [Repr α] : Testable (x == y) := - if h : x == y then - .isTrue h - else - .isFalse h 0 0 $ s!"Expected to be equal: '{repr x}' and '{repr y}'" - -/-- Testable instance for decidable inequality. -/ -instance (priority := 50) (x y : α) [DecidableEq α] [Repr α] : Testable (x ≠ y) := - if h : x ≠ y then - .isTrue h - else - .isFalse h 0 0 s!"Expected to be different but both equal to '{repr x}'" - -/-- Testable instance for boolean inequality. -/ -instance (priority := 50) (x y : α) [BEq α] [Repr α] : Testable (x != y) := - if h : x != y then - .isTrue h - else - .isFalse h 0 0 s!"Expected to be different but both equal to '{repr x}'" - -/-- -Testable instance for bounded universal quantification over natural numbers. - -This enables tests like: -```lean -#lspec test "all small" $ ∀ n, n < 10 → n * n < 100 -``` - -The bound `b` determines how many values are tested (0 to b-1). -If any value fails, the output shows which input caused the failure. --/ -instance Nat.Testable_forall_lt - (b : Nat) (p : Nat → Prop) - [d : (n : Nat) → Testable (p n)] : - Testable (∀ n, n < b → p n) := - match b with - | 0 => .isTrue (by simp [Nat.not_lt_zero]) - | b + 1 => - match Testable_forall_lt b p with - | .isTrue h => - match d b with - | .isTrue hb => - .isTrue $ by - intros n hn - cases Nat.eq_or_lt_of_le (Nat.le_of_lt_succ hn) with - | inl hl => cases hl; assumption - | inr => apply h; assumption - | .isPassed numSamples msg => .isPassed numSamples msg - | .isMaybe msg => .isMaybe msg - | .isFalse hb failedAt totalTests msg => - .isFalse (λ h => hb (h _ (Nat.lt_succ_self _))) failedAt totalTests $ - match msg with - | some msg => s!"Fails on input {b}. {msg}" - | none => s!"Fails on input {b}." - | .isFailure failedAt totalTests msg => .isFailure failedAt totalTests msg - | .isPassed numSamples msg => .isPassed numSamples msg - | .isMaybe msg => .isMaybe msg - | .isFalse h failedAt totalTests msg => .isFalse (λ h' => h λ n hn => h' _ (Nat.le_succ_of_le hn)) failedAt totalTests msg - | .isFailure failedAt totalTests msg => .isFailure failedAt totalTests msg - -end -end LSpec diff --git a/LSpec/LSpec.lean b/LSpec/LSpec.lean deleted file mode 100644 index 614fcb3..0000000 --- a/LSpec/LSpec.lean +++ /dev/null @@ -1,610 +0,0 @@ -module -public import LSpec.SlimCheck.Checkable - -/-! -# The core `LSpec` framework - -A lightweight testing framework for Lean 4, inspired by Hspec. - -## Overview - -LSpec provides three main ways to define tests: - -- **`test`**: For simple decidable propositions (unit tests) -- **`check`/`check'`**: For property-based tests using SlimCheck, evaluated at compile time -- **`checkIO`/`checkIO'`**: For property-based tests evaluated at runtime with configurable seeds - -## Quick Start - -```lean -import LSpec - -open LSpec - --- Simple unit tests using #lspec -#lspec test "basic arithmetic" (2 + 2 = 4) - --- Property tests with syntax capture (shows the property in output) -#lspec check' "addition is commutative" (∀ n m : Nat, n + m = m + n) - --- Runtime tests via main function -def myTests : TestSeq := - test "equality" (1 = 1) ++ - checkIO' "commutativity" (∀ n m : Nat, n + m = m + n) - -def main : IO UInt32 := lspecIO (.ofList [("myTests", [myTests])]) [] -``` - -## Output Format - -LSpec uses logical quantifier notation to indicate verification level: - -| Symbol | Meaning | Example | -|--------|---------|---------| -| `✓ ∃:` | Unit test passed (single case verified) | `✓ ∃: basic arithmetic` | -| `✓ ∀:` | Property test with formal proof | `✓ ∀: "name" (∀ n, n = n)` | -| `✓ ∃ₙ:` | Property test passed n samples (no proof) | `✓ ∃₁₀₀: "add_comm" (∀ n m, ...)` | -| `× ∃ⁿ/ₘ:` | Property test failed on sample n of m | `× ∃²/₁₀₀: "fails" (∀ n, ...)` | - -The `check'` and `checkIO'` macros capture the property syntax for display. -Use `check` and `checkIO` (without apostrophe) for simpler output. - -## Test Functions - -| Function | Evaluation | Syntax Capture | Use Case | -|------------|------------|----------------|-----------------------------------| -| `test` | Compile | No | Simple decidable propositions | -| `check` | Compile | No | Property tests (description only) | -| `check'` | Compile | Yes | Property tests (shows property) | -| `checkIO` | Runtime | No | Runtime property tests | -| `checkIO'` | Runtime | Yes | Runtime tests (shows property) | - -## References - - * https://hackage.haskell.org/package/hspec - * https://hackage.haskell.org/package/QuickCheck --/ - -namespace LSpec -public section -/-- -The main typeclass of propositions that can be tested by `LSpec`. - -| Constructor | Symbol | Meaning | -|-------------|--------|---------| -| `isTrue` | `✓ ∃:` | Unit test passed with formal proof | -| `isPassed` | `✓ ∃ₙ:` | Property test passed n samples (no formal proof) | -| `isMaybe` | `?` | Inconclusive | -| `isFalse` | `× ∃ⁿ/ₘ:` | Property test failed on sample n of m with formal refutation | -| `isFailure` | `×` | Failed without formal refutation | - -For success: `numSamples` = total tests passed -For failure: `failedAt` = which test failed (1-indexed), `totalTests` = total configured --/ -class inductive Testable (p : Prop) where - | isTrue (h : p) - | isPassed (numSamples : Nat := 0) (msg : Option String := none) - | isMaybe (msg : Option String := none) - | isFalse (h : ¬ p) (failedAt : Nat := 0) (totalTests : Nat := 0) (msg : Option String := none) - | isFailure (failedAt : Nat := 0) (totalTests : Nat := 0) (msg : Option String := none) - -/-- A default `Testable` instance with low priority. -/ -instance (priority := 25) (p : Prop) [d : Decidable p] : Testable p := - match d with - | isFalse h => .isFalse h 0 0 "Evaluated to false" - | isTrue h => .isTrue h - -open SlimCheck in -abbrev instTestableOfCheckable (p : Prop) (cfg : Configuration) [Checkable p] : Testable p := - let ((res, numSamples), _) := ReaderT.run (Checkable.runSuite p cfg) (.up mkStdGen) - match res with - | .success (.inr h) => .isTrue h - | .success (.inl _) => .isPassed numSamples - | .gaveUp n => .isFailure 0 cfg.numInst s!"Gave up {n} times" - | .failure h xs n => .isFalse h (numSamples + 1) cfg.numInst $ Checkable.formatFailure "Found problems!" xs n - -/-- Formats the extra error message from `Testable` failures. -/ -def formatErrorMsg : Option String → String - | some msg => s!"\n {msg}" - | none => "" - -section TestSequences - -/-- -A sequence of tests to be executed. - -Constructors: -- `individual`: A compile-time test with a description, proposition, optional property string, and proof of testability -- `individualIO`: A deferred IO test that runs at execution time (used by `checkIO`) -- `group`: A named group of tests for organized output -- `done`: Marks the end of a test sequence - -Tests can be chained using the `next` parameter or appended with `++`: -```lean -def tests : TestSeq := - test "first" (1 = 1) $ - test "second" (2 = 2) - --- Equivalent using append -def tests' : TestSeq := - test "first" (1 = 1) ++ test "second" (2 = 2) -``` - -The `propString` field allows property tests to display the original property syntax. -For `individualIO`, the action returns `(success, numSamples, totalTests, errorMsg)`. --/ -inductive TestSeq - | individual : String → (prop : Prop) → (propString : Option String) → Testable prop → TestSeq → TestSeq - | individualIO : String → (propString : Option String) → IO (Bool × Nat × Nat × Option String) → TestSeq → TestSeq - | group : String → TestSeq → TestSeq → TestSeq - | done - -/-- Appends two sequences of tests. -/ -def TestSeq.append : TestSeq → TestSeq → TestSeq - | done, t => t - | individual d p ps i n, t' => individual d p ps i $ n.append t' - | individualIO d ps action n, t' => individualIO d ps action $ n.append t' - | group d ts n, t' => group d ts $ n.append t' - -instance : Append TestSeq where - append := TestSeq.append - -/-- -Allows the composition of tests with propositions for which a `Testable` -instance exists. Used for unit tests (existential checks). --/ -def test (descr : String) (p : Prop) [Testable p] - (next : TestSeq := .done) : TestSeq := - .individual descr p none inferInstance next - -/-- Allows collecting a `TestSeq` into a test group to print results in a group. -/ -def group (descr : String) (groupTests : TestSeq) - (next : TestSeq := .done) : TestSeq := - .group descr groupTests next - -/-- Alias for `group`. Groups related tests under a descriptive label. - Use for describing a component or function being tested. -/ -def describe (descr : String) (groupTests : TestSeq) (next : TestSeq := .done) : TestSeq := - group descr groupTests next - -/-- Alias for `group`. Groups related tests under a contextual label. - Use for describing circumstances under which tests run. -/ -def context (descr : String) (groupTests : TestSeq) (next : TestSeq := .done) : TestSeq := - group descr groupTests next - -open SlimCheck Decorations in -/-- -Property-based test evaluated at **compile time**. - -Uses SlimCheck to generate random test cases and check the property. The test runs -during elaboration with a fixed random seed (`mkStdGen`), making results deterministic -across compilations. - -- `descr`: Description shown in test output (can be empty if propString is provided) -- `propString`: Optional string representation of the property for display -- `p`: The property to check (e.g., `∀ n m : Nat, n + m = m + n`) -- `next`: Next test in the sequence (default: `.done`) -- `cfg`: SlimCheck configuration (number of tests, etc.) - -```lean -#lspec check "addition commutes" (∀ n m : Nat, n + m = m + n) -#lspec check "with config" (∀ n : Nat, n + 0 = n) .done { numInst := 50 } -``` - -For runtime evaluation with configurable seeds, use `checkIO` instead. --/ -def check (descr : String) (p : Prop) (next : TestSeq := .done) (cfg : Configuration := {}) - (propString : Option String := none) - (p' : DecorationsOf p := by mk_decorations) [Checkable p'] : TestSeq := - haveI : Testable p' := instTestableOfCheckable p' cfg - .individual descr p' propString inferInstance next - -open SlimCheck Decorations in -/-- -Property-based test evaluated at **runtime**. - -Unlike `check`, which runs during compilation, `checkIO` defers test execution until -the test suite is run. This enables: -- Configurable random seeds via `cfg.randomSeed` for reproducible test runs -- Different random values on each execution (when no seed is specified) -- Integration with CI systems that may want deterministic test runs - -- `descr`: Description shown in test output (can be empty if propString is provided) -- `propString`: Optional string representation of the property for display -- `p`: The property to check (e.g., `∀ n m : Nat, n + m = m + n`) -- `next`: Next test in the sequence (default: `.done`) -- `cfg`: SlimCheck configuration including optional `randomSeed` - -```lean --- Runtime test with random seed (different each run) -def tests : TestSeq := - checkIO "addition commutes" (∀ n m : Nat, n + m = m + n) - --- Reproducible test with fixed seed -def reproducible : TestSeq := - checkIO "deterministic" (∀ n : Nat, n * 1 = n) .done { randomSeed := some 42 } - --- Run via main -def main : IO UInt32 := lspecIO (.ofList [("tests", [tests])]) [] -``` - -Note: `checkIO` tests are skipped when run via `#lspec` (which uses the pure runner). -Use `lspecIO` or `lspecEachIO` to execute them. --/ -def checkIO (descr : String) (p : Prop) (next : TestSeq := .done) (cfg : Configuration := {}) - (propString : Option String := none) - (p' : DecorationsOf p := by mk_decorations) [Checkable p'] : TestSeq := - let action : IO (Bool × Nat × Nat × Option String) := do - let (result, numSamples) ← Checkable.checkIO p' cfg - match result with - | .success _ => pure (true, numSamples, cfg.numInst, none) - | .gaveUp n => pure (false, 0, cfg.numInst, some s!"Gave up {n} times") - | .failure _ xs n => pure (false, numSamples, cfg.numInst, some $ Checkable.formatFailure "Found problems!" xs n) - .individualIO descr propString action next - -section SyntaxCapturingMacros -open Lean in -/-- -Macro for `check` that automatically captures the property syntax for display. - -This produces output like: -``` -✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) -``` - -Usage: -```lean -#lspec check' "add_comm" (∀ n m : Nat, n + m = m + n) - --- Can be chained: -def tests : TestSeq := - check' "test1" (∀ n : Nat, n = n) ++ - check' "test2" (∀ n : Nat, n + 0 = n) -``` --/ -scoped macro "check'" descr:str prop:term : term => do - let propStr := prop.raw.reprint.getD s!"{prop}" - `((check $descr $prop .done {} (some $(Lean.quote propStr)) : TestSeq)) - -/-- -Macro for `checkIO` that automatically captures the property syntax for display. - -This produces output like: -``` -✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) -``` - -Usage: -```lean -def tests : TestSeq := - checkIO' "add_comm" (∀ n m : Nat, n + m = m + n) -``` --/ -scoped macro "checkIO'" descr:str prop:term : term => do - let propStr := prop.raw.reprint.getD s!"{prop}" - `((checkIO $descr $prop .done {} (some $(Lean.quote propStr)) : TestSeq)) - -end SyntaxCapturingMacros - -inductive ExpectationFailure (exp got : String) : Prop - -instance : Testable (ExpectationFailure exp got) := - .isFailure 0 0 s!"Expected '{repr exp}' but got '{repr got}'" - -/-- A test pipeline to run a function assuming that `opt` is `Option.some _` -/ -def withOptionSome (descr : String) (opt : Option α) (f : α → TestSeq) : - TestSeq := - match opt with - | none => test descr (ExpectationFailure "some _" "none") - | some a => test descr true $ f a - -/-- A test pipeline to run a function assuming that `opt` is `Option.none` -/ -def withOptionNone (descr : String) (opt : Option α) [ToString α] - (f : TestSeq) : TestSeq := - match opt with - | none => test descr true $ f - | some a => test descr (ExpectationFailure "none" s!"some {a}") - -/-- A test pipeline to run a function assuming that `exc` is `Except.ok _` -/ -def withExceptOk (descr : String) (exc : Except ε α) [ToString ε] - (f : α → TestSeq) : TestSeq := - match exc with - | .error e => test descr (ExpectationFailure "ok _" s!"error {e}") - | .ok a => test descr true $ f a - -/-- A test pipeline to run a function assuming that `exc` is `Except.error _` -/ -def withExceptError (descr : String) (exc : Except ε α) [ToString α] - (f : ε → TestSeq) : TestSeq := - match exc with - | .error e => test descr true $ f e - | .ok a => test descr (ExpectationFailure "error _" s!"ok {a}") - -/-- -Format test output line for successful tests. - -Output formats: -- Unit test: `∃: description` -- Property test with proof: `∀: "description" (property)` -- Property test without proof: `∃₁₀₀: "description" (property)` - -The subscript indicates how many samples were tested. --/ -def formatSuccessLine (descr : String) (propString : Option String) - (hasProof : Bool) (numSamples : Nat) : String := - match propString with - | some ps => - -- Property test: show both description and property - if hasProof then - -- Universal proof: ✓ ∀: "descr" propStr - s!"∀: \"{descr}\" {ps}" - else - -- Existential (sampled): ✓ ∃ₙ: "descr" propStr - s!"∃{numSamples.toSubscriptString}: \"{descr}\" {ps}" - | none => - -- Unit test: ✓ ∃: descr - s!"∃: {descr}" - -/-- -Format test output line for failed tests. - -Output formats: -- Unit test failure: `∃: description` -- Property test failure: `∃²/₁₀₀: "description" (property)` - -The superscript indicates which sample failed (1-indexed). -The subscript indicates the total number of samples configured. --/ -def formatFailureLine (descr : String) (propString : Option String) - (failedAt : Nat) (totalTests : Nat) : String := - match propString with - | some ps => - -- Property test failure: × ∃ⁿ/ₘ: "descr" propStr - if totalTests > 0 then - s!"∃{failedAt.toSuperscriptString}/{totalTests.toSubscriptString}: \"{descr}\" {ps}" - else - s!"∃: \"{descr}\" {ps}" - | none => - -- Unit test failure: × ∃: descr - s!"∃: {descr}" - -/-- -Pure runner for `TestSeq`. Returns `(success, output)` where `success` is `true` -if all tests passed. - -This runner executes `individual` tests but **skips** `individualIO` tests (marking them -with "?"). Used by `#lspec` for compile-time test execution. - -For runtime tests including `checkIO`, use `TestSeq.runIO` instead. - -Output format: -- Unit tests: `✓ ∃: test name` -- Property tests with universal proof: `✓ ∀: "descr" ∀ n m, ...` -- Property tests without proof: `✓ ∃₁₀₀: "descr" ∀ n m, ...` -- Failed property tests: `× ∃ₙ: "descr" ∀ n m, ... (counter-example)` --/ -def TestSeq.run (tSeq : TestSeq) (indent := 0) : Bool × String := - let pad := String.ofList $ List.replicate indent ' ' - let rec aux (acc : String) : TestSeq → Bool × String - | .done => (true, acc) - | .group d ts n => - let (pass, msg) := ts.run (indent + 2) - let (b, m) := aux s!"{acc}{pad}{d}:\n{msg}" n - (pass && b, m) - -- Test with formal proof - | .individual d _ propStr (.isTrue _) n => - let line := formatSuccessLine d propStr true 0 - aux s!"{acc}{pad}✓ {line}\n" n - -- Property test passed without formal proof: ✓ ∃ₙ: "descr" prop - | .individual d _ propStr (.isPassed numSamples _) n => - let line := formatSuccessLine d propStr false numSamples - aux s!"{acc}{pad}✓ {line}\n" n - -- Inconclusive test: ? - | .individual d _ propStr (.isMaybe msg) n => - let line := formatSuccessLine d propStr false 0 - aux s!"{acc}{pad}? {line}{formatErrorMsg msg}\n" n - -- Failed property test with refutation: × ∃ⁿ/ₘ: "descr" prop - | .individual d _ propStr (.isFalse _ failedAt totalTests msg) n => - let line := formatFailureLine d propStr failedAt totalTests - let (_b, m) := aux s!"{acc}{pad}× {line}{formatErrorMsg msg}\n" n - (false, m) - -- Failed test without refutation - | .individual d _ propStr (.isFailure failedAt totalTests msg) n => - let line := formatFailureLine d propStr failedAt totalTests - let (_b, m) := aux s!"{acc}{pad}× {line}{formatErrorMsg msg}\n" n - (false, m) - -- IO test skipped in pure runner - | .individualIO d propStr _ n => - let line := formatSuccessLine d propStr false 0 - aux s!"{acc}{pad}? {line} (IO test skipped in pure runner)\n" n - aux "" tSeq - -/-- -IO runner for `TestSeq`. Returns `(success, output)` where `success` is `true` -if all tests passed. - -Unlike `TestSeq.run`, this runner executes both `individual` and `individualIO` tests, -making it suitable for running `checkIO` property tests at runtime. - -Used by `lspecIO` and `lspecEachIO` for runtime test execution. - -Output format: -- Unit tests: `✓ ∃: test name` -- Property tests with universal proof: `✓ ∀: "descr" ∀ n m, ...` -- Property tests without proof: `✓ ∃₁₀₀: "descr" ∀ n m, ...` -- Failed property tests: `× ∃ₙ: "descr" ∀ n m, ... (counter-example)` --/ -def TestSeq.runIO (tSeq : TestSeq) (indent := 0) : IO (Bool × String) := do - let pad := String.ofList $ List.replicate indent ' ' - let rec aux (acc : String) : TestSeq → IO (Bool × String) - | .done => pure (true, acc) - | .group d ts n => do - let (pass, msg) ← ts.runIO (indent + 2) - let (b, m) ← aux s!"{acc}{pad}{d}:\n{msg}" n - pure (pass && b, m) - -- Test with formal proof - | .individual d _ propStr (.isTrue _) n => - let line := formatSuccessLine d propStr true 0 - aux s!"{acc}{pad}✓ {line}\n" n - -- Property test passed without formal proof: ✓ ∃ₙ: "descr" prop - | .individual d _ propStr (.isPassed numSamples _) n => - let line := formatSuccessLine d propStr false numSamples - aux s!"{acc}{pad}✓ {line}\n" n - -- Inconclusive test: ? - | .individual d _ propStr (.isMaybe msg) n => - let line := formatSuccessLine d propStr false 0 - aux s!"{acc}{pad}? {line}{formatErrorMsg msg}\n" n - -- Failed property test with refutation: × ∃ⁿ/ₘ: "descr" prop - | .individual d _ propStr (.isFalse _ failedAt totalTests msg) n => do - let line := formatFailureLine d propStr failedAt totalTests - let (_b, m) ← aux s!"{acc}{pad}× {line}{formatErrorMsg msg}\n" n - pure (false, m) - -- Failed test without refutation - | .individual d _ propStr (.isFailure failedAt totalTests msg) n => do - let line := formatFailureLine d propStr failedAt totalTests - let (_b, m) ← aux s!"{acc}{pad}× {line}{formatErrorMsg msg}\n" n - pure (false, m) - -- IO property test - | .individualIO d propStr action n => do - let (success, numSamples, totalTests, msgOpt) ← action - if success then - let line := formatSuccessLine d propStr false numSamples - aux s!"{acc}{pad}✓ {line}\n" n - else - -- numSamples is tests passed before failure, so failedAt = numSamples + 1 - let line := formatFailureLine d propStr (numSamples + 1) totalTests - let (_b, m) ← aux s!"{acc}{pad}× {line}{formatErrorMsg msgOpt}\n" n - pure (false, m) - aux "" tSeq - -end TestSequences - -/-- -Runs a `TestSeq` with an output meant for the Lean Infoview. -This function is meant to be called from a custom command. It runs in -`TermElabM` to have access to `logInfo` and `throwError`. --/ -def runInTermElabMAsUnit (tSeq : TestSeq) : Lean.Elab.TermElabM Unit := - match tSeq.run with - | (true, msg) => Lean.logInfo msg - | (false, msg) => throwError msg - -/-- -A custom command to run `LSpec` tests. Example: - -```lean -#lspec test "four equals four" (4 = 4) -``` --/ -macro "#lspec " term:term : command => - `(#eval LSpec.runInTermElabMAsUnit $term) - -open Std (HashMap) in -/-- -Runs test suites from a CLI-style main function. Returns `0` on success, `1` on failure. - -- `map`: A map from suite names to lists of `TestSeq` -- `args`: Command-line arguments to filter which suites run - -If `args` is empty, all suites run. Otherwise, only suites whose names start with -one of the arguments will run. - -Supports both `test`/`check` (compile-time) and `checkIO` (runtime) tests. - -```lean -def mathTests : TestSeq := - test "addition" (1 + 1 = 2) $ - checkIO "commutativity" (∀ n m : Nat, n + m = m + n) - -def stringTests : TestSeq := - test "concat" ("a" ++ "b" = "ab") - -def main (args : List String) : IO UInt32 := - lspecIO (.ofList [("math", [mathTests]), ("string", [stringTests])]) args - --- Run all tests: ./test --- Run math only: ./test math --- Run string only: ./test string -``` --/ -def lspecIO (map : HashMap String (List TestSeq)) (args : List String) : IO UInt32 := do - -- Compute the filtered entries as a List for destructive consumption. - -- Using a List (rather than HashMap) allows tail-recursive pattern matching - -- to release each test suite from memory after it finishes running. - let numSuites := map.size - let entries : List (String × List TestSeq) := - if args.isEmpty then map.toList - else Id.run do - let mut acc : List (String × List TestSeq) := [] - for arg in args do - for (key, tSeq) in map do - if key.startsWith arg then - acc := (key, tSeq) :: acc - pure acc - -- map is now dead — compiler can dec it before the long-running runSuites - let testsWithErrors ← runSuites entries (.emptyWithCapacity numSuites) - - -- Early return 0 when there are no errors - if testsWithErrors.isEmpty then return 0 - - -- Print error messages and then return 1 - IO.eprintln "-------------------------------- Failing tests ---------------------------------" - for (key, msgs) in testsWithErrors do - IO.eprintln key - for msg in msgs do - IO.eprintln msg - return 1 - -where - -- Tail-recursive: after each recursive call, `tSeq` goes out of scope - -- and its reference count is decremented, allowing GC between tests. - runTests (key : String) : - List TestSeq → HashMap String (Array String) → IO (HashMap String (Array String)) - | [], errors => pure errors - | tSeq :: rest, errors => do - let (success, msg) ← tSeq.runIO (indent := 2) - if success then - IO.println msg - runTests key rest errors - else - IO.eprintln msg - let errors := match errors[key]? with - | some msgs => errors.insert key (msgs.push msg) - | none => errors.insert key #[msg] - runTests key rest errors - - -- Tail-recursive: after each recursive call, `tSeqs` goes out of scope - -- and its reference count is decremented, allowing GC between suites. - runSuites : - List (String × List TestSeq) → HashMap String (Array String) → IO (HashMap String (Array String)) - | [], errors => pure errors - | (key, tSeqs) :: rest, errors => do - IO.println key - let errors ← runTests key tSeqs errors - runSuites rest errors - -/-- -Runs tests lazily from a list, alternating between test creation and execution. -Returns `0` on success, `1` on failure. - -Unlike `lspecIO` which builds all test suites upfront, this function creates and runs -tests one at a time. Useful when test creation involves expensive IO operations -(e.g., reading files, network calls). - -Supports both `test`/`check` (compile-time) and `checkIO` (runtime) tests. - -```lean -def main : IO UInt32 := - lspecEachIO ["file1.json", "file2.json"] fun path => do - let contents ← IO.FS.readFile path - pure $ test s!"{path} is valid" (contents.length > 0) -``` --/ -def lspecEachIO (l : List α) (f : α → IO TestSeq) : IO UInt32 := do - let success ← l.foldlM (init := true) fun acc a => do - match ← (← f a).runIO with - | (true, msg) => IO.println msg; pure acc - | (false, msg) => IO.eprintln msg; pure false - if success then return 0 else return 1 - -end -end LSpec diff --git a/LSpec/Plausible.lean b/LSpec/Plausible.lean deleted file mode 100644 index 7d14664..0000000 --- a/LSpec/Plausible.lean +++ /dev/null @@ -1,170 +0,0 @@ -module -public meta import LSpec.LSpec -public meta import Plausible - -/-! -# Plausible integration for `LSpec` - -This module provides an alternative property-based testing backend for `LSpec` -built on Lean's official [Plausible](https://github.com/leanprover-community/plausible) -library. - -For backwards-compatibility reasons, the functions in this module live alongside LSpec's -SlimCheck-based `check`/`checkIO`functions, as opposed to replacing them. - -The new entry points are: - -- **`checkPlausible`/`checkPlausible'`**: compile-time property tests -- **`checkPlausibleIO`/`checkPlausibleIO'`**: runtime property tests with configurable seeds --/ - -namespace LSpec -public meta section - -/-- Variant of `Plausible.Testable.runSuiteAux`: tries `n` times to find a counter-example to `p`, - and reports the no. of trials that succeeded before a counterexample was found. -/ -def runPlausibleSuiteAux (p : Prop) [Plausible.Testable p] (cfg : Plausible.Configuration) : - Plausible.TestResult p → Nat → Plausible.Gen (Plausible.TestResult p × Nat) - | r, 0 => return (r, cfg.numInst) - | r, n + 1 => do - let size (_ : Nat) := (cfg.numInst - n - 1) * cfg.maxSize / cfg.numInst - let x ← Plausible.retry ((Plausible.Testable.runProp p cfg true).resize size) cfg.numRetries - match x with - | .success (PSum.inl ()) => runPlausibleSuiteAux p cfg x n - | .gaveUp g => runPlausibleSuiteAux p cfg (Plausible.giveUp g r) n - | _ => return (x, cfg.numInst - n - 1) - -/-- Variant of `Plausible.Testable.runSuite` (tries to find a counter-example to `p`), - but also tracks the no. of trials that succeeded before a counterexample was found. -/ -def runPlausibleSuite (p : Prop) [Plausible.Testable p] (cfg : Plausible.Configuration := {}) : - Plausible.Gen (Plausible.TestResult p × Nat) := - runPlausibleSuiteAux p cfg (.gaveUp 0) cfg.numInst - -/-- Variant of `Plausible.Testable.checkIO` (run a test suite for `p` in `IO` using the global RNG - in `stdGenRef`), but also tracks the no. of trials that succeeded. -/ -def runPlausibleSuiteIO (p : Prop) [Plausible.Testable p] (cfg : Plausible.Configuration := {}) : - IO (Plausible.TestResult p × Nat) := - match cfg.randomSeed with - | none => Plausible.Gen.run (runPlausibleSuite p cfg) 0 - | some seed => Plausible.runRandWith seed (runPlausibleSuite p cfg) - -/-- Bridges a `Plausible.Testable` instance into LSpec's `Testable` result type, - running the suite at compile time with a fixed seed for deterministic results. -/ -abbrev instTestableOfPlausible (p : Prop) (cfg : Plausible.Configuration) [Plausible.Testable p] : - Testable p := - match ReaderT.run (Plausible.runRandWith 0 (runPlausibleSuite p cfg)) ⟨0⟩ with - | .error _ => .isFailure 0 cfg.numInst "Generation failure" - | .ok (.success (.inr h), _) => .isTrue h - | .ok (.success (.inl _), _) => .isPassed cfg.numInst - | .ok (.gaveUp n, _) => .isFailure 0 cfg.numInst s!"Gave up {n} times" - | .ok (.failure h xs n, numSamples) => - .isFalse h (numSamples + 1) cfg.numInst $ Plausible.Testable.formatFailure "Found problems!" xs n - -open Plausible.Decorations in -/-- -Property-based test evaluated at compile time, using Plausible. - -This is the Plausible-based counterpart to `check`, which uses SlimCheck. -Generates random test cases and checks the property during elaboration with a fixed random seed, -making results deterministic across compilations. - -- `descr`: Description shown in test output (can be empty if propString is provided) -- `p`: The property to check (e.g., `∀ n m : Nat, n + m = m + n`) -- `next`: Next test in the sequence (default: `.done`) -- `cfg`: Plausible configuration (number of tests, etc.) -- `propString`: Optional string representation of the property for display - -```lean -#lspec checkPlausible "addition commutes" (∀ n m : Nat, n + m = m + n) -#lspec checkPlausible "with config" (∀ n : Nat, n + 0 = n) .done { numInst := 50 } -``` - -For runtime evaluation with configurable seeds, use `checkPlausibleIO` instead. --/ -def checkPlausible (descr : String) (p : Prop) (next : TestSeq := .done) - (cfg : Plausible.Configuration := {}) (propString : Option String := none) - (p' : DecorationsOf p := by mk_decorations) [Plausible.Testable p'] : TestSeq := - haveI : Testable p' := instTestableOfPlausible p' cfg - .individual descr p' propString inferInstance next - -open Plausible.Decorations in -/-- -Property-based test evaluated at runtime, using Plausible. - -This is the Plausible-based analog to `checkIO`. Unlike `checkPlausible`, which runs during -compilation, `checkPlausibleIO` defers test execution until the test suite is run, enabling -configurable random seeds via `cfg.randomSeed` and fresh random values on each run. - -- `descr`: Description shown in test output (can be empty if propString is provided) -- `p`: The property to check (e.g., `∀ n m : Nat, n + m = m + n`) -- `next`: Next test in the sequence (default: `.done`) -- `cfg`: Plausible configuration including optional `randomSeed` -- `propString`: Optional string representation of the property for display - -```lean -def tests : TestSeq := - checkPlausibleIO "addition commutes" (∀ n m : Nat, n + m = m + n) - -def reproducible : TestSeq := - checkPlausibleIO "deterministic" (∀ n : Nat, n * 1 = n) .done { randomSeed := some 42 } - -def main : IO UInt32 := lspecIO (.ofList [("tests", [tests])]) [] -``` - -Note: `checkPlausibleIO` tests are skipped when run via `#lspec` (which uses the pure runner). -Use `lspecIO` or `lspecEachIO` to execute them. --/ -def checkPlausibleIO (descr : String) (p : Prop) (next : TestSeq := .done) - (cfg : Plausible.Configuration := {}) (propString : Option String := none) - (p' : DecorationsOf p := by mk_decorations) [Plausible.Testable p'] : TestSeq := - let action : IO (Bool × Nat × Nat × Option String) := do - match ← runPlausibleSuiteIO p' cfg with - | (.success _, _) => pure (true, cfg.numInst, cfg.numInst, none) - | (.gaveUp n, _) => pure (false, 0, cfg.numInst, some s!"Gave up {n} times") - | (.failure _ xs n, numSamples) => - pure (false, numSamples, cfg.numInst, some $ Plausible.Testable.formatFailure "Found problems!" xs n) - .individualIO descr propString action next - -section SyntaxCapturingMacros -open Lean in -/-- -Macro for `checkPlausible` that automatically captures the property syntax for display. - -This produces output like: -``` -✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) -``` - -Usage: -```lean -#lspec checkPlausible' "add_comm" (∀ n m : Nat, n + m = m + n) -``` --/ -scoped macro "checkPlausible'" descr:str prop:term : term => do - let propStr := prop.raw.reprint.getD s!"{prop}" - `((checkPlausible $descr $prop .done {} (some $(Lean.quote propStr)) : TestSeq)) - -open Lean in -/-- -Macro for `checkPlausibleIO` that automatically captures the property syntax for display. -This is the Plausible counterpart to LSpec's `checkIO'` macro that currently uses SlimCheck. - -This produces output like: -``` -✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) -``` - -Usage: -```lean -def tests : TestSeq := - checkPlausibleIO' "add_comm" (∀ n m : Nat, n + m = m + n) -``` --/ -scoped macro "checkPlausibleIO'" descr:str prop:term : term => do - let propStr := prop.raw.reprint.getD s!"{prop}" - `((checkPlausibleIO $descr $prop .done {} (some $(Lean.quote propStr)) : TestSeq)) - -end SyntaxCapturingMacros - -end -end LSpec diff --git a/LSpec/Processors.lean b/LSpec/Processors.lean new file mode 100644 index 0000000..e4c4cbd --- /dev/null +++ b/LSpec/Processors.lean @@ -0,0 +1,183 @@ +module +public import LSpec.Core +public import LSpec.Runner + +/-! +# Built-in `TestProcessor`s (`LSpec.Processors`) + +Inspired by `nest-core`'s pluggable `TestProcessor` architecture and `LSpec`'s +readable hierarchical console output with bottom failure recaps: +- `Processors.list`: prints all matching test paths (with tags & mode) without + running any tests or acquiring any resources. +- `Processors.console`: executes the `TestTree` with bounded parallelism and + renders hierarchical pass/fail/skip output, per-test timings, captured stdout + on failure (or `--verbose`), summary counts, and a bottom recap of failures. +-/ + +namespace LSpec.Processors +public section + +private def ansiReset := "\x1b[0m" +private def ansiGreen := "\x1b[32m" +private def ansiBoldGreen := "\x1b[1;32m" +private def ansiRed := "\x1b[31m" +private def ansiBoldRed := "\x1b[1;31m" +private def ansiYellow := "\x1b[33m" +private def ansiDim := "\x1b[2m" +private def ansiBold := "\x1b[1m" + +private def colorize (useColor : Bool) (code : String) (s : String) : String := + if useColor then code ++ s ++ ansiReset else s + +private def pad (indent : Nat) : String := + String.ofList (List.replicate indent ' ') + +private def indentBlock (indent : Nat) (s : String) : String := + let prefixStr := pad indent + let lines := s.splitOn "\n" + "\n".intercalate (lines.map (prefixStr ++ ·)) + +/-- Build a `TestFilter` from standard `TestOptions` keys. -/ +def filterFromOptions (opts : TestOptions) : TestFilter := + let splitNonEmpty (key : String) : Array String := + let raw := opts.getString key "" + if raw.isEmpty then #[] + else (raw.splitOn "\x00").filter (!·.isEmpty) |>.toArray + { + includes := splitNonEmpty "filter.includes" + exact := splitNonEmpty "filter.exact" + excludes := splitNonEmpty "filter.excludes" + includeTags := splitNonEmpty "filter.includeTags" + excludeTags := splitNonEmpty "filter.excludeTags" + } + +/-- Build a `RunConfig` from standard `TestOptions` keys. -/ +def runConfigFromOptions (opts : TestOptions) : RunConfig := + { + threads := opts.getNat "runner.threads" 1 + defaultMode := + if opts.getBool "runner.sequential" false then .sequential else .parallel + seed := opts.getUInt64? "runner.seed" + filter := filterFromOptions opts + options := opts + failFast := opts.getBool "runner.failFast" false + isolateStreams := opts.getBool "runner.isolateStreams" true + } + +/-- Format a `ReportTree` as a human-readable string (useful for both console + output and programmatic inspection in tests). -/ +partial def formatReport (report : ReportTree) (useColor : Bool := false) + (verbose : Bool := false) : String := + let lines := (go 0 report).run #[] |>.2 + "\n".intercalate lines.toList +where + push (s : String) : StateM (Array String) Unit := modify (·.push s) + + go (indent : Nat) : ReportTree → StateM (Array String) Unit + | .group name children => do + let nextIndent := + if name.isEmpty then indent + else indent + 2 + unless name.isEmpty do + push s!"{pad indent}{colorize useColor ansiBold name}" + for c in children do + go nextIndent c + | .leaf rep => do + let timing := colorize useColor ansiDim s!"({rep.durationMs} ms)" + match rep.result.outcome with + | .passed => + let glyph := colorize useColor ansiGreen "✓" + let extra := if rep.result.summary.isEmpty then "" else s!" {colorize useColor ansiDim rep.result.summary}" + push s!"{pad indent}{glyph} {rep.name}{extra} {timing}" + if verbose && !rep.result.details.isEmpty then + push (indentBlock (indent + 2) rep.result.details) + if verbose && !rep.capturedOutput.isEmpty then + push (indentBlock (indent + 2) s!"[output]\n{rep.capturedOutput.trimAsciiEnd}") + | .skipped reason => + let glyph := colorize useColor ansiYellow "○" + let msg := match reason with + | some r => s!" ({r})" + | none => " (pending)" + push s!"{pad indent}{glyph} {rep.name}{colorize useColor ansiYellow msg}" + | .failed _ => + let glyph := colorize useColor ansiRed "×" + let msg := if rep.result.summary.isEmpty then "" else s!": {rep.result.summary}" + push s!"{pad indent}{glyph} {colorize useColor ansiRed (rep.name ++ msg)} {timing}" + unless rep.result.details.isEmpty do + push (indentBlock (indent + 4) rep.result.details) + unless rep.capturedOutput.isEmpty do + push (indentBlock (indent + 4) s!"[captured output]\n{rep.capturedOutput.trimAsciiEnd}") + +/-- Format the bottom failure recap and run summary. -/ +def formatSummary (report : ReportTree) (summary : RunSummary) + (useColor : Bool := false) : String := Id.run do + let mut lines : Array String := #[] + let fails := report.failures + unless fails.isEmpty do + lines := lines.push "" + lines := lines.push (colorize useColor ansiBoldRed + "-------------------------------- Failing tests ---------------------------------") + for rep in fails do + let fullPath := "/".intercalate rep.path.toList + lines := lines.push (colorize useColor ansiRed s!"× {fullPath}") + unless rep.result.summary.isEmpty do + lines := lines.push (indentBlock 2 rep.result.summary) + unless rep.result.details.isEmpty do + lines := lines.push (indentBlock 2 rep.result.details) + lines := lines.push "" + let statusStr := + if summary.allPassed then + colorize useColor ansiBoldGreen + s!"{summary.passed} passed, {summary.failed} failed, {summary.skipped} skipped" + else + colorize useColor ansiBoldRed + s!"{summary.passed} passed, {summary.failed} failed, {summary.skipped} skipped" + let metaInfo := colorize useColor ansiDim + s!"({summary.total} total, {summary.totalDurationMs} ms, threads={summary.threads}, seed={summary.seed})" + lines := lines.push s!"{statusStr} {metaInfo}" + return "\n".intercalate lines.toList + +/-- Processor that lists all matching tests without executing them or acquiring resources. + Enabled when `TestOptions` has `"runner.list" = true`. -/ +def list : TestProcessor where + name := "list" + shouldRun opts := opts.getBool "runner.list" false + exec opts tree := do + let filter := filterFromOptions opts + let mode := if opts.getBool "runner.sequential" false then .sequential else .parallel + let filtered := filterTree filter tree + match filtered with + | none => return 0 + | some t => + let entries := listTests t mode + for entry in entries do + let tagSuffix := + if entry.tags.isEmpty then "" + else s!" [{", ".intercalate entry.tags.toList}]" + let modeSuffix := match entry.mode with + | .sequential => " (sequential)" + | .parallel => "" + IO.println s!"{entry.pathString}{tagSuffix}{modeSuffix}" + return 0 + +/-- Default console processor that runs tests with bounded parallelism and prints + hierarchical results plus a summary. -/ +def console : TestProcessor where + name := "console" + shouldRun _ := true + exec opts tree := do + let cfg := runConfigFromOptions opts + let useColor := opts.getBool "console.color" true + let verbose := opts.getBool "console.verbose" false + let (report, summary) ← runTree tree cfg + let body := formatReport report useColor verbose + unless body.isEmpty do + IO.println body + IO.println (formatSummary report summary useColor) + return if summary.allPassed then 0 else 1 + +/-- Default processor pipeline: `list` first (if `--list`), otherwise `console`. -/ +def defaultProcessors : List TestProcessor := [list, console] + +end +end LSpec.Processors diff --git a/LSpec/Property/Check.lean b/LSpec/Property/Check.lean new file mode 100644 index 0000000..60d147f --- /dev/null +++ b/LSpec/Property/Check.lean @@ -0,0 +1,260 @@ +module +public import LSpec.Core +public import LSpec.Assert +public import LSpec.Property.Gen +public import LSpec.Property.Sampleable + +/-! +# Bool-based Property Testing (`Property`, `PropTestable`, `PropTest`) + +Purely `Bool`- and `AssertM`-based property testing inspired by QuickCheck and +`nest-slimcheck`: +- No `Prop` / `Decidable` / `mk_decorations` tactic overhead. +- Works for arbitrary arity functions `fun (a : A) (b : B) => ...` returning + `Bool`, `AssertM Unit`, `Except String Unit`, or nested `forAll` / `==>` combinators. +- Thread-safe deterministic per-test PRNG (`Rng`) with seed always recorded and + reported for 100% reproducible failures under parallel execution. +-/ + +namespace LSpec.Prop +public section + +/-- Configuration for a property-based test. -/ +structure PropertyConfig where + /-- Number of passing test cases required. -/ + numTests : Nat := 100 + /-- Maximum generator size parameter (grows linearly from 0 to `maxSize`). -/ + maxSize : Nat := 100 + /-- Maximum ratio of discarded inputs per requested test before giving up. -/ + maxDiscardRatio : Nat := 10 + /-- Maximum shrinking steps per failing argument. -/ + maxShrinks : Nat := 100 + /-- Optional fixed seed; if `none`, uses the deterministic per-test seed from `TestContext`. -/ + seed : Option UInt64 := none + deriving BEq, Repr + +namespace PropertyConfig + +/-- Read overrides from `TestOptions` keys (`prop.numTests`, `prop.maxSize`, + `prop.maxDiscardRatio`, `prop.maxShrinks`, `prop.seed`). -/ +def fromOptions (opts : TestOptions) (base : PropertyConfig := {}) : PropertyConfig := + { + numTests := opts.getNat "prop.numTests" base.numTests + maxSize := opts.getNat "prop.maxSize" base.maxSize + maxDiscardRatio := opts.getNat "prop.maxDiscardRatio" base.maxDiscardRatio + maxShrinks := opts.getNat "prop.maxShrinks" base.maxShrinks + seed := opts.getUInt64? "prop.seed" |>.orElse fun () => base.seed + } + +end PropertyConfig + +/-- Outcome of a single generated property trial (after any shrinking). -/ +inductive PropOutcome where + | passed + | discarded + | failed (args : List String) (message : String) (pos : Option SourcePos := none) + deriving BEq, Repr + +/-- A single-trial property runner returning `(outcome, numShrinks, nextRng)`. -/ +structure Property where + runOnce : PropertyConfig → Nat → Rng → IO (PropOutcome × Nat × Rng) + +/-- Any type that can be checked as a property (`Bool`, `AssertM Unit`, + `Except String Unit`, `Implies`, `Property`, and functions `α → β`). -/ +class PropTestable (α : Type u) where + toProperty : α → Property + +instance : PropTestable Property where + toProperty p := p + +instance : PropTestable Bool where + toProperty b := { + runOnce := fun _ _ rng => + if b then pure (.passed, 0, rng) + else pure (.failed [] "property evaluated to false" none, 0, rng) + } + +instance : PropTestable (AssertM Unit) where + toProperty act := { + runOnce := fun _ _ rng => do + match ← act.run with + | .ok () => pure (.passed, 0, rng) + | .error (.skipped _) => pure (.discarded, 0, rng) + | .error (.failed err) => + let msg := if err.details.isEmpty then err.message + else s!"{err.message}\n{err.details}" + pure (.failed [] msg err.pos, 0, rng) + } + +instance : PropTestable (Except String Unit) where + toProperty res := { + runOnce := fun _ _ rng => + match res with + | .ok () => pure (.passed, 0, rng) + | .error msg => pure (.failed [] msg none, 0, rng) + } + +/-- Precondition guard for properties: `(n != 0) ==> Nat.blt (n - 1) n`. + If `cond` is `false`, the generated input is discarded without evaluating `body`. -/ +def implies [PropTestable β] (cond : Bool) (body : Unit → β) : Property where + runOnce cfg size rng := + if cond then + (PropTestable.toProperty (body ())).runOnce cfg size rng + else + pure (.discarded, 0, rng) + +/-- Precondition guard syntax for properties: `(n != 0) ==> Nat.blt (n - 1) n`. -/ +syntax:25 term:26 " ==> " term:25 : term +macro_rules + | `($c ==> $b) => `(LSpec.Prop.implies $c (fun () => $b)) + +/-- Greedy shrinking loop bounded by `maxShrinks`. -/ +private partial def shrinkLoop [PropTestable β] (cfg : PropertyConfig) (size : Nat) + (innerRng : Rng) (shrink : α → List α) (f : α → β) + (curX : α) (curArgs : List String) (curMsg : String) (curPos : Option SourcePos) + (stepsLeft : Nat) (totalShrinks : Nat) : IO (α × List String × String × Option SourcePos × Nat) := do + if stepsLeft == 0 then + return (curX, curArgs, curMsg, curPos, totalShrinks) + let candidates := shrink curX + for cand in candidates do + let (res, innerShrinks, _) ← (PropTestable.toProperty (f cand)).runOnce cfg size innerRng + match res with + | .failed candArgs candMsg candPos => + return ← shrinkLoop cfg size innerRng shrink f cand candArgs candMsg candPos + (stepsLeft - 1) (totalShrinks + 1 + innerShrinks) + | _ => pure () + return (curX, curArgs, curMsg, curPos, totalShrinks) + +/-- Format a generated argument for counterexample display. + Provides built-in support for `Repr`, `ToString`, and `ByteArray` without orphan instances. -/ +class FormatValue (α : Type u) where + formatValue : α → String + +instance (priority := high) [Repr α] : FormatValue α where + formatValue x := reprStr x + +instance (priority := low) [ToString α] : FormatValue α where + formatValue x := toString x + +instance : FormatValue ByteArray where + formatValue bs := s!"ByteArray({bs.data.toList})" + +/-- Quantify over a custom generator and shrinker with an optional argument label. -/ +def forAllShrink [FormatValue α] [PropTestable β] (gen : Gen α) (shrink : α → List α) + (f : α → β) (label : Option String := none) : Property where + runOnce cfg size rng := do + let (x, rngAfterSample) := gen.runWith size rng + let (res, innerShrinks, rngAfterBody) ← (PropTestable.toProperty (f x)).runOnce cfg size rngAfterSample + match res with + | .passed => return (.passed, 0, rngAfterBody) + | .discarded => return (.discarded, 0, rngAfterBody) + | .failed args msg pos => + let (minX, minArgs, minMsg, minPos, totalShrinks) ← + shrinkLoop cfg size rngAfterSample shrink f x args msg pos cfg.maxShrinks innerShrinks + let rendered := FormatValue.formatValue minX + let formatted := match label with + | some name => s!"{name} := {rendered}" + | none => rendered + return (.failed (formatted :: minArgs) minMsg minPos, totalShrinks, rngAfterBody) + +/-- Quantify over a custom generator using `Shrinkable α`. -/ +def forAll [FormatValue α] [Shrinkable α] [PropTestable β] (gen : Gen α) + (f : α → β) (label : Option String := none) : Property := + forAllShrink gen Shrinkable.shrink f label + +/-- Quantify over a custom generator with shrinking disabled. -/ +def forAllNoShrink [FormatValue α] [PropTestable β] (gen : Gen α) + (f : α → β) (label : Option String := none) : Property := + forAllShrink gen (fun _ => []) f label + +/-- Quantify over `Sampleable α` with an explicit variable name shown in counterexamples. -/ +def forAllNamed [Sampleable α] [Shrinkable α] [FormatValue α] [PropTestable β] + (name : String) (f : α → β) : Property := + forAllShrink Sampleable.sample Shrinkable.shrink f (some name) + +/-- Automatic property checking for arbitrary-arity functions `α → β`. -/ +instance (priority := low) [Sampleable α] [Shrinkable α] [FormatValue α] [PropTestable β] : + PropTestable (α → β) where + toProperty f := forAllShrink Sampleable.sample Shrinkable.shrink f none + +/-- Overall result of running a property test suite. -/ +inductive PropertyResult where + | passed (numTests : Nat) (seed : UInt64) + | failed (args : List String) (message : String) (pos : Option SourcePos) + (numTests : Nat) (numShrinks : Nat) (seed : UInt64) + | gaveUp (discarded : Nat) (passed : Nat) (seed : UInt64) + deriving BEq, Repr + +/-- Execute a `Property` with `cfg` and explicit `seed`. -/ +def runProperty (prop : Property) (cfg : PropertyConfig) (seed : UInt64) : IO PropertyResult := do + let maxDiscards := cfg.numTests * cfg.maxDiscardRatio + let mut passed := 0 + let mut discarded := 0 + let mut rng := Rng.ofSeed seed + while passed < cfg.numTests do + let attempt := passed + discarded + let size := + if cfg.numTests ≤ 1 then cfg.maxSize + else min cfg.maxSize ((attempt * cfg.maxSize) / (cfg.numTests - 1)) + let (outcome, shrinks, rng') ← prop.runOnce cfg size rng + rng := rng' + match outcome with + | .passed => + passed := passed + 1 + | .discarded => + discarded := discarded + 1 + if discarded > maxDiscards then + return .gaveUp discarded passed seed + | .failed args msg pos => + return .failed args msg pos (passed + 1) shrinks seed + return .passed passed seed + +/-- Format counterexample arguments for failure output. -/ +def formatCounterexample (args : List String) (msg : String) + (pos : Option SourcePos) (failedAt : Nat) (totalTests : Nat) + (numShrinks : Nat) (seed : UInt64) : String := + let argLines := args.zipIdx.map fun (a, i) => + if (a.splitOn " := ").length > 1 then s!" {a}" + else s!" arg {i} := {a}" + let locLine := match pos with + | some p => [s!" at {p}"] + | none => [] + let header := s!"Falsified after {failedAt}/{totalTests} tests ({numShrinks} shrinks, seed {seed}):" + let body := argLines ++ locLine ++ [s!" reason: {msg}"] + "\n".intercalate (header :: body) + +/-- A packaged property test implementing `LSpec.IsTest`. + Defers construction of the `Property` via `Unit → Property` so nothing runs on import. -/ +structure PropTest where + mkProperty : Unit → Property + config : PropertyConfig := {} + +namespace PropTest + +def of [PropTestable α] (p : Unit → α) (config : PropertyConfig := {}) : PropTest := + { mkProperty := fun () => PropTestable.toProperty (p ()), config } + +end PropTest + +instance : IsTest PropTest where + run ctx pt := do + let cfg := PropertyConfig.fromOptions ctx.options pt.config + let seed := cfg.seed.getD ctx.seed + let prop ← IO.lazyPure pt.mkProperty + match ← runProperty prop cfg seed with + | .passed n s => + return .pass s!"({n} tests, seed {s})" + | .gaveUp d p s => + return .fail + s!"gave up after {d} discarded inputs ({p}/{cfg.numTests} passed, seed {s})" + "" + (.gaveUp s d p) + | .failed args msg pos failedAt shrinks s => + let details := formatCounterexample args msg pos failedAt cfg.numTests shrinks s + return .fail + s!"falsified after {failedAt}/{cfg.numTests} tests ({shrinks} shrinks, seed {s})" + details + (.property s failedAt shrinks) + +end +end LSpec.Prop diff --git a/LSpec/Property/Gen.lean b/LSpec/Property/Gen.lean new file mode 100644 index 0000000..13b2264 --- /dev/null +++ b/LSpec/Property/Gen.lean @@ -0,0 +1,227 @@ +module + +/-! +# Pure Random Generator (`Gen`) + +A deterministic, pure generator monad for property-based testing. +Unlike `IO.runRand`, `Gen` never touches global `IO.stdGenRef`, making it +100% thread-safe and reproducible under parallel test execution. +-/ + +namespace LSpec.Prop +public section + +/-- Deterministic SplitMix64 PRNG state. Fast, splittable, and completely thread-safe. -/ +structure Rng where + state : UInt64 + deriving BEq, Repr, Inhabited + +namespace Rng + +def ofSeed (seed : UInt64) : Rng := ⟨seed⟩ + +/-- Advance state and return a uniformly distributed `UInt64`. -/ +@[inline] def nextUInt64 (r : Rng) : UInt64 × Rng := + let s := r.state + 0x9E3779B97F4A7C15 + let z := (s ^^^ (s >>> 30)) * 0xBF58476D1CE4E5B9 + let z := (z ^^^ (z >>> 27)) * 0x94D049BB133111EB + (z ^^^ (z >>> 31), ⟨s⟩) + +/-- Split into two independent PRNG streams. -/ +@[inline] def split (r : Rng) : Rng × Rng := + let (a, r1) := r.nextUInt64 + let (b, r2) := r1.nextUInt64 + (⟨a⟩, ⟨b ^^^ r2.state⟩) + +/-- Uniform `Nat` in `[lo, hi]` (inclusive). If `lo > hi`, swaps bounds. -/ +def nextNatBound (r : Rng) (lo hi : Nat) : Nat × Rng := + let (lo, hi) := if lo ≤ hi then (lo, hi) else (hi, lo) + let span := hi - lo + 1 + if span ≤ 1 then + (lo, r) + else if span ≤ UInt64.size then + let (v, r') := r.nextUInt64 + (lo + v.toNat % span, r') + else + -- Combine two UInt64 draws for very large spans. + let (v1, r1) := r.nextUInt64 + let (v2, r2) := r1.nextUInt64 + let combined := v1.toNat * UInt64.size + v2.toNat + (lo + combined % span, r2) + +end Rng + +/-- Pure generator monad parameterized by a size hint (`Nat`) and pure `Rng` state. -/ +abbrev Gen (α : Type u) := ReaderT (ULift Nat) (StateM (ULift Rng)) α + +namespace Gen + +/-- Execute a generator with a given size and PRNG state. -/ +def runWith (g : Gen α) (size : Nat) (rng : Rng) : α × Rng := + let (a, st) := (g.run ⟨size⟩).run ⟨rng⟩ + (a, st.down) + +/-- Execute a generator with a given size and `UInt64` seed. -/ +def evalSeed (g : Gen α) (size : Nat) (seed : UInt64) : α := + (g.runWith size (Rng.ofSeed seed)).1 + +/-- Read the current size parameter. -/ +def getSize : Gen Nat := + return (← read).down + +/-- Run a generator with a transformed size parameter. -/ +def resize (f : Nat → Nat) (g : Gen α) : Gen α := + withReader (fun s => ⟨f s.down⟩) g + +/-- Run a generator with the size parameter passed explicitly. -/ +def sized (f : Nat → Gen α) : Gen α := do + f (← getSize) + +/-- Scale the size parameter by `f`. Alias for `resize`. -/ +def scale (f : Nat → Nat) (g : Gen α) : Gen α := + resize f g + +/-- Draw a raw `UInt64`. -/ +def nextUInt64 : Gen UInt64 := do + let r := (← get).down + let (v, r') := r.nextUInt64 + set (ULift.up r') + return v + +/-- Generate a `Nat` uniformly in `[lo, hi]` (inclusive). -/ +def chooseNat (lo hi : Nat) : Gen Nat := do + let r := (← get).down + let (v, r') := r.nextNatBound lo hi + set (ULift.up r') + return v + +/-- Generate an `Int` uniformly in `[lo, hi]` (inclusive). -/ +def chooseInt (lo hi : Int) : Gen Int := do + let (lo, hi) := if lo ≤ hi then (lo, hi) else (hi, lo) + let span := (hi - lo).toNat + let offset ← chooseNat 0 span + return lo + Int.ofNat offset + +/-- Generate a `Bool` with equal probability. -/ +def bool : Gen Bool := do + return ((← nextUInt64) &&& 1) == 1 + +/-- Generate a `UInt8` in `[lo, hi]`. -/ +def chooseUInt8 (lo : UInt8 := 0) (hi : UInt8 := UInt8.ofNat (UInt8.size - 1)) : Gen UInt8 := + Nat.toUInt8 <$> chooseNat lo.toNat hi.toNat + +/-- Generate a `UInt16` in `[lo, hi]`. -/ +def chooseUInt16 (lo : UInt16 := 0) (hi : UInt16 := UInt16.ofNat (UInt16.size - 1)) : Gen UInt16 := + Nat.toUInt16 <$> chooseNat lo.toNat hi.toNat + +/-- Generate a `UInt32` in `[lo, hi]`. -/ +def chooseUInt32 (lo : UInt32 := 0) (hi : UInt32 := UInt32.ofNat (UInt32.size - 1)) : Gen UInt32 := + Nat.toUInt32 <$> chooseNat lo.toNat hi.toNat + +/-- Generate a `UInt64` in `[lo, hi]`. -/ +def chooseUInt64 (lo : UInt64 := 0) (hi : UInt64 := UInt64.ofNat (UInt64.size - 1)) : Gen UInt64 := + Nat.toUInt64 <$> chooseNat lo.toNat hi.toNat + +/-- Generate a `Fin n` uniformly. -/ +def chooseFin (n : Nat) [NeZero n] : Gen (Fin n) := do + let k ← chooseNat 0 (n - 1) + return Fin.ofNat n k + +/-- Choose uniformly among an array of generators, using `fallback` if empty. -/ +def oneOf (gens : Array (Gen α)) (fallback : Gen α) : Gen α := do + if h : gens.size > 0 then + let i ← chooseNat 0 (gens.size - 1) + if hi : i < gens.size then gens[i] else fallback + else + fallback + +/-- Choose uniformly among an array of generators (requires `Inhabited α`). -/ +def oneOf! [Inhabited α] (gens : Array (Gen α)) : Gen α := + oneOf gens (pure default) + +/-- Choose uniformly among an array of values, returning `fallback` if empty. -/ +def elements (xs : Array α) (fallback : α) : Gen α := do + if h : xs.size > 0 then + let i ← chooseNat 0 (xs.size - 1) + if hi : i < xs.size then return xs[i] else return fallback + else + return fallback + +/-- Choose uniformly among an array of values (requires `Inhabited α`). -/ +def elements! [Inhabited α] (xs : Array α) : Gen α := + elements xs default + +/-- Weighted choice among `(weight, generator)` pairs. -/ +def frequency (weighted : Array (Nat × Gen α)) (fallback : Gen α) : Gen α := do + let totalWeight := weighted.foldl (fun acc (w, _) => acc + w) 0 + if totalWeight == 0 then + fallback + else + let choice ← chooseNat 0 (totalWeight - 1) + let mut cumulative := 0 + for (w, g) in weighted do + cumulative := cumulative + w + if choice < cumulative then + return ← g + fallback + +/-- Generate an `Array α` of length in `[0, size]`. -/ +def arrayOf (g : Gen α) : Gen (Array α) := do + let len ← chooseNat 0 (← getSize) + let mut out := Array.mkEmpty len + for _ in [:len] do + out := out.push (← g) + return out + +/-- Generate a non-empty `Array α` of length in `[1, max 1 size]`. -/ +def arrayOf1 (g : Gen α) : Gen (Array α) := do + let sz := max 1 (← getSize) + let len ← chooseNat 1 sz + let mut out := Array.mkEmpty len + for _ in [:len] do + out := out.push (← g) + return out + +/-- Generate a `List α` of length in `[0, size]`. -/ +def listOf (g : Gen α) : Gen (List α) := + Array.toList <$> arrayOf g + +/-- Generate a non-empty `List α`. -/ +def listOf1 (g : Gen α) : Gen (List α) := + Array.toList <$> arrayOf1 g + +/-- Generate an `Option α` (`none` ~20% of the time, `some` ~80%). -/ +def optionOf (g : Gen α) : Gen (Option α) := + frequency #[(1, pure none), (4, some <$> g)] (pure none) + +/-- Generate a `Prod α β`. -/ +def prodOf {α β : Type u} (ga : Gen α) (gb : Gen β) : Gen (α × β) := + return (← ga, ← gb) + +/-- Generate a `ByteArray` of length in `[0, size]`. -/ +def byteArray : Gen ByteArray := do + let len ← chooseNat 0 (← getSize) + let mut out := ByteArray.emptyWithCapacity len + for _ in [:len] do + out := out.push (← chooseUInt8) + return out + +/-- Generate a random permutation of `xs`. -/ +def permutationOf : List α → Gen (List α) + | [] => pure [] + | x :: xs => do + let ys ← permutationOf xs + let i ← chooseNat 0 ys.length + return ys.take i ++ [x] ++ ys.drop i + +/-- Try up to `maxTries` times to generate a value satisfying `p`. -/ +def suchThat? (g : Gen α) (p : α → Bool) (maxTries : Nat := 100) : Gen (Option α) := do + for _ in [:maxTries] do + let x ← g + if p x then return some x + return none + +end Gen + +end +end LSpec.Prop diff --git a/LSpec/Property/Sampleable.lean b/LSpec/Property/Sampleable.lean new file mode 100644 index 0000000..9fae13d --- /dev/null +++ b/LSpec/Property/Sampleable.lean @@ -0,0 +1,236 @@ +module +public import LSpec.Property.Gen + +/-! +# `Sampleable` and `Shrinkable` + +Pure typeclasses for generating and shrinking random values for Bool-based +property testing. No `WellFoundedRelation` proof obligation is required; +shrinking terminates via a configurable fuel bound. +-/ + +namespace LSpec.Prop +public section + +/-- Generates random values of type `α`. -/ +class Sampleable (α : Type u) where + sample : Gen α + +/-- Produces strictly simpler candidate values for counterexample minimization. -/ +class Shrinkable (α : Type u) where + shrink : α → List α := fun _ => [] + +/-- Wrapper disabling shrinking for a type. -/ +structure NoShrink (α : Type u) where + val : α + deriving BEq, Repr, Inhabited + +instance : Shrinkable (NoShrink α) where + shrink _ := [] + +instance [Sampleable α] : Sampleable (NoShrink α) where + sample := NoShrink.mk <$> Sampleable.sample + +/-! ## Built-in `Shrinkable` instances -/ + +def natShrinkAux (fuel n : Nat) : List Nat := + match fuel with + | 0 => [] + | fuel + 1 => + if n == 0 then [] + else + let half := n / 2 + if half == 0 then [0] + else half :: natShrinkAux fuel half + +instance : Shrinkable Nat where + shrink n := + if n == 0 then [] + else if n == 1 then [0] + else 0 :: (natShrinkAux 64 n ++ [n - 1]).eraseDups.filter (· < n) + +instance : Shrinkable Int where + shrink i := + if i == 0 then [] + else + let base := Shrinkable.shrink i.natAbs + if i < 0 then + -- Try positive counterpart first, then smaller negatives and positives + Int.ofNat i.natAbs :: base.map (fun n => -Int.ofNat n) + else + base.map Int.ofNat + +instance : Shrinkable Bool where + shrink + | true => [false] + | false => [] + +instance : Shrinkable UInt8 where + shrink n := (Shrinkable.shrink n.toNat).map Nat.toUInt8 + +instance : Shrinkable UInt16 where + shrink n := (Shrinkable.shrink n.toNat).map Nat.toUInt16 + +instance : Shrinkable UInt32 where + shrink n := (Shrinkable.shrink n.toNat).map Nat.toUInt32 + +instance : Shrinkable UInt64 where + shrink n := (Shrinkable.shrink n.toNat).map Nat.toUInt64 + +instance : Shrinkable USize where + shrink n := (Shrinkable.shrink n.toNat).map Nat.toUSize + +instance {n : Nat} [NeZero n] : Shrinkable (Fin n) where + shrink x := (Shrinkable.shrink x.val).map (Fin.ofNat n) + +instance : Shrinkable Char where + shrink c := + if c == 'a' then [] + else if c == ' ' then ['a'] + else ['a', '0', ' '].filter (· != c) + +instance [Shrinkable α] : Shrinkable (Option α) where + shrink + | none => [] + | some a => none :: (Shrinkable.shrink a).map some + +instance [Shrinkable α] [Shrinkable β] : Shrinkable (α × β) where + shrink + | (a, b) => + (Shrinkable.shrink a).map (·, b) ++ + (Shrinkable.shrink b).map (a, ·) + +instance [Shrinkable α] [Shrinkable β] : Shrinkable (Sum α β) where + shrink + | .inl a => (Shrinkable.shrink a).map .inl + | .inr b => (Shrinkable.shrink b).map .inr + +instance [Shrinkable ε] [Shrinkable α] : Shrinkable (Except ε α) where + shrink + | .error e => (Shrinkable.shrink e).map .error + | .ok a => (Shrinkable.shrink a).map .ok + +/-- Shrink a list by removing chunks (halves, single elements) and then shrinking elements. -/ +def shrinkList [Shrinkable α] (xs : List α) : List (List α) := + match xs with + | [] => [] + | [x] => [] :: (Shrinkable.shrink x).map (fun x' => [x']) + | _ => + let n := xs.length + let half := n / 2 + let drops := [ + [], + xs.take half, + xs.drop half + ] + let dropOne := (List.range n).map fun i => xs.take i ++ xs.drop (i + 1) + let shrinkElems := (xs.zipIdx).flatMap fun (x, i) => + (Shrinkable.shrink x).map fun x' => xs.set i x' + drops ++ dropOne ++ shrinkElems + +instance [Shrinkable α] : Shrinkable (List α) where + shrink := shrinkList + +instance [Shrinkable α] : Shrinkable (Array α) where + shrink xs := (shrinkList xs.toList).map List.toArray + +instance : Shrinkable String where + shrink s := (shrinkList s.toList).map String.ofList + +instance : Shrinkable ByteArray where + shrink bs := (shrinkList bs.data.toList).map (fun l => ByteArray.mk l.toArray) + +/-! ## Built-in `Sampleable` instances -/ + +instance : Sampleable Bool where + sample := Gen.bool + +instance : Sampleable Nat where + sample := do + let sz ← Gen.getSize + Gen.chooseNat 0 sz + +instance : Sampleable Int where + sample := do + let sz ← Gen.getSize + Gen.chooseInt (-Int.ofNat sz) (Int.ofNat sz) + +instance : Sampleable UInt8 where + sample := do + let sz ← Gen.getSize + Gen.chooseUInt8 0 (Nat.toUInt8 (min sz 255)) + +instance : Sampleable UInt16 where + sample := do + let sz ← Gen.getSize + Gen.frequency #[ + (3, Gen.chooseUInt16 0 (Nat.toUInt16 (min sz 65535))), + (1, Gen.chooseUInt16) + ] (pure 0) + +instance : Sampleable UInt32 where + sample := do + let sz ← Gen.getSize + Gen.frequency #[ + (3, Gen.chooseUInt32 0 (Nat.toUInt32 sz)), + (1, Gen.chooseUInt32) + ] (pure 0) + +instance : Sampleable UInt64 where + sample := do + let sz ← Gen.getSize + Gen.frequency #[ + (3, Gen.chooseUInt64 0 (Nat.toUInt64 sz)), + (1, Gen.chooseUInt64) + ] (pure 0) + +instance : Sampleable USize where + sample := do + let sz ← Gen.getSize + Nat.toUSize <$> Gen.chooseNat 0 sz + +instance {n : Nat} [NeZero n] : Sampleable (Fin n) where + sample := Gen.chooseFin n + +def defaultChars : Array Char := + #[' ', '0', '1', '2', '3', '9', 'a', 'b', 'c', 'z', 'A', 'B', 'Z', + ':', ',', ';', '.', '_', '-', '/', '\\', '\n'] + +instance : Sampleable Char where + sample := Gen.frequency #[ + (3, Gen.elements defaultChars 'a'), + (1, Char.ofNat <$> Gen.chooseNat 32 126) + ] (pure 'a') + +instance : Sampleable String where + sample := String.ofList <$> Gen.listOf Sampleable.sample + +instance : Sampleable ByteArray where + sample := Gen.byteArray + +instance [Sampleable α] : Sampleable (Option α) where + sample := Gen.optionOf Sampleable.sample + +instance {α β : Type u} [Sampleable α] [Sampleable β] : Sampleable (α × β) where + sample := Gen.prodOf Sampleable.sample Sampleable.sample + +instance [Sampleable α] [Sampleable β] : Sampleable (Sum α β) where + sample := Gen.frequency #[ + (1, Sum.inl <$> Sampleable.sample), + (1, Sum.inr <$> Sampleable.sample) + ] (Sum.inl <$> Sampleable.sample) + +instance [Sampleable ε] [Sampleable α] : Sampleable (Except ε α) where + sample := Gen.frequency #[ + (1, Except.error <$> Sampleable.sample), + (3, Except.ok <$> Sampleable.sample) + ] (Except.ok <$> Sampleable.sample) + +instance [Sampleable α] : Sampleable (List α) where + sample := Gen.listOf Sampleable.sample + +instance [Sampleable α] : Sampleable (Array α) where + sample := Gen.arrayOf Sampleable.sample + +end +end LSpec.Prop diff --git a/LSpec/Runner.lean b/LSpec/Runner.lean new file mode 100644 index 0000000..edd68a5 --- /dev/null +++ b/LSpec/Runner.lean @@ -0,0 +1,731 @@ +module +public import LSpec.Core +public import Std.Sync.Mutex +public import Init.Data.Queue +public import Init.System.Promise + +/-! +# Bounded-Thread Parallel Test Runner (`LSpec.Runner`) + +Executes a `TestTree` with: +- Pre-execution filtering by path pattern, exact path, exclusions, and tags + (filtered-out subtrees never execute and their `withResource` specs are never acquired). +- A pure, total `ExecPlan` compiler (`compilePlan`) shared by both sequential and + parallel execution so context propagation (`options`, `path`, `tags`, `seed`, + `aroundEach`, `ExecutionMode`) and report tree reconstruction are identical + regardless of thread count. +- Bounded concurrency via a fixed-size `WorkerPool` (`threads` dedicated workers + pulling from a mutex+condvar `Std.Queue`). At most `threads` tests execute + concurrently, letting CI jobs cap peak memory (RSS) while maximizing speed. +- Eager memory reclamation: jobs are popped from the queue before execution and + dropped immediately upon completion, keeping only lightweight `LeafReport`s. +- Respect for `ExecutionMode.sequential` (runs a subtree as one sequential unit) + and `TestTree.withResource` (acquired once before its subtree, released in + `finally` after all subtree tests finish; skipped without acquisition when + `failFast` has already tripped). +- Per-test `IO.FS.withIsolatedStreams` stdout/stderr capture, uncaught `IO.Error` + handling, wall-clock timing, and deterministic per-test seed derivation. + +All pure tree/filter/report/plan functions are total (non-`partial`) and +`@[expose]`d so `LSpecProofs` proves their correctness directly against the +executable code. +-/ + +namespace LSpec +public section + +/-- Filter criteria applied to a `TestTree` before execution or listing. -/ +structure TestFilter where + /-- Substring patterns: if non-empty, at least one must match the test path. -/ + includes : Array String := #[] + /-- Exact path matches (slash-separated, e.g. `"Math/Addition/commutes"`). -/ + exact : Array String := #[] + /-- Substring patterns to exclude. -/ + excludes : Array String := #[] + /-- If non-empty, the test must carry at least one of these tags. -/ + includeTags : Array String := #[] + /-- Exclude any test carrying any of these tags. -/ + excludeTags : Array String := #[] + deriving BEq, Repr + +/-- Substring predicate used by `TestFilter`. -/ +@[expose] def containsSubstr (haystack needle : String) : Bool := + needle.isEmpty || (haystack.splitOn needle).length > 1 + +namespace TestFilter + +@[expose] def isEmpty (f : TestFilter) : Bool := + f.includes.isEmpty && f.exact.isEmpty && f.excludes.isEmpty && + f.includeTags.isEmpty && f.excludeTags.isEmpty + +/-- Check whether a leaf at `path` with `tags` passes the filter. -/ +@[expose] def matchesTest (f : TestFilter) (path : Array String) (tags : Array String) : Bool := + let fullPath := "/".intercalate path.toList + let hasIncludeFilter := !f.includes.isEmpty || !f.exact.isEmpty + let included := + if !hasIncludeFilter then true + else + f.exact.any (· == fullPath) || + f.includes.any (containsSubstr fullPath ·) + let excluded := f.excludes.any (containsSubstr fullPath ·) + let tagIncluded := + if f.includeTags.isEmpty then true + else f.includeTags.any (tags.contains ·) + let tagExcluded := f.excludeTags.any (tags.contains ·) + included && !excluded && tagIncluded && !tagExcluded + +end TestFilter + +private theorem array_toList_sizeOf_lt [SizeOf α] (a : Array α) : + sizeOf a.toList < sizeOf a := by + cases a; simp + +mutual + +/-- Total structural worker for `filterTree`. -/ +@[expose] def filterTreeGo (filter : TestFilter) (path : Array String) (tags : Array String) : + TestTree → Option TestTree + | .leaf name leafTags exec => + let fullPath := if name.isEmpty then path else path.push name + let allTags := tags ++ leafTags + if filter.matchesTest fullPath allTags then + some (.leaf name leafTags exec) + else + none + | .group name children => + let nextPath := if name.isEmpty then path else path.push name + let kept := filterTreeChildren filter nextPath tags children.toList + if kept.isEmpty then none else some (.group name kept.toArray) + | .withMode mode child => + (filterTreeGo filter path tags child).map (.withMode mode) + | .withTags more child => + (filterTreeGo filter path (tags ++ more) child).map (.withTags more) + | .withOptions f child => + (filterTreeGo filter path tags child).map (.withOptions f) + | .aroundEach wrap child => + (filterTreeGo filter path tags child).map (.aroundEach wrap) + | .withResource desc acq child => + (filterTreeGo filter path tags child).map (.withResource desc acq) +termination_by t => sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Total child-list helper for `filterTreeGo`. -/ +@[expose] def filterTreeChildren (filter : TestFilter) (path : Array String) (tags : Array String) : + List TestTree → List TestTree + | [] => [] + | c :: cs => + match filterTreeGo filter path tags c with + | some c' => c' :: filterTreeChildren filter path tags cs + | none => filterTreeChildren filter path tags cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Prune a `TestTree` to only the leaves matching `filter`. + Returns `none` if no leaves match, ensuring filtered-out `withResource` + blocks are never acquired. -/ +@[expose] def filterTree (filter : TestFilter) (tree : TestTree) : Option TestTree := + if filter.isEmpty then some tree + else filterTreeGo filter #[] #[] tree + +/-- Metadata for a single discovered test (returned by `listTests` without running tests). -/ +structure ListedTest where + path : Array String + tags : Array String + mode : ExecutionMode + deriving BEq, Repr + +namespace ListedTest + +@[expose] def pathString (t : ListedTest) : String := + "/".intercalate t.path.toList + +end ListedTest + +mutual + +/-- Total structural worker for `listTests`, returning tests in declaration order. -/ +@[expose] def listTestsGo (path : Array String) (tags : Array String) (mode : ExecutionMode) : + TestTree → List ListedTest + | .leaf name leafTags _ => + let fullPath := if name.isEmpty then path else path.push name + [{ path := fullPath, tags := tags ++ leafTags, mode }] + | .group name children => + let nextPath := if name.isEmpty then path else path.push name + listTestsChildren nextPath tags mode children.toList + | .withMode m child => + listTestsGo path tags (ExecutionMode.combine mode m) child + | .withTags more child => + listTestsGo path (tags ++ more) mode child + | .withOptions _ child => + listTestsGo path tags mode child + | .aroundEach _ child => + listTestsGo path tags mode child + | .withResource _ _ child => + listTestsGo path tags mode child +termination_by t => sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Total child-list helper for `listTestsGo`. -/ +@[expose] def listTestsChildren (path : Array String) (tags : Array String) (mode : ExecutionMode) : + List TestTree → List ListedTest + | [] => [] + | c :: cs => listTestsGo path tags mode c ++ listTestsChildren path tags mode cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Enumerate all leaves in a `TestTree` without executing any test or acquiring resources. -/ +@[expose] def listTests (tree : TestTree) (defaultMode : ExecutionMode := .parallel) : + Array ListedTest := + (listTestsGo #[] #[] defaultMode tree).toArray + +/-- Execution report for a single leaf test. -/ +structure LeafReport where + name : String + path : Array String + tags : Array String + result : TestResult + durationMs : Nat + capturedOutput : String := "" + deriving BEq, Repr, Inhabited + +/-- Hierarchical execution report mirroring the executed `TestTree`. -/ +inductive ReportTree where + | leaf (report : LeafReport) + | group (name : String) (children : Array ReportTree) + deriving BEq, Repr, Inhabited + +/-- Aggregate statistics over a `ReportTree`. -/ +structure RunSummary where + passed : Nat := 0 + failed : Nat := 0 + skipped : Nat := 0 + totalDurationMs : Nat := 0 + seed : UInt64 := 0 + threads : Nat := 1 + deriving BEq, Repr, Inhabited + +namespace RunSummary + +@[expose] def total (s : RunSummary) : Nat := s.passed + s.failed + s.skipped + +@[expose] def allPassed (s : RunSummary) : Bool := s.failed == 0 + +end RunSummary + +namespace ReportTree + +mutual + +/-- Collect all leaf reports in declaration order as a `List`. -/ +@[expose] def leavesList : ReportTree → List LeafReport + | .leaf rep => [rep] + | .group _ children => leavesChildren children.toList +termination_by r => sizeOf r +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Helper collecting leaf reports from a list of child `ReportTree`s. -/ +@[expose] def leavesChildren : List ReportTree → List LeafReport + | [] => [] + | c :: cs => leavesList c ++ leavesChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Collect all leaf reports in declaration order. -/ +@[expose] def leaves (r : ReportTree) : Array LeafReport := + r.leavesList.toArray + +mutual + +/-- Count the total number of leaves in a `ReportTree`. -/ +@[expose] def leafCount : ReportTree → Nat + | .leaf _ => 1 + | .group _ children => leafCountChildren children.toList +termination_by r => sizeOf r +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Helper counting leaves across a list of child `ReportTree`s. -/ +@[expose] def leafCountChildren : List ReportTree → Nat + | [] => 0 + | c :: cs => leafCount c + leafCountChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +mutual + +/-- Collect all failing leaf reports in tree order as a `List`. -/ +@[expose] def failuresList : ReportTree → List LeafReport + | .leaf rep => if rep.result.isFailed then [rep] else [] + | .group _ children => failuresChildren children.toList +termination_by r => sizeOf r +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Helper collecting failing leaf reports from child `ReportTree`s. -/ +@[expose] def failuresChildren : List ReportTree → List LeafReport + | [] => [] + | c :: cs => failuresList c ++ failuresChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Collect all failing leaf reports in tree order. -/ +@[expose] def failures (r : ReportTree) : Array LeafReport := + r.failuresList.toArray + +mutual + +/-- Compute `(passed, failed, skipped)` counts over a `ReportTree`. -/ +@[expose] def summarizeGo : ReportTree → Nat × Nat × Nat + | .leaf rep => + match rep.result.outcome with + | .passed => (1, 0, 0) + | .failed _ => (0, 1, 0) + | .skipped _ => (0, 0, 1) + | .group _ children => summarizeChildren children.toList +termination_by r => sizeOf r +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Helper summing `(passed, failed, skipped)` counts over child `ReportTree`s. -/ +@[expose] def summarizeChildren : List ReportTree → Nat × Nat × Nat + | [] => (0, 0, 0) + | c :: cs => + let (p1, f1, s1) := summarizeGo c + let (p2, f2, s2) := summarizeChildren cs + (p1 + p2, f1 + f2, s1 + s2) +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Compute pass/fail/skip counts over a `ReportTree`. -/ +@[expose] def summarize (r : ReportTree) (totalDurationMs : Nat := 0) + (seed : UInt64 := 0) (threads : Nat := 1) : RunSummary := + let (p, f, s) := summarizeGo r + { passed := p, failed := f, skipped := s, totalDurationMs, seed, threads } + +end ReportTree + +/-! ## Resolved Execution Plan (`ExecPlan`) -/ + +/-- Pure execution plan compiled from a `TestTree`. + All context propagation (`options`, `path`, `tags`, `seed`, `aroundEach`, and + `ExecutionMode`) is resolved once by `compilePlan`, so sequential (`-j 1`) + and parallel (`-j N`) execution share the exact same resolved plan. -/ +inductive ExecPlan : Type where + | leaf (name : String) (path : Array String) (tags : Array String) + (opts : TestOptions) (seed : UInt64) + (exec : TestContext → IO TestResult) + | group (name : String) (children : Array ExecPlan) + | seq (child : ExecPlan) + | resource (desc : String) (path : Array String) (tags : Array String) + (acquire : IO (IO Unit)) (child : ExecPlan) + +mutual + +/-- Total compiler from `TestTree` to `ExecPlan`. -/ +@[expose] def compilePlanGo (masterSeed : UInt64) (opts : TestOptions) + (path : Array String) (tags : Array String) (mode : ExecutionMode) + (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) : + TestTree → ExecPlan + | .leaf name leafTags exec => + let fullPath := if name.isEmpty then path else path.push name + let allTags := tags ++ leafTags + let seed := deriveTestSeed masterSeed fullPath + .leaf name fullPath allTags opts seed (wrap exec) + | .group name children => + let nextPath := if name.isEmpty then path else path.push name + .group name (compilePlanChildren masterSeed opts nextPath tags mode wrap children.toList).toArray + | .withMode m child => + let nextMode := ExecutionMode.combine mode m + let sub := compilePlanGo masterSeed opts path tags nextMode wrap child + match mode, nextMode with + | .parallel, .sequential => .seq sub + | _, _ => sub + | .withTags more child => + compilePlanGo masterSeed opts path (tags ++ more) mode wrap child + | .withOptions f child => + compilePlanGo masterSeed (f opts) path tags mode wrap child + | .aroundEach w child => + compilePlanGo masterSeed opts path tags mode (fun inner => wrap (w inner)) child + | .withResource desc acq child => + .resource desc path tags acq (compilePlanGo masterSeed opts path tags mode wrap child) +termination_by t => sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Total child-list helper for `compilePlanGo`. -/ +@[expose] def compilePlanChildren (masterSeed : UInt64) (opts : TestOptions) + (path : Array String) (tags : Array String) (mode : ExecutionMode) + (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) : + List TestTree → List ExecPlan + | [] => [] + | c :: cs => + compilePlanGo masterSeed opts path tags mode wrap c :: + compilePlanChildren masterSeed opts path tags mode wrap cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Compile a `TestTree` into an `ExecPlan` with resolved paths, tags, options, + seeds, `aroundEach` wrappers, and `seq` boundaries. -/ +@[expose] def compilePlan (masterSeed : UInt64) (opts : TestOptions) + (defaultMode : ExecutionMode) (tree : TestTree) : ExecPlan := + let plan := compilePlanGo masterSeed opts #[] #[] defaultMode id tree + match defaultMode with + | .sequential => .seq plan + | .parallel => plan + +namespace ExecPlan + +mutual + +/-- Enumerate the leaves of an `ExecPlan` in declaration order (matches `listTests`). -/ +@[expose] def toListedList (mode : ExecutionMode) : ExecPlan → List ListedTest + | .leaf _ path tags _ _ _ => [{ path, tags, mode }] + | .group _ children => toListedChildren mode children.toList + | .seq child => toListedList .sequential child + | .resource _ _ _ _ child => toListedList mode child +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Child-list helper for `ExecPlan.toListedList`. -/ +@[expose] def toListedChildren (mode : ExecutionMode) : List ExecPlan → List ListedTest + | [] => [] + | c :: cs => toListedList mode c ++ toListedChildren mode cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +/-- Enumerate the leaves of an `ExecPlan` as an `Array`. -/ +@[expose] def toListed (p : ExecPlan) (defaultMode : ExecutionMode := .parallel) : + Array ListedTest := + (p.toListedList defaultMode).toArray + +mutual + +/-- Build a skipped `ReportTree` for every leaf in an `ExecPlan` without executing + any test or acquiring any resource (used when `failFast` has already tripped). -/ +@[expose] def skipAll (reason : String) : ExecPlan → ReportTree + | .leaf name path tags _ _ _ => + .leaf { + name, path, tags + result := .skip (some reason) + durationMs := 0 + } + | .group name children => + .group name (skipAllChildren reason children.toList).toArray + | .seq child => skipAll reason child + | .resource _ _ _ _ child => skipAll reason child +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +/-- Child-list helper for `ExecPlan.skipAll`. -/ +@[expose] def skipAllChildren (reason : String) : List ExecPlan → List ReportTree + | [] => [] + | c :: cs => skipAll reason c :: skipAllChildren reason cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +end + +end ExecPlan + +/-- Compute the number of worker threads to start for `threads` and `totalLeaves`. + Always in `[1, max 1 threads]` and capped at `max 1 totalLeaves`. -/ +@[expose] def computeWorkerCount (threads totalLeaves : Nat) : Nat := + min (max 1 threads) (max 1 totalLeaves) + +/-- Runner configuration. -/ +structure RunConfig where + /-- Maximum number of tests running concurrently (`1` = strictly sequential on main thread). -/ + threads : Nat := 1 + /-- Default execution mode when no `parallel`/`sequential` modifier is present. -/ + defaultMode : ExecutionMode := .parallel + /-- Optional master seed for property tests. If `none`, generated from OS randomness. -/ + seed : Option UInt64 := none + /-- Filter applied before execution. -/ + filter : TestFilter := {} + /-- Base `TestOptions` merged into every test's `TestContext`. -/ + options : TestOptions := {} + /-- If `true`, skip remaining queued tests after the first failure. -/ + failFast : Bool := false + /-- If `true`, capture per-test stdout/stderr via `IO.FS.withIsolatedStreams`. -/ + isolateStreams : Bool := true + +/-- Bounded-concurrency worker pool backed by `Std.Mutex` + `Std.Condvar`. -/ +private structure PoolState where + queue : Std.Queue (IO Unit) := ∅ + closed : Bool := false + deriving Nonempty + +private structure WorkerPool where + state : Std.Mutex PoolState + condvar : Std.Condvar + workers : Array (Task (Except IO.Error Unit)) + +private def WorkerPool.popJob (pool : WorkerPool) : BaseIO (Option (IO Unit)) := + pool.state.atomicallyOnce pool.condvar + (do let st ← get; return !st.queue.isEmpty || st.closed) + (do + let st ← get + match st.queue.dequeue? with + | some (job, rest) => + set { st with queue := rest } + return some job + | none => return none) + +private partial def WorkerPool.workerLoop (state : Std.Mutex PoolState) (condvar : Std.Condvar) : + IO Unit := do + let pool : WorkerPool := { state, condvar, workers := #[] } + while true do + match ← pool.popJob with + | none => break + | some job => job + +private def WorkerPool.start (numWorkers : Nat) : IO WorkerPool := do + let state ← Std.Mutex.new ({} : PoolState) + let condvar ← Std.Condvar.new + let mut workers := Array.mkEmpty numWorkers + for _ in [:numWorkers] do + let t ← IO.asTask (WorkerPool.workerLoop state condvar) .dedicated + workers := workers.push t + return { state, condvar, workers } + +private def WorkerPool.submit [Nonempty α] (pool : WorkerPool) (action : IO α) : + BaseIO (IO.Promise (Except IO.Error α)) := do + let promise ← IO.Promise.new + let job : IO Unit := do + let res ← try + pure (.ok (← action)) + catch e => + pure (.error e) + promise.resolve res + pool.state.atomically do + let st ← get + set { st with queue := st.queue.enqueue job } + pool.condvar.notifyOne + return promise + +private def WorkerPool.shutdown (pool : WorkerPool) : IO Unit := do + pool.state.atomically do + let st ← get + set { st with closed := true } + pool.condvar.notifyAll + for w in pool.workers do + let _ ← IO.wait w + +/-- Await a `Promise (Except IO.Error α)` safely. -/ +private def awaitPromise (p : IO.Promise (Except IO.Error α)) : IO α := do + match ← IO.wait p.result? with + | none => throw (IO.userError "worker dropped task promise without resolving") + | some (.error e) => throw e + | some (.ok a) => return a + +/-- Generate a 64-bit random seed from OS entropy. -/ +def generateRandomSeed : IO UInt64 := do + let bytes ← IO.getRandomBytes 8 + if bytes.size ≥ 8 then + return bytes.toUInt64LE! + else + return (← IO.monoNanosNow).toUInt64 + +/-- Environment threaded through plan execution. -/ +private structure ExecEnv where + pool? : Option WorkerPool + failFast : Bool + isolateStreams : Bool + failedFlag : IO.Ref Bool + +/-- Execute a single resolved leaf test on the current thread (with stream isolation, + exception handling, timing, and fail-fast short-circuiting). -/ +private def execPlanLeaf (env : ExecEnv) (name : String) (path : Array String) + (tags : Array String) (opts : TestOptions) (seed : UInt64) + (exec : TestContext → IO TestResult) : IO LeafReport := do + if env.failFast && (← env.failedFlag.get) then + return { + name, path, tags + result := .skip (some "skipped (fail-fast)") + durationMs := 0 + } + let ctx : TestContext := { options := opts, path, seed } + let start ← IO.monoMsNow + let runOne : IO TestResult := do + try + exec ctx + catch e => + pure (.fail "uncaught IO exception" s!"IO error: {e}" (.exception e.toString)) + let (captured, res) ← + if env.isolateStreams then + IO.FS.withIsolatedStreams runOne + else + pure ("", ← runOne) + let stop ← IO.monoMsNow + if res.isFailed then + env.failedFlag.set true + return { + name, path, tags + result := res + durationMs := stop - start + capturedOutput := captured + } + +/-- Execute an `ExecPlan` strictly sequentially on the current thread. -/ +private partial def execPlanSeq (env : ExecEnv) : ExecPlan → IO ReportTree + | .leaf name path tags opts seed exec => do + let rep ← execPlanLeaf env name path tags opts seed exec + return .leaf rep + | .group name children => do + let mut reports := Array.mkEmpty children.size + for c in children do + reports := reports.push (← execPlanSeq env c) + return .group name reports + | .seq child => + execPlanSeq env child + | .resource desc path tags acq child => do + if env.failFast && (← env.failedFlag.get) then + return child.skipAll "skipped (fail-fast)" + let release? : Except IO.Error (IO Unit) ← try + pure (Except.ok (← acq)) + catch e => + pure (Except.error e) + match release? with + | .error e => + env.failedFlag.set true + return .leaf { + name := s!"resource: {desc}" + path := path.push desc + tags := tags + result := .fail s!"failed to acquire resource '{desc}'" + s!"IO error: {e}" (.exception e.toString) + durationMs := 0 + } + | .ok release => + try + execPlanSeq env child + finally + try release catch _ => pure () + +/-- A handle representing in-flight asynchronous execution of an `ExecPlan`. -/ +private inductive PendingReport where + | ready (r : ReportTree) + | promise (p : IO.Promise (Except IO.Error ReportTree)) + | task (t : Task (Except IO.Error ReportTree)) + | group (name : String) (children : Array PendingReport) + +private partial def PendingReport.await : PendingReport → IO ReportTree + | .ready r => pure r + | .promise p => awaitPromise p + | .task t => do IO.ofExcept (← IO.wait t) + | .group name children => do + let mut out := Array.mkEmpty children.size + for c in children do + out := out.push (← c.await) + return .group name out + +/-- Dispatch a compiled `ExecPlan` using the shared `WorkerPool` (when `env.pool?` is `some`). + - Parallel leaves are submitted individually to the pool. + - `.seq` subtrees are submitted as a single bounded worker job. + - `.resource` nodes acquire once (skipping if `failFast` already tripped), + dispatch their child plan across the pool, await completion, and release + in `finally`. -/ +private partial def dispatchPlan (env : ExecEnv) (plan : ExecPlan) : IO PendingReport := do + match env.pool? with + | none => + return .ready (← execPlanSeq env plan) + | some pool => + match plan with + | .leaf name path tags opts seed exec => + let p ← pool.submit do + let rep ← execPlanLeaf env name path tags opts seed exec + return ReportTree.leaf rep + return .promise p + | .group name children => + let mut pending := Array.mkEmpty children.size + for c in children do + pending := pending.push (← dispatchPlan env c) + return .group name pending + | .seq child => + let p ← pool.submit (execPlanSeq env child) + return .promise p + | .resource desc path tags acq child => + -- Lightweight coordinator task for the resource lifecycle; all actual + -- leaf executions inside `child` still flow through the bounded `pool`, + -- preventing worker-pool starvation on nested `withResource` scopes. + let t ← IO.asTask (do + if env.failFast && (← env.failedFlag.get) then + return child.skipAll "skipped (fail-fast)" + let release? : Except IO.Error (IO Unit) ← try + pure (Except.ok (← acq)) + catch e => + pure (Except.error e) + match release? with + | .error e => + env.failedFlag.set true + return ReportTree.leaf { + name := s!"resource: {desc}" + path := path.push desc + tags := tags + result := .fail s!"failed to acquire resource '{desc}'" + s!"IO error: {e}" (.exception e.toString) + durationMs := 0 + } + | .ok release => + try + let sub ← dispatchPlan env child + sub.await + finally + try release catch _ => pure ()) + return .task t + +/-- Run a `TestTree` according to `cfg`, returning `(reportTree, summary)`. -/ +def runTree (tree : TestTree) (cfg : RunConfig := {}) : IO (ReportTree × RunSummary) := do + let seed ← match cfg.seed with + | some s => pure s + | none => generateRandomSeed + let threads := max 1 cfg.threads + let start ← IO.monoMsNow + match filterTree cfg.filter tree with + | none => + let stop ← IO.monoMsNow + return (.group "" #[], { + passed := 0, failed := 0, skipped := 0, + totalDurationMs := stop - start, seed, threads + }) + | some filtered => + let plan := compilePlan seed cfg.options cfg.defaultMode filtered + let failedFlag ← IO.mkRef false + let pool? ← + if threads > 1 then + let totalLeaves := (listTests filtered cfg.defaultMode).size + let numWorkers := computeWorkerCount threads totalLeaves + if numWorkers > 1 then some <$> WorkerPool.start numWorkers + else pure none + else + pure none + let env : ExecEnv := { + pool? + failFast := cfg.failFast + isolateStreams := cfg.isolateStreams + failedFlag + } + let report ← try + let pending ← dispatchPlan env plan + pending.await + finally + if let some pool := pool? then + pool.shutdown + let stop ← IO.monoMsNow + let summary := report.summarize (stop - start) seed threads + return (report, summary) + +end +end LSpec diff --git a/LSpec/SlimCheck.lean b/LSpec/SlimCheck.lean deleted file mode 100644 index 6761985..0000000 --- a/LSpec/SlimCheck.lean +++ /dev/null @@ -1,4 +0,0 @@ -module -public import LSpec.SlimCheck.Gen -public import LSpec.SlimCheck.Checkable -public import LSpec.SlimCheck.Sampleable diff --git a/LSpec/SlimCheck/Checkable.lean b/LSpec/SlimCheck/Checkable.lean deleted file mode 100644 index e753820..0000000 --- a/LSpec/SlimCheck/Checkable.lean +++ /dev/null @@ -1,514 +0,0 @@ -/- -Copyright (c) 2022 Henrik Böving. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Henrik Böving, Simon Hudon --/ - -module -public import LSpec.SlimCheck.Sampleable -public import Lean.Elab.Tactic.Basic -meta import Lean.Elab.Tactic.Basic - -/-! -# `Checkable` Class -Checkable propositions have a procedure that can generate counter-examples -together with a proof that they invalidate the proposition. -This is a port of the Haskell QuickCheck library. -## Creating Customized Instances -The type classes `Checkable`, `SampleableExt` and `Shrinkable` are the -means by which `SlimCheck` creates samples and tests them. For instance, -the proposition `∀ i j : ℕ, i ≤ j` has a `Checkable` instance because `ℕ` -is sampleable and `i ≤ j` is decidable. Once `SlimCheck` finds the `Checkable` -instance, it can start using the instance to repeatedly creating samples -and checking whether they satisfy the property. Once it has found a -counter-example it will then use a `Shrinkable` instance to reduce the -example. This allows the user to create new instances and apply -`SlimCheck` to new situations. -### What do I do if I'm testing a property about my newly defined type? -Let us consider a type made for a new formalization: -```lean -structure MyType where - x : ℕ - y : ℕ - h : x ≤ y - deriving Repr -``` -How do we test a property about `MyType`? For instance, let us consider -`Checkable.check $ ∀ a b : MyType, a.y ≤ b.x → a.x ≤ b.y`. Writing this -property as is will give us an error because we do not have an instance -of `Shrinkable MyType` and `SampleableExt MyType`. We can define one as follows: -```lean -instance : Shrinkable MyType where - shrink := fun ⟨x,y,h⟩ => - let proxy := Shrinkable.shrink (x, y - x) - proxy.map (fun ⟨⟨fst, snd⟩, ha⟩ => ⟨⟨fst, fst + snd, sorry⟩, sorry⟩) -instance : SampleableExt MyType := - SampleableExt.mkSelfContained do - let x ← SampleableExt.interpSample Nat - let xyDiff ← SampleableExt.interpSample Nat - pure $ ⟨x, x + xyDiff, sorry⟩ -``` -Again, we take advantage of the fact that other types have useful -`Shrinkable` implementations, in this case `Prod`. Note that the second -proof is heavily based on `WellFoundedRelation` since its used for termination so -the first step you want to take is almost always to `simp_wf` in order to -get through the `WellFoundedRelation`. -## Main definitions - * `Checkable` class - * `Checkable.check`: a way to test a proposition using random examples -## Tags -random testing -## References - * https://hackage.haskell.org/package/QuickCheck --/ - -namespace SlimCheck -public section -/-- Result of trying to disprove `p` -The constructors are: - * `success : (PSum Unit p) → TestResult p` - succeed when we find another example satisfying `p` - In `success h`, `h` is an optional proof of the proposition. - Without the proof, all we know is that we found one example - where `p` holds. With a proof, the one test was sufficient to - prove that `p` holds and we do not need to keep finding examples. - * `gaveUp : ℕ → TestResult p` - give up when a well-formed example cannot be generated. - `gaveUp n` tells us that `n` invalid examples were tried. - Above 100, we give up on the proposition and report that we - did not find a way to properly test it. - * `failure : ¬ p → (List String) → ℕ → TestResult p` - a counter-example to `p`; the strings specify values for the relevant variables. - `failure h vs n` also carries a proof that `p` does not hold. This way, we can - guarantee that there will be no false positive. The last component, `n`, - is the number of times that the counter-example was shrunk. --/ -inductive TestResult (p : Prop) where - | success : PSum Unit p → TestResult p - | gaveUp : Nat → TestResult p - | failure : ¬ p → List String → Nat → TestResult p - deriving Inhabited - -/-- Configuration for testing a property. -/ -structure Configuration where - numInst : Nat := 100 - maxSize : Nat := 100 - numRetries : Nat := 10 - traceDiscarded : Bool := false - traceSuccesses : Bool := false - traceShrink : Bool := false - traceShrinkCandidates : Bool := false - randomSeed : Option Nat := none - quiet : Bool := false - -namespace Configuration - -/-- A configuration with all the trace options enabled, useful for debugging. -/ -def verbose : Configuration where - traceDiscarded := true - traceSuccesses := true - traceShrink := true - traceShrinkCandidates := true - -end Configuration - -/-- -`PrintableProp p` allows one to print a proposition so that -`SlimCheck` can indicate how values relate to each other. -It's basically a poor man's delaborator. --/ -class PrintableProp (p : Prop) where - printProp : String - -export PrintableProp (printProp) - -instance (priority := low) : PrintableProp p where - printProp := "⋯" - -/-- `Checkable p` uses random examples to try to disprove `p`. -/ -class Checkable (p : Prop) where - run (cfg : Configuration) (minimize : Bool) : Gen (TestResult p) - -@[expose] -def NamedBinder (_n : String) (p : Prop) : Prop := p - -namespace TestResult - -def toString : TestResult p → String -| success (PSum.inl _) => "success (no proof)" -| success (PSum.inr _) => "success (proof)" -| gaveUp n => s!"gave {n} times" -| failure _ counters _ => s!"failed {counters}" - -instance : ToString (TestResult p) := ⟨toString⟩ - -/-- Applicative combinator proof carrying test results. -/ -def combine {p q : Prop} : PSum Unit (p → q) → PSum Unit p → PSum Unit q -| PSum.inr f, PSum.inr proof => PSum.inr $ f proof -| _, _ => PSum.inl () - -/-- Combine the test result for properties `p` and `q` to create a test for their conjunction. -/ -def and : TestResult p → TestResult q → TestResult (p ∧ q) -| failure h xs n, _ => failure (fun h2 => h h2.left) xs n -| _, failure h xs n => failure (fun h2 => h h2.right) xs n -| success h1, success h2 => success $ combine (combine (PSum.inr And.intro) h1) h2 -| gaveUp n, gaveUp m => gaveUp $ n + m -| gaveUp n, _ => gaveUp n -| _, gaveUp n => gaveUp n - -/-- Combine the test result for properties `p` and `q` to create a test for their disjunction. -/ -def or : TestResult p → TestResult q → TestResult (p ∨ q) -| failure h1 xs n, failure h2 ys m => - let h3 := fun h => - match h with - | Or.inl h3 => h1 h3 - | Or.inr h3 => h2 h3 - failure h3 (xs ++ ys) (n + m) -| success h, _ => success $ combine (PSum.inr Or.inl) h -| _, success h => success $ combine (PSum.inr Or.inr) h -| gaveUp n, gaveUp m => gaveUp $ n + m -| gaveUp n, _ => gaveUp n -| _, gaveUp n => gaveUp n - -/-- If `q → p`, then `¬ p → ¬ q` which means that testing `p` can allow us -to find counter-examples to `q`. -/ -def imp (h : q → p) (r : TestResult p) - (p : PSum Unit (p → q) := PSum.inl ()) : TestResult q := - match r with - | failure h2 xs n => failure (mt h h2) xs n - | success h2 => success $ combine p h2 - | gaveUp n => gaveUp n - -/-- Test `q` by testing `p` and proving the equivalence between the two. -/ -def iff (h : q ↔ p) (r : TestResult p) : TestResult q := - imp h.mp r (PSum.inr h.mpr) - -/-- When we assign a value to a universally quantified variable, -we record that value using this function so that our counter-examples -can be informative. -/ -def addInfo (x : String) (h : q → p) (r : TestResult p) - (p : PSum Unit (p → q) := PSum.inl ()) : TestResult q := - if let failure h2 xs n := r then - failure (mt h h2) (x :: xs) n - else - imp h r p - -/-- Add some formatting to the information recorded by `addInfo`. -/ -def addVarInfo [Repr γ] (var : String) (x : γ) (h : q → p) (r : TestResult p) - (p : PSum Unit (p → q) := PSum.inl ()) : TestResult q := - addInfo s!"{var} := {repr x}" h r p - -def isFailure : TestResult p → Bool - | failure .. => true - | _ => false - -end TestResult - -namespace Checkable - -open TestResult - -def runProp (p : Prop) [Checkable p] : Configuration → Bool → Gen (TestResult p) := Checkable.run - -/-- A `dbgTrace` with special formatting -/ -def slimTrace [Pure m] (s : String) : m Unit := - dbgTrace s!"[SlimCheck: {s}]" fun _ => pure () - -instance andCheckable [Checkable p] [Checkable q] : Checkable (p ∧ q) where - run := fun cfg min => do - let xp ← runProp p cfg min - let xq ← runProp q cfg min - pure $ and xp xq - -instance orCheckable [Checkable p] [Checkable q] : Checkable (p ∨ q) where - run := fun cfg min => do - let xp ← runProp p cfg min - -- As a little performance optimization we can just not run the second - -- test if the first succeeds - match xp with - | success (PSum.inl h) => pure $ success (PSum.inl h) - | success (PSum.inr h) => pure $ success (PSum.inr $ Or.inl h) - | _ => - let xq ← runProp q cfg min - pure $ or xp xq - -instance iffCheckable [Checkable ((p ∧ q) ∨ (¬ p ∧ ¬ q))] : Checkable (p ↔ q) where - run := fun cfg min => do - let h ← runProp ((p ∧ q) ∨ (¬ p ∧ ¬ q)) cfg min - have key {a b} : (a ↔ b) ↔ (a ∧ b) ∨ (¬ a ∧ ¬ b) := by - constructor - · intro h; rw [h] - by_cases h : b - · exact .inl $ .intro h h - · exact .inr $ .intro h h - · intro h - match h with - | .inl h => exact Iff.intro (fun _ => h.2) (fun _ => h.1) - | .inr h => exact Iff.intro (fun a => False.elim $ h.1 a) (fun b => False.elim $ h.2 b) - pure $ iff key h - -instance decGuardCheckable [PrintableProp p] [Decidable p] {β : p → Prop} [∀ h, Checkable (β h)] : Checkable (NamedBinder var $ ∀ h, β h) where - run := fun cfg min => do - if h : p then - let res := (runProp (β h) cfg min) - let s := printProp p - (fun r => addInfo s!"guard: {s}" (· $ h) r (PSum.inr $ fun q _ => q)) <$> res - else if cfg.traceDiscarded || cfg.traceSuccesses then - let res := (fun _ => pure $ gaveUp 1) - let s := printProp p - slimTrace s!"discard: Guard {s} does not hold"; res - else - pure $ gaveUp 1 - -instance forallTypesCheckable {f : Type → Prop} [Checkable (f Int)] : Checkable (NamedBinder var $ ∀ x, f x) where - run := fun cfg min => do - let r ← runProp (f Int) cfg min - pure $ addVarInfo var "ℤ" (· $ Int) r - -/-- Format the counter-examples found in a test failure. -/ -def formatFailure (s : String) (xs : List String) (n : Nat) : String := - let counter := "\n".intercalate xs - let parts := [ - "\n===================", - s, - counter, - s!"({n} shrinks)", - "-------------------" - ] - "\n".intercalate parts - -/-- Increase the number of shrinking steps in a test result. -/ -def addShrinks (n : Nat) : TestResult p → TestResult p -| TestResult.failure p xs m => TestResult.failure p xs (m + n) -| p => p - -/-- Shrink a counter-example `x` by using `Shrinkable.shrink x`, picking the first -candidate that falsifies a property and recursively shrinking that one. -The process is guaranteed to terminate because `shrink x` produces -a proof that all the values it produces are smaller (according to `SizeOf`) -than `x`. -/ -def minimizeAux [SampleableExt α] {β : α → Prop} [∀ x, Checkable (β x)] - (cfg : Configuration) (var : String) (x : SampleableExt.proxy α) (n : Nat) : - OptionT Gen (Σ x, TestResult (β (SampleableExt.interp x))) := do - let candidates := SampleableExt.shrink.shrink x - if cfg.traceShrinkCandidates then - slimTrace s!"Candidates for {var} := {repr x}:\n {repr candidates}" - for candidate in candidates do - if cfg.traceShrinkCandidates then - slimTrace s!"Trying {var} := {repr candidate}" - let res ← OptionT.lift $ Checkable.runProp (β (SampleableExt.interp candidate)) cfg true - if res.isFailure then - if cfg.traceShrink then - slimTrace s!"{var} shrunk to {repr candidate} from {repr x}" - let currentStep := OptionT.lift $ pure $ Sigma.mk candidate (addShrinks (n + 1) res) - -- todo: `nextStep` is unused. Why is it here? - -- let nextStep := @minimizeAux α _ β _ cfg var candidate (n + 1) - return ← (currentStep) - if cfg.traceShrink then - slimTrace s!"No shrinking possible for {var} := {repr x}" - failure - -/-- Once a property fails to hold on an example, look for smaller counter-examples -to show the user. -/ -def minimize [SampleableExt α] {β : α → Prop} [∀ x, Checkable (β x)] (cfg : Configuration) (var : String) - (x : SampleableExt.proxy α) (r : TestResult (β $ SampleableExt.interp x)) : Gen (Σ x, TestResult (β $ SampleableExt.interp x)) := do - if cfg.traceShrink then - slimTrace "Shrink" - slimTrace s!"Attempting to shrink {var} := {repr x}" - let res ← OptionT.run $ minimizeAux cfg var x 0 - pure $ res.getD ⟨x, r⟩ - -/-- Test a universal property by creating a sample of the right type and instantiating the -bound variable with it. -/ -instance varCheckable [SampleableExt α] {β : α → Prop} [∀ x, Checkable (β x)] : Checkable (NamedBinder var $ ∀ x : α, β x) where - run := fun cfg min => do - let x ← SampleableExt.sample - if cfg.traceSuccesses || cfg.traceDiscarded then - slimTrace s!"{var} := {repr x}" - let r ← Checkable.runProp (β $ SampleableExt.interp x) cfg false - let ⟨finalX, finalR⟩ ← - if isFailure r then - if cfg.traceSuccesses then - slimTrace s!"{var} := {repr x} is a failure" - if min then - minimize cfg var x r - else - pure $ ⟨x, r⟩ - else - pure $ ⟨x, r⟩ - pure $ addVarInfo var finalX (· $ SampleableExt.interp finalX) finalR - -/-- Test a universal property about propositions -/ -instance propVarCheckable {β : Prop → Prop} [∀ b : Bool, Checkable (β b)] : - Checkable (NamedBinder var $ ∀ p : Prop, β p) -where - run := fun cfg min => - imp (fun h (b : Bool) => h b) <$> Checkable.runProp (NamedBinder var $ ∀ b : Bool, β b) cfg min - -instance (priority := high) unusedVarCheckable [Nonempty α] [Checkable β] : - Checkable (NamedBinder var $ ∀ _x : α, β) -where - run := fun cfg min => do - if cfg.traceDiscarded || cfg.traceSuccesses then - slimTrace s!"{var} is unused" - let r ← Checkable.runProp β cfg min - let finalR := addInfo s!"{var} is irrelevant (unused)" id r - pure $ imp (· $ Classical.ofNonempty) finalR (PSum.inr $ fun x _ => x) - -instance (priority := low) decidableCheckable {p : Prop} [PrintableProp p] [Decidable p] : Checkable p where - run := fun _ _ => - if h : p then - pure $ success (PSum.inr h) - else - let s := printProp p - pure $ failure h [s!"issue: {s} does not hold"] 0 - -end Checkable - -section PrintableProp - -instance Eq.printableProp [Repr α] {x y : α} : PrintableProp (x = y) where - printProp := s!"{repr x} = {repr y}" - -instance Ne.printableProp [Repr α] {x y : α} : PrintableProp (x ≠ y) where - printProp := s!"{repr x} ≠ {repr y}" - -instance LE.printableProp [Repr α] [LE α] {x y : α} : PrintableProp (x ≤ y) where - printProp := s!"{repr x} ≤ {repr y}" - -instance LT.printableProp [Repr α] [LT α] {x y : α} : PrintableProp (x < y) where - printProp := s!"{repr x} < {repr y}" - -instance And.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x ∧ y) where - printProp := s!"{printProp x} ∧ {printProp y}" - -instance Or.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x ∨ y) where - printProp := s!"{printProp x} ∨ {printProp y}" - -instance Iff.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x ↔ y) where - printProp := s!"{printProp x} ↔ {printProp y}" - -instance Imp.printableProp [PrintableProp x] [PrintableProp y] : PrintableProp (x → y) where - printProp := s!"{printProp x} → {printProp y}" - -instance Not.printableProp [PrintableProp x] : PrintableProp (¬x) where - printProp := s!"¬{printProp x}" - -instance True.printableProp : PrintableProp True where - printProp := "True" - -instance False.printableProp : PrintableProp False where - printProp := "False" - -instance Bool.printableProp {b : Bool} : PrintableProp b where - printProp := if b then "true" else "false" - -end PrintableProp - -section IO -open TestResult - -/-- Execute `cmd` and repeat every time the result is `gave_up` (at most `n` times). -/ -def retry (cmd : Rand (TestResult p)) : Nat → Rand (TestResult p) - | 0 => pure $ TestResult.gaveUp 1 - | n + 1 => do match ← cmd with - | success hp => pure $ success hp - | TestResult.failure h xs n => pure $ failure h xs n - | gaveUp _ => retry cmd n - -/-- Count the number of times the test procedure gave up. -/ -def giveUp (x : Nat) : TestResult p → TestResult p - | success (PSum.inl ()) => gaveUp x - | success (PSum.inr p) => success $ (PSum.inr p) - | gaveUp n => gaveUp $ n + x - | TestResult.failure h xs n => failure h xs n - -/-- Try `n` times to find a counter-example for `p`. -Returns a tuple of (result, numSuccessfulSamples). -/ -def Checkable.runSuiteAux (p : Prop) [Checkable p] (cfg : Configuration) (r : TestResult p) - (successCount : Nat) : Nat → Rand (TestResult p × Nat) - | 0 => pure (r, successCount) - | n + 1 => do - let size := (cfg.numInst - n - 1) * cfg.maxSize / cfg.numInst - if cfg.traceSuccesses then - slimTrace s!"New sample" - slimTrace s!"Retrying up to {cfg.numRetries} times until guards hold" - let x ← retry (ReaderT.run (Checkable.runProp p cfg true) ⟨size⟩) cfg.numRetries - match x with - | (success (PSum.inl ())) => runSuiteAux p cfg r (successCount + 1) n - | (gaveUp g) => runSuiteAux p cfg (giveUp g r) successCount n - | _ => pure (x, successCount) - -/-- Try to find a counter-example of `p`. -Returns a tuple of (result, numSuccessfulSamples). -/ -def Checkable.runSuite (p : Prop) [Checkable p] (cfg : Configuration := {}) - : Rand (TestResult p × Nat) := - Checkable.runSuiteAux p cfg (success $ PSum.inl ()) 0 cfg.numInst - -/-- Run a test suite for `p` in `BaseIO` using the global RNG in `stdGenRef`. -Returns a tuple of (result, numSuccessfulSamples). -/ -def Checkable.checkIO (p : Prop) [Checkable p] (cfg : Configuration := {}) - : BaseIO (TestResult p × Nat) := - match cfg.randomSeed with - | none => IO.runRand (Checkable.runSuite p cfg) - | some seed => IO.runRandWith seed (Checkable.runSuite p cfg) - -end IO - -namespace Decorations - -open Lean - -/-- Traverse the syntax of a proposition to find universal quantifiers -quantifiers and add `NamedBinder` annotations next to them. -/ -meta partial def addDecorations (e : Expr) : Expr := - e.replace fun expr => match expr with - | Expr.forallE name type body data => - let n := name.toString - let newType := addDecorations type - let newBody := addDecorations body - let rest := Expr.forallE name newType newBody data - some $ mkApp2 (mkConst `SlimCheck.NamedBinder) (mkStrLit n) rest - | _ => none - -/-- `DecorationsOf p` is used as a hint to `mk_decorations` to specify -that the goal should be satisfied with a proposition equivalent to `p` -with added annotations. -/ -abbrev DecorationsOf (_p : Prop) := Prop - -open Elab.Tactic in -/-- In a goal of the shape `⊢ DecorationsOf p`, `mk_decoration` examines -the syntax of `p` and adds `NamedBinder` around universal quantifications -to improve error messages. This tool can be used in the declaration of a -function as follows: -```lean -def foo (p : Prop) (p' : Decorations.DecorationsOf p := by mk_decorations) [Checkable p'] : ... -``` -`p` is the parameter given by the user, `p'` is a definitionally equivalent -proposition where the quantifiers are annotated with `NamedBinder`. --/ -scoped elab "mk_decorations" : tactic => do - let goalType ← (← getMainGoal).getType - if let Expr.app (.const ``Decorations.DecorationsOf ..) body := goalType then - closeMainGoal `SlimCheck.mk_decorations (addDecorations body) - -end Decorations - -open Decorations in -/-- Run a test suite for `p` and throw an exception if `p` does not not hold.-/ -def Checkable.check (p : Prop) (cfg : Configuration := {}) - (p' : DecorationsOf p := by mk_decorations) [Checkable p'] : IO Unit := do - let (result, numSamples) ← Checkable.checkIO p' cfg - match result with - | TestResult.success _ => - if !cfg.quiet then IO.println s!"Success ({numSamples} samples)" else pure () - | TestResult.gaveUp n => if !cfg.quiet then IO.println s!"Gave up {n} times" - | TestResult.failure _ xs n => throw (IO.userError $ formatFailure "Found problems!" xs n) - --- #eval Checkable.check (∀ (x y z a : Nat) (h1 : 3 < x) (h2 : 3 < y), x - y = y - x) Configuration.verbose --- #eval Checkable.check (∀ x : Nat, ∀ y : Nat, x + y = y + x) Configuration.verbose --- #eval Checkable.check (∀ (x : (Nat × Nat)), x.fst - x.snd - 10 = x.snd - x.fst - 10) Configuration.verbose --- #eval Checkable.check (∀ (x : Nat) (h : 10 < x), 5 < x) Configuration.verbose - -end -end SlimCheck diff --git a/LSpec/SlimCheck/Control/DefaultRange.lean b/LSpec/SlimCheck/Control/DefaultRange.lean deleted file mode 100644 index 6fa6bf4..0000000 --- a/LSpec/SlimCheck/Control/DefaultRange.lean +++ /dev/null @@ -1,64 +0,0 @@ -/- -Copyright (c) 2022 Hanting Zhang. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Hanting Zhang --/ -module - -/-! -# Bounded and DefaultRange classes - -This module encapsulates the notion of a range of elements. - -## Main definitions - * `Bounded` class for objects which are naturally bounded - by two `lo` and `hi` elements; - * `DefaultRange` class for objects which are unbounded, - but nevertheless need a convenient range of values which to operate within. - -Note that we go against Lean's principles by NOT providing any -mathematical guarantees for the `Bounded` and `DefaultRange` classes. -It is perfectly possible to define `Bounded Nat` with `lo := 37` and `hi := 37`; -we leave these to the judgement of the programmer. *gasp of horror* -This more follows the design of `Bounded` in Haskell, and allows us to -forgo carrying proofs around when we start defining `Random` instances. - -Lean developers, please forgive us. - -## References - * Haskell --/ - -namespace SlimCheck -public section - -class Bounded (α : Type u) where - lo : α - hi : α - -class DefaultRange (α : Type u) where - lo : α - hi : α - -instance [Bounded α] : DefaultRange α where - lo := Bounded.lo - hi := Bounded.hi - -instance : Bounded Bool where - lo := false - hi := true - -instance : DefaultRange Nat where - lo := 0 - hi := USize.size - 1 - -instance {n : Nat} : Bounded (Fin n.succ) where - lo := ⟨0, n.succ_pos⟩ - hi := ⟨n, n.lt_succ_self⟩ - -instance : DefaultRange Int where - lo := - Int.ofNat (USize.size / 2) - hi := Int.ofNat (USize.size / 2 - 1) - -end -end SlimCheck diff --git a/LSpec/SlimCheck/Control/Random.lean b/LSpec/SlimCheck/Control/Random.lean deleted file mode 100644 index cfa5fa7..0000000 --- a/LSpec/SlimCheck/Control/Random.lean +++ /dev/null @@ -1,139 +0,0 @@ -/- -Copyright (c) 2022 Henrik Böving. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Henrik Böving --/ -module -public import LSpec.SlimCheck.Control.DefaultRange - -/-! -# Rand Monad and Random Class - -This module provides tools for formulating computations guided by randomness and for -defining objects that can be created randomly. - -## Main definitions - * `Rand` and `RandT` monad for computations guided by randomness; - * `Random` class for objects that can be generated randomly; - * `random` to generate one object; - * `BoundedRandom` class for objects that can be generated randomly inside a range; - * `randomR` to generate one object inside a range; - * `IO.runRand` to run a randomized computation inside the `IO` monad; - -## Notes - * Often we need to do some panic-possible things like use `List.get!`. - In these cases, panic often needs an instance of `Inhabited (Gen α)`; - the default generator will always be `StdGen` with `seed := 0`. - -## References - * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom --/ - -namespace SlimCheck -public section - -/-- A monad to generate random objects using the generic generator type `g` -/ -abbrev RandT (g : Type) := StateM (ULift g) - -instance inhabitedRandT [Inhabited g] [Inhabited α] : Inhabited (RandT g α) where - default := fun _ => pure (default, .up default) - -/-- A monad to generate random objects using the generator type `Rng` -/ -abbrev Rand (α : Type u) := RandT StdGen α - -instance inhabitedStdGen : Inhabited StdGen where - default := mkStdGen - -/-- `Random α` gives us machinery to generate values of type `α` -/ -class Random (α : Type u) where - randomR [RandomGen g] (lo hi : α) : RandT g α - --- /-- `BoundedRandom α` gives us machinery to generate values of type `α` between certain bounds -/ --- class BoundedRandom (α : Type u) [LE α] where --- randomR {g : Type} (lo hi : α) (h : lo ≤ hi) [RandomGen g] : RandT g {a // lo ≤ a ∧ a ≤ hi} - -namespace Rand - /-- Generate one more `Nat` -/ - def next [RandomGen g] : RandT g Nat := do - let rng := (← get).down - let (res, new) := RandomGen.next rng - set (ULift.up new) - pure res - - /-- Create a new random number generator distinct from the one stored in the state -/ - def split {g : Type} [RandomGen g] : RandT g g := do - let rng := (← get).down - let (r1, r2) := RandomGen.split rng - set (ULift.up r1) - pure r2 - - /-- Get the range of Nat that can be generated by the generator `g` -/ - def range {g : Type} [RandomGen g] : RandT g (Nat × Nat) := do - let rng := (← get).down - pure <| RandomGen.range rng -end Rand - -namespace Random - -open Rand - -/-- Generate a random value of type `α`. -/ -def rand (α : Type u) [Random α] [range : DefaultRange α] [RandomGen g] : RandT g α := - Random.randomR range.lo range.hi - -/-- Generate a random value of type `α` between `x` and `y` inclusive. -/ -def randBound (α : Type u) [Random α] (lo hi : α) [RandomGen g] : RandT g α := - Random.randomR lo hi - -def randFin {n : Nat} [NeZero n] [RandomGen g] : RandT g (Fin n) := - λ ⟨g⟩ => - let (x, gen) := randNat g 0 n.succ - (Fin.ofNat n x, ULift.up gen) - -instance : Random Bool where - randomR := fun lo hi g => - let (n, g') := RandomGen.next g.down - match lo, hi with - | true, false => (n % 2 == 1, .up g') - | false, true => (n % 2 == 0, .up g') -- this doesn't matter btw, I'm just being quirky - | x, _ => (x, .up g') - -instance : Random Nat where - randomR := fun lo hi g => - let (n, g') := randNat g.down lo hi - (n, .up g') - -instance {n : Nat} [NeZero n] : Random (Fin n) where - randomR := fun lo hi g => - let (x, g') := randNat g.down lo hi - (Fin.ofNat n x, .up g') - -instance : Random Int where - randomR := fun lo hi g => - let lo' := if lo > hi then hi else lo - let hi' := if lo > hi then lo else hi - let hi'' := (hi' - lo').toNat - let (n, g') := randNat g.down 0 hi'' - (.ofNat n - lo', .up g') - -end Random - -/-- Computes a `Rand α` using the global `stdGenRef` as RNG. - Note that: - - `stdGenRef` is not necessarily properly seeded on program startup - as of now and will therefore be deterministic. - - `stdGenRef` is not thread local, hence two threads accessing it - at the same time will get the exact same generator. --/ -def IO.runRand (cmd : Rand α) : BaseIO α := do - let stdGen ← IO.stdGenRef.get - let rng := ULift.up stdGen - let (res, new) := Id.run <| StateT.run cmd rng - IO.stdGenRef.set new.down - pure res - -def IO.runRandWith (seed : Nat) (cmd : Rand α) : BaseIO α := do - pure $ (cmd.run (ULift.up $ mkStdGen seed)).1 - -end -end SlimCheck diff --git a/LSpec/SlimCheck/Gen.lean b/LSpec/SlimCheck/Gen.lean deleted file mode 100644 index 4b9aca4..0000000 --- a/LSpec/SlimCheck/Gen.lean +++ /dev/null @@ -1,124 +0,0 @@ -/- -Copyright (c) 2021 Henrik Böving. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Henrik Böving, Simon Hudon --/ -module -public import LSpec.SlimCheck.Control.Random - -/-! -# `Gen` Monad -This monad is used to formulate randomized computations with a parameter -to specify the desired size of the result. -This is a port of the Haskell QuickCheck library. -## Main definitions - * `Gen` monad -## Tags -random testing -## References - * https://hackage.haskell.org/package/QuickCheck --/ - -namespace SlimCheck -public section - -open Random - -/-- Monad to generate random examples to test properties with. -It has a `Nat` parameter so that the caller can decide on the -size of the examples. -/ -abbrev Gen (α : Type u) := ReaderT (ULift Nat) Rand α - -namespace Gen - -/-- Lift `Random.random` to the `Gen` monad. -/ -def chooseAny (α : Type u) [Random α] [DefaultRange α] : Gen α := - fun _ => rand α - -/-- Lift `BoundedRandom.randomR` to the `Gen` monad. -/ -def choose (α : Type u) [Random α] (lo hi : α) : Gen α := - fun _ => randBound α lo hi - -/-- Get access to the size parameter of the `Gen` monad. -/ -def getSize : Gen Nat := - return (← read).down - -/-- Apply a function to the size parameter. -/ -def resize (f : Nat → Nat) (x : Gen α) : Gen α := - withReader (ULift.up ∘ f ∘ ULift.down) x - -/-- Create an `Array` of examples using `x`. The size is controlled -by the size parameter of `Gen`. -/ -def arrayOf (x : Gen α) : Gen (Array α) := do - let sz ← choose Nat 0 (← getSize) - let mut res := #[] - for _ in [0:sz] do - res := res.push (← x) - pure res - -/-- Create an `List` of examples using `x`. The size is controlled -by the size parameter of `Gen`. -/ -def listOf (x : Gen α) : Gen (List α) := - arrayOf x >>= pure ∘ Array.toList - -/-- Given an array of example generators, choose one to create an example. -/ -def oneOf [Inhabited α] (xs : Array (Gen α)) : Gen α := do - let i ← choose Nat 0 (xs.size - 1) - if h : i < xs.size then - xs[i] - else -- The array is empty - pure default - -/-- Choose from generators with weighted probability. - Each pair is (weight, generator). Higher weights are more likely to be chosen. - - Example: - ``` - Gen.frequency #[(1, pure 0), (9, choose Nat 1 100)] (pure 0) -- 10% zeros, 90% 1-100 - ``` --/ -def frequency (weighted : Array (Nat × Gen α)) (fallback : Gen α) : Gen α := do - if weighted.isEmpty then - fallback - else - let totalWeight := weighted.foldl (fun acc (w, _) => acc + w) 0 - if totalWeight == 0 then - fallback - else - let choice ← choose Nat 0 (totalWeight - 1) - let mut cumulative := 0 - for (weight, gen) in weighted do - cumulative := cumulative + weight - if choice < cumulative then - return ← gen - -- Fallback (should not reach here) - fallback - -/-- Given an array of examples, choose one. -/ -def elements [Inhabited α] (xs : Array α) : Gen α := do - let i ← choose Nat 0 (xs.size - 1) - if h : i < xs.size then - return xs[i] - else -- The array is empty - pure default - -/-- Generate a random permutation of a given list. -/ -def permutationOf : (xs : List α) → Gen (List α) -| [] => pure [] -| x::xs => do - let ys ← permutationOf xs - let n ← choose Nat 0 ys.length - pure $ ys.take n ++ [x] ++ ys.drop n - -/-- Given two generators produces a tuple consisting out of the result of both -/ -def prodOf {α β : Type u} (x : Gen α) (y : Gen β) : Gen (α × β) := do - pure (←x, ←y) - -end Gen - -/-- Execute a `Gen` inside the `IO` monad using `size` as the example size-/ -def Gen.run (x : Gen α) (size : Nat) : BaseIO α := - IO.runRand $ ReaderT.run x ⟨size⟩ - -end -end SlimCheck diff --git a/LSpec/SlimCheck/Sampleable.lean b/LSpec/SlimCheck/Sampleable.lean deleted file mode 100644 index 1a7878b..0000000 --- a/LSpec/SlimCheck/Sampleable.lean +++ /dev/null @@ -1,232 +0,0 @@ -/- -Copyright (c) 2022 Henrik Böving. All rights reserved. -Released under Apache 2.0 license as described in the file LICENSE. -Authors: Henrik Böving, Simon Hudon --/ -module -public import LSpec.SlimCheck.Gen - -/-! -# `SampleableExt` Class -This class permits the creation samples of a given type -controlling the size of those values using the `Gen` monad`. -# `Shrinkable` Class -This class helps minimize examples by creating smaller versions of -given values. -When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, -`SlimCheck` requires that `ℕ` have an instance of `SampleableExt` and for -`prime n` to be decidable. `SlimCheck` will then use the instance of -`SampleableExt` to generate small examples of ℕ and progressively increase -in size. For each example `n`, `prime n` is tested. If it is false, -the example will be rejected (not a test success nor a failure) and -`SlimCheck` will move on to other examples. If `prime n` is true, `n -≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ -n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, -the test passes and `SlimCheck` moves on to trying more examples. -This is a port of the Haskell QuickCheck library. -## Main definitions - * `SampleableExt` class - * `Shrinkable` class -### `SampleableExt` -`SampleableExt` can be used in two ways. The first (and most common) -is to simply generate values of a type directly using the `Gen` monad, -if this is what you want to do then `SampleableExt.mkSelfContained` is -the way to go. -Furthermore it makes it possible to express generators for types that -do not lend themselves to introspection, such as `ℕ → ℕ`. -If we test a quantification over functions the -counter-examples cannot be shrunken or printed meaningfully. -For that purpose, `SampleableExt` provides a proxy representation -`proxy` that can be printed and shrunken as well -as interpreted (using `interp`) as an object of the right type. If you -are using it in the first way, this proxy type will simply be the type -itself and the `interp` function `id`. -### `Shrinkable -Given an example `x : α`, `Shrinkable α` gives us a way to shrink it -and suggest simpler examples. -## Shrinking -Shrinking happens when `SlimCheck` find a counter-example to a -property. It is likely that the example will be more complicated than -necessary so `SlimCheck` proceeds to shrink it as much as -possible. Although equally valid, a smaller counter-example is easier -for a user to understand and use. -The `Shrinkable` class, , has a `shrink` function so that we can use -specialized knowledge while shrinking a value. It is not responsible -for the whole shrinking process however. It only has to take one step -in the shrinking process. `SlimCheck` will repeatedly call `shrink` -until no more steps can be taken. Because `shrink` guarantees that the -size of the candidates it produces is strictly smaller than the -argument, we know that `SlimCheck` is guaranteed to terminate. -## Tags -random testing -## References - * https://hackage.haskell.org/package/QuickCheck --/ - -namespace SlimCheck -public section - -open Random - -/-- Given an example `x : α`, `Shrinkable α` gives us a way to shrink it -and suggest simpler examples. -/ -class Shrinkable (α : Type u) extends WellFoundedRelation α where - shrink : (x : α) → List α := fun _ => [] - -/-- `SampleableExt` can be used in two ways. The first (and most common) -is to simply generate values of a type directly using the `Gen` monad, -if this is what you want to do then `SampleableExt.mkSelfContained` is -the way to go. -Furthermore it makes it possible to express generators for types that -do not lend themselves to introspection, such as `ℕ → ℕ`. -If we test a quantification over functions the -counter-examples cannot be shrunken or printed meaningfully. -For that purpose, `SampleableExt` provides a proxy representation -`proxy` that can be printed and shrunken as well -as interpreted (using `interp`) as an object of the right type. -/ -class SampleableExt (α : Sort u) where - proxy : Type v - [proxyRepr : Repr proxy] - [shrink : Shrinkable proxy] - sample : Gen proxy - interp : proxy → α - -attribute [reducible, instance] SampleableExt.proxyRepr -attribute [reducible, instance] SampleableExt.shrink - -namespace SampleableExt - -/-- Use to generate instance whose purpose is to simply generate values -of a type directly using the `Gen` monad -/ -@[reducible] -def mkSelfContained [Repr α] [Shrinkable α] (sample : Gen α) : SampleableExt α where - proxy := α - proxyRepr := inferInstance - shrink := inferInstance - sample := sample - interp := id - -/-- First samples a proxy value and interprets it. Especially useful if -the proxy and target type are the same. -/ -def interpSample (α : Type u) [SampleableExt α] : Gen α := - SampleableExt.interp <$> SampleableExt.sample - -end SampleableExt - -section Shrinkers - -/-- `Nat.shrink' n` creates a list of smaller natural numbers by -successively dividing `n` by 2 . For example, `Nat.shrink 5 = [2, 1, 0]`. -/ -partial def Nat.shrink (n : Nat) : List Nat := - if 0 < n then - let m := n / 2 - let rest := shrink m - m :: rest - else - [] - -instance Nat.shrinkable : Shrinkable Nat where - shrink := Nat.shrink - -/-- `Fin.shrink` works like `Nat.shrink` but instead operates on `Fin`. -/ -partial def Fin.shrink {n : Nat} [NeZero n] (m : Fin n) : List (Fin n) := - if 0 < m then - let m := m / 2 - let rest := shrink m - m :: rest - else - [] - -instance Fin.shrinkable {n : Nat} [NeZero n] : Shrinkable (Fin n) where - shrink := Fin.shrink - -local instance Int_sizeOfAbs : SizeOf Int := ⟨Int.natAbs⟩ - -/-- `Int.shrinkable` operates like `Nat.shrinkable` but also includes the negative variants. -/ -instance Int.shrinkable : Shrinkable Int where - shrink n := - Nat.shrink n.natAbs |>.map fun x => - Int.ofNat x - -instance Bool.shrinkable : Shrinkable Bool := {} -instance Char.shrinkable : Shrinkable Char := {} - -instance Prod.shrinkable [shrA : Shrinkable α] [shrB : Shrinkable β] : Shrinkable (Prod α β) where - shrink := fun (fst,snd) => - let shrink1 := shrA.shrink fst |>.map fun x => (x, snd) - let shrink2 := shrB.shrink snd |>.map fun x => (fst, x) - shrink1 ++ shrink2 - -end Shrinkers - -section Samplers - -open Gen SampleableExt - -instance Nat.sampleableExt : SampleableExt Nat := - mkSelfContained (do choose Nat 0 (← getSize)) - -instance Fin.sampleableExt {n : Nat} [NeZero n] : SampleableExt (Fin n) := - mkSelfContained (do choose (Fin n) (Fin.ofNat n 0) (Fin.ofNat n (← getSize))) - -instance Int.sampleableExt : SampleableExt Int := - mkSelfContained (do choose Int (-(← getSize)) (← getSize)) - -instance Bool.sampleableExt : SampleableExt Bool := - mkSelfContained $ chooseAny Bool - -/-- This can be specialized into customized `SampleableExt Char` instances. -The resulting instance has `1 / length` chances of making an unrestricted choice of characters -and it otherwise chooses a character from `chars` with uniform probabilities. -/ -@[reducible] -def Char.sampleable (length : Nat) (chars : Array Char) : SampleableExt Char := - mkSelfContained do - let x ← choose Nat 0 length - if x == 0 then - let n ← interpSample Nat - pure $ Char.ofNat n - else - elements chars - -instance Char.sampleableDefault : SampleableExt Char := - Char.sampleable 3 - #[' ', '0', '1', '2', '3', 'a', 'b', 'c', 'A', 'B', 'C', ':', ',', ';', '`', '\\', '/'] - -instance Prod.sampleableExt {α β : Type u} [SampleableExt α] [SampleableExt β] : - SampleableExt (α × β) where - proxy := Prod (proxy α) (proxy β) - proxyRepr := inferInstance - shrink := inferInstance - sample := prodOf sample sample - interp := Prod.map interp interp - -instance Prop.sampleableExt : SampleableExt Prop where - proxy := Bool - proxyRepr := inferInstance - sample := interpSample Bool - shrink := inferInstance - interp := Coe.coe - -end Samplers - -/-- An annotation for values that should never get shrinked. -/ -@[expose] -def NoShrink (α : Type u) := α - -namespace NoShrink - -def mk (x : α) : NoShrink α := x -def get (x : NoShrink α) : α := x - -instance inhabited [inst : Inhabited α] : Inhabited (NoShrink α) := inst -instance repr [inst : Repr α] : Repr (NoShrink α) := inst - -instance shrinkable : Shrinkable (NoShrink α) where - shrink := fun _ => [] - -instance sampleableExt [SampleableExt α] [Repr α] : SampleableExt (NoShrink α) := - SampleableExt.mkSelfContained $ (NoShrink.mk ∘ SampleableExt.interp) <$> SampleableExt.sample - -end NoShrink - -end -end SlimCheck diff --git a/LSpec/Spec.lean b/LSpec/Spec.lean new file mode 100644 index 0000000..5e918a1 --- /dev/null +++ b/LSpec/Spec.lean @@ -0,0 +1,228 @@ +module +public import LSpec.Core +public import LSpec.Assert +public import LSpec.Property.Check + +/-! +# Hspec-style Specification DSL (`SpecM`, `Spec`) + +Provides a clean `do`-block DSL (`describe`, `context`, `it`, `prop`, `xit`, +`parallel`, `sequential`, `withTag`, `withOptions`, `withResource`, +`beforeAll`, `beforeEach`, `afterEach`, `aroundEach`) backed by the `TestTree` IR. + +Because `Spec := SpecM Unit` is `StateT (Array TestTree) BaseIO Unit`, defining +a suite (`def mySuite : Spec := do ...`) does **zero** test-tree construction or +execution at module import time. For suites containing large closed pure +expressions inside `it` blocks (expressions that do not depend on any runtime +variable or parameter), set `set_option compiler.extract_closed false` on the +declaration or test library so Lean does not hoist them into module initializers. +-/ + +namespace LSpec +public section + +/-- Specification builder monad accumulating `TestTree` nodes. + Lives in `BaseIO` so suites are deferred until run time and `withResource` + can allocate typed scope slots without acquiring resources during `--list`. -/ +abbrev SpecM (α : Type) := StateT (Array TestTree) BaseIO α + +/-- A test specification (Hspec-style `do` block). -/ +abbrev Spec := SpecM Unit + +/-- Run a `Spec` and collect its top-level `TestTree` children. -/ +def Spec.collect (s : Spec) : BaseIO (Array TestTree) := do + let (_, trees) ← s.run #[] + return trees + +/-- Run a `Spec` and wrap its children in a single named root `TestTree.group`. -/ +def Spec.toTestTree (rootName : String := "") (s : Spec) : BaseIO TestTree := do + let children ← s.collect + if rootName.isEmpty && children.size == 1 then + return children[0]! + else + return .group rootName children + +/-- Push a raw `TestTree` node into the current `SpecM` scope. -/ +def addTree (tree : TestTree) : SpecM Unit := + modify (·.push tree) + +/-- Include another `Spec` inline in the current scope. -/ +def includeSpec (s : Spec) : SpecM Unit := s + +/-! ## Grouping -/ + +/-- Group related tests under a component/module description (Hspec `describe`). -/ +def describe (name : String) (body : Spec) : SpecM Unit := do + let children ← body.collect + addTree (.group name children) + +/-- Group related tests under a scenario/circumstance description (Hspec `context`). -/ +def context (name : String) (body : Spec) : SpecM Unit := + describe name body + +/-- Alias for `describe`. -/ +def group (name : String) (body : Spec) : SpecM Unit := + describe name body + +/-! ## Leaf Tests -/ + +/-- Define a deferred unit test whose body `Unit → AssertM Unit` is only evaluated + when the test actually executes (never at module import, `--list`, or filtering). -/ +def itThunk (name : String) (mkBody : Unit → AssertM Unit) : SpecM Unit := + addTree (.leaf name #[] fun ctx => do + let action ← IO.lazyPure mkBody + IsTest.run ctx action) + +/-- Define a unit test whose body runs in `AssertM Unit` (Bool assertions + IO). + Expands to `itThunk` so even pure `let` bindings at the top of a `do` block + are deferred under a `Unit →` lambda and never execute during tree construction. + Uses a non-reserved symbol so downstream code can still use `it` as an identifier. -/ +syntax &"it " term:arg term : term +syntax &"it " term:arg " <| " term : term + +macro_rules + | `(it $name $body) => `(LSpec.itThunk $name (fun () => $body)) + | `(it $name <| $body) => `(LSpec.itThunk $name (fun () => $body)) + +/-- Define a unit test from any `IsTest` instance. -/ +def test [IsTest t] (name : String) (tVal : t) : SpecM Unit := + addTree (.single name tVal) + +/-- Define a deferred pure `Bool` unit test (`Unit → Bool`). -/ +def itCheck (name : String) (cond : Unit → Bool) (pos : SourcePos := by exact pos%) : SpecM Unit := + itThunk name fun () => do + let ok ← liftM (m := IO) (IO.lazyPure cond) + expect ok "expected true, got false" pos + +/-- Convenience macro for deferred pure `Bool` unit tests: + `itBool "addition works" (2 + 2 == 4)`. -/ +syntax &"itBool " term:arg term : term +macro_rules + | `(itBool $name $cond) => `(LSpec.itCheck $name (fun () => $cond)) + +/-- Define a skipped / pending test (Hspec `xit`). The body is never executed. -/ +def xitThunk (name : String) (_body : Unit → AssertM Unit := fun () => pure ()) + (reason : Option String := some "skipped (xit)") : SpecM Unit := + addTree (.leaf name #[] (fun _ => pure (.skip reason))) + +syntax &"xit " term:arg term : term +macro_rules + | `(xit $name $body) => `(LSpec.xitThunk $name (fun () => $body)) + +/-- Define a deferred Bool-based property test (`Unit → α`). -/ +def propThunk [Prop.PropTestable α] (name : String) (mkBody : Unit → α) + (config : Prop.PropertyConfig := {}) : SpecM Unit := + addTree (.single name (Prop.PropTest.of mkBody config)) + +/-- Define a Bool-based property test (`fun (a : A) (b : B) => ...`). + Accepts any `Prop.PropTestable` body (`Bool`, `AssertM Unit`, `Except String Unit`, + `==>`, `forAll`, or arbitrary-arity functions) and defers it under `fun () => ...`. + Uses non-reserved symbols so downstream code can still use `prop` as an identifier. -/ +syntax &"prop " term:arg term : term +syntax &"prop " term:arg " <| " term : term +syntax &"propWith " term:arg term:arg term : term +syntax &"propWith " term:arg term:arg " <| " term : term + +macro_rules + | `(prop $name $body) => `(LSpec.propThunk $name (fun () => $body)) + | `(prop $name <| $body) => `(LSpec.propThunk $name (fun () => $body)) + | `(propWith $name $cfg $body) => `(LSpec.propThunk $name (fun () => $body) $cfg) + | `(propWith $name $cfg <| $body) => `(LSpec.propThunk $name (fun () => $body) $cfg) + +/-- Define a skipped property test. -/ +def xpropThunk (name : String) (_body : Unit → α) + (reason : Option String := some "skipped (xprop)") : SpecM Unit := + addTree (.leaf name #[] (fun _ => pure (.skip reason))) + +syntax &"xprop " term:arg term : term +macro_rules + | `(xprop $name $body) => `(LSpec.xpropThunk $name (fun () => $body)) + +/-! ## Concurrency, Tags, and Options Modifiers -/ + +private def wrapChildren (wrap : TestTree → TestTree) (body : Spec) : SpecM Unit := do + let children ← body.collect + if children.size == 1 then + addTree (wrap children[0]!) + else if children.size > 1 then + addTree (wrap (.group "" children)) + +/-- Allow tests in `body` to run concurrently (up to the runner's `--threads` limit). -/ +def parallel (body : Spec) : SpecM Unit := + wrapChildren (.withMode .parallel) body + +/-- Force tests in `body` to run sequentially in declaration order. -/ +def sequential (body : Spec) : SpecM Unit := + wrapChildren (.withMode .sequential) body + +/-- Attach a single tag to all tests in `body` (filterable via `--tag` / `--exclude-tag`). -/ +def withTag (tag : String) (body : Spec) : SpecM Unit := + wrapChildren (.withTags #[tag]) body + +/-- Attach multiple tags to all tests in `body`. -/ +def withTags (tags : Array String) (body : Spec) : SpecM Unit := + wrapChildren (.withTags tags) body + +/-- Override `TestOptions` for all tests in `body`. -/ +def withOptions (f : TestOptions → TestOptions) (body : Spec) : SpecM Unit := + wrapChildren (.withOptions f) body + +/-- Override property-testing defaults (`numTests`, `maxSize`, `seed`, etc.) for `body`. -/ +def withPropConfig (cfg : Prop.PropertyConfig) (body : Spec) : SpecM Unit := + withOptions (fun opts => + let opts := opts + |>.setNat "prop.numTests" cfg.numTests + |>.setNat "prop.maxSize" cfg.maxSize + |>.setNat "prop.maxDiscardRatio" cfg.maxDiscardRatio + |>.setNat "prop.maxShrinks" cfg.maxShrinks + match cfg.seed with + | some s => opts.setUInt64 "prop.seed" s + | none => opts) body + +/-! ## Scoped Resources & Lifecycle Hooks -/ + +/-- Acquire a shared resource once before running `body`, pass a getter `IO α` + to tests inside `body`, and release the resource in a `finally` block once + all tests in `body` complete. + + Listing (`--list`) or filtering out `body` never calls `spec.acquire`. -/ +def withResource (spec : ResourceSpec α) (body : IO α → Spec) : SpecM Unit := do + let ref ← IO.mkRef (none : Option α) + let getRes : IO α := do + match ← ref.get with + | some a => pure a + | none => throw (IO.userError s!"Resource '{spec.description}' accessed outside its active scope") + let children ← (body getRes).collect + let acquire : IO (IO Unit) := do + let a ← spec.acquire + ref.set (some a) + return do + try + spec.release a + finally + ref.set none + let inner := + if children.size == 1 then children[0]! + else .group "" children + addTree (.withResource spec.description acquire inner) + +/-- Hspec-style `beforeAll`: acquire a resource once for `body` (optional `release` hook). -/ +def beforeAll (acquire : IO α) (release : α → IO Unit := fun _ => pure ()) + (description : String := "shared resource") (body : IO α → Spec) : SpecM Unit := + withResource { description, acquire, release } body + +/-- Run a `setup` action before every leaf test in `body`. -/ +def beforeEach (setup : IO Unit) (body : Spec) : SpecM Unit := + wrapChildren (.aroundEach fun run ctx => do setup; run ctx) body + +/-- Run a `teardown` action after every leaf test in `body` (even on failure/exception). -/ +def afterEach (teardown : IO Unit) (body : Spec) : SpecM Unit := + wrapChildren (.aroundEach fun run ctx => do + try run ctx finally teardown) body + +/-- Wrap every leaf test execution in `body` (Hspec `around`). -/ +def aroundEach (wrap : IO TestResult → IO TestResult) (body : Spec) : SpecM Unit := + wrapChildren (.aroundEach fun run ctx => wrap (run ctx)) body + +end +end LSpec diff --git a/LSpecProofs.lean b/LSpecProofs.lean new file mode 100644 index 0000000..31de88c --- /dev/null +++ b/LSpecProofs.lean @@ -0,0 +1,20 @@ +module +public import LSpecProofs.Filter +public import LSpecProofs.Report +public import LSpecProofs.Concurrency +public import LSpecProofs.Axioms + +/-! +# LSpec Formal Verification Suite (`LSpecProofs`) + +Zero-`sorry`, zero-dependency formal proofs of `LSpec.Runner`: +- `LSpecProofs.Filter`: Direct proofs on executable `TestFilter`, `filterTree`, and `listTests` + (soundness, completeness, idempotence, non-empty surviving `withResource` scopes). +- `LSpecProofs.Report`: Direct proofs on executable `ReportTree`, `RunSummary`, `compilePlan`, + and `computeWorkerCount` (exact pass/fail/skip accounting, permutation invariance, unified + plan equivalence with `listTests`, deterministic per-test seed assignment, worker bounds). +- `LSpecProofs.Concurrency`: Small-step operational semantics of the bounded-thread `WorkerPool` + and `ExecPlan` scheduler (bounded concurrency `≤ cap`, sequential exclusion & left-to-right + ordering, `withResource` acquire/release bracketing, deadlock freedom & termination, and + sequential–parallel equivalence). +-/ diff --git a/LSpecProofs/Axioms.lean b/LSpecProofs/Axioms.lean new file mode 100644 index 0000000..66661b9 --- /dev/null +++ b/LSpecProofs/Axioms.lean @@ -0,0 +1,168 @@ +module +public import LSpecProofs.Filter +public import LSpecProofs.Report +public import LSpecProofs.Concurrency + +/-! +# Compile-Time Axiom Audit (`LSpecProofs.Axioms`) + +Enforces at build time (under both `lake build LSpecProofs` and `nix flake check`) +that every headline theorem in `LSpecProofs` depends exclusively on Lean's standard +axioms (`propext`, `Quot.sound`, and at most `Classical.choice`) — never `sorryAx` +or any custom axiom. +-/ + +/-- +info: 'LSpec.Proofs.matchesTest_empty' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.matchesTest_empty + +/-- +info: 'LSpec.Proofs.matchesTest_excludeTag_rejects' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.matchesTest_excludeTag_rejects + +/-- +info: 'LSpec.Proofs.matchesTest_exclude_rejects' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.matchesTest_exclude_rejects + +/-- +info: 'LSpec.Proofs.filterTree_empty' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.filterTree_empty + +/-- +info: 'LSpec.Proofs.listTests_filterTree_eq' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.listTests_filterTree_eq + +/-- +info: 'LSpec.Proofs.filterTree_eq_none_iff' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.filterTree_eq_none_iff + +/-- +info: 'LSpec.Proofs.filterTreeGo_noEmptyScopes' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.filterTreeGo_noEmptyScopes + +/-- +info: 'LSpec.Proofs.filterTree_withResource_has_leaf' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.filterTree_withResource_has_leaf + +/-- +info: 'LSpec.Proofs.filterTree_idempotent' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.filterTree_idempotent + +/-- +info: 'LSpec.Proofs.leafCount_eq_leaves_size' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.leafCount_eq_leaves_size + +/-- +info: 'LSpec.Proofs.failures_eq_filter_leaves' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.failures_eq_filter_leaves + +/-- +info: 'LSpec.Proofs.summarize_total_eq_leafCount' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.summarize_total_eq_leafCount + +/-- +info: 'LSpec.Proofs.summarize_failed_eq_failures_size' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.summarize_failed_eq_failures_size + +/-- +info: 'LSpec.Proofs.summarize_allPassed_iff_failures_empty' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.summarize_allPassed_iff_failures_empty + +/-- +info: 'LSpec.Proofs.summarize_allPassed_iff_forall' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.summarize_allPassed_iff_forall + +/-- +info: 'LSpec.Proofs.summarizeChildren_perm' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.summarizeChildren_perm + +/-- +info: 'LSpec.Proofs.toListed_compilePlan' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.toListed_compilePlan + +/-- +info: 'LSpec.Proofs.compilePlan_seeds_deterministic' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.compilePlan_seeds_deterministic + +/-- +info: 'LSpec.Proofs.skipAll_summary' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.skipAll_summary + +/-- +info: 'LSpec.Proofs.computeWorkerCount_bounds' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.computeWorkerCount_bounds + +/-- +info: 'LSpec.Proofs.Concurrency.bounded_concurrency' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.bounded_concurrency + +/-- +info: 'LSpec.Proofs.Concurrency.seq_strict_left_to_right' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.seq_strict_left_to_right + +/-- +info: 'LSpec.Proofs.Concurrency.seq_exclusion' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.seq_exclusion + +/-- +info: 'LSpec.Proofs.Concurrency.seq_exclusion_at_root' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.seq_exclusion_at_root + +/-- +info: 'LSpec.Proofs.Concurrency.resPending_only_acquire' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.resPending_only_acquire + +/-- +info: 'LSpec.Proofs.Concurrency.resActive_release_requires_done' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.resActive_release_requires_done + +/-- +info: 'LSpec.Proofs.Concurrency.resource_bracket_invariant' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.resource_bracket_invariant + +/-- +info: 'LSpec.Proofs.Concurrency.resource_released_exactly_once_on_done' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.resource_released_exactly_once_on_done + +/-- +info: 'LSpec.Proofs.Concurrency.progress_deadlock_free' depends on axioms: [propext, Classical.choice, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.progress_deadlock_free + +/-- +info: 'LSpec.Proofs.Concurrency.termination_step_bound' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.termination_step_bound + +/-- +info: 'LSpec.Proofs.Concurrency.parallel_eq_sequential' depends on axioms: [propext, Quot.sound] +-/ +#guard_msgs in #print axioms LSpec.Proofs.Concurrency.parallel_eq_sequential diff --git a/LSpecProofs/Concurrency.lean b/LSpecProofs/Concurrency.lean new file mode 100644 index 0000000..52f465c --- /dev/null +++ b/LSpecProofs/Concurrency.lean @@ -0,0 +1,1332 @@ +module +public import LSpec.Runner +public import LSpecProofs.Report + +/-! +# Formal Small-Step Operational Semantics of the Parallel Runner (`LSpecProofs.Concurrency`) + +Formalizes the concurrency, sequential-isolation, resource-bracketing, +deadlock-freedom, termination, and determinism guarantees of `LSpec.Runner`'s +`WorkerPool` + `ExecPlan` scheduler via a faithful small-step transition system. + +Main theorems (all `sorry`-free): +1. `bounded_concurrency`: at every reachable interleaving, `activeWorkers rt ≤ cap`. +2. `seq_exclusion` & `seq_strict_left_to_right`: inside any active `.runningSeq` + subtree, at most 1 leaf is ever running and children execute strictly in + declaration order. +3. `resource_bracket_invariant`, `resource_released_exactly_once_on_done`, + `resPending_only_acquire`, and `resActive_release_requires_done`: + no child executes before acquire succeeds, release fires only after all children + finish, failed acquire skips children with zero releases, and every acquired + resource is released exactly once upon termination. +4. `progress_deadlock_free` & `termination_step_bound`: every non-terminal reachable + state can step (proving that nested `withResource` coordinators waiting outside + the worker pool cannot deadlock even at `cap = 1`), and every trace terminates in + at most `planSteps plan` steps. +5. `parallel_eq_sequential`: every reachable terminal state under ANY thread count + `cap ≥ 1` yields the exact same `ReportTree` and `RunSummary` as sequential + evaluation `evalSeq plan`. +-/ + +namespace LSpec.Proofs.Concurrency +public section + +open LSpec + +private theorem list_mem_sizeOf_lt {α : Type _} [SizeOf α] (x : α) : + ∀ (xs : List α), x ∈ xs → sizeOf x < sizeOf xs + | [], h => nomatch h + | y :: ys, h => by + simp only [List.mem_cons] at h + cases h with + | inl hEq => subst hEq; simp; omega + | inr hMem => have := list_mem_sizeOf_lt x ys hMem; simp; omega + +/-! ## Pure Model of `ExecPlan` and Canonical Sequential Semantics -/ + +/-- Pure deterministic model of a compiled `ExecPlan` (capturing leaves, groups, + sequential subtrees, and resource acquire outcomes). -/ +inductive PurePlan : Type where + | leaf (name : String) (path tags : Array String) (result : TestResult) + | group (name : String) (children : List PurePlan) + | seq (child : PurePlan) + | resource (desc : String) (path tags : Array String) (acq : Except String Unit) (child : PurePlan) + +/-- Failure report emitted when a resource fails to acquire (matching `LSpec.Runner`). -/ +def resourceFailReport (desc : String) (path tags : Array String) (err : String) : ReportTree := + .leaf { + name := s!"resource: {desc}" + path := path.push desc + tags := tags + result := .fail s!"failed to acquire resource '{desc}'" s!"IO error: {err}" (.exception err) + durationMs := 0 + } + +mutual + +/-- Canonical sequential evaluation of a `PurePlan`. -/ +def evalSeq : PurePlan → ReportTree + | .leaf name path tags result => + .leaf { name, path, tags, result, durationMs := 0 } + | .group name children => + .group name (evalSeqChildren children).toArray + | .seq child => + evalSeq child + | .resource desc path tags acq child => + match acq with + | .error err => resourceFailReport desc path tags err + | .ok () => evalSeq child +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +def evalSeqChildren : List PurePlan → List ReportTree + | [] => [] + | c :: cs => evalSeq c :: evalSeqChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +/-! ## Small-Step Concurrent Runtime Tree (`RT`) -/ + +/-- In-flight runtime state of a `PurePlan` executing on a bounded `WorkerPool`. -/ +inductive RT : Type where + /-- Leaf queued in the `WorkerPool` (0 slots held). -/ + | queuedLeaf (name : String) (path tags : Array String) (result : TestResult) + /-- Leaf actively running on a worker thread (1 pool slot held). -/ + | runningLeaf (name : String) (path tags : Array String) (result : TestResult) + /-- Completed subtree (0 slots held). -/ + | done (report : ReportTree) + /-- Group whose children execute concurrently and reassemble in declaration order. -/ + | group (name : String) (children : List RT) + /-- Sequential subtree queued as one job in the `WorkerPool` (0 slots held). -/ + | queuedSeq (plan : PurePlan) + /-- Sequential subtree actively executing on 1 worker thread (1 pool slot held). -/ + | runningSeq (inner : RT) + /-- Resource coordinator awaiting acquisition (runs outside pool capacity). -/ + | resPending (desc : String) (path tags : Array String) (acq : Except String Unit) (child : PurePlan) + /-- Resource acquired; child subtree is executing on the pool until `.done`. -/ + | resActive (desc : String) (child : RT) + +/-- Observable execution events emitted by small-step transitions. -/ +inductive Event : Type where + | startLeaf (path : Array String) + | finishLeaf (path : Array String) + | startSeq + | finishSeq + | acquireOk (desc : String) + | acquireFail (desc : String) + | release (desc : String) + | collapseGroup (name : String) + deriving BEq, Repr + +def Event.isAcquireOk : Event → Bool + | .acquireOk _ => true + | _ => false + +def Event.isRelease : Event → Bool + | .release _ => true + | _ => false + +def countAcquireOk (tr : List Event) : Nat := + (tr.filter Event.isAcquireOk).length + +def countRelease (tr : List Event) : Nat := + (tr.filter Event.isRelease).length + +mutual + +/-- Initial runtime state produced by dispatching a `PurePlan`. -/ +def RT.ofPlan : PurePlan → RT + | .leaf name path tags result => .queuedLeaf name path tags result + | .group name children => .group name (RT.ofPlanChildren children) + | .seq child => .queuedSeq child + | .resource desc path tags acq child => .resPending desc path tags acq child +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +def RT.ofPlanChildren : List PurePlan → List RT + | [] => [] + | c :: cs => RT.ofPlan c :: RT.ofPlanChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +/-! ## State Metrics -/ + +mutual + +/-- Number of `WorkerPool` slots currently held by `rt`. + `runningSeq` holds exactly 1 slot regardless of its inner state, and + `resPending`/`resActive` hold 0 coordinator slots (only their children + consume pool slots). -/ +def activeWorkers : RT → Nat + | .queuedLeaf _ _ _ _ => 0 + | .runningLeaf _ _ _ _ => 1 + | .done _ => 0 + | .group _ cs => activeWorkersChildren cs + | .queuedSeq _ => 0 + | .runningSeq _ => 1 + | .resPending _ _ _ _ _ => 0 + | .resActive _ child => activeWorkers child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def activeWorkersChildren : List RT → Nat + | [] => 0 + | c :: cs => activeWorkers c + activeWorkersChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +/-- Number of `runningLeaf` nodes currently executing inside `rt`. -/ +def runningLeaves : RT → Nat + | .queuedLeaf _ _ _ _ => 0 + | .runningLeaf _ _ _ _ => 1 + | .done _ => 0 + | .group _ cs => runningLeavesChildren cs + | .queuedSeq _ => 0 + | .runningSeq inner => runningLeaves inner + | .resPending _ _ _ _ _ => 0 + | .resActive _ child => runningLeaves child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def runningLeavesChildren : List RT → Nat + | [] => 0 + | c :: cs => runningLeaves c + runningLeavesChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +/-- Number of acquired-but-not-yet-released resources inside `rt`. -/ +def activeResources : RT → Nat + | .queuedLeaf _ _ _ _ => 0 + | .runningLeaf _ _ _ _ => 0 + | .done _ => 0 + | .group _ cs => activeResourcesChildren cs + | .queuedSeq _ => 0 + | .runningSeq inner => activeResources inner + | .resPending _ _ _ _ _ => 0 + | .resActive _ child => 1 + activeResources child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def activeResourcesChildren : List RT → Nat + | [] => 0 + | c :: cs => activeResources c + activeResourcesChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +/-- Canonical `ReportTree` denotation of any intermediate runtime tree `rt`. -/ +def denote : RT → ReportTree + | .queuedLeaf name path tags result => + .leaf { name, path, tags, result, durationMs := 0 } + | .runningLeaf name path tags result => + .leaf { name, path, tags, result, durationMs := 0 } + | .done r => r + | .group name cs => .group name (denoteChildren cs).toArray + | .queuedSeq plan => evalSeq plan + | .runningSeq inner => denote inner + | .resPending desc path tags acq child => + match acq with + | .error err => resourceFailReport desc path tags err + | .ok () => evalSeq child + | .resActive _ child => denote child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def denoteChildren : List RT → List ReportTree + | [] => [] + | c :: cs => denote c :: denoteChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +/-- Exact number of small steps required for a `PurePlan` to reach `.done`. -/ +def planSteps : PurePlan → Nat + | .leaf _ _ _ _ => 2 + | .group _ cs => 1 + planStepsChildren cs + | .seq child => 2 + planSteps child + | .resource _ _ _ acq child => + match acq with + | .error _ => 1 + | .ok () => 2 + planSteps child +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +def planStepsChildren : List PurePlan → Nat + | [] => 0 + | c :: cs => planSteps c + planStepsChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +/-- Strict progress measure: every `SeqStep` and `ParStep` decrements `remainingSteps` by 1. -/ +def remainingSteps : RT → Nat + | .queuedLeaf _ _ _ _ => 2 + | .runningLeaf _ _ _ _ => 1 + | .done _ => 0 + | .group _ cs => 1 + remainingStepsChildren cs + | .queuedSeq plan => 2 + planSteps plan + | .runningSeq inner => 1 + remainingSteps inner + | .resPending _ _ _ acq child => + match acq with + | .error _ => 1 + | .ok () => 2 + planSteps child + | .resActive _ child => 1 + remainingSteps child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def remainingStepsChildren : List RT → Nat + | [] => 0 + | c :: cs => remainingSteps c + remainingStepsChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +/-- Extract completed reports when every child in a list is `.done`. -/ +def allDoneReports : List RT → Option (List ReportTree) + | [] => some [] + | .done r :: rest => (allDoneReports rest).map (r :: ·) + | _ :: _ => none + +/-- Predicate asserting a runtime node is terminal (`.done _`). -/ +def RT.isDone : RT → Prop + | .done _ => True + | _ => False + +private theorem isDone_iff {rt : RT} : rt.isDone ↔ ∃ r, rt = .done r := by + cases rt <;> simp [RT.isDone] + +/-! ## Small-Step Relations: Sequential (`SeqStep`) and Bounded-Parallel (`ParStep`) -/ + +mutual + +/-- Strict left-to-right sequential execution inside a single worker thread (`execPlanSeq`). -/ +inductive SeqStep : RT → Event → RT → Prop where + | startLeaf (name path tags res) : + SeqStep (.queuedLeaf name path tags res) (.startLeaf path) (.runningLeaf name path tags res) + | finishLeaf (name path tags res) : + SeqStep (.runningLeaf name path tags res) (.finishLeaf path) + (.done (.leaf { name, path, tags, result := res, durationMs := 0 })) + | groupStep {name cs cs' ev} : + SeqGroupStep cs ev cs' → + SeqStep (.group name cs) ev (.group name cs') + | groupCollapse {name cs rs} : + allDoneReports cs = some rs → + SeqStep (.group name cs) (.collapseGroup name) (.done (.group name rs.toArray)) + | startSeq (plan) : + SeqStep (.queuedSeq plan) .startSeq (.runningSeq (RT.ofPlan plan)) + | stepSeq {inner inner' ev} : + SeqStep inner ev inner' → + SeqStep (.runningSeq inner) ev (.runningSeq inner') + | finishSeq (r) : + SeqStep (.runningSeq (.done r)) .finishSeq (.done r) + | resAcqOk (desc path tags child) : + SeqStep (.resPending desc path tags (.ok ()) child) (.acquireOk desc) + (.resActive desc (RT.ofPlan child)) + | resAcqFail (desc path tags err child) : + SeqStep (.resPending desc path tags (.error err) child) (.acquireFail desc) + (.done (resourceFailReport desc path tags err)) + | resStep {desc child child' ev} : + SeqStep child ev child' → + SeqStep (.resActive desc child) ev (.resActive desc child') + | resRelease (desc r) : + SeqStep (.resActive desc (.done r)) (.release desc) (.done r) + +/-- Strict left-to-right stepping on a group's child list: only advances past + children that are already `.done`. -/ +inductive SeqGroupStep : List RT → Event → List RT → Prop where + | head {c c' rest ev} : + SeqStep c ev c' → + SeqGroupStep (c :: rest) ev (c' :: rest) + | skipDone {r rest rest' ev} : + SeqGroupStep rest ev rest' → + SeqGroupStep (.done r :: rest) ev (.done r :: rest') + +end + +/-- Bounded-concurrency parallel step relation. `free` is the number of currently + available `WorkerPool` slots (`cap - activeWorkers root`). -/ +inductive ParStep (free : Nat) : RT → Event → RT → Prop where + | startLeaf (name path tags res) (hFree : free ≥ 1) : + ParStep free (.queuedLeaf name path tags res) (.startLeaf path) + (.runningLeaf name path tags res) + | finishLeaf (name path tags res) : + ParStep free (.runningLeaf name path tags res) (.finishLeaf path) + (.done (.leaf { name, path, tags, result := res, durationMs := 0 })) + | groupStep {name pre c c' post ev} : + ParStep free c ev c' → + ParStep free (.group name (pre ++ c :: post)) ev (.group name (pre ++ c' :: post)) + | groupCollapse {name cs rs} : + allDoneReports cs = some rs → + ParStep free (.group name cs) (.collapseGroup name) (.done (.group name rs.toArray)) + | startSeq (plan) (hFree : free ≥ 1) : + ParStep free (.queuedSeq plan) .startSeq (.runningSeq (RT.ofPlan plan)) + | stepSeq {inner inner' ev} : + SeqStep inner ev inner' → + ParStep free (.runningSeq inner) ev (.runningSeq inner') + | finishSeq (r) : + ParStep free (.runningSeq (.done r)) .finishSeq (.done r) + | resAcqOk (desc path tags child) : + ParStep free (.resPending desc path tags (.ok ()) child) (.acquireOk desc) + (.resActive desc (RT.ofPlan child)) + | resAcqFail (desc path tags err child) : + ParStep free (.resPending desc path tags (.error err) child) (.acquireFail desc) + (.done (resourceFailReport desc path tags err)) + | resStep {desc child child' ev} : + ParStep free child ev child' → + ParStep free (.resActive desc child) ev (.resActive desc child') + | resRelease (desc r) : + ParStep free (.resActive desc (.done r)) (.release desc) (.done r) + +/-- Top-level bounded-pool machine transition at thread limit `cap`. -/ +def MachineStep (cap : Nat) (rt : RT) (ev : Event) (rt' : RT) : Prop := + ParStep (cap - activeWorkers rt) rt ev rt' + +/-- Multi-step execution trace of the bounded-pool machine. -/ +inductive Trace (cap : Nat) : RT → List Event → RT → Prop where + | refl (rt : RT) : Trace cap rt [] rt + | step {rt rt' rt'' ev tr} : + MachineStep cap rt ev rt' → + Trace cap rt' tr rt'' → + Trace cap rt (ev :: tr) rt'' + +/-! ## Helper Lemmas -/ + +theorem activeWorkersChildren_append (xs ys : List RT) : + activeWorkersChildren (xs ++ ys) = activeWorkersChildren xs + activeWorkersChildren ys := by + induction xs with + | nil => simp [activeWorkersChildren] + | cons x rest ih => simp [activeWorkersChildren, ih]; omega + +theorem activeResourcesChildren_append (xs ys : List RT) : + activeResourcesChildren (xs ++ ys) = activeResourcesChildren xs + activeResourcesChildren ys := by + induction xs with + | nil => simp [activeResourcesChildren] + | cons x rest ih => simp [activeResourcesChildren, ih]; omega + +theorem denoteChildren_append (xs ys : List RT) : + denoteChildren (xs ++ ys) = denoteChildren xs ++ denoteChildren ys := by + induction xs with + | nil => simp [denoteChildren] + | cons x rest ih => simp [denoteChildren, ih] + +theorem remainingStepsChildren_append (xs ys : List RT) : + remainingStepsChildren (xs ++ ys) = remainingStepsChildren xs + remainingStepsChildren ys := by + induction xs with + | nil => simp [remainingStepsChildren] + | cons x rest ih => simp [remainingStepsChildren, ih]; omega + +theorem allDoneReports_activeWorkers {cs : List RT} {rs : List ReportTree} + (h : allDoneReports cs = some rs) : activeWorkersChildren cs = 0 := by + induction cs generalizing rs with + | nil => simp [activeWorkersChildren] + | cons c rest ih => + cases c <;> simp [allDoneReports] at h + rename_i r + obtain ⟨rs', hrs', _⟩ := h + simp [activeWorkersChildren, activeWorkers, ih hrs'] + +theorem allDoneReports_activeResources {cs : List RT} {rs : List ReportTree} + (h : allDoneReports cs = some rs) : activeResourcesChildren cs = 0 := by + induction cs generalizing rs with + | nil => simp [activeResourcesChildren] + | cons c rest ih => + cases c <;> simp [allDoneReports] at h + rename_i r + obtain ⟨rs', hrs', _⟩ := h + simp [activeResourcesChildren, activeResources, ih hrs'] + +theorem allDoneReports_denote {cs : List RT} {rs : List ReportTree} + (h : allDoneReports cs = some rs) : denoteChildren cs = rs := by + induction cs generalizing rs with + | nil => + simp [allDoneReports] at h + subst h + simp [denoteChildren] + | cons c rest ih => + cases c <;> simp [allDoneReports] at h + rename_i r + obtain ⟨rs', hrs', rfl⟩ := h + simp [denoteChildren, denote, ih hrs'] + +theorem allDoneReports_remainingSteps {cs : List RT} {rs : List ReportTree} + (h : allDoneReports cs = some rs) : remainingStepsChildren cs = 0 := by + induction cs generalizing rs with + | nil => simp [remainingStepsChildren] + | cons c rest ih => + cases c <;> simp [allDoneReports] at h + rename_i r + obtain ⟨rs', hrs', _⟩ := h + simp [remainingStepsChildren, remainingSteps, ih hrs'] + +mutual + +theorem activeWorkers_ofPlan : (p : PurePlan) → activeWorkers (RT.ofPlan p) = 0 + | .leaf _ _ _ _ => by simp [RT.ofPlan, activeWorkers] + | .group _ cs => by simp [RT.ofPlan, activeWorkers, activeWorkers_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, activeWorkers] + | .resource _ _ _ _ _ => by simp [RT.ofPlan, activeWorkers] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem activeWorkers_ofPlanChildren : (cs : List PurePlan) → + activeWorkersChildren (RT.ofPlanChildren cs) = 0 + | [] => by simp [RT.ofPlanChildren, activeWorkersChildren] + | c :: rest => by + simp [RT.ofPlanChildren, activeWorkersChildren, activeWorkers_ofPlan c, + activeWorkers_ofPlanChildren rest] +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +theorem runningLeaves_ofPlan : (p : PurePlan) → runningLeaves (RT.ofPlan p) = 0 + | .leaf _ _ _ _ => by simp [RT.ofPlan, runningLeaves] + | .group _ cs => by simp [RT.ofPlan, runningLeaves, runningLeaves_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, runningLeaves] + | .resource _ _ _ _ _ => by simp [RT.ofPlan, runningLeaves] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem runningLeaves_ofPlanChildren : (cs : List PurePlan) → + runningLeavesChildren (RT.ofPlanChildren cs) = 0 + | [] => by simp [RT.ofPlanChildren, runningLeavesChildren] + | c :: rest => by + simp [RT.ofPlanChildren, runningLeavesChildren, runningLeaves_ofPlan c, + runningLeaves_ofPlanChildren rest] +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +theorem activeResources_ofPlan : (p : PurePlan) → activeResources (RT.ofPlan p) = 0 + | .leaf _ _ _ _ => by simp [RT.ofPlan, activeResources] + | .group _ cs => by simp [RT.ofPlan, activeResources, activeResources_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, activeResources] + | .resource _ _ _ _ _ => by simp [RT.ofPlan, activeResources] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem activeResources_ofPlanChildren : (cs : List PurePlan) → + activeResourcesChildren (RT.ofPlanChildren cs) = 0 + | [] => by simp [RT.ofPlanChildren, activeResourcesChildren] + | c :: rest => by + simp [RT.ofPlanChildren, activeResourcesChildren, activeResources_ofPlan c, + activeResources_ofPlanChildren rest] +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +theorem denote_ofPlan : (p : PurePlan) → denote (RT.ofPlan p) = evalSeq p + | .leaf _ _ _ _ => by simp [RT.ofPlan, denote, evalSeq] + | .group _ cs => by simp [RT.ofPlan, denote, evalSeq, denote_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, denote, evalSeq] + | .resource _ _ _ acq _ => by + cases acq with + | ok u => cases u; simp [RT.ofPlan, denote, evalSeq] + | error _ => simp [RT.ofPlan, denote, evalSeq] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem denote_ofPlanChildren : (cs : List PurePlan) → + denoteChildren (RT.ofPlanChildren cs) = evalSeqChildren cs + | [] => by simp [RT.ofPlanChildren, denoteChildren, evalSeqChildren] + | c :: rest => by + simp [RT.ofPlanChildren, denoteChildren, evalSeqChildren, denote_ofPlan c, + denote_ofPlanChildren rest] +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +theorem remainingSteps_ofPlan : (p : PurePlan) → remainingSteps (RT.ofPlan p) = planSteps p + | .leaf _ _ _ _ => by simp [RT.ofPlan, remainingSteps, planSteps] + | .group _ cs => by simp [RT.ofPlan, remainingSteps, planSteps, remainingSteps_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, remainingSteps, planSteps] + | .resource _ _ _ acq _ => by + cases acq with + | ok u => cases u; simp [RT.ofPlan, remainingSteps, planSteps] + | error _ => simp [RT.ofPlan, remainingSteps, planSteps] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem remainingSteps_ofPlanChildren : (cs : List PurePlan) → + remainingStepsChildren (RT.ofPlanChildren cs) = planStepsChildren cs + | [] => by simp [RT.ofPlanChildren, remainingStepsChildren, planStepsChildren] + | c :: rest => by + simp [RT.ofPlanChildren, remainingStepsChildren, planStepsChildren, remainingSteps_ofPlan c, + remainingSteps_ofPlanChildren rest] +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +/-! ## Theorem 1: Bounded Concurrency (`activeWorkers ≤ cap`) -/ + +theorem parStep_activeWorkers_delta {free : Nat} {rt rt' : RT} {ev : Event} + (h : ParStep free rt ev rt') : + activeWorkers rt' ≤ activeWorkers rt + free := by + induction h with + | startLeaf _ _ _ _ hFree => simp [activeWorkers]; omega + | finishLeaf _ _ _ _ => simp [activeWorkers] + | groupStep _ ih => + simp only [activeWorkers, activeWorkersChildren_append, activeWorkersChildren] + omega + | groupCollapse hDone => + simp [activeWorkers, allDoneReports_activeWorkers hDone] + | startSeq _ hFree => simp [activeWorkers]; omega + | stepSeq _ => simp [activeWorkers] + | finishSeq _ => simp [activeWorkers] + | resAcqOk _ _ _ child => simp [activeWorkers, activeWorkers_ofPlan] + | resAcqFail _ _ _ _ _ => simp [activeWorkers] + | resStep _ ih => simp [activeWorkers]; omega + | resRelease _ _ => simp [activeWorkers] + +theorem machineStep_preserves_bound {cap : Nat} {rt rt' : RT} {ev : Event} + (hLe : activeWorkers rt ≤ cap) (hStep : MachineStep cap rt ev rt') : + activeWorkers rt' ≤ cap := by + have hDelta := parStep_activeWorkers_delta hStep + omega + +private theorem trace_preserves_bound {cap : Nat} {rt₀ rt : RT} {tr : List Event} + (hTrace : Trace cap rt₀ tr rt) (h0 : activeWorkers rt₀ ≤ cap) : + activeWorkers rt ≤ cap := by + induction hTrace with + | refl _ => exact h0 + | step hStep _ ih => exact ih (machineStep_preserves_bound h0 hStep) + +/-- **Theorem 1 (Bounded Concurrency)**: + Along every possible interleaving from `RT.ofPlan plan` under thread bound `cap`, + the number of simultaneously active worker-pool slots never exceeds `cap`. -/ +theorem bounded_concurrency {cap : Nat} {plan : PurePlan} {tr : List Event} {rt : RT} + (hTrace : Trace cap (RT.ofPlan plan) tr rt) : + activeWorkers rt ≤ cap := + trace_preserves_bound hTrace (by simp [activeWorkers_ofPlan]) + +/-! ## Theorem 2: Sequential Exclusion & Strict Declaration-Order Execution -/ + +/-- **Theorem 2a (Strict Left-to-Right Ordering)**: + Inside a sequential group, no later sibling in `rest` can ever step while + the head child `c` is not `.done`. -/ +theorem seq_strict_left_to_right {c : RT} {rest cs' : List RT} {ev : Event} + (hNotDone : ¬ c.isDone) (hStep : SeqGroupStep (c :: rest) ev cs') : + ∃ c', cs' = c' :: rest ∧ SeqStep c ev c' := by + cases hStep with + | head hSub => exact ⟨_, rfl, hSub⟩ + | skipDone _ => exact absurd trivial hNotDone + +mutual + +/-- Invariant for a runtime tree executing strictly sequentially: + every `.group` has only unfinished siblings with 0 running leaves behind + its active child, and the whole subtree has at most 1 running leaf. -/ +def SeqWF : RT → Prop + | .queuedLeaf _ _ _ _ => True + | .runningLeaf _ _ _ _ => True + | .done _ => True + | .group _ cs => SeqWFChildren cs + | .queuedSeq _ => True + | .runningSeq inner => SeqWF inner + | .resPending _ _ _ _ _ => True + | .resActive _ child => SeqWF child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def SeqWFChildren : List RT → Prop + | [] => True + | .done _ :: rest => SeqWFChildren rest + | c :: rest => SeqWF c ∧ SeqWFChildren rest ∧ runningLeavesChildren rest = 0 +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +mutual + +theorem seqWF_runningLeaves_le_one : (rt : RT) → SeqWF rt → runningLeaves rt ≤ 1 + | .queuedLeaf _ _ _ _, _ => by simp [runningLeaves] + | .runningLeaf _ _ _ _, _ => by simp [runningLeaves] + | .done _, _ => by simp [runningLeaves] + | .group _ cs, h => by + simp only [SeqWF] at h + simp only [runningLeaves] + exact seqWFChildren_runningLeaves_le_one cs h + | .queuedSeq _, _ => by simp [runningLeaves] + | .runningSeq inner, h => by + simp only [SeqWF] at h + simp only [runningLeaves] + exact seqWF_runningLeaves_le_one inner h + | .resPending _ _ _ _ _, _ => by simp [runningLeaves] + | .resActive _ child, h => by + simp only [SeqWF] at h + simp only [runningLeaves] + exact seqWF_runningLeaves_le_one child h +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +theorem seqWFChildren_runningLeaves_le_one : (cs : List RT) → SeqWFChildren cs → + runningLeavesChildren cs ≤ 1 + | [], _ => by simp [runningLeavesChildren] + | c :: rest, h => by + cases c with + | done _ => + simp only [SeqWFChildren] at h + simp only [runningLeavesChildren, runningLeaves, Nat.zero_add] + exact seqWFChildren_runningLeaves_le_one rest h + | queuedLeaf _ _ _ _ | runningLeaf _ _ _ _ | group _ _ | queuedSeq _ | runningSeq _ + | resPending _ _ _ _ _ | resActive _ _ => + simp only [SeqWFChildren] at h + obtain ⟨hc, _, hRestZero⟩ := h + have hHead := seqWF_runningLeaves_le_one _ hc + simp only [runningLeavesChildren, hRestZero, Nat.add_zero] + exact hHead +termination_by cs => sizeOf cs +decreasing_by all_goals (try subst_vars; simp_wf; try omega) + +end + +mutual + +theorem seqWF_ofPlan : (p : PurePlan) → SeqWF (RT.ofPlan p) + | .leaf _ _ _ _ => by simp [RT.ofPlan, SeqWF] + | .group _ cs => by simp [RT.ofPlan, SeqWF, seqWF_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, SeqWF] + | .resource _ _ _ _ _ => by simp [RT.ofPlan, SeqWF] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem seqWF_ofPlanChildren : (cs : List PurePlan) → + SeqWFChildren (RT.ofPlanChildren cs) + | [] => by simp [RT.ofPlanChildren, SeqWFChildren] + | c :: rest => by + cases hHead : RT.ofPlan c with + | done _ => cases c <;> simp [RT.ofPlan] at hHead + | queuedLeaf _ _ _ _ | runningLeaf _ _ _ _ | group _ _ | queuedSeq _ | runningSeq _ + | resPending _ _ _ _ _ | resActive _ _ => + simp only [RT.ofPlanChildren, hHead, SeqWFChildren] + exact ⟨by rw [← hHead]; exact seqWF_ofPlan c, + seqWF_ofPlanChildren rest, + runningLeaves_ofPlanChildren rest⟩ +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +theorem seqStep_not_done {rt rt' : RT} {ev : Event} (h : SeqStep rt ev rt') : ¬ rt.isDone := by + cases h <;> simp [RT.isDone] + +mutual + +theorem seqStep_preserves_seqWF {rt rt' : RT} {ev : Event} : + SeqStep rt ev rt' → SeqWF rt → SeqWF rt' + | .startLeaf .., _ => by simp [SeqWF] + | .finishLeaf .., _ => by simp [SeqWF] + | .groupStep hG, h => by + simp only [SeqWF] at h ⊢ + exact seqGroupStep_preserves_seqWF hG h + | .groupCollapse _, _ => by simp [SeqWF] + | .startSeq plan, _ => by simp [SeqWF, seqWF_ofPlan] + | .stepSeq hSub, h => by + simp only [SeqWF] at h ⊢ + exact seqStep_preserves_seqWF hSub h + | .finishSeq _, _ => by simp [SeqWF] + | .resAcqOk _ _ _ child, _ => by simp [SeqWF, seqWF_ofPlan] + | .resAcqFail .., _ => by simp [SeqWF] + | .resStep hSub, h => by + simp only [SeqWF] at h ⊢ + exact seqStep_preserves_seqWF hSub h + | .resRelease .., _ => by simp [SeqWF] + +theorem seqGroupStep_preserves_seqWF {cs cs' : List RT} {ev : Event} : + SeqGroupStep cs ev cs' → SeqWFChildren cs → SeqWFChildren cs' + | @SeqGroupStep.head c c' rest _ hSub, hWF => by + cases c with + | done _ => exact absurd trivial (seqStep_not_done hSub) + | queuedLeaf _ _ _ _ | runningLeaf _ _ _ _ | group _ _ | queuedSeq _ | runningSeq _ + | resPending _ _ _ _ _ | resActive _ _ => + simp only [SeqWFChildren] at hWF + obtain ⟨hHeadWF, hRestWF, hRestZero⟩ := hWF + have hHeadWF' := seqStep_preserves_seqWF hSub hHeadWF + cases c' with + | done _ => simpa [SeqWFChildren] using hRestWF + | queuedLeaf _ _ _ _ | runningLeaf _ _ _ _ | group _ _ | queuedSeq _ | runningSeq _ + | resPending _ _ _ _ _ | resActive _ _ => + simpa [SeqWFChildren] using ⟨hHeadWF', hRestWF, hRestZero⟩ + | .skipDone hSub, hWF => by + simp only [SeqWFChildren] at hWF ⊢ + exact seqGroupStep_preserves_seqWF hSub hWF + +end + +mutual + +/-- Global parallel-tree invariant: every active `.runningSeq inner` anywhere + in the runtime tree satisfies `SeqWF inner` (and therefore `runningLeaves inner ≤ 1`). -/ +def AllSeqsWF : RT → Prop + | .queuedLeaf _ _ _ _ => True + | .runningLeaf _ _ _ _ => True + | .done _ => True + | .group _ cs => AllSeqsWFChildren cs + | .queuedSeq _ => True + | .runningSeq inner => SeqWF inner + | .resPending _ _ _ _ _ => True + | .resActive _ child => AllSeqsWF child +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +def AllSeqsWFChildren : List RT → Prop + | [] => True + | c :: cs => AllSeqsWF c ∧ AllSeqsWFChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +theorem allSeqsWFChildren_append {xs ys : List RT} : + AllSeqsWFChildren (xs ++ ys) ↔ AllSeqsWFChildren xs ∧ AllSeqsWFChildren ys := by + induction xs with + | nil => simp [AllSeqsWFChildren] + | cons x rest ih => + simp only [List.cons_append, AllSeqsWFChildren, ih] + exact ⟨fun ⟨hx, h1, h2⟩ => ⟨⟨hx, h1⟩, h2⟩, fun ⟨⟨hx, h1⟩, h2⟩ => ⟨hx, h1, h2⟩⟩ + +mutual + +theorem allSeqsWF_ofPlan : (p : PurePlan) → AllSeqsWF (RT.ofPlan p) + | .leaf _ _ _ _ => by simp [RT.ofPlan, AllSeqsWF] + | .group _ cs => by simp [RT.ofPlan, AllSeqsWF, allSeqsWF_ofPlanChildren cs] + | .seq _ => by simp [RT.ofPlan, AllSeqsWF] + | .resource _ _ _ _ _ => by simp [RT.ofPlan, AllSeqsWF] +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; try omega) + +theorem allSeqsWF_ofPlanChildren : (cs : List PurePlan) → + AllSeqsWFChildren (RT.ofPlanChildren cs) + | [] => by simp [RT.ofPlanChildren, AllSeqsWFChildren] + | c :: rest => by + simp only [RT.ofPlanChildren, AllSeqsWFChildren] + exact ⟨allSeqsWF_ofPlan c, allSeqsWF_ofPlanChildren rest⟩ +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +theorem parStep_preserves_allSeqsWF {free : Nat} {rt rt' : RT} {ev : Event} + (hStep : ParStep free rt ev rt') (hWF : AllSeqsWF rt) : AllSeqsWF rt' := by + induction hStep with + | startLeaf => simp [AllSeqsWF] + | finishLeaf => simp [AllSeqsWF] + | groupStep _ ih => + simp only [AllSeqsWF, allSeqsWFChildren_append, AllSeqsWFChildren] at hWF ⊢ + exact ⟨hWF.1, ih hWF.2.1, hWF.2.2⟩ + | groupCollapse => simp [AllSeqsWF] + | startSeq plan _ => simp [AllSeqsWF, seqWF_ofPlan] + | stepSeq hSub => + simp only [AllSeqsWF] at hWF ⊢ + exact seqStep_preserves_seqWF hSub hWF + | finishSeq => simp [AllSeqsWF] + | resAcqOk _ _ _ child => simp [AllSeqsWF, allSeqsWF_ofPlan] + | resAcqFail => simp [AllSeqsWF] + | resStep _ ih => + simp only [AllSeqsWF] at hWF ⊢ + exact ih hWF + | resRelease => simp [AllSeqsWF] + +private theorem trace_preserves_allSeqsWF {cap : Nat} {rt₀ rt : RT} {tr : List Event} + (hTrace : Trace cap rt₀ tr rt) (h0 : AllSeqsWF rt₀) : AllSeqsWF rt := by + induction hTrace with + | refl _ => exact h0 + | step hStep _ ih => exact ih (parStep_preserves_allSeqsWF hStep h0) + +/-- **Theorem 2b (Sequential Exclusion)**: + Along every reachable parallel trace, every active `.runningSeq inner` subtree + satisfies `SeqWF inner` and therefore has at most 1 running leaf (`runningLeaves inner ≤ 1`). -/ +theorem seq_exclusion {cap : Nat} {plan : PurePlan} {tr : List Event} {rt : RT} + (hTrace : Trace cap (RT.ofPlan plan) tr rt) : + AllSeqsWF rt := + trace_preserves_allSeqsWF hTrace (allSeqsWF_ofPlan plan) + +theorem seq_exclusion_at_root {cap : Nat} {plan : PurePlan} {tr : List Event} {inner : RT} + (hTrace : Trace cap (RT.ofPlan plan) tr (.runningSeq inner)) : + runningLeaves inner ≤ 1 := by + have hWF := seq_exclusion hTrace + simp only [AllSeqsWF] at hWF + exact seqWF_runningLeaves_le_one inner hWF + +/-! ## Theorem 3: Resource Bracket Safety (`withResource` / `beforeAll`) -/ + +/-- No child leaf can execute while a resource is still pending: the only step + from `.resPending` is `acquireOk` or `acquireFail`. -/ +theorem resPending_only_acquire {free : Nat} {desc : String} {path tags : Array String} + {acq : Except String Unit} {child : PurePlan} {rt' : RT} {ev : Event} + (h : ParStep free (.resPending desc path tags acq child) ev rt') : + (ev = .acquireOk desc ∧ acq = .ok () ∧ rt' = .resActive desc (RT.ofPlan child)) ∨ + (∃ err, ev = .acquireFail desc ∧ acq = .error err ∧ rt' = .done (resourceFailReport desc path tags err)) := by + cases h with + | resAcqOk => exact Or.inl ⟨rfl, rfl, rfl⟩ + | resAcqFail => exact Or.inr ⟨_, rfl, rfl, rfl⟩ + +/-- `release desc` on `.resActive desc child` can only fire once `child` is completely `.done` + (with 0 active workers and 0 running leaves). -/ +theorem resActive_release_requires_done {free : Nat} {desc : String} {child rt' : RT} + (h : ParStep free (.resActive desc child) (.release desc) rt') + (hNoNestedSame : ∀ child', ¬ ParStep free child (.release desc) child') : + ∃ r, child = .done r ∧ rt' = .done r ∧ activeWorkers child = 0 ∧ runningLeaves child = 0 := by + cases h with + | resStep hSub => exact absurd hSub (hNoNestedSame _) + | resRelease => exact ⟨_, rfl, rfl, by simp [activeWorkers], by simp [runningLeaves]⟩ + +mutual + +theorem seqStep_resource_conservation {rt rt' : RT} {ev : Event} : + SeqStep rt ev rt' → + activeResources rt' + (if ev.isRelease then 1 else 0) = + activeResources rt + (if ev.isAcquireOk then 1 else 0) + | .startLeaf .. => by simp [activeResources, Event.isRelease, Event.isAcquireOk] + | .finishLeaf .. => by simp [activeResources, Event.isRelease, Event.isAcquireOk] + | .groupStep hG => by + simp only [activeResources] + exact seqGroupStep_resource_conservation hG + | .groupCollapse hDone => by + simp [activeResources, allDoneReports_activeResources hDone, Event.isRelease, Event.isAcquireOk] + | .startSeq plan => by + simp [activeResources, activeResources_ofPlan, Event.isRelease, Event.isAcquireOk] + | .stepSeq hSub => by + simp only [activeResources] + exact seqStep_resource_conservation hSub + | .finishSeq _ => by simp [activeResources, Event.isRelease, Event.isAcquireOk] + | .resAcqOk _ _ _ child => by + simp [activeResources, activeResources_ofPlan, Event.isRelease, Event.isAcquireOk] + | .resAcqFail .. => by simp [activeResources, Event.isRelease, Event.isAcquireOk] + | .resStep hSub => by + have ih := seqStep_resource_conservation hSub + simp only [activeResources] + omega + | .resRelease .. => by simp [activeResources, Event.isRelease, Event.isAcquireOk] + +theorem seqGroupStep_resource_conservation {cs cs' : List RT} {ev : Event} : + SeqGroupStep cs ev cs' → + activeResourcesChildren cs' + (if ev.isRelease then 1 else 0) = + activeResourcesChildren cs + (if ev.isAcquireOk then 1 else 0) + | .head hSub => by + have ih := seqStep_resource_conservation hSub + simp only [activeResourcesChildren] + omega + | .skipDone hSub => by + have ih := seqGroupStep_resource_conservation hSub + simp only [activeResourcesChildren, activeResources] + omega + +end + +theorem parStep_resource_conservation {free : Nat} {rt rt' : RT} {ev : Event} + (h : ParStep free rt ev rt') : + activeResources rt' + (if ev.isRelease then 1 else 0) = + activeResources rt + (if ev.isAcquireOk then 1 else 0) := by + induction h with + | startLeaf => simp [activeResources, Event.isRelease, Event.isAcquireOk] + | finishLeaf => simp [activeResources, Event.isRelease, Event.isAcquireOk] + | groupStep _ ih => + simp only [activeResources, activeResourcesChildren_append, activeResourcesChildren] + omega + | groupCollapse hDone => + simp [activeResources, allDoneReports_activeResources hDone, Event.isRelease, Event.isAcquireOk] + | startSeq plan _ => + simp [activeResources, activeResources_ofPlan, Event.isRelease, Event.isAcquireOk] + | stepSeq hSub => + simp only [activeResources] + exact seqStep_resource_conservation hSub + | finishSeq => simp [activeResources, Event.isRelease, Event.isAcquireOk] + | resAcqOk _ _ _ child => + simp [activeResources, activeResources_ofPlan, Event.isRelease, Event.isAcquireOk] + | resAcqFail => simp [activeResources, Event.isRelease, Event.isAcquireOk] + | resStep _ ih => simp only [activeResources]; omega + | resRelease => simp [activeResources, Event.isRelease, Event.isAcquireOk] + +private theorem trace_resource_conservation {cap : Nat} {rt₀ rt : RT} {tr : List Event} + (hTrace : Trace cap rt₀ tr rt) : + activeResources rt₀ + countAcquireOk tr = countRelease tr + activeResources rt := by + induction hTrace with + | refl _ => simp [countAcquireOk, countRelease] + | step hStep _ ih => + rename_i a b c ev rest _ + have hCons := parStep_resource_conservation hStep + simp only [countAcquireOk, countRelease, List.filter_cons] at ih ⊢ + cases hA : ev.isAcquireOk <;> cases hR : ev.isRelease <;> simp_all <;> omega + +/-- **Theorem 3a (Resource Bracket Accounting Invariant)**: + At every prefix of every reachable trace, `countAcquireOk tr = countRelease tr + activeResources rt` + (so `countRelease tr ≤ countAcquireOk tr` at all times — never an unmatched release). -/ +theorem resource_bracket_invariant {cap : Nat} {plan : PurePlan} {tr : List Event} {rt : RT} + (hTrace : Trace cap (RT.ofPlan plan) tr rt) : + countAcquireOk tr = countRelease tr + activeResources rt := by + have h := trace_resource_conservation hTrace + rw [activeResources_ofPlan, Nat.zero_add] at h + exact h + +/-- **Theorem 3b (Exact-Once Release on Termination)**: + In every terminal state (even when child tests fail), every acquired resource + has been released exactly once (`countAcquireOk tr = countRelease tr`). -/ +theorem resource_released_exactly_once_on_done {cap : Nat} {plan : PurePlan} + {tr : List Event} {r : ReportTree} + (hTrace : Trace cap (RT.ofPlan plan) tr (.done r)) : + countAcquireOk tr = countRelease tr := by + have h := resource_bracket_invariant hTrace + simp only [activeResources, Nat.add_zero] at h + exact h + +/-! ## Theorem 4: Deadlock Freedom & Termination -/ + +mutual + +theorem seqStep_progress : ∀ (rt : RT), ¬ rt.isDone → ∃ ev rt', SeqStep rt ev rt' + | .queuedLeaf name path tags res, _ => + ⟨.startLeaf path, .runningLeaf name path tags res, .startLeaf ..⟩ + | .runningLeaf name path tags res, _ => + ⟨.finishLeaf path, _, .finishLeaf ..⟩ + | .done _, h => absurd trivial h + | .group name cs, _ => by + match hDone : allDoneReports cs with + | some rs => + exact ⟨.collapseGroup name, .done (.group name rs.toArray), .groupCollapse hDone⟩ + | none => + have ⟨ev, cs', hG⟩ := seqGroupStep_progress cs hDone + exact ⟨ev, .group name cs', .groupStep hG⟩ + | .queuedSeq plan, _ => + ⟨.startSeq, .runningSeq (RT.ofPlan plan), .startSeq plan⟩ + | .runningSeq inner, _ => by + by_cases hDone : inner.isDone + · obtain ⟨r, rfl⟩ := isDone_iff.mp hDone + exact ⟨.finishSeq, .done r, .finishSeq r⟩ + · have ⟨ev, inner', hSub⟩ := seqStep_progress inner hDone + exact ⟨ev, .runningSeq inner', .stepSeq hSub⟩ + | .resPending desc path tags acq child, _ => by + cases acq with + | ok u => + cases u + exact ⟨.acquireOk desc, .resActive desc (RT.ofPlan child), .resAcqOk ..⟩ + | error err => + exact ⟨.acquireFail desc, .done (resourceFailReport desc path tags err), .resAcqFail ..⟩ + | .resActive desc child, _ => by + by_cases hDone : child.isDone + · obtain ⟨r, rfl⟩ := isDone_iff.mp hDone + exact ⟨.release desc, .done r, .resRelease desc r⟩ + · have ⟨ev, child', hSub⟩ := seqStep_progress child hDone + exact ⟨ev, .resActive desc child', .resStep hSub⟩ +termination_by rt => sizeOf rt +decreasing_by all_goals (simp_wf; try omega) + +theorem seqGroupStep_progress : ∀ (cs : List RT), allDoneReports cs = none → + ∃ ev cs', SeqGroupStep cs ev cs' + | [], h => by simp [allDoneReports] at h + | c :: rest, h => by + by_cases hDone : c.isDone + · obtain ⟨r, rfl⟩ := isDone_iff.mp hDone + have hRest : allDoneReports rest = none := by + cases hR : allDoneReports rest with + | none => rfl + | some rs => simp [allDoneReports, hR] at h + have ⟨ev, rest', hSub⟩ := seqGroupStep_progress rest hRest + exact ⟨ev, .done r :: rest', .skipDone hSub⟩ + · have ⟨ev, c', hSub⟩ := seqStep_progress c hDone + exact ⟨ev, c' :: rest, .head hSub⟩ +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; try omega) + +end + +private theorem find_active_child : ∀ (cs : List RT), activeWorkersChildren cs > 0 → + ∃ pre c post, cs = pre ++ c :: post ∧ activeWorkers c > 0 + | [], h => by simp [activeWorkersChildren] at h + | c :: rest, h => by + simp only [activeWorkersChildren] at h + by_cases hc : activeWorkers c > 0 + · exact ⟨[], c, rest, rfl, hc⟩ + · have hRest : activeWorkersChildren rest > 0 := by omega + have ⟨pre, c', post, hEq, hPos⟩ := find_active_child rest hRest + exact ⟨c :: pre, c', post, by simp [hEq], hPos⟩ + +private theorem find_undone_child : ∀ (cs : List RT), allDoneReports cs = none → + ∃ pre c post, cs = pre ++ c :: post ∧ ¬ c.isDone + | [], h => by simp [allDoneReports] at h + | c :: rest, h => by + cases c with + | done r => + have hRest : allDoneReports rest = none := by + cases hR : allDoneReports rest with + | none => rfl + | some rs => simp [allDoneReports, hR] at h + have ⟨pre, c', post, hEq, hNotDone⟩ := find_undone_child rest hRest + exact ⟨.done r :: pre, c', post, by simp [hEq], hNotDone⟩ + | queuedLeaf _ _ _ _ | runningLeaf _ _ _ _ | group _ _ | queuedSeq _ | runningSeq _ + | resPending _ _ _ _ _ | resActive _ _ => + exact ⟨[], _, rest, rfl, by simp [RT.isDone]⟩ + +/-- Any subtree holding ≥ 1 active worker slot can always make progress with `free = 0` + (no additional pool slots required). This is the key lemma verifying why running + `withResource` coordinators outside the pool prevents pool-starvation deadlocks. -/ +theorem parStep_progress_of_active (free : Nat) : + ∀ (rt : RT), activeWorkers rt > 0 → ∃ ev rt', ParStep free rt ev rt' + | .queuedLeaf _ _ _ _, h => by simp [activeWorkers] at h + | .runningLeaf name path tags res, _ => + ⟨.finishLeaf path, _, .finishLeaf ..⟩ + | .done _, h => by simp [activeWorkers] at h + | .group name cs, h => by + simp only [activeWorkers] at h + have ⟨pre, c, post, hEq, hPos⟩ := find_active_child cs h + have ⟨ev, c', hSub⟩ := parStep_progress_of_active free c hPos + rw [hEq] + exact ⟨ev, .group name (pre ++ c' :: post), .groupStep hSub⟩ + | .queuedSeq _, h => by simp [activeWorkers] at h + | .runningSeq inner, _ => by + by_cases hDone : inner.isDone + · obtain ⟨r, rfl⟩ := isDone_iff.mp hDone + exact ⟨.finishSeq, .done r, .finishSeq r⟩ + · have ⟨ev, inner', hSub⟩ := seqStep_progress inner hDone + exact ⟨ev, .runningSeq inner', .stepSeq hSub⟩ + | .resPending _ _ _ _ _, h => by simp [activeWorkers] at h + | .resActive desc child, h => by + simp only [activeWorkers] at h + have ⟨ev, child', hSub⟩ := parStep_progress_of_active free child h + exact ⟨ev, .resActive desc child', .resStep hSub⟩ +termination_by rt => sizeOf rt +decreasing_by + all_goals + simp_wf + first + | omega + | (have := list_mem_sizeOf_lt c cs (by rw [hEq]; simp); omega) + +/-- When `free ≥ 1`, any non-terminal runtime tree can step. -/ +theorem parStep_progress_of_free {free : Nat} (hFree : free ≥ 1) : + ∀ (rt : RT), ¬ rt.isDone → ∃ ev rt', ParStep free rt ev rt' + | .queuedLeaf name path tags res, _ => + ⟨.startLeaf path, .runningLeaf name path tags res, .startLeaf _ _ _ _ hFree⟩ + | .runningLeaf name path tags res, _ => + ⟨.finishLeaf path, _, .finishLeaf ..⟩ + | .done _, h => absurd trivial h + | .group name cs, _ => by + match hDone : allDoneReports cs with + | some rs => + exact ⟨.collapseGroup name, .done (.group name rs.toArray), .groupCollapse hDone⟩ + | none => + have ⟨pre, c, post, hEq, hNotDone⟩ := find_undone_child cs hDone + have ⟨ev, c', hSub⟩ := parStep_progress_of_free hFree c hNotDone + rw [hEq] + exact ⟨ev, .group name (pre ++ c' :: post), .groupStep hSub⟩ + | .queuedSeq plan, _ => + ⟨.startSeq, .runningSeq (RT.ofPlan plan), .startSeq plan hFree⟩ + | .runningSeq inner, _ => by + by_cases hDone : inner.isDone + · obtain ⟨r, rfl⟩ := isDone_iff.mp hDone + exact ⟨.finishSeq, .done r, .finishSeq r⟩ + · have ⟨ev, inner', hSub⟩ := seqStep_progress inner hDone + exact ⟨ev, .runningSeq inner', .stepSeq hSub⟩ + | .resPending desc path tags acq child, _ => by + cases acq with + | ok u => + cases u + exact ⟨.acquireOk desc, .resActive desc (RT.ofPlan child), .resAcqOk ..⟩ + | error err => + exact ⟨.acquireFail desc, .done (resourceFailReport desc path tags err), .resAcqFail ..⟩ + | .resActive desc child, _ => by + by_cases hDone : child.isDone + · obtain ⟨r, rfl⟩ := isDone_iff.mp hDone + exact ⟨.release desc, .done r, .resRelease desc r⟩ + · have ⟨ev, child', hSub⟩ := parStep_progress_of_free hFree child hDone + exact ⟨ev, .resActive desc child', .resStep hSub⟩ +termination_by rt => sizeOf rt +decreasing_by + all_goals + simp_wf + first + | omega + | (have := list_mem_sizeOf_lt c cs (by rw [hEq]; simp); omega) + +/-- **Theorem 4a (Deadlock Freedom)**: + For any worker capacity `cap ≥ 1` and any reachable state `rt` (including + arbitrarily nested `withResource` and `sequential` blocks), either `rt` is + already `.done` or at least one `MachineStep` is enabled. -/ +theorem progress_deadlock_free {cap : Nat} (hCap : cap ≥ 1) + {plan : PurePlan} {tr : List Event} {rt : RT} + (hTrace : Trace cap (RT.ofPlan plan) tr rt) (hNotDone : ¬ rt.isDone) : + ∃ ev rt', MachineStep cap rt ev rt' := by + have hBound := bounded_concurrency hTrace + by_cases hActive : activeWorkers rt > 0 + · exact parStep_progress_of_active (cap - activeWorkers rt) rt hActive + · have hFree : cap - activeWorkers rt ≥ 1 := by omega + exact parStep_progress_of_free hFree rt hNotDone + +mutual + +theorem seqStep_remainingSteps {rt rt' : RT} {ev : Event} : + SeqStep rt ev rt' → remainingSteps rt' + 1 = remainingSteps rt + | .startLeaf .. => by simp [remainingSteps] + | .finishLeaf .. => by simp [remainingSteps] + | .groupStep hG => by + have ih := seqGroupStep_remainingSteps hG + simp only [remainingSteps] + omega + | .groupCollapse hDone => by simp [remainingSteps, allDoneReports_remainingSteps hDone] + | .startSeq plan => by simp [remainingSteps, remainingSteps_ofPlan]; omega + | .stepSeq hSub => by + have ih := seqStep_remainingSteps hSub + simp only [remainingSteps] + omega + | .finishSeq _ => by simp [remainingSteps] + | .resAcqOk _ _ _ child => by simp [remainingSteps, remainingSteps_ofPlan]; omega + | .resAcqFail .. => by simp [remainingSteps] + | .resStep hSub => by + have ih := seqStep_remainingSteps hSub + simp only [remainingSteps] + omega + | .resRelease .. => by simp [remainingSteps] + +theorem seqGroupStep_remainingSteps {cs cs' : List RT} {ev : Event} : + SeqGroupStep cs ev cs' → remainingStepsChildren cs' + 1 = remainingStepsChildren cs + | .head hSub => by + have ih := seqStep_remainingSteps hSub + simp only [remainingStepsChildren] + omega + | .skipDone hSub => by + have ih := seqGroupStep_remainingSteps hSub + simp only [remainingStepsChildren, remainingSteps] + omega + +end + +theorem parStep_remainingSteps {free : Nat} {rt rt' : RT} {ev : Event} + (h : ParStep free rt ev rt') : + remainingSteps rt' + 1 = remainingSteps rt := by + induction h with + | startLeaf => simp [remainingSteps] + | finishLeaf => simp [remainingSteps] + | groupStep _ ih => + simp only [remainingSteps, remainingStepsChildren_append, remainingStepsChildren] + omega + | groupCollapse hDone => simp [remainingSteps, allDoneReports_remainingSteps hDone] + | startSeq plan _ => simp [remainingSteps, remainingSteps_ofPlan]; omega + | stepSeq hSub => + have ih := seqStep_remainingSteps hSub + simp only [remainingSteps] + omega + | finishSeq => simp [remainingSteps] + | resAcqOk _ _ _ child => simp [remainingSteps, remainingSteps_ofPlan]; omega + | resAcqFail => simp [remainingSteps] + | resStep _ ih => simp only [remainingSteps]; omega + | resRelease => simp [remainingSteps] + +private theorem trace_remainingSteps {cap : Nat} {rt₀ rt : RT} {tr : List Event} + (hTrace : Trace cap rt₀ tr rt) : + tr.length + remainingSteps rt = remainingSteps rt₀ := by + induction hTrace with + | refl _ => simp + | step hStep _ ih => + have hDec := parStep_remainingSteps hStep + simp only [List.length_cons] + omega + +/-- **Theorem 4b (Strong Normalization / Termination Bound)**: + Every execution trace from `RT.ofPlan plan` strictly consumes `planSteps plan` + and therefore must terminate in at most `planSteps plan` steps. -/ +theorem termination_step_bound {cap : Nat} {plan : PurePlan} {tr : List Event} {rt : RT} + (hTrace : Trace cap (RT.ofPlan plan) tr rt) : + tr.length + remainingSteps rt = planSteps plan := by + rw [trace_remainingSteps hTrace, remainingSteps_ofPlan] + +/-! ## Theorem 5: Sequential–Parallel Equivalence (Determinism / Confluence) -/ + +mutual + +theorem seqStep_preserves_denote {rt rt' : RT} {ev : Event} : + SeqStep rt ev rt' → denote rt' = denote rt + | .startLeaf .. => by simp [denote] + | .finishLeaf .. => by simp [denote] + | .groupStep hG => by + simp only [denote, seqGroupStep_preserves_denote hG] + | .groupCollapse hDone => by simp [denote, allDoneReports_denote hDone] + | .startSeq plan => by simp [denote, denote_ofPlan] + | .stepSeq hSub => by simp only [denote, seqStep_preserves_denote hSub] + | .finishSeq _ => by simp [denote] + | .resAcqOk _ _ _ child => by simp [denote, denote_ofPlan] + | .resAcqFail .. => by simp [denote] + | .resStep hSub => by simp only [denote, seqStep_preserves_denote hSub] + | .resRelease .. => by simp [denote] + +theorem seqGroupStep_preserves_denote {cs cs' : List RT} {ev : Event} : + SeqGroupStep cs ev cs' → denoteChildren cs' = denoteChildren cs + | .head hSub => by simp only [denoteChildren, seqStep_preserves_denote hSub] + | .skipDone hSub => by simp only [denoteChildren, seqGroupStep_preserves_denote hSub] + +end + +theorem parStep_preserves_denote {free : Nat} {rt rt' : RT} {ev : Event} + (h : ParStep free rt ev rt') : + denote rt' = denote rt := by + induction h with + | startLeaf => simp [denote] + | finishLeaf => simp [denote] + | groupStep _ ih => + simp only [denote, denoteChildren_append, denoteChildren, ih] + | groupCollapse hDone => simp [denote, allDoneReports_denote hDone] + | startSeq plan _ => simp [denote, denote_ofPlan] + | stepSeq hSub => + simp only [denote] + exact seqStep_preserves_denote hSub + | finishSeq => simp [denote] + | resAcqOk _ _ _ child => simp [denote, denote_ofPlan] + | resAcqFail => simp [denote] + | resStep _ ih => simp only [denote, ih] + | resRelease => simp [denote] + +theorem trace_preserves_denote {cap : Nat} {rt rt' : RT} {tr : List Event} + (hTrace : Trace cap rt tr rt') : + denote rt' = denote rt := by + induction hTrace with + | refl _ => rfl + | step hStep _ ih => exact ih.trans (parStep_preserves_denote hStep) + +/-- **Theorem 5 (Sequential–Parallel Equivalence / Confluence)**: + For ANY thread limit `cap ≥ 1` and ANY interleaving `tr` terminating at `.done r`, + the resulting `ReportTree` and `RunSummary` are identical to canonical sequential + evaluation `evalSeq plan`. -/ +theorem parallel_eq_sequential {cap : Nat} {plan : PurePlan} {tr : List Event} {r : ReportTree} + (hTrace : Trace cap (RT.ofPlan plan) tr (.done r)) + (d : Nat := 0) (sd : UInt64 := 0) (th : Nat := 1) : + r = evalSeq plan ∧ r.summarize d sd th = (evalSeq plan).summarize d sd th := by + have hDen := trace_preserves_denote hTrace + simp only [denote, denote_ofPlan] at hDen + exact ⟨hDen, congrArg (·.summarize d sd th) hDen⟩ + +end +end LSpec.Proofs.Concurrency diff --git a/LSpecProofs/Filter.lean b/LSpecProofs/Filter.lean new file mode 100644 index 0000000..6210a4d --- /dev/null +++ b/LSpecProofs/Filter.lean @@ -0,0 +1,499 @@ +module +public import LSpec.Runner + +/-! +# Formal Correctness of `TestFilter`, `filterTree`, and `listTests` + +Direct kernel-checked theorems on the executable functions in `LSpec.Runner`: +- Soundness & completeness of `filterTree` relative to `listTests` +- Empty filter identity and exclusion dominance +- Exact `none` characterization (no matching leaves) +- Non-emptiness of every surviving `withResource` / `group` subtree (filtered-out + resources are never acquired) +- Idempotence of `filterTree` +-/ + +namespace LSpec.Proofs +public section + +open LSpec + +private theorem array_toList_sizeOf_lt [SizeOf α] (a : Array α) : + sizeOf a.toList < sizeOf a := by + cases a; simp + +private theorem array_any_empty {α : Type _} (a : Array α) (p : α → Bool) + (h : a.isEmpty = true) : a.any p = false := by + cases a with + | mk xs => + cases xs with + | nil => simp + | cons _ _ => simp [Array.isEmpty] at h + +/-! ## `TestFilter.matchesTest` Properties -/ + +theorem matchesTest_empty (f : TestFilter) (h : f.isEmpty = true) + (path tags : Array String) : f.matchesTest path tags = true := by + simp only [TestFilter.isEmpty, Bool.and_eq_true] at h + obtain ⟨⟨⟨⟨hInc, hEx⟩, hExc⟩, hIT⟩, hET⟩ := h + simp only [TestFilter.matchesTest, hInc, hEx, hIT] + rw [array_any_empty f.excludes _ hExc, array_any_empty f.excludeTags _ hET] + simp + +theorem matchesTest_excludeTag_rejects (f : TestFilter) (path tags : Array String) + {t : String} (htf : t ∈ f.excludeTags.toList) (htt : t ∈ tags.toList) : + f.matchesTest path tags = false := by + simp only [TestFilter.matchesTest] + have hContains : tags.contains t = true := by + rw [Array.contains_iff_exists_mem_beq] + exact ⟨t, Array.mem_def.mpr htt, beq_self_eq_true t⟩ + have hAny : f.excludeTags.any (tags.contains ·) = true := by + rw [Array.any_eq_true] + have hMem : t ∈ f.excludeTags := Array.mem_def.mpr htf + obtain ⟨i, hi, rfl⟩ := Array.mem_iff_getElem.mp hMem + exact ⟨i, hi, hContains⟩ + rw [hAny] + simp + +theorem matchesTest_exclude_rejects (f : TestFilter) (path tags : Array String) + {pat : String} (hpf : pat ∈ f.excludes.toList) + (hSub : containsSubstr ("/".intercalate path.toList) pat = true) : + f.matchesTest path tags = false := by + simp only [TestFilter.matchesTest] + have hAny : f.excludes.any (containsSubstr ("/".intercalate path.toList) ·) = true := by + rw [Array.any_eq_true] + have hMem : pat ∈ f.excludes := Array.mem_def.mpr hpf + obtain ⟨i, hi, rfl⟩ := Array.mem_iff_getElem.mp hMem + exact ⟨i, hi, hSub⟩ + rw [hAny] + simp + +/-! ## `filterTree` Soundness & Completeness -/ + +theorem filterTree_empty (f : TestFilter) (h : f.isEmpty = true) (t : TestTree) : + filterTree f t = some t := by + simp [filterTree, h] + +mutual + +theorem listTestsGo_filterTreeGo (f : TestFilter) (path tags : Array String) + (mode : ExecutionMode) (t : TestTree) : + ((filterTreeGo f path tags t).map (listTestsGo path tags mode)).getD [] = + (listTestsGo path tags mode t).filter (fun lt => f.matchesTest lt.path lt.tags) := by + cases t with + | leaf name leafTags exec => + simp only [filterTreeGo, listTestsGo] + cases hM : f.matchesTest (if name.isEmpty then path else path.push name) (tags ++ leafTags) with + | true => simp only [ite_true, Option.map_some, Option.getD_some, listTestsGo, List.filter, hM] + | false => simp only [Bool.false_eq_true, ite_false, Option.map_none, Option.getD_none, List.filter, hM] + | group name children => + simp only [filterTreeGo, listTestsGo] + have ih := listTestsChildren_filterTreeChildren f + (if name.isEmpty then path else path.push name) tags mode children.toList + cases hKept : filterTreeChildren f (if name.isEmpty then path else path.push name) tags children.toList with + | nil => + rw [hKept] at ih + simp only [listTestsChildren] at ih + simp [ih] + | cons c cs => + rw [hKept] at ih + simp only [List.isEmpty_cons, Bool.false_eq_true, ite_false, Option.map_some, + Option.getD_some, listTestsGo] + exact ih + | withMode m child => + have ih := listTestsGo_filterTreeGo f path tags (ExecutionMode.combine mode m) child + simp only [filterTreeGo, listTestsGo] + cases h : filterTreeGo f path tags child with + | none => rw [h] at ih; simpa using ih + | some c' => rw [h] at ih; simpa [listTestsGo] using ih + | withTags more child => + have ih := listTestsGo_filterTreeGo f path (tags ++ more) mode child + simp only [filterTreeGo, listTestsGo] + cases h : filterTreeGo f path (tags ++ more) child with + | none => rw [h] at ih; simpa using ih + | some c' => rw [h] at ih; simpa [listTestsGo] using ih + | withOptions optFn child => + have ih := listTestsGo_filterTreeGo f path tags mode child + simp only [filterTreeGo, listTestsGo] + cases h : filterTreeGo f path tags child with + | none => rw [h] at ih; simpa using ih + | some c' => rw [h] at ih; simpa [listTestsGo] using ih + | aroundEach wrap child => + have ih := listTestsGo_filterTreeGo f path tags mode child + simp only [filterTreeGo, listTestsGo] + cases h : filterTreeGo f path tags child with + | none => rw [h] at ih; simpa using ih + | some c' => rw [h] at ih; simpa [listTestsGo] using ih + | withResource desc acq child => + have ih := listTestsGo_filterTreeGo f path tags mode child + simp only [filterTreeGo, listTestsGo] + cases h : filterTreeGo f path tags child with + | none => rw [h] at ih; simpa using ih + | some c' => rw [h] at ih; simpa [listTestsGo] using ih +termination_by sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +theorem listTestsChildren_filterTreeChildren (f : TestFilter) (path tags : Array String) + (mode : ExecutionMode) (cs : List TestTree) : + listTestsChildren path tags mode (filterTreeChildren f path tags cs) = + (listTestsChildren path tags mode cs).filter (fun lt => f.matchesTest lt.path lt.tags) := by + cases cs with + | nil => simp [filterTreeChildren, listTestsChildren] + | cons c rest => + have ihHead := listTestsGo_filterTreeGo f path tags mode c + have ihTail := listTestsChildren_filterTreeChildren f path tags mode rest + simp only [filterTreeChildren, listTestsChildren, List.filter_append] + cases h : filterTreeGo f path tags c with + | none => + rw [h] at ihHead + simp only [Option.map_none, Option.getD_none] at ihHead + rw [← ihHead, List.nil_append, ihTail] + | some c' => + rw [h] at ihHead + simp only [Option.map_some, Option.getD_some] at ihHead + simp only [listTestsChildren, ihHead, ihTail] +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- **Main Filter Soundness & Completeness Theorem**: + Listing tests after `filterTree f t` yields the exact declaration-ordered + subsequence of `listTests t` satisfying `f.matchesTest`. -/ +theorem listTests_filterTree_eq (f : TestFilter) (t : TestTree) + (mode : ExecutionMode := .parallel) : + ((filterTree f t).map (listTests · mode)).getD #[] = + (listTests t mode).filter (fun lt => f.matchesTest lt.path lt.tags) := by + unfold filterTree listTests + by_cases hEmpty : f.isEmpty = true + · simp only [hEmpty, ite_true, Option.map_some, Option.getD_some] + apply Array.ext' + simp only [Array.toList_filter] + symm + apply List.filter_eq_self.mpr + intro lt _ + exact matchesTest_empty f hEmpty lt.path lt.tags + · have hFalse : f.isEmpty = false := Bool.eq_false_iff.mpr hEmpty + simp only [hFalse, Bool.false_eq_true, ite_false] + have hGo := listTestsGo_filterTreeGo f #[] #[] mode t + cases h : filterTreeGo f #[] #[] t with + | none => + rw [h] at hGo + simp only [Option.map_none, Option.getD_none] at hGo + apply Array.ext' + simp [← hGo] + | some t' => + rw [h] at hGo + simp only [Option.map_some, Option.getD_some] at hGo + apply Array.ext' + simp [hGo] + +/-! ## Non-emptiness & Zero Filtered-Out Resource Acquisition -/ + +mutual + +/-- Structural predicate stating that every `.group` and `.withResource` node + in `t` contains at least one leaf (so no empty resource block can be acquired). -/ +def NoEmptyScopes : TestTree → Prop + | .leaf _ _ _ => True + | .group _ children => children.toList ≠ [] ∧ NoEmptyScopesChildren children.toList + | .withMode _ child => NoEmptyScopes child + | .withTags _ child => NoEmptyScopes child + | .withOptions _ child => NoEmptyScopes child + | .aroundEach _ child => NoEmptyScopes child + | .withResource _ _ child => NoEmptyScopes child +termination_by t => sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +def NoEmptyScopesChildren : List TestTree → Prop + | [] => True + | c :: cs => NoEmptyScopes c ∧ NoEmptyScopesChildren cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +theorem listTestsGo_nonempty_of_noEmptyScopes (path tags : Array String) (mode : ExecutionMode) : + (t : TestTree) → NoEmptyScopes t → listTestsGo path tags mode t ≠ [] + | .leaf name leafTags exec, _ => by simp [listTestsGo] + | .group name children, h => by + simp only [NoEmptyScopes] at h + obtain ⟨hNe, hKids⟩ := h + cases hList : children.toList with + | nil => exact absurd hList hNe + | cons c cs => + rw [hList] at hKids + simp only [NoEmptyScopesChildren] at hKids + have hHead := listTestsGo_nonempty_of_noEmptyScopes + (if name.isEmpty then path else path.push name) tags mode c hKids.1 + simp only [listTestsGo, hList, listTestsChildren] + intro hApp + exact hHead (List.append_eq_nil_iff.mp hApp).1 + | .withMode m child, h => by + simp only [NoEmptyScopes] at h + simp only [listTestsGo] + exact listTestsGo_nonempty_of_noEmptyScopes path tags (ExecutionMode.combine mode m) child h + | .withTags more child, h => by + simp only [NoEmptyScopes] at h + simp only [listTestsGo] + exact listTestsGo_nonempty_of_noEmptyScopes path (tags ++ more) mode child h + | .withOptions _ child, h => by + simp only [NoEmptyScopes] at h + simp only [listTestsGo] + exact listTestsGo_nonempty_of_noEmptyScopes path tags mode child h + | .aroundEach _ child, h => by + simp only [NoEmptyScopes] at h + simp only [listTestsGo] + exact listTestsGo_nonempty_of_noEmptyScopes path tags mode child h + | .withResource _ _ child, h => by + simp only [NoEmptyScopes] at h + simp only [listTestsGo] + exact listTestsGo_nonempty_of_noEmptyScopes path tags mode child h +termination_by t => sizeOf t +decreasing_by + all_goals + simp_wf + first + | done + | omega + | (have h1 := array_toList_sizeOf_lt children; rw [hList] at h1; simp at h1; omega) + +mutual + +theorem filterTreeGo_noEmptyScopes (f : TestFilter) (path tags : Array String) : + (t : TestTree) → (t' : TestTree) → filterTreeGo f path tags t = some t' → NoEmptyScopes t' + | .leaf name leafTags exec, t', h => by + simp only [filterTreeGo] at h + cases hM : f.matchesTest (if name.isEmpty then path else path.push name) (tags ++ leafTags) with + | true => + rw [hM] at h + simp only [ite_true, Option.some.injEq] at h + subst h + simp [NoEmptyScopes] + | false => + rw [hM] at h + simp at h + | .group name children, t', h => by + simp only [filterTreeGo] at h + cases hKept : filterTreeChildren f (if name.isEmpty then path else path.push name) tags children.toList with + | nil => rw [hKept] at h; simp at h + | cons c cs => + rw [hKept] at h + simp only [List.isEmpty_cons, Bool.false_eq_true, ite_false, Option.some.injEq] at h + subst h + have hKids := filterTreeChildren_noEmptyScopes f + (if name.isEmpty then path else path.push name) tags children.toList + rw [hKept] at hKids + simp [NoEmptyScopes, hKids] + | .withMode m child, t', h => by + simp only [filterTreeGo, Option.map_eq_some_iff] at h + obtain ⟨c', hc', rfl⟩ := h + simp only [NoEmptyScopes] + exact filterTreeGo_noEmptyScopes f path tags child c' hc' + | .withTags more child, t', h => by + simp only [filterTreeGo, Option.map_eq_some_iff] at h + obtain ⟨c', hc', rfl⟩ := h + simp only [NoEmptyScopes] + exact filterTreeGo_noEmptyScopes f path (tags ++ more) child c' hc' + | .withOptions optFn child, t', h => by + simp only [filterTreeGo, Option.map_eq_some_iff] at h + obtain ⟨c', hc', rfl⟩ := h + simp only [NoEmptyScopes] + exact filterTreeGo_noEmptyScopes f path tags child c' hc' + | .aroundEach wrap child, t', h => by + simp only [filterTreeGo, Option.map_eq_some_iff] at h + obtain ⟨c', hc', rfl⟩ := h + simp only [NoEmptyScopes] + exact filterTreeGo_noEmptyScopes f path tags child c' hc' + | .withResource desc acq child, t', h => by + simp only [filterTreeGo, Option.map_eq_some_iff] at h + obtain ⟨c', hc', rfl⟩ := h + simp only [NoEmptyScopes] + exact filterTreeGo_noEmptyScopes f path tags child c' hc' +termination_by t => sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +theorem filterTreeChildren_noEmptyScopes (f : TestFilter) (path tags : Array String) + (cs : List TestTree) : + NoEmptyScopesChildren (filterTreeChildren f path tags cs) := by + cases cs with + | nil => simp [filterTreeChildren, NoEmptyScopesChildren] + | cons c rest => + simp only [filterTreeChildren] + cases h : filterTreeGo f path tags c with + | none => exact filterTreeChildren_noEmptyScopes f path tags rest + | some c' => + simp only [NoEmptyScopesChildren] + exact ⟨filterTreeGo_noEmptyScopes f path tags c c' h, + filterTreeChildren_noEmptyScopes f path tags rest⟩ +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- When `filterTreeGo` returns `some t'`, `t'` contains at least one matching leaf. -/ +theorem filterTreeGo_some_nonempty (f : TestFilter) (path tags : Array String) + (mode : ExecutionMode) (t t' : TestTree) (h : filterTreeGo f path tags t = some t') : + listTestsGo path tags mode t' ≠ [] := + listTestsGo_nonempty_of_noEmptyScopes path tags mode t' + (filterTreeGo_noEmptyScopes f path tags t t' h) + +/-- Exact characterization of when `filterTreeGo` prunes a subtree completely. -/ +theorem filterTreeGo_eq_none_iff (f : TestFilter) (path tags : Array String) + (mode : ExecutionMode) (t : TestTree) : + filterTreeGo f path tags t = none ↔ + ∀ lt ∈ listTestsGo path tags mode t, f.matchesTest lt.path lt.tags = false := by + have hList := listTestsGo_filterTreeGo f path tags mode t + constructor + · intro hNone + rw [hNone] at hList + simp only [Option.map_none, Option.getD_none] at hList + intro lt hMem + cases hMatch : f.matchesTest lt.path lt.tags with + | false => rfl + | true => + have hIn : lt ∈ (listTestsGo path tags mode t).filter (fun lt => f.matchesTest lt.path lt.tags) := + List.mem_filter.mpr ⟨hMem, hMatch⟩ + rw [← hList] at hIn + cases hIn + · intro hAllFalse + cases hRes : filterTreeGo f path tags t with + | none => rfl + | some t' => + have hNonEmpty := filterTreeGo_some_nonempty f path tags mode t t' hRes + rw [hRes] at hList + simp only [Option.map_some, Option.getD_some] at hList + have hFilterNil : (listTestsGo path tags mode t).filter (fun lt => f.matchesTest lt.path lt.tags) = [] := by + rw [List.filter_eq_nil_iff] + intro lt hMem + simp [hAllFalse lt hMem] + rw [hFilterNil] at hList + exact absurd hList hNonEmpty + +/-- For any non-empty filter, `filterTree f t = none` iff no leaf in `t` matches `f`. + In particular, `runTree` never executes `compilePlan` or acquires any `withResource` + when no leaf matches. -/ +theorem filterTree_eq_none_iff (f : TestFilter) (hNe : f.isEmpty = false) + (t : TestTree) (mode : ExecutionMode := .parallel) : + filterTree f t = none ↔ + ∀ lt ∈ (listTests t mode).toList, f.matchesTest lt.path lt.tags = false := by + simp only [filterTree, hNe, Bool.false_eq_true, ite_false, listTests, List.toList_toArray] + exact filterTreeGo_eq_none_iff f #[] #[] mode t + +/-- Every surviving `.withResource` in a filtered tree has at least one matching leaf. -/ +theorem filterTree_withResource_has_leaf (f : TestFilter) (hNe : f.isEmpty = false) + (t : TestTree) {desc : String} {acq : IO (IO Unit)} {child : TestTree} + (h : filterTree f t = some (.withResource desc acq child)) + (mode : ExecutionMode := .parallel) : + (listTests child mode).size > 0 := by + simp only [filterTree, hNe, Bool.false_eq_true, ite_false] at h + have hNeList := filterTreeGo_some_nonempty f #[] #[] mode t (.withResource desc acq child) h + simp only [listTestsGo] at hNeList + simp only [listTests, List.size_toArray] + exact List.length_pos_iff.mpr hNeList + +/-! ## `filterTree` Idempotence -/ + +mutual + +theorem filterTreeGo_idempotent (f : TestFilter) (path tags : Array String) (t : TestTree) : + (filterTreeGo f path tags t).bind (filterTreeGo f path tags) = filterTreeGo f path tags t := by + cases t with + | leaf name leafTags exec => + simp only [filterTreeGo] + cases hM : f.matchesTest (if name.isEmpty then path else path.push name) (tags ++ leafTags) with + | true => + simp only [ite_true, Option.bind_some, filterTreeGo, hM] + | false => + simp only [Bool.false_eq_true, ite_false, Option.bind_none] + | group name children => + simp only [filterTreeGo] + have ih := filterTreeChildren_idempotent f + (if name.isEmpty then path else path.push name) tags children.toList + cases hKept : filterTreeChildren f (if name.isEmpty then path else path.push name) tags children.toList with + | nil => simp + | cons c cs => + rw [hKept] at ih + simp only [List.isEmpty_cons, Bool.false_eq_true, ite_false, Option.bind_some, + filterTreeGo, ih] + | withMode m child => + have ih := filterTreeGo_idempotent f path tags child + simp only [filterTreeGo] + cases h : filterTreeGo f path tags child with + | none => simp + | some c' => + rw [h] at ih + simp only [Option.bind_some] at ih + simp [filterTreeGo, ih] + | withTags more child => + have ih := filterTreeGo_idempotent f path (tags ++ more) child + simp only [filterTreeGo] + cases h : filterTreeGo f path (tags ++ more) child with + | none => simp + | some c' => + rw [h] at ih + simp only [Option.bind_some] at ih + simp [filterTreeGo, ih] + | withOptions optFn child => + have ih := filterTreeGo_idempotent f path tags child + simp only [filterTreeGo] + cases h : filterTreeGo f path tags child with + | none => simp + | some c' => + rw [h] at ih + simp only [Option.bind_some] at ih + simp [filterTreeGo, ih] + | aroundEach wrap child => + have ih := filterTreeGo_idempotent f path tags child + simp only [filterTreeGo] + cases h : filterTreeGo f path tags child with + | none => simp + | some c' => + rw [h] at ih + simp only [Option.bind_some] at ih + simp [filterTreeGo, ih] + | withResource desc acq child => + have ih := filterTreeGo_idempotent f path tags child + simp only [filterTreeGo] + cases h : filterTreeGo f path tags child with + | none => simp + | some c' => + rw [h] at ih + simp only [Option.bind_some] at ih + simp [filterTreeGo, ih] +termination_by sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +theorem filterTreeChildren_idempotent (f : TestFilter) (path tags : Array String) + (cs : List TestTree) : + filterTreeChildren f path tags (filterTreeChildren f path tags cs) = + filterTreeChildren f path tags cs := by + cases cs with + | nil => simp [filterTreeChildren] + | cons c rest => + have ihHead := filterTreeGo_idempotent f path tags c + have ihTail := filterTreeChildren_idempotent f path tags rest + simp only [filterTreeChildren] + cases h : filterTreeGo f path tags c with + | none => exact ihTail + | some c' => + rw [h] at ihHead + simp only [Option.bind_some] at ihHead + simp only [filterTreeChildren, ihHead, ihTail] +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- Filtering twice with the same `TestFilter` is identical to filtering once. -/ +theorem filterTree_idempotent (f : TestFilter) (t : TestTree) : + (filterTree f t).bind (filterTree f) = filterTree f t := by + unfold filterTree + by_cases hEmpty : f.isEmpty = true + · simp [hEmpty] + · have hFalse : f.isEmpty = false := Bool.eq_false_iff.mpr hEmpty + simp only [hFalse, Bool.false_eq_true, ite_false] + exact filterTreeGo_idempotent f #[] #[] t + +end +end LSpec.Proofs diff --git a/LSpecProofs/Report.lean b/LSpecProofs/Report.lean new file mode 100644 index 0000000..10af15a --- /dev/null +++ b/LSpecProofs/Report.lean @@ -0,0 +1,407 @@ +module +public import LSpec.Runner + +/-! +# Formal Correctness of `ReportTree`, `RunSummary`, `compilePlan`, and Worker Bounds + +Direct kernel-checked theorems on the executable functions in `LSpec.Runner`: +- Exact report accounting: `passed + failed + skipped = leafCount = leaves.size` +- Exact failure accounting: `summary.failed = report.failures.size` and + `summary.allPassed = true ↔ report.failures.isEmpty` +- Permutation invariance of `summarizeChildren` (parallel completion order cannot + alter aggregate counts) +- `compilePlan` preserves the exact `(path, tags, mode)` sequence of `listTests` + and assigns deterministic seeds `deriveTestSeed masterSeed path` to every leaf +- `ExecPlan.skipAll` produces zero passes/failures and skips every leaf +- `computeWorkerCount` bounds: `1 ≤ workers ≤ max 1 threads` and `workers ≤ max 1 leaves` +-/ + +namespace LSpec.Proofs +public section + +open LSpec + +private theorem array_toList_sizeOf_lt [SizeOf α] (a : Array α) : + sizeOf a.toList < sizeOf a := by + cases a; simp + +/-! ## `ReportTree` Accounting Invariants -/ + +mutual + +theorem leafCount_eq_leavesList_length (r : ReportTree) : + r.leafCount = r.leavesList.length := by + cases r with + | leaf rep => simp [ReportTree.leafCount, ReportTree.leavesList] + | group _ children => + simp only [ReportTree.leafCount, ReportTree.leavesList] + exact leafCountChildren_eq_leavesChildren_length children.toList +termination_by sizeOf r +decreasing_by all_goals (simp_wf; first | done | (have := array_toList_sizeOf_lt children; omega)) + +theorem leafCountChildren_eq_leavesChildren_length (cs : List ReportTree) : + ReportTree.leafCountChildren cs = (ReportTree.leavesChildren cs).length := by + cases cs with + | nil => simp [ReportTree.leafCountChildren, ReportTree.leavesChildren] + | cons c rest => + simp only [ReportTree.leafCountChildren, ReportTree.leavesChildren, List.length_append] + rw [leafCount_eq_leavesList_length c, leafCountChildren_eq_leavesChildren_length rest] +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +theorem leafCount_eq_leaves_size (r : ReportTree) : + r.leafCount = r.leaves.size := by + simp [ReportTree.leaves, leafCount_eq_leavesList_length] + +mutual + +theorem failuresList_eq_filter_leavesList (r : ReportTree) : + r.failuresList = r.leavesList.filter (·.result.isFailed) := by + cases r with + | leaf rep => + simp only [ReportTree.failuresList, ReportTree.leavesList, List.filter] + cases rep.result.isFailed <;> rfl + | group _ children => + simp only [ReportTree.failuresList, ReportTree.leavesList] + exact failuresChildren_eq_filter_leavesChildren children.toList +termination_by sizeOf r +decreasing_by all_goals (simp_wf; first | done | (have := array_toList_sizeOf_lt children; omega)) + +theorem failuresChildren_eq_filter_leavesChildren (cs : List ReportTree) : + ReportTree.failuresChildren cs = (ReportTree.leavesChildren cs).filter (·.result.isFailed) := by + cases cs with + | nil => simp [ReportTree.failuresChildren, ReportTree.leavesChildren] + | cons c rest => + simp only [ReportTree.failuresChildren, ReportTree.leavesChildren, List.filter_append] + rw [failuresList_eq_filter_leavesList c, failuresChildren_eq_filter_leavesChildren rest] +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +theorem failures_eq_filter_leaves (r : ReportTree) : + r.failures = r.leaves.filter (·.result.isFailed) := by + unfold ReportTree.failures ReportTree.leaves + apply Array.ext' + simp [failuresList_eq_filter_leavesList] + +mutual + +theorem summarizeGo_total (r : ReportTree) : + let (p, f, s) := r.summarizeGo + p + f + s = r.leafCount := by + cases r with + | leaf rep => + simp only [ReportTree.summarizeGo, ReportTree.leafCount] + cases rep.result.outcome <;> rfl + | group _ children => + simp only [ReportTree.summarizeGo, ReportTree.leafCount] + exact summarizeChildren_total children.toList +termination_by sizeOf r +decreasing_by all_goals (simp_wf; first | done | (have := array_toList_sizeOf_lt children; omega)) + +theorem summarizeChildren_total (cs : List ReportTree) : + let (p, f, s) := ReportTree.summarizeChildren cs + p + f + s = ReportTree.leafCountChildren cs := by + cases cs with + | nil => simp [ReportTree.summarizeChildren, ReportTree.leafCountChildren] + | cons c rest => + have ih1 := summarizeGo_total c + have ih2 := summarizeChildren_total rest + simp only [ReportTree.summarizeChildren, ReportTree.leafCountChildren] + omega +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- Every leaf in a `ReportTree` is accounted for in `passed + failed + skipped`. -/ +theorem summarize_total_eq_leafCount (r : ReportTree) (d : Nat) (sd : UInt64) (th : Nat) : + (r.summarize d sd th).total = r.leafCount := by + simp only [ReportTree.summarize, RunSummary.total] + exact summarizeGo_total r + +mutual + +theorem summarizeGo_failed (r : ReportTree) : + r.summarizeGo.2.1 = r.failuresList.length := by + cases r with + | leaf rep => + rcases rep with ⟨_, _, _, ⟨out, _, _⟩, _, _⟩ + cases out <;> simp [ReportTree.summarizeGo, ReportTree.failuresList, TestResult.isFailed] + | group _ children => + simp only [ReportTree.summarizeGo, ReportTree.failuresList] + exact summarizeChildren_failed children.toList +termination_by sizeOf r +decreasing_by all_goals (simp_wf; first | done | (have := array_toList_sizeOf_lt children; omega)) + +theorem summarizeChildren_failed (cs : List ReportTree) : + (ReportTree.summarizeChildren cs).2.1 = (ReportTree.failuresChildren cs).length := by + cases cs with + | nil => simp [ReportTree.summarizeChildren, ReportTree.failuresChildren] + | cons c rest => + have ih1 := summarizeGo_failed c + have ih2 := summarizeChildren_failed rest + simp only [ReportTree.summarizeChildren, ReportTree.failuresChildren, List.length_append] + rw [ih1, ih2] +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- The summary's `failed` count equals `report.failures.size`. -/ +theorem summarize_failed_eq_failures_size (r : ReportTree) (d : Nat) (sd : UInt64) (th : Nat) : + (r.summarize d sd th).failed = r.failures.size := by + simp only [ReportTree.summarize, ReportTree.failures, List.size_toArray] + exact summarizeGo_failed r + +/-- `allPassed` holds iff `report.failures` is empty. -/ +theorem summarize_allPassed_iff_failures_empty (r : ReportTree) (d : Nat) (sd : UInt64) (th : Nat) : + (r.summarize d sd th).allPassed = true ↔ r.failures.isEmpty = true := by + simp only [RunSummary.allPassed, beq_iff_eq, summarize_failed_eq_failures_size, + Array.isEmpty_iff_size_eq_zero] + +/-- `allPassed` holds iff no leaf in `report` failed. -/ +theorem summarize_allPassed_iff_forall (r : ReportTree) (d : Nat) (sd : UInt64) (th : Nat) : + (r.summarize d sd th).allPassed = true ↔ + ∀ rep ∈ r.leaves.toList, rep.result.isFailed = false := by + rw [summarize_allPassed_iff_failures_empty] + simp only [ReportTree.failures, ReportTree.leaves, Array.isEmpty_iff_size_eq_zero, + List.size_toArray, List.toList_toArray, List.length_eq_zero_iff, + failuresList_eq_filter_leavesList, List.filter_eq_nil_iff, Bool.not_eq_true] + +/-! ## Order-Independence (Permutation Invariance) of Summary Counts -/ + +theorem summarizeChildren_append (xs ys : List ReportTree) : + ReportTree.summarizeChildren (xs ++ ys) = + let (p1, f1, s1) := ReportTree.summarizeChildren xs + let (p2, f2, s2) := ReportTree.summarizeChildren ys + (p1 + p2, f1 + f2, s1 + s2) := by + induction xs with + | nil => simp [ReportTree.summarizeChildren] + | cons x rest ih => + simp only [List.cons_append, ReportTree.summarizeChildren, ih] + simp only [Prod.mk.injEq] + omega + +theorem summarizeChildren_perm {xs ys : List ReportTree} (h : List.Perm xs ys) : + ReportTree.summarizeChildren xs = ReportTree.summarizeChildren ys := by + induction h with + | nil => rfl + | cons x _ ih => + simp only [ReportTree.summarizeChildren, ih] + | swap x y l => + simp only [ReportTree.summarizeChildren, Prod.mk.injEq] + omega + | trans _ _ ih1 ih2 => + exact ih1.trans ih2 + +/-! ## `compilePlan` Consistency with `listTests` and Seed Determinism -/ + +mutual + +theorem toListedList_compilePlanGo (masterSeed : UInt64) (opts : TestOptions) + (path tags : Array String) (mode : ExecutionMode) + (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) + (t : TestTree) : + (compilePlanGo masterSeed opts path tags mode wrap t).toListedList mode = + listTestsGo path tags mode t := by + cases t with + | leaf name leafTags exec => + simp [compilePlanGo, ExecPlan.toListedList, listTestsGo] + | group name children => + simp only [compilePlanGo, ExecPlan.toListedList, listTestsGo] + exact toListedChildren_compilePlanChildren masterSeed opts + (if name.isEmpty then path else path.push name) tags mode wrap children.toList + | withMode m child => + have ih := toListedList_compilePlanGo masterSeed opts path tags + (ExecutionMode.combine mode m) wrap child + cases mode <;> cases m <;> + · unfold compilePlanGo + simp only [listTestsGo, ExecutionMode.combine, ExecPlan.toListedList] at ih ⊢ + exact ih + | withTags more child => + simp only [compilePlanGo, listTestsGo] + exact toListedList_compilePlanGo masterSeed opts path (tags ++ more) mode wrap child + | withOptions f child => + simp only [compilePlanGo, listTestsGo] + exact toListedList_compilePlanGo masterSeed (f opts) path tags mode wrap child + | aroundEach w child => + simp only [compilePlanGo, listTestsGo] + exact toListedList_compilePlanGo masterSeed opts path tags mode (fun inner => wrap (w inner)) child + | withResource desc acq child => + simp only [compilePlanGo, ExecPlan.toListedList, listTestsGo] + exact toListedList_compilePlanGo masterSeed opts path tags mode wrap child +termination_by sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +theorem toListedChildren_compilePlanChildren (masterSeed : UInt64) (opts : TestOptions) + (path tags : Array String) (mode : ExecutionMode) + (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) + (cs : List TestTree) : + ExecPlan.toListedChildren mode (compilePlanChildren masterSeed opts path tags mode wrap cs) = + listTestsChildren path tags mode cs := by + cases cs with + | nil => simp [compilePlanChildren, ExecPlan.toListedChildren, listTestsChildren] + | cons c rest => + simp only [compilePlanChildren, ExecPlan.toListedChildren, listTestsChildren] + rw [toListedList_compilePlanGo, toListedChildren_compilePlanChildren] +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- **Unified Plan Equivalence**: compiling a `TestTree` with `compilePlan` produces + the exact same sequence of `(path, tags, mode)` leaves as `listTests`. -/ +theorem toListed_compilePlan (masterSeed : UInt64) (opts : TestOptions) + (defaultMode : ExecutionMode) (tree : TestTree) : + (compilePlan masterSeed opts defaultMode tree).toListed defaultMode = + listTests tree defaultMode := by + unfold compilePlan ExecPlan.toListed listTests + cases defaultMode with + | parallel => + simp [toListedList_compilePlanGo] + | sequential => + simp [ExecPlan.toListedList, toListedList_compilePlanGo] + +mutual + +/-- Predicate asserting every leaf in an `ExecPlan` carries its deterministic seed + `deriveTestSeed masterSeed path`. -/ +def PlanSeedsDeterministic (masterSeed : UInt64) : ExecPlan → Prop + | .leaf _ path _ _ seed _ => seed = deriveTestSeed masterSeed path + | .group _ children => PlanSeedsDeterministicChildren masterSeed children.toList + | .seq child => PlanSeedsDeterministic masterSeed child + | .resource _ _ _ _ child => PlanSeedsDeterministic masterSeed child +termination_by p => sizeOf p +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +def PlanSeedsDeterministicChildren (masterSeed : UInt64) : List ExecPlan → Prop + | [] => True + | c :: cs => PlanSeedsDeterministic masterSeed c ∧ PlanSeedsDeterministicChildren masterSeed cs +termination_by cs => sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +mutual + +theorem compilePlanGo_seeds_deterministic (masterSeed : UInt64) (opts : TestOptions) + (path tags : Array String) (mode : ExecutionMode) + (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) + (t : TestTree) : + PlanSeedsDeterministic masterSeed (compilePlanGo masterSeed opts path tags mode wrap t) := by + cases t with + | leaf name leafTags exec => + simp [compilePlanGo, PlanSeedsDeterministic] + | group name children => + simp only [compilePlanGo, PlanSeedsDeterministic] + exact compilePlanChildren_seeds_deterministic masterSeed opts + (if name.isEmpty then path else path.push name) tags mode wrap children.toList + | withMode m child => + have ih := compilePlanGo_seeds_deterministic masterSeed opts path tags + (ExecutionMode.combine mode m) wrap child + cases mode <;> cases m <;> + · unfold compilePlanGo + simp only [ExecutionMode.combine, PlanSeedsDeterministic] at ih ⊢ + exact ih + | withTags more child => + simp only [compilePlanGo] + exact compilePlanGo_seeds_deterministic masterSeed opts path (tags ++ more) mode wrap child + | withOptions f child => + simp only [compilePlanGo] + exact compilePlanGo_seeds_deterministic masterSeed (f opts) path tags mode wrap child + | aroundEach w child => + simp only [compilePlanGo] + exact compilePlanGo_seeds_deterministic masterSeed opts path tags mode (fun inner => wrap (w inner)) child + | withResource desc acq child => + simp only [compilePlanGo, PlanSeedsDeterministic] + exact compilePlanGo_seeds_deterministic masterSeed opts path tags mode wrap child +termination_by sizeOf t +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +theorem compilePlanChildren_seeds_deterministic (masterSeed : UInt64) (opts : TestOptions) + (path tags : Array String) (mode : ExecutionMode) + (wrap : (TestContext → IO TestResult) → TestContext → IO TestResult) + (cs : List TestTree) : + PlanSeedsDeterministicChildren masterSeed + (compilePlanChildren masterSeed opts path tags mode wrap cs) := by + cases cs with + | nil => simp [compilePlanChildren, PlanSeedsDeterministicChildren] + | cons c rest => + simp only [compilePlanChildren, PlanSeedsDeterministicChildren] + exact ⟨compilePlanGo_seeds_deterministic masterSeed opts path tags mode wrap c, + compilePlanChildren_seeds_deterministic masterSeed opts path tags mode wrap rest⟩ +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +/-- Every leaf in a compiled plan receives `deriveTestSeed masterSeed path`, + independent of thread count, scheduling order, or sibling tests. -/ +theorem compilePlan_seeds_deterministic (masterSeed : UInt64) (opts : TestOptions) + (defaultMode : ExecutionMode) (tree : TestTree) : + PlanSeedsDeterministic masterSeed (compilePlan masterSeed opts defaultMode tree) := by + unfold compilePlan + cases defaultMode <;> + simpa [PlanSeedsDeterministic] using + compilePlanGo_seeds_deterministic masterSeed opts #[] #[] _ id tree + +/-! ## `ExecPlan.skipAll` Accounting -/ + +mutual + +theorem skipAll_summarizeGo (reason : String) (mode : ExecutionMode) (p : ExecPlan) : + (p.skipAll reason).summarizeGo = (0, 0, (p.toListedList mode).length) := by + cases p with + | leaf name path tags opts seed exec => + simp [ExecPlan.skipAll, ReportTree.summarizeGo, TestResult.skip, ExecPlan.toListedList] + | group name children => + simp only [ExecPlan.skipAll, ReportTree.summarizeGo, ExecPlan.toListedList] + exact skipAllChildren_summarizeChildren reason mode children.toList + | seq child => + simp only [ExecPlan.skipAll, ExecPlan.toListedList] + exact skipAll_summarizeGo reason .sequential child + | resource desc path tags acq child => + simp only [ExecPlan.skipAll, ExecPlan.toListedList] + exact skipAll_summarizeGo reason mode child +termination_by sizeOf p +decreasing_by all_goals (simp_wf; first | done | omega | (have := array_toList_sizeOf_lt children; omega)) + +theorem skipAllChildren_summarizeChildren (reason : String) (mode : ExecutionMode) + (cs : List ExecPlan) : + ReportTree.summarizeChildren (ExecPlan.skipAllChildren reason cs) = + (0, 0, (ExecPlan.toListedChildren mode cs).length) := by + cases cs with + | nil => simp [ExecPlan.skipAllChildren, ReportTree.summarizeChildren, ExecPlan.toListedChildren] + | cons c rest => + simp only [ExecPlan.skipAllChildren, ReportTree.summarizeChildren, + ExecPlan.toListedChildren, List.length_append] + rw [skipAll_summarizeGo reason mode c, skipAllChildren_summarizeChildren reason mode rest] + simp +termination_by sizeOf cs +decreasing_by all_goals (simp_wf; omega) + +end + +theorem skipAll_summary (reason : String) (p : ExecPlan) (d : Nat) (sd : UInt64) (th : Nat) + (mode : ExecutionMode := .parallel) : + let s := (p.skipAll reason).summarize d sd th + s.passed = 0 ∧ s.failed = 0 ∧ s.skipped = (p.toListed mode).size ∧ s.allPassed = true := by + simp only [ReportTree.summarize, ExecPlan.toListed, List.size_toArray, + skipAll_summarizeGo reason mode p, RunSummary.allPassed] + simp + +/-! ## Worker Pool Size Bounds -/ + +theorem computeWorkerCount_bounds (threads totalLeaves : Nat) : + 1 ≤ computeWorkerCount threads totalLeaves ∧ + computeWorkerCount threads totalLeaves ≤ max 1 threads ∧ + computeWorkerCount threads totalLeaves ≤ max 1 totalLeaves := by + unfold computeWorkerCount + omega + +end +end LSpec.Proofs diff --git a/LSpecTests/ImportCheck.lean b/LSpecTests/ImportCheck.lean new file mode 100644 index 0000000..a362971 --- /dev/null +++ b/LSpecTests/ImportCheck.lean @@ -0,0 +1,42 @@ +module +public import LSpec + +/-! +# Import-Time Execution Guard Fixture + +Imported unconditionally by `LSpecTests.Main`. Every suite here contains a sentinel +that would fail or panic if Lean evaluated test bodies during module +initialization (either eagerly or via `compiler.extract_closed` hoisting). +-/ + +namespace LSpecTests.ImportCheck +public section + +open LSpec + +/-- Pure computation that panics if ever evaluated. With `compiler.extract_closed` + disabled on the suite, importing this module must not hoist or evaluate this + before `main` runs. -/ +@[noinline] def boomIfEvaluatedAtImport (n : Nat) : Bool := + if n == 999999 then panic! "BUG: pure test body was evaluated at import time!" + else true + +set_option compiler.extract_closed false in +/-- Suite that is imported by `LSpecTests.Main` and registered under the + `import-guard` tag so it is filtered out by default; if any body ran at + import time, the process would crash immediately on startup. -/ +public def importGuardSuite : Spec := do + withTag "import-guard" do + describe "Import-time laziness guard" do + itBool "closed pure panic is never evaluated at import" (boomIfEvaluatedAtImport 999999) + it "closed pure let inside AssertM is never evaluated at import" do + let ok := boomIfEvaluatedAtImport 999999 + expect ok + prop "closed pure let inside prop is never evaluated at import" <| + let ok := boomIfEvaluatedAtImport 999999 + fun (_ : Nat) => ok + it "passing lazy check runs normally when selected" do + expect (boomIfEvaluatedAtImport 1) + +end +end LSpecTests.ImportCheck diff --git a/LSpecTests/Main.lean b/LSpecTests/Main.lean new file mode 100644 index 0000000..bc5621b --- /dev/null +++ b/LSpecTests/Main.lean @@ -0,0 +1,457 @@ +import LSpec +import LSpecTests.ImportCheck + +open LSpec LSpec.Prop + +/-! # LSpec Self-Test Suite + +Dogfoods LSpec's own `SpecM` DSL, `AssertM` expectations, Bool-based property +testing, bounded-thread parallel runner, scoped resources, filtering, and CLI. + +Run all primary tests: + `lake test` + `lake exe tests -j 4` + +Run the opt-in memory stress suite (50 × 100MB allocations): + `lake exe tests --tag memory -j 4` +-/ + +/-- Helper to run a small inner `Spec` programmatically and inspect its result. -/ +private def runInner (s : Spec) (cfg : RunConfig := {}) : IO (ReportTree × RunSummary) := + runSpec s cfg + +/-! ## Assertions & Expectations -/ + +def assertionSuite : Spec := do + describe "Assertions & Expectations" do + it "expect and expectFalse pass on expected booleans" do + expect true + assertTrue true + expectFalse false + assertFalse false + expectAll #[true, true, true] + assertAll #[true, true, true] + + it "expect fails with source location on false" do + let (rep, sum) ← runInner do + it "failing expect" do + expect false "custom failure" + shouldBe sum.failed 1 + shouldBe sum.passed 0 + let fails := rep.failures + shouldBe fails.size 1 + shouldContainSubstr fails[0]!.result.summary "custom failure" + shouldContainSubstr fails[0]!.result.details "LSpecTests/Main.lean:" + + it "assertAll reports the failing index" do + let (rep, sum) ← runInner do + it "index 2 fails" do + assertAll #[true, true, false, true] "check" + shouldBe sum.failed 1 + shouldContainSubstr rep.failures[0]!.result.summary "index 2" + + it "shouldBe and shouldNotBe compare via BEq and format Repr on failure" do + shouldBe (2 + 2) 4 + shouldNotBe "hello" "world" + let (rep, sum) ← runInner do + it "mismatch" do + shouldBe (1 + 1) 3 + shouldBe sum.failed 1 + shouldContainSubstr rep.failures[0]!.result.details "expected: 3" + shouldContainSubstr rep.failures[0]!.result.details "but got: 2" + + it "shouldSatisfy and ordering expectations work via Ord" do + shouldSatisfy (42 : Nat) (· % 2 == 0) "even" + shouldBeLt (1 : Nat) 2 + shouldBeLe (2 : Nat) 2 + shouldBeGt (5 : Nat) 3 + shouldBeGe (5 : Nat) 5 + shouldContain [1, 2, 3] 2 + shouldContainSubstr "hello world" "world" + + it "shouldReturn and shouldThrow test IO actions" do + shouldReturn (pure 7 : IO Nat) 7 + shouldThrow (throw (IO.userError "boom: disk full") : IO Unit) (some "disk full") + let (_, sum) ← runInner do + it "did not throw" do + shouldThrow (pure () : IO Unit) + shouldBe sum.failed 1 + + it "expectSome / expectNone / expectOk / expectErr unwrap cleanly" do + let v ← expectSome (some 42) + shouldBe v 42 + expectNone (none : Option Nat) + let okVal ← expectOk (Except.ok 10 : Except String Nat) + shouldBe okVal 10 + let errVal ← expectErr (Except.error "oops" : Except String Nat) + shouldBe errVal "oops" + + let (_, sum) ← runInner do + it "none fails" do + let _ ← expectSome (none : Option Nat) + it "error fails" do + let _ ← expectOk (Except.error "bad" : Except String Nat) + shouldBe sum.failed 2 + + it "pending, pendingWith, and xit record skipped tests" do + let (_, sum) ← runInner do + it "p1" do pending + it "p2" do pendingWith "waiting on upstream" + xit "p3" do fail "must not run" + shouldBe sum.skipped 3 + shouldBe sum.failed 0 + shouldBe sum.allPassed true + + itBool "itBool runs deferred pure Bool checks" (List.range 5 == [0, 1, 2, 3, 4]) + + it "uncaught IO exceptions are caught per test without crashing the runner" do + let (rep, sum) ← runInner do + it "throws" do + let _ ← (throw (IO.userError "unexpected crash") : IO Unit) + it "still runs" do + expect true + shouldBe sum.failed 1 + shouldBe sum.passed 1 + shouldContainSubstr rep.failures[0]!.result.details "unexpected crash" + + it "IO.ofExcept lifts cleanly into AssertM and DSL keywords stay non-reserved" do + let v ← IO.ofExcept (Except.ok 42 : Except String Nat) + let prop := v + let it := prop + 1 + shouldBe it 43 + +/-! ## Scoped Resources & Lifecycle Hooks -/ + +def resourceSuite : Spec := do + describe "Scoped Resources & Hooks" do + it "withResource acquires once, shares across tests, and releases in finally" do + let log ← IO.mkRef (#[] : Array String) + let resSpec : ResourceSpec String := { + description := "test-db" + acquire := do + log.modify (·.push "acquire") + return "conn-42" + release := fun c => do + log.modify (·.push s!"release:{c}") + } + let (_, sum) ← runInner (cfg := { threads := 2 }) do + withResource resSpec fun getConn => do + it "t1" do + let c ← getConn + shouldBe c "conn-42" + it "t2 fails" do + let c ← getConn + shouldBe c "wrong" + shouldBe sum.passed 1 + shouldBe sum.failed 1 + let events ← log.get + shouldBe events #["acquire", "release:conn-42"] + + it "filtered-out or listed withResource never calls acquire" do + let acquired ← IO.mkRef false + let resSpec : ResourceSpec Unit := { + description := "expensive" + acquire := acquired.set true + } + let s : Spec := do + describe "GroupA" do + withResource resSpec fun _ => do + it "heavy" do expect true + describe "GroupB" do + it "light" do expect true + let tree ← s.toTestTree "" + -- Listing must not acquire + let listed := listTests tree + shouldBe listed.size 2 + expectFalse (← acquired.get) + -- Filtering out GroupA must not acquire + let (_, sum) ← runTree tree { filter := { includes := #["GroupB"] } } + shouldBe sum.passed 1 + expectFalse (← acquired.get) + + it "beforeEach, afterEach, and aroundEach wrap every leaf test" do + let count ← IO.mkRef 0 + let (_, sum) ← runInner (cfg := { threads := 1 }) do + beforeEach (count.modify (· + 1)) do + afterEach (count.modify (· + 10)) do + it "a" do expect true + it "b" do expect false + shouldBe sum.passed 1 + shouldBe sum.failed 1 + -- Each of 2 tests adds 1 before + 10 after = 22 + shouldBe (← count.get) 22 + +/-! ## Bool-based Property Testing -/ + +def propertySuite : Spec := do + describe "Bool-based Property Testing" do + prop "Nat addition is commutative" fun (a b : Nat) => + a + b == b + a + + prop "List reverse is an involution" fun (xs : List Nat) => + xs.reverse.reverse == xs + + prop "Array toList/toArray roundtrip" fun (xs : Array Int) => + xs.toList.toArray == xs + + prop "ByteArray append size" fun (a b : ByteArray) => + (a ++ b).size == a.size + b.size + + prop "precondition guard ==> filters inputs" fun (n : Nat) => + (n != 0) ==> Nat.blt (n - 1) n + + prop "AssertM body works inside prop" fun (xs ys : List Nat) => + shouldBe (xs ++ ys).length (xs.length + ys.length) + + prop "custom generator with forAll" <| + forAll (Gen.chooseNat 10 20) fun n => + Nat.ble 10 n && Nat.ble n 20 + + it "shrinks failing Nat counterexample to minimal value" do + let (rep, sum) ← runInner (cfg := { seed := some 12345 }) do + propWith "lt 10" { numTests := 100, maxSize := 50 } fun (n : Nat) => Nat.blt n 10 + shouldBe sum.failed 1 + let details := rep.failures[0]!.result.details + shouldContainSubstr details "arg 0 := 10" + shouldContainSubstr details "seed " + + it "shrinks failing List counterexample to minimal length and elements" do + let (rep, sum) ← runInner (cfg := { seed := some 999 }) do + propWith "len < 2" { numTests := 100, maxSize := 20 } fun (xs : List Nat) => Nat.blt xs.length 2 + shouldBe sum.failed 1 + shouldContainSubstr rep.failures[0]!.result.details "[0, 0]" + + it "reports gaveUp when precondition is unsatisfiable" do + let (rep, sum) ← runInner (cfg := { seed := some 42 }) do + propWith "impossible guard" { numTests := 10, maxDiscardRatio := 2 } fun (n : Nat) => + (Nat.blt n 0) ==> true + shouldBe sum.failed 1 + shouldContainSubstr rep.failures[0]!.result.summary "gave up" + + it "is 100% deterministic across sequential and parallel runs with the same seed" do + let mkSpec : Spec := do + describe "Det" do + prop "p1" (fun (n : Nat) => shouldBeLt n 7) + prop "p2" (fun (a b : Nat) => shouldBeLt (a + b) 12) + prop "p3" (fun (xs : List Nat) => shouldBeLt xs.length 3) + let (r1, _) ← runInner mkSpec { threads := 1, seed := some 77777 } + let (r2, _) ← runInner mkSpec { threads := 4, seed := some 77777 } + let d1 := r1.failures.map (·.result.details) + let d2 := r2.failures.map (·.result.details) + shouldBe d1 d2 + shouldBe d1.size 3 + +/-! ## Bounded-Thread Parallel Runner -/ + +def parallelSuite : Spec := do + describe "Bounded-Thread Parallel Runner" do + it "strictly enforces --threads N concurrency bound while achieving real parallelism" do + let active ← Std.Mutex.new (0 : Nat) + let peak ← Std.Mutex.new (0 : Nat) + let makeWorkers : Spec := do + describe "Workers" do + for i in [:12] do + it s!"worker-{i}" do + active.atomically do + let cur := (← get) + 1 + set cur + peak.atomically do + if cur > (← get) then set cur + IO.sleep 30 + active.atomically do + set ((← get) - 1) + let (_, sum) ← runInner makeWorkers { threads := 3 } + shouldBe sum.passed 12 + shouldBe sum.threads 3 + let maxObserved ← peak.atomically get + shouldBeLe maxObserved 3 + shouldBeGe maxObserved 2 + + it "runs strictly sequentially when threads := 1" do + let active ← Std.Mutex.new (0 : Nat) + let peak ← Std.Mutex.new (0 : Nat) + let s : Spec := do + for i in [:5] do + it s!"seq-{i}" do + active.atomically do + let cur := (← get) + 1 + set cur + peak.atomically do + if cur > (← get) then set cur + IO.sleep 10 + active.atomically do + set ((← get) - 1) + let (_, sum) ← runInner s { threads := 1 } + shouldBe sum.passed 5 + shouldBe (← peak.atomically get) 1 + + it "respects sequential modifier even when threads > 1" do + let order ← Std.Mutex.new (#[] : Array Nat) + let active ← Std.Mutex.new (0 : Nat) + let peak ← Std.Mutex.new (0 : Nat) + let s : Spec := do + sequential do + for i in [:5] do + it s!"ordered-{i}" do + active.atomically do + let cur := (← get) + 1 + set cur + peak.atomically do + if cur > (← get) then set cur + IO.sleep 10 + order.atomically (modify (·.push i)) + active.atomically (modify (· - 1)) + let (_, sum) ← runInner s { threads := 4 } + shouldBe sum.passed 5 + shouldBe (← peak.atomically get) 1 + shouldBe (← order.atomically get) #[0, 1, 2, 3, 4] + + it "isolates stdout per test under concurrent execution" do + let s : Spec := do + for i in [:8] do + it s!"io-{i}" do + IO.println s!"marker-start-{i}" + IO.sleep 15 + IO.println s!"marker-end-{i}" + let (rep, sum) ← runInner s { threads := 4 } + shouldBe sum.passed 8 + match rep with + | .group _ children => + shouldBe children.size 8 + for h : i in [:children.size] do + match children[i] with + | .leaf lr => + shouldBe lr.capturedOutput s!"marker-start-{i}\nmarker-end-{i}\n" + | _ => fail "expected leaf report" + | _ => fail "expected group report" + + it "supports --fail-fast skipping remaining queued tests" do + let (_, sum) ← runInner (cfg := { threads := 1, failFast := true }) do + it "t1 fails" do expect false + it "t2 skipped" do expect true + it "t3 skipped" do expect true + shouldBe sum.failed 1 + shouldBe sum.skipped 2 + shouldBe sum.passed 0 + + it "does not acquire withResource after --fail-fast triggers" do + let acquired ← IO.mkRef false + let (_, sum) ← runInner (cfg := { threads := 1, failFast := true }) do + it "t1 fails" do expect false + beforeAll (do acquired.set true; pure 1) (fun _ => pure ()) "should-skip" fun getR => do + it "t2 skipped" do + let _ ← getR + expect true + it "t3 skipped" do + let _ ← getR + expect true + shouldBe (← acquired.get) false + shouldBe sum.failed 1 + shouldBe sum.skipped 2 + shouldBe sum.passed 0 + + it "keeps nested parallel inside sequential strictly sequential in listTests and execution" do + let s : Spec := do + sequential do + parallel do + it "a" do expect true + it "b" do expect true + let tree ← s.toTestTree "" + let listed := listTests tree .parallel + shouldBe listed.size 2 + shouldBe (listed.all (·.mode == .sequential)) true + +/-! ## Filtering, Listing & CLI -/ + +def cliSuite : Spec := do + describe "Filtering, Listing & CLI" do + it "filters by substring, exact path, exclude, and tags" do + let s : Spec := do + describe "Math" do + withTag "fast" do + it "add" do expect true + withTag "slow" do + it "mul" do expect true + describe "String" do + withTag "fast" do + it "concat" do expect true + let tree ← s.toTestTree "" + shouldBe (listTests tree).size 3 + + let (_, s1) ← runTree tree { filter := { includes := #["Math"] } } + shouldBe s1.passed 2 + + let (_, s2) ← runTree tree { filter := { exact := #["Math/add"] } } + shouldBe s2.passed 1 + + let (_, s3) ← runTree tree { filter := { excludes := #["mul"] } } + shouldBe s3.passed 2 + + let (_, s4) ← runTree tree { filter := { includeTags := #["fast"] } } + shouldBe s4.passed 2 + + let (_, s5) ← runTree tree { filter := { excludeTags := #["slow"] } } + shouldBe s5.passed 2 + + it "parses CLI flags cleanly and rejects invalid options" do + let cli ← expectOk (parseCliArgs [ + "-j", "8", "--seed", "42", "--num-tests=250", "--max-size", "64", + "--tag", "fast", "--exclude-tag=slow,nightly", "--exclude=flaky", + "--exact", "Math/add", "--fail-fast", "--no-color", "-v", "Math" + ]) + shouldBe cli.threads (some 8) + shouldBe cli.seed (some 42) + shouldBe cli.numTests (some 250) + shouldBe cli.maxSize (some 64) + shouldBe cli.includeTags #["fast"] + shouldBe cli.excludeTags #["slow", "nightly"] + shouldBe cli.excludes #["flaky"] + shouldBe cli.exact #["Math/add"] + shouldBe cli.includes #["Math"] + shouldBe cli.failFast true + shouldBe cli.color (some false) + shouldBe cli.verbose true + + let _ ← expectErr (parseCliArgs ["--threads", "0"]) + let errMissing ← expectErr (parseCliArgs ["--threads"]) + shouldContainSubstr errMissing "missing value" + let _ ← expectErr (parseCliArgs ["--bogus-flag"]) + + it "import-time guard suite can run its safe test without triggering boom tests" do + let (_, sum) ← runInner LSpecTests.ImportCheck.importGuardSuite { + filter := { includes := #["passing lazy check"] } + } + shouldBe sum.passed 1 + shouldBe sum.failed 0 + +/-! ## Opt-in Memory Stress Suite (`--tag memory`) + +Each of 50 tests allocates a 100 MB `ByteArray`. With bounded concurrency (`-j N`), +completed test closures are released immediately so peak RSS stays proportional +to `N × 100 MB` rather than growing to `5 GB`. +-/ + +set_option compiler.extract_closed false in +def memoryStressSuite : Spec := do + withTag "memory" do + describe "Memory stress (50 × 100MB)" do + for i in [:50] do + it s!"alloc 100MB #{i + 1}" do + let arr := ByteArray.mk (.replicate (100 * 1024 * 1024) 0xFF) + expect (arr.size == 100 * 1024 * 1024) + +def allTests : Spec := do + assertionSuite + resourceSuite + propertySuite + parallelSuite + cliSuite + LSpecTests.ImportCheck.importGuardSuite + memoryStressSuite + +def main (args : List String) : IO UInt32 := do + -- Exclude opt-in suites (`memory`, `import-guard`) unless explicitly requested via `--tag`. + let defaults : RunConfig := + if args.any (fun a => a == "--tag" || a.startsWith "--tag=") then {} + else { filter := { excludeTags := #["memory", "import-guard"] } } + lspecMain allTests args defaults diff --git a/README.md b/README.md index e5615ad..f2c83e3 100644 --- a/README.md +++ b/README.md @@ -1,199 +1,190 @@ # LSpec -A testing framework for Lean 4, inspired by Haskell's [Hspec](https://hspec.github.io/) package. - -## Usage - -### Composing tests - -Sequences of tests are represented by the `TestSeq` datatype. -In order to instantiate terms of `TestSeq`, use the `test` helper function: - -```lean -#check - test "Nat equality" (4 = 4) $ - test "Nat inequality" (4 ≠ 5) --- test "Nat equality" (4 = 4) (test "Nat inequality" (4 ≠ 5)) : TestSeq +A lightweight, **Bool-based**, **parallel-first**, **formally verified** testing framework for Lean 4 with zero external dependencies. + +LSpec combines ideas from: +- **[Hspec](https://hspec.github.io/)**: ergonomic `SpecM` `do`-block DSL (`describe`, `context`, `it`, `prop`, `shouldBe`, `beforeAll`, `parallel`, `sequential`, `xit`/`pending`) +- **[nest-core](https://github.com/hargoniX/nest-core)**: `TestTree` IR, extensible `IsTest` typeclass, pluggable `TestProcessor`s, and scoped resources +- **[nest-unit](https://github.com/hargoniX/nest-unit)**: `AssertM` monad with compile-time source locations (`file:line:col`) via `pos%` +- **[nest-slimcheck](https://github.com/hargoniX/nest-slimcheck)**: per-test deterministic seeds always printed for reproducible property-test failures + +## Key Design Goals + +1. **Zero import-time overhead**: + - All tests are `Bool`- and `AssertM`-based (no `Prop`/`Decidable` synthesis, proof-erasure overhead, or runtime `Lean` compiler dependency). + - Every leaf test (`it`, `itBool`, `prop`, `propWith`) is deferred under a `Unit →` thunk inside `Spec` (`StateT (Array TestTree) BaseIO Unit`). For test libraries or declarations containing heavy closed pure expressions inside `it` blocks, setting `compiler.extract_closed false` (e.g. `moreLeanArgs = ["-Dcompiler.extract_closed=false"]` on your test library) prevents Lean from hoisting them into module initializers. Importing test modules does zero test work. +2. **Bounded-thread parallel execution (`-j N` / `--threads N`)**: + - A fixed-size worker pool runs at most `N` tests concurrently while releasing each completed test closure immediately so peak RSS stays proportional to `N` rather than total suite size. + - Per-test stdout/stderr isolation (`IO.FS.withIsolatedStreams`) keeps output deterministic and readable. + - `sequential` subtrees and scoped `withResource`/`beforeAll` fixtures compose cleanly with parallelism. +3. **Deterministic, thread-safe Bool property testing**: + - Pure SplitMix64 `Gen` monad (never mutates global `IO.stdGenRef`), with fuel-bounded shrinking and deterministic per-test seeds derived from `(masterSeed, testPath)`. +4. **Formally verified runner (`LSpecProofs`)**: + - Core filtering, reporting, and plan-compilation logic is total and verified directly in Lean with zero `sorry`s, alongside a small-step operational semantics proof of bounded concurrency, sequential exclusion, resource bracket safety, deadlock freedom, and sequential–parallel equivalence—enforced in CI with zero overhead for consumers. + +## Installation & Quick Start + +Add LSpec as a dependency and register a test driver executable in `lakefile.toml`: + +```toml +testDriver = "tests" + +[[require]] +name = "LSpec" +git = "https://github.com/argumentcomputer/LSpec" +rev = "main" + +[[lean_exe]] +name = "tests" +root = "Tests.Main" ``` -`test` consumes a description a proposition and a next test -The proposition, however, must have its own instance of `Testable`. - -You can also collect `TestSeq` into conceptual test groups by using the -helper function `group`: +Write your test suite in `Tests/Main.lean` (see also [Examples/Examples.lean](Examples/Examples.lean)): ```lean -#check - test "Nat equality" (42 = 42) $ - group "manual group" $ - test "Nat equality inside group" (4 = 4) -``` +import LSpec -### The `Testable` class +open LSpec LSpec.Prop -`Testable` is how Lean is instructed to decide whether certain propositions are resolved as `true` or `false`. +def mySuite : Spec := do + describe "Arithmetic" do + it "adds numbers" do + shouldBe (2 + 2) 4 + shouldBeLt (3 : Nat) 5 -This is an example of a simple instance for decidability of equalities: + itBool "multiplies numbers" (3 * 4 == 12) -```lean -instance (x y : α) [DecidableEq α] [Repr α] : Testable (x = y) := - if h : x = y then - .isTrue h - else - .isFalse h s!"Not equal: {repr x} and {repr y}" -``` + prop "addition is commutative" fun (a b : Nat) => + a + b == b + a -The custom failure message is optional. + prop "subtraction with guard" fun (a b : Nat) => + (Nat.ble b a) ==> (a - b + b == a) -There are more examples of `Testable` instances in [LSpec/Instances.lean](LSpec/Instances.lean). +def main (args : List String) : IO UInt32 := + lspecMain mySuite args +``` -The user is, of course, free to provide their own instances. +Run via `lake test` or invoke the compiled binary directly: -### Actually running the tests +```bash +# Run sequentially (default) +lake test -#### The `#lspec` command +# Run with 4 worker threads (bounded concurrency for CI speed vs. RSS tuning) +lake test -- -j 4 -The `#lspec` command allows you to test interactively in a file. +# List all tests without running tests or acquiring resources +lake test -- --list -Examples: +# Filter by path, exact path, exclusion, or tags +lake test -- Arithmetic --exclude slow --tag fast -```lean -#lspec - test "four equals four" (4 = 4) $ - test "five equals five" (5 = 5) --- ✓ four equals four --- ✓ five equals five +# Reproduce a property-test failure with its reported seed +lake test -- --seed 123456789 --num-tests 200 ``` -An important note is that a failing test will raise an error, interrupting the building process. - -#### The `lspecIO` function +## Assertions & Expectations (`AssertM`) -`lspecIO` is meant to be used in files to be compiled and integrated in a testing infrastructure, as shown below. - -```lean -def aaSuite := [ - test "four equals four" (4 = 4) - ] - -def bbSuite := [ - test "five equals five" (5 = 5) - ] - -def main := lspecIO $ .ofList [ - ("aa", aaSuite), - ("bb", bbSuite) - ] -``` +Inside `it "description" do ...`, assertions run in `AssertM Unit` (`ExceptT AssertStop IO Unit`) and capture the exact `file:line:col` of any failure: -Once such `main` function is defined, its respective executable can be tagged as the `@[test_driver]` in the lakefile. -For further information, inspect the docstring of `lspecIO`. +| Function | Purpose | +|---|---| +| `expect cond` / `assertTrue cond` | Fail if `cond == false` *(note: `assert` is a Lean 4 `do`-keyword)* | +| `expectFalse cond` / `assertFalse cond` | Fail if `cond == true` | +| `expectAll conds` / `assertAll conds` | Fail with index on first `false` in `Array Bool` | +| `shouldBe actual expected` | `BEq` equality with `Repr` diff | +| `shouldNotBe actual unexpected` | `BEq` inequality | +| `shouldSatisfy actual pred label` | Boolean predicate check | +| `shouldBeLt` / `shouldBeLe` / `shouldBeGt` / `shouldBeGe` | `Ord`-based comparisons | +| `shouldContain` / `shouldContainSubstr` | List / String containment | +| `shouldReturn action expected` | Assert `IO` return value | +| `shouldThrow action expectedSubstr?` | Assert `IO` throws an error | +| `expectSome` / `expectNone` | Unwrap `Option` in `do`-notation | +| `expectOk` / `expectOkRepr` / `expectErr` | Unwrap `Except` in `do`-notation | +| `fail msg` / `pending` / `pendingWith reason` | Explicit failure or pending skip | -## Integration with `SlimCheck` +## Property-Based Testing (`LSpec.Prop`) -There are 3 main typeclasses associated with any `SlimCheck` test: +Properties accept arbitrary-arity functions returning `Bool`, `AssertM Unit`, `Except String Unit`, precondition guards (`==>`), or explicit generators (`forAll`, `forAllShrink`, `forAllNoShrink`, `forAllNamed`). Use `propWith` or `withPropConfig` to override sample counts, size, or seeds per test/subtree: -* `Shrinkable` : The typeclass that takes a type `a : α` and returns a `List α` of elements which - should be thought of as being "smaller" than `a` (in some sense dependent on the type `α` being - considered). -* `SampleableExt` : The typeclass of a . - This is roughly equivalent to `QuickCheck`'s `Arbitrary` typeclass. -* `Checkable` : The property to be checked by `SlimCheck` must have a `Checkable` instance. +```lean +def propSuite : Spec := do + describe "Lists" do + prop "reverse involution" fun (xs : List Nat) => + xs.reverse.reverse == xs -In order to use `SlimCheck` tests for custom data types, the user will need to implement -instances of the typeclasses `Shrinkable` and `SampleableExt` for the custom types appearing -in the properties being tested. + prop "append length (using AssertM)" fun (xs ys : List Nat) => + shouldBe (xs ++ ys).length (xs.length + ys.length) -The module [LSpec.SlimCheck.Checkable](LSpec/SlimCheck/Checkable.lean) contains may of -the useful definitions and instances that can be used to derive a Checkable instance -for a wide variety of properties given just the instances above. If all else fails, the user can -also define the Checkable instance by hand. + propWith "custom generator" { numTests := 200 } <| + forAll (Gen.chooseNat 10 20) fun n => + Nat.ble 10 n && Nat.ble n 20 +``` -Once this is done a `Slimcheck` test is evaluated in a similar way to -`LSpec` tests: +Custom types only need `Sampleable`, `Shrinkable` (no `WellFoundedRelation` proof required), and `Repr` (or `ToString` / `FormatValue`): ```lean -#lspec check "add_comm" $ ∀ n m : Nat, n + m = m + n - -#lspec check "add_comm" $ ∀ n m : Nat, n + m = m + m --- × add_comm - --- =================== --- Found problems! --- n := 1 --- m := 0 --- issue: 1 = 0 does not hold --- (0 shrinks) --- ------------------- +structure Pair where + left : Nat + right : Nat + deriving BEq, Repr + +instance : Shrinkable Pair where + shrink p := + (Shrinkable.shrink p.left).map (fun l => { p with left := l }) ++ + (Shrinkable.shrink p.right).map (fun r => { p with right := r }) + +instance : Sampleable Pair where + sample := return { left := ← Gen.chooseNat 0 (← Gen.getSize), + right := ← Gen.chooseNat 0 (← Gen.getSize) } ``` -## Integration with `Plausible` - -LSpec also integrates with Lean's [Plausible](https://github.com/leanprover-community/plausible) property-based testing library. The Plausible backend lives alongside the SlimCheck-based `check`/`checkIO` -described above rather than replacing them, so existing SlimCheck tests continue to work unchanged. - -Plausible relies on the same core typeclasses as QuickCheck — `Shrinkable` and `SampleableExt` -to generate and shrink random values — plus `Plausible.Testable` for the property itself. -Instances for the common types (`Nat`, `Int`, `List`, etc.) ship with Plausible, and custom -types are supported by providing `Shrinkable`/`SampleableExt` instances just as with SlimCheck. +## Parallelism, Resources, and Hooks -The module [LSpec.Plausible](LSpec/Plausible.lean) exposes two macros: +- **`--threads N` / `-j N`**: caps concurrent test execution to `N` worker threads. Completed test closures are dropped immediately upon finishing to keep peak RSS bounded. +- **Preventing closed-term hoisting**: plain `def mySuite : Spec := do ...` works for both top-level and parameterized suites. If a test module contains expensive closed pure expressions inside `it`/`itBool` bodies, add `set_option compiler.extract_closed false` (or `moreLeanArgs = ["-Dcompiler.extract_closed=false"]` on your test library) so Lean never hoists them into module initializers. +- **`sequential do ...` / `parallel do ...`**: override concurrency per subtree. A `sequential` subtree runs its tests strictly in order as one pool job, while sibling `sequential` subtrees may still run concurrently if their parent is `parallel`. +- **`withResource` / `beforeAll`**: acquire a shared resource once for a subtree and release it in `finally` after all tests in that subtree complete. Never acquired during `--list` or when filtered out. +- **`beforeEach` / `afterEach` / `aroundEach`**: per-leaf lifecycle hooks. +- **`withTag` / `withTags`**: tag subtrees for `--tag` and `--exclude-tag` selection. +- **`withOptions` / `withPropConfig`**: scope configuration overrides to a subtree. -* `checkPlausible'` — a **compile-time** property test, evaluated during elaboration with a - fixed random seed (deterministic across compilations). This is the Plausible-backed - counterpart to `check'`. -* `checkPlausibleIO'` — a **runtime** property test, deferred until the test suite is run. - This enables fresh random values on each run and configurable seeds via `cfg.randomSeed`. - This is the Plausible-backed counterpart to `checkIO'`. +## CLI Options (`lspecMain` / `defaultMain`) -Both macros capture the property syntax so it appears in the output. (Non-syntax-capturing -`checkPlausible`/`checkPlausibleIO` functions are also available if you don't need the -property echoed back.) +Any test executable whose `main` delegates to `lspecMain` (or `defaultMain` / `defaultMainTree`) automatically parses the flags below via `LSpec.parseCliArgs`. Pass them via `lake test -- `, `lake exe `, or directly to the compiled binary (projects with custom drivers calling `runSpec` / `runTree` programmatically can reuse `parseCliArgs` or define their own CLI): -A compile-time test with `#lspec`: - -```lean -#lspec checkPlausible' "add_comm" (∀ n m : Nat, n + m = m + n) --- ✓ ∃₁₀₀: "add_comm" (∀ n m : Nat, n + m = m + n) - -#lspec checkPlausible' "bad" (∀ n : Nat, n < 5) --- × ∃¹⁰/₁₀₀: "bad" (∀ n : Nat, n < 5) - --- =================== --- Found problems! --- n := 6 --- issue: 6 < 5 does not hold --- (0 shrinks) --- ------------------- +``` + -j, --threads Run up to N tests concurrently (default: 1) + --sequential Run all tests sequentially (alias for --threads 1) + --list List matching test paths and exit without running + Run only tests whose path contains + --filter Same as positional (repeatable) + --exact Run only tests matching exactly (repeatable) + --exclude Exclude tests whose path contains + --tag Run only tests carrying (repeatable) + --exclude-tag Skip tests carrying (repeatable) + --seed Master seed for deterministic property tests + --num-tests Override property-test sample count + --max-size Override property-test maximum generator size + --fail-fast Stop starting new tests after the first failure + --color / --no-color Force or disable ANSI color output + -v, --verbose Show extra details and captured output on passes + -h, --help Show this help message ``` -A runtime test, run via `lspecIO`. Because `checkPlausibleIO'` tests are skipped by the pure -`#lspec` runner, they must be executed with `lspecIO` (or `lspecEachIO`): - -```lean -open LSpec +`--exclude=a,b`, `--tag=a,b`, and `--exclude-tag=a,b` also accept comma-separated lists, and `NO_COLOR` disables ANSI colors when neither `--color` nor `--no-color` is passed. -def plausibleTests : TestSeq := - checkPlausibleIO' "add_comm" (∀ n m : Nat, n + m = m + n) +## Formal Verification (`LSpecProofs`) -def main : IO UInt32 := lspecIO (.ofList [("plausibleTests", [plausibleTests])]) [] -``` +The core pure functions in `LSpec.Runner` (`filterTree`, `listTests`, `ReportTree.summarize`, `ReportTree.failures`, `compilePlan`, `computeWorkerCount`) are total and formally verified in the optional `LSpecProofs` library (zero `sorry`s, zero external dependencies, zero runtime overhead for consumers): -Multiple property tests can be sequenced with `++`. Note that the `'`-suffixed macros -capture everything up to the end of the line as the property, so to chain them use the -non-capturing `checkPlausibleIO` function (which takes an explicit `next` argument): +- **[LSpecProofs/Filter.lean](LSpecProofs/Filter.lean)**: filter soundness & completeness (`listTests_filterTree_eq`), idempotence (`filterTree_idempotent`), empty-filter identity, exclusion dominance, and non-empty surviving `withResource` scopes (filtered-out resources are never acquired). +- **[LSpecProofs/Report.lean](LSpecProofs/Report.lean)**: exact report accounting (`passed + failed + skipped = leafCount`, `failed = failures.size`, `allPassed ↔ failures.isEmpty`), permutation invariance of summary counts across parallel completion orders, `compilePlan` equivalence with `listTests`, deterministic per-test seed assignment, and `computeWorkerCount` bounds. +- **[LSpecProofs/Concurrency.lean](LSpecProofs/Concurrency.lean)**: small-step operational semantics of the bounded `WorkerPool` + `ExecPlan` scheduler proving bounded concurrency (`activeWorkers ≤ cap`), sequential exclusion & strict left-to-right ordering, `withResource` acquire/release bracketing (no child before acquire, no release before children finish, exact-once release on termination), deadlock freedom & strong normalization, and sequential–parallel confluence (`parallel_eq_sequential`). +- **[LSpecProofs/Axioms.lean](LSpecProofs/Axioms.lean)**: compile-time `#guard_msgs in #print axioms` gate ensuring all 31 headline theorems rely exclusively on Lean's standard axioms (`propext`, `Quot.sound`, `Classical.choice`) with zero `sorryAx` or custom axioms, built with `-DwarningAsError=true` in CI. -```lean -def suite : TestSeq := - checkPlausibleIO "add_comm" (∀ n m : Nat, n + m = m + n) $ - checkPlausibleIO "mul_one" (∀ n : Nat, n * 1 = n) -``` - -The `'`-suffixed macros always use the default configuration. To pass a fixed seed for -reproducible runs (or otherwise customise the `Plausible.Configuration`), call the underlying -`checkPlausibleIO` function directly: +Build and verify all proofs with: -```lean -def reproducible : TestSeq := - checkPlausibleIO "add_comm" (∀ n m : Nat, n + m = m + n) .done { randomSeed := some 42 } +```sh +lake build LSpecProofs --wfail ``` diff --git a/Tests/Main.lean b/Tests/Main.lean deleted file mode 100644 index 94f02e9..0000000 --- a/Tests/Main.lean +++ /dev/null @@ -1,258 +0,0 @@ -import LSpec - -open LSpec - -/-! # LSpec test suite - -Dogfoods `lspecIO` as the outer runner. Primary suites always run; -the memory stress suite is opt-in via `./tests memory`. --/ - -private def String.containsSub (s sub : String) : Bool := - (s.splitOn sub).length > 1 - --- Helper: run an IO action with stdout and stderr redirected to /dev/null. -def quietly (action : IO α) : IO α := do - let devNull ← IO.FS.Handle.mk "/dev/null" .write - let nullStream := IO.FS.Stream.ofHandle devNull - let oldStdout ← (IO.setStdout nullStream : BaseIO _) - let oldStderr ← (IO.setStderr nullStream : BaseIO _) - try - let result ← action - let _ ← (IO.setStdout oldStdout : BaseIO _) - let _ ← (IO.setStderr oldStderr : BaseIO _) - pure result - catch e => - let _ ← (IO.setStdout oldStdout : BaseIO _) - let _ ← (IO.setStderr oldStderr : BaseIO _) - throw e - --- Helper: run a TestSeq via runIO (no printing), then assert on the bool and --- check that the output contains a given substring. -def assertRunIO (tSeq : TestSeq) (expectPass : Bool) (expectSubstr : String := "") : - IO (Bool × Nat × Nat × Option String) := do - let (pass, output) ← tSeq.runIO - let boolOk := pass == expectPass - let substrOk := expectSubstr.isEmpty || output.containsSub expectSubstr - if boolOk && substrOk then - pure (true, 0, 0, none) - else - let mut msg := "" - unless boolOk do - msg := msg ++ s!"expected pass={expectPass} but got pass={pass}" - unless substrOk do - if !msg.isEmpty then msg := msg ++ "; " - msg := msg ++ s!"expected output to contain \"{expectSubstr}\" but got:\n{output}" - pure (false, 0, 0, some msg) - -section PrimarySuites - -/-! ## TestSeq.runIO basics -/ - -def runIOBasics : TestSeq := - group "TestSeq.runIO basics" ( - .individualIO "passing test returns (true, _)" none - (assertRunIO (test "t" (1 = 1)) true) .done ++ - .individualIO "failing test returns (false, _)" none - (assertRunIO (test "t" (1 = 2)) false) .done ++ - .individualIO "multiple passing tests" none - (assertRunIO (test "a" (1 = 1) ++ test "b" (2 = 2)) true) .done ++ - .individualIO "mixed pass/fail returns false" none - (assertRunIO (test "a" (1 = 1) ++ test "b" (1 = 2)) false) .done ++ - .individualIO ".done is identity" none - (assertRunIO .done true) .done - ) - -/-! ## Grouping -/ - -def groupingTests : TestSeq := - group "Grouping" ( - .individualIO "group produces labeled output" none - (assertRunIO (group "myGroup" (test "t" true)) true "myGroup") .done ++ - .individualIO "describe produces labeled output" none - (assertRunIO (describe "myDescribe" (test "t" true)) true "myDescribe") .done ++ - .individualIO "context produces labeled output" none - (assertRunIO (context "myContext" (test "t" true)) true "myContext") .done ++ - .individualIO "nested groups work" none - (assertRunIO (group "outer" (group "inner" (test "t" true))) true "inner") .done - ) - -/-! ## IO tests -/ - -def ioTests : TestSeq := - group "IO tests" ( - .individualIO "individualIO success" none (do - let (pass, _) ← (TestSeq.individualIO "t" none (pure (true, 0, 0, none)) .done).runIO - if pass then pure (true, 0, 0, none) - else pure (false, 0, 0, some "expected pass=true") - ) .done ++ - .individualIO "individualIO failure" none (do - let (pass, _) ← (TestSeq.individualIO "t" none (pure (false, 0, 100, some "boom")) .done).runIO - if !pass then pure (true, 0, 0, none) - else pure (false, 0, 0, some "expected failure but got success") - ) .done ++ - .individualIO "individualIO error message propagates" none - (assertRunIO - (TestSeq.individualIO "t" none (pure (false, 0, 100, some "specific error msg")) .done) - false "specific error msg") .done - ) - -/-! ## Combinators -/ - -def combinatorTests : TestSeq := - group "Combinators" ( - withOptionSome "withOptionSome on some" (some 42) (fun n => - test "value is 42" (n = 42)) ++ - withOptionNone "withOptionNone on none" (none : Option Nat) - (test "reached" true) ++ - .individualIO "withOptionSome on none fails" none - (assertRunIO - (withOptionSome "got none" (none : Option Nat) (fun _ => test "unreachable" true)) - false) .done ++ - .individualIO "withOptionNone on some fails" none - (assertRunIO - (withOptionNone "got some" (some 42) (test "unreachable" true)) - false) .done ++ - withExceptOk "withExceptOk on ok" (Except.ok 10 : Except String Nat) (fun n => - test "value is 10" (n = 10)) ++ - withExceptError "withExceptError on error" (Except.error "oops" : Except String Nat) (fun e => - test "error is oops" (e = "oops")) - ) - -/-! ## Append -/ - -def appendTests : TestSeq := - group "Append" ( - .individualIO "++ chains tests" none - (assertRunIO (test "a" (1 = 1) ++ test "b" (2 = 2)) true) .done ++ - .individualIO "++ preserves order" none (do - let (_, output) ← (test "first" (1 = 1) ++ test "second" (2 = 2)).runIO - -- "first" should appear before "second" in the output - let hasBoth := output.containsSub "first" && output.containsSub "second" - -- Check ordering via splitOn: if we split on "first", "second" should be in the tail - let afterFirst := (output.splitOn "first").getD 1 "" - let ordered := afterFirst.containsSub "second" - if hasBoth && ordered then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected 'first' before 'second' in:\n{output}") - ) .done - ) - -/-! ## Property tests -/ - -def propertyTests : TestSeq := - group "Property tests" ( - .individualIO "checkIO passing property" none - (assertRunIO (checkIO "add_zero" (∀ n : Nat, n + 0 = n)) true) .done ++ - .individualIO "checkIO failing property" none - (assertRunIO (checkIO "bad" (∀ n : Nat, n = n + 1)) false) .done - ) - --- Variant of `propertyTests` above which tests the Plausible integration -def plausiblePropertyTests : TestSeq := - group "Plausible property tests" ( - .individualIO "checkPlausibleIO passing property" none - (assertRunIO (checkPlausibleIO "add_zero" (∀ n : Nat, n + 0 = n)) true) .done ++ - .individualIO "checkPlausibleIO failing property" none - (assertRunIO (checkPlausibleIO "bad" (∀ n : Nat, n = n + 1)) false) .done - ) - -/-! ## lspecIO integration -/ - -def lspecIOIntegration : TestSeq := - group "lspecIO integration" ( - .individualIO "returns 0 on all-pass" none (quietly do - let map := Std.HashMap.ofList [("s", [test "t" (1 = 1)])] - let rc ← lspecIO map [] - if rc == 0 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=0, got rc={rc}") - ) .done ++ - .individualIO "returns 1 on any failure" none (quietly do - let map := Std.HashMap.ofList [("s", [test "t" (1 = 2)])] - let rc ← lspecIO map [] - if rc == 1 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=1, got rc={rc}") - ) .done ++ - .individualIO "empty map returns 0" none (quietly do - let rc ← lspecIO (.ofList []) [] - if rc == 0 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=0, got rc={rc}") - ) .done ++ - .individualIO "suite filtering by name prefix" none (quietly do - let map := Std.HashMap.ofList [ - ("math.add", [test "t" (1 + 1 = 2)]), - ("string.concat", [test "t" ("a" ++ "b" = "ab")]) - ] - let rc ← lspecIO map ["math"] - if rc == 0 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=0 with filter, got rc={rc}") - ) .done ++ - .individualIO "non-matching filter runs nothing (returns 0)" none (quietly do - let map := Std.HashMap.ofList [("suite", [test "t" (1 = 2)])] - let rc ← lspecIO map ["nonexistent"] - if rc == 0 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=0 with no matches, got rc={rc}") - ) .done - ) - -/-! ## lspecEachIO -/ - -def lspecEachIOTests : TestSeq := - group "lspecEachIO" ( - .individualIO "returns 0 on all-pass" none (quietly do - let rc ← lspecEachIO [1, 2, 3] fun n => pure (test s!"{n}" (n > 0)) - if rc == 0 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=0, got rc={rc}") - ) .done ++ - .individualIO "returns 1 on any failure" none (quietly do - let rc ← lspecEachIO [1, 0, 3] fun n => - pure (test s!"{n}>0" (decide (n > 0))) - if rc == 1 then pure (true, 0, 0, none) - else pure (false, 0, 0, some s!"expected rc=1, got rc={rc}") - ) .done - ) - -end PrimarySuites - -/-! ## Memory stress suite (opt-in: `./tests memory`) - -Each of 50 tests allocates a 100 MB `ByteArray`. With the tail-recursive fix, -RSS should stay bounded rather than climbing to 5 GB+. -Run and watch in htop to verify. --/ - -def memoryStressTests : TestSeq := - go 50 -where - go : Nat → TestSeq - | 0 => .done - | n + 1 => - .individualIO s!"alloc 100MB #{50 - n}" none (do - -- Allocate 100 MB and touch it so it's not optimised away - let arr := ByteArray.mk (.replicate (100 * 1024 * 1024) 0xFF) - let ok := arr.size > 0 - pure (ok, 0, 0, none) - ) (go n) - -def main (args : List String) : IO UInt32 := do - let runMemory := args.contains "memory" - let primarySuites : Std.HashMap String (List TestSeq) := .ofList [ - ("TestSeq.runIO basics", [runIOBasics]), - ("Grouping", [groupingTests]), - ("IO tests", [ioTests]), - ("Combinators", [combinatorTests]), - ("Append", [appendTests]), - ("Property tests", [propertyTests]), - ("Plausible property tests", [plausiblePropertyTests]), - ("lspecIO integration", [lspecIOIntegration]), - ("lspecEachIO", [lspecEachIOTests]) - ] - let filterArgs := args.filter (· != "memory") - let rc ← lspecIO primarySuites filterArgs - if runMemory then - IO.println "\n=== Memory stress test (watch RSS in htop) ===" - let memMap : Std.HashMap String (List TestSeq) := .ofList [ - ("memory stress (50 × 100MB)", [memoryStressTests]) - ] - let rc2 ← lspecIO memMap [] - return max rc rc2 - return rc diff --git a/flake.nix b/flake.nix index 7893060..3a28bcc 100644 --- a/flake.nix +++ b/flake.nix @@ -49,22 +49,31 @@ }; # `mkPackage "LSpec"` only builds the library target, so the `tests` - # exe is built explicitly, reusing `lspec`'s build artifacts. + # exe and `LSpecProofs` library are built explicitly, reusing `lspec`'s + # build artifacts. lspecTest = lake2nix.mkPackage { name = "tests"; inherit src; lakeArtifacts = lspec; }; + + lspecProofs = lake2nix.mkPackage { + name = "LSpecProofs"; + inherit src; + lakeArtifacts = lspec; + }; in { # Build the library with `nix build` packages.default = lspec; - # Build and run the test suite as a flake check (`nix flake check`). + # Build and run the test suite and verify formal proofs (`nix flake check`). checks.tests = pkgs.runCommand "LSpec-tests" {} '' ${lspecTest}/bin/tests touch $out ''; + checks.proofs = lspecProofs; + devShells.default = pkgs.mkShell { packages = [lean]; }; diff --git a/lake-manifest.json b/lake-manifest.json index f25abb9..b958feb 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,16 +1,6 @@ {"version": "1.2.0", "packagesDir": ".lake/packages", - "packages": - [{"url": "https://github.com/leanprover-community/plausible", - "type": "git", - "subDir": null, - "scope": "", - "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", - "name": "plausible", - "manifestFile": "lake-manifest.json", - "inputRev": "v4.34.0", - "inherited": false, - "configFile": "lakefile.toml"}], + "packages": [], "name": "LSpec", "lakeDir": ".lake", "fixedToolchain": false} diff --git a/lakefile.toml b/lakefile.toml index 331fd7f..000bb31 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -1,16 +1,19 @@ name = "LSpec" -version = "2.0.0" +version = "3.0.0" defaultTargets = ["LSpec"] testDriver = "tests" -[[require]] -name = "plausible" -git = "https://github.com/leanprover-community/plausible" -rev = "v4.34.0" - [[lean_lib]] name = "LSpec" +[[lean_lib]] +name = "LSpecProofs" +moreLeanArgs = ["-DwarningAsError=true"] + +[[lean_lib]] +name = "LSpecTests" +roots = ["LSpecTests.ImportCheck", "LSpecTests.Main"] + [[lean_exe]] name = "tests" -root = "Tests.Main" +root = "LSpecTests.Main"